使用 tf.data 使用我自己的图像进行自定义训练



我是Tensorflow的新手,在将自定义数据提供给keras模型时遇到问题。

我遵循了本指南:加载图像以将我的.jpg文件转换为tf.data。

现在我已将数据转换为(image_batch,label_batch(。image_batch是形状为 (32,224,224,3( 的 EagerTensor,label_batch是形状为 (32,2( 的 EagerTensor。

然后我找到了这个指南:自定义训练:演练,但公会中的数据被转换为形状为 (32,4( 的 EagerTensor。

执行代码时收到警告:

model = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation=tf.nn.relu, input_shape=(3,)),  # input shape required
tf.keras.layers.Dense(10, activation=tf.nn.relu),
tf.keras.layers.Dense(3)
])
predictions = model(image_batch)
WARNING:tensorflow:Model was constructed with shape (None, 3) for input Tensor("dense_input:0", shape=(None, 3), dtype=float32), but it was called on an input with incompatible shape (32, 224, 224, 3).

我应该如何调整我的模型或我应该如何处理我的数据?

编辑:

该模型现在可以工作,但还有一个额外的问题。

当我运行以下代码时:

print("Prediction: {}".format(tf.argmax(predictions, axis=1)))
print("    Labels: {}".format(labels_batch))

它打印:

Prediction: [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
Labels: [[ True False]
[False  True]
[ True False]
[False  True]
[ True False]...(omitted)]

但我希望它打印如下:

Prediction: [0 1 0 1 1 1 0 1 0 1 1 0 0 0 0 0 1 1 0 1 0 0 1 0 0 0 0 1 0 0 1 0]
Labels: [2 0 2 0 0 0 1 0 2 0 0 1 1 2 2 2 1 0 1 0 1 2 0 1 1 1 1 0 2 2 0 2]

将标签作为带有整数的一维数组。

我想知道预测都是 1 是否正常?我该怎么办?

您输入的是 32 张形状为 (224, 224, 3( 的图像,而不是 (3,(。输入形状需要为 (224,224,3(。

我还注意到您的输出形状看起来也会是 (224,224,3(,这与您的标签不匹配。您需要在某个时候展平数据或执行类似操作。

model = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation=tf.nn.relu, input_shape=(224,224,3)),  # input shape required
tf.keras.layers.Dense(10, activation=tf.nn.relu),
tf.kears.layers.Flatten(),
tf.keras.layers.Dense(2)
])

Danse 图层的输入形状应具有维度 (None, n(,其中 None 是batch_size。在您的情况下,如果您想使用密集图层,您应该首先使用Flatten图层,将图像滚动到形状(32, 224 * 224 * 3)。代码应为:

model = tf.keras.Sequential([
tf.keras.layers.Flatten(), 
tf.keras.layers.Dense(10, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.relu),
tf.keras.layers.Dense(3)
])

有关更多详细信息,请参阅 https://www.tensorflow.org/api_docs/python/tf/keras/layers/Flatten

最新更新