質問編集履歴

2

試した事の4番目を追加。

2024/02/11 13:34

投稿

python01
python01

スコア11

test CHANGED
File without changes
test CHANGED
@@ -229,14 +229,12 @@
229
229
  threshold = 0.5
230
230
  y_pred = y_pred_proba >= threshold
231
231
 
232
+ confusion = confusion_matrix(y_pred, y_pred) #←追加コード:第1引数に正解のデータを入れたい
233
+
232
234
  cmd = ConfusionMatrixDisplay(confusion, [0,1]) #←発生している問題2の該当部分
233
235
  cmd.plot(cmap=plt.cm.Blues)
234
236
 
235
237
 
236
- ```
237
-
238
- ```
239
- 特になし
240
238
  ```
241
239
 
242
240
  ### 試したこと・調べたこと
@@ -290,5 +288,21 @@
290
288
  ↓表示される図
291
289
  ![表示される図](https://ddjkaamml8q8x.cloudfront.net/questions/2024-02-11/22cf3d30-147f-4d9c-bc85-6b6dd5c3f46e.png)
292
290
 
291
+ 4.182行目に下記コードを追加(該当のソースコードに記入済み)すると、
292
+ 混同行列自体は表示されるようになりました。
293
+ しかし、confusion_matrixの第1引数に正解データを入れたいのですが、
294
+ ここがわかりません。
295
+ y_predの中身を確認すると、下記のような配列になっているので、
296
+
297
+ array([[False], [False], [ True],....)
298
+
299
+ 正解データも同様の形式で配列に格納したいです。
300
+
301
+ ```
302
+ confusion = confusion_matrix(y_pred, y_pred) #←追加コード:第1引数に正解のデータを入れたい
303
+ ```
304
+ ↓表示された混同行列
305
+ ![イメージ説明](https://ddjkaamml8q8x.cloudfront.net/questions/2024-02-11/2c62c720-e4e4-4c26-a15a-d068ca10dd09.png)
306
+
293
307
  ### 補足
294
308
  Python 3.8.3

1

全コードを記載しました。また、エラー名と図も記載しております。

2024/02/11 06:22

投稿

python01
python01

スコア11

test CHANGED
File without changes
test CHANGED
@@ -7,12 +7,18 @@
7
7
 
8
8
  上記のコードを順に打ち込んでおり、
9
9
  一番最後の「検証-2.混同行列」でつまづいております。
10
+ (該当のソースコード欄に実際の全コードを記載しました。
11
+  現状動作しない部分は173行目の#検証(混同行列で確認)の部分になります。)
12
+
10
13
 
11
14
  ### 発生している問題・分からないこと
12
- hdf5ファイルが見つからない。
15
+ 1.参考URLをそのまま打ち込むと、hdf5ファイルが見つからない。といった内容のエラーになる。
16
+ 2.プログラム中で生成したmodel(model-XXX.h5)を参照させると、
17
+  引数が適切でない。といった内容のエラーになる。
18
+
13
19
 
14
20
  ### エラーメッセージ
15
- ```error
21
+ ```error(発生している問題1のerror)
16
22
  ---------------------------------------------------------------------------
17
23
  OSError Traceback (most recent call last)
18
24
  <ipython-input-72-b4c8e44d1521> in <module>
@@ -21,42 +27,212 @@
21
27
  3
22
28
  4 y_pred_proba = best_model.predict(test_generator, verbose=1)
23
29
  5 threshold = 0.5
24
-
25
- ~\anaconda3\lib\site-packages\keras\src\saving\saving_api.py in load_model(filepath, custom_objects, compile, safe_mode, **kwargs)
26
- 236
30
+ )
27
- 237 # Legacy case.
28
- --> 238 return legacy_sm_saving_lib.load_model(
29
- 239 filepath, custom_objects=custom_objects, compile=compile, **kwargs
30
- 240 )
31
-
32
- ~\anaconda3\lib\site-packages\keras\src\utils\traceback_utils.py in error_handler(*args, **kwargs)
33
- 68 # To get the full stack trace, call:
34
- 69 # `tf.debugging.disable_traceback_filtering()`
35
- ---> 70 raise e.with_traceback(filtered_tb) from None
36
- 71 finally:
37
- 72 del filtered_tb
38
-
39
- ~\anaconda3\lib\site-packages\keras\src\saving\legacy\save.py in load_model(filepath, custom_objects, compile, options)
40
- 232 if isinstance(filepath_str, str):
41
- 233 if not tf.io.gfile.exists(filepath_str):
42
- --> 234 raise IOError(
43
- 235 f"No file or directory found at {filepath_str}"
44
- 236 )
45
31
 
46
32
  OSError: No file or directory found at ./cnn_casting_inspection3.hdf5
47
33
  ```
