TensorFlow 2.4.0 使用张量数组作为输入时 model.predict 报错

根据 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)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注