一、tf.shape()
獲取的是張量的大小,直接上代碼,一看便知:
#tf.shape()獲取的是張量的大小
import tensorflow as tf
import numpy as np
a_array = np.array([[1,2,3],[4,5,6]])
b_list = [[1,2,3],[4,5,6]]
c_tensor = tf.constant([[1,2,3],[4,5,6]])
with tf.Session() as sess:
print(sess.run(tf.shape(a_array)))
print(sess.run(tf.shape(b_list)))
print(sess.run(tf.shape(c_tensor)))
運行結果:
二、x.get_shape()
x.get_shape(),只有tensor纔可以使用這種方法,返回的是一個元組。
上代碼:
#只有tensor纔可以使用這種方法,返回的是一個元組
import tensorflow as tf
import numpy as np
a_array=np.array([[1,2,3],[4,5,6]])
b_list=[[1,2,3],[4,5,6]]
c_tensor=tf.constant([[1,2,3],[4,5,6]])
print(c_tensor.get_shape()) #返回的是一個元組
print(c_tensor.get_shape()[-1].value) #返回的是索引值
print(c_tensor.get_shape().as_list()) #返回的是列表
with tf.Session() as sess:
print(sess.run(tf.shape(a_array)))
print(sess.run(tf.shape(b_list)))
print(sess.run(tf.shape(c_tensor)))
運行結果:
下面強調一些注意點:
第一點:tensor.get_shape()返回的是元組,不能放到sess.run()裏面,這個裏面只能放operation和tensor;
第二點:tf.shape()返回的是一個tensor。要想知道是多少,必須通過sess.run()