在之后如何使用keras中的cnn预测我自己的图像(在目录中) MNIST数据集上的培训? 我知道我可以使用'model.predict(X_test [:])'对测试集图像进行预测,但是如何预测自己的图像呢?
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten
import matplotlib.pyplot as plt
from keras.datasets import mnist
from keras.utils import to_categorical
#download mnist data and split into train and test sets
(X_train, y_train), (X_test, y_test) = mnist.load_data()
#plot the first image in the dataset
plt.imshow(X_train[0])
X_train = X_train.reshape(60000,28,28,1)
X_test = X_test.reshape(10000,28,28,1)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
y_train[0]
#create model
model = Sequential()
#add model layers
model.add(Conv2D(64, kernel_size=3, activation='relu', input_shape=(28,28,1)))
model.add(Conv2D(32, kernel_size=3, activation='relu'))
model.add(Flatten())
model.add(Dense(10, activation='softmax'))
#compile model using accuracy as a measure of model performance
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train,validation_data=(X_test, y_test), epochs=1)
答案 0 :(得分:0)
您应该首先通过cv2
读入图像并将其大小调整为(28,28)。最后,将批次尺寸(第0个尺寸)和通道尺寸(最后一个尺寸)添加到keras模型中。
import cv2
import numpy as np
img = cv2.imread("your_image.png",0)
img = cv2.resize(img, (28, 28))
img = np.reshape(img, [1, 28, 28, 1])
print(np.argmax(model.predict(img)))