tensorflow擷取變數維度資訊,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變數中擷取具體維度數值的方法
# 直接擷取TensorShape變數的第i個維度值x.shape[i].valuex.get_shape()[i].value# 將TensorShape變數轉化為list類型,然後直接按照索引取值x.get_shape().as_list()
下面給出全部的樣本程式:
import tensorflow as tfx1 = 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: 2tf.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]: 2Within session, tf.shape(x1): [2 3]
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。