溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

tf.shape和tensor.shape()的區(qū)別是什么

發(fā)布時間:2020-07-01 10:39:11 來源:腳本之家 閱讀:418 作者:清晨 欄目:開發(fā)技術(shù)

tf.shape(tensor)和tensor.shape()的區(qū)別

a=tf.zeros([4,5,4,5,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, 5, 4, 5, 6]
<class 'tensorflow.python.framework.ops.Tensor'>
<class 'tensorflow.python.framework.ops.Tensor'>
[4, <tf.Tensor 'strided_slice_1:0' shape=() dtype=int32>, 4, 5, 6]
[4 5 4 5 6]

其中tf.shape(tensor)使用的是動態(tài)的,即必須要在session中運行后才能顯示出來,但是tensor.shape()是靜態(tài)的,即通過定義的shape可以驚天的運行出來。

原因:在我們定義的時候,比如進(jìn)行placeholder的時候我們可能會定義某些維度為None,在靜態(tài)的時候是看不出來的,只能在運行的時候找到維度。

**使用:**可以在獲得某些tensor的維度的時候進(jìn)行檢驗,防止維度為None。

補充知識:tensorflow.python.framework.tensor_shape.TensorShape 類

TensorShape 是tensorflow中關(guān)于張量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,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時會自動調(diào)用p1中的value屬性
print("p1.is_fully_defined() = ",p1.is_fully_defined())# is_fully_defined 是 TensorShape 類的一個內(nèi)部函數(shù)
print("p1.ndims = ",p1.ndims) # ndims 也是TensorShape的一個屬性值
print("p1.as_list() = ",p1.as_list()) # 把TensorShape的value屬性轉(zhuǎn)換成python中的list類型
print("const = ",const)

結(jié)果如下:

type(p1) = <class 'tensorflow.python.framework.tensor_shape.TensorShape'>
p1 = (10, 10, 10)
p1.is_fully_defined() = True
p1.ndims = 3
p1.as_list() = [10, 10, 10]
const = Tensor("Const:0", shape=(3,), dtype=int32)

以上這篇基于tf.shape(tensor)和tensor.shape()的區(qū)別說明就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI