类别不平衡处理
Python数据分析入门Python
问题
数据集类别不平衡时如何处理?
答题要点
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix
# 不平衡数据集(流失用户<<正常用户)
df = pd.read_csv('user_data.csv')
print("类别分布:")
print(df['is_churned'].value_counts())
# 0(未流失): 9500
# 1(流失): 500
X = df.drop('is_churned', axis=1)
y = df['is_churned']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 方法1:类别权重
model = RandomForestClassifier(class_weight='balanced', random_state=42)
model.fit(X_train, y_train)
# 方法2:过采样(SMOTE)
from imblearn.over_sampling import SMOTE
smote = SMOTE(random_state=42)
X_train_balanced, y_train_balanced = smote.fit_resample(X_train, y_train)
print("\nSMOTE后类别分布:")
print(pd.Series(y_train_balanced).value_counts())
model = RandomForestClassifier(random_state=42)
model.fit(X_train_balanced, y_train_balanced)
# 方法3:欠采样
from imblearn.under_sampling import RandomUnderSampler
rus = RandomUnderSampler(random_state=42)
X_train_under, y_train_under = rus.fit_resample(X_train, y_train)
# 方法4:组合采样(SMOTEENN)
from imblearn.combine import SMOTEENN
smoteenn = SMOTEENN(random_state=42)
X_train_combined, y_train_combined = smoteenn.fit_resample(X_train, y_train)
# 方法5:调整决策阈值
from sklearn.metrics import roc_curve
y_proba = model.predict_proba(X_test)[:, 1]
# 选择最佳阈值(最大化F1)
from sklearn.metrics import f1_score
thresholds = np.arange(0.1, 0.9, 0.05)
f1_scores = []
for threshold in thresholds:
y_pred = (y_proba >= threshold).astype(int)
f1_scores.append(f1_score(y_test, y_pred))
best_threshold = thresholds[np.argmax(f1_scores)]
print(f"\n最佳阈值: {best_threshold:.2f}")
y_pred_tuned = (y_proba >= best_threshold).astype(int)
# 评估(不平衡数据不用accuracy)
print("\n分类报告:")
print(classification_report(y_test, y_pred_tuned))
# 混淆矩阵
cm = confusion_matrix(y_test, y_pred_tuned)
print("\n混淆矩阵:")
print(cm)
# 关注指标:Precision, Recall, F1(而非Accuracy)
from sklearn.metrics import precision_recall_curve
import matplotlib.pyplot as plt
precision, recall, thresholds = precision_recall_curve(y_test, y_proba)
plt.plot(recall, precision)
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('Precision-Recall曲线')
plt.show()
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题