【问题标题】:TensorFlow 2.4.0 model.predict error when using array of Tensors as inputTensorFlow 2.4.0 model.predict 使用张量数组作为输入时出现错误
【发布时间】:2021-03-17 03:31:03
【问题描述】:

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

形状如下:

  • 模型输入:&lt;KerasTensor: shape=(None, 224, 224, 3) dtype=float32
  • test_batch:(&lt;tf.Tensor: shape=(224, 224, 3), dtype=float32&gt;, &lt;tf.Tensor: shape=(224, 224, 3), dtype=float32&gt;)

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

【问题讨论】:

    标签: python tensorflow machine-learning keras deep-learning


    【解决方案1】:

    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)
    

    【讨论】:

    • 谢谢,这行得通。但是我不明白为什么文档说模型可以将张量列表作为输入。在那种情况下,第一个维度不会是批量大小,即列表的长度,为什么 TensorFlow 不能正确地将其解释为批量维度?
    • 在模型有多个输入的情况下,可以将张量列表作为输入。我认为最有可能的是,TensorFlow 不能将列表的大小解释为批处理,因为它需要这种形式的多个输入。因此,一种将它们堆叠成数组以创建批次的最干净、最好的方法。
    【解决方案2】:

    我发现的一个可能的解决方案是简单地堆叠两个张量来创建一个批处理维度,如下所示:

    test_batch = tf.stack([img_tf1, img_tf2])
    predictions = model.predict(test_batch)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-07
      • 2020-12-10
      • 2018-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-22
      相关资源
      最近更新 更多