P4 PyTorch Broadcasting

前言:

        维度变换

目录:

  1.    Broadcasting 流程
  2.    broadcasting-able
  3.    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()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值