48
34
 
35
+ ```error(発生している問題2のerror)
36
+ 1/1 [==============================] - 0s 234ms/step
37
+ ---------------------------------------------------------------------------
38
+ TypeError Traceback (most recent call last)
39
+ <ipython-input-101-e403463aafc7> in <module>
40
+ 8
41
+ 9 #cmd = ConfusionMatrixDisplay(confusion, [0,1])
42
+ ---> 10 cmd = ConfusionMatrixDisplay(confusion, [0,1])
43
+ 11 cmd.plot(cmap=plt.cm.Blues)
44
+
45
+ TypeError: __init__() takes 2 positional arguments but 3 were given
46
+ ```
47
+
49
48
  ### 該当のソースコード
50
49
 
51
50
  ```python
51
+ import os
52
+ import cv2
53
+ import random
54
+ import pandas as pd
55
+ import numpy as np
56
+ import matplotlib.pyplot as plt
57
+ import tensorflow as tf
58
+ import keras
59
+ import keras.preprocessing.image as Image
60
+ import sklearn.metrics
61
+ from keras.preprocessing.image import ImageDataGenerator
52
62
  from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
63
+ from sklearn.metrics import classification_report
64
+ from tensorflow.keras.layers import Dense, Dropout, Flatten, Input
65
+ from tensorflow.keras.models import Model, Sequential
66
+ from tensorflow.keras import preprocessing, layers, models, callbacks
67
+ from keras.callbacks import ModelCheckpoint
68
+ from keras.preprocessing.image import load_img, save_img, img_to_array, array_to_img
69
+ from keras.preprocessing import image
70
+
71
+ #CNN用
72
+ from tensorflow.keras.layers import Activation, Conv2D, Dense, Flatten, MaxPooling2D
73
+ from tensorflow.keras.models import Sequential, load_model
74
+ from tensorflow.keras.utils import to_categorical
75
+ import h5py
76
+
77
+ #モデルの定義
78
+ model = Sequential()
79
+
80
+ #データ数のチェック////////////////////////////////////
81
+ #train data数
82
+ print("OK_train :", len(os.listdir("./train/OK")))
83
+ print("NG_train :", len(os.listdir("./train/NG")) )
84
+ print("")
85
+ #test data数
86
+ print("OK_test :", len(os.listdir("./test/OK")))
87
+ print("NG_test:", len(os.listdir("./test/NG")))
88
+
89
+ #画像のチェック/////////////////////////////////////////
90
+ img_ok = "./train/OK"
91
+ lsdir = os.listdir(img_ok)
92
+
93
+ imgs = []
94
+ for i in lsdir:
95
+ target = os.path.join(img_ok, i)
96
+ img = cv2.imread(target)
97
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
98
+ imgs.append(img)
99
+
100
+ count = 8
101
+ plt.figure(figsize=(15, 6))
102
+ for i, l in enumerate(random.sample(imgs, count)):#ランダムに複数の要素を選択(重複なし)
103
+ plt.subplot(2,5, i+1)
104
+ plt.axis('off')
105
+ plt.title("img"+str(i))
106
+ plt.imshow(l)
107
+
108
+
109
+ #正規化//////////////////////////////////////////////////////////////////////////////
110
+ #kerasのImageDataGeneratorクラスのインスタンスを作成
111
+ datagen = image.ImageDataGenerator(
112
+ rescale=1/255,
113
+ validation_split = 0.1
114
+ )
115
+
116
+ #flow_from_directory()でディレクトリへのパスを受け取り、そこから自動でデータを読み取って加工したデータのバッチを生成
117
+ train_generator = datagen.flow_from_directory("./train/",
118
+ class_mode='binary',
119
+ batch_size=32,
120
+ target_size=(300,300),
121
+ color_mode='grayscale',
122
+ classes={'OK':0, 'NG':1},
123
+ shuffle=True,
124
+ subset = "training"#はじめに書いたvalidationかtrainのデータかを指定する。
125
+ )
126
+
127
+ val_generator = datagen.flow_from_directory("./train",
128
+ class_mode='binary',
129
+ batch_size=32,
130
+ target_size=(300,300),
131
+ color_mode='grayscale',
132
+ classes={'OK':0, 'NG':1},
133
+ shuffle=True,
134
+ subset = "validation"
135
+ )
136
+
137
+ #ImageDataGeneratorクラスのインスタンスを作成(テストデータ用)
138
+ test_datagen = image.ImageDataGenerator(
139
+ rescale = 1/255
140
+ )
141
+
142
+ n_test = sum([len(files) for curDir, dirs, files in os.walk("./test")])
143
+
144
+ test_generator = test_datagen.flow_from_directory("./test",
145
+ class_mode='binary',
146
+ batch_size=n_test,
147
+ target_size=(300,300),
148
+ color_mode='grayscale',
149
+ classes={'OK':0, 'NG':1},
150
+ shuffle = False
151
+ )
152
+
153
+ #CNN////////////////////////////////////////////////////////////
154
+ # 畳み込み層
155
+ model.add(Conv2D(filters=16,kernel_size=(7,7),strides=(2,2),padding='same',activation='relu',input_shape=(300,300,1)))
156
+ model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2)))
157
+
158
+ model.add(Conv2D(filters=32,kernel_size=(3,3),activation='relu',padding='same'))
159
+ model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2)))
160
+
161
+ model.add(Conv2D(filters=64, kernel_size=(3,3), activation="relu", padding="same"))
162
+ model.add(MaxPooling2D(pool_size = (2,2), strides =(2,2)))
163
+
164
+ model.add(Conv2D(filters=128, kernel_size=(3,3), activation="relu", padding="same"))
165
+ model.add(MaxPooling2D(pool_size = (2,2), strides =(2,2)))
166
+
167
+ model.add(Conv2D(filters=256, kernel_size=(3,3), activation="relu", padding="same"))
168
+ model.add(MaxPooling2D(pool_size = (2,2), strides =(2,2)))
169
+
170
+ model.add(Flatten())
171
+
172
+ model.add(Dense(units=64,activation='relu'))
173
+ model.add(Dropout(rate=0.2))
174
+ model.add(Dense(units=1,activation='sigmoid'))
175
+
176
+ #コンパイル→ニューラルネットワークモデルの生成終了
177
+ model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
178
+
179
+ #ニューラルネットワークの構造確認
180
+ model.summary()
181
+
182
+ #モデルの学習
183
+ model.fit_generator(train_generator, validation_data=val_generator, epochs=10)
184
+
185
+
186
+ #学習//////////////////////////////////////////////////
187
+ %%time
188
+ filepath = "./model/model-{epoch:02d}.h5"
189
+
190
+ # エポックごとにモデルを保存するかチェック
191
+ checkpoint = ModelCheckpoint (
192
+ filepath=filepath,
193
+ monitor='val_loss', #評価をチェックする対象
194
+ verbose=1,
195
+ save_best_only=True, # 精度が向上した場合のみ保存する。
196
+ mode='min',
197
+ period=1 )
198
+
199
+ H = model.fit(
200
+ train_generator,
201
+ validation_data=val_generator,
202
+ epochs=20,
203
+ callbacks=[checkpoint],
204
+ )
205
+
206
+ #損失関数の確認
207
+ #accuracy・・・正解率
208
+ #loss・・・正解と予測値の差。小さいとよい。
209
+ #val・・・validation(検証)
210
+
211
+ fig = plt.figure(figsize=(8, 6))
212
+
213
+ plt.plot(H.history['accuracy'], label='acc', ls='-', marker='o')
214
+ plt.plot(H.history['val_accuracy'], label='val_acc', ls='-', marker='x')
215
+ plt.plot(H.history['loss'], label='loss', ls='-', marker='o')
216
+ plt.plot(H.history['val_loss'], label='val_loss', ls='-', marker='x')
217
+ plt.title('Model Evaluaton')
218
+ plt.xlabel('epoch')
219
+ plt.ylabel('')
220
+ plt.legend(['acc', 'val_acc', 'loss', 'val_loss'])
221
+ plt.grid(color='gray', alpha=0.2)
222
+
223
+ #検証(混同行列で確認)////////////////////////////////////////////////////////////////////////
224
+ from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
53
- best_model = models.load_model("./cnn_casting_inspection3.hdf5")
225
+ #best_model = models.load_model("./cnn_casting_inspection3.hdf5")#←発生している問題1の該当部分
226
+ best_model = models.load_model("./model/model-40.h5")#←発生している問題1はこのコードに直すと、解消される
54
227
 
55
228
  y_pred_proba = best_model.predict(test_generator, verbose=1)
56
229
  threshold = 0.5
57
230
  y_pred = y_pred_proba >= threshold
231
+
58
- cmd = ConfusionMatrixDisplay(confusion, [0,1])
232
+ cmd = ConfusionMatrixDisplay(confusion, [0,1]) #←発生している問題2の該当部分
59
233
  cmd.plot(cmap=plt.cm.Blues)
234
+
235
+
60
236
  ```
61
237
 
62
238
  ```
@@ -72,11 +248,47 @@
72
248
  ##### 上記の詳細・結果
73
249
  1.「import h5py」コードを追加しましたが、結果は変わりません。
74
250
   バージョン・・・h5py:2.10.0
75
-
76
251
  2.googleで「models.load_model」のワードで検索しましたが、
77
252
  hdf5を読み込んでいる他の参考コードは見つかりませんでした。
78
253
 
79
- 3.フォルダ内にh5pyファイルが生成されているか確認しましたが、ありませんでした
254
+ 3.ConfusionMatrixDisplayの引数を下記のように変更
255
+
256
+ ```全コードの182行目(変更前)
257
+ cmd = ConfusionMatrixDisplay(confusion, [0,1]) #←発生している問題2の該当部分
258
+ ```
259
+ ```全コードの182行目(変更後)
260
+ cmd = ConfusionMatrixDisplay(confusion_matrix = confusion_matrix, display_labels = [0,1])
261
+ ```
262
+
263
+ すると、別のerrorコードが発生。
264
+
265
+ ```error(発生している問題2のerror)
266
+ 1/1 [==============================] - 0s 230ms/step
267
+ ---------------------------------------------------------------------------
268
+ AttributeError Traceback (most recent call last)
269
+ <ipython-input-100-b1f4923769f1> in <module>
270
+ 9 #cmd = ConfusionMatrixDisplay(confusion, [0,2])
271
+ 10 cmd = ConfusionMatrixDisplay(confusion_matrix = confusion_matrix, display_labels = [0,1])
272
+ ---> 11 cmd.plot(cmap=plt.cm.Blues)
273
+
274
+ ~\anaconda3\lib\site-packages\sklearn\utils\validation.py in inner_f(*args, **kwargs)
275
+ 71 FutureWarning)
276
+ 72 kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
277
+ ---> 73 return f(**kwargs)
278
+ 74 return inner_f
279
+ 75
280
+
281
+ ~\anaconda3\lib\site-packages\sklearn\metrics\_plot\confusion_matrix.py in plot(self, include_values, cmap, xticks_rotation, values_format, ax)
282
+ 84
283
+ 85 cm = self.confusion_matrix
284
+ ---> 86 n_classes = cm.shape[0]
285
+ 87 self.im_ = ax.imshow(cm, interpolation='nearest', cmap=cmap)
286
+ 88 self.text_ = None
287
+
288
+ AttributeError: 'function' object has no attribute 'shape'
289
+ ```
290
+ ↓表示される図
291
+ ![表示される図](https://ddjkaamml8q8x.cloudfront.net/questions/2024-02-11/22cf3d30-147f-4d9c-bc85-6b6dd5c3f46e.png)
80
292
 
81
293
  ### 補足
82
294
  Python 3.8.3