我使用下面的配置来建立图像分类模型。
model = keras.Sequential([
keras.layers.Flatten(input_shape=(100, 100, 3)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10)
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
如果我打印model.inputs,那么它就会返回
[<tf.Tensor 'flatten_input:0' shape=(None, 100, 100, 3) dtype=float32>]
如果我把张量图像传给这个模型,那么它就不能工作。所以我的问题是,我应该对我的模型做什么改变,使它能接受张量图。
我使用下面的代码传递图像。
image = np.asarray(image)
# The input needs to be a tensor, convert it using `tf.convert_to_tensor`.
input_tensor = tf.convert_to_tensor(image)
# The model expects a batch of images, so add an axis with `tf.newaxis`.
input_tensor = input_tensor[tf.newaxis,...]
# Run inference
output_dict = model(input_tensor)
如果我传递张量图像,我得到了以下错误
WARNING:tensorflow:Model was constructed with shape (None, 100, 100, 3) for input Tensor("flatten_input:0", shape=(None, 100, 100, 3), dtype=float32), but it was called on an input with incompatible shape (1, 886, 685, 3).
---------------------------------------------------------------------------
InvalidArgumentError Traceback (most recent call last)
我只是想知道我应该更新哪些Keras层和输入参数到模型中,以便它可以接受张量图像作为输入。谢谢
这个消息是一个警告,不是错误,只是一些语义。这个警告确实指出了一个真正的问题。
你的模型采集图像的形状是 (100, 100, 3)
而你给它输入的是形状 (886, 865, 3)
. 空间尺寸不匹配,你需要调整图像的大小到 100 x 100
.
定义你的模型,你需要告诉keras你的图片的通道数:1为黑白图片,3为RGB......
所以你需要写。
keras.layers.Flatten(input_shape=(1, 100, 100, 3)) for a 1 channel picture
我还注意到,你没有定义一个激活函数的最后一层 。keras.layers.Dense(10)
如果你定义了一个交叉熵的损失,你需要得到一些概率作为你的网络的输出,比如说 keras.layers.Dense(10, activation='softmax')
希望你能明白