初识 PyTorch

初步了解PyTorch基本操作。

环境管理(Conda)

使用conda (24.5.0) 管理python环境

创建环境:

1
conda create --name d2l python=3.11 -y

激活环境:

1
conda activate d2l

列出环境:

1
conda env list

安装包:

1
conda install package_name

查看当前环境安装了哪些包:

1
conda list

运行环境(Jupyter & Spyder)

Jupyter

定位路径(mine: cd d2l-zh)后,用以下命令打开Jupyter笔记本。

1
jupyter notebook

Spyder

在对应环境 conda install spyder ,以后可直接进入。

初识

矩阵处理

初始化矩阵:

1
2
3
4
5
6
7
8
9
A = torch.arange(20).reshape(5, 4)

print(A)
"""矩阵A"""
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19]])

转置矩阵:

1
2
3
4
5
6
7
print(A.T)

"""矩阵A转置"""
tensor([[ 0, 4, 8, 12, 16],
[ 1, 5, 9, 13, 17],
[ 2, 6, 10, 14, 18],
[ 3, 7, 11, 15, 19]])

点乘:

1
2
3
4
5
6
x = torch.arange(4.0)                      # tensor([0., 1., 2., 3.])
y = torch.ones(4, dtype = torch.float32) # tensor([1., 1., 1., 1.])
print(torch.dot(x, y))

"""输出点乘结果"""
tensor(6.)

叉乘:

1
2
3
4
5
6
7
8
9
10
A = torch.arange(20.).reshape(5, 4)
B = torch.ones(4, 3)
print(torch.mm(A, B))

"""输出叉乘结果"""
tensor([[ 6., 6., 6.],
[22., 22., 22.],
[38., 38., 38.],
[54., 54., 54.],
[70., 70., 70.]])

trytry 自动求导

好理解:grad can be implicitly created only for scalar outputs-CSDN博客

计算 y = x * x * xx 的导数。

1
2
3
4
5
6
7
8
9
10
import torch

x = torch.arange(5.0, requires_grad = True)

y = x * x * x
y.sum().backward()
print(x.grad)

"""求导结果"""
tensor([ 0., 3., 12., 27., 48.])

其中 backward() ,反向传播(backpropagate),意味着跟踪整个计算图,填充关于每个参数的偏导数。

trytry 绘制切线

任务:给定函数f(x) ,画出在 x = 1 处的近似切线。(f(x) 任意指定)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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

def numerical_lim(f, x, delta):
return (f(x + delta) - f(x)) / delta

def use_svg_display():
"""使用svg格式在Jupyter中显示绘图"""
backend_inline.set_matplotlib_formats('svg')

def set_figsize(figsize=(3.5, 2.5)):
"""设置matplotlib的图表大小"""
use_svg_display()
d2l.plt.rcParams['figure.figsize'] = figsize

def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):
"""设置matplotlib的轴"""
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()

def plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None,
ylim=None, xscale='linear', yscale='linear',
fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None):
"""绘制数据点"""
if legend is None:
legend = []
set_figsize(figsize)
axes = axes if axes else d2l.plt.gca()
# 如果X有一个轴,输出True

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 is None:
X, Y = [[]] * len(X), X
elif has_one_axis(Y):
Y = [Y]
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)


if __name__ == "__main__":
delta = 1e-5
tangent = numerical_lim(f, 1, delta)
print(f'delta={delta:.5f}, numerical limit={tangent:.5f}')

x = np.arange(0.01, 3, 0.005)
plot(x, [f(x), tangent * x + f(1) - tangent * 1], 'x', 'f(x)', legend=['f(x)', 'Tangent line (x=1)'])

运行结果: