TensorFlow2.0 Broadcast 與 數學操作

TensorFlow2.0 Broadcast 與 數學操作

import tensorflow as tf
import numpy as np
print(tf.__version__)
x = tf.random.normal([4, 32, 32, 3])
# 使用+號 直接隱式調用 broadcast  右邊對齊,1或相等shape纔可以
print((x + tf.random.normal([3])).shape)
print((x + tf.random.normal([32, 32, 1])).shape)
print((x + tf.random.normal([4, 1, 1, 1])).shape)

# 出現錯誤
# print((x + tf.random.normal([1, 4, 1, 1])).shape)

在這裏插入圖片描述

# 顯示調用  broadcast
b = tf.broadcast_to(tf.random.normal([4, 1, 1,1]), [4, 32, 32, 3])
print(b.shape)

在這裏插入圖片描述

# broadcast 與 tile
# broadcast 並非真實創建內存空間,節省內存空間
# tile真實創建內存空間 
a = tf.ones([3, 4])
a1 = tf.broadcast_to(a, [2, 3, 4])
print(a1)

a2 = tf.expand_dims(a, axis=0)
a2 = tf.tile(a2, [2, 1, 1])
print(a2)

在這裏插入圖片描述

數學操作

Log計算

a = tf.fill([2, 2], 2.0)
b = tf.ones([2, 2])

# log  e爲底
print(tf.math.log(b))
print(tf.exp(b))

# log 2爲底
print(tf.math.log(8.0) / tf.math.log(2.0))
# log 10爲底
print(tf.math.log(100.0) / tf.math.log(10.0))

在這裏插入圖片描述

矩陣相乘 最後2個維度需要銜接
即 [4,2,3] 與[4, 3, 5] 對應
即 [4,2] 與[2, 1] 對應

# 矩陣相乘
print(tf.matmul(b,a))
print(b@a)

a = tf.ones([4, 2, 3])
b = tf.fill([4, 3, 5], 2.0)
print(a @ b)

# Y = X @ W + b
x = tf.ones([4, 2])
W = tf.ones([2, 1])
b = tf.constant(0.1)
Y = x@W + b
print(Y)

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章