gpt4 book ai didi

tensorflow获取变量维度信息

转载 作者:qq735679552 更新时间:2022-09-28 22:32:09 25 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章tensorflow获取变量维度信息由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

tensorflow版本1.4 。

获取变量维度是一个使用频繁的操作,在tensorflow中获取变量维度主要用到的操作有以下三种:

  • Tensor.shape
  • Tensor.get_shape()
  • tf.shape(input,name=None,out_type=tf.int32)

对上面三种操作做一下简单分析:(这三种操作先记作A、B、C) 。

A 和 B 基本一样,只不过前者是Tensor的属性变量,后者是Tensor的函数。 A 和 B 均返回TensorShape类型,而 C 返回一个1D的out_type类型的Tensor。 A 和 B 可以在任意位置使用,而 C 必须在Session中使用。 A 和 B 获取的是静态shape,可以返回不完整的shape; C 获取的是动态的shape,必须是完整的shape.

另外,补充从TenaorShape变量中获取具体维度数值的方法 。

?
1
2
3
4
5
6
# 直接获取TensorShape变量的第i个维度值
x.shape[i].value
x.get_shape()[i].value
 
# 将TensorShape变量转化为list类型,然后直接按照索引取值
x.get_shape().as_list()

下面给出全部的示例程序:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import tensorflow as tf
 
x1 = tf.constant([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]])
# 占位符创建变量,第一个维度初始化为None,表示暂不指定维度
x2 = tf.placeholder(tf.float32,[ None , 2 , 3 ])
print ( 'x1.shape:' ,x1.shape)
print ( 'x2.shape:' ,x2.shape)
print ( 'x2.shape[1].value:' ,x2.shape[ 1 ].value)
print ( 'tf.shape(x1):' ,tf.shape(x1))
print ( 'tf.shape(x2):' ,tf.shape(x2))
print ( 'x1.get_shape():' ,x1.get_shape())
print ( 'x2.get_shape():' ,x2.get_shape())
print ( 'x2.get_shape.as_list[1]:' ,x2.get_shape().as_list()[ 1 ])
shapeOP1 = tf.shape(x1)
shapeOP2 = tf.shape(x2)
with tf.Session() as sess:
  print ( 'Within session, tf.shape(x1):' ,sess.run(shapeOP1))
  # 由于x2未进行完整的变量填充,其维度不完整,因此执行下面的命令将会报错
  # print('Within session, tf.shape(x2):',sess.run(shapeOP2)) # 此命令将会报错

输出结果为:

?
1
2
3
4
5
6
7
8
9
x1.shape: ( 2 , 3 )
x2.shape: (?, 2 , 3 )
x2.shape[ 1 ].value: 2
tf.shape(x1): Tensor( "Shape:0" , shape = ( 2 ,), dtype = int32)
tf.shape(x2): Tensor( "Shape_1:0" , shape = ( 3 ,), dtype = int32)
x1.get_shape(): ( 2 , 3 )
x2.get_shape(): (?, 2 , 3 )
x2.get_shape.as_list[ 1 ]: 2
Within session, tf.shape(x1): [ 2 3 ]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我.

原文链接:http://blog.csdn.net/shuzfan/article/details/79051042 。

最后此篇关于tensorflow获取变量维度信息的文章就讲到这里了,如果你想了解更多关于tensorflow获取变量维度信息的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com