# 拆分数据集 X_train, X_test, y_train, y_test = train_test_split(heartbeats_image, labels, test_size=0.2, random_state=42) X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42) # 保存数据集 np.save('X_train.npy', X_train) np.save('X_val.npy', X_val) np.save('X_test.npy', X_test) np.save('y_train.npy', y_train) np.save('y_val.npy', y_val) np.save('y_test.npy', y_test) from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout # 定义卷积神经网络 model = Sequential([ Conv2D(filters=32, kernel_size=(3,3), activation='relu', input_shape=(255,255,1)), MaxPooling2D(pool_size=(2,2)), Conv2D(filters=64, kernel_size=(3,3), activation='relu'), MaxPooling2D(pool_size=(2,2)), Conv2D(filters=128, kernel_size=(3,3), activation='relu'), MaxPooling2D(pool_size=(2,2)), Flatten(), Dense(units=128, activation='relu'), Dropout(0.5), Dense(units=1, activation='sigmoid') ]) model.add(Dense(20, activation='softmax')) # 编译模型 model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # 训练模型 history = model.fit(X_train, y_train, epochs=10, validation_data=(X_val, y_val)) # 保存模型 model.save('my_model.h5') from sklearn.metrics import confusion_matrix, roc_curve, auc import matplotlib.pyplot as plt # 对测试集进行预测 y_pred = model.predict(X_test) # 将预测结果转换为标签 y_pred_labels = (y_pred > 0.5).astype(int) from sklearn.metrics import confusion_matrix from sklearn.utils.multiclass import unique_labels # 将多标签指示器转换成标签数组 y_test = unique_labels(y_test) y_pred_labels = unique_labels(y_pred_labels) # 计算混淆矩阵 cm = confusion_matrix(y_test, y_pred_labels) # 绘制混淆矩阵 plt.imshow(cm, cmap=plt.cm.Blues) plt.xlabel("Predicted labels") plt.ylabel("True labels") plt.xticks([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19], ['N','L','R','A','a','J','S','V','F','[','!',']','e','j','E','/','f','x','Q','|']) plt.yticks([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19], ['N','L','R','A','a','J','S','V','F','[','!',']','e','j','E','/','f','x','Q','|']) plt.title('Confusion matrix') plt.colorbar() plt.show()之后怎么绘制ROC曲线
时间: 2023-06-14 18:05:57 浏览: 314
要绘制ROC曲线,需要计算模型的真正率(True Positive Rate,TPR)和假正率(False Positive Rate,FPR),可以使用sklearn.metrics库中的roc_curve函数来计算TPR和FPR,然后使用matplotlib库中的plot函数来绘制ROC曲线。
以下是绘制ROC曲线的代码示例:
```python
from sklearn.metrics import roc_curve, auc
# 计算TPR和FPR
fpr, tpr, thresholds = roc_curve(y_test, y_pred)
# 计算AUC值
roc_auc = auc(fpr, tpr)
# 绘制ROC曲线
plt.figure()
plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (AUC = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], color='navy', lw=2, 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()
```
其中,y_test是测试集的真实标签,y_pred是模型对测试集的预测结果。计算TPR和FPR时,可以使用roc_curve函数来计算,返回的fpr和tpr即为FPR和TPR,thresholds是阈值,这里用不到。计算AUC值时,可以使用auc函数来计算。绘制ROC曲线时,使用plot函数来绘制,其中color为曲线颜色,lw为线宽,label为图例标签,xlim和ylim为坐标轴范围,xlabel和ylabel为坐标轴标签,title为图表标题,legend为图例。
阅读全文