不平衡数据集的处理 知识点: 1.不平衡数据集的处理策略:过采样、修改权重、修改阈值 2.交叉验证代码
作业: 从示例代码可以看到 效果没有变好,所以很多步骤都是理想是好的,但是现实并不一定可以变好。这个实验仍然有改进空间,如下。
- 我还没做smote+过采样+修改权重的组合策略,有可能一起做会变好。
- 我还没有调参,有可能调参后再取上述策略可能会变好
随机过采样:随机过采样输出数据集形状,然后训练随机森林模型,输出训练起始时间,然后是随测试集进行预测。
1. 随机过采样
from imblearn.over_sampling import RandomOverSampler
ros = RandomOverSampler(random_state=42) # 创建随机过采样对象
X_train_ros, y_train_ros = ros.fit_resample(X_train, y_train) # 对训练集进行随机过采样
print("随机过采样后训练集的形状:", X_train_ros.shape, y_train_ros.shape)
# 训练随机森林模型(使用随机过采样后的训练集)
rf_model_ros = RandomForestClassifier(random_state=42)
start_time_ros = time.time()
rf_model_ros.fit(X_train_ros, y_train_ros)
end_time_ros = time.time()
print(f"随机过采样后训练与预测耗时: {end_time_ros - start_time_ros:.4f} 秒")
# 在测试集上预测
rf_pred_ros = rf_model_ros.predict(X_test)
rf_pred_ros = rf_model_ros.p
print("\n随机过采样后随机森林 在测试集上的分类报告:")
print(classification_report(y_test, rf_pred_ros))
print("随机过采样后随机森林 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, rf_pred_ros))
SMOT算法的实现过程和随机过采样的过程差不太多,但是两者却完全不同。
from imblearn.over_sampling import RandomOverSampler
smote = SMOT(random_state=42)
X_train_smote, y_train_smote = smote.fit_resample(X_train, y_train)
print("smote过采样后数据集的形状:", X_train_smote, y_train_smote)
# 训练随机森林模型(使用SMOTE过采样后的训练集)
rf_model_smote = RandomForestClassifier(random_state=42)
start_time_smote = time.time()
rf_model_smote.fit(X_train_smote, y_train_smote)
end_time_smote = time.time()
print(f"SMOTE过采样后训练与预测耗时: {end_time_smote - start_time_smote:.4f} 秒")
# 在测试集上预测
rf_pred_smote = rf_model_smote.predict(X_test)
print("\nSMOTE过采样后随机森林 在测试集上的分类报告:")
print(classification_report(y_test, rf_pred_smote))
print("SMOTE过采样后随机森林 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, rf_pred_smote))
修改类别权重和修改分类阈值本质上一个是侧重于向更好的模型进行学习,另一个则是在现有的模型下进行调整,得到更高的某一数值。
这个还没搞完,明天在交差。@浙大疏锦行
71

被折叠的 条评论
为什么被折叠?



