我想将张量的形状从(3,4)更改为(1,3,4),所以我使用get_shape()。as_list()来获取原始形状,并尝试修改它列表使用insert,但是,我发现包含维度信息的原始列表变为None,发生了什么?或者,如果我想从(3,4)到(1,3,4)重构张量,我该怎么办?
a=np.random.random([3,4])
a=tf.constant(a)
g=a.get_shape().as_list()
g
#[3,4]
g=a.get_shape().as_list().insert(0,1)
type(g)
#NoneType
答案 0 :(得分:0)
为什么不使用tf.reshape()?
>>> a=np.random.random([3,4])
>>> a=tf.constant(a)
>>> a
<tf.Tensor 'Const_2:0' shape=(3, 4) dtype=float64>
>>> a=tf.reshape(a, (1, 3, 4))
>>> a
<tf.Tensor 'Reshape_2:0' shape=(1, 3, 4) dtype=float64>
编辑:在Python中,列表的.insert()方法不返回任何内容。因此你得到无类型。参考:https://www.tutorialspoint.com/python/list_insert.htm
您应该将g用作临时列表。试试这个;
>>> a=np.random.random([3,4])
>>> a=tf.constant(a)
>>> a
<tf.Tensor 'Const_1:0' shape=(3, 4) dtype=float64>
>>> g=a.get_shape().as_list()
>>> g
[3, 4]
>>> g.insert(0, 1)
>>> g
[1, 3, 4]
>>> a=tf.reshape(a, g)
>>> a
<tf.Tensor 'Reshape:0' shape=(1, 3, 4) dtype=float64>