質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

CNN (Convolutional Neural Network)

CNN (Convolutional Neural Network)は、全結合層のみではなく畳み込み層とプーリング層で構成されるニューラルネットワークです。画像認識において優れた性能を持ち、畳み込みニューラルネットワークとも呼ばれています。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

283閲覧

CNNでの画像識別における混同行列での確認方法に関して

python01

総合スコア11

Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

CNN (Convolutional Neural Network)

CNN (Convolutional Neural Network)は、全結合層のみではなく畳み込み層とプーリング層で構成されるニューラルネットワークです。画像認識において優れた性能を持ち、畳み込みニューラルネットワークとも呼ばれています。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2024/02/11 00:08

編集2024/02/11 13:34

実現したいこと

CNNで学習させたモデルに対して、
混同行列を用いて評価したいです。

下記を参考にpythonで作成しております。
https://qiita.com/tmengine/items/4eeb6770a9a69baf9439

上記のコードを順に打ち込んでおり、
一番最後の「検証-2.混同行列」でつまづいております。
(該当のソースコード欄に実際の全コードを記載しました。
現状動作しない部分は173行目の#検証(混同行列で確認)の部分になります。)

発生している問題・分からないこと

1.参考URLをそのまま打ち込むと、hdf5ファイルが見つからない。といった内容のエラーになる。
2.プログラム中で生成したmodel(model-XXX.h5)を参照させると、
引数が適切でない。といった内容のエラーになる。

エラーメッセージ

error(発生している問題1のerror)

1--------------------------------------------------------------------------- 2OSError Traceback (most recent call last) 3<ipython-input-72-b4c8e44d1521> in <module> 4 1 from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay 5----> 2 best_model = models.load_model("./cnn_casting_inspection3.hdf5") 6 3 7 4 y_pred_proba = best_model.predict(test_generator, verbose=1) 8 5 threshold = 0.5 9 ) 10 11OSError: No file or directory found at ./cnn_casting_inspection3.hdf5

error(発生している問題2のerror)

11/1 [==============================] - 0s 234ms/step 2--------------------------------------------------------------------------- 3TypeError Traceback (most recent call last) 4<ipython-input-101-e403463aafc7> in <module> 5 8 6 9 #cmd = ConfusionMatrixDisplay(confusion, [0,1]) 7---> 10 cmd = ConfusionMatrixDisplay(confusion, [0,1]) 8 11 cmd.plot(cmap=plt.cm.Blues) 9 10TypeError: __init__() takes 2 positional arguments but 3 were given

該当のソースコード

python

1import os 2import cv2 3import random 4import pandas as pd 5import numpy as np 6import matplotlib.pyplot as plt 7import tensorflow as tf 8import keras 9import keras.preprocessing.image as Image 10import sklearn.metrics 11from keras.preprocessing.image import ImageDataGenerator 12from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay 13from sklearn.metrics import classification_report 14from tensorflow.keras.layers import Dense, Dropout, Flatten, Input 15from tensorflow.keras.models import Model, Sequential 16from tensorflow.keras import preprocessing, layers, models, callbacks 17from keras.callbacks import ModelCheckpoint 18from keras.preprocessing.image import load_img, save_img, img_to_array, array_to_img 19from keras.preprocessing import image 20 21#CNN用 22from tensorflow.keras.layers import Activation, Conv2D, Dense, Flatten, MaxPooling2D 23from tensorflow.keras.models import Sequential, load_model 24from tensorflow.keras.utils import to_categorical 25import h5py 26 27#モデルの定義 28model = Sequential() 29 30#データ数のチェック//////////////////////////////////// 31#train data数 32print("OK_train :", len(os.listdir("./train/OK"))) 33print("NG_train :", len(os.listdir("./train/NG")) ) 34print("") 35#test data数 36print("OK_test :", len(os.listdir("./test/OK"))) 37print("NG_test:", len(os.listdir("./test/NG"))) 38 39#画像のチェック///////////////////////////////////////// 40img_ok = "./train/OK" 41lsdir = os.listdir(img_ok) 42 43imgs = [] 44for i in lsdir: 45 target = os.path.join(img_ok, i) 46 img = cv2.imread(target) 47 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 48 imgs.append(img) 49 50count = 8 51plt.figure(figsize=(15, 6)) 52for i, l in enumerate(random.sample(imgs, count)):#ランダムに複数の要素を選択(重複なし) 53 plt.subplot(2,5, i+1) 54 plt.axis('off') 55 plt.title("img"+str(i)) 56 plt.imshow(l) 57 58 59#正規化////////////////////////////////////////////////////////////////////////////// 60#kerasのImageDataGeneratorクラスのインスタンスを作成 61datagen = image.ImageDataGenerator( 62 rescale=1/255, 63 validation_split = 0.1 64) 65 66#flow_from_directory()でディレクトリへのパスを受け取り、そこから自動でデータを読み取って加工したデータのバッチを生成 67train_generator = datagen.flow_from_directory("./train/", 68 class_mode='binary', 69 batch_size=32, 70 target_size=(300,300), 71 color_mode='grayscale', 72 classes={'OK':0, 'NG':1}, 73 shuffle=True, 74 subset = "training"#はじめに書いたvalidationかtrainのデータかを指定する。 75) 76 77val_generator = datagen.flow_from_directory("./train", 78 class_mode='binary', 79 batch_size=32, 80 target_size=(300,300), 81 color_mode='grayscale', 82 classes={'OK':0, 'NG':1}, 83 shuffle=True, 84 subset = "validation" 85) 86 87#ImageDataGeneratorクラスのインスタンスを作成(テストデータ用) 88test_datagen = image.ImageDataGenerator( 89 rescale = 1/255 90) 91 92n_test = sum([len(files) for curDir, dirs, files in os.walk("./test")]) 93 94test_generator = test_datagen.flow_from_directory("./test", 95 class_mode='binary', 96 batch_size=n_test, 97 target_size=(300,300), 98 color_mode='grayscale', 99 classes={'OK':0, 'NG':1}, 100 shuffle = False 101) 102 103#CNN//////////////////////////////////////////////////////////// 104# 畳み込み層 105model.add(Conv2D(filters=16,kernel_size=(7,7),strides=(2,2),padding='same',activation='relu',input_shape=(300,300,1))) 106model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2))) 107 108model.add(Conv2D(filters=32,kernel_size=(3,3),activation='relu',padding='same')) 109model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2))) 110 111model.add(Conv2D(filters=64, kernel_size=(3,3), activation="relu", padding="same")) 112model.add(MaxPooling2D(pool_size = (2,2), strides =(2,2))) 113 114model.add(Conv2D(filters=128, kernel_size=(3,3), activation="relu", padding="same")) 115model.add(MaxPooling2D(pool_size = (2,2), strides =(2,2))) 116 117model.add(Conv2D(filters=256, kernel_size=(3,3), activation="relu", padding="same")) 118model.add(MaxPooling2D(pool_size = (2,2), strides =(2,2))) 119 120model.add(Flatten()) 121 122model.add(Dense(units=64,activation='relu')) 123model.add(Dropout(rate=0.2)) 124model.add(Dense(units=1,activation='sigmoid')) 125 126#コンパイル→ニューラルネットワークモデルの生成終了 127model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy']) 128 129#ニューラルネットワークの構造確認 130model.summary() 131 132#モデルの学習 133model.fit_generator(train_generator, validation_data=val_generator, epochs=10) 134 135 136#学習////////////////////////////////////////////////// 137%%time 138filepath = "./model/model-{epoch:02d}.h5" 139 140# エポックごとにモデルを保存するかチェック 141checkpoint = ModelCheckpoint ( 142 filepath=filepath, 143 monitor='val_loss', #評価をチェックする対象 144 verbose=1, 145 save_best_only=True, # 精度が向上した場合のみ保存する。 146 mode='min', 147 period=1 ) 148 149H = model.fit( 150 train_generator, 151 validation_data=val_generator, 152 epochs=20, 153 callbacks=[checkpoint], 154) 155 156#損失関数の確認 157#accuracy・・・正解率 158#loss・・・正解と予測値の差。小さいとよい。 159#val・・・validation(検証) 160 161fig = plt.figure(figsize=(8, 6)) 162 163plt.plot(H.history['accuracy'], label='acc', ls='-', marker='o') 164plt.plot(H.history['val_accuracy'], label='val_acc', ls='-', marker='x') 165plt.plot(H.history['loss'], label='loss', ls='-', marker='o') 166plt.plot(H.history['val_loss'], label='val_loss', ls='-', marker='x') 167plt.title('Model Evaluaton') 168plt.xlabel('epoch') 169plt.ylabel('') 170plt.legend(['acc', 'val_acc', 'loss', 'val_loss']) 171plt.grid(color='gray', alpha=0.2) 172 173#検証(混同行列で確認)//////////////////////////////////////////////////////////////////////// 174from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay 175#best_model = models.load_model("./cnn_casting_inspection3.hdf5")#←発生している問題1の該当部分 176best_model = models.load_model("./model/model-40.h5")#←発生している問題1はこのコードに直すと、解消される 177 178y_pred_proba = best_model.predict(test_generator, verbose=1) 179threshold = 0.5 180y_pred = y_pred_proba >= threshold 181 182confusion = confusion_matrix(y_pred, y_pred) #←追加コード:第1引数に正解のデータを入れたい 183 184cmd = ConfusionMatrixDisplay(confusion, [0,1]) #←発生している問題2の該当部分 185cmd.plot(cmap=plt.cm.Blues) 186 187

