目錄python
[32]
[1,1,1,32]dom
[4,16,16,32]ide
Broadcasting能夠理解成把維度分紅大維度和小維度,小維度較爲具體,大維度更加抽象。也就是小維度針對某個示例,而後讓這個示例通用語大維度。idea
import tensorflow as tf
x = tf.random.normal([4,32,32,3]) x.shape
TensorShape([4, 32, 32, 3])
(x+tf.random.normal([3])).shape
TensorShape([4, 32, 32, 3])
(x+tf.random.normal([32,32,1])).shape
TensorShape([4, 32, 32, 3])
(x+tf.random.normal([4,1,1,1])).shape
TensorShape([4, 32, 32, 3])
try: (x+tf.random.normal([1,4,1,1])).shape except Exception as e: print(e)
Incompatible shapes: [4,32,32,3] vs. [1,4,1,1] [Op:Add] name: add/
(x+tf.random.normal([4,1,1,1])).shape
TensorShape([4, 32, 32, 3])
b = tf.broadcast_to(tf.random.normal([4,1,1,1]),[4,32,32,3])
b.shape
TensorShape([4, 32, 32, 3])
a = tf.ones([3,4])
a.shape
TensorShape([3, 4])
a1 = tf.broadcast_to(a,[2,3,4])
a1.shape
TensorShape([2, 3, 4])
a2 = tf.expand_dims(a,axis=0) # 0前插入一維
a2.shape
TensorShape([1, 3, 4])
a2 = tf.tile(a2,[2,1,1]) # 複製一維2次,複製2、三維1次
a2.shape
TensorShape([2, 3, 4])