美文网首页
Tensorflow中shape的理解

Tensorflow中shape的理解

作者: D_Major | 来源:发表于2019-03-05 15:27 被阅读0次

参考https://www.jianshu.com/p/00e537e3deec
Tensorflow中的shape应该怎么理解,怎么记住呢?

x = tf.placeholder(tf.float32, shape=[1,2,3] )

以上面这段代码为例为例。
首先,单看[1,2,3],这是1维的,但它作为shape时,代表要传入的数据必须是个3维的,这点首先要明白,自己理解一下。
Tensorflow和numpy一样,读shape时应该从外向内读。
先举个例子:

[[1,2,3], [4,5,6]]

 [[1,2,3],
  [4,5,6]]

是一样的,都是2行3列(shape=[2,3])。应该怎么记呢?
这个矩阵,先拿掉最外层中括号,变成[1,2,3], [4,5,6],[1,2,3]和 [4,5,6]被逗号隔开成2块,理解为有2个元素,每个元素(如[1,2,3])拿掉中括号后,剩下1、2和3被逗号隔开,理解为有3个元素,所以是shape=[2,3]。
再换个例子,如果shape=[1,1,1],那它会接收什么样的数据?我们根据规则,第1个数字为“1”表示最外层的元素个数只有1个。
[a]
第二层的数字为“1”表示拿掉一次括号后,剩下的仍然只有1个元素.
[ [a] ]
相应的,第3个“1”表示再拿掉一次括号后还是只剩1个元素
[ [ [a] ] ]就是结果。
shape = [1,1,2]表示数据应该是这样的:[[[a,b]]]。
回到最开始,x应该输入的是[[[a,b,c],[d,e,f]]]这样格式的, 即shape=[1, 2, 3]。

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。

参考(https://blog.csdn.net/weixin_40395922/article/details/81708532)

相关文章

网友评论

      本文标题:Tensorflow中shape的理解

      本文链接:https://www.haomeiwen.com/subject/sqqouqtx.html