tensorflow获取变量维度信息

yipeiwu_com7年前Python基础

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变量中获取具体维度数值的方法

# 直接获取TensorShape变量的第i个维度值
x.shape[i].value
x.get_shape()[i].value

# 将TensorShape变量转化为list类型,然后直接按照索引取值
x.get_shape().as_list()

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

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)) # 此命令将会报错

输出结果为:

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]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现查找最小的k个数示例【两种解法】

本文实例讲述了Python实现查找最小的k个数。分享给大家供大家参考,具体如下: 题目描述 输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的...

将python依赖包打包成window下可执行文件bat方式

1、 打开一个记事本,将需要安装的第三方python依赖包写入文件,比如:需要安装urllib3、flask、bs4三个python库(替换成你想要安装的库,每个库之间用空格隔开),输入...

python 多个参数不为空校验方法

在实际开发中经常需要对前端传递的多个参数进行不为空校验,可以使用python提供的all()函数 if not all([arg1, arg2, arg3]): # 当 arg1,...

详解Django将秒转换为xx天xx时xx分

Django将秒转换为xx天xx时xx分,具体代码如下所示: from django.utils.translation import ngettext_lazy as _n de...

python 内置函数filter

python 内置函数filter class filter(object): """ filter(function or None, iterable) --> fil...