在 TensorFlow 中,主要操作的對象是張量(tf.Tensor
)。張量表示一個多維數組,可以執行各種操作以構建和修改計算圖。以下是一些常見的 TensorFlow 張量操作:
1. 創建張量:
- 使用
tf.constant
創建常量張量。 - 使用
tf.Variable
創建可訓練的變量張量。
# 創建常量張量
tensor_a = tf.constant([[1, 2, 3],[4, 5, 6]], dtype=tf.int32)# 創建變量張量
variable_tensor = tf.Variable([1, 2, 3])
2.?數學運算:
- 加法、減法、乘法、除法等數學運算。
tensor_a = tf.constant([1, 2, 3])
tensor_b = tf.constant([4, 5, 6])# 加法
sum_tensor = tf.add(tensor_a, tensor_b)# 減法
diff_tensor = tf.subtract(tensor_a, tensor_b)# 乘法
product_tensor = tf.multiply(tensor_a, tensor_b)# 除法
quotient_tensor = tf.divide(tensor_a, tensor_b)
3. 形狀操作:
- 獲取張量的形狀、改變形狀等。
tensor = tf.constant([[1, 2, 3],[4, 5, 6]])# 獲取形狀
shape = tf.shape(tensor)# 改變形狀
reshaped_tensor = tf.reshape(tensor, shape=(3, 2))
4. 索引和切片:
- 使用索引和切片操作獲取張量的部分。
tensor = tf.constant([[1, 2, 3],[4, 5, 6]])# 獲取第一行
first_row = tensor[0, :]# 獲取第一列
first_column = tensor[:, 0]# 切片操作
sliced_tensor = tensor[:, 1:3]
5. 歸約操作:
- 對張量的元素進行歸約操作,例如求和、平均值等。
tensor = tf.constant([1, 2, 3, 4, 5])# 求和
sum_result = tf.reduce_sum(tensor)# 求平均值
mean_result = tf.reduce_mean(tensor)
參考:
https://www.tensorflow.org/api_docs/python/tf/Tensor