目录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])