我遵循了 tensorflow2 教程,但現在想使用該模型來預測影像。
我的代碼:
import tensorflow
import tensorflow_datasets
import matplotlib.pyplot as plot
import numpy
def normalize_img(img, label):
return tensorflow.cast(img, tensorflow.float32) / 255., label
(mnist_train, mnist_raw), mnist_info = tensorflow_datasets.load(
'mnist',
split=['train', 'test'],
shuffle_files=True,
as_supervised=True,
with_info=True,
)
mnist_train = mnist_train.map(normalize_img, num_parallel_calls=tensorflow.data.AUTOTUNE)
mnist_train = mnist_train.cache()
mnist_train = mnist_train.shuffle(mnist_info.splits['train'].num_examples)
mnist_train = mnist_train.batch(128)
mnist_train = mnist_train.prefetch(tensorflow.data.AUTOTUNE)
mnist_test = mnist_raw.map(normalize_img, num_parallel_calls=tensorflow.data.AUTOTUNE)
mnist_test = mnist_test.batch(128)
mnist_test = mnist_test.cache()
mnist_test = mnist_test.prefetch(tensorflow.data.AUTOTUNE)
model = tensorflow.keras.models.Sequential([
tensorflow.keras.layers.Flatten(input_shape=(28, 28)),
tensorflow.keras.layers.Dense(128, activation='relu'),
tensorflow.keras.layers.Dropout(0.16),
tensorflow.keras.layers.Dense(10, activation="softmax")
])
model.compile(
optimizer=tensorflow.keras.optimizers.Adam(0.001),
loss=tensorflow.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=["accuracy"]
)
result = model.fit(mnist_train, epochs=6, validation_data=mnist_test)
it = mnist_test.as_numpy_iterator()
first = it.next()
images, labels = first[0], first[1]
plot.imshow(images[0].squeeze())
model(images[0].squeeze().flatten())
最后一行給出了錯誤:
ValueError Traceback (most recent call last)
ipython-input-87-57d521ba8778> in <module>()
----> 1 model(images[0].squeeze().flatten())
1 frames
/usr/local/lib/python3.7/dist-packages/keras/engine/input_spec.py in assert_input_compatibility(input_spec, inputs, layer_name)
247 if value is not None and shape_as_list[int(axis)] not in {value, None}:
248 raise ValueError(
--> 249 f'Input {input_index} of layer "{layer_name}" is '
250 f'incompatible with the layer: expected axis {axis} '
251 f'of input shape to have value {value}, '
ValueError: Exception encountered when calling layer "sequential_1" (type Sequential).
Input 0 of layer "dense_2" is incompatible with the layer: expected axis -1 of input shape to have value 784, but received input with shape (784, 1)
Call arguments received:
? inputs=tf.Tensor(shape=(784,), dtype=float32)
? training=False
? mask=None
據我所知,模型 operator() 需要一個一維陣列,但我為它提供了一個二維陣列,其中第二維是 1(本質上是一個 1 維陣列)。
我發現了這個問題:層順序的輸入 0 與層不兼容:輸入形狀的預期軸 -1 具有值 784
但如果我做 reshape(1, 784) 錯誤訊息切換到預期維度 (28,28)。如果我不展平陣列,我會得到 (28, 28) 提供的錯誤,但它想要 (784)。
uj5u.com熱心網友回復:
檢查形狀images[0].squeeze().flatten():
import numpy as np
print(np.shape(images[0].squeeze().flatten()))
(784,)
但是,您的輸入是(None, 28, 28). 因此,您不需要 flatten (由Flattenat 輸入處理)。此外,您需要批量維度。所以你可以這樣做:
model(np.expand_dims(images[0, :], axis=0))
請注意,如果您想一次輸入更多影像,它可以正常作業:
model(images[0:10, :])
因為批量維度是存在的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/475731.html
