tf.reshape没有为第一个元素提供?(None)

Moh*_* ah 5 python python-3.x tensorflow

我是tensorflow的新手,我的张量如下

a = tf.constant([[1, 2, 3], [4, 5, 6]])
Run Code Online (Sandbox Code Playgroud)

输出a.shape

TensorShape([Dimension(2),Dimension(3)])

对于我的计算过程,我想将张量重塑为 (?, 2, 3)

我无法将其重塑为所需的格式。

我试过了,

tf.reshape(a, [-1, 2, 3])
Run Code Online (Sandbox Code Playgroud)

但是它回来了

<tf.Tensor 'Reshape_18:0' shape=(1, 2, 3) dtype=int32> # 1 has to be replaced by ?
Run Code Online (Sandbox Code Playgroud)

我进一步尝试了

tf.reshape(a, [-1, -1, 2, 3])
Run Code Online (Sandbox Code Playgroud)

它返回

<tf.Tensor 'Reshape_19:0' shape=(?, ?, 2, 3) dtype=int32> # two ? are there
Run Code Online (Sandbox Code Playgroud)

如何获得理想的结果?

抱歉,这听起来很简单。

jde*_*esa 1

“问题”是 TensorFlow 会尽可能多地进行形状推断,这通常是件好事,但如果您明确想要有一个None维度,它就会变得更加复杂。这不是理想的解决方案,但一种可能的解决方法是使用 a tf.placeholder_with_default,例如如下所示:

import tensorflow as tf

a = tf.constant([[1, 2, 3], [4, 5, 6]])
# This placeholder is never actually fed
z = tf.placeholder_with_default(tf.zeros([1, 1, 1], a.dtype), [None, 1, 1])
b = a + z
print(b)
# Tensor("add:0", shape=(?, 2, 3), dtype=int32)
Run Code Online (Sandbox Code Playgroud)

或者另一个类似的选项,只是重塑:

import tensorflow as tf

a = tf.constant([[1, 2, 3], [4, 5, 6]])
s = tf.placeholder_with_default([1, int(a.shape[0]), int(a.shape[1])], [3])
b = tf.reshape(a, s)
b.set_shape(tf.TensorShape([None]).concatenate(a.shape))
print(b)
# Tensor("Reshape:0", shape=(?, 2, 3), dtype=int32)
Run Code Online (Sandbox Code Playgroud)