shape相关函数: tf.shape(), x.get_shape().as_list(), x.shape.as_list(), tf.set_shape()和tf.reshape()

https://blog.csdn.net/gqixf/article/details/82769174
https://blog.csdn.net/ch1209498273/article/details/78773421
x.get_shape().as_list(): x必须为tensor, get_shape(), 返回tuple, 用as_list()转换为list
x.shape.as_list():x必须为tensor, x.shape()返回tuple
tf.shape():是一个op, 必须sess.run, 返回list,
tf.set_shape(): 更新tensor的 static shape,不改变dynamic shape。
tf.reshape(): 创建一个具备不同 dynamic shape的新的tensor.

在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 的样例如下所示:

[python]  view plain  copy
  1. x = tf.placeholder(tf.int32, shape = [4])  
  2. print(x.get_shape())  
  3. # ==> '(4,)'  

     get_shape() 返回了x 的静态类型,4指代 x 是一个长度为 4 的向量。

需要注意的是,get_shape()不需要放在Session中即可运行。

tf.shape() 与get_shape() 不同,示例如下所示:

[python]  view plain  copy
  1. y, _ = tf.unique(x)  
  2. print(y.get_shape())  
  3. # ==> '(?, )'  
  4. sess = tf.Session()  
  5. print(sess.run(y, feed_dict = {x: [0123]}).shape)  
  6. #==> '(4, )'  
  7. print(sess.run(y, feed_dict = {x: [0000]}).shape)  
  8. #==> '(1, )'  

通过这两个示例就可以看出两种shape方法的不同之处,需要注意的是tf.shape()需要在session中运行。


2. 区分 x.set_shape() 和 tf.reshape()

set_shape更新tensor的 static shape,不改变 dynamic shape。reshape 创建一个具备不同 dynamic shape 的新的tensor.


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值