import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, confusion_matrix,classification_report, roc_curve, auc import seaborn as sns import matplotlib.pyplot as plt # 读取数据 data = pd.read_excel('E:/桌面/预测脆弱性/20230523/预测样本/预测样本.xlsx') # 分割训练集和验证集 train_data = data.sample(frac=0.8, random_state=1) test_data = data.drop(train_data.index) # 定义特征变量和目标变量 features = ['高程', '起伏度', '桥梁长', '道路长', '平均坡度', '平均地温', 'T小于0', '相态'] target = '交通风险' # 训练随机森林模型 rf = RandomForestClassifier(n_estimators=100, random_state=1) rf.fit(train_data[features], train_data[target]) # 在验证集上进行预测并计算精度、召回率和F1值等指标 pred = rf.predict(test_data[features]) accuracy = accuracy_score(test_data[target], pred) confusion_mat = confusion_matrix(test_data[target], pred) classification_rep = classification_report(test_data[target], pred) print('Accuracy:', accuracy) print('Confusion matrix:') print(confusion_mat) print('Classification report:') print(classification_rep) # 输出混淆矩阵图片 sns.heatmap(confusion_mat, annot=True, cmap="Blues") plt.show() # 计算并绘制ROC曲线和AUC值 fpr, tpr, thresholds = roc_curve(test_data[target], pred) roc_auc = auc(fpr, tpr) print('AUC:', roc_auc) plt.figure() lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic') plt.legend(loc="lower right") plt.show() # 读取新数据文件并预测结果 new_data = pd.read_excel('E:/桌面/预测脆弱性/20230523/预测样本/预测结果/交通风险预测096.xlsx') new_pred = rf.predict(new_data[features]) new_data['交通风险预测结果'] = new_pred new_data.to_excel('E:/桌面/预测脆弱性/20230523/预测样本/预测结果/交通风险预测096结果.xlsx', index=False)改进代码使用多元roc曲线
时间: 2024-01-28 17:04:19 浏览: 68
好的,你可以尝试使用以下改进代码,这里使用了 One-vs-Rest 策略来处理多分类任务,并使用 multiclass_roc_auc_score() 函数来计算多类分类的 ROC AUC:
```
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report, multiclass_roc_auc_score
import seaborn as sns
import matplotlib.pyplot as plt
# 读取数据
data = pd.read_excel('E:/桌面/预测脆弱性/20230523/预测样本/预测样本.xlsx')
# 分割训练集和验证集
train_data = data.sample(frac=0.8, random_state=1)
test_data = data.drop(train_data.index)
# 定义特征变量和目标变量
features = ['高程', '起伏度', '桥梁长', '道路长', '平均坡度', '平均地温', 'T小于0', '相态']
target = '交通风险'
# 训练随机森林模型
rf = RandomForestClassifier(n_estimators=100, random_state=1)
rf.fit(train_data[features], train_data[target])
# 在验证集上进行预测并计算精度、召回率和F1值等指标
pred = rf.predict(test_data[features])
accuracy = accuracy_score(test_data[target], pred)
confusion_mat = confusion_matrix(test_data[target], pred)
classification_rep = classification_report(test_data[target], pred)
print('Accuracy:', accuracy)
print('Confusion matrix:')
print(confusion_mat)
print('Classification report:')
print(classification_rep)
# 输出混淆矩阵图片
sns.heatmap(confusion_mat, annot=True, cmap="Blues")
plt.show()
# 计算并绘制多元ROC曲线和AUC值
y_test = pd.get_dummies(test_data[target])
y_pred = rf.predict_proba(test_data[features])
fpr = {}
tpr = {}
roc_auc = {}
for i in range(len(target_names)):
fpr[i], tpr[i], _ = roc_curve(y_test.iloc[:, i], y_pred[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
# 计算微平均AUC值
fpr["micro"], tpr["micro"], _ = roc_curve(y_test.values.ravel(), y_pred.ravel())
roc_auc["micro"] = multiclass_roc_auc_score(y_test, y_pred, average="micro")
# 计算宏平均AUC值
all_fpr = np.unique(np.concatenate([fpr[i] for i in range(len(target_names))]))
mean_tpr = np.zeros_like(all_fpr)
for i in range(len(target_names)):
mean_tpr += interp(all_fpr, fpr[i], tpr[i])
mean_tpr /= len(target_names)
fpr["macro"] = all_fpr
tpr["macro"] = mean_tpr
roc_auc["macro"] = multiclass_roc_auc_score(y_test, y_pred, average="macro")
# 绘制ROC曲线
plt.figure()
plt.plot(fpr["micro"], tpr["micro"], label='micro-average ROC curve (area = {0:0.2f})'.format(roc_auc["micro"]), color='deeppink', linestyle=':')
plt.plot(fpr["macro"], tpr["macro"], label='macro-average ROC curve (area = {0:0.2f})'.format(roc_auc["macro"]), color='navy', linestyle=':')
for i in range(len(target_names)):
plt.plot(fpr[i], tpr[i], label='ROC curve of class {0} (area = {1:0.2f})'.format(target_names[i], roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Multi-Class Receiver Operating Characteristic')
plt.legend(loc="lower right")
plt.show()
# 读取新数据文件并预测结果
new_data = pd.read_excel('E:/桌面/预测脆弱性/20230523/预测样本/预测结果/交通风险预测096.xlsx')
new_pred = rf.predict(new_data[features])
new_data['交通风险预测结果'] = new_pred
new_data.to_excel('E:/桌面/预测脆弱性/20230523/预测样本/预测结果/交通风险预测096结果.xlsx', index=False)
```
注意:在这里,我们需要将目标变量进行 One-hot 编码,以便使用 multiclass_roc_auc_score() 函数计算多类分类的 ROC AUC。另外,你需要将 `target_names` 定义为目标变量的所有类别名称,以便在绘制 ROC 曲线时使用。
阅读全文