Broadcasting
本质上
是一个张量的维度的扩张手段,它是指对某一个维度上面重复N多次,但是却没有真正的复制数据,但是却呈现出数据被扩张了。
机制:
- expand
- without copying data
- VS tf.tile
- tf.broadcast_to
举例:
Feature maps: [4, 32, 32, 3]
▪ Bias: [3] → [1, 1, 1, 32] → [4, 32, 32, 3]
如何理解??
When it has no axis 如果没有这一个维度
▪ Create a new concept 创建一个新的概念
▪ [classes, students, scores] + [scores]
When it has dim of size 1 当存在dim=1的维度**
▪ Treat it shared by all 1的维度是对每一个维度适用的
▪ [classes, students, scores] + [students, 1]
为什么要做boardcasting?
-
实际上存在这种需求
▪ [classes, students, scores]
▪ 给所有学生加 5 分
▪ [4, 32, 8] + [4, 32, 8]
▪ [4, 32, 8] + [5.0] -
减少内存空间
▪ [4, 32, 8] → 1024
▪ bias=[8]: [5.0,5.0,5.0,…] → 8
是否能够broadcast?
▪ 如果当前 dim=1, 扩张
▪ 如果相应位置上没有维度, 插入一个维度(shape 是 1),扩张成相同的维度
▪ 否则不能扩张
例如:
[4, 32, 14, 14]
[1, 32, 1, 1] → [4, 32, 14, 14]
可以扩张,[1, 32, 1, 1]可以扩张为[4, 32, 14, 14],因为维度相等,且需要扩张的地方都是1,可以扩张
[4, 32, 14, 14]
[14, 14] → [1, 1, 14, 14] → [4, 32, 14, 14]
可以扩张,[14, 14]可以扩张为[4, 32, 14, 14],因为维度不等,先给相应位置上添加维度,再扩张
▪ [4, 32, 14, 14]
▪ [2, 32, 14, 14]
不能扩张。因为维度相等,相应位置上都有维度,且不是1,
实操
import tensorflow as tf
x = tf.random.normal([4,32,32,3])
print("初始维度:",x.shape)
print("x + tf.random.normal([3]) :",(x + tf.random.normal([3])).shape)
print("x + tf.random.normal([32,32,1]): ",(x + tf.random.normal([32,32,1])).shape)
#print("x+tf.random.normal([1,4,1,1]): ",(x+tf.random.normal([1,4,1,1])))
#报错:InvalidArgumentError: Incompatible shapes: [4,32,32,3] vs. [1,4,1,1] [Op:AddV2]
#因为都是四维,axis=1的维度对应的数字为4,无法扩张为32