tf.shape() get wrong shape in tensorflow

后端 未结 6 565
南笙
南笙 2020-12-04 10:21

I define a tensor like this:

x = tf.get_variable(\"x\", [100])

But when I try to print shape of tensor :

print( tf.shape(x) )

6条回答
  •  眼角桃花
    2020-12-04 10:56

    Simply, use tensor.shape to get the static shape:

    In [102]: a = tf.placeholder(tf.float32, [None, 128])
    
    # returns [None, 128]
    In [103]: a.shape.as_list()
    Out[103]: [None, 128]
    

    Whereas to get the dynamic shape, use tf.shape():

    dynamic_shape = tf.shape(a)
    

    You can also get the shape as you'd in NumPy with your_tensor.shape as in the following example.

    In [11]: tensr = tf.constant([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]])
    
    In [12]: tensr.shape
    Out[12]: TensorShape([Dimension(2), Dimension(5)])
    
    In [13]: list(tensr.shape)
    Out[13]: [Dimension(2), Dimension(5)]
    
    In [16]: print(tensr.shape)
    (2, 5)
    

    Also, this example, for tensors which can be evaluated.

    In [33]: tf.shape(tensr).eval().tolist()
    Out[33]: [2, 5]
    

提交回复
热议问题