2.3 线性代数
2.3.1 标量
ini
import torch
x = torch.tensor(2.0)
y = torch.tensor(3.0)
x + y, x * y, x / y, x ** y

2.3.2 向量
python
'''
只有一个值称为标量,
多个标量组合在一起称为向量。
'''
x = torch.arange(4)
x[2]

python
'''
len(x)输出元素个数,x.shape输出张量的形状
'''
print(len(x))
print(x.shape)

python
'''
len(y)输出的是第一个维度的大小
y.numel()输出的才是所有元素个数
'''
y = torch.ones(3, 4)
y, len(y), y.numel(), y.shape

css
A = torch.arange(20).reshape(5, 4)
A

python
'''
assert只能对单值进行判断,
直接 B == B.T可以对多个位置进行判断
'''
B = torch.tensor([[1, 2, 3], [2, 0, 4], [3, 4, 5]])
B == B.T

2.3.4 张量
ini
X = torch.arange(36).reshape(4, 3, 3)
X

2.3.5 张量算法的基本性质
css
'''
注意 B = A 和 B = A.clone()之间的区别
B = A 则B和A指向同一块内存空间
B = A.clone() 则是新分配一块内存给B,内容和A一样
'''
A = torch.arange(20, dtype = torch.float32).reshape(5, 4)
B = A.clone()
A, B, A + B

python
'''
重大发现:
PyTorch和Numpy中,*是按照元素相乘,也就是Hadamard积
如果非得使用矩阵成大,那就得用@
'''
A = torch.arange(4).reshape(2, 2)
B = torch.arange(4).reshape(2, 2)
A * B, A @ B

2.3.6 降维
python
'''
sum()可以对张量中所有元素求和
利用dtype指定元素类型的时候还不能直接用float32,
还得指定为torch.float32
使用sum()跟张量的形状无关,无论张量是几维的,都可以对所有元素求和。
'''
import torch
X = torch.arange(10, dtype = torch.float32).reshape(2, 5)
X, X.sum()

python
'''
axis = 0 纵向操作
axis = 1 横向操作
'''
A = torch.arange(12, dtype = torch.int32).reshape(3, 4)
A_sum_axis0 = A.sum(axis = 0)
A, A_sum_axis0

非降维求和
python
'''
如果在计算sum的时候不适用keepdims = True, 那么默认降维;
使用keepdims = True,那就是非降维求和。
非降维求和的好处是有利于广播。
什么是广播?回忆一下:
是否适用广播机制是由从右到左逐一比较维度决定的。
1. 相等
2. 二选一为1
3. 不存在
非降维求和可以让二维的还是保持二维,只不过把其中一维压缩为1,适用广播机制。
'''
import torch
A = torch.arange(20, dtype = torch.float32).reshape(4, 5)
A_hengxiang_junzhi = A.sum(axis = 1, keepdims = True)
A, A.shape, A_hengxiang_junzhi, A_hengxiang_junzhi.shape

python
'''
广播机制加减乘除都能用,并不仅仅局限于加法
这么看我前面"2.1数据操作"中对于广播机制应用场景很少的观点确实有问题。
广播机制是一种很优秀的,效率很高的方法,能对数据进行很快速的,方便的,简洁的运算
而且加减乘除都能用
'''
print(f"{A + A_hengxiang_junzhi},\n\n{A - A_hengxiang_junzhi}, \n\n{A * A_hengxiang_junzhi}, \n\n{A / A_hengxiang_junzhi}")

2.3.7 点积
python
'''
点积:逐元素相乘再相加
'''
import torch
X = torch.tensor([1, 2, 3])
Y = torch.tensor([1, 2, 3])
torch.dot(X, Y)

python
'''
计算两个向量的点积有两种方法:
torch.dot(X, Y)
另一种是:
torch.sum(X*Y)
由于float32, int32, double64, sum() 等等都是来自torch里面的
所以在用的时候基本上都得指定torch.balabala
'''
torch.sum(X*Y)

2.3.8 矩阵向量积
python
'''
torch.mv(A, X) 本质上就是在计算 A @ X
问一下:arange是什么缩写?
'''
A = torch.arange(12).reshape(3, 4)
X = torch.ones(4, dtype = torch.long)
torch.mv(A, X)

