iT邦幫忙

0

Python_CNN_影像辨識問題與進行預測

model = tf.keras.models.Sequential()

model.add(tf.keras.layers.Conv2D(filters=16, kernel_size=(2, 2),
padding="same",
activation='relu',
input_shape=(w,h,3)))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(50, activation='relu'))
model.add(tf.keras.layers.Dense(units=category,
activation=tf.nn.softmax ))

learning_rate = 0.01
opt1 = tf.keras.optimizers.Adam(lr=learning_rate)
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])

model.summary()
with open("model_ImageDataGenerator_myImage.json", "w") as json_file:
json_file.write(model.to_json())

try:
with open('model_ImageDataGenerator_myImage.h5', 'r') as load_weights:
model.load_weights("model_ImageDataGenerator_myImage.h5")
except IOError:
print("File not exists")

checkpoint = tf.keras.callbacks.ModelCheckpoint("model_ImageDataGenerator_myImage.h5", monitor='loss', verbose=1,
save_best_only=True, mode='auto', save_freq=1)

trainData=datagen.flow(x_train,y_train2,batch_size=16)
history = model.fit_generator(trainData,
epochs=20,
callbacks=[checkpoint]
)
model.save('model_defetct_6000.h5')

#測試
score = model.evaluate(x_test, y_test2, batch_size=32)

print("score:",score)

predict = model.predict(x_test)
print("Ans:",np.argmax(predict[0]),np.argmax(predict[1]),np.argmax(predict[2]),np.argmax(predict[3]))

predict2 = model.predict_classes(x_test)
print("predict_classes:",predict2)
print("y_test",y_test[:])

for t1 in predict2:
print(dirs[t1])

#圖片顯示
img=x_test[0]
img=img.reshape(w,h,3)
img=img*255
img = img.astype('uint8')
img = cv2.resize(img, (1000, 750), interpolation=cv2.INTER_AREA)
im_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
i = np.argmax(predict[0])
str1 = dirs[i] + " " + str(predict[0][i])
print(str1);

im_bgr = cv2.putText(im_bgr, str1, (10,30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0, 0), 1, cv2.LINE_AA)
cv2.imshow('image', im_bgr)
cv2.waitKey(0)
cv2.destroyAllWindows()

因程式碼是看書編寫的
有許多不懂的地方
想詢問一下訓練完的預測
為什麼結果會顯示
predict_classes: [2 0 4 0 7 0 1 4 1 4 0 1]
y_test [2 0 4 0 6 0 1 4 1 4 0 1]
glue
bubble
measling
bubble
ruled
bubble
dent
measling
dent
measling
bubble
dent
glue 0.99999416
只有最後一個glue 有出現準確度0.99999416

而圖片顯示部分則會顯示橫條波浪紋
看似九張照片共同在一視窗內
若我只想要單一張圖像的話
該如何更改呢?

另外若我要以另外圖案讓訓練好模組進行預判
是先呼叫h.5檔案後進行預測嗎?
也是需要先將圖片前置處理後才能放入模組預測
然後再恢復原圖規格顯現出來嗎?

因為不太懂原理
問題很多再麻煩高手幫忙了
謝謝

godman08 iT邦新手 5 級 ‧ 2021-03-11 21:34:03 檢舉
有大神可以幫幫忙嗎?
godman08 iT邦新手 5 級 ‧ 2021-03-15 22:07:53 檢舉
有人可以指教一下嗎?

尚未有邦友回答

立即登入回答