試したこと・調べたこと

  • teratailやGoogle等で検索した
  • ソースコードを自分なりに変更した
  • 知人に聞いた
  • その他
上記の詳細・結果

1.「import h5py」コードを追加しましたが、結果は変わりません。
バージョン・・・h5py:2.10.0
2.googleで「models.load_model」のワードで検索しましたが、
hdf5を読み込んでいる他の参考コードは見つかりませんでした。

3.ConfusionMatrixDisplayの引数を下記のように変更。

cmd = ConfusionMatrixDisplay(confusion, [0,1]) #←発生している問題2の該当部分
cmd = ConfusionMatrixDisplay(confusion_matrix = confusion_matrix, display_labels = [0,1])

すると、別のerrorコードが発生。

error(発生している問題2のerror)

11/1 [==============================] - 0s 230ms/step 2--------------------------------------------------------------------------- 3AttributeError Traceback (most recent call last) 4<ipython-input-100-b1f4923769f1> in <module> 5 9 #cmd = ConfusionMatrixDisplay(confusion, [0,2]) 6 10 cmd = ConfusionMatrixDisplay(confusion_matrix = confusion_matrix, display_labels = [0,1]) 7---> 11 cmd.plot(cmap=plt.cm.Blues) 8 9~\anaconda3\lib\site-packages\sklearn\utils\validation.py in inner_f(*args, **kwargs) 10 71 FutureWarning) 11 72 kwargs.update({k: arg for k, arg in zip(sig.parameters, args)}) 12---> 73 return f(**kwargs) 13 74 return inner_f 14 75 15 16~\anaconda3\lib\site-packages\sklearn\metrics\_plot\confusion_matrix.py in plot(self, include_values, cmap, xticks_rotation, values_format, ax) 17 84 18 85 cm = self.confusion_matrix 19---> 86 n_classes = cm.shape[0] 20 87 self.im_ = ax.imshow(cm, interpolation='nearest', cmap=cmap) 21 88 self.text_ = None 22 23AttributeError: 'function' object has no attribute 'shape'

↓表示される図
表示される図

