【发布时间】:2018-01-09 19:42:21
【问题描述】:
我在使用 MNIST 尝试 Keras 时遇到问题。我有一个保存的模型,其准确率超过 99%,但是当我用它来预测一些图像时,它总是预测为 1。我认为这是由于我在 test.py 文件中以错误的方式重新调整了图像数据输入。
我得到了错误:
ValueError: Error when checking : expected conv2d_1_input to have 4 dimensions, but got array with shape (28, 28)
或者,如果我尝试随机重塑 (1, 1, 28, 28),我会收到以下错误:
ValueError: Error when checking : expected conv2d_1_input to have shape (None, 28, 28, 1) but got array with shape (1, 1, 28, 28)
所以我尝试在 image_to_data 函数中添加以下内容:
image_data = image_data.reshape((1, 28, 28, 1))
现在代码运行但总是预测相同的值。如何以正确的方式将图像数据重塑为 28 x 28 像素,使其适合模型中的第一层以预测一个图像的类别?
train.py
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
batch_size = 128
num_classes = 10
epochs = 20
# input image dimensions
img_rows, img_cols = 28, 28
# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu',
input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# serialize model to YAML
model_yaml = model.to_yaml()
with open("model-new.yaml", "w") as yaml_file:
yaml_file.write(model_yaml)
# serialize weights to HDF5
model.save_weights("model-new.h5")
print("Saved model to disk")
test.py
from PIL import Image
from keras.models import model_from_yaml
import numpy as np
def load_model():
# load YAML and create model
yaml_file = open('model.yaml', 'r')
model_yaml = yaml_file.read()
yaml_file.close()
model = model_from_yaml(model_yaml)
# load weights into new model
model.load_weights("model.h5")
print("Loaded model from disk")
model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
return model
def image_to_data(image):
image_data = np.array(image) / 255
image_data = image_data.reshape((1, 28, 28, 1))
return image_data
def predict(model, image):
data = image_to_data(image)
prediction = model.predict_classes(data)
return prediction
def predict_image(model, filename):
image = Image.open(filename)
data = image_to_data(image)
prediction = predict(model, data)
return prediction
model = load_model()
print(predict_image(model, '3.png'))
print(predict_image(model, '6.png'))
print(predict_image(model, '8.png'))
【问题讨论】:
-
首先我会在训练模型时尝试减少 epoch 的数量,模型可能已经过拟合(99% 的准确率)。为了评估这一点,您可以非常轻松地使用 keras 实现交叉验证测试。这使您可以更真实地了解准确度,因为您可以在整个训练过程中流畅地比较测试准确度(使用训练图片进行测试)和交叉验证准确度(使用模型从未见过的图片进行测试) .
-
我从 mnist 数据 (x_train, y_train), (x_test, y_test) = mnist.load_data() 中有一个单独的测试集,但也许我应该再次检查,以便模块没有该数据在训练集中也是如此,我认为它不会,因为在两个地方都有它是没有意义的。
-
你也可以做类似 np.expand_dims(image, axis=0)/255 的事情。这将我的 (256, 256, 3) 图像转换为 (1, 256, 256, 3)。
标签: python numpy machine-learning neural-network keras