A = torch.arange(20, dtype=torch.float32).reshape(5,4)
A, A.T
tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[12., 13., 14., 15.],
[16., 17., 18., 19.]]),
tensor([[ 0., 4., 8., 12., 16.],
[ 1., 5., 9., 13., 17.],
[ 2., 6., 10., 14., 18.],
[ 3., 7., 11., 15., 19.]])
## 制造一个对称矩阵
B = torch.tensor([[1,2,3], [2,0,4], [3,4,5]])
B
tensor
([[1, 2, 3],
[2, 0, 4],
[3, 4, 5]])
判断:
B == B.T
tensor
([[True, True, True],
[True, True, True],
[True, True, True]])
A = torch.arange(20, dtype=torch.float32).reshape(5,4)
B = A.clone() # 通过分配新内存,将A的一个副本分配给B
A * B
a = 2
X = torch.arange(24, dtype=torch.float32).reshape(2,3,4)
X, a+X, a*X
tensor
([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]]),
tensor
([[[ 2, 3, 4, 5],
[ 6, 7, 8, 9],
[10, 11, 12, 13]],
[[14, 15, 16, 17],
[18, 19, 20, 21],
[22, 23, 24, 25]]]),
tensor
([[[ 0, 2, 4, 6],
[ 8, 10, 12, 14],
[16, 18, 20, 22]],
[[24, 26, 28, 30],
[32, 34, 36, 38],
[40, 42, 44, 46]]])
A.mean(), A.sum()/A.numel()
结果:
tensor(9.5000), tensor(9.5000)
A.mean(axis = 0), A.sum(axis=0)/A.shape[0]
结果:
tensor([ 8., 9., 10., 11.]), tensor([ 8., 9., 10., 11.]
A.shape()
torch.Size([5, 4])
A.sum(axis = 1).shape
torch.Size([5])
A.sum(axis = 1, keepdims = True).shape
torch.Size([5, 1])
A, A.cumsum(axis = 0)
tensor
([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[12., 13., 14., 15.],
[16., 17., 18., 19.]]),
tensor
([[ 0., 1., 2., 3.],
[ 4., 6., 8., 10.],
[12., 15., 18., 21.],
[24., 28., 32., 36.],
[40., 45., 50., 55.]])
# 点积是相同位置的按元素乘积的和
x = torch.arange(4, dtype = torch.float32)
y = torch.ones(4, dtype = torch.float32)
x, y, torch.dot(x,y) ## 必须是相同的数据类型才能进行点积
(tensor([0., 1., 2., 3.]), tensor([1., 1., 1., 1.]), tensor(6.))
torch.dot(x,y), torch.sum(x*y)
tensor(6.), tensor(6.)
A = torch.arange(20, dtype=torch.float32).reshpae(5,4)
x = torch.arange(4, dtype = torch.float32)
## 如果能够点积,需要vector的长度与matrix的列数相等,这样vector就会被转换成一个 mx1的matrix
torch.mv(A,x)
tensor([ 14., 38., 62., 86., 110.])
B = torch.ones(4,3)
torch.mm(A,B)
tensor
([[ 6., 6., 6.],
[22., 22., 22.],
[38., 38., 38.],
[54., 54., 54.],
[70., 70., 70.]])
u = torch.tensor([[-3.0, 4]])
torch.abs(u).sum()
tensor(7.)
torch.norm(u)
注意:input dtype should be either floating point or complex dtypes
torch.norm(torch.ones((4,9)))
tensor(6.)
路遥知马力,
更应砥砺前行
mingxin