Torch.norm
参数:
input(Tensor)
– 输入张量
p(float)
– 范数计算中的幂指数值
dim(int)
– 缩减的维度
out(Tensor, optional)
– 结果张量
keepdim(bool)
– 保持输出的维度 (此参数官方文档中未给出,但是很常用)
- dim指定操作的维度;-1一般指最后一维
a = torch.tensor([[1, 2, 3, 4],
[1, 2, 3, 4]]).float() #norm仅支持floatTensor,a是一个2*4的Tensor
a0 = torch.norm(a,p=2,dim=0) #按0维度求2范数
a1 = torch.norm(a,p=2,dim=1) #按1维度求2范数
print(a0)
print(a1)
Out:
tensor([1.4142, 2.8284, 4.2426, 5.6569])
tensor([5.4772, 5.4772])
- keepdim指定是否维持维度
a = torch.rand((2,3,4))
at = torch.norm(a,p=2,dim=1,keepdim=True) #保持维度
af = torch.norm(a,p=2,dim=1,keepdim=False) #不保持维度
print(a.shape)
print(at.shape)
print(af.shape)
Out:
torch.Size([2, 3, 4])
torch.Size([2, 1, 4])
torch.Size([2, 4])
permute
参考
该方法用于将tensor的维度进行换位
参数:
dims
– 原张量中的维度索引
a = torch.tensor(
[[[1., 2., 3.],
[4., 5., 6.]]])
a = a.permute(0, 2, 1)
print(a)
print(a.size())
Out:
tensor([[[1., 4.],
[2., 5.],
[3., 6.]]])
torch.Size([1, 3, 2])
gather
gather的操作理解比较复杂
参考
gather的参数如下:
input (Tensor)
– 输入张量
dim (int)
– 进行操作的维度
index (LongTensor)
– 进行操作的索引下标
out (Tensor, optional)
– 目标向量
Ex:
inputs = torch.Tensor([[1,2,3],[4,5,6]])
Out:
tensor([[1., 2., 3.],
[4., 5., 6.]])
gather操作
index_1 = torch.LongTensor([[0,1],[2,0]])
index_2 = torch.LongTensor([[0,1,1],[0,0,0]])
a = torch.gather(inputs, dim=1, index=index_1)
b = torch.gather(inputs, dim=0, index=index_2)
Out:
# a
tensor([[1., 2.],
[6., 4.]])
# b
tensor([[1., 5., 6.],
[1., 2., 3.]])
解释
dim
指定的是index分配的维度
如a的产生中,首先将dim=1上填充index_1
[ ,0] [ ,1]
[ ,2] [ ,0]
再分别将对应的dim=0上的坐标按原矩阵的维度进行填充
[0,0] [0,1]
[1,2] [1,0]
即得到
[1, 2]
[6, 4]
根据索引数组取值
参考
比如给定一个矩阵
tensor([[1., 2., 3.],
[4., 5., 6.]])
我们想根据索引数组取其[0,0],[1,1],[0,2]位置的元素
类似tf.gather_nd
row_index = [0, 1, 0]
col_index = [0, 1, 2]
a = inputs[[row_index, col_index]]
Out:
tensor([1., 5., 3.])
arange
a = torch.arange(1,6)
print(a.dtype)
Out:
# a
tensor([1, 2, 3, 4, 5])
torch.int64
矩阵乘法
torch.mul
按位相乘,可以广播
a: tensor([[ 1.8351, 2.1536],
[-0.8320, -1.4578]])
b: tensor([[2.9355, 0.3450],
[0.5708, 1.9957]])
c = torch.mul(a,b)
c: tensor([[ 5.3869, 0.7429],
[-0.4749, -2.9093]])
torch.mm
处理二维矩阵的乘法,而且也只能处理二维矩阵
mat1 = torch.randn(2, 3)
mat2 = torch.randn(3, 3)
torch.mm(mat1, mat2)
tensor([[ 0.4851, 0.5037, -0.3633],
[-0.0760, -3.6705, 2.4784]])
torch.bmm
可以进行batch维度上的计算,但不能进行广播
a = torch.randn(8,20,30)
b = torch.randn(8,30,50)
out = torch.bmm(a,b)
torch.Size([8, 20, 50])
torch.matmul
适用性最多的,能处理batch、广播的矩阵
nn.MaxPool1d
对形如(N, C, L_in)的张量,求第二维上固定窗口的最大向量,产生(N, C, L_out)
- 两个主要参数
- kernel_size
- stride,默认与kernel_size相同
# input torch.Size([1, 4, 3])
tensor([[[-7.0000, -0.2000, -1.0000],
[ 0.8000, -0.3000, 0.2000],
[ 0.2000, -0.1000, 0.4000],
[ 0.4000, -0.4000, 0.8000]]], dtype=torch.float64)
m=nn.MaxPool1d(2, stride=1)
m(input)
# torch.Size([1, 4, 2])
tensor([[[-0.2000, -0.2000],
[ 0.8000, 0.2000],
[ 0.2000, 0.4000],
[ 0.4000, 0.8000]]], dtype=torch.float64)