【问题标题】:tensorflow importing images correctlytensorflow正确导入图像
【发布时间】: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


【解决方案1】:

为了做出准确的预测,您需要为模型提供与其所学到的数据相似的数据。在这种情况下,您对训练数据使用了归一化函数,因此网络已经学习了浮点值介于 0 和 1 之间的数据。因此,您需要对尝试预测的数据进行相同的处理来自。

im2arr = np.array(img) 
im2arr = tf.keras.utils.normalize(im2arr, axis=1)

【讨论】:

  • 如果我替换 im2arr = im2arr.reshape(1,1,28,28) 我得到这个错误ValueError: Input 0 of layer dense is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape [None, 28] ,如果我保留它但也把你建议没有改变的那一行写进去跨度>
  • 像你一样对其进行规范化,没有改变任何东西,删除 im2arr = im2arr.reshape(1,1,28,28) 会给我一个错误
  • 规范化输入不会改变任何东西,除了提供更好的结果,这就是你所追求的。
  • 尽管如此,他们仍然非常错误,而且似乎每次我制作一个新模型时,它都会专注于其中一个数字并总是预测那个数字,无论我输入的是什么跨度>
猜你喜欢
  • 2019-11-21
  • 1970-01-01
  • 1970-01-01
  • 2020-12-29
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
  • 2016-08-22
  • 2021-11-10
相关资源
最近更新 更多