如何在SVM图像分类中保存混淆矩阵的假阳性与假阴性样本
保存SVM图像分类中的假阳性/假阴性样本
嘿,这事儿好办!我来帮你把那些分类错误的样本单独保存下来,方便你后续分析。先明确两个关键概念:
- 假阳性(FP):实际是
negative类别的图像,却被模型误判成了positive - 假阴性(FN):实际是
positive类别的图像,却被模型误判成了negative
接下来我们只需要在你的现有代码里加几部分逻辑:判断每个测试样本的真实标签和预测结果,把对应错误的样本复制到指定目录就行。下面是修改后的完整代码,我标注了新增的关键部分:
import sklearn from sklearn import metrics from sklearn import svm from sklearn.svm import SVC from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix import numpy as np import PIL from PIL import Image import os import shutil # 新增:用于复制文件到指定目录 # 新增:定义假阳性和假阴性的保存路径,可根据需求修改 save_false_positive = "C:/false_positive" save_false_negative = "C:/false_negative" COMMON_SIZE = (50, 50) # 新增:确保保存目录存在,不存在则自动创建 for save_dir in [save_false_positive, save_false_negative]: if not os.path.exists(save_dir): os.makedirs(save_dir) def image_to_matrix(filename): """ takes a filename and turns it into a numpy array of RGB pixels """ img = Image.open(filename) img = img.resize(COMMON_SIZE) img = np.asarray(img) return img def flatten_matrix(matrix): """ takes in an (m, n) numpy array and flattens it into an array of shape (1, m * n * 3) """ s = matrix.shape[0] * matrix.shape[1] * 3 mat = matrix.reshape(1,s) return mat[0] classes = ['positive', 'negative'] # 训练集加载逻辑(原代码不变) train_image_dirs = ["C:/potholes_50/train/positive/", "C:/potholes_50/train/negative/"] train_images = [] train_labels = [] for directory in train_image_dirs: temp_list = [directory+ f for f in os.listdir(directory)] train_labels.extend(len(temp_list)*[classes[train_image_dirs.index(directory)]]) train_images.extend(temp_list) train_data = [] for image in train_images: image = image_to_matrix(image) image = flatten_matrix(image) train_data.append(image) train_data = np.array(train_data) # 测试集加载逻辑(原代码不变) test_labels = [] test_image_dirs = ["C:/potholes_50/model_test/positive/", "C:/potholes_50/model_test/negative/"] test_images = [] for directory in test_image_dirs: temp_list = [directory+ f for f in os.listdir(directory)] test_labels.extend(len(temp_list)*[classes[test_image_dirs.index(directory)]]) test_images.extend(temp_list) test_data = [] for image in test_images: image = image_to_matrix(image) image = flatten_matrix(image) test_data.append(image) test_data = np.array(test_data) # SVM训练与预测(原代码不变) clf = svm.SVC(kernel = 'linear',gamma =5, C=1) clf.fit(train_data, train_labels) print("SVM average score: %f" % clf.score(test_data, test_labels)) predicted_label = clf.predict(test_data) # 评估指标计算(原代码不变) Accuracy_Score = accuracy_score(test_labels, predicted_label) Precision_Score = precision_score(test_labels, predicted_label, average="macro") Recall_Score = recall_score(test_labels, predicted_label, average="macro") F1_Score = f1_score(test_labels, predicted_label, average="macro") print('Average Accuracy: %0.2f +/- (%0.1f) %%' % (Accuracy_Score.mean()*100, Accuracy_Score.std()*100)) print('Average Precision: %0.2f +/- (%0.1f) %%' % (Precision_Score.mean()*100, Precision_Score.std()*100)) print('Average Recall: %0.2f +/- (%0.1f) %%' % (Recall_Score.mean()*100, Recall_Score.std()*100)) print('Average F1-Score: %0.2f +/- (%0.1f) %%' % (F1_Score.mean()*100, F1_Score.std()*100)) print("") CM = confusion_matrix(test_labels, predicted_label) print(CM) # 新增:遍历测试样本,保存假阳性和假阴性样本 for img_path, true_label, pred_label in zip(test_images, test_labels, predicted_label): # 假阳性:真实标签是negative,预测为positive if true_label == 'negative' and pred_label == 'positive': shutil.copy(img_path, save_false_positive) print(f"已保存假阳性样本: {os.path.basename(img_path)}") # 假阴性:真实标签是positive,预测为negative elif true_label == 'positive' and pred_label == 'negative': shutil.copy(img_path, save_false_negative) print(f"已保存假阴性样本: {os.path.basename(img_path)}")
关键修改说明
- 导入
shutil模块:用来实现文件复制功能,把错误分类的样本复制到指定目录 - 创建保存目录:用
os.makedirs确保保存假阳性/假阴性的目录存在,避免因目录不存在报错 - 遍历判断并保存:通过
zip同时遍历测试样本路径、真实标签和预测标签,逐一判断样本类型,复制到对应目录
运行这段代码后,你就能在C:/false_positive和C:/false_negative目录下找到所有分类错误的样本了,文件名和原测试集一致,方便你对应查看原始数据~
内容的提问来源于stack exchange,提问作者Vosco
相关产品推荐
相关产品推荐

