sklearn.metrics.roc_curve使用简要说明

一、背景说明

小哥我是一名机器学习小白,刚开始学习sklearn。像部分刚入门的小白一样被混淆矩阵搞得头昏脑胀,最近碰到朋友咨询我roc_curve返回的结果是如何生成的时候,我一脸懵逼。shift+Tab查看系统说明没有看明白(本人英语水平很弱,亲一定要学好英语);然后,上网求助,也没有得到想要的答案。最后受这篇文章http://www.bubuko.com/infodetail-2718749.html的启发,自己重新摸索出规律,把自己一点小想法分享给大家,希望能帮助大家

二、TP、TN、FP、FN概念

在这里插入图片描述## 三、TPR、TNR、FPR、FNR概念
1、TPR=tp/(tp+fn)
TPR:即真正率或灵敏度或召回率或查全率或真正率或功效,本来为正样本的样本被预测为正样本的总样本数量÷真实结果为正样本的总样本数
另:精确度或查准率公式等于tp/(tp+fp)
准确得分计算:(tp+tn)/(tp+fp+fn+tn)
2、FNR=fn/(tp+fn) =1-TPR
FNR:即假负率,本来为正样本的样本被预测为负样本的总样本数量÷真实结果为正样本的总样本数。
相当于假设检验中,犯第二类错误概率(β)
3、FPR=fp/(fp+tn)
FPR:即假正率,本来为负样本的样本被预测为正样本的总样本数量÷真实结果为负样本的总样本数。
相当于假设检验中,犯第一类错误概率(α)
4、TNR=tn/(fp+tn)=1-FPR
TNR:即真负率或特异度,本来为负样本的样本被预测为负样本的总样本数量÷真实结果为负样本的总样本数。

四、roc_curve运行机制简单剖析

4.1、roc_curve简单介绍

4.1.1 重要参数

y_true:真实结果数据,数据类型是数组
y_score:预测结果数据,可以是标签数据也可以是概率值,数据类型是形状 与y_true一致的数组
pos_label:默认为None,只有当标签数据如{0,1}、{-1,1}二分类数据才能默认;否则需要设置正样本值

4.1.2 返回的结果

返回三个数组结果分别是fpr(假正率),tpr(召回率),threshold(阈值)

4.2、第一种情形:y_score是标签数据

4.2.1、例子

代码.

