|
import pandas as pd
|
|
from sklearn.model_selection import train_test_split
|
|
from sklearn.ensemble import RandomForestClassifier
|
|
from sklearn.metrics import classification_report, confusion_matrix
|
|
from sklearn.feature_extraction.text import TfidfVectorizer
|
|
import matplotlib.pyplot as plt
|
|
import seaborn as sns
|
|
|
|
|
|
data_url = 'https://archive.ics.uci.edu/static/public/591/data.csv'
|
|
|
|
|
|
df = pd.read_csv(data_url)
|
|
|
|
|
|
print("数据集的前几行:")
|
|
print(df.head())
|
|
|
|
|
|
|
|
df['Gender'] = df['Gender'].map({'M': 1, 'F': 0})
|
|
|
|
|
|
X = df[['Name', 'Count', 'Probability']]
|
|
y = df['Gender']
|
|
|
|
|
|
vectorizer = TfidfVectorizer()
|
|
X_name = vectorizer.fit_transform(X['Name'])
|
|
|
|
|
|
import scipy
|
|
X_combined = scipy.sparse.hstack((X_name, X[['Count', 'Probability']].values))
|
|
|
|
|
|
X_train, X_test, y_train, y_test = train_test_split(X_combined, y, test_size=0.2, random_state=42)
|
|
|
|
|
|
model = RandomForestClassifier(random_state=42)
|
|
model.fit(X_train, y_train)
|
|
|
|
|
|
y_pred = model.predict(X_test)
|
|
|
|
|
|
print("\n分类报告:")
|
|
print(classification_report(y_test, y_pred))
|
|
|
|
|
|
cm = confusion_matrix(y_test, y_pred)
|
|
plt.figure(figsize=(8, 6))
|
|
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=['Female', 'Male'], yticklabels=['Female', 'Male'])
|
|
plt.ylabel('Actual')
|
|
plt.xlabel('Predicted')
|
|
plt.title('Confusion Matrix')
|
|
plt.show()
|
|
|
|
|
|
from ucimlrepo import fetch_ucirepo
|
|
|
|
|
|
gender_by_name = fetch_ucirepo(id=591)
|
|
|
|
|
|
X = gender_by_name.data.features
|
|
y = gender_by_name.data.targets
|
|
|
|
|
|
print(gender_by_name.metadata)
|
|
|
|
|
|
print(gender_by_name.variables)
|
|
|