【d2l】2.3.线性代数
【d2l】2.3.线性代数
标量
这一块采用torch将标量实例化
import torch
x = torch.tensor(3.0)
y = torch.tensor(2.0)
x + y, x * y, x / y, x ** y
(tensor(5.), tensor(6.), tensor(1.5000), tensor(9.))
向量
x = torch.arange(4)
x
tensor([0, 1, 2, 3])
对这个向量可以通过索引随机访问
对于长度和形状采用以下接口
len(x)
x.shape
矩阵
.T接口可以进行矩阵转置
A = torch.arange(20).reshape(5, 4)
A, A.T
对于矩阵转置的判断有两种方式
B = torch.tensor(
[
[1, 2, 3],
[2, 0, 4],
[3, 4, 5]
]
)
B == B.T, torch.equal(B, B.T)
前者返回一个bool矩阵,后者返回一个bool值
张量
张量是一种代数对象,计算方式需要区别于矩阵
A = torch.arange(20, dtype = torch.float32).reshape(5, 4)
B = A.clone() # 深拷贝矩阵
A, A + B, A * B
张量的默认乘法是哈达玛积,表示为
\[A \odot B =
\left [
\begin{matrix}
a_{11}b_{11}& a_{12}b_{12}& ...& a_{1n}b_{1n} \\
a_{21}b_{21}& a_{22}b_{22}& ...& a_{2n}b_{2n} \\
\vdots& \vdots& & \vdots\\
a_{n1}b_{n1}& a_{n2}b_{n2}& ...& a_{nn}b_{nn} \\
\end{matrix}
\right ]
\]
即对应元素相乘
张量加上或乘上一个标量都不会影响形状
a = 2
X = torch.arange(24).reshape(2, 3, 4)
a + X, (a * X).shape
(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]]]),
torch.Size([2, 3, 4]))
降维
主要采用的是参数中的axis = 0或axis = 1,分别代表按照列操作和按照行操作
axis = 0
A_sum_axis0 = A.sum(axis = 0)
A_sum_axis0, A_sum_axis0.shape
axis = 1
A_sum_axis1 = A.sum(axis = 1)
A_sum_axis1, A_sum_axis1.shape
结果为
(tensor([40., 45., 50., 55.]), torch.Size([4]))
(tensor([ 6., 22., 38., 54., 70.]), torch.Size([5]))
mean()的接口也支持axis参数
A.mean(axis = 0), A.sum(axis = 0) / A.shape[0]
对于axis = 1的情况,为了保持轴不变,可以令keepdims = True
sum_A = A.sum(axis = 1, keepdims = True)
sum_A
tensor([[ 6.],
[22.],
[38.],
[54.],
[70.]])
对于按行/按列求和,可以用cumsum()接口保证不降维度,结果是一个前缀和矩阵
A.cumsum(axis = 0)
tensor([[ 0., 1., 2., 3.],
[ 4., 6., 8., 10.],
[12., 15., 18., 21.],
[24., 28., 32., 36.],
[40., 45., 50., 55.]])
点积
有两种表示方式,但事实上只会用dot()接口
y = torch.ones(4, dtype = torch.float32)
x, y, torch.dot(x, y), torch.sum(x * y)
矩阵-向量积
采用mv()函数——matrix-vector
A.shape, x.shape, torch.mv(A, x)
(torch.Size([5, 4]), torch.Size([4]), tensor([ 14., 38., 62., 86., 110.]))
矩阵-矩阵乘法
采用mm()函数——matrix multiply
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.]])
范数
范数简单理解上可以认为是距离的度量
常用的是\(L_2\)范数
\[||x||_2 = \sqrt{\sum_{i = 1}^n x_i^2}
\]
也会有\(L_1\)范数
\[||x||_1 = \sum_{i = 1}^n |x_i|
\]
相比较下\(L_1\)范数受到异常值的影响比较小
以下是两种范数的实例化
u = torch.tensor([3.0, -4.0])
torch.norm(u) # L2
torch.abs(u).sum() # L1
事实上两种范数都是\(L_p\)范数的特例
\[||x||_p = (\sum_{i = 1}^n |x_i|^p)^{\frac{1}{p}}
\]
对于矩阵来说,采用Frobenius范数,类似\(L_2\)范数
\[||X||_F = \sqrt{\sum_{i = 1}^m\sum_{j = 1}^n x_{ij}^2}
\]
实例化如下:
torch.norm(torch.ones((4, 9)))
从应用来看,范数可以用来作为优化问题中,不同对象之间的距离的度量

浙公网安备 33010602011771号