我正在尝试获取所有正确和不正确的预测值(我要预测图像类别)
所以,我的代码是:
#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)
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
我正在尝试使用tutorial中的代码,但出现错误:
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)
答案 0 :(得分:0)
根据您的形状,我假设您有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)