【发布时间】:2020-12-04 13:59:38
【问题描述】:
https://pythonprogramming.net/introduction-deep-learning-python-tensorflow-keras/
一直在学习本教程,我的代码几乎是准确的,稍作修改。
代码运行良好并且几乎总是正确的,除非我绘制新图像它经常失败,我认为样本量太小,但即使我从培训材料中复制粘贴图片,我仍然得到错误的结果.
这是我当前的代码:
import tensorflow as tf
import numpy as np
from PIL import Image
import PIL
print(tf.__version__)
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
'''
import matplotlib.pyplot as plt
plt.imshow(x_train[0],cmap=plt.cm.binary)
plt.show()
'''
x_train = tf.keras.utils.normalize(x_train, axis=1) # scales data between 0 and 1
x_test = tf.keras.utils.normalize(x_test, axis=1) # scales data between 0 and 1
def train():
model = tf.keras.models.Sequential() # a basic feed-forward model
model.add(tf.keras.layers.Flatten()) # takes our 28x28 and makes it 1x784
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) # a simple fully-connected layer, 128 units, relu activation
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) # a simple fully-connected layer, 128 units, relu activation
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax)) # our output layer. 10 units for 10 classes. Softmax for probability distribution
model.compile(optimizer='adam', # Good default optimizer to start with
loss='sparse_categorical_crossentropy', # how will we calculate our "error." Neural network aims to minimize loss.
metrics=['accuracy']) # what to track
model.fit(x_train, y_train, epochs=3) # train the model
val_loss, val_acc = model.evaluate(x_test, y_test) # evaluate the out of sample data with model
print(val_loss) # model's loss (error)
print(val_acc) # model's accuracy
model.save('model',save_format='tf')
def predict():
model = tf.keras.models.load_model('model')
img = Image.open('tests/num.png')
img = np.resize(img, (28,28,1))
im2arr = np.array(img)
im2arr = im2arr.reshape(1,1,28,28)
y_pred = model.predict(im2arr)
print(np.argmax(y_pred))
print(y_pred)
predict()
将 predict() 替换为 train() 以创建模型,然后对其进行编辑并运行脚本
【问题讨论】:
-
你对训练集和测试集进行了归一化,但是你没有对新图像进行归一化,难怪预测不正确。
标签: python tensorflow keras