前言:
维度变换
目录:
- Broadcasting 流程
- broadcasting-able
- code
参考:
课时24 Broadcasting-1_哔哩哔哩_bilibili
一 Broadcasting 流程
分三步:
i broadcasting 从最后一个维度开始,进行维度对齐
ii 最前面插入一个维度
iii 最后对size =1 的维度进行expand
例1 训练集数据
batch size: 4
channel:32
width:14
height:14
train data = [4,32, 14,14]
bias = [32,1,1]
例2:如下要[4,3]列的两个矩阵相加
更简单的方式
B shape[3], 先插入一个维度[1,3] ,然后按照行repetion 4次
二 broadcasting-able
总结一下broadcasting 流程:
if current dim=1 :
expand to same
if either has no dim:
insert one dim and expand to same
other wise
not broadcasting-able
A.shape [4,32,3]
class = 4
students = 32
scores = 3[语数外]
如果需要数学分数上面加上10分
B=[0,10,0], B.shape [3]
原理:
insert dim B =[1,1,3]
expand B= [4,32,3]
C =A+B
三 Code
Pytorch通过Broadcasting(广播),能够自动实现标量B的维度的扩展,使其扩展到[2,3,2,2]这个维度,从而实现A和B的加法运算。
import torch
def broadcast():
A = torch.tensor([[8.0,9.0,1.0],
[2.0,3.0,1.0]])
print(A.shape)
B= torch.tensor([0,0,0.9])
print(B.shape)
C =A+B
print("\n broadcast \n ",C)
broadcast()