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]以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林站長站。
新聞熱點
疑難解答