简体   繁体   English

不能建立混淆矩阵

[英]cannot build confusion matrix

I want to build a confusion matrix for my CNN model there is the code: 我想为我的CNN模型构建一个混淆矩阵,有代码:

classifier = Sequential()


classifier.add(Conv2D(32, (3, 3), input_shape=(64,64, 3), 
activation='relu'))


classifier.add(MaxPooling2D(pool_size=(2, 2)))  

classifier.add(Flatten())
classifier.add(Dense(units=1, activation='sigmoid'))



classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics= 
['accuracy'])


batch_size = 32

train_datagen = ImageDataGenerator(rescale=1. / 255,
                               shear_range=0.2,
                               zoom_range=0.2,
                               horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1. / 255)

training_set = train_datagen.flow_from_directory('x1' ,
                                             target_size=(64,64),
                                             batch_size=64,
                                             class_mode='binary')

test_set = test_datagen.flow_from_directory('x2' ,
                                        target_size=(64,64),
                                        batch_size=64,
                                        class_mode='binary')



ep=50

H=classifier.fit_generator(training_set,
                     steps_per_epoch=1204/batch_size,
                     epochs=ep,
                     validation_data=test_set,
                     validation_steps=408/batch_size,
                                     )

validation_steps=408

confusion matrix: 混淆矩阵:

from sklearn.metrics import confusion_matrix
Y_pred = classifier.predict_generator(test_set,validation_steps//batch_size+1)


y_pred = np.argmax(Y_pred, axis=1)
print('Confusion Matrix')
print(confusion_matrix(test_set.classes, y_pred))

I got this error : 我收到了这个错误:

ValueError: Found input variables with inconsistent numbers of samples: [408, 792] ValueError:找到样本数不一致的输入变量:[408,792]

What should I do? 我该怎么办?

test_set and y_pred don't have the same number of observations. test_sety_pred没有相同数量的观察结果。 Likely the number of steps you are passing to predict_generator is incorrect. 您传递给predict_generator的步骤数可能不正确。

Not sure which version of Keras you are using, but try Y_pred =classifier.predict_generator(test_set) . 不确定您使用的是哪种版本的Y_pred =classifier.predict_generator(test_set) ,但请尝试Y_pred =classifier.predict_generator(test_set) In newer versions leaving out number of steps will return predictions on all images. 在较新的版本中,省略多个步骤将返回所有图像的预测。

You have 你有

batch_size = 32

but inside test_set, 但在test_set中,

batch_size=64

so when you run predict_generator with validation_steps//batch_size+1 steps you are using 32 to create your steps but 64 for your generator. 因此,当您使用validation_steps//batch_size+1步骤运行predict_generator ,您使用32来创建步骤,但是为您的生成器创建64步。

You must set both to 32 or 64 您必须将两者都设置为32或64

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM