[英]Get predicted values with model.predict using ImageDataGenerator - keras 2.1.0 (deep learning)
我正在嘗試獲取所有正確和不正確的預測值(我想預測圖像的 class)
所以,我的代碼是:
#Load the trained model
loaded_model= tf.keras.models.load_model('C:/Desktop/data/model.h5')
#ImageDataGenerator for reading data from directory
test_generator = ImageDataGenerator().flow_from_directory(
'C:/Desktop/data/test',
target_size=(img_width, img_height),
batch_size=batch,
class_mode='categorical')
#Predicting the classes of images
predictions = loaded_model.predict(test_generator)
print('predictions shape:', predictions.shape)
print('predictions:', predictions)
Output 用於predictions.shape
。形狀為(568, 2)
和predictions
:
[[4.5327284e-11 1.0000000e+00]
[1.0000000e+00 3.6808674e-11]
[1.3124708e-03 9.9868757e-01]
...
[1.0000000e+00 2.0863072e-11]
[9.3747419e-01 6.2525854e-02]
[1.0000000e+00 4.2702163e-14]]
但我需要得到預測,比如可用於混淆矩陣的數據
所以我需要有這樣的價值觀:
24 predictions for class 1 was correct
5 predictions for class 1 was incorrect
1 prediction for class 0 was correct
7 predictions for class 0 was incorrect
我正在嘗試使用教程中的代碼,但出現錯誤:
AttributeError: 'DirectoryIterator' object has no attribute 'class_indicies'
我現在的代碼:
test_generator = ImageDataGenerator().flow_from_directory(
'C:/Desktop/data/test',
target_size=(img_width, img_height),
batch_size=batch,
class_mode='categorical',
shuffle=False)
predictions = loaded_model.predict(test_generator, steps=test_generator.batch_size, verbose=1)
predicted_class_indices = np.argmax(predictions, axis=1)
print('predictions: ', predicted_class_indices)
labels = test_generator.class_indicies #here I am getting an error
labels = dict((v,k) for k,v in labels.items())
predictionss = [labels[k] for k in predicted_class_indices]
print(predictionss)
根據您的形狀,我假設您有 2 個班級。
#Load the trained model
loaded_model= tf.keras.models.load_model('C:/Desktop/data/model.h5')
#ImageDataGenerator for reading data from directory
test_generator = ImageDataGenerator().flow_from_directory(
'C:/Desktop/data/test',
target_size=(img_width, img_height),
batch_size=batch,
class_mode='categorical')
#Predicting the classes of images
predictions = loaded_model.predict_generator(test_generator)
print('predictions shape:', predictions.shape)
print('predictions:', predictions)
# getting the labels
pred_labels = list(np.argmax(predictions, axis=-1))
# getting true labels
true_labels = test_generator.classes
# get the confusion plot
cm = sklearn.metrics.confusion_matrix(true_labels, pred_labels)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.