Keras + MNIST +测试自己的图片。不好预测

问题描述 投票:2回答:2

它通过测试MNIST自己的测试图像正常,但只要我使用的图片从外面MNIST,它预测错了。我甚至试图复制从MNIST数据集的图像之一,它仍然could'nt预测右边的数字(即使完全相同的图像是确定的(预测)的MNIST数据集内时)。

可能有人看我做什么了?我猜有什么东西与图像的尺寸或形状。

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D
import cv2 as cv

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()

x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
input_shape = (28, 28, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
# Normalizing the RGB codes by dividing it to the max RGB value.
x_train /= 255
x_test /= 255

# -------------------------- CREATE MODEL ------------------------------
'''
model = Sequential()
model.add(Conv2D(28, kernel_size=(3,3), input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten()) # Flattening the 2D arrays for fully connected layers
model.add(Dense(128, activation=tf.nn.relu))
model.add(Dropout(0.2))
model.add(Dense(10,activation=tf.nn.softmax))

# ----------------------------------------------------------------------

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.fit(x=x_train,y=y_train, epochs=1)

# ----------------------------------------------------------------------
'''
model = tf.keras.models.load_model("C:/Users/A551110/PycharmProjects/keras_mnist/venv/mnistv2.model")
file = "C:/Users/A551110/Documents/images/7.png"
model.evaluate(x_test, y_test)

image = cv.imread(file, cv.IMREAD_GRAYSCALE)
image = cv.resize(image, (28,28))
image = 255-image          #inverts image. Always gets read inverted.

plt.imshow(image.reshape(28, 28),cmap='Greys')
plt.show()
pred = model.predict(image.reshape(1, 28, 28, 1), batch_size=1)

print(pred.argmax())

我试过pred = model.predict(image.reshape(1, 28, 28, 1))

以及pred = model.predict_classes(image.reshape(1, 28, 28, 1))

The digits i was predicting. Upper one from mnist dataset (predicted correctly) and one lower one copied and put in (predicted wrongly)

python tensorflow keras mnist
2个回答
3
投票

我想到了。我没有用这个代码块得到正确的标准化值了。

image = cv.imread(file, cv.IMREAD_GRAYSCALE)
image = cv.resize(image, (28,28))
image = 255-image     

相反,我曾与师在底部(在这里的底部),我误了图像= 255图像之前在早期尝试把纠正。这是故障之一,在缺少之间铸造类型FLOAT32这使我们可以正常化,以及重塑在那里一起。

image = cv.imread(file, cv.IMREAD_GRAYSCALE)
image = cv.resize(file, (28, 28))
image = image.astype('float32')
image = image.reshape(1, 28, 28, 1)
image = 255-image
image /= 255

0
投票

有猜测

1)你归你的训练和测试数据。我假设你可能会忘记做预测之前,一定要规范你的输入数据?

x_train /= 255
x_test /= 255

2)您是否验证该模型是否正确装入?保存和加载后,验证它仍然执行的测试集相同。如果效果不好,告诉你的是,权重未正确加载。

3)是否有任何预处理(你自己的正常化以外)的数据集,通过tf.keras.datasets.mnist.load_data()提供?如果是这样,你必须进行预处理与推论与之前相同的变换自己的输入数据

© www.soinside.com 2019 - 2024. All rights reserved.