刚开始使用TensorFlow
和Keras
建立我的第一个模型。该模型的评估精度达到98%,但在预测模型时遇到困难。
import tensorflow as tf
import numpy as np
from PIL import Image
from keras.preprocessing import image
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
tf.keras.backend.image_data_format()== 'channels_last'
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
print(x_train.shape)
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test, verbose=2)
img = Image.open('8.png')
img = img.resize((28,28)
im2arr = np.array(img)
im2arr = im2arr.reshape(1,28,28,1)
print(im2arr.shape)
prediction = model.predict_classes(im2arr)
print(prediction)
答案 0 :(得分:0)
我不知道您的8.png
里面有什么,但是我更改了代码中的一些内容,对我来说,它可以处理一些测试图像。
import tensorflow as tf
import numpy as np
import PIL
from PIL import Image
from keras.preprocessing import image
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
tf.keras.backend.image_data_format()== 'channels_last'
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.GaussianNoise(0.05),
tf.keras.layers.Dense(32, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
print(x_train.shape)
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=10)
model.evaluate(x_test, y_test, verbose=2)
img = Image.open('8.png').convert('L')
img = img.resize((28, 28), resample=PIL.Image.BILINEAR)
im2arr = 255. - np.array(img, dtype=np.float32)
im2arr = im2arr / 255.
im2arr = im2arr.reshape(1,28,28,1)
print(im2arr.shape)
prediction = model.predict_classes(im2arr)
print(prediction)
基本上,我只是修改了模型以使其对过度拟合更为健壮,并在将输入图像提供给模型之前为输入图像添加了一些准备。