2.4 微积分
拟合模型的两个关键问题:
-
优化:用模型拟合观测数据
-
泛化:生成有效性超出用于训练的数据集本身的模型。
教材程序代码
用pycharm运行 %matplotlib inline会报错:SyntaxError: invalid syntax
-
解决1:将其删除,在最后加上 d2l.plt.show() 就可以显示图像
-
解决2:在Jupyter notebook里运行。
#@save的意思
书中的解释:是一个特殊的标记,会将对应的函数、类或语句保存在d2l包中。因此,以后无需重新定义就可以直接调用它们。
一开始理解为自己写的函数可以通过这个标记保存到d2l库中,但显然不是。后来看解释,应该理解为这些有标记的函数已经封装在d2l库中,是可以直接调用的,这里是对其展开讲解,标记是为了将其与临时定义(自己定义)的函数做区分。
《动手学深度学习-pytorch》书中定义函数后加#@save的含义
# %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
def numerical_lim(f, x, h):
return (f(x + h) - f(x)) / h
h = 0.1
for i in range(5):
print(f'h={h:.5f},numerical limit={numerical_lim(f, 1, h):.5f}')
h *= 0.1
def use_svg_display(): #@save
"""使用svg格式在Jupyter中显示绘图"""
backend_inline.set_matplotlib_formats('svg')
def set_figsize(figsize=(3.5, 2.5)): #@save
"""设置matplotlib的图标大小"""
use_svg_display()
#这里以及后文可以直接使用d2l.plt,是因为d2l包中包含了导入语句from matplotlib import pyplot as plt
d2l.plt.rcParams['figure.figsize'] = figsize
# @save
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()
#@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=(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)
x = np.arange(0, 3, 0.1)
plot(x, [f(x), 2 * x - 3], 'x', 'f(x)', legend=['f(x)', 'Tangent line (x=1)'])
d2l.plt.show()
结果:
绘制函数f(x) = x**3 -1/x,在x=1处的切线为y=4x-4
2.5 自动微分
例子
对函数y = 2xTx(2乘以x和x的点积)关于列向量x求导
注:一个标量函数关于向量x的梯度是向量,并且与x具有相同的形状。
import torch
#创建变量x并分配一个初始值
x = torch.arange(4.0)
print(x)
x.requires_grad_(True) # 等价于x=torch.arange(4.0,requires_grad=True)
x.grad # 默认值是None
#计算y的标量输出
y = 2 * torch.dot(x, x)
print(y)
#通过调用反向传播函数来自动计算y关于x每个分量的梯度
y.backward()
print(x.grad)#打印梯度
#验证梯度是否计算正确
print(x.grad == 4 * x)
#计算x的另一个函数
# 在默认情况下,PyTorch会累积梯度,所以需要清除之前的值
x.grad.zero_()
y = x.sum()
y.backward()
print(x.grad)
#结果
#tensor([0., 1., 2., 3.])
#tensor(28., grad_fn=<MulBackward0>)
#tensor([ 0., 4., 8., 12.])
#tensor([True, True, True, True])
#tensor([1., 1., 1., 1.])
非标量变量的反向传播
# 对非标量调用backward需要传入一个gradient参数,该参数指定微分函数关于self的梯度。
# 本例只想求偏导数的和,所以传递一个1的梯度是合适的
x.grad.zero_()
y = x * x
# 等价于y.backward(torch.ones(len(x)))
y.sum().backward()
print(x.grad)
#结果
#tensor([0., 2., 4., 6.])
分离计算
detach()函数:返回一个新的张量,从当前计算图中分离出来,但仍指向原变量的位置,不具有梯度。
pytorch-detach() .detach_() 的作用和区别
x.grad.zero_()
y = x * x
u = y.detach()#分离y返回一个新变量
z = u * x
z.sum().backward()
print(x.grad == u)
x.grad.zero_()
y.sum().backward()
print(x.grad == 2 * x)
#结果
#tensor([True, True, True, True])
#tensor([True, True, True, True])
Python控制流的梯度计算
使用自动微分的好处:即使构建函数的计算图需要通过Python控制流(例如:条件、循环或任意函数调用),仍可以计算得到变量的梯度。
def f(a):
b = a * 2
while b.norm() < 1000:
b = b * 2
if b.sum() > 0:
c = b
else:
c = 100 * b
return c
a = torch.randn(size=(), requires_grad=True)
d = f(a)
d.backward()
print(a.grad == d / a)
#结果
#tensor(True)