根据 Keras 序列模型 .predict() 文档,模型可以使用多种输入形式,包括:
一个 TensorFlow 张量,或者一个张量列表(如果模型有多个输入)。
我尝试做的正是如此,即使用两个张量的“批次”作为 predict() 的输入,并在以下代码中获得两个预测作为输出:
test_batch = (img_tf1, img_tf2) # 列表中的两个张量predictions = model.predict(test_batch)
然而我得到了以下错误:
ValueError: Layer sequential 期望 1 个输入,但收到了 2 个输入张量。收到的输入:[<tf.Tensor 'IteratorGetNext:0' shape=(32, 224, 3) dtype=float32>, <tf.Tensor 'IteratorGetNext:1' shape=(32, 224, 3) dtype=float32>]
形状如下:
- 模型输入:
<KerasTensor: shape=(None, 224, 224, 3) dtype=float32
- test_batch:
(<tf.Tensor: shape=(224, 224, 3), dtype=float32>, <tf.Tensor: shape=(224, 224, 3), dtype=float32>)
有谁知道问题出在哪里吗?我相信我按照文档的说明正确使用了 API。我的 TensorFlow 版本是 2.4.0,通过 pip 在 conda 环境中安装的。
回答:
TensorFlow 将它们视为模型的独立输入,因为它们没有被堆叠。你可以做两件事:
img1 = tf.expand_dims(img1, axis = 0) # 如果你没有添加批次维度img2 = tf.expand_dims(img2, axis = 0) # 如果你没有添加批次维度test_batch = (img1,img2)test_batch = tf.experimental.numpy.vstack(test_batch)preds = last_model.predict(test_batch)
或者你可以创建 tf.data.Dataset
,它们稍后会被批处理:
img1 = tf.random.uniform((32,32,3))img2 = tf.random.uniform((32,32,3))test_batch = [img1,img2] # 将它们存储在一个列表中test_batch = tf.data.Dataset.from_tensor_slices(test_batch).batch(1)
我们可以看到它们有一个批次维度。
test_batch<BatchDataset shapes: (None, 32, 32, 3), types: tf.float32>
之后,它们可以被预测:
preds = last_model.predict(test_batch)