[英]Confusion Matrix in Keras+Tensorflow
我已经训练了CNN模型,并将其另存为model.h5
。 我正在尝试检测3个物体。 说“猫”,“狗”和“其他”。 我的测试集有300张图像,每个类别有100张图像。 前100个是“猫”,第二个100是“狗”,第3个100是“其他”。 我正在使用flow_from_directory
类ImageDataGenerator
和flow_from_directory
。 这是示例代码:
test_datagen = ImageDataGenerator(rescale=1./255)
test_generator = test_datagen.flow_from_directory(
test_dir,
target_size=(150, 150),
batch_size=20,
class_mode='sparse',
shuffle=False)
现在使用
from sklearn.metrics import confusion_matrix
cnf_matrix = confusion_matrix(y_test, y_pred)
我需要y_test
和y_pred
。 我可以使用以下代码获取y_pred
:
probabilities = model.predict_generator(test_generator)
y_pred = np.argmax(probabilities, axis=1)
print (y_pred)
[0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 1 0 0 0 0 0 0 1 0 0 0
0 0 0 0 1 0 0 0 0 1 2 0 2 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 1 1
0 2 0 0 0 0 1 0 0 0 0 0 0 1 0 2 0 1 0 0 1 0 0 1 0 0 1 1 1 1 1 1 1 1 1 1 2
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1
1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 2 2 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 2
1 1 1 1 1 2 1 1 1 1 1 2 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 1 2 2 2 2 2 2 2 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 1 2 2 2 2 2 2 2 2 1 2 2 2 1 2 2 2 1 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2]
这基本上是将对象预测为0,1和2。现在我知道前100个对象(猫)为0,第二个100对象(狗)为1,第3个100对象(其他)为2。是否手动创建列表?使用numpy
,其中前100点为0,第二个100点为1,第3个100点为2以得到y_test
? 是否有任何Keras类可以做到这一点(创建y_test
)?
如何查看错误检测的对象。 如果您查看print(y_pred)
,则第三个点是1,这是错误预测的。 如何在不手动进入“ test_dir”文件夹的情况下看到该图像?
由于您没有使用任何增强和shuffle=False
,因此可以简单地从生成器获取图像:
imgBatch = next(test_generator)
#it may be interesting to create the generator again if
#you're not sure it has output exactly all images before
使用绘图库(例如Pillow(PIL)或MatplotLib)在imgBatch中绘制每个图像。
要仅绘制所需的图像, y_test
与y_pred
进行比较:
compare = y_test == y_pred
position = 0
while position < len(y_test):
imgBatch = next(test_generator)
batch = imgBatch.shape[0]
for i in range(position,position+batch):
if compare[i] == False:
plot(imgBatch[i-position])
position += batch
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.