10from typing import List, Optional
11
12from torch import nn
13
14from labml import experiment
15from labml.configs import option
16from labml_nn.experiments.cifar10 import CIFAR10Configs
17from labml_nn.resnet import ResNetBase

配置

我们使用CIFAR10Configs 它来定义所有与数据集相关的配置、优化器和训练循环。

20class Configs(CIFAR10Configs):

每个要素地图大小的区块数

29    n_blocks: List[int] = [3, 3, 3]

每个要素映射大小的通道数

31    n_channels: List[int] = [16, 32, 64]

瓶颈大小

33    bottlenecks: Optional[List[int]] = None

初始卷积层的内核大小

35    first_kernel_size: int = 3

创建模型

38@option(Configs.model)
39def _resnet(c: Configs):
44    base = ResNetBase(c.n_blocks, c.n_channels, c.bottlenecks, img_channels=3, first_kernel_size=c.first_kernel_size)

用于分类的线性层

46    classification = nn.Linear(c.n_channels[-1], 10)

堆叠它们

49    model = nn.Sequential(base, classification)

将模型移到设备上

51    return model.to(c.device)
54def main():

创建实验

56    experiment.create(name='resnet', comment='cifar10')

创建配置

58    conf = Configs()

装载配置

60    experiment.configs(conf, {
61        'bottlenecks': [8, 16, 16],
62        'n_blocks': [6, 6, 6],
63
64        'optimizer.optimizer': 'Adam',
65        'optimizer.learning_rate': 2.5e-4,
66
67        'epochs': 500,
68        'train_batch_size': 256,
69
70        'train_dataset': 'cifar10_train_augmented',
71        'valid_dataset': 'cifar10_valid_no_augment',
72    })

设置保存/加载的模型

74    experiment.add_pytorch_models({'model': conf.model})

开始实验并运行训练循环

76    with experiment.start():
77        conf.run()

81if __name__ == '__main__':
82    main()