Pyorch基础(三)

Pyorch基础(三)

broadcasting(广播机制)

broadcasting是把tensor自动扩张,比如在不同维度的tensor相加的时候,就会先利用broadcasting机制将两个tensor扩充为相同维度,再进行相加。

合并与分割

  • cat

将多个tensor按指定维度进行合并

合并的维度可以不同,但其他维度必须相同

a = torch.rand(4,32,8)
b = torch.rand(5,32,8)
c = torch.cat([a,b],dim=0)
print(c.shape) # torch.Size([9,32,8])
  • stack

将多个tensor进行合并。但与cat不同,stack会在指定维度的前面插入一个新的维度,这个新的维度会区分合并前的那些tensor

与cat不同,进行stack的两个tensor维度必须完全一致

a = torch.rand(32, 8)
b = torch.rand(32, 8)
c = torch.stack([a, b], dim=0)
print(c.shape) # torch.Size([2,32,8])
  • split

split是按照某个维度,规定步长来拆分

规定的步长必须正好把原先的tensor拆完,不多不少

c = torch.rand(2, 32, 8)
a, b = d.split(1, dim=0) # 按照固定的步长1
print(a.shape) # torch.Size([1,32,8])
print(b.shape) # torch.Size([1,32,8])

d = torch.rand(6, 32, 8)
a, b, c = c.split([1, 2 ,3], dim=0) # 按照1,2,3的数量拆分第一个维度(第一个维度有6个通道)
print(a.shape) # torch.Size([1,32,8])
print(b.shape) # torch.Size([2,32,8])
print(c.shape) # torch.Size([3,32,8])
  • chunk

与split不同,chunk是按照拆分的数量来进行划分(平均分)

c = torch.rand(6, 32, 8)
a, b = torch.chunk(2,dim=0)
print(a.shape) # torch.Size([3,32,8])
print(b.shape) # torch.Size([3,32,8])

Tensor的基本运算

  • add/minus/multioly/divide
  • 加法:a + btorch,add(a, b)

    不同的维度的tensor是可以直接相加的,因为pytorch有broadcasting机制

  • 减法:a - btorch.sub(a, b)

  • matmul
  • 点乘:a * btorch.mul(a, b)
  • 叉乘:a @ btorch.matmul(a, b) (troch.mm也是叉乘,但仅在2维下使用)

2维以上矩阵的叉乘只取最后两维做矩阵的叉乘运算,其他的维度维持不变

乘法运算也可以使用broadcasting机制

a = torch.tensor([[1,2],
            [3,4]])
b = torch.tensor([[5,6],
            [7,8]])
print(a * b)
# out:
# tensor([[ 5, 12],
#         [21, 32]])
print(torch.mul(a,b))
# out:
# tensor([[ 5, 12],
#         [21, 32]])
print(torch.matmul(a,b))
# out:
# tensor([[19, 22],
#         [43, 50]])
print(a @ b)
# out:
# tensor([[19, 22],
#         [43, 50]])
  • 除法:a / btorch.div(a, b)
  • pow

乘方:a ** ba.pow(3)

  • sqrt/rsqrt
  • sqrt()平方根
  • rsqrt()平方跟的导数
  • 近似
  • .floor()向下取整
  • .ceil()向上取整
  • .trunc()整数部分
  • .frac()小数部分
  • .round()四舍五入
  • clamp

clamp(min,max)裁剪到min到max之间,如果只传入一个参数的话,默认为min

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值