4.182行目に下記コードを追加(該当のソースコードに記入済み)すると、
混同行列自体は表示されるようになりました。
しかし、confusion_matrixの第1引数に正解データを入れたいのですが、
ここがわかりません。
y_predの中身を確認すると、下記のような配列になっているので、

array([[False], [False], [ True],....)

正解データも同様の形式で配列に格納したいです。

confusion = confusion_matrix(y_pred, y_pred) #←追加コード:第1引数に正解のデータを入れたい

↓表示された混同行列
イメージ説明

補足

Python 3.8.3

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

meg_

2024/02/11 02:37

「混同行列を用いて評価したい」モデルを指定してください。
python01

2024/02/11 03:07

modelフォルダ内に生成している「model-40.h5」を用いて 試しましたが、下記エラーが返ってきました。 引数の指定が間違っているとのエラーのようなので、 下記のような書き方が必要なのでしょうか? ConfusionMatrixDisplay(引数1,引数2=XX) この辺を調べているのですが、いまいち理解できません。 --- code --------------------------------------------------------------------------- from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay #best_model = models.load_model("./cnn_casting_inspection3.hdf5") best_model = models.load_model("./model/model-40.h5") y_pred_proba = best_model.predict(test_generator, verbose=1) threshold = 0.5 y_pred = y_pred_proba >= threshold cmd = ConfusionMatrixDisplay(confusion, [0,1]) cmd.plot(cmap=plt.cm.Blues) ----------------------------------------------------------------------------------- ---- error------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-94-9e81cb7aafde> in <module> 6 threshold = 0.5 7 y_pred = y_pred_proba >= threshold ----> 8 cmd = ConfusionMatrixDisplay(confusion, [0,1]) 9 cmd.plot(cmap=plt.cm.Blues) TypeError: __init__() takes 2 positional arguments but 3 were given
meg_

2024/02/11 03:32

エラーメッセージは抜粋では内容が良く分かりません。 質問に状況を追記されてはいかがでしょうか?
python01

2024/02/11 06:29

質問に全コードを記載しました。 また本文の発生している事を2つに分け、 試した事3を追加しました。 今の状況を簡単にまとめると下記になります。 ---------------------------------------------------------------------------------------- 発生している事1:hdf5ファイルがみつからない 発生している事2:hdf5ファイルの代わりに、model-40.h5を探すようにする。          →model-40.h5は探せたようだが、           ConfusionMatrixDisplayでエラー(引数が間違っている?) 試した事3:ConfusionMatrixDisplayの引数を変更       →図が正しく描写されない ----------------------------------------------------------------------------------------
guest

回答1

0

ベストアンサー

ConfusionMatrixDisplayの第一引数には作成した混同行列を渡してください。
詳細はsklearn.metrics.ConfusionMatrixDisplayをご覧ください。

以下は上記ドキュメントからの抜粋です。

import matplotlib.pyplot as plt from sklearn.datasets import make_classification from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from sklearn.svm import SVC X, y = make_classification(random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = SVC(random_state=0) clf.fit(X_train, y_train) predictions = clf.predict(X_test) cm = confusion_matrix(y_test, predictions, labels=clf.classes_) disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=clf.classes_) disp.plot() plt.show()

投稿2024/02/11 07:18

meg_

総合スコア10582

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

python01

2024/02/11 13:39

ご教授ありがとうございます。混同行列の表示はできるようになりました。 もう一息でできそうです。 「試した事の4番目」にも追加しましたが、 正解データを配列で格納できるといいのですが、ここの操作がわかりません。 「試した事の4番目」をご確認頂けないでしょうか? 検証時の正解データはval_generatorに入ってそうなので、 この辺をいじれば、できそうな気がしますが。
meg_

2024/02/11 14:13

test_generator.classesでどうでしょうか?
python01

2024/02/12 06:25

ご教示頂いた内容で正常に動作しました! 大変ありがとうございます!! 変更前:confusion = confusion_matrix(test_generator., y_pred) 変更後:confusion = confusion_matrix(test_generator.classes, y_pred)
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問