tensorflow版本1.4
獲取變量維度是一個(gè)使用頻繁的操作,在tensorflow中獲取變量維度主要用到的操作有以下三種:
對(duì)上面三種操作做一下簡(jiǎn)單分析:(這三種操作先記作A、B、C)
A 和 B 基本一樣,只不過(guò)前者是Tensor的屬性變量,后者是Tensor的函數(shù)。
A 和 B 均返回TensorShape類型,而 C 返回一個(gè)1D的out_type類型的Tensor。
A 和 B 可以在任意位置使用,而 C 必須在Session中使用。
A 和 B 獲取的是靜態(tài)shape,可以返回不完整的shape; C 獲取的是動(dòng)態(tài)的shape,必須是完整的shape。
另外,補(bǔ)充從TenaorShape變量中獲取具體維度數(shù)值的方法
# 直接獲取TensorShape變量的第i個(gè)維度值x.shape[i].valuex.get_shape()[i].value# 將TensorShape變量轉(zhuǎn)化為list類型,然后直接按照索引取值x.get_shape().as_list()
下面給出全部的示例程序:
import tensorflow as tfx1 = tf.constant([[1,2,3],[4,5,6]])# 占位符創(chuàng)建變量,第一個(gè)維度初始化為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未進(jìn)行完整的變量填充,其維度不完整,因此執(zhí)行下面的命令將會(huì)報(bào)錯(cuò) # print('Within session, tf.shape(x2):',sess.run(shapeOP2)) # 此命令將會(huì)報(bào)錯(cuò)輸出結(jié)果為:
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]以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選