不使用xtrain xtest ytrain ytest的keras cnn模型中的混淆矩阵

时间:2018-11-12 01:18:55

标签: tensorflow keras conv-neural-network confusion-matrix

我目前正在尝试在我的cnn模型代码中实现一个混淆矩阵。我一直在观看的所有示例都包括使用x_train, x_test, y_train, y_test,但是我不知道如何在我的代码中执行此操作,或者我是否能够从my_model.h5文件中执行此操作。希望你能帮助我。谢谢。

我将我的模型代码留在这里:

classifier = Sequential()
classifier.add(Conv2D(32, (3,  3), input_shape = (64, 64, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size =(2,2)))
classifier.add(Conv2D(32, (3,  3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size =(2,2)))
classifier.add(Conv2D(64, (3,  3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size =(2,2)))
classifier.add(Flatten())
classifier.add(Dense(256, activation = 'relu'))
classifier.add(Dropout(0.5))
classifier.add(Dense(26, activation = 'softmax'))

classifier.compile(
          optimizer = optimizers.SGD(lr = 0.01),
          loss = 'categorical_crossentropy',
          metrics = ['accuracy'])

classifier.summary()

from keras.preprocessing.image import ImageDataGenerator
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(
    'mydata/training_set',
    target_size=(64, 64),
    batch_size=32,
    class_mode='categorical')

test_set = test_datagen.flow_from_directory(
    'mydata/test_set',
    target_size=(64, 64),
    batch_size=32,
    class_mode='categorical')

model = classifier.fit_generator(
    training_set,
    steps_per_epoch=int(steps_per_epoch_user),
    epochs=int(epochs_user),
    validation_data = test_set,
    validation_steps = int(validation_steps_user)
  )

import h5py
classifier.save('my_model.h5')

print(model.history.keys()) 

import matplotlib.pyplot as plt

plt.plot(model.history['acc'])
plt.plot(model.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('acc')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

plt.plot(model.history['loss'])
plt.plot(model.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

1 个答案:

答案 0 :(得分:0)

我将添加以下代码:

从sklearn.metrics导入confusion_matrix

cm = confusion_matrix(Y_test,Y_test_predicted)

print('\ n','cm =','\ n',cm)

有关更具描述性的混淆矩阵,请查看以下链接中的scikit-learn文档:

https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html