Python tf.Reformate未为第一个元素提供?(无)

Python tf.Reformate未为第一个元素提供?(无),python,python-3.x,tensorflow,Python,Python 3.x,Tensorflow,我是tensorflow的新手,我有下面这样的张量 a = tf.constant([[1, 2, 3], [4, 5, 6]]) a.shape的输出为 张量形状([尺寸(2),尺寸(3)]) 对于我的计算过程,我想将张量重塑为(?,2,3) 我无法改变它的格式 我试过了 tf.reshape(a, [-1, 2, 3]) 但它回来了 <tf.Tensor 'Reshape_18:0' shape=(1, 2, 3) dtype=int32> # 1 has to be rep

我是tensorflow的新手,我有下面这样的张量

a = tf.constant([[1, 2, 3], [4, 5, 6]])
a.shape
的输出为

张量形状([尺寸(2),尺寸(3)])

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

我无法改变它的格式

我试过了

tf.reshape(a, [-1, 2, 3])
但它回来了

<tf.Tensor 'Reshape_18:0' shape=(1, 2, 3) dtype=int32> # 1 has to be replaced by ?
<tf.Tensor 'Reshape_19:0' shape=(?, ?, 2, 3) dtype=int32> # two ? are there
它回来了

<tf.Tensor 'Reshape_18:0' shape=(1, 2, 3) dtype=int32> # 1 has to be replaced by ?
<tf.Tensor 'Reshape_19:0' shape=(?, ?, 2, 3) dtype=int32> # two ? are there
两个?有 我如何获得期望的结果

抱歉,如果这听起来很简单的问题

问题是TensorFlow尽可能多地进行形状推断,这通常是一件好事,但如果您明确希望有一个
None
维度,它会使它变得更复杂。这不是一个理想的解决方案,但一个可能的解决方法是使用,例如:

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)
或另一个类似的选项,只需重塑:

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)

你试图完成的任务根本上是错误的。您正在尝试从完全已知形状生成部分已知形状

在图形构造过程中,当您不知道完全已知的形状时,将使用部分已知的形状。无论如何,在执行图形时必须指定实际形状。因此,将形状完全已知的张量转换为部分已知的张量是没有意义的


如果要对某些部分已知的形状执行操作,请使用广播(例如,对带有形状
(1,2,3)
的张量执行
添加
操作,并且
(无,2,3)
会导致形状
(无,2,3)
)的张量,问题是什么?任何需要形状
(?,2,3)
的东西也应该接受形状
(1,2,3)
。你有例外吗?是的。我得到一个例外,张量的外维是1,应该是零。这是tensorflow服务模型的一部分,它希望最外层维度为none,以便提供批处理输出。如果是一个,那么它只能提供一个输出。感谢您的解决方案,我会检查并让您知道。您能解释一下它是如何工作的吗
z=tf.placeholder\u和默认值(tf.zeros([1,1,1],a.dtype),[None,1,1])
此行。特别是[1,1,1]@MohamedThasinah它所做的是创建一个带有shape
(?,1,1)
,默认值为
[[0]]]
,它实际上具有shape
(1,1,1)
。因为原则上,您可以为占位符提供不同的值,TunSoFrof不能假定实际形状总是要<代码>(1, 1, 1)< /C>,所以必须考虑第一个维度可以有任何大小,这将导致广播添加
a
,从而提供新的初始
维度。“诀窍”是你从来没有为占位符实际输入过值,所以它就像一个带有部分未知形状的常量。@MohamedThasinah说,如果可能的话,你通常不希望这样做,而是希望检查形状是否精确相等,而是检查形状是否兼容。