Nil*_*Cao 55 python python-3.x tensorflow tensor
我定义了一个像这样的张量:
x = tf.get_variable("x", [100])
但是当我尝试打印张量的形状时:
print( tf.shape(x) )
我得到Tensor("Shape:0",shape =(1,),dtype = int32),为什么输出的结果不应该是shape =(100)
nes*_*uno 118
tf.shape(input,name = None)返回表示输入形状的1-D整数张量.
你要找的:x.get_shape()
它返回TensorShape
的的x
变量.
更新:由于这个答案,我写了一篇文章来阐明Tensorflow中的动态/静态形状:https://pgaleone.eu/tensorflow/2018/07/28/understanding-tensorflow-tensors-shape-static-dynamic/
小智 11
澄清:
tf.shape(x)创建一个op并返回一个对象,该对象代表构造的op的输出,这是您当前正在打印的内容.要获得形状,请在会话中运行该操作:
matA = tf.constant([[7, 8], [9, 10]])
shapeOp = tf.shape(matA)
print(shapeOp) #Tensor("Shape:0", shape=(2,), dtype=int32)
with tf.Session() as sess:
print(sess.run(shapeOp)) #[2 2]
Run Code Online (Sandbox Code Playgroud)
信用:看了上面的答案后,我在Tensorflow中看到了tf.rank函数的答案,我发现它更有帮助,我在这里尝试过改写它.
只是一个基于@Salvador Dali答案的简单例子.
a = tf.Variable(tf.zeros(shape=(2, 3, 4)))
print('-'*60)
print("v1", tf.shape(a))
print('-'*60)
print("v2", a.get_shape())
print('-'*60)
with tf.Session() as sess:
print("v3", sess.run(tf.shape(a)))
print('-'*60)
print("v4",a.shape)
Run Code Online (Sandbox Code Playgroud)
输出将是:
------------------------------------------------------------
v1 Tensor("Shape:0", shape=(3,), dtype=int32)
------------------------------------------------------------
v2 (2, 3, 4)
------------------------------------------------------------
v3 [2 3 4]
------------------------------------------------------------
v4 (2, 3, 4)
Run Code Online (Sandbox Code Playgroud)
TF FAQ中很好地解释了类似的问题:
在 TensorFlow 中,张量同时具有静态(推断)形状和动态(真实)形状。可以使用以下方法读取静态形状
tf.Tensor.get_shape
:该形状是从用于创建张量的操作推断出来的,并且可能是部分完整的。如果静态形状未完全定义,则可以通过评估 来确定张量 t 的动态形状tf.shape(t)
。
因此tf.shape()
返回一个张量,其大小始终为shape=(N,)
,并且可以在会话中计算:
a = tf.Variable(tf.zeros(shape=(2, 3, 4)))
with tf.Session() as sess:
print sess.run(tf.shape(a))
Run Code Online (Sandbox Code Playgroud)
另一方面,您可以使用 提取静态形状x.get_shape().as_list()
,这可以在任何地方计算。
归档时间: |
|
查看次数: |
86365 次 |
最近记录: |