2.3.9 矩阵矩阵乘法
python
'''
mv = matrix * vector
mm = matrix * matrix
我觉得了解一下函数的缩写是很有必要的,这能帮助你更好得理解函数的用法
A @ B
'''
A = torch.arange(12).reshape(3, 4)
B = torch.arange(12).reshape(4, 3)
torch.mm(A, B)

2.3.10 范数
python
'''
L1范数是绝对值之和,L2范数是欧几里得距离(勾股定理)
直接取norm()那就是L2范数,也就是欧几里得距离
tensor,张量的默认数据类型是long
norm()计算的是欧几里得距离,涉及到开根号,整数开根号除了一些特殊的,比如3, 4, 5, 还有, 8, 10
这种开出来就是是整数,但是大部分常见情况下都是复数或者小数,所以数据类型要么是complex,要么是float
torch默认的数据类型是int64, 也就是long
'''
x = torch.tensor([6, 8], dtype = torch.float)
torch.norm(x)

python
'''
直接用norm()是L2范数,
如果想要计算L1范数,也就是绝对值之和,那就是abs和sum搭配使用
直接用torch.tensor()去定义向量的话,记住小括号里面还得加中括号
'''
x = torch.tensor([3, -4, -5])
L1_norm = torch.abs(x).sum()
L1_norm

python
'''
L2范数针对向量,Frobenius范数针对矩阵,但是它们的计算并没有本质区别
'''
X = torch.ones(49).reshape(7, 7)
torch.norm(X)

练习
1. 证明A转置的转置还是A
ini
A = torch.arange(12).reshape(3, 4)
B = A.T.T
A == B

2. 证明A转+B转 = A+B的转
css
A = torch.arange(12).reshape(3, 4)
B = torch.ones(12).reshape(3, 4)
(A.T + B.T) == (A + B).T

3. 给定任意方阵A,A + A转一定是对称矩阵吗
回答是肯定的。因为被主对角线切成的两部分,在经过A + A转以后两部分都是原上 + 原下,所以结果是一样的。
css
A = torch.arange(16).reshape(4, 4)
B = A + A.T
B == B.T

4. (2, 3, 4)的X,len(x)是什么
回答是2
验证一下
scss
X = torch.arange(24).reshape(4, 2, 3)
len(X)

5. 对于任意形状的张量X,len(X)是否总是对应于X特定轴的长度?这个轴是什么?
len(x)输出的一定是第一个维度的值
6. 运行A/A.sum(axis=1),看看会发生什么。请分析一下原因?
会报错。
因为当你不设置keepdim = True, 那么A.sum(axis = 1)算出来就被降维了。 降维以后从右往左看,第一个维度分别是4和3,对不齐,用不了广播机制,报错。
ini
A = torch.arange(12).reshape(3, 4)
A.sum(axis = 1).shape, A.sum(axis = 1, keepdims = True).shape

7. (2, 3, 4)三个维度求和分别是什么形状?
python
'''
以哪个轴就是把哪个轴给噶掉,剩下的是什么轴就是什么形状。
'''
A = torch.arange(24).reshape(2, 3, 4)
A.sum(axis = 0), A.sum(axis = 1), A.sum(axis = 2)

8. 为linalg.norm函数提供3个或更多轴的张量,并观察其输出。对于任意形状的张量这个函数计算得到什么?
python
'''
linalg = linear + algbra
ord = order
直接使用torch.norm()出来的就是L2范数
但是linalg.norm()更加通用,通过ord参数指定范数的类型。
'''
X = torch.ones(49).reshape(7, 7)
torch.linalg.norm(X, ord = "fro", keepdim = True), torch.linalg.norm(X, ord = "fro")

2.4 微积分
2.4.1 导数和微分
python
'''
% matplotlib inline 作用是让matplotlib绘制的图像出现在Jupyter的单元格中,而不是出现在新弹出的窗口中。
matplotlib_inline 用于控制内联图像的行为
backend_inline 用来设置内联图像的属性
from d2l import torch as d2l 相较于直接import torch,d2l里面实现的torch封装了更多函数,可以直接调用。
'''
%matplotlib inline
import numpy as np
from matplotlib_inline import backend_inline
from d2l import torch as d2l
def f(x):
return 3*x**2 - 4*x
python
'''
h从0.1开始不断缩小,每次变为原来的十分之一,h变得越来越小,求出来的导数(或者说斜率)就越来越精确
两个注意点:
1. number, numerical 单词别写错了
2. 函数本身作为另一个函数的参数时,不需要带上自己的参数
'''
def numerical_lim(f, x, h):
return (f(x+h) - f(x)) / h
h = 0.1
x = 1
for _ in range(5):
print(f"当h为{h: .5f}时,f(x)在x = {x}处的值为{numerical_lim(f, x, h): .5f}")
h = h * 0.1

