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)