Pytorch 大杂烩
tensor
flip
对某一个维度进行反转: 1
torch.flip(input,dims)
dims是一个list or tuple
1 | t=torch.LongTensor([[2,3,4],[5,6,7],[1,2,3]]) |
输出 1
2
3tensor([[2, 3, 4],
[5, 6, 7],
[1, 2, 3]])1
2t=torch.flip(t,dims=(1,))
print(t)1
2
3tensor([[4, 3, 2],
[7, 6, 5],
[3, 2, 1]])1
t.sum()
当然还有别的用法 1
2t=torch.LongTensor([[2,3,4],[5,6,7],[1,2,3]])
print(torch.sum(t,0))1
tensor([ 8, 11, 14])
cat
1 | torch.cat(tensors, dim=0, *, out=None) → Tensor |
其中 tensors是tuple或者list 在dim维度拼接(也就是说第dim维度的东西会增多)
1 | t1=torch.LongTensor([[2,3,4],[5,6,7],[1,2,3]]) |
输出 1
2
3tensor([[2, 3, 4, 1, 1, 4],
[5, 6, 7, 5, 1, 4],
[1, 2, 3, 1, 9, 1]])torch.cat(dim=d)后将会得到shape为\((a_1,a_2,...x_d+y_d,...a_n)\)
stack
1 | torch.stack(tensors, dim=0, *, out=None) → Tensor |
其中tensors是列表或元组,在第dim维度堆叠 1
2
3t1=torch.LongTensor([[2,3,4],[5,6,7],[1,2,3]])
t2=torch.LongTensor([[1,1,4],[5,1,4],[1,9,1]])
print(torch.stack([t1,t2],dim=1))1
2
3
4
5
6
7
8tensor([[[2, 3, 4],
[1, 1, 4]],
[[5, 6, 7],
[5, 1, 4]],
[[1, 2, 3],
[1, 9, 1]]])
堆叠的所有tensor的shape一定要一致
归纳:将\(k\)个tensor堆叠后,他们的shape将会在dim维多出一个\(k\).
Parameter
1 | torch.nn.Parameter(input_tensor) |
可以将input_tensor嵌入在模型中,成为模型的参数.