基於tf.shape(tensor)和tensor.shape()的區別說明
阿新 • • 發佈:2020-07-01
#tf.shape(tensor)和tensor.shape()的區別
a=tf.zeros([4,5,4,6]) print(type(a.shape)) print(a.shape.ndims)#多少個維度 print(a.shape.as_list())#返回列表 print(type(tf.shape(a))) print(type(tf.shape(a)[0])) b=a.shape.as_list() c=tf.shape(a) b[1]=tf.shape(a)[1] print(b) sess=tf.Session() d=sess.run(c) print(d)
outputs: <class 'tensorflow.python.framework.tensor_shape.TensorShape'> 5 [4,6] <class 'tensorflow.python.framework.ops.Tensor'> <class 'tensorflow.python.framework.ops.Tensor'> [4,<tf.Tensor 'strided_slice_1:0' shape=() dtype=int32>,6] [4 5 4 5 6]
其中tf.shape(tensor)使用的是動態的,即必須要在session中執行後才能顯示出來,但是tensor.shape()是靜態的,即通過定義的shape可以驚天的執行出來。
原因:在我們定義的時候,比如進行placeholder的時候我們可能會定義某些維度為None,在靜態的時候是看不出來的,只能在執行的時候找到維度。
**使用:**可以在獲得某些tensor的維度的時候進行檢驗,防止維度為None。
補充知識:tensorflow.python.framework.tensor_shape.TensorShape 類
TensorShape 是tensorflow中關於張量shape的類(class).
使用示例如下:
import tensorflow.compat.v1 as tf from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import constant_op tensor_test1=[10,10,10] tensor_test2 = [None,10] p1 = tensor_shape.as_shape(tensor_test1) # 得到的是一個類例項,該類例項包含一個屬性,是 tensor_test1 的value const = constant_op.constant(p1.as_list()) print("type(p1) = ",type(p1)) print("p1 = ",p1) # 使用p1時會自動呼叫p1中的value屬性 print("p1.is_fully_defined() = ",p1.is_fully_defined())# is_fully_defined 是 TensorShape 類的一個內部函式 print("p1.ndims = ",p1.ndims) # ndims 也是TensorShape的一個屬性值 print("p1.as_list() = ",p1.as_list()) # 把TensorShape的value屬性轉換成python中的list型別 print("const = ",const)
結果如下:
type(p1) = <class 'tensorflow.python.framework.tensor_shape.TensorShape'> p1 = (10,10) p1.is_fully_defined() = True p1.ndims = 3 p1.as_list() = [10,10] const = Tensor("Const:0",shape=(3,),dtype=int32)
以上這篇基於tf.shape(tensor)和tensor.shape()的區別說明就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。