torch.linspace() torch.arange() torch.stack() 函数详解

1 torch.linspace函数详解

torch.linspace(start, end, steps=100, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor
函数的作用是,返回一个一维的tensor(张量),这个张量包含了从start到end,分成steps个线段得到的向量。常用的几个变量
start:开始值
end:结束值
steps:分割的点数,默认是100
dtype:返回值(张量)的数据类型

举例:

in_W = 352
feat_W16 = 22
x_stride = torch.linspace(0, in_W - 1, feat_W16, dtype=torch.float)

在这里插入图片描述

x_stride = torch.linspace(0, in_W - 1, feat_W16, dtype=torch.float).view(1, 1, feat_W16)

在这里插入图片描述

x_stride = torch.linspace(0, in_W - 1, feat_W16, dtype=torch.float).view(1, 1, feat_W16).expand(D, feat_H16, feat_W16)

[41,8,22] DHW

2 torch.arange函数详解

  • 函数原型
 arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor

在这里插入图片描述

  • 代码示例
>>> torch.arange(5)  # 默认以 0 为起点
tensor([ 0,  1,  2,  3,  4])
>>> torch.arange(1, 4)  # 默认间隔为 1
tensor([ 1,  2,  3])
>>> torch.arange(1, 2.5, 0.5)  # 指定间隔 0.5
tensor([ 1.0000,  1.5000,  2.0000])
  • 实际使用
distance = torch.arange(*self.grid_conf['dbound'], dtype=torch.float).view(-1, 1, 1).expand(-1, feat_H16, feat_W16)

3 torch.stack函数详解

  • 函数原型
    在这里插入图片描述
  • 代码示例1
  • 代码
 x = t.tensor([1,2,3,4])
 y = t.tensor([5,6,7,8])
 
 print(x.shape)
 print(y.shape)
 
 z1 = t.stack((x,y), dim=0)
 print(z1)
 print(z1.shape)
 
 z2 = t.stack((x,y), dim=1)
 print(z2)
 print(z2.shape)
  • 运行结果
torch.Size([4])
torch.Size([4])

tensor([[1, 2, 3, 4],
        [5, 6, 7, 8]])
torch.Size([2, 4])

tensor([[1, 5],
        [2, 6],
        [3, 7],
        [4, 8]])
torch.Size([4, 2])
  • 图解
    在这里插入图片描述
  • 代码示例2
  • 代码
 x = t.tensor([[1,2,3],[4,5,6]])
 y = t.tensor([[7,8,9],[10,11,12]])
 print(x.shape)
 print(y.shape)

 z1 = t.stack((x,y), dim=0)
 print(z1)
 print(z1.shape)

 z2 = t.stack((x,y), dim=1)
 print(z2)
 print(z2.shape)

 z3 = t.stack((x,y), dim=2)
 print(z3)
 print(z3.shape)
  • 运行结果
torch.Size([2, 3])
torch.Size([2, 3])

tensor([[[ 1,  2,  3],
         [ 4,  5,  6]],

        [[ 7,  8,  9],
         [10, 11, 12]]])
torch.Size([2, 2, 3])

tensor([[[ 1,  2,  3],
         [ 7,  8,  9]],

        [[ 4,  5,  6],
         [10, 11, 12]]])
torch.Size([2, 2, 3])

tensor([[[ 1,  7],
         [ 2,  8],
         [ 3,  9]],

        [[ 4, 10],
         [ 5, 11],
         [ 6, 12]]])
torch.Size([2, 3, 2])
  • 图解
    在这里插入图片描述

  • 实际使用

        # 创建视锥
        # [41,8,22,3]
        frustum = torch.stack((x_stride, y_stride, distance), -1)
        # 不计算梯度,不需要学习
        return nn.Parameter(frustum, requires_grad=False)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BILLY BILLY

你的奖励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值