2.1.5 变换
变换的概念更加宽泛一点,我们这里指索引、分和合以外的tensor操作。
torch.gather:沿着某个维度对输入tensor进行变换,用法如下:
代码语言:javascript复制torch.gather(input, dim, index, *, sparse_grad=False, out=None)
下面举个例子说明下:
代码语言:javascript复制>>> cvtutorials = torch.randn(2, 2)
>>> cvtutorials
tensor([[-0.3918, -0.3979],
[-0.5268, -0.7679]])
>>> torch.gather(cvtutorials, 1, torch.tensor([[1, 0], [0, 1]]))
tensor([[-0.3979, -0.3918],
[-0.5268, -0.7679]])
>>> torch.gather(cvtutorials, 0, torch.tensor([[1, 0], [0, 1]]))
tensor([[-0.5268, -0.3979],
[-0.3918, -0.7679]])
torch.permute:返回输入tensor的一个维度层次的置换,不知道置换的概念,可以搜索下群论中的置换群的定义及置换的记号。用法如下:
代码语言:javascript复制torch.permute(input, dims)
举个例子:
代码语言:javascript复制>>> cvtutorials = torch.randn(3, 4, 5)
>>> cvtutorials.size()
torch.Size([3, 4, 5])
>>> torch.permute(cvtutorials, (2, 1, 0)).size()
torch.Size([5, 4, 3])
torch.shape: 对输入tensor的shape进行变换,这个函数在深度学习编程中经常用到,用法如下:
代码语言:javascript复制>>> cvtutorials = torch.randn(3, 4)
>>> torch.reshape(cvtutorials, (2, 6))
tensor([[ 0.3349, -1.6753, -1.9647, -1.7345, -1.5996, 0.4831],
[ 1.3172, 0.4480, -0.4297, -0.5676, 1.2655, -0.2147]])
torch.transpose: 对tensor进行变换,如果是二维tensor,也就是矩阵中的转置,用法如下:
代码语言:javascript复制torch.transpose(input, dim0, dim1)
举个例子如下:
代码语言:javascript复制>>> cvtutorials
tensor([[ 0.0692, 0.8415, 1.2454, -1.8095],
[ 0.4224, -0.3615, -1.2436, -0.8849]])
>>> torch.transpose(cvtutorials, 0, 1)
tensor([[ 0.0692, 0.4224],
[ 0.8415, -0.3615],
[ 1.2454, -1.2436],
[-1.8095, -0.8849]])
torch.tile:通过重复输入tensor的元素构造新的元素,类似matlab中的repmat,用法如下:
代码语言:javascript复制torch.tile(input, dims)
举个例子说明如下:
代码语言:javascript复制>>> cvtutorials = torch.randn(2, 4)
>>> cvtutorials
tensor([[-1.7618, 0.8413, 1.5977, 1.3316],
[ 1.1877, -0.3684, -0.0081, -0.0878]])
>>> torch.tile(cvtutorials, (1, 2))
tensor([[-1.7618, 0.8413, 1.5977, 1.3316, -1.7618, 0.8413, 1.5977, 1.3316],
[ 1.1877, -0.3684, -0.0081, -0.0878, 1.1877, -0.3684, -0.0081, -0.0878]])
>>> torch.tile(cvtutorials, (2, 1))
tensor([[-1.7618, 0.8413, 1.5977, 1.3316],
[ 1.1877, -0.3684, -0.0081, -0.0878],
[-1.7618, 0.8413, 1.5977, 1.3316],
[ 1.1877, -0.3684, -0.0081, -0.0878]])