预备知识

  • 绘图类

    1
    2
    3
    def use_svg_display():  #@save
    """使用svg格式在Jupyter中显示绘图"""
    backend_inline.set_matplotlib_formats('svg')
    1
    2
    3
    4
    def set_figsize(figsize=(3.5, 2.5)):  #@save
    """设置matplotlib的图表大小"""
    use_svg_display()
    d2l.plt.rcParams['figure.figsize'] = figsize
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    #@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()
    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
    #@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)

线性神经网络

  • 计时器

    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
    class Timer:  #@save
    """记录多次运行时间"""
    def __init__(self):
    self.times = []
    self.start()

    def start(self):
    """启动计时器"""
    self.tik = time.time()

    def stop(self):
    """停止计时器并将时间记录在列表中"""
    self.times.append(time.time() - self.tik)
    return self.times[-1]

    def avg(self):
    """返回平均时间"""
    return sum(self.times) / len(self.times)

    def sum(self):
    """返回时间总和"""
    return sum(self.times)

    def cumsum(self):
    """返回累计时间"""
    return np.array(self.times).cumsum().tolist()
  • 线性回归训练集生成

    1
    2
    3
    4
    5
    6
    def synthetic_data(w, b, num_examples):  #@save
    """生成y=Xw+b+噪声"""
    X = torch.normal(0, 1, (num_examples, len(w)))
    y = torch.matmul(X, w) + b
    y += torch.normal(0, 0.01, y.shape)
    return X, y.reshape((-1, 1))
  • softmax回归 标签数字转换

    1
    2
    3
    4
    5
    def get_fashion_mnist_labels(labels):  #@save
    """返回Fashion-MNIST数据集的文本标签"""
    text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat',
    'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
    return [text_labels[int(i)] for i in labels]
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    def show_images(imgs, num_rows, num_cols, titles=None, scale=1.5):  #@save
    """绘制图像列表"""
    figsize = (num_cols * scale, num_rows * scale)
    # 我们不打算使用函数返回的第一个值,因此用_来丢弃它
    _, axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize) # 包含多个子图的图像网格,返回了包含图形和子图句柄的元组
    axes = axes.flatten() # 将子图句柄展平为一维数组,以便在循环中更容易处理
    for i, (ax, img) in enumerate(zip(axes, imgs)): # 迭代处理每个子图和对应的图像,zip将两个可迭代对象逐个配对组合成一个新的可迭代对象
    if torch.is_tensor(img):
    # 图片张量
    ax.imshow(img.numpy())
    else:
    # PIL图片
    ax.imshow(img)
    ax.axes.get_xaxis().set_visible(False) # 将子图的x轴和y轴标签隐藏,以去除默认的坐标轴
    ax.axes.get_yaxis().set_visible(False)
    if titles:
    ax.set_title(titles[i])
    return axes
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    def load_data_fashion_mnist(batch_size, resize=None):  #@save
    """下载Fashion-MNIST数据集,然后将其加载到内存中"""
    trans = [transforms.ToTensor()]
    if resize:
    trans.insert(0, transforms.Resize(resize))
    trans = transforms.Compose(trans) # Compose函数将多个图像变换组合在一起
    mnist_train = torchvision.datasets.FashionMNIST(
    root="./data", train=True, transform=trans, download=False)
    mnist_test = torchvision.datasets.FashionMNIST(
    root="./data", train=False, transform=trans, download=False)
    return (data.DataLoader(mnist_train, batch_size, shuffle=True,
    num_workers=get_dataloader_workers()),
    data.DataLoader(mnist_test, batch_size, shuffle=False,
    num_workers=get_dataloader_workers()))