tf.Tensor 表示元素的多維數組。
用法
tf.Tensor(
op, value_index, dtype
)參數
-
op一個Operation。Operation計算這個張量。 -
value_index一個int。產生此張量的操作端點的索引。 -
dtype一個DType。存儲在此張量中的元素類型。
拋出
-
TypeError如果操作不是Operation。
屬性
-
device將在其上生成此張量的設備的名稱,或無。 -
dtype該張量中元素的DType。 -
graph包含此張量的Graph。 -
name這個張量的字符串名稱。 -
opOperation產生這個張量作為輸出。 -
shape返回一個tf.TensorShape表示這個張量的形狀。t = tf.constant([1,2,3,4,5]) t.shape TensorShape([5])tf.Tensor.shape等同於tf.Tensor.get_shape()。在
tf.function或使用tf.keras.Input構建模型時,它們返回張量的 build-time 形狀,這可能部分未知。tf.TensorShape不是張量。使用tf.shape(t)獲取包含形狀的張量,在運行時計算。有關詳細信息和示例,請參閱
tf.Tensor.get_shape()和tf.TensorShape。 -
value_index該張量在其Operation的輸出中的索引。
所有元素都是單一的已知數據類型。
在編寫 TensorFlow 程序時,操作和傳遞的主要對象是 tf.Tensor 。
tf.Tensor 具有以下屬性:
- 單一數據類型(例如,float32、int32 或字符串)
- 一個形狀
TensorFlow 支持即刻執行和圖執行。在即刻執行中,會立即評估操作。在圖執行中,構建計算圖以供以後評估。
TensorFlow 默認為即刻執行。在下麵的示例中,立即計算矩陣乘法結果。
# Compute some values using a Tensor
c = tf.constant([[1.0, 2.0], [3.0, 4.0]])
d = tf.constant([[1.0, 1.0], [0.0, 1.0]])
e = tf.matmul(c, d)
print(e)
tf.Tensor(
[[1. 3.]
[3. 7.]], shape=(2, 2), dtype=float32)
請注意,在即刻執行期間,您可能會發現您的 Tensors 實際上屬於 EagerTensor 類型。這是一個內部細節,但它確實讓您可以訪問一個有用的函數 numpy :
type(e)
<class '...ops.EagerTensor'>
print(e.numpy())
[[1. 3.]
[3. 7.]]
在 TensorFlow 中,tf.function 是定義圖執行的常用方法。
張量的形狀(即張量的秩和每個維度的大小)可能並不總是完全已知的。在tf.function 定義中,形狀可能隻是部分已知的。
如果輸入的形狀也完全已知,則大多數操作會產生 fully-known 形狀的張量,但在某些情況下,隻能在執行時找到張量的形狀。
許多專用張量可用:參見 tf.Variable 、 tf.constant 、 tf.placeholder 、 tf.sparse.SparseTensor 和 tf.RaggedTensor 。
警告:從 numpy 數組或 pandas 數據幀構造張量時,可以重用底層緩衝區:
a = np.array([1, 2, 3])
b = tf.constant(a)
a[0] = 4
print(b) # tf.Tensor([4 2 3], shape=(3,), dtype=int64)注意:這是一個可能會更改的實現細節,用戶不應依賴此行為。
有關張量的更多信息,請參閱指南。
相關用法
- Python tf.Tensor.__rsub__用法及代碼示例
- Python tf.TensorSpec.from_spec用法及代碼示例
- Python tf.Tensor.__lt__用法及代碼示例
- Python tf.Tensor.set_shape用法及代碼示例
- Python tf.Tensor.__abs__用法及代碼示例
- Python tf.Tensor.ref用法及代碼示例
- Python tf.Tensor.__getitem__用法及代碼示例
- Python tf.Tensor.__ge__用法及代碼示例
- Python tf.TensorSpec.from_tensor用法及代碼示例
- Python tf.TensorShape.merge_with用法及代碼示例
- Python tf.TensorArray用法及代碼示例
- Python tf.Tensor.__rmatmul__用法及代碼示例
- Python tf.TensorShape.__eq__用法及代碼示例
- Python tf.Tensor.__bool__用法及代碼示例
- Python tf.Tensor.get_shape用法及代碼示例
- Python tf.Tensor.__xor__用法及代碼示例
- Python tf.Tensor.__sub__用法及代碼示例
- Python tf.Tensor.__rpow__用法及代碼示例
- Python tf.Tensor.__gt__用法及代碼示例
- Python tf.Tensor.__le__用法及代碼示例
注:本文由純淨天空篩選整理自tensorflow.org大神的英文原創作品 tf.Tensor。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
