aibiology

Artificial intelligence in biology

0%

Pytorch实操

pytorch,深度学习流行的框架之一,Facebook开发维护,社区活跃度高。

1.pytorch维度转化相关

1.1 permute vs transpose

词义是重新排列,改变次序的意思,在pytorch中主要用来实现tensor的维度转换。

pytorch官方的解释如下:

1
2
3
4
$ permute(*dims) → Tensor
$ Returns a view of the original tensor with its dimensions permuted.
$ Parameters
$ *dims (int...) – The desired ordering of dimensions

Example

1
2
3
4
5
>>> x = torch.randn(1, 2, 3, 5)
>>> x.size()
torch.Size([1, 2, 3, 5])
>>> x.permute(3, 2, 0, 1).size()
torch.Size([5, 3, 1, 2])
Tensor.permute(a,b,c,d, ...):permute函数可以对任意高维矩阵进行转置; 但没有 torch.permute() 这个调用方式,只能 Tensor.permute();

torch.transpose(Tensor, a,b):transpose只能操作2D矩阵的转置, 但是多次的2D转换的结果和permute的一致。

1
2
3
4
5
6
>>> torch.randn(1,2,3,5).transpose(2,0).shape
torch.Size([3, 2, 1, 5])
>>> torch.randn(1,2,3,5).transpose(2,0).transpose(3,0)
torch.Size([5, 2, 1, 3])
>>> torch.randn(1,2,3,5).transpose(2,0).transpose(3,0).transpose(3,1)
torch.Size([5, 3, 1, 2])
总结,复杂的转换可以使用permute,简答的2D转换用transpose。

1.2 view

改变tensor的形状,但是和permute和transpose不同; 参数中的-1就代表这个位置由其他位置的数字来推断;

pytorch的官方解释如下: Returns a new tensor with the same data as the self tensor but of a different shape.

1
2
3
$ view(*shape) → Tensor
$ Parameters
$ shape (torch.Size or int...) – the desired size
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>>> x = torch.randn(4, 4)
>>> x.size()
torch.Size([4, 4])
>>> y = x.view(16)
>>> y.size()
torch.Size([16])
>>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions
>>> z.size()
torch.Size([2, 8])

>>> a = torch.randn(1, 2, 3, 4)
>>> a.size()
torch.Size([1, 2, 3, 4])
>>> b = a.transpose(1, 2) # Swaps 2nd and 3rd dimension
>>> b.size()
torch.Size([1, 3, 2, 4])
>>> c = a.view(1, 3, 2, 4) # Does not change tensor layout in memory
>>> c.size()
torch.Size([1, 3, 2, 4])
>>> torch.equal(b, c)
False