https://www.jianshu.com/p/2b88256ad206
tf中有两对方法比较容易混淆,涉及的是shape问题,在此做一些区分。
首先说明tf中tensor有两种shape,分别为static (inferred) shape
和dynamic (true) shape
,其中static shape
用于构建图,由创建这个tensor的op推断(inferred)得来,故又称inferred shape
。如果该tensor的static shape
未定义,则可用tf.shape()
来获得其dynamic shape
。
1. 区分x.get_shape()
和x = tf.shape(x)
x.get_shape()
返回static shape
,只有tensor有这个方法,返回是元组。x.get_shape().as_list()
是一个常用方法,经常被用于将输出转为标准的python list。
关于static shape
的样例示范如下:
x = tf.placeholder(tf.int32, shape=[4])
print x.get_shape()
# ==> '(4,)'
get_shape()
返回了x的静态类型,4代指x是一个长度为4的向量。需要注意,get_shape()
不需要放在session中即可运行。
与get_shape()
不同,tf.shape()
的示例代码如下:
y, _ = tf.unique(x)
print y.get_shape()
# ==> '(?,)'
sess = tf.Session()
print sess.run(y, feed_dict={x: [0, 1, 2, 3]}).shape
# ==> '(4,)'
print sess.run(y, feed_dict={x: [0, 0, 0, 0]}).shape
# ==> '(1,)'
通过此代码体会两种shape的不同,需要注意tf.shape()
需要在session中运行。
2. 区分x.set_shape()
和tf.reshape()
set_shape更新tensor的static shape
,不改变dynamic shape
。reshape创建一个具备不同dynamic shape
的新的tensor。
#####################################################################################
两种方法都可以获得变量的shape
tf.shape(x)
其中x可以是tensor,也可不是tensor,返回是一个tensor.
shape=tf.placeholder(tf.float32, shape=[None, 227,227,3] )
- 1
我们经常会这样来feed
数据,如果在运行的时候想知道None
到底是多少,这时候,只能通过tf.shape(x)[0]
这种方式来获得.
tensor.get_shape()
只有tensor有这个方法, 返回是一个tuple
tf.shape(xxx) 和 xxx.get_shape()比较
- 相同点:都可以得到tensor xxx 的尺寸
- 不同点:tf.shape(xxx)中xxx数据的类型可以是tensor,list,array;而xxx.get_shape()中的xxx的数据类型必须是tensor,且返回的是一个tuple.可以通过xxx.get_shape().as_list()得到一个list。
例如:
x= tf.truncated_normal([32, 32, 3], dtype=tf.float32)
print(tf.shape(x))
print(x.get_shape())
print(x.get_shape().as_list())
- 1
- 2
- 3
- 4
- 5
输出:
Tensor("Shape:0", shape=(3,), dtype=int32)
(32, 32, 3)
[32, 32, 3]
- 1
- 2
- 3
注意:dtype=int32是tf.shape()这个op的输出类型,默认为tf.int32。