您的位置:首页 > 其它

【TensorFlow】tf中关于shape的问题汇总

2017-05-08 13:01 274 查看
在TensorFlow中,涉及到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中即可运行。

tf.shape() 与get_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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: