例子1
import torch
T = torch.tensor([1,2,3])
print("T's shape: ",T.shape,"\n")
print("T: ",T,"\n")
print("T.repeat(2,2): \n", T.repeat(2,2),"\n")
print("T.repeat(1,5): \n", T.repeat(1,5),"\n")
输出:
关注:T.repeat(1,5)
T's shape: torch.Size([3])
T: tensor([1, 2, 3])
T.repeat(2,2):
tensor([[1, 2, 3, 1, 2, 3],
[1, 2, 3, 1, 2, 3]])
T.repeat(1,5):
tensor([[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]])
例子2
注意:
gt_depth.reshape(-1, 1)
gt_depth = gt_depth.repeat(1, N_samples)
import torch
N_samples = 4
gt_depth = torch.tensor([[1,2,3],[4,5,6]])
print(gt_depth.shape)
print(gt_depth,"\n")
gt_depth = gt_depth.reshape(-1, 1)
print(gt_depth.shape)
print(gt_depth,"\n")
gt_depth = gt_depth.repeat(1, N_samples)
print(gt_depth.shape)
print(gt_depth,"\n")
torch.Size([2, 3])
tensor([[1, 2, 3],
[4, 5, 6]])
torch.Size([6, 1])
tensor([[1],
[2],
[3],
[4],
[5],
[6]])
torch.Size([6, 4])
tensor([[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4],
[5, 5, 5, 5],
[6, 6, 6, 6]])
例子3
N = 4
t = torch.linspace(4,8,N)
print(t.shape)
print(t)
t = t.unsqueeze(0).repeat(N)
输出:
t = t.unsqueeze(0).repeat(N)
RuntimeError: Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor
因为 t = t.unsqueeze(0)
的shape是
[
1
,
N
]
[1,N]
[1,N],有两个dim。而 .repeat(N)
只有1个dim。
例子4
在一条直线上采样若干个点,输出其坐标
import torch
N_Sample = 4
N_ray_d = 3
ray_o = torch.zeros(N_ray_d)
ray_d = torch.rand(N_ray_d)
print("Original ray_d: ",ray_d)
ray_d = ray_d.unsqueeze(0).repeat(N_Sample,1)
print("ray_d after repeat: ",ray_d)
sample_start = 4
sample_end = 8
t = torch.linspace(sample_start,sample_end,N_Sample)
print(t.shape)
print(t)
t = t.unsqueeze(0).reshape(-1,1).repeat(1,N_ray_d)
print(t.shape)
print(t)
point1 = ray_o+t*ray_d
print("sample point1: ",point1)
输出
Original ray_d: tensor([0.9077, 0.2101, 0.9342])
ray_d after repeat: tensor([[0.9077, 0.2101, 0.9342],
[0.9077, 0.2101, 0.9342],
[0.9077, 0.2101, 0.9342],
[0.9077, 0.2101, 0.9342]])
torch.Size([4])
tensor([4.0000, 5.3333, 6.6667, 8.0000])
torch.Size([4, 3])
tensor([[4.0000, 4.0000, 4.0000],
[5.3333, 5.3333, 5.3333],
[6.6667, 6.6667, 6.6667],
[8.0000, 8.0000, 8.0000]])
sample point1: tensor([[3.6308, 0.8404, 3.7366],
[4.8410, 1.1206, 4.9822],
[6.0513, 1.4007, 6.2277],
[7.2616, 1.6808, 7.4732]])