Python TensorFlow 2.4.0模型。使用张量数组作为输入时预测误差

Python TensorFlow 2.4.0模型。使用张量数组作为输入时预测误差,python,tensorflow,machine-learning,keras,deep-learning,Python,Tensorflow,Machine Learning,Keras,Deep Learning,根据文档,模型可以使用多种输入形式,包括: 张量流张量或张量列表(如果模型有多个输入) 这正是我要做的,即使用两个张量的“批”作为输入predict()并在以下代码中获得两个预测作为输出: test_batch = (img_tf1, img_tf2) # two Tensors in list predictions = model.predict(test_batch) 但是,我得到以下错误: ValueError: Layer sequential expects 1 input(s),

根据文档,模型可以使用多种输入形式,包括:

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

这正是我要做的,即使用两个张量的“批”作为输入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>]
ValueError:Layer sequential需要1个输入,但收到2个输入张量。收到的投入:[,]
形状如下:

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

  • 模型输入:
    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>
    

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

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

    谢谢,这很有效。然而,我不明白的是,为什么文档中说模型可以将张量列表作为输入。在这种情况下,第一个维度不是批次大小,即列表的长度,为什么TensorFlow不能将其正确解释为批次维度?在模型有多个输入的情况下,可以将张量列表作为输入。我认为最有可能的是,TensorFlow无法将列表的大小解释为批处理,因为它需要以该形式进行多个输入。因此,将它们堆叠到一个数组中以创建批处理是一种最干净、最好的方法。