//python 代码
y_true=np.array([0, 0, 0, 1, 1, 0, 0
from sklearn.metrics import confusion_matrix import seaborn as sns import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout from tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array from tensorflow.keras.callbacks import EarlyStopping import tensorflow as tf from glob import glob # 设置数据集路径 base_dir = "D:/dataset" # 创建数据集DataFrame - 从文件名自动推断标签 def create_dataframe(dataset_path): data = [] for img_file in glob(dataset_path + r'/*/0/*.png'): if img_file.endswith('.png'): # img_path = os.path.join(dataset_path, img_file) img_path = img_file # 从文件名推断标签: 文件名中包含"class1"为阳性(1), 其他为阴性(0) # label = 1 if "class1" in img_file.lower() else 0 data.append([img_path, 0]) for img_file in glob(dataset_path + r'/*/1/*.png'): if img_file.endswith('.png'): # img_path = os.path.join(dataset_path, img_file) img_path = img_file # 从文件名推断标签: 文件名中包含"class1"为阳性(1), 其他为阴性(0) # label = 1 if "class1" in img_file.lower() else 0 data.append([img_path, 1]) # for img_file in glob(dataset_path): # if img_file.endswith('.png'): # # img_path = os.path.join(dataset_path, img_file) # img_path = img_file # # 从文件名推断标签: 文件名中包含"class1"为阳性(1), 其他为阴性(0) # label = 1 if "class1" in img_file.lower() else 0 # data.append([img_path, label]) return pd.DataFrame(data, columns=['path', 'label']) # 创建数据集DataFrame df = create_dataframe(base_dir) df = create_dataframe("D:/dataset") print("总样本数:", len(df)) print(df['label'].value_counts()) print(df.head()) # 检查数据集分布 print(f"阴性样本数(0): {len(df[df['label'] == 0])}") print(f"阳性样本数(1): {len(df[df['label'] == 1])}") # 划分训练集和测试集 (80%训练, 20%测试) train_df, test_df = train_test_split(df, test_size=0.2, random_state=42, stratify=df['label']) # 自定义数据生成器 - 直接从文件路径加载图像 class CustomDataGenerator(tf.keras.utils.Sequence): def __init__(self, df, batch_size=32, img_size=(50, 50), shuffle=True, augment=False): self.df = df self.batch_size = batch_size self.img_size = img_size self.shuffle = shuffle self.augment = augment self.on_epoch_end() # 创建数据增强生成器 self.augmenter = ImageDataGenerator( rotation_range=20, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest' ) if augment else None def __len__(self): return int(np.ceil(len(self.df) / self.batch_size)) def __getitem__(self, index): batch_paths = self.paths[index * self.batch_size:(index + 1) * self.batch_size] batch_labels = self.labels[index * self.batch_size:(index + 1) * self.batch_size] batch_images = [] for path in batch_paths: img = load_img(path, target_size=self.img_size) img_array = img_to_array(img) / 255.0 # 归一化 if self.augment and self.augmenter: # 应用数据增强 img_array = self.augmenter.random_transform(img_array) batch_images.append(img_array) return np.array(batch_images), np.array(batch_labels) def on_epoch_end(self): self.paths = self.df['path'].values self.labels = self.df['label'].values if self.shuffle: indices = np.arange(len(self.paths)) np.random.shuffle(indices) self.paths = self.paths[indices] self.labels = self.labels[indices] # 图像尺寸 (参考Kaggle数据集) img_width, img_height = 50, 50 batch_size = 32 # 创建数据生成器 train_generator = CustomDataGenerator( train_df, batch_size=batch_size, img_size=(img_width, img_height), augment=True # 训练集使用数据增强 ) test_generator = CustomDataGenerator( test_df, batch_size=batch_size, img_size=(img_width, img_height), shuffle=False # 测试集不需要打乱 ) # 构建CNN模型 model = Sequential([ Conv2D(32, (3, 3), activation='relu', input_shape=(img_width, img_height, 3)), MaxPooling2D((2, 2)), Conv2D(64, (3, 3), activation='relu'), MaxPooling2D((2, 2)), Conv2D(128, (3, 3), activation='relu'), MaxPooling2D((2, 2)), Flatten(), Dense(256, activation='relu'), Dropout(0.5), Dense(1, activation='sigmoid') ]) # 编译模型 model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy', tf.keras.metrics.Precision(name='precision'), tf.keras.metrics.Recall(name='recall'), tf.keras.metrics.AUC(name='auc')]) # 提前停止回调 early_stop = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True) # 训练模型 history = model.fit( train_generator, epochs=30, validation_data=test_generator, callbacks=[early_stop] ) # 评估测试集 test_results = model.evaluate(test_generator) print( f"测试集准确率: {test_results[1]:.4f}, 精确率: {test_results[2]:.4f}, 召回率: {test_results[3]:.4f}, AUC: {test_results[4]:.4f}") # 保存模型 model.save('breast_cancer_cnn.h5') # 绘制训练历史 plt.figure(figsize=(12, 4)) plt.subplot(1, 2, 1) plt.plot(history.history['accuracy'], label='训练准确率') plt.plot(history.history['val_accuracy'], label='验证准确率') plt.title('模型准确率') plt.ylabel('准确率') plt.xlabel('轮次') plt.legend() plt.subplot(1, 2, 2) plt.plot(history.history['loss'], label='训练损失') plt.plot(history.history['val_loss'], label='验证损失') plt.title('模型损失') plt.ylabel('损失') plt.xlabel('轮次') plt.legend() plt.savefig('training_history.png') plt.show() # 获取测试集真实标签和预测标签 test_labels = [] for i in range(len(test_generator)): _, labels = test_generator[i] test_labels.extend(labels) test_labels = np.array(test_labels) # 模型预测(输出概率) pred_probs = model.predict(test_generator) # 转换为二分类标签(阈值0.5) pred_labels = (pred_probs > 0.5).astype(int).flatten() # 计算混淆矩阵 cm = confusion_matrix(test_labels, pred_labels) # 绘制并保存混淆矩阵图 plt.figure(figsize=(8, 6)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=['IDC(-)', 'IDC(+)'], yticklabels=['IDC(-)', 'IDC(+)']) plt.title('Confusion Matrix') plt.xlabel('Predicted Label') plt.ylabel('True Label') plt.savefig('confusion_matrix.png') plt.show() # === 新增的ROC曲线绘制代码 === from sklearn.metrics import roc_curve, auc # 计算ROC曲线参数 fpr, tpr, thresholds = roc_curve(test_labels, pred_probs) roc_auc = auc(fpr, tpr) # 绘制ROC曲线 plt.figure(figsize=(8, 6)) plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (AUC = {roc_auc:.4f})') 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 (ROC) Curve') plt.legend(loc="lower right") plt.grid(True, alpha=0.3) # 保存ROC曲线图 plt.savefig('roc_curve.png') plt.show() # === 新增模型评估指标代码 === from sklearn.metrics import classification_report # 生成分类报告 report = classification_report(test_labels, pred_labels, target_names=['IDC(-)', 'IDC(+)']) print("分类报告:\n", report) Testing dataset accuracy: 87.11% Precision: 78.79% Recall: 74.70% AUC: 92.24%总结英文分析报告
最新发布
09-24
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值