• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

基于tf.shape(tensor)和tensor.shape()的区别说明

python 搞代码 4年前 (2022-01-09) 31次浏览 已收录 0个评论

#tf.shape(tensor)和tensor.shape()的区别

a=tf.zeros([4,5,4,5,6])
print(type(a.shape))
print(a.shape.ndims)#多少个维度
print(a.shape.as_list())#返回列表
print(type(tf.shape(a)))
print(type(tf.shape(a)[0]))
b=a.shape.as_list()
c=tf.shape(a)
b[1]=tf.shape(a)[1]
print(b)
sess=tf.Session()
d=sess.run(c)
print(d)
outputs:
<class 'tensorflow.python.framework.tensor_shape.TensorShape'>
5
[4, 5, 4, 5, 6]
<class 'tensorflow.python.framework.ops.Tensor'>
<class 'tensorflow.python.framework.ops.Tensor'>
[4, <tf.Tensor 'strided_slice_1:0' shape=() dtype=int32>, 4, 5, 6]
[4 5 4 5 6]

其中tf.shape(tensor)使用的是动态的,即必须要在session中运行后才能显示出来,但是tensor.shape()是静态的,即通过定义的shape可以惊天的运行出来。

原因:在我们定义的时候,比如进行placeholder的时候我们可能会定义某些维度为None,在静态的时候是看不出来的,只能在运行的时候找到维度。

**使用:**可以在获得某些tensor的维度的时候进行检验,防止维度为None。

补充知识:tensorflow.python.framework.tensor_shape.TensorShape 类

TensorShape 是tensorflow中关于张量shape的类(class).

使用示例如下:

import tensorflow.compat.v1 as tf
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import constant_op
 
tensor_test1=[10,10,10]
tensor_test2 = [None,10,10]
 
p1 = tensor_shape.as_shape(tensor_test1) # 得到的是一个类实例,该类实例包含一个属性,是 tensor_test1 的value
const = constant_op.constant(p1.as_list())
 
print("type(p1) = ",type(p1))
print("p1 = ",p1) # 使用p1时会自动调用p1中的value属性
print("p1.is_fully_defined() = ",p1.is_fully_defined())# is_fully_defined 是 TensorShape 类的一个内部函数
print("p1.ndims = ",p1.ndims) # ndims 也是TensorShape的一个属性值
print("p1.as_list() = ",p1.as_list()) # 把TensorSh<b style="color:transparent">来&源gao@dai!ma.com搞$代^码%网</b>ape的value属性转换成python中的list类型
print("const = ",const)

结果如下:

type(p1) = <class 'tensorflow.python.framework.tensor_shape.TensorShape'>
p1 = (10, 10, 10)
p1.is_fully_defined() = True
p1.ndims = 3
p1.as_list() = [10, 10, 10]
const = Tensor("Const:0", shape=(3,), dtype=int32)

以上这篇基于tf.shape(tensor)和tensor.shape()的区别说明就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:基于tf.shape(tensor)和tensor.shape()的区别说明

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址