【问题标题】:How to code keras to read my own picture using my trained model?如何使用我训练过的模型编写 keras 来读取我自己的图片?
【发布时间】:2021-02-03 21:25:33
【问题描述】:

我使用 minst 训练了自己的读数模型,但是当我尝试上传自己的图片进行预测时,它告诉我一个错误:“ValueError: Input 0 of layer dense_3 is in compatible with the layer: expected axis -输入形状的 1 具有值 784,但接收到形状为 [None, 84] 的输入“(我的模型训练正确,在 minst 中预测图片成功。 这是我的代码:

import numpy as np
from keras.applications.imagenet_utils import decode_predictions
from keras.preprocessing import image
from keras.applications import *
import glob
 
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

img = []
x = []

images = image.load_img("/content/gdrive/My Drive/Colab Notebooks/num.png", target_size=(28, 28))
x = image.img_to_array(images)
x = np.expand_dims(x, axis=1)
img.append(x)

print(len(x))
x = np.concatenate([x for x in img])
 
model = tf.keras.models.load_model('num_reader.model')
y = model.predict(x)
print('Predicted:', decode_predictions(y, top=3))

这是我的错误:

28    #This is printed by "print(len(x))"
WARNING:tensorflow:Model was constructed with shape (None, 28, 28) for input Tensor("flatten_1_input_3:0", shape=(None, 28, 28), dtype=float32), but it was called on an input with incompatible shape (None, 1, 28, 3).
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-18-cd1af7600aac> in <module>()
     27 
     28 model = tf.keras.models.load_model('num_reader.model')
---> 29 y = model.predict(x)
     30 print('Predicted:', decode_predictions(y, top=3))

10 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    971           except Exception as e:  # pylint:disable=broad-except
    972             if hasattr(e, "ag_error_metadata"):
--> 973               raise e.ag_error_metadata.to_exception(e)
    974             else:
    975               raise

ValueError: in user code:

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1462 predict_function  *
        return step_function(self, iterator)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1452 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:1211 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2585 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2945 _call_for_each_replica
        return fn(*args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1445 run_step  **
        outputs = model.predict_step(data)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1418 predict_step
        return self(x, training=False)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py:985 __call__
        outputs = call_fn(inputs, *args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/sequential.py:372 call
        return super(Sequential, self).call(inputs, training=training, mask=mask)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/functional.py:386 call
        inputs, training=training, mask=mask)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/functional.py:508 _run_internal_graph
        outputs = node.layer(*args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py:976 __call__
        self.name)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/input_spec.py:216 assert_input_compatibility
        ' but received input with shape ' + str(shape))

    ValueError: Input 0 of layer dense_3 is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape [None, 84]

Minst 是 28x28 图片,因此此代码使用 28x28 图片。 我的开发环境是:“Google Colab”和“Juypter Notebook”,这个错误我已经尝试了这两个环境,仍然得到这个错误。 有人可以帮忙吗? import tensorflow as tf # 深度学习库。张量只是多维数组

mnist = tf.keras.datasets.mnist  # mnist is a dataset of 28x28 images of handwritten digits and their labels
(x_train, y_train),(x_test, y_test) = mnist.load_data()  # unpacks images to x_train/x_test and labels to y_train/y_test

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

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(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=10)  # 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

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

    如果不确切知道您的模型是如何构建的以及 num.png 的样子,这有点难以判断。但是,从错误消息来看,您似乎有两个错误:您正在加载 rgb 彩色图像(尽管 MNIST 并且您的模型很可能是在灰度图像上训练的),因此(或者这是第二个错误)您的尺寸错误(3 表示RGB,而不是灰度)。 28*3 = 84 是我解释错误信息的方式:

    但收到了形状为 [None, 84] 的输入

    尝试add rgb_to_grayscaleaxis=0

    import tensorflow as tf
    from keras_preprocessing import image
    images = image.load_img("/content/gdrive/My Drive/Colab Notebooks/num.png", target_size=(28, 28))    
    x = image.img_to_array(images)
    x = tf.image.rgb_to_grayscale(x)
    x = np.expand_dims(x, axis=0)
    x = x/255.0
    img.append(x)
    
    print(len(x))
    x = np.concatenate([x for x in img])
     
    model = tf.keras.models.load_model('num_reader.model')
    y = model.predict(x)
    print('Predicted:', decode_predictions(y, top=3))
    

    请注意,我添加了 x=x/255.0,因为我假设您也忘记了重新调整为 [0,1]。我假设如果您密切关注 MNIST ML 教程,您就可以在预处理中对模型应用重新缩放来训练模型。你也必须应用它。

    更新: 将 x 直接传递给 model.predict 也适用于我:

    images = image.load_img("/content/gdrive/My Drive/Colab Notebooks/num.png", target_size=(28, 28))    
    x = image.img_to_array(images)
    x = tf.image.rgb_to_grayscale(x)
    x = np.expand_dims(x, axis=0)
    x = x/255.0
    
    model = tf.keras.models.load_model('num_reader.model')
    model.predict(x)
    

    【讨论】:

    • ValueError: 尝试将具有不受支持类型 () 的值 () 转换为张量。我在“x = tf.image.rgb_to_grayscale(images)”行遇到了这个错误,但我不知道“”和 不都是一样的吗?我添加了代码让你知道我是如何训练它的。
    • 已更新,您可以再试一次吗?我补充说: from keras_preprocessing import image 和 import tensorflow as tf.请使用这些导入语句进行尝试。 ValueError 告诉我使用的程序和包有问题。所以 tf.image。不是来自 PIL 包。
    • 请检查更新,我也改了顺序,所以tf.image.rgb_to_grayscale需要在图片加载之后。请再次检查。
    • 我已经添加了它,但我仍然收到同样的错误。
    • 我刚刚在代码中更改了顺序,对不起,你能再检查一下吗,请确保 tf.image.rgb_to_grayscale 在图像加载后出现。错误是否仍然出现?
    【解决方案2】:

    在拟合模型之前,您需要使用 to_categorical 更改您的训练和测试标签。

    from keras.utils import to_categorical
    train_label=to_categorical(train_label)
    test_labels=to_categorical(test_labels)
    

    【讨论】:

      【解决方案3】:

      检查输出层的神经元数量是否与类数匹配。 我也遇到了同样的问题,原来我是在二分类中设置模型2的输出单位,应该是1。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-26
        • 1970-01-01
        • 2019-09-05
        • 2019-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多