JoyBeanRobber

导航

李沐动手学深度学习3——线性代数

李沐动手学深度学习,有视频、有中文电子书(含配套代码),推荐!

视频(B站搜一大堆):https://www.bilibili.com/video/BV1fsmyYnEfw?spm_id_from=333.788.videopod.episodes&vd_source=0199f117e2bdbb60970034d4f33ff67d

官网电子书:https://zh.d2l.ai/index.html

 代码如下,主要知识点是矩阵降维、矩阵乘法、求范数

import torch

x = torch.tensor([3.0])
y = torch.tensor([2.0])
print(x+y, x*y, x/y, x**y)
x = torch.arange(4)
print(x, x[3], len(x), x.shape)
A = torch.arange(20).reshape(5, 4)
print(A, A.T)
B = torch.tensor([[1, 2, 3], [2, 0, 4], [3, 4, 5]])
print(B == B.T)
X = torch.arange(24).reshape(2, 3, 4)
print(X)
A = torch.arange(20, dtype=torch.float32).reshape(5, 4)
B = A.clone()
print(A, A+B, A*B, sep="\n")
x = torch.arange(4, dtype=torch.float32)
print(x, x.sum())

# 降维
A = torch.arange(20, dtype=torch.float32).reshape(5, 4)
print(A.shape, A.sum())
A_sum_axis0, A_sum_axis1 = A.sum(dim=0), A.sum(dim=1)
print(A_sum_axis0, A_sum_axis0.shape, A_sum_axis1, A_sum_axis1.shape)
# 表示在两个维度(0,1)上求和
print(A.sum([0, 1]))

# 平均值
# 求mean值,张量数据类型必须为int或float
# 如果21行中没有加“dtype=torch.float32”,会默认A中数据类型为long,求mean会报错
print(A.mean(), A.sum()/A.numel())
print(A.mean(dim=0), A.sum(dim=0)/A.shape[0])

# 求和不降维度
sum_A = A.sum(dim=1, keepdim=True)
print(sum_A)
# 求和不降维度的意义是可以利用广播机制直接计算A/sum_A
print(A/sum_A)

# 累加求和
# 比如矩阵以行进行累加求和第二行加第一行,第三行加新的第二行,以此类推
print(A.cumsum(dim=0))

# 向量点积
y = torch.ones(4, dtype=torch.float32)
print(x, y, x@y)
# 矩阵(二维)乘向量(一维)
# mv限制只能在矩阵乘向量中使用,更加严格且语义明确
# @符号可以计算维度相同的矩阵乘法,不能直接计算二维矩阵与一维向量的积(可以先将向量转化为(1,n)形式的二维向量)
print(A.shape, x.shape, torch.mv(A, x))
# 与mv类似的是mm,限制在两个矩阵做乘法中使用
B = torch.ones(4, 3)
print(torch.mm(A, B))
# 还有dot,用于计算两个向量的内积

# L2范数,欧氏距离,是向量所有元素平方和的平方根
# norm函数求向量范数
u = torch.tensor([3.0, -4.0])
print(u.norm())
# L1范数,是向量所有元素绝对值之和
print(u.abs().sum())
# F范数,是矩阵所有元素平方和的平方根
print(torch.ones((4, 9)).norm())

 

posted on 2025-04-16 15:18  欢乐豆掠夺者  阅读(27)  评论(0)    收藏  举报