-1 在张量输入的形状中意味着什么?

What does a -1 mean in the shape of a tensor input?

我有一个 TensorFlowJS 模型,其输入如下所示:

{"name":"dense_3_input","shape":[-1,25],"dtype":"float32"}

-1 是什么意思?

构建模型的方式是使用 Dense(1, input_dim=25, activation="sigmoid"),所以我不知道 -1 从哪里来,也不知道如何正确创建它正在寻找的张量。

如果我传递一个

的张量
tf.tensor([0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1])

我收到这个错误。

Error: The shape of dict['dense_3_input'] provided in model.execute(dict) must be [-1,25], but was [25]

当通过上述 25 0/1 的输入时,模型在 python 中正常工作。转换为 TensorFlowJS 模型是否无法正常工作?任何见解将不胜感激。

-1表示未定数,可以任意取数

如果您传入一个形状为 [25] 的张量,则需要添加括号,因此形状变为 [1,25],这将是有效的。

尝试:

tf.tensor([[0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1]])

如@mark-h 的评论所述,问题是我将单个值数组传递给带有 tf.tensor([0, 1...]) 的张量。 [-1, 25] 表示存在未确定数量的数组,其中包含输入所期望的 25 个值。

将我的张量更改为 tf.tensor([[0, 1...]]) 解决了这个问题。

-1 在张量的一个维度中意味着该维度的大小将根据其他维度进行计算。张量形状应该是其他维度大小乘积的倍数才能起作用

tensor size: 25, shape [-1, 25] => [1, 25]

                 shape [-1, 5] => [5, 5]

                 shape [-1, 3] => will not work

当我们不知道张量的大小但知道它将是某些值的倍数时,它很有用。

题例中,初始张量可以重塑:

  • tf.tensor([0, 1...]).reshape([-1, 25])

  • 可以直接构造为2d张量tf.tensor([[0, 1...]])