python
def use_svg_display(): #@save
backend_inline.set_matplotlib_formats("svg")
'''
d2l.plt 这里的plt本质上就是 import matplotlib.pyplot as plt,只不过d2l包里面把这行代码已经写过了,因此可以通过d2l.plt直接用
rcParams是全局配置字典,会影响后续所有图像的设置。
'''
def set_figsize(figsize = (6.5, 5.5)): #@save
use_svg_display()
d2l.plt.rcParams['figure.figsize'] = figsize
python
'''
legend用于给图中的线添加文字
'''
#@save
def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):
axes.set_xlabel(xlabel)
axes.set_ylabel(ylabel)
axes.set_xscale(xscale)
axes.set_yscale(yscale)
axes.set_xlim(xlim)
axes.set_ylim(ylim)
if legend:
axes.legend(legend)
axes.grid()
python
'''
代码挺多的,但是我依然认为需要自己敲一遍,不应该直接复制粘贴。
哪怕是照着抄,也得自己写,因为后面的要求是要靠自己写出来。
这一节主要是在定义一个plot函数,后面就可以直接用它绘图。
如果调用同一个函数多次,那么形参的默认值只会在第一次调用时设置,后面再调用的时候使用的是同一个参数值,
因此legend不能在形参处就设置为[], 只能先设置成None, 然后在plot()函数体内部更改legend的值,因为函数体内部
每次调用都会被重新执行。
d2l里面的很多函数其实就只是搬运工,只不过是把matplotlib.pyplot里面的东西换个位置搬出来。
d2l本质上是d2l.torch, 当我想使用gca() get current axes时,不能直接d2l.gca(),因为d2l.torch里面没有gca()
gca()存在于plt中,也就是调用的时候的得用d2l.plt.gca()
'''
#@save
def plot(X, Y = None, xlabel = None, ylabel = None, legend = None, xlim = None, ylim = None,
xscale = "linear", yscale = "linear", fmts = ("-", "m--", "g-.", "r:"), figsize = (6.5, 5.5), axes = None):
if legend == None:
legend = []
set_figsize(figsize)
axes = axes if axes else d2l.plt.gca()
def has_one_axis(X):
return (hasattr(X, "ndim") and X.ndim == 1 or isinstance(X, list) and
not hasattr(X[0], "__len__"))
if has_one_axis(X):
X = [X]
if Y == None:
X, Y = [[]]* len(X), X
elif has_one_axis(Y):
Y = [Y]
'''
直接对列表乘以2,是对列表内部元素的复制
'''
if len(X) != len(Y):
X = X * len(Y)
axes.cla()
'''
循环的单次就绘制了一条线
'''
for x, y, fmt in zip(X, Y, fmts):
if len(x):
axes.plot(x, y, fmt)
else:
axes.plot(y, fmt)
set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
scss
x = np.arange(0, 3, 0.1)
plot(x, [f(x), 2*x-3], "x", "f(x)", legend = ["f(x)", "Tangent line (x=1)"])

2.4.2 偏导数 略
2.4.3 梯度
一个多元函数,对所有变量的偏导组合在一起就构成了梯度。
2.4.4 链式法则
链式法则本质上就是对复合函数求导。
练习
意外发现,原来Jupyter Notebook里面的Markdown单元格也是可以粘贴图像的

切线方程:y = 4*x - 4
一张图上画两条线,一条是f(x),另一条是它在x=1处的切线
scss
X = np.arange(0, 3, 0.1)
plot(X, [x**3-x**(-1), 4*x-4], "x", "f(x)", legend = ["f(x)", "Tangent line: x = 1"])




两条杠,右下角写个2,这指的是L2范数
具体的计算方法应该是x1 ** 2 + x2 ** 2 + ... + xn ** 2 再开根号


