###前提・実現したいこと
kerasで画像を学習させたモデルを読み込み,テストデータを用いてこちらのようなROC曲線を書きたいと思っています.
しかし,下記のコードを実行すると次のエラーが出てしまいます.
roc_curveに入れるものが間違っていると思うのですが,どなたかご教授下さい.
ValueError: Data is not binary and pos_label is not specified
###該当のソースコード
Python
1from keras.models import load_model 2import keras 3import matplotlib.pyplot as plt 4from keras.preprocessing.image import array_to_img, img_to_array, list_pictures, load_img 5import numpy as np 6from sklearn.metrics import precision_recall_curve, roc_curve 7from sklearn.metrics import auc 8from collections import defaultdict 9 10def read_img(X, Y, test_dir): 11 # Loading Image 12 for picture in list_pictures(test_dir + 'A/'): 13 img = img_to_array(load_img(picture, target_size=(299, 299))) 14 X.append(img) 15 Y.append(0) 16 17 for picture in list_pictures(test_dir + 'B/'): 18 img = img_to_array(load_img(picture, target_size=(299, 299))) 19 X.append(img) 20 Y.append(1) 21 22 for picture in list_pictures(test_dir + 'C/'): 23 img = img_to_array(load_img(picture, target_size=(299, 299))) 24 X.append(img) 25 Y.append(2) 26 27 for picture in list_pictures(test_dir + 'D/'): 28 img = img_to_array(load_img(picture, target_size=(299, 299))) 29 X.append(img) 30 Y.append(3) 31 32 X = np.asarray(X) 33 Y = np.asarray(Y) 34 print(X.shape) 35 print(Y.shape) 36 return X, Y 37 38# 参照先のまま 39def save_plot_roc(y_labels, roc_scores, tprs, fprs): 40 plt.clf() 41 plt.figure(figsize=(35, 35)) 42 column = 4 43 row = int(len(y_labels) / column) + 1 44 for i, y_label in enumerate(y_labels): 45 plt.subplot(row, column, i + 1) 46 auc_score = np.mean(roc_scores[y_label]) 47 label = '%s vs rest' % y_label 48 49 plt.grid(True) 50 plt.plot([0, 1], [0, 1], 'k--') 51 for j, tpr in enumerate(tprs[y_label]): 52 plt.plot(fprs[y_label][j], tpr) 53 plt.fill_between(fprs[y_label][j], tpr, alpha=0.5) 54 plt.xlim([0.0, 1.0]) 55 plt.ylim([0.0, 1.0]) 56 plt.xlabel('False Positive Rate') 57 plt.ylabel('True Positive Rate') 58 plt.title('ROC curve (AUC = %0.2f) / %s' % 59 (auc_score, label), verticalalignment="bottom") 60 plt.legend(loc="lower right") 61 plt.show() 62 # plt.savefig(file_name, bbox_inches="tight") 63 64img_size = 299 65test_dir = 'D:/roc/' 66 67classes = ['A', 'B', 'C', 'D'] 68 69model = load_model(filepath='D:/models/model.hdf5') 70 71X = [] 72Y = [] 73 74X, Y = read_img(X, Y, test_dir) 75 76print('predict start') 77preds = model.predict(X) 78print('predict end\n') 79 80roc_scores = defaultdict(list) 81tprs = defaultdict(list) 82fprs = defaultdict(list) 83 84for i, label in enumerate(classes): 85 print('number:', i) 86 y_label_test = np.asarray(Y == label, dtype=int) 87 # y_label_test = Y 88 print('y_label', y_label_test) 89 pred_label = preds[:, i] 90 print('pred label', pred_label) 91 92 fpr, tpr, roc_thresholds = roc_curve(y_label_test, pred_label) 93 roc_scores[label].append(auc(fpr, tpr)) 94 tprs[label].append(tpr) 95 fprs[label].append(fpr) 96 97save_plot_roc(classes, roc_scores, tprs, fprs)
あなたの回答
tips
プレビュー