我使用 MNIST 训练了自己的数字识别模型,但当我尝试上传自己的图片进行预测时,它提示一个错误:"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]"(我的模型训练正确,用 MNIST 预测图片也成功)。以下是我的代码:
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和Jupyter Notebook,并且我已经在两种环境下尝试过,仍然出现了这个错误。 有人可以帮忙吗? 导入tensorflow库,它是一个深度学习库。张量只是多维数组。
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