首页 > 解决方案 > 使用张量数组作为输入时,TensorFlow 2.4.0 model.predict 错误

问题描述

根据Keras Sequential Model .predict()文档,该模型可以使用多种输入形式,包括:

TensorFlow 张量或张量列表(如果模型有多个输入)。

这正是我想要做的,即使用两个张量的“批次”作为 predict() 的输入,并在以下代码中获得两个预测作为输出:

test_batch = (img_tf1, img_tf2) # two Tensors in list
predictions = model.predict(test_batch)

但是我收到以下错误:

ValueError: Layer sequential expects 1 input(s), but it received 2 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(32, 224, 3) dtype=float32>, <tf.Tensor 'IteratorGetNext:1' shape=(32, 224, 3) dtype=float32>]

形状如下:

有谁知道问题出在哪里?我相信我正确地使用了 API,正如文档中所指定的那样。我的 TensorFlow 版本是 2.4.0,在 conda 环境中安装了 pip。

标签: pythontensorflowmachine-learningkerasdeep-learning

解决方案


TensorFlow 将它们视为模型的单独输入,因为它们没有堆叠。你可以做两件事:

img1 = tf.expand_dims(img1, axis = 0) # in case you did not add batch dims.
img2 = tf.expand_dims(img2, axis = 0) # in case you did not add batch dims.

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] # store them in a list

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)

推荐阅读