#我们在这里画的是方程3*x**2 - 4*x 在x = 1处的切线
#欠拟合:欠拟合指的是模型对训练数据的拟合度过低,误差值过大,自然泛化能力也不怎么好。
#泛化能力指模型对未知数据的拟合度
#过拟合:指模型对训练数据的拟合度较好,误差值较小,但是泛化能力并不好。
#对误差函数进行惩罚,从而提高模型的泛化能力
#恰当拟合:模型对训练数据和测试数据的拟合度均较高,误差值也较小,而且模型并不复杂
#优化:用模型拟合观察数据的过程
#泛化:数学原理和实践者的智慧,能够指导我们生成有效性超出用于训练的数据集本身的模型
#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)是一种格式化字符串的语法结构。其中'{}'是占位符,用于指向将要插入该位置的变量。
print(f'h = {h:.5f}, numerical limit = {numerical_lim(f, 1, h):.5f}')
h *= 0.1
'''
def use_svg_display():
backend_inline.set_matplotlib_formats('svg') #使用svg格式绘图
def set_figsize(figsize=(3.5, 2.5)):
#设置matplotlib的图表大小
use_svg_display()
d2l.plt.rcParams['figure.figsize'] = figsize
#set_axes函数用于设置由matplotlib生成图表的轴的属性
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 f(x):
return 3 * x ** 2 - 4 * x
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)'])