tf中几个shape问题

来源:互联网 发布:淘宝上架商品搜不到 编辑:程序博客网 时间:2024/05/30 05:41

tf中有两对方法比较容易混淆,涉及的是shape问题,在此做一些区分。
首先说明tf中tensor有两种shape,分别为static (inferred) shapedynamic (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。


参考:
http://stackoverflow.com/questions/37096225/how-to-understand-static-shape-and-dynamic-shape-in-tensorflow
https://www.tensorflow.org/programmers_guide/faq



作者:神奇的腿
链接:http://www.jianshu.com/p/2b88256ad206
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。