Pytorch基础运算
加 + 、减 - 、乘 * 、幂次 **
x = torch.tensor([1.0, 2, 4, 8])
y = torch.tensor([2, 2, 2, 2])
x + y, x - y,x * y, x / y, x ** y # **运算符是求幂级
out:
(tensor([ 3., 4., 6., 10.]),
tensor([-1., 0., 2., 6.]),
tensor([ 2., 4., 8., 16.]),
tensor([0.5000, 1.0000, 2.0000, 4.0000]),
tensor([ 1., 4., 16., 64.]))
torch.exp() 是求e的指数
torch.exp(x)
out:
tensor([2.7183e+00, 7.3891e+00, 5.4598e+01, 2.9810e+03])
torch.cat(inputs, dim = ?) 是对张量进行维度上的拼接
X = torch.arange(12, dtype = torch.float32).reshape((3,2,2))
Y = torch.tensor([[[2.0, 1],[1, 2]],[[4, 3],[1,2]],[[3.,5],[1,3]]])
torch.cat((X, Y), dim = 0), torch.cat((X, Y),dim = 1),torch.cat((X,Y), dim = 2)
dim = 0:
(tensor([[[ 0., 1.],
[ 2., 3.]],
[[ 4., 5.],
[ 6., 7.]],
[[ 8., 9.],
[10., 11.]],
[[ 2., 1.],
[ 1., 2.]],
[[ 4., 3.],
[ 1., 2.]],
[[ 3., 5.],
[ 1., 3.]]]),
dim = 1:
tensor([[[ 0., 1.],
[ 2., 3.],
[ 2., 1.],
[ 1., 2.]],
[[ 4., 5.],
[ 6., 7.],
[ 4., 3.],
[ 1., 2.]],
[[ 8., 9.],
[10., 11.],
[ 3., 5.],
[ 1., 3.]]]),
dim = 2:
tensor([[[ 0., 1., 2., 1.],
[ 2., 3., 1., 2.]],
[[ 4., 5., 4., 3.],
[ 6., 7., 1., 2.]],
[[ 8., 9., 3., 5.],
[10., 11., 1., 3.]]]))
dim的取值在0到(最大维度-1)之间,也可取负(-最大维度)至-1,其中dim = (-最大维度)等价与dim = 0。
也就是张量维度为3,dim最大可取2。正如上述代码中,因为构建的矩阵维度为三维,若dim = 3 则会报错。
以上述代码为例,dim = 0,则矩阵在第一个维度上拼接,(3,2,2)->(6,2,2);
dim = 1,则在第二个维度上拼接,(3,2,2)->(3,4,2);dim = 2,同理。
另外,即使两个矩阵的形状不同,也可通过广播机制来执行元素操作。
input:
a = torch.arange(3).reshape((3,1))
b = torch.arange(2).reshape((1,2))
a,b
out:
(tensor([[0],
[1],
[2]]),
tensor([[0, 1]]))
input:
a + b
out:
tensor([[0, 1],
[1, 2],
[2, 3]])