• CV+Deep Learning——网络架构Pytorch复现系列——basenets(BackBones)(一)


    引言此系列重点在于复现计算机视觉(分类、目标检测、语义分割)中深度学习各个经典的网络模型,以便初学者使用(深入浅出)!

    代码都运行无误!!

    首先复现深度学习经典网络模型(basenet)(就是家喻户晓的Backbone,但是我会对Backbone做一些改动,所以这个系列就不叫Backbone,叫basenet)这些网络大都是分类的经典网络(1.,2.,3.,4.,5.,6.,7.),目标检测的Backbone(8.,9.),有:

    1.LeNet5(√)

    2.VGG(√)

    3.AlexNet(√)

    4.ResNet(√)

    5.GoogLeNet

    5.MobileNet

    6.ShuffleNet

    7.EfficientNet

    8.VovNet

    9.DarkNet

    ...

    注意:

    a) 完整代码上传至我的github

    https://github.com/HanXiaoyiGitHub/Simple-CV-Pytorch-masterhttps://github.com/HanXiaoyiGitHub/Simple-CV-Pytorch-masterb) 编译环境设置为 (其实不用这个编译环境,你会调bug也行!)

    1. python == 3.9.12
    2. torch == 1.11.0+cu113
    3. torchvision== 0.11.0+cu113
    4. torchaudio== 0.12.0+cu113
    5. pycocotools == 2.0.4
    6. numpy
    7. Cython
    8. matplotlib
    9. opencv-python
    10. tqdm
    11. thop

    c) 分类数据集使用ImageNet或CIFAR10,其目录 (coco和voc用于目标检测和语义分割现在暂时用不到):

    1. dataset path: /data/
    2. data
    3. |
    4. |----coco----|----coco2017
    5. |
    6. |----cifar
    7. |
    8. |----ImageNet----|----ILSVRC2012
    9. |
    10. |----VOCdevkit
    11. coco2017 path: /data/coco/coco2017
    12. coco2017
    13. |
    14. |
    15. |----annotations
    16. |----train2017
    17. |----test2017
    18. |----val2017
    19. voc path: /data/VOCdevkit
    20. |
    21. | |----Annotations
    22. | |----ImageSets
    23. |----VOC2007----|----JPEGImages
    24. | |----SegmentationClass
    25. | |----SegmentationObject
    26. |
    27. |
    28. | |----Annotations
    29. | |----ImageSets
    30. |----VOC2012----|----JPEGImages
    31. | |----SegmentationClass
    32. | |----SegmentationObject
    33. ILSVRC2012 path : /data/ImageNet/ILSVRC2012
    34. |
    35. |----train
    36. |
    37. |----val
    38. cifar path: /data/cifar
    39. |
    40. |----cifar-10-batches-py
    41. |
    42. |----cifar-10-python.tar.gz

    d) 使用了amp混精度使gpu加速,若不知如何使用可参考如下链接:

    如何使用Pytorch让网络模型加速训练?(autocast与GradScaler)https://blog.csdn.net/XiaoyYidiaodiao/article/details/124854343?spm=1001.2014.3001.5502

    所以需要在网络模型的forward函数前加入 @autocast(),并且又因为使用了1.4以上版本的torch,必须修改ReLu(inplace=False),Dropout(inplace=False),等等有inplace都设置为False。

    e) 由于LeNet5、VGG16、AlexNet使用了全连接层不能修改图像的size,所以这些网络架构在图像预处理时图像的size就必须固定

    f) 项目文件结构

    使用的OS (Ubuntu 20.04),当然windows下也能运行,我运行过。有的文件夹用不上,先别管,我之后会讲。

    1. project path: /data/PycharmProject/
    2. Simple-CV-master path: /data/PycharmProject/Simple-CV-Pytorch-master
    3. |
    4. |----checkpoints ( resnet50-19c8e357.pth \COCO_ResNet50.pth[RetinaNet]\ VOC_ResNet50.pth[RetinaNet] )
    5. |
    6. | |----cifar.py ( null, I just use torchvision.datasets.ImageFolder )
    7. | |----CIAR_labels.txt
    8. | |----coco.py
    9. | |----coco_eval.py
    10. | |----coco_labels.txt
    11. |----data----|----__init__.py
    12. | |----config.py ( path )
    13. | |----imagenet.py ( null, I just use torchvision.datasets.ImageFolder )
    14. | |----ImageNet_labels.txt
    15. | |----voc0712.py
    16. | |----voc_eval.py
    17. | |----voc_labels.txt
    18. | |----crash_helmet.jpg
    19. |----images----|----classification----|----sunflower.jpg
    20. | | |----photocopier.jpg
    21. | | |----automobile.jpg
    22. | |
    23. | |----detection----|----000001.jpg
    24. | |----000001.xml
    25. | |----000002.jpg
    26. | |----000002.xml
    27. | |----000003.jpg
    28. | |----000003.xml
    29. |
    30. |----log(XXX[ detection or classification ]_XXX[ train or test or eval ].info.log)
    31. |
    32. | |----__init__.py
    33. | |
    34. | | |----__init.py
    35. | |----anchor----|----RetinaNetAnchors.py
    36. | |
    37. | | |----lenet5.py
    38. | | |----alexnet.py
    39. | |----basenet----|----vgg.py
    40. | | |----resnet.py
    41. | |
    42. | | |----DarkNetBackbone.py
    43. | |----backbones----|----__init__.py ( Don't finish writing )
    44. | | |----ResNetBackbone.py
    45. | | |----VovNetBackbone.py
    46. | |
    47. | |
    48. | |
    49. |----models----|----heads----|----__init.py
    50. | | |----RetinaNetHeads.py
    51. | |
    52. | | |----RetinaNetLoss.py
    53. | |----losses----|----__init.py
    54. | |
    55. | | |----FPN.py
    56. | |----necks----|----__init__.py
    57. | | |-----FPN.txt
    58. | |
    59. | |----RetinaNet.py
    60. |
    61. |----results ( eg: detection ( VOC or COCO AP ) )
    62. |
    63. |----tensorboard ( Loss visualization )
    64. |
    65. |----tools |----eval.py
    66. | |----classification----|----train.py
    67. | | |----test.py
    68. | |
    69. | |
    70. | |
    71. | | |----eval_coco.py
    72. | | |----eval_voc.py
    73. | |----detection----|----test.py
    74. | |----train.py
    75. |
    76. |
    77. | |----AverageMeter.py
    78. | |----BBoxTransform.py
    79. | |----ClipBoxes.py
    80. | |----Sampler.py
    81. | |----iou.py
    82. |----utils----|----__init__.py
    83. | |----accuracy.py
    84. | |----augmentations.py
    85. | |----collate.py
    86. | |----get_logger.py
    87. | |----nms.py
    88. | |----path.py
    89. |
    90. |----FolderOrganization.txt
    91. |
    92. |----main.py
    93. |
    94. |----README.md
    95. |
    96. |----requirements.txt

    1.LeNet5(size: 32 * 32 * 3)

     图 1.

    如图 1.还原代码

    加入nn.BatchNorm2d(),使其精度上升,当然为了完全复现,你们可以忽略掉nn.BatchNorm2d(),将其从代码中删除。

    可根据数据集类别自行调整最后一层连接层的输出

    1. from torch import nn
    2. from torch.cuda.amp import autocast
    3. class lenet5(nn.Module):
    4. # cifar: 10, ImageNet: 1000
    5. def __init__(self, num_classes=1000, init_weights=False):
    6. super(lenet5, self).__init__()
    7. self.num_classes = num_classes
    8. self.layers = nn.Sequential(
    9. # input:32 * 32 * 3 -> 28 * 28 * 6
    10. nn.Conv2d(in_channels=3, out_channels=6, kernel_size=5, padding=0, stride=1, bias=False),
    11. nn.BatchNorm2d(6),
    12. nn.ReLU(),
    13. # 28 * 28 * 6 -> 14 * 14 * 6
    14. nn.MaxPool2d(kernel_size=2, stride=2, padding=0),
    15. # 14 * 14 * 6 -> 10 * 10 * 16
    16. nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5, padding=0, stride=1, bias=False),
    17. nn.BatchNorm2d(16),
    18. nn.ReLU(),
    19. # 10 * 10 * 16 -> 5 * 5 * 16
    20. nn.MaxPool2d(kernel_size=2, stride=2, padding=0),
    21. nn.Flatten(),
    22. nn.Linear(16 * 5 * 5, 120),
    23. nn.Linear(120, 84))
    24. self.classifier = nn.Linear(84, self.num_classes)
    25. if init_weights:
    26. self._initialize_weights()
    27. @autocast()
    28. def forward(self, x):
    29. x = self.layers(x)
    30. x = self.classifier(x)
    31. return x
    32. def _initialize_weights(self):
    33. for m in self.modules():
    34. if isinstance(m, nn.Conv2d):
    35. nn.init.xavier_uniform_(m.weight)
    36. if m.bias is not None:
    37. nn.init.constant_(m.bias, 0)
    38. elif isinstance(m, nn.Linear):
    39. nn.init.xavier_uniform_(m.weight)
    40. nn.init.constant_(m.bias, 0)

    2.AlexNet (Size: 224 * 224* 3)

    图 2.

    如图 2.,若不是特别清楚,可参考下图 3.

    图 3.

    将图 3. 转成图 4. ,这是因为之前的AlexNet是放在两张显卡(当年的计算力是不行的)上跑,现在的计算力能跟上了,可放在一张GPU上跑。

     图 4.

    可根据数据集类别自行调整最后一层连接层的输出

    加入nn.BatchNorm2d(),使其精度上升,当然为了完全复现,你们可以忽略掉nn.BatchNorm2d(),将其从代码中删除。

    1. import torch.nn as nn
    2. from torch.cuda.amp import autocast
    3. class alexnet(nn.Module):
    4. def __init__(self, num_classes=1000, init_weights=False):
    5. super(alexnet, self).__init__()
    6. self.layers = nn.Sequential(
    7. # input: 224 * 224 * 3 -> 55 * 55 * (48*2)
    8. nn.Conv2d(in_channels=3, out_channels=96, kernel_size=11, stride=4, padding=2, bias=False),
    9. nn.BatchNorm2d(96),
    10. nn.ReLU(),
    11. # 55 * 55 * (48*2) -> 27 * 27 * (48*2)
    12. nn.MaxPool2d(kernel_size=3, stride=2),
    13. # 27 * 27 * (48*2) -> 27 * 27 * (128*2)
    14. nn.Conv2d(in_channels=96, out_channels=256, kernel_size=5, padding=2, bias=False),
    15. nn.BatchNorm2d(256),
    16. nn.ReLU(),
    17. # 27 * 27 * (128*2) -> 13 * 13 * (128*2)
    18. nn.MaxPool2d(kernel_size=3, stride=2),
    19. # 13 * 13 * (128*2) -> 13 * 13 * (192*2)
    20. nn.Conv2d(in_channels=256, out_channels=384, kernel_size=3, padding=1, bias=False),
    21. nn.BatchNorm2d(384),
    22. nn.ReLU(),
    23. # 13 * 13 * (192*2) -> 13 * 13 * (192*2)
    24. nn.Conv2d(in_channels=384, out_channels=384, kernel_size=3, padding=1, bias=False),
    25. nn.BatchNorm2d(384),
    26. nn.ReLU(),
    27. # 13 * 13 * (192*2) -> 13 * 13 * (128*2)
    28. nn.Conv2d(in_channels=384, out_channels=256, kernel_size=3, padding=1, bias=False),
    29. nn.BatchNorm2d(256),
    30. nn.ReLU(),
    31. # 13 * 13 * (128*2) -> 6 * 6 * (128*2)
    32. nn.MaxPool2d(kernel_size=3, stride=2)
    33. )
    34. self.fc = nn.Sequential(
    35. nn.Flatten(),
    36. nn.Dropout(0.5),
    37. nn.Linear(6 * 6 * 128 * 2, 2048),
    38. nn.ReLU(),
    39. nn.Dropout(0.5),
    40. nn.Linear(2048, 2048),
    41. nn.ReLU()
    42. )
    43. self.classifier = nn.Linear(2048, num_classes)
    44. if init_weights:
    45. self._initialize_weights()
    46. @autocast()
    47. def forward(self, x):
    48. x = self.layers(x)
    49. x = self.fc(x)
    50. x = self.classifier(x)
    51. return x
    52. def _initialize_weights(self):
    53. for m in self.modules():
    54. if isinstance(m, nn.Conv2d):
    55. nn.init.xavier_uniform_(m.weight)
    56. if m.bias is not None:
    57. nn.init.constant_(m.bias, 0)
    58. elif isinstance(m, nn.Linear):
    59. nn.init.xavier_uniform_(m.weight)
    60. nn.init.constant_(m.bias, 0)

    3.VGG (Size: 224 * 224* 3 )

    图 5.

    如图 5.复现绿框中框出的网络架构,还原代码

    我是看不下去精度那么差,所以我就把nn.BatchNorm2d(i)添加进去,并且做了迁移学习。

    可根据数据集类别自行调整最后一层连接层的输出

    1. import torch
    2. from torch import nn
    3. from utils.path import CheckPoints
    4. from torch.cuda.amp import autocast
    5. __all__ = [
    6. 'vgg11',
    7. 'vgg13',
    8. 'vgg16',
    9. 'vgg19',
    10. ]
    11. # if your network is limited, you can download them, and put them into CheckPoints(my Project:Simple-CV-Pytorch-master/checkpoints/).
    12. model_urls = {
    13. # 'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
    14. 'vgg11': '{}/vgg11-bbd30ac9.pth'.format(CheckPoints),
    15. # 'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth',
    16. 'vgg13': '{}/vgg13-c768596a.pth'.format(CheckPoints),
    17. # 'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth',
    18. 'vgg16': '{}/vgg16-397923af.pth'.format(CheckPoints),
    19. # 'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth',
    20. 'vgg19': '{}/vgg19-dcbb9e9d.pth'.format(CheckPoints)
    21. }
    22. def vgg_(arch, num_classes, pretrained, init_weights=False, **kwargs):
    23. cfg = cfgs["vgg" + arch]
    24. features = make_features(cfg)
    25. model = vgg(num_classes=num_classes, features=features, init_weights=init_weights, **kwargs)
    26. # if you're training for the first time, no pretrained is required!
    27. if pretrained:
    28. pretrained_models = torch.load(model_urls["vgg" + arch])
    29. # transfer learning
    30. # if you want to train your own dataset
    31. if arch == '11':
    32. del pretrained_models['features.8.weight']
    33. del pretrained_models['features.11.weight']
    34. del pretrained_models['features.16.weight']
    35. elif arch == '13':
    36. del pretrained_models['features.7.weight']
    37. del pretrained_models['features.10.weight']
    38. del pretrained_models['features.15.weight']
    39. del pretrained_models['features.17.weight']
    40. del pretrained_models['features.22.weight']
    41. elif arch == '16':
    42. del pretrained_models['features.7.weight']
    43. del pretrained_models['features.10.weight']
    44. del pretrained_models['features.14.weight']
    45. del pretrained_models['features.17.weight']
    46. del pretrained_models['features.21.weight']
    47. del pretrained_models['features.24.weight']
    48. del pretrained_models['features.28.weight']
    49. elif arch == '19':
    50. del pretrained_models['features.7.weight']
    51. del pretrained_models['features.10.weight']
    52. del pretrained_models['features.14.weight']
    53. del pretrained_models['features.21.weight']
    54. del pretrained_models['features.23.weight']
    55. del pretrained_models['features.28.weight']
    56. del pretrained_models['features.34.weight']
    57. else:
    58. raise ValueError("Pretrained: unsupported VGG depth")
    59. model.load_state_dict(pretrained_models, strict=False)
    60. return model
    61. def vgg11(num_classes, pretrained=False, init_weights=False, **kwargs):
    62. return vgg_('11', num_classes, pretrained, init_weights, **kwargs)
    63. def vgg13(num_classes, pretrained=False, init_weights=False, **kwargs):
    64. return vgg_('13', num_classes, pretrained, init_weights, **kwargs)
    65. def vgg16(num_classes, pretrained=False, init_weights=False, **kwargs):
    66. return vgg_('16', num_classes, pretrained, init_weights, **kwargs)
    67. def vgg19(num_classes, pretrained=False, init_weights=False, **kwargs):
    68. return vgg_('19', num_classes, pretrained, init_weights, **kwargs)
    69. class vgg(nn.Module):
    70. # cifar: 10, ImageNet: 1000
    71. def __init__(self, features, num_classes=1000, init_weights=False):
    72. super(vgg, self).__init__()
    73. self.num_classes = num_classes
    74. self.features = features
    75. self.fc = nn.Sequential(
    76. nn.Flatten(),
    77. nn.Linear(7 * 7 * 512, 4096),
    78. nn.ReLU(),
    79. nn.Dropout(0.5),
    80. nn.Linear(4096, 4096),
    81. nn.ReLU(),
    82. nn.Dropout(0.5),
    83. )
    84. self.classifier = nn.Linear(4096, self.num_classes)
    85. if init_weights:
    86. self._initialize_weights()
    87. @autocast()
    88. def forward(self, x):
    89. x = self.features(x)
    90. x = x.view(x.size(0), -1)
    91. x = self.fc(x)
    92. x = self.classifier(x)
    93. return x
    94. def _initialize_weights(self):
    95. for m in self.modules():
    96. if isinstance(m, nn.Conv2d):
    97. nn.init.xavier_uniform_(m.weight)
    98. if m.bias is not None:
    99. nn.init.constant_(m.bias, 0)
    100. elif isinstance(m, nn.Linear):
    101. nn.init.xavier_uniform_(m.weight)
    102. nn.init.constant_(m.bias, 0)
    103. elif isinstance(m, nn.BatchNorm2d):
    104. nn.init.xavier_uniform_(m.weight)
    105. nn.init.constant_(m.bias, 0)
    106. def make_features(cfgs: list):
    107. layers = []
    108. in_channels = 3
    109. for i in cfgs:
    110. if i == "M":
    111. layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
    112. else:
    113. conv2d = nn.Conv2d(in_channels, i, kernel_size=3, stride=1, padding=1, bias=False)
    114. layers += [conv2d, nn.BatchNorm2d(i), nn.ReLU()]
    115. in_channels = i
    116. return nn.Sequential(*layers)
    117. cfgs = {
    118. 'vgg11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    119. 'vgg13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    120. 'vgg16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
    121. 'vgg19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
    122. }

    4.ResNet

    图 6.

    如图 6. 复现网络架构(ResNet18,ResNet34,ResNet50,ResNet101,ResNet152),还原代码

    首先来看每个block如何复现?如图18-layer, 34-layer由下图 7. 绿框表示,50-layer, 101-layer, 152-layer由下图 7. 蓝框表示;

    block: 18-layer, 34-layer

    1. # 18-layer, 34-layer
    2. class BasicBlock(nn.Module):
    3. expansion = 1
    4. def __init__(self, in_channels, out_channels, stride=1, downsample=None):
    5. super(BasicBlock, self).__init__()
    6. self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=stride,
    7. padding=1, bias=False)
    8. self.bn1 = nn.BatchNorm2d(out_channels)
    9. self.relu = nn.ReLU()
    10. self.conv2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1,
    11. bias=False)
    12. self.bn2 = nn.BatchNorm2d(out_channels)
    13. self.downsample = downsample
    14. def forward(self, x):
    15. identity = x
    16. if self.downsample is not None:
    17. identity = self.downsample(x)
    18. out = self.conv1(x)
    19. out = self.bn1(out)
    20. out = self.relu(out)
    21. out = self.conv2(out)
    22. out = self.bn2(out)
    23. out += identity
    24. out = self.relu(out)
    25. return out

     block: 50-layer, 101-layer, 152-layer

    1. # 50-layer, 101-layer, 152-layer
    2. class Bottleneck(nn.Module):
    3. """
    4. self.conv1(kernel_size=1,stride=2)
    5. self.conv2(kernel_size=3,stride=1)
    6. to
    7. self.conv1(kernel_size=1,stride=1)
    8. self.conv2(kernel_size=3,stride=2)
    9. """
    10. expansion = 4
    11. def __init__(self, in_channels, out_channels, stride=1, downsample=None):
    12. super(Bottleneck, self).__init__()
    13. self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1,
    14. stride=1, bias=False)
    15. self.bn1 = nn.BatchNorm2d(out_channels)
    16. self.conv2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3,
    17. stride=stride, bias=False)
    18. self.bn2 = nn.BatchNorm2d(out_channels)
    19. self.conv3 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels * self.expansion, kernel__size=1,
    20. stride=1, bias=False)
    21. self.bn3 = nn.BatchNorm2d(out_channels * self.expansion)
    22. self.relu = nn.ReLU()
    23. self.downsample = downsample
    24. def forward(self, x):
    25. identity = x
    26. if self.downsample is not None:
    27. identity = self.downsample(x)
    28. out = self.conv1(x)
    29. out = self.bn1(out)
    30. out = self.relu(out)
    31. out = self.conv2(out)
    32. out = self.bn2(out)
    33. out = self.relu(out)
    34. out = self.conv3(out)
    35. out = self.bn3(out)
    36. out += identity
    37. out = self.relu(out)
    38. return out

    整个ResNet模型的还原,先还原第一层卷积和最大池化层

    1. class ResNet(nn.Module):
    2. def __init__(self, block, blocks_num, num_classes=1000, include_top=True):
    3. super(ResNet, self).__init__()
    4. self.include_top = include_top
    5. self.in_channels = 64
    6. self.conv1 = nn.Conv2d(in_channels=3, out_channels=self.in_channels, kernel_size=7, stride=2,
    7. padding=3, bias=False)
    8. self.bn1 = nn.BatchNorm2d(self.in_channels)
    9. self.relu = nn.ReLU()
    10. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)

    之后的layer层,如图 8. 代码与图中的表示模块的对等关系

    1. conv2_x -> self.layer1,
    2. conv3_x -> self.layer2,
    3. conv4_x -> self.layer3,
    4. conv5_x -> self.layer4

    1. ...
    2. self.layer1 = self._make_layer(block, 64, blocks_num[0])
    3. self.layer2 = self._make_layer(block, 128, blocks_num[1], stride=2)
    4. self.layer3 = self._make_layer(block, 256, blocks_num[2], stride=2)
    5. self.layer4 = self._make_layer(block, 512, blocks_num[3], stride=2)
    6. ...

    50-layer, 101-layer, 152-layer 复现虚线部分;18-layer,34-layer也是这样,就不展示了。

    图 8.

    1. def _make_layer(self, block, channels, block_num, stride=1):
    2. downsample = None
    3. if stride != 1 or self.in_channels != channels * block.expansion:
    4. downsample = nn.Sequential(
    5. nn.Conv2d(in_channels=self.in_channels, out_channels=channels * block.expansion,
    6. kernel_size=1, stride=stride, bias=False),
    7. nn.BatchNorm2d(channels * block.expansion)
    8. )
    9. ...

    之后调用ResNet模型,选取合适的layer(18, 34, 50, 101, 152)

    1. def resnet18(num_classes=1000, pretrained=False, include_top=True):
    2. return resnet_('18', BasicBlock, [2, 2, 2, 2], num_classes, pretrained, include_top)
    3. def resnet34(num_classes=1000, pretrained=False, include_top=True):
    4. return resnet_('34', BasicBlock, [3, 4, 6, 3], num_classes, pretrained, include_top)
    5. def resnet50(num_classes=1000, pretrained=False, include_top=True):
    6. return resnet_('50', Bottleneck, [3, 4, 6, 3], num_classes, pretrained, include_top)
    7. def resnet101(num_classes=1000, pretrained=False, include_top=True):
    8. return resnet_('101', Bottleneck, [3, 4, 23, 3], num_classes, pretrained, include_top)
    9. def resnet152(num_classes=1000, pretrained=False, include_top=True):
    10. return resnet_('152', Bottleneck, [3, 8, 36, 3], num_classes, pretrained, include_top)

    完整代码

    1. import torch
    2. import torch.nn as nn
    3. from utils.path import CheckPoints
    4. from torch.cuda.amp import autocast
    5. __all__ = [
    6. 'resnet18',
    7. 'resnet34',
    8. 'resnet50',
    9. 'resnet101',
    10. 'resnet152'
    11. ]
    12. # if your network is limited, you can download them, and put them into CheckPoints(my Project:Simple-CV-Pytorch-master/checkpoints/).
    13. model_urls = {
    14. # 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
    15. 'resnet18': '{}/resnet18-5c106cde.pth'.format(CheckPoints),
    16. # 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
    17. 'resnet34': '{}/resnet34-333f7ec4.pth'.format(CheckPoints),
    18. # 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
    19. 'resnet50': '{}/resnet50-19c8e357.pth'.format(CheckPoints),
    20. # 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
    21. 'resnet101': '{}/resnet101-5d3b4d8f.pth'.format(CheckPoints),
    22. # 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
    23. 'resnet152': '{}/resnet152-b121ed2d.pth'.format(CheckPoints)
    24. }
    25. def resnet_(arch, block, block_num, num_classes, pretrained, include_top, **kwargs):
    26. model = resnet(block=block, blocks_num=block_num, num_classes=num_classes, include_top=include_top, **kwargs)
    27. # if you're training for the first time, no pretrained is required!
    28. if pretrained:
    29. # if you want to use cpu, you should modify map_loaction=torch.device("cpu")
    30. pretrained_models = torch.load(model_urls["resnet" + arch], map_location=torch.device("cuda:0"))
    31. # transfer learning
    32. # if you want to train your own dataset
    33. # del pretrained_models['module.classifier.bias']
    34. model.load_state_dict(pretrained_models, strict=False)
    35. return model
    36. # 18-layer, 34-layer
    37. class BasicBlock(nn.Module):
    38. expansion = 1
    39. def __init__(self, in_channels, out_channels, stride=1, downsample=None):
    40. super(BasicBlock, self).__init__()
    41. self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=stride,
    42. padding=1, bias=False)
    43. self.bn1 = nn.BatchNorm2d(out_channels)
    44. self.relu = nn.ReLU()
    45. self.conv2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1,
    46. bias=False)
    47. self.bn2 = nn.BatchNorm2d(out_channels)
    48. self.downsample = downsample
    49. @autocast()
    50. def forward(self, x):
    51. identity = x
    52. if self.downsample is not None:
    53. identity = self.downsample(x)
    54. out = self.conv1(x)
    55. out = self.bn1(out)
    56. out = self.relu(out)
    57. out = self.conv2(out)
    58. out = self.bn2(out)
    59. out += identity
    60. out = self.relu(out)
    61. return out
    62. # 50-layer, 101-layer, 152-layer
    63. class Bottleneck(nn.Module):
    64. """
    65. self.conv1(kernel_size=1,stride=2)
    66. self.conv2(kernel_size=3,stride=1)
    67. to
    68. self.conv1(kernel_size=1,stride=1)
    69. self.conv2(kernel_size=3,stride=2)
    70. acc: up 0.5%
    71. """
    72. expansion = 4
    73. def __init__(self, in_channels, out_channels, stride=1, downsample=None):
    74. super(Bottleneck, self).__init__()
    75. self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1,
    76. stride=1, bias=False)
    77. self.bn1 = nn.BatchNorm2d(out_channels)
    78. self.conv2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3,
    79. stride=stride, bias=False)
    80. self.bn2 = nn.BatchNorm2d(out_channels)
    81. self.conv3 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels * self.expansion, kernel__size=1,
    82. stride=1, bias=False)
    83. self.bn3 = nn.BatchNorm2d(out_channels * self.expansion)
    84. self.relu = nn.ReLU()
    85. self.downsample = downsample
    86. @autocast()
    87. def forward(self, x):
    88. identity = x
    89. if self.downsample is not None:
    90. identity = self.downsample(x)
    91. out = self.conv1(x)
    92. out = self.bn1(out)
    93. out = self.relu(out)
    94. out = self.conv2(out)
    95. out = self.bn2(out)
    96. out = self.relu(out)
    97. out = self.conv3(out)
    98. out = self.bn3(out)
    99. out += identity
    100. out = self.relu(out)
    101. return out
    102. class resnet(nn.Module):
    103. def __init__(self, block, blocks_num, num_classes=1000, include_top=True):
    104. super(resnet, self).__init__()
    105. self.include_top = include_top
    106. self.in_channels = 64
    107. self.conv1 = nn.Conv2d(in_channels=3, out_channels=self.in_channels, kernel_size=7, stride=2,
    108. padding=3, bias=False)
    109. self.bn1 = nn.BatchNorm2d(self.in_channels)
    110. self.relu = nn.ReLU()
    111. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
    112. self.layer1 = self._make_layer(block, 64, blocks_num[0])
    113. self.layer2 = self._make_layer(block, 128, blocks_num[1], stride=2)
    114. self.layer3 = self._make_layer(block, 256, blocks_num[2], stride=2)
    115. self.layer4 = self._make_layer(block, 512, blocks_num[3], stride=2)
    116. if self.include_top:
    117. self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
    118. self.flatten = nn.Flatten()
    119. self.fc = nn.Linear(512 * block.expansion, num_classes)
    120. for m in self.modules():
    121. if isinstance(m, nn.Conv2d):
    122. nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
    123. def _make_layer(self, block, channels, block_num, stride=1):
    124. downsample = None
    125. if stride != 1 or self.in_channels != channels * block.expansion:
    126. downsample = nn.Sequential(
    127. nn.Conv2d(in_channels=self.in_channels, out_channels=channels * block.expansion,
    128. kernel_size=1, stride=stride, bias=False),
    129. nn.BatchNorm2d(channels * block.expansion)
    130. )
    131. layers = []
    132. layers.append(block(in_channels=self.in_channels, out_channels=channels, downsample=downsample, stride=stride))
    133. self.in_channels = channels * block.expansion
    134. for _ in range(1, block_num):
    135. layers.append(
    136. block(in_channels=self.in_channels, out_channels=channels))
    137. return nn.Sequential(*layers)
    138. @autocast()
    139. def forward(self, x):
    140. x = self.conv1(x)
    141. x = self.bn1(x)
    142. x = self.relu(x)
    143. x = self.maxpool(x)
    144. x = self.layer1(x)
    145. x = self.layer2(x)
    146. x = self.layer3(x)
    147. x = self.layer4(x)
    148. if self.include_top:
    149. x = self.avgpool(x)
    150. x = self.flatten(x)
    151. x = self.fc(x)
    152. return x
    153. def resnet18(num_classes=1000, pretrained=False, include_top=True):
    154. return resnet_('18', BasicBlock, [2, 2, 2, 2], num_classes, pretrained, include_top)
    155. def resnet34(num_classes=1000, pretrained=False, include_top=True):
    156. return resnet_('34', BasicBlock, [3, 4, 6, 3], num_classes, pretrained, include_top)
    157. def resnet50(num_classes=1000, pretrained=False, include_top=True):
    158. return resnet_('50', Bottleneck, [3, 4, 6, 3], num_classes, pretrained, include_top)
    159. def resnet101(num_classes=1000, pretrained=False, include_top=True):
    160. return resnet_('101', Bottleneck, [3, 4, 23, 3], num_classes, pretrained, include_top)
    161. def resnet152(num_classes=1000, pretrained=False, include_top=True):
    162. return resnet_('152', Bottleneck, [3, 8, 36, 3], num_classes, pretrained, include_top)

    一些配置文件

    utils/path.py

    1. import os.path
    2. import sys
    3. BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
    4. sys.path.append(BASE_DIR)
    5. # Gets home dir cross platform
    6. # "/data/"
    7. MyName = "PycharmProject"
    8. Folder = "Simple-CV-Pytorch-master"
    9. # Path to store checkpoint model
    10. CheckPoints = 'checkpoints'
    11. CheckPoints = os.path.join(BASE_DIR, MyName, Folder, CheckPoints)
    12. # Path to store tensorboard load
    13. tensorboard_log = 'tensorboard'
    14. tensorboard_log = os.path.join(BASE_DIR, MyName, Folder, tensorboard_log)
    15. # Path to save log
    16. log = 'log'
    17. log = os.path.join(BASE_DIR, MyName, Folder, log)
    18. # Path to save classification train log
    19. classification_train_log = 'classification_train'
    20. # Path to save classification test log
    21. classification_test_log = 'classification_test'
    22. # Path to save classification eval log
    23. classification_eval_log = 'classification_eval'
    24. # Classification evaluate model path
    25. classification_evaluate = None
    26. # Images classification path
    27. image_cls = 'automobile.jpg'
    28. images_cls_path = 'images/classification'
    29. images_cls_path = os.path.join(BASE_DIR, MyName, Folder, images_cls_path, image_cls)
    30. # Data
    31. DATAPATH = BASE_DIR
    32. # ImageNet/ILSVRC2012
    33. ImageNet = "ImageNet/ILSVRC2012"
    34. ImageNet_Train_path = os.path.join(DATAPATH, ImageNet, 'train')
    35. ImageNet_Eval_path = os.path.join(DATAPATH, ImageNet, 'val')
    36. # CIFAR10
    37. CIFAR = 'cifar'
    38. CIFAR_path = os.path.join(DATAPATH, CIFAR)

    data/config.py

    1. from utils import path
    2. # Path to save log
    3. log = path.log
    4. # Path to save classification train log
    5. classification_train_log = path.classification_train_log
    6. # Path to save classification test log
    7. classification_test_log = path.classification_test_log
    8. # Path to save classification eval log
    9. classification_eval_log = path.classification_eval_log
    10. # Path to store checkpoint model
    11. checkpoint_path = path.CheckPoints
    12. # Classification evaluate model path
    13. classification_evaluate = path.classification_evaluate
    14. # Classification test images
    15. images_cls_root = path.images_cls_path
    16. # Path to save tensorboard
    17. tensorboard_log = path.tensorboard_log

    训练代码

    tools/classification/train.py

    1. import os
    2. import logging
    3. import argparse
    4. import warnings
    5. warnings.filterwarnings('ignore')
    6. import sys
    7. BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    8. sys.path.append(BASE_DIR)
    9. import time
    10. import torch
    11. from data import *
    12. import torchvision
    13. import torch.nn as nn
    14. import torch.nn.parallel
    15. import torch.optim as optim
    16. from torchvision import transforms
    17. from utils.accuracy import accuracy
    18. from torch.utils.data import DataLoader
    19. from utils.get_logger import get_logger
    20. from models.basenets.lenet5 import lenet5
    21. from models.basenets.alexnet import alexnet
    22. from utils.AverageMeter import AverageMeter
    23. from torch.cuda.amp import autocast, GradScaler
    24. from models.basenets.vgg import vgg11, vgg13, vgg16, vgg19
    25. from models.basenets.resnet import resnet18, resnet34, resnet50, resnet101, resnet152
    26. def parse_args():
    27. parser = argparse.ArgumentParser(description='PyTorch Classification Training')
    28. parser.add_mutually_exclusive_group()
    29. parser.add_argument('--dataset',
    30. type=str,
    31. default='CIFAR',
    32. choices=['ImageNet', 'CIFAR'],
    33. help='ImageNet, CIFAR')
    34. parser.add_argument('--dataset_root',
    35. type=str,
    36. default=CIFAR_ROOT,
    37. choices=[ImageNet_Train_ROOT, CIFAR_ROOT],
    38. help='Dataset root directory path')
    39. parser.add_argument('--basenet',
    40. type=str,
    41. default='lenet',
    42. choices=['resnet', 'vgg', 'lenet', 'alexnet'],
    43. help='Pretrained base model')
    44. parser.add_argument('--depth',
    45. type=int,
    46. default=5,
    47. help='BaseNet depth, including: LeNet of 5, AlexNet of 0, VGG of 11, 13, 16, 19, ResNet of 18, 34, 50, 101, 152')
    48. parser.add_argument('--batch_size',
    49. type=int,
    50. default=32,
    51. help='Batch size for training')
    52. parser.add_argument('--resume',
    53. type=str,
    54. default=None,
    55. help='Checkpoint state_dict file to resume training from')
    56. parser.add_argument('--num_workers',
    57. type=int,
    58. default=8,
    59. help='Number of workers user in dataloading')
    60. parser.add_argument('--cuda',
    61. type=str,
    62. default=True,
    63. help='Use CUDA to train model')
    64. parser.add_argument('--momentum',
    65. type=float,
    66. default=0.9,
    67. help='Momentum value for optim')
    68. parser.add_argument('--gamma',
    69. type=float,
    70. default=0.1,
    71. help='Gamma update for SGD')
    72. parser.add_argument('--accumulation_steps',
    73. type=int,
    74. default=1,
    75. help='Gradient acumulation steps')
    76. parser.add_argument('--save_folder',
    77. type=str,
    78. default=config.checkpoint_path,
    79. help='Directory for saving checkpoint models')
    80. parser.add_argument('--tensorboard',
    81. type=str,
    82. default=False,
    83. help='Use tensorboard for loss visualization')
    84. parser.add_argument('--log_folder',
    85. type=str,
    86. default=config.log,
    87. help='Log Folder')
    88. parser.add_argument('--log_name',
    89. type=str,
    90. default=config.classification_train_log,
    91. help='Log Name')
    92. parser.add_argument('--tensorboard_log',
    93. type=str,
    94. default=config.tensorboard_log,
    95. help='Use tensorboard for loss visualization')
    96. parser.add_argument('--lr',
    97. type=float,
    98. default=1e-2,
    99. help='learning rate')
    100. parser.add_argument('--epochs',
    101. type=int,
    102. default=30,
    103. help='Number of epochs')
    104. parser.add_argument('--weight_decay',
    105. type=float,
    106. default=1e-4,
    107. help='weight decay')
    108. parser.add_argument('--milestones',
    109. type=list,
    110. default=[15, 20, 30],
    111. help='Milestones')
    112. parser.add_argument('--num_classes',
    113. type=int,
    114. default=10,
    115. help='the number classes, like ImageNet:1000, cifar:10')
    116. parser.add_argument('--image_size',
    117. type=int,
    118. default=32,
    119. help='image size, like ImageNet:224, cifar:32')
    120. parser.add_argument('--pretrained',
    121. type=str,
    122. default=True,
    123. help='Models was pretrained')
    124. parser.add_argument('--init_weights',
    125. type=str,
    126. default=False,
    127. help='Init Weights')
    128. return parser.parse_args()
    129. args = parse_args()
    130. # 1. Log
    131. get_logger(args.log_folder, args.log_name)
    132. logger = logging.getLogger(args.log_name)
    133. # 2. Torch choose cuda or cpu
    134. if torch.cuda.is_available():
    135. if args.cuda:
    136. torch.set_default_tensor_type('torch.cuda.FloatTensor')
    137. if not args.cuda:
    138. print("WARNING: It looks like you have a CUDA device, but you aren't using it" +
    139. "\n You can set the parameter of cuda to True.")
    140. torch.set_default_tensor_type('torch.FloatTensor')
    141. else:
    142. torch.set_default_tensor_type('torch.FloatTensor')
    143. if not os.path.exists(args.save_folder):
    144. os.mkdir(args.save_folder)
    145. def train():
    146. # 3. Create SummaryWriter
    147. if args.tensorboard:
    148. from torch.utils.tensorboard import SummaryWriter
    149. # tensorboard loss
    150. writer = SummaryWriter(args.tensorboard_log)
    151. # vgg16, alexnet and lenet5 need to resize image_size, because of fc.
    152. if args.basenet == 'vgg' or args.basenet == 'alexnet':
    153. args.image_size = 224
    154. elif args.basenet == 'lenet':
    155. args.image_size = 32
    156. # 4. Ready dataset
    157. if args.dataset == 'ImageNet':
    158. if args.dataset_root == CIFAR_ROOT:
    159. raise ValueError('Must specify dataset_root if specifying dataset ImageNet2012.')
    160. elif os.path.exists(ImageNet_Train_ROOT) is None:
    161. raise ValueError("WARNING: Using default ImageNet2012 dataset_root because " +
    162. "--dataset_root was not specified.")
    163. dataset = torchvision.datasets.ImageFolder(
    164. root=args.dataset_root,
    165. transform=torchvision.transforms.Compose([
    166. transforms.Resize((args.image_size,
    167. args.image_size)),
    168. transforms.ToTensor(),
    169. transforms.Normalize(mean=[0.485, 0.456, 0.406],
    170. std=[0.229, 0.224, 0.225]),
    171. ]))
    172. elif args.dataset == 'CIFAR':
    173. if args.dataset_root == ImageNet_Train_ROOT:
    174. raise ValueError('Must specify dataset_root if specifying dataset CIFAR10.')
    175. elif args.dataset_root is None:
    176. raise ValueError("Must provide --dataset_root when training on CIFAR10.")
    177. dataset = torchvision.datasets.CIFAR10(root=args.dataset_root, train=True,
    178. transform=torchvision.transforms.Compose([
    179. transforms.Resize((args.image_size,
    180. args.image_size)),
    181. torchvision.transforms.ToTensor()]))
    182. else:
    183. raise ValueError('Dataset type not understood (must be ImageNet or CIFAR), exiting.')
    184. dataloader = torch.utils.data.DataLoader(dataset=dataset, batch_size=args.batch_size,
    185. shuffle=True, num_workers=args.num_workers,
    186. pin_memory=False, generator=torch.Generator(device='cuda'))
    187. top1 = AverageMeter()
    188. top5 = AverageMeter()
    189. losses = AverageMeter()
    190. # 5. Define train model
    191. # Unfortunately, Lenet5 and Alexnet don't provide pretrianed Model.
    192. if args.basenet == 'lenet':
    193. if args.depth == 5:
    194. model = lenet5(num_classes=args.num_classes,
    195. init_weights=args.init_weights)
    196. else:
    197. raise ValueError('Unsupported LeNet depth!')
    198. elif args.basenet == 'alexnet':
    199. model = alexnet(num_classes=args.num_classes,
    200. init_weights=args.init_weights)
    201. elif args.basenet == 'vgg':
    202. if args.depth == 11:
    203. model = vgg11(pretrained=args.pretrained,
    204. num_classes=args.num_classes,
    205. init_weights=args.init_weights)
    206. elif args.depth == 13:
    207. model = vgg13(pretrained=args.pretrained,
    208. num_classes=args.num_classes,
    209. init_weights=args.init_weights)
    210. elif args.depth == 16:
    211. model = vgg16(pretrained=args.pretrained,
    212. num_classes=args.num_classes,
    213. init_weights=args.init_weights)
    214. elif args.depth == 19:
    215. model = vgg19(pretrained=args.pretrained,
    216. num_classes=args.num_classes,
    217. init_weights=args.init_weights)
    218. else:
    219. raise ValueError('Unsupported VGG depth!')
    220. # Unfortunately for my resnet, there is no set init_weight, because I'm going to set object detection algorithm
    221. elif args.basenet == 'resnet':
    222. if args.depth == 18:
    223. model = resnet18(pretrained=args.pretrained,
    224. num_classes=args.num_classes)
    225. elif args.depth == 34:
    226. model = resnet34(pretrained=args.pretrained,
    227. num_classes=args.num_classes)
    228. elif args.depth == 50:
    229. model = resnet50(pretrained=args.pretrained,
    230. num_classes=args.num_classes) # False means the models was not trained
    231. elif args.depth == 101:
    232. model = resnet101(pretrained=args.pretrained,
    233. num_classes=args.num_classes)
    234. elif args.depth == 152:
    235. model = resnet152(pretrained=args.pretrained,
    236. num_classes=args.num_classes)
    237. else:
    238. raise ValueError('Unsupported ResNet depth!')
    239. else:
    240. raise ValueError('Unsupported model type!')
    241. if args.cuda:
    242. if torch.cuda.is_available():
    243. model = model.cuda()
    244. model = torch.nn.DataParallel(model).cuda()
    245. else:
    246. model = torch.nn.DataParallel(model)
    247. # 6. Loading weights
    248. if args.resume:
    249. other, ext = os.path.splitext(args.resume)
    250. if ext == '.pkl' or '.pth':
    251. print('Loading weights into state dict...')
    252. model_load = os.path.join(args.save_folder, args.resume)
    253. model.load_state_dict(torch.load(model_load))
    254. else:
    255. print('Sorry only .pth and .pkl files supported.')
    256. if args.init_weights:
    257. # initialize newly added models' weights with xavier method
    258. if args.basenet == 'resnet':
    259. print("There is no set init_weight, because I'm going to set object detection algorithm.")
    260. else:
    261. print("Initializing weights...")
    262. else:
    263. print("Not Initializing weights...")
    264. if args.pretrained:
    265. if args.basenet == 'lenet' or args.basenet == 'alexnet':
    266. print("There is no available pretrained model on the website. ")
    267. else:
    268. print("Models was pretrained...")
    269. else:
    270. print("Pretrained models is False...")
    271. model.train()
    272. iteration = 0
    273. # 7. Optimizer
    274. optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum,
    275. weight_decay=args.weight_decay)
    276. criterion = nn.CrossEntropyLoss()
    277. scheduler = torch.optim.lr_scheduler.MultiStepLR(
    278. optimizer, milestones=args.milestones, gamma=args.gamma)
    279. scaler = GradScaler()
    280. # 8. Length
    281. iter_size = len(dataset) // args.batch_size
    282. print("len(dataset): {}, iter_size: {}".format(len(dataset), iter_size))
    283. logger.info(f"args - {args}")
    284. t0 = time.time()
    285. # 9. Create batch iterator
    286. for epoch in range(args.epochs):
    287. t1 = time.time()
    288. torch.cuda.empty_cache()
    289. # 10. Load train data
    290. for data in dataloader:
    291. iteration += 1
    292. images, targets = data
    293. # 11. Backward
    294. optimizer.zero_grad()
    295. if args.cuda:
    296. images, targets = images.cuda(), targets.cuda()
    297. criterion = criterion.cuda()
    298. # 12. Forward
    299. with autocast():
    300. outputs = model(images)
    301. loss = criterion(outputs, targets)
    302. loss = loss / args.accumulation_steps
    303. if args.tensorboard:
    304. writer.add_scalar("train_classification_loss", loss.item(), iteration)
    305. scaler.scale(loss).backward()
    306. scaler.step(optimizer)
    307. scaler.update()
    308. # 13. Measure accuracy and record loss
    309. acc1, acc5 = accuracy(outputs, targets, topk=(1, 5))
    310. top1.update(acc1.item(), images.size(0))
    311. top5.update(acc5.item(), images.size(0))
    312. losses.update(loss.item(), images.size(0))
    313. if iteration % 100 == 0:
    314. logger.info(
    315. f"- epoch: {epoch}, iteration: {iteration}, lr: {optimizer.param_groups[0]['lr']}, "
    316. f"top1 acc: {acc1.item():.2f}%, top5 acc: {acc5.item():.2f}%, "
    317. f"loss: {loss.item():.3f}, (losses.avg): {losses.avg:3f} "
    318. )
    319. scheduler.step(losses.avg)
    320. t2 = time.time()
    321. h_time = (t2 - t1) // 3600
    322. m_time = ((t2 - t1) % 3600) // 60
    323. s_time = ((t2 - t1) % 3600) % 60
    324. print("epoch {} is finished, and the time is {}h{}min{}s".format(epoch, int(h_time), int(m_time), int(s_time)))
    325. # 14. Save train model
    326. if epoch != 0 and epoch % 10 == 0:
    327. print('Saving state, iter:', epoch)
    328. torch.save(model.state_dict(),
    329. args.save_folder + '/' + args.dataset +
    330. '_' + args.basenet + str(args.depth) + '_' + repr(epoch) + '.pth')
    331. torch.save(model.state_dict(),
    332. args.save_folder + '/' + args.dataset + "_" + args.basenet + str(args.depth) + '.pth')
    333. if args.tensorboard:
    334. writer.close()
    335. t3 = time.time()
    336. h = (t3 - t0) // 3600
    337. m = ((t3 - t0) % 3600) // 60
    338. s = ((t3 - t0) % 3600) % 60
    339. print("The Finished Time is {}h{}m{}s".format(int(h), int(m), int(s)))
    340. return top1.avg, top5.avg, losses.avg
    341. if __name__ == '__main__':
    342. torch.multiprocessing.set_start_method('spawn')
    343. logger.info("Program started")
    344. top1, top5, loss = train()
    345. print("top1 acc: {}, top5 acc: {}, loss:{}".format(top1, top5, loss))
    346. logger.info("Done!")

    测试代码

    tools/classification/test.py

    1. import logging
    2. import os
    3. import argparse
    4. import warnings
    5. warnings.filterwarnings('ignore')
    6. import sys
    7. BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    8. sys.path.append(BASE_DIR)
    9. import time
    10. from data import *
    11. from PIL import Image
    12. import torch.nn.parallel
    13. from torchvision import transforms
    14. from utils.get_logger import get_logger
    15. from models.basenets.lenet5 import lenet5
    16. from models.basenets.alexnet import alexnet
    17. from models.basenets.vgg import vgg11, vgg13, vgg16, vgg19
    18. from models.basenets.resnet import resnet18, resnet34, resnet50, resnet101, resnet152
    19. def parse_args():
    20. parser = argparse.ArgumentParser(description='PyTorch Classification Testing')
    21. parser.add_mutually_exclusive_group()
    22. parser.add_argument('--dataset',
    23. type=str,
    24. default='CIFAR',
    25. choices=['ImageNet', 'CIFAR'],
    26. help='ImageNet, CIFAR')
    27. parser.add_argument('--images_root',
    28. type=str,
    29. default=config.images_cls_root,
    30. help='Dataset root directory path')
    31. parser.add_argument('--basenet',
    32. type=str,
    33. default='alexnet',
    34. choices=['resnet', 'vgg', 'lenet', 'alexnet'],
    35. help='Pretrained base model')
    36. parser.add_argument('--depth',
    37. type=int,
    38. default=0,
    39. help='BaseNet depth, including: LeNet of 5, AlexNet of 0, VGG of 11, 13, 16, 19, ResNet of 18, 34, 50, 101, 152')
    40. parser.add_argument('--evaluate',
    41. type=str,
    42. default=config.classification_evaluate,
    43. help='Checkpoint state_dict file to evaluate training from')
    44. parser.add_argument('--save_folder',
    45. type=str,
    46. default=config.checkpoint_path,
    47. help='Directory for saving checkpoint models')
    48. parser.add_argument('--log_folder',
    49. type=str,
    50. default=config.log,
    51. help='Log Folder')
    52. parser.add_argument('--log_name',
    53. type=str,
    54. default=config.classification_test_log,
    55. help='Log Name')
    56. parser.add_argument('--cuda',
    57. type=str,
    58. default=True,
    59. help='Use CUDA to train model')
    60. parser.add_argument('--num_classes',
    61. type=int,
    62. default=10,
    63. help='the number classes, like ImageNet:1000, cifar:10')
    64. parser.add_argument('--image_size',
    65. type=int,
    66. default=32,
    67. help='image size, like ImageNet:224, cifar:32')
    68. parser.add_argument('--pretrained',
    69. type=str,
    70. default=False,
    71. help='Models was pretrained')
    72. return parser.parse_args()
    73. args = parse_args()
    74. # 1. Torch choose cuda or cpu
    75. if torch.cuda.is_available():
    76. if args.cuda:
    77. torch.set_default_tensor_type('torch.cuda.FloatTensor')
    78. if not args.cuda:
    79. print("WARNING: It looks like you have a CUDA device, but you aren't using it" +
    80. "\n You can set the parameter of cuda to True.")
    81. torch.set_default_tensor_type('torch.FloatTensor')
    82. else:
    83. torch.set_default_tensor_type('torch.FloatTensor')
    84. if not os.path.exists(args.save_folder):
    85. os.mkdir(args.save_folder)
    86. # 2. Log
    87. get_logger(args.log_folder, args.log_name)
    88. logger = logging.getLogger(args.log_name)
    89. def get_label_file(filename):
    90. if not os.path.exists(filename):
    91. print("The dataset label.txt is empty, We need to create a new one.")
    92. os.mkdir(filename)
    93. return filename
    94. def dataset_labels_results(filename, output):
    95. filename = os.path.join(BASE_DIR, 'data', filename + '_labels.txt')
    96. get_label_file(filename=filename)
    97. with open(file=filename, mode='r') as f:
    98. dict = f.readlines()
    99. output = output.cpu().numpy()
    100. output = output[0]
    101. output = dict[output]
    102. f.close()
    103. return output
    104. def test():
    105. # vgg16, alexnet and lenet5 need to resize image_size, because of fc.
    106. if args.basenet == 'vgg' or args.basenet == 'alexnet':
    107. args.image_size = 224
    108. elif args.basenet == 'lenet':
    109. args.image_size = 32
    110. # 3. Ready image
    111. if args.images_root is None:
    112. raise ValueError("The images is None, you should load image!")
    113. image = Image.open(args.images_root)
    114. transform = transforms.Compose([
    115. transforms.Resize((args.image_size,
    116. args.image_size)),
    117. transforms.ToTensor()])
    118. image = transform(image)
    119. image = image.reshape(1, 3, args.image_size, args.image_size)
    120. # 4. Define to train mode
    121. if args.basenet == 'lenet':
    122. if args.depth == 5:
    123. model = lenet5(num_classes=args.num_classes)
    124. else:
    125. raise ValueError('Unsupported LeNet depth!')
    126. elif args.basenet == 'alexnet':
    127. model = alexnet(num_classes=args.num_classes)
    128. elif args.basenet == 'vgg':
    129. if args.depth == 11:
    130. model = vgg11(pretrained=args.pretrained, num_classes=args.num_classes)
    131. elif args.depth == 13:
    132. model = vgg13(pretrained=args.pretrained, num_classes=args.num_classes)
    133. elif args.depth == 16:
    134. model = vgg16(pretrained=args.pretrained, num_classes=args.num_classes)
    135. elif args.depth == 19:
    136. model = vgg19(pretrained=args.pretrained, num_classes=args.num_classes)
    137. else:
    138. raise ValueError('Unsupported VGG depth!')
    139. elif args.basenet == 'resnet':
    140. if args.depth == 18:
    141. model = resnet18(pretrained=args.pretrained,
    142. num_classes=args.num_classes)
    143. elif args.depth == 34:
    144. model = resnet34(pretrained=args.pretrained,
    145. num_classes=args.num_classes)
    146. elif args.depth == 50:
    147. model = resnet50(pretrained=args.pretrained,
    148. num_classes=args.num_classes) # False means the models is not trained
    149. elif args.depth == 101:
    150. model = resnet101(pretrained=args.pretrained,
    151. num_classes=args.num_classes)
    152. elif args.depth == 152:
    153. model = resnet152(pretrained=args.pretrained,
    154. num_classes=args.num_classes)
    155. else:
    156. raise ValueError('Unsupported ResNet depth!')
    157. else:
    158. raise ValueError('Unsupported model type!')
    159. if args.cuda:
    160. model = model.cuda()
    161. model = torch.nn.DataParallel(model).cuda()
    162. else:
    163. model = torch.nn.DataParallel(model)
    164. # 5. Loading model
    165. if args.evaluate:
    166. other, ext = os.path.splitext(args.evaluate)
    167. if ext == '.pkl' or '.pth':
    168. print('Loading weights into state dict...')
    169. model_evaluate_load = os.path.join(args.save_folder, args.evaluate)
    170. model.load_state_dict(torch.load(model_evaluate_load))
    171. else:
    172. print('Sorry only .pth and .pkl files supported.')
    173. elif args.evaluate is None:
    174. print("Sorry, you should load weights! ")
    175. model.eval()
    176. # 6. print
    177. logger.info(f"args - {args}")
    178. # 7. Test
    179. with torch.no_grad():
    180. t0 = time.time()
    181. # 8. Forward
    182. if args.cuda:
    183. image = image.cuda()
    184. output = model(image)
    185. output = output.argmax(1)
    186. t1 = time.time()
    187. m = (t1 - t0) // 60
    188. s = (t1 - t0) % 60
    189. folder_name = args.dataset
    190. output = dataset_labels_results(filename=folder_name, output=output)
    191. logger.info(f"output: {output}")
    192. print("It took a total of {}m{}s to complete the testing.".format(int(m), int(s)))
    193. return output
    194. if __name__ == '__main__':
    195. torch.multiprocessing.set_start_method('spawn')
    196. logger.info("Program started")
    197. output = test()
    198. logger.info("Done!")

    标签

    CIFAR_label.txt

    1. {0: 'airplane',
    2. 1: 'automobile',
    3. 2: 'bird',
    4. 3: 'cat',
    5. 4: 'deer',
    6. 5: 'dog',
    7. 6: 'frog',
    8. 7: 'horse',
    9. 8: 'ship',
    10. 9: 'truck'}

    ImageNet_label.txt

    1. {0: 'tench, Tinca tinca',
    2. 1: 'goldfish, Carassius auratus',
    3. 2: 'great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias',
    4. 3: 'tiger shark, Galeocerdo cuvieri',
    5. 4: 'hammerhead, hammerhead shark',
    6. 5: 'electric ray, crampfish, numbfish, torpedo',
    7. 6: 'stingray',
    8. 7: 'cock',
    9. 8: 'hen',
    10. 9: 'ostrich, Struthio camelus',
    11. 10: 'brambling, Fringilla montifringilla',
    12. 11: 'goldfinch, Carduelis carduelis',
    13. 12: 'house finch, linnet, Carpodacus mexicanus',
    14. 13: 'junco, snowbird',
    15. 14: 'indigo bunting, indigo finch, indigo bird, Passerina cyanea',
    16. 15: 'robin, American robin, Turdus migratorius',
    17. 16: 'bulbul',
    18. 17: 'jay',
    19. 18: 'magpie',
    20. 19: 'chickadee',
    21. 20: 'water ouzel, dipper',
    22. 21: 'kite',
    23. 22: 'bald eagle, American eagle, Haliaeetus leucocephalus',
    24. 23: 'vulture',
    25. 24: 'great grey owl, great gray owl, Strix nebulosa',
    26. 25: 'European fire salamander, Salamandra salamandra',
    27. 26: 'common newt, Triturus vulgaris',
    28. 27: 'eft',
    29. 28: 'spotted salamander, Ambystoma maculatum',
    30. 29: 'axolotl, mud puppy, Ambystoma mexicanum',
    31. 30: 'bullfrog, Rana catesbeiana',
    32. 31: 'tree frog, tree-frog',
    33. 32: 'tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui',
    34. 33: 'loggerhead, loggerhead turtle, Caretta caretta',
    35. 34: 'leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea',
    36. 35: 'mud turtle',
    37. 36: 'terrapin',
    38. 37: 'box turtle, box tortoise',
    39. 38: 'banded gecko',
    40. 39: 'common iguana, iguana, Iguana iguana',
    41. 40: 'American chameleon, anole, Anolis carolinensis',
    42. 41: 'whiptail, whiptail lizard',
    43. 42: 'agama',
    44. 43: 'frilled lizard, Chlamydosaurus kingi',
    45. 44: 'alligator lizard',
    46. 45: 'Gila monster, Heloderma suspectum',
    47. 46: 'green lizard, Lacerta viridis',
    48. 47: 'African chameleon, Chamaeleo chamaeleon',
    49. 48: 'Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis',
    50. 49: 'African crocodile, Nile crocodile, Crocodylus niloticus',
    51. 50: 'American alligator, Alligator mississipiensis',
    52. 51: 'triceratops',
    53. 52: 'thunder snake, worm snake, Carphophis amoenus',
    54. 53: 'ringneck snake, ring-necked snake, ring snake',
    55. 54: 'hognose snake, puff adder, sand viper',
    56. 55: 'green snake, grass snake',
    57. 56: 'king snake, kingsnake',
    58. 57: 'garter snake, grass snake',
    59. 58: 'water snake',
    60. 59: 'vine snake',
    61. 60: 'night snake, Hypsiglena torquata',
    62. 61: 'boa constrictor, Constrictor constrictor',
    63. 62: 'rock python, rock snake, Python sebae',
    64. 63: 'Indian cobra, Naja naja',
    65. 64: 'green mamba',
    66. 65: 'sea snake',
    67. 66: 'horned viper, cerastes, sand viper, horned asp, Cerastes cornutus',
    68. 67: 'diamondback, diamondback rattlesnake, Crotalus adamanteus',
    69. 68: 'sidewinder, horned rattlesnake, Crotalus cerastes',
    70. 69: 'trilobite',
    71. 70: 'harvestman, daddy longlegs, Phalangium opilio',
    72. 71: 'scorpion',
    73. 72: 'black and gold garden spider, Argiope aurantia',
    74. 73: 'barn spider, Araneus cavaticus',
    75. 74: 'garden spider, Aranea diademata',
    76. 75: 'black widow, Latrodectus mactans',
    77. 76: 'tarantula',
    78. 77: 'wolf spider, hunting spider',
    79. 78: 'tick',
    80. 79: 'centipede',
    81. 80: 'black grouse',
    82. 81: 'ptarmigan',
    83. 82: 'ruffed grouse, partridge, Bonasa umbellus',
    84. 83: 'prairie chicken, prairie grouse, prairie fowl',
    85. 84: 'peacock',
    86. 85: 'quail',
    87. 86: 'partridge',
    88. 87: 'African grey, African gray, Psittacus erithacus',
    89. 88: 'macaw',
    90. 89: 'sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita',
    91. 90: 'lorikeet',
    92. 91: 'coucal',
    93. 92: 'bee eater',
    94. 93: 'hornbill',
    95. 94: 'hummingbird',
    96. 95: 'jacamar',
    97. 96: 'toucan',
    98. 97: 'drake',
    99. 98: 'red-breasted merganser, Mergus serrator',
    100. 99: 'goose',
    101. 100: 'black swan, Cygnus atratus',
    102. 101: 'tusker',
    103. 102: 'echidna, spiny anteater, anteater',
    104. 103: 'platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus',
    105. 104: 'wallaby, brush kangaroo',
    106. 105: 'koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus',
    107. 106: 'wombat',
    108. 107: 'jellyfish',
    109. 108: 'sea anemone, anemone',
    110. 109: 'brain coral',
    111. 110: 'flatworm, platyhelminth',
    112. 111: 'nematode, nematode worm, roundworm',
    113. 112: 'conch',
    114. 113: 'snail',
    115. 114: 'slug',
    116. 115: 'sea slug, nudibranch',
    117. 116: 'chiton, coat-of-mail shell, sea cradle, polyplacophore',
    118. 117: 'chambered nautilus, pearly nautilus, nautilus',
    119. 118: 'Dungeness crab, Cancer magister',
    120. 119: 'rock crab, Cancer irroratus',
    121. 120: 'fiddler crab',
    122. 121: 'king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica',
    123. 122: 'American lobster, Northern lobster, Maine lobster, Homarus americanus',
    124. 123: 'spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish',
    125. 124: 'crayfish, crawfish, crawdad, crawdaddy',
    126. 125: 'hermit crab',
    127. 126: 'isopod',
    128. 127: 'white stork, Ciconia ciconia',
    129. 128: 'black stork, Ciconia nigra',
    130. 129: 'spoonbill',
    131. 130: 'flamingo',
    132. 131: 'little blue heron, Egretta caerulea',
    133. 132: 'American egret, great white heron, Egretta albus',
    134. 133: 'bittern',
    135. 134: 'crane',
    136. 135: 'limpkin, Aramus pictus',
    137. 136: 'European gallinule, Porphyrio porphyrio',
    138. 137: 'American coot, marsh hen, mud hen, water hen, Fulica americana',
    139. 138: 'bustard',
    140. 139: 'ruddy turnstone, Arenaria interpres',
    141. 140: 'red-backed sandpiper, dunlin, Erolia alpina',
    142. 141: 'redshank, Tringa totanus',
    143. 142: 'dowitcher',
    144. 143: 'oystercatcher, oyster catcher',
    145. 144: 'pelican',
    146. 145: 'king penguin, Aptenodytes patagonica',
    147. 146: 'albatross, mollymawk',
    148. 147: 'grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus',
    149. 148: 'killer whale, killer, orca, grampus, sea wolf, Orcinus orca',
    150. 149: 'dugong, Dugong dugon',
    151. 150: 'sea lion',
    152. 151: 'Chihuahua',
    153. 152: 'Japanese spaniel',
    154. 153: 'Maltese dog, Maltese terrier, Maltese',
    155. 154: 'Pekinese, Pekingese, Peke',
    156. 155: 'Shih-Tzu',
    157. 156: 'Blenheim spaniel',
    158. 157: 'papillon',
    159. 158: 'toy terrier',
    160. 159: 'Rhodesian ridgeback',
    161. 160: 'Afghan hound, Afghan',
    162. 161: 'basset, basset hound',
    163. 162: 'beagle',
    164. 163: 'bloodhound, sleuthhound',
    165. 164: 'bluetick',
    166. 165: 'black-and-tan coonhound',
    167. 166: 'Walker hound, Walker foxhound',
    168. 167: 'English foxhound',
    169. 168: 'redbone',
    170. 169: 'borzoi, Russian wolfhound',
    171. 170: 'Irish wolfhound',
    172. 171: 'Italian greyhound',
    173. 172: 'whippet',
    174. 173: 'Ibizan hound, Ibizan Podenco',
    175. 174: 'Norwegian elkhound, elkhound',
    176. 175: 'otterhound, otter hound',
    177. 176: 'Saluki, gazelle hound',
    178. 177: 'Scottish deerhound, deerhound',
    179. 178: 'Weimaraner',
    180. 179: 'Staffordshire bullterrier, Staffordshire bull terrier',
    181. 180: 'American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier',
    182. 181: 'Bedlington terrier',
    183. 182: 'Border terrier',
    184. 183: 'Kerry blue terrier',
    185. 184: 'Irish terrier',
    186. 185: 'Norfolk terrier',
    187. 186: 'Norwich terrier',
    188. 187: 'Yorkshire terrier',
    189. 188: 'wire-haired fox terrier',
    190. 189: 'Lakeland terrier',
    191. 190: 'Sealyham terrier, Sealyham',
    192. 191: 'Airedale, Airedale terrier',
    193. 192: 'cairn, cairn terrier',
    194. 193: 'Australian terrier',
    195. 194: 'Dandie Dinmont, Dandie Dinmont terrier',
    196. 195: 'Boston bull, Boston terrier',
    197. 196: 'miniature schnauzer',
    198. 197: 'giant schnauzer',
    199. 198: 'standard schnauzer',
    200. 199: 'Scotch terrier, Scottish terrier, Scottie',
    201. 200: 'Tibetan terrier, chrysanthemum dog',
    202. 201: 'silky terrier, Sydney silky',
    203. 202: 'soft-coated wheaten terrier',
    204. 203: 'West Highland white terrier',
    205. 204: 'Lhasa, Lhasa apso',
    206. 205: 'flat-coated retriever',
    207. 206: 'curly-coated retriever',
    208. 207: 'golden retriever',
    209. 208: 'Labrador retriever',
    210. 209: 'Chesapeake Bay retriever',
    211. 210: 'German short-haired pointer',
    212. 211: 'vizsla, Hungarian pointer',
    213. 212: 'English setter',
    214. 213: 'Irish setter, red setter',
    215. 214: 'Gordon setter',
    216. 215: 'Brittany spaniel',
    217. 216: 'clumber, clumber spaniel',
    218. 217: 'English springer, English springer spaniel',
    219. 218: 'Welsh springer spaniel',
    220. 219: 'cocker spaniel, English cocker spaniel, cocker',
    221. 220: 'Sussex spaniel',
    222. 221: 'Irish water spaniel',
    223. 222: 'kuvasz',
    224. 223: 'schipperke',
    225. 224: 'groenendael',
    226. 225: 'malinois',
    227. 226: 'briard',
    228. 227: 'kelpie',
    229. 228: 'komondor',
    230. 229: 'Old English sheepdog, bobtail',
    231. 230: 'Shetland sheepdog, Shetland sheep dog, Shetland',
    232. 231: 'collie',
    233. 232: 'Border collie',
    234. 233: 'Bouvier des Flandres, Bouviers des Flandres',
    235. 234: 'Rottweiler',
    236. 235: 'German shepherd, German shepherd dog, German police dog, alsatian',
    237. 236: 'Doberman, Doberman pinscher',
    238. 237: 'miniature pinscher',
    239. 238: 'Greater Swiss Mountain dog',
    240. 239: 'Bernese mountain dog',
    241. 240: 'Appenzeller',
    242. 241: 'EntleBucher',
    243. 242: 'boxer',
    244. 243: 'bull mastiff',
    245. 244: 'Tibetan mastiff',
    246. 245: 'French bulldog',
    247. 246: 'Great Dane',
    248. 247: 'Saint Bernard, St Bernard',
    249. 248: 'Eskimo dog, husky',
    250. 249: 'malamute, malemute, Alaskan malamute',
    251. 250: 'Siberian husky',
    252. 251: 'dalmatian, coach dog, carriage dog',
    253. 252: 'affenpinscher, monkey pinscher, monkey dog',
    254. 253: 'basenji',
    255. 254: 'pug, pug-dog',
    256. 255: 'Leonberg',
    257. 256: 'Newfoundland, Newfoundland dog',
    258. 257: 'Great Pyrenees',
    259. 258: 'Samoyed, Samoyede',
    260. 259: 'Pomeranian',
    261. 260: 'chow, chow chow',
    262. 261: 'keeshond',
    263. 262: 'Brabancon griffon',
    264. 263: 'Pembroke, Pembroke Welsh corgi',
    265. 264: 'Cardigan, Cardigan Welsh corgi',
    266. 265: 'toy poodle',
    267. 266: 'miniature poodle',
    268. 267: 'standard poodle',
    269. 268: 'Mexican hairless',
    270. 269: 'timber wolf, grey wolf, gray wolf, Canis lupus',
    271. 270: 'white wolf, Arctic wolf, Canis lupus tundrarum',
    272. 271: 'red wolf, maned wolf, Canis rufus, Canis niger',
    273. 272: 'coyote, prairie wolf, brush wolf, Canis latrans',
    274. 273: 'dingo, warrigal, warragal, Canis dingo',
    275. 274: 'dhole, Cuon alpinus',
    276. 275: 'African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus',
    277. 276: 'hyena, hyaena',
    278. 277: 'red fox, Vulpes vulpes',
    279. 278: 'kit fox, Vulpes macrotis',
    280. 279: 'Arctic fox, white fox, Alopex lagopus',
    281. 280: 'grey fox, gray fox, Urocyon cinereoargenteus',
    282. 281: 'tabby, tabby cat',
    283. 282: 'tiger cat',
    284. 283: 'Persian cat',
    285. 284: 'Siamese cat, Siamese',
    286. 285: 'Egyptian cat',
    287. 286: 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor',
    288. 287: 'lynx, catamount',
    289. 288: 'leopard, Panthera pardus',
    290. 289: 'snow leopard, ounce, Panthera uncia',
    291. 290: 'jaguar, panther, Panthera onca, Felis onca',
    292. 291: 'lion, king of beasts, Panthera leo',
    293. 292: 'tiger, Panthera tigris',
    294. 293: 'cheetah, chetah, Acinonyx jubatus',
    295. 294: 'brown bear, bruin, Ursus arctos',
    296. 295: 'American black bear, black bear, Ursus americanus, Euarctos americanus',
    297. 296: 'ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus',
    298. 297: 'sloth bear, Melursus ursinus, Ursus ursinus',
    299. 298: 'mongoose',
    300. 299: 'meerkat, mierkat',
    301. 300: 'tiger beetle',
    302. 301: 'ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle',
    303. 302: 'ground beetle, carabid beetle',
    304. 303: 'long-horned beetle, longicorn, longicorn beetle',
    305. 304: 'leaf beetle, chrysomelid',
    306. 305: 'dung beetle',
    307. 306: 'rhinoceros beetle',
    308. 307: 'weevil',
    309. 308: 'fly',
    310. 309: 'bee',
    311. 310: 'ant, emmet, pismire',
    312. 311: 'grasshopper, hopper',
    313. 312: 'cricket',
    314. 313: 'walking stick, walkingstick, stick insect',
    315. 314: 'cockroach, roach',
    316. 315: 'mantis, mantid',
    317. 316: 'cicada, cicala',
    318. 317: 'leafhopper',
    319. 318: 'lacewing, lacewing fly',
    320. 319: "dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk",
    321. 320: 'damselfly',
    322. 321: 'admiral',
    323. 322: 'ringlet, ringlet butterfly',
    324. 323: 'monarch, monarch butterfly, milkweed butterfly, Danaus plexippus',
    325. 324: 'cabbage butterfly',
    326. 325: 'sulphur butterfly, sulfur butterfly',
    327. 326: 'lycaenid, lycaenid butterfly',
    328. 327: 'starfish, sea star',
    329. 328: 'sea urchin',
    330. 329: 'sea cucumber, holothurian',
    331. 330: 'wood rabbit, cottontail, cottontail rabbit',
    332. 331: 'hare',
    333. 332: 'Angora, Angora rabbit',
    334. 333: 'hamster',
    335. 334: 'porcupine, hedgehog',
    336. 335: 'fox squirrel, eastern fox squirrel, Sciurus niger',
    337. 336: 'marmot',
    338. 337: 'beaver',
    339. 338: 'guinea pig, Cavia cobaya',
    340. 339: 'sorrel',
    341. 340: 'zebra',
    342. 341: 'hog, pig, grunter, squealer, Sus scrofa',
    343. 342: 'wild boar, boar, Sus scrofa',
    344. 343: 'warthog',
    345. 344: 'hippopotamus, hippo, river horse, Hippopotamus amphibius',
    346. 345: 'ox',
    347. 346: 'water buffalo, water ox, Asiatic buffalo, Bubalus bubalis',
    348. 347: 'bison',
    349. 348: 'ram, tup',
    350. 349: 'bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis',
    351. 350: 'ibex, Capra ibex',
    352. 351: 'hartebeest',
    353. 352: 'impala, Aepyceros melampus',
    354. 353: 'gazelle',
    355. 354: 'Arabian camel, dromedary, Camelus dromedarius',
    356. 355: 'llama',
    357. 356: 'weasel',
    358. 357: 'mink',
    359. 358: 'polecat, fitch, foulmart, foumart, Mustela putorius',
    360. 359: 'black-footed ferret, ferret, Mustela nigripes',
    361. 360: 'otter',
    362. 361: 'skunk, polecat, wood pussy',
    363. 362: 'badger',
    364. 363: 'armadillo',
    365. 364: 'three-toed sloth, ai, Bradypus tridactylus',
    366. 365: 'orangutan, orang, orangutang, Pongo pygmaeus',
    367. 366: 'gorilla, Gorilla gorilla',
    368. 367: 'chimpanzee, chimp, Pan troglodytes',
    369. 368: 'gibbon, Hylobates lar',
    370. 369: 'siamang, Hylobates syndactylus, Symphalangus syndactylus',
    371. 370: 'guenon, guenon monkey',
    372. 371: 'patas, hussar monkey, Erythrocebus patas',
    373. 372: 'baboon',
    374. 373: 'macaque',
    375. 374: 'langur',
    376. 375: 'colobus, colobus monkey',
    377. 376: 'proboscis monkey, Nasalis larvatus',
    378. 377: 'marmoset',
    379. 378: 'capuchin, ringtail, Cebus capucinus',
    380. 379: 'howler monkey, howler',
    381. 380: 'titi, titi monkey',
    382. 381: 'spider monkey, Ateles geoffroyi',
    383. 382: 'squirrel monkey, Saimiri sciureus',
    384. 383: 'Madagascar cat, ring-tailed lemur, Lemur catta',
    385. 384: 'indri, indris, Indri indri, Indri brevicaudatus',
    386. 385: 'Indian elephant, Elephas maximus',
    387. 386: 'African elephant, Loxodonta africana',
    388. 387: 'lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens',
    389. 388: 'giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca',
    390. 389: 'barracouta, snoek',
    391. 390: 'eel',
    392. 391: 'coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch',
    393. 392: 'rock beauty, Holocanthus tricolor',
    394. 393: 'anemone fish',
    395. 394: 'sturgeon',
    396. 395: 'gar, garfish, garpike, billfish, Lepisosteus osseus',
    397. 396: 'lionfish',
    398. 397: 'puffer, pufferfish, blowfish, globefish',
    399. 398: 'abacus',
    400. 399: 'abaya',
    401. 400: "academic gown, academic robe, judge's robe",
    402. 401: 'accordion, piano accordion, squeeze box',
    403. 402: 'acoustic guitar',
    404. 403: 'aircraft carrier, carrier, flattop, attack aircraft carrier',
    405. 404: 'airliner',
    406. 405: 'airship, dirigible',
    407. 406: 'altar',
    408. 407: 'ambulance',
    409. 408: 'amphibian, amphibious vehicle',
    410. 409: 'analog clock',
    411. 410: 'apiary, bee house',
    412. 411: 'apron',
    413. 412: 'ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin',
    414. 413: 'assault rifle, assault gun',
    415. 414: 'backpack, back pack, knapsack, packsack, rucksack, haversack',
    416. 415: 'bakery, bakeshop, bakehouse',
    417. 416: 'balance beam, beam',
    418. 417: 'balloon',
    419. 418: 'ballpoint, ballpoint pen, ballpen, Biro',
    420. 419: 'Band Aid',
    421. 420: 'banjo',
    422. 421: 'bannister, banister, balustrade, balusters, handrail',
    423. 422: 'barbell',
    424. 423: 'barber chair',
    425. 424: 'barbershop',
    426. 425: 'barn',
    427. 426: 'barometer',
    428. 427: 'barrel, cask',
    429. 428: 'barrow, garden cart, lawn cart, wheelbarrow',
    430. 429: 'baseball',
    431. 430: 'basketball',
    432. 431: 'bassinet',
    433. 432: 'bassoon',
    434. 433: 'bathing cap, swimming cap',
    435. 434: 'bath towel',
    436. 435: 'bathtub, bathing tub, bath, tub',
    437. 436: 'beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon',
    438. 437: 'beacon, lighthouse, beacon light, pharos',
    439. 438: 'beaker',
    440. 439: 'bearskin, busby, shako',
    441. 440: 'beer bottle',
    442. 441: 'beer glass',
    443. 442: 'bell cote, bell cot',
    444. 443: 'bib',
    445. 444: 'bicycle-built-for-two, tandem bicycle, tandem',
    446. 445: 'bikini, two-piece',
    447. 446: 'binder, ring-binder',
    448. 447: 'binoculars, field glasses, opera glasses',
    449. 448: 'birdhouse',
    450. 449: 'boathouse',
    451. 450: 'bobsled, bobsleigh, bob',
    452. 451: 'bolo tie, bolo, bola tie, bola',
    453. 452: 'bonnet, poke bonnet',
    454. 453: 'bookcase',
    455. 454: 'bookshop, bookstore, bookstall',
    456. 455: 'bottlecap',
    457. 456: 'bow',
    458. 457: 'bow tie, bow-tie, bowtie',
    459. 458: 'brass, memorial tablet, plaque',
    460. 459: 'brassiere, bra, bandeau',
    461. 460: 'breakwater, groin, groyne, mole, bulwark, seawall, jetty',
    462. 461: 'breastplate, aegis, egis',
    463. 462: 'broom',
    464. 463: 'bucket, pail',
    465. 464: 'buckle',
    466. 465: 'bulletproof vest',
    467. 466: 'bullet train, bullet',
    468. 467: 'butcher shop, meat market',
    469. 468: 'cab, hack, taxi, taxicab',
    470. 469: 'caldron, cauldron',
    471. 470: 'candle, taper, wax light',
    472. 471: 'cannon',
    473. 472: 'canoe',
    474. 473: 'can opener, tin opener',
    475. 474: 'cardigan',
    476. 475: 'car mirror',
    477. 476: 'carousel, carrousel, merry-go-round, roundabout, whirligig',
    478. 477: "carpenter's kit, tool kit",
    479. 478: 'carton',
    480. 479: 'car wheel',
    481. 480: 'cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM',
    482. 481: 'cassette',
    483. 482: 'cassette player',
    484. 483: 'castle',
    485. 484: 'catamaran',
    486. 485: 'CD player',
    487. 486: 'cello, violoncello',
    488. 487: 'cellular telephone, cellular phone, cellphone, cell, mobile phone',
    489. 488: 'chain',
    490. 489: 'chainlink fence',
    491. 490: 'chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour',
    492. 491: 'chain saw, chainsaw',
    493. 492: 'chest',
    494. 493: 'chiffonier, commode',
    495. 494: 'chime, bell, gong',
    496. 495: 'china cabinet, china closet',
    497. 496: 'Christmas stocking',
    498. 497: 'church, church building',
    499. 498: 'cinema, movie theater, movie theatre, movie house, picture palace',
    500. 499: 'cleaver, meat cleaver, chopper',
    501. 500: 'cliff dwelling',
    502. 501: 'cloak',
    503. 502: 'clog, geta, patten, sabot',
    504. 503: 'cocktail shaker',
    505. 504: 'coffee mug',
    506. 505: 'coffeepot',
    507. 506: 'coil, spiral, volute, whorl, helix',
    508. 507: 'combination lock',
    509. 508: 'computer keyboard, keypad',
    510. 509: 'confectionery, confectionary, candy store',
    511. 510: 'container ship, containership, container vessel',
    512. 511: 'convertible',
    513. 512: 'corkscrew, bottle screw',
    514. 513: 'cornet, horn, trumpet, trump',
    515. 514: 'cowboy boot',
    516. 515: 'cowboy hat, ten-gallon hat',
    517. 516: 'cradle',
    518. 517: 'crane',
    519. 518: 'crash helmet',
    520. 519: 'crate',
    521. 520: 'crib, cot',
    522. 521: 'Crock Pot',
    523. 522: 'croquet ball',
    524. 523: 'crutch',
    525. 524: 'cuirass',
    526. 525: 'dam, dike, dyke',
    527. 526: 'desk',
    528. 527: 'desktop computer',
    529. 528: 'dial telephone, dial phone',
    530. 529: 'diaper, nappy, napkin',
    531. 530: 'digital clock',
    532. 531: 'digital watch',
    533. 532: 'dining table, board',
    534. 533: 'dishrag, dishcloth',
    535. 534: 'dishwasher, dish washer, dishwashing machine',
    536. 535: 'disk brake, disc brake',
    537. 536: 'dock, dockage, docking facility',
    538. 537: 'dogsled, dog sled, dog sleigh',
    539. 538: 'dome',
    540. 539: 'doormat, welcome mat',
    541. 540: 'drilling platform, offshore rig',
    542. 541: 'drum, membranophone, tympan',
    543. 542: 'drumstick',
    544. 543: 'dumbbell',
    545. 544: 'Dutch oven',
    546. 545: 'electric fan, blower',
    547. 546: 'electric guitar',
    548. 547: 'electric locomotive',
    549. 548: 'entertainment center',
    550. 549: 'envelope',
    551. 550: 'espresso maker',
    552. 551: 'face powder',
    553. 552: 'feather boa, boa',
    554. 553: 'file, file cabinet, filing cabinet',
    555. 554: 'fireboat',
    556. 555: 'fire engine, fire truck',
    557. 556: 'fire screen, fireguard',
    558. 557: 'flagpole, flagstaff',
    559. 558: 'flute, transverse flute',
    560. 559: 'folding chair',
    561. 560: 'football helmet',
    562. 561: 'forklift',
    563. 562: 'fountain',
    564. 563: 'fountain pen',
    565. 564: 'four-poster',
    566. 565: 'freight car',
    567. 566: 'French horn, horn',
    568. 567: 'frying pan, frypan, skillet',
    569. 568: 'fur coat',
    570. 569: 'garbage truck, dustcart',
    571. 570: 'gasmask, respirator, gas helmet',
    572. 571: 'gas pump, gasoline pump, petrol pump, island dispenser',
    573. 572: 'goblet',
    574. 573: 'go-kart',
    575. 574: 'golf ball',
    576. 575: 'golfcart, golf cart',
    577. 576: 'gondola',
    578. 577: 'gong, tam-tam',
    579. 578: 'gown',
    580. 579: 'grand piano, grand',
    581. 580: 'greenhouse, nursery, glasshouse',
    582. 581: 'grille, radiator grille',
    583. 582: 'grocery store, grocery, food market, market',
    584. 583: 'guillotine',
    585. 584: 'hair slide',
    586. 585: 'hair spray',
    587. 586: 'half track',
    588. 587: 'hammer',
    589. 588: 'hamper',
    590. 589: 'hand blower, blow dryer, blow drier, hair dryer, hair drier',
    591. 590: 'hand-held computer, hand-held microcomputer',
    592. 591: 'handkerchief, hankie, hanky, hankey',
    593. 592: 'hard disc, hard disk, fixed disk',
    594. 593: 'harmonica, mouth organ, harp, mouth harp',
    595. 594: 'harp',
    596. 595: 'harvester, reaper',
    597. 596: 'hatchet',
    598. 597: 'holster',
    599. 598: 'home theater, home theatre',
    600. 599: 'honeycomb',
    601. 600: 'hook, claw',
    602. 601: 'hoopskirt, crinoline',
    603. 602: 'horizontal bar, high bar',
    604. 603: 'horse cart, horse-cart',
    605. 604: 'hourglass',
    606. 605: 'iPod',
    607. 606: 'iron, smoothing iron',
    608. 607: "jack-o'-lantern",
    609. 608: 'jean, blue jean, denim',
    610. 609: 'jeep, landrover',
    611. 610: 'jersey, T-shirt, tee shirt',
    612. 611: 'jigsaw puzzle',
    613. 612: 'jinrikisha, ricksha, rickshaw',
    614. 613: 'joystick',
    615. 614: 'kimono',
    616. 615: 'knee pad',
    617. 616: 'knot',
    618. 617: 'lab coat, laboratory coat',
    619. 618: 'ladle',
    620. 619: 'lampshade, lamp shade',
    621. 620: 'laptop, laptop computer',
    622. 621: 'lawn mower, mower',
    623. 622: 'lens cap, lens cover',
    624. 623: 'letter opener, paper knife, paperknife',
    625. 624: 'library',
    626. 625: 'lifeboat',
    627. 626: 'lighter, light, igniter, ignitor',
    628. 627: 'limousine, limo',
    629. 628: 'liner, ocean liner',
    630. 629: 'lipstick, lip rouge',
    631. 630: 'Loafer',
    632. 631: 'lotion',
    633. 632: 'loudspeaker, speaker, speaker unit, loudspeaker system, speaker system',
    634. 633: "loupe, jeweler's loupe",
    635. 634: 'lumbermill, sawmill',
    636. 635: 'magnetic compass',
    637. 636: 'mailbag, postbag',
    638. 637: 'mailbox, letter box',
    639. 638: 'maillot',
    640. 639: 'maillot, tank suit',
    641. 640: 'manhole cover',
    642. 641: 'maraca',
    643. 642: 'marimba, xylophone',
    644. 643: 'mask',
    645. 644: 'matchstick',
    646. 645: 'maypole',
    647. 646: 'maze, labyrinth',
    648. 647: 'measuring cup',
    649. 648: 'medicine chest, medicine cabinet',
    650. 649: 'megalith, megalithic structure',
    651. 650: 'microphone, mike',
    652. 651: 'microwave, microwave oven',
    653. 652: 'military uniform',
    654. 653: 'milk can',
    655. 654: 'minibus',
    656. 655: 'miniskirt, mini',
    657. 656: 'minivan',
    658. 657: 'missile',
    659. 658: 'mitten',
    660. 659: 'mixing bowl',
    661. 660: 'mobile home, manufactured home',
    662. 661: 'Model T',
    663. 662: 'modem',
    664. 663: 'monastery',
    665. 664: 'monitor',
    666. 665: 'moped',
    667. 666: 'mortar',
    668. 667: 'mortarboard',
    669. 668: 'mosque',
    670. 669: 'mosquito net',
    671. 670: 'motor scooter, scooter',
    672. 671: 'mountain bike, all-terrain bike, off-roader',
    673. 672: 'mountain tent',
    674. 673: 'mouse, computer mouse',
    675. 674: 'mousetrap',
    676. 675: 'moving van',
    677. 676: 'muzzle',
    678. 677: 'nail',
    679. 678: 'neck brace',
    680. 679: 'necklace',
    681. 680: 'nipple',
    682. 681: 'notebook, notebook computer',
    683. 682: 'obelisk',
    684. 683: 'oboe, hautboy, hautbois',
    685. 684: 'ocarina, sweet potato',
    686. 685: 'odometer, hodometer, mileometer, milometer',
    687. 686: 'oil filter',
    688. 687: 'organ, pipe organ',
    689. 688: 'oscilloscope, scope, cathode-ray oscilloscope, CRO',
    690. 689: 'overskirt',
    691. 690: 'oxcart',
    692. 691: 'oxygen mask',
    693. 692: 'packet',
    694. 693: 'paddle, boat paddle',
    695. 694: 'paddlewheel, paddle wheel',
    696. 695: 'padlock',
    697. 696: 'paintbrush',
    698. 697: "pajama, pyjama, pj's, jammies",
    699. 698: 'palace',
    700. 699: 'panpipe, pandean pipe, syrinx',
    701. 700: 'paper towel',
    702. 701: 'parachute, chute',
    703. 702: 'parallel bars, bars',
    704. 703: 'park bench',
    705. 704: 'parking meter',
    706. 705: 'passenger car, coach, carriage',
    707. 706: 'patio, terrace',
    708. 707: 'pay-phone, pay-station',
    709. 708: 'pedestal, plinth, footstall',
    710. 709: 'pencil box, pencil case',
    711. 710: 'pencil sharpener',
    712. 711: 'perfume, essence',
    713. 712: 'Petri dish',
    714. 713: 'photocopier',
    715. 714: 'pick, plectrum, plectron',
    716. 715: 'pickelhaube',
    717. 716: 'picket fence, paling',
    718. 717: 'pickup, pickup truck',
    719. 718: 'pier',
    720. 719: 'piggy bank, penny bank',
    721. 720: 'pill bottle',
    722. 721: 'pillow',
    723. 722: 'ping-pong ball',
    724. 723: 'pinwheel',
    725. 724: 'pirate, pirate ship',
    726. 725: 'pitcher, ewer',
    727. 726: "plane, carpenter's plane, woodworking plane",
    728. 727: 'planetarium',
    729. 728: 'plastic bag',
    730. 729: 'plate rack',
    731. 730: 'plow, plough',
    732. 731: "plunger, plumber's helper",
    733. 732: 'Polaroid camera, Polaroid Land camera',
    734. 733: 'pole',
    735. 734: 'police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria',
    736. 735: 'poncho',
    737. 736: 'pool table, billiard table, snooker table',
    738. 737: 'pop bottle, soda bottle',
    739. 738: 'pot, flowerpot',
    740. 739: "potter's wheel",
    741. 740: 'power drill',
    742. 741: 'prayer rug, prayer mat',
    743. 742: 'printer',
    744. 743: 'prison, prison house',
    745. 744: 'projectile, missile',
    746. 745: 'projector',
    747. 746: 'puck, hockey puck',
    748. 747: 'punching bag, punch bag, punching ball, punchball',
    749. 748: 'purse',
    750. 749: 'quill, quill pen',
    751. 750: 'quilt, comforter, comfort, puff',
    752. 751: 'racer, race car, racing car',
    753. 752: 'racket, racquet',
    754. 753: 'radiator',
    755. 754: 'radio, wireless',
    756. 755: 'radio telescope, radio reflector',
    757. 756: 'rain barrel',
    758. 757: 'recreational vehicle, RV, R.V.',
    759. 758: 'reel',
    760. 759: 'reflex camera',
    761. 760: 'refrigerator, icebox',
    762. 761: 'remote control, remote',
    763. 762: 'restaurant, eating house, eating place, eatery',
    764. 763: 'revolver, six-gun, six-shooter',
    765. 764: 'rifle',
    766. 765: 'rocking chair, rocker',
    767. 766: 'rotisserie',
    768. 767: 'rubber eraser, rubber, pencil eraser',
    769. 768: 'rugby ball',
    770. 769: 'rule, ruler',
    771. 770: 'running shoe',
    772. 771: 'safe',
    773. 772: 'safety pin',
    774. 773: 'saltshaker, salt shaker',
    775. 774: 'sandal',
    776. 775: 'sarong',
    777. 776: 'sax, saxophone',
    778. 777: 'scabbard',
    779. 778: 'scale, weighing machine',
    780. 779: 'school bus',
    781. 780: 'schooner',
    782. 781: 'scoreboard',
    783. 782: 'screen, CRT screen',
    784. 783: 'screw',
    785. 784: 'screwdriver',
    786. 785: 'seat belt, seatbelt',
    787. 786: 'sewing machine',
    788. 787: 'shield, buckler',
    789. 788: 'shoe shop, shoe-shop, shoe store',
    790. 789: 'shoji',
    791. 790: 'shopping basket',
    792. 791: 'shopping cart',
    793. 792: 'shovel',
    794. 793: 'shower cap',
    795. 794: 'shower curtain',
    796. 795: 'ski',
    797. 796: 'ski mask',
    798. 797: 'sleeping bag',
    799. 798: 'slide rule, slipstick',
    800. 799: 'sliding door',
    801. 800: 'slot, one-armed bandit',
    802. 801: 'snorkel',
    803. 802: 'snowmobile',
    804. 803: 'snowplow, snowplough',
    805. 804: 'soap dispenser',
    806. 805: 'soccer ball',
    807. 806: 'sock',
    808. 807: 'solar dish, solar collector, solar furnace',
    809. 808: 'sombrero',
    810. 809: 'soup bowl',
    811. 810: 'space bar',
    812. 811: 'space heater',
    813. 812: 'space shuttle',
    814. 813: 'spatula',
    815. 814: 'speedboat',
    816. 815: "spider web, spider's web",
    817. 816: 'spindle',
    818. 817: 'sports car, sport car',
    819. 818: 'spotlight, spot',
    820. 819: 'stage',
    821. 820: 'steam locomotive',
    822. 821: 'steel arch bridge',
    823. 822: 'steel drum',
    824. 823: 'stethoscope',
    825. 824: 'stole',
    826. 825: 'stone wall',
    827. 826: 'stopwatch, stop watch',
    828. 827: 'stove',
    829. 828: 'strainer',
    830. 829: 'streetcar, tram, tramcar, trolley, trolley car',
    831. 830: 'stretcher',
    832. 831: 'studio couch, day bed',
    833. 832: 'stupa, tope',
    834. 833: 'submarine, pigboat, sub, U-boat',
    835. 834: 'suit, suit of clothes',
    836. 835: 'sundial',
    837. 836: 'sunglass',
    838. 837: 'sunglasses, dark glasses, shades',
    839. 838: 'sunscreen, sunblock, sun blocker',
    840. 839: 'suspension bridge',
    841. 840: 'swab, swob, mop',
    842. 841: 'sweatshirt',
    843. 842: 'swimming trunks, bathing trunks',
    844. 843: 'swing',
    845. 844: 'switch, electric switch, electrical switch',
    846. 845: 'syringe',
    847. 846: 'table lamp',
    848. 847: 'tank, army tank, armored combat vehicle, armoured combat vehicle',
    849. 848: 'tape player',
    850. 849: 'teapot',
    851. 850: 'teddy, teddy bear',
    852. 851: 'television, television system',
    853. 852: 'tennis ball',
    854. 853: 'thatch, thatched roof',
    855. 854: 'theater curtain, theatre curtain',
    856. 855: 'thimble',
    857. 856: 'thresher, thrasher, threshing machine',
    858. 857: 'throne',
    859. 858: 'tile roof',
    860. 859: 'toaster',
    861. 860: 'tobacco shop, tobacconist shop, tobacconist',
    862. 861: 'toilet seat',
    863. 862: 'torch',
    864. 863: 'totem pole',
    865. 864: 'tow truck, tow car, wrecker',
    866. 865: 'toyshop',
    867. 866: 'tractor',
    868. 867: 'trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi',
    869. 868: 'tray',
    870. 869: 'trench coat',
    871. 870: 'tricycle, trike, velocipede',
    872. 871: 'trimaran',
    873. 872: 'tripod',
    874. 873: 'triumphal arch',
    875. 874: 'trolleybus, trolley coach, trackless trolley',
    876. 875: 'trombone',
    877. 876: 'tub, vat',
    878. 877: 'turnstile',
    879. 878: 'typewriter keyboard',
    880. 879: 'umbrella',
    881. 880: 'unicycle, monocycle',
    882. 881: 'upright, upright piano',
    883. 882: 'vacuum, vacuum cleaner',
    884. 883: 'vase',
    885. 884: 'vault',
    886. 885: 'velvet',
    887. 886: 'vending machine',
    888. 887: 'vestment',
    889. 888: 'viaduct',
    890. 889: 'violin, fiddle',
    891. 890: 'volleyball',
    892. 891: 'waffle iron',
    893. 892: 'wall clock',
    894. 893: 'wallet, billfold, notecase, pocketbook',
    895. 894: 'wardrobe, closet, press',
    896. 895: 'warplane, military plane',
    897. 896: 'washbasin, handbasin, washbowl, lavabo, wash-hand basin',
    898. 897: 'washer, automatic washer, washing machine',
    899. 898: 'water bottle',
    900. 899: 'water jug',
    901. 900: 'water tower',
    902. 901: 'whiskey jug',
    903. 902: 'whistle',
    904. 903: 'wig',
    905. 904: 'window screen',
    906. 905: 'window shade',
    907. 906: 'Windsor tie',
    908. 907: 'wine bottle',
    909. 908: 'wing',
    910. 909: 'wok',
    911. 910: 'wooden spoon',
    912. 911: 'wool, woolen, woollen',
    913. 912: 'worm fence, snake fence, snake-rail fence, Virginia fence',
    914. 913: 'wreck',
    915. 914: 'yawl',
    916. 915: 'yurt',
    917. 916: 'web site, website, internet site, site',
    918. 917: 'comic book',
    919. 918: 'crossword puzzle, crossword',
    920. 919: 'street sign',
    921. 920: 'traffic light, traffic signal, stoplight',
    922. 921: 'book jacket, dust cover, dust jacket, dust wrapper',
    923. 922: 'menu',
    924. 923: 'plate',
    925. 924: 'guacamole',
    926. 925: 'consomme',
    927. 926: 'hot pot, hotpot',
    928. 927: 'trifle',
    929. 928: 'ice cream, icecream',
    930. 929: 'ice lolly, lolly, lollipop, popsicle',
    931. 930: 'French loaf',
    932. 931: 'bagel, beigel',
    933. 932: 'pretzel',
    934. 933: 'cheeseburger',
    935. 934: 'hotdog, hot dog, red hot',
    936. 935: 'mashed potato',
    937. 936: 'head cabbage',
    938. 937: 'broccoli',
    939. 938: 'cauliflower',
    940. 939: 'zucchini, courgette',
    941. 940: 'spaghetti squash',
    942. 941: 'acorn squash',
    943. 942: 'butternut squash',
    944. 943: 'cucumber, cuke',
    945. 944: 'artichoke, globe artichoke',
    946. 945: 'bell pepper',
    947. 946: 'cardoon',
    948. 947: 'mushroom',
    949. 948: 'Granny Smith',
    950. 949: 'strawberry',
    951. 950: 'orange',
    952. 951: 'lemon',
    953. 952: 'fig',
    954. 953: 'pineapple, ananas',
    955. 954: 'banana',
    956. 955: 'jackfruit, jak, jack',
    957. 956: 'custard apple',
    958. 957: 'pomegranate',
    959. 958: 'hay',
    960. 959: 'carbonara',
    961. 960: 'chocolate sauce, chocolate syrup',
    962. 961: 'dough',
    963. 962: 'meat loaf, meatloaf',
    964. 963: 'pizza, pizza pie',
    965. 964: 'potpie',
    966. 965: 'burrito',
    967. 966: 'red wine',
    968. 967: 'espresso',
    969. 968: 'cup',
    970. 969: 'eggnog',
    971. 970: 'alp',
    972. 971: 'bubble',
    973. 972: 'cliff, drop, drop-off',
    974. 973: 'coral reef',
    975. 974: 'geyser',
    976. 975: 'lakeside, lakeshore',
    977. 976: 'promontory, headland, head, foreland',
    978. 977: 'sandbar, sand bar',
    979. 978: 'seashore, coast, seacoast, sea-coast',
    980. 979: 'valley, vale',
    981. 980: 'volcano',
    982. 981: 'ballplayer, baseball player',
    983. 982: 'groom, bridegroom',
    984. 983: 'scuba diver',
    985. 984: 'rapeseed',
    986. 985: 'daisy',
    987. 986: "yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum",
    988. 987: 'corn',
    989. 988: 'acorn',
    990. 989: 'hip, rose hip, rosehip',
    991. 990: 'buckeye, horse chestnut, conker',
    992. 991: 'coral fungus',
    993. 992: 'agaric',
    994. 993: 'gyromitra',
    995. 994: 'stinkhorn, carrion fungus',
    996. 995: 'earthstar',
    997. 996: 'hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa',
    998. 997: 'bolete',
    999. 998: 'ear, spike, capitulum',
    1000. 999: 'toilet tissue, toilet paper, bathroom tissue'}

    运行结果

    1.LeNet5

    1. basenet: lenet5 (image size: 32 * 32 * 3)
    2. dataset: cifar
    3. len(dataset): 50000, iter_size: 1562
    4. batch_size: 32
    5. optim: SGD
    6. scheduler: MultiStepLR
    7. milestones: [15, 20, 30]
    8. weight_decay: 1e-4
    9. gamma: 0.1
    10. momentum: 0.9
    11. lr: 0.01
    12. epoch: 30
    epochtimestop1 acc (%)top5 acc (%)
    00h0min23s50.0093.75
    10h0min21s62.5096.88
    20h0min24s65.6296.88
    30h0min21s53.1296.88
    ............
    290h0min23s75.00100.00

    共计

    epochstimesavg top1 acc (%)avg top5 acc (%)
    300h11m44s62.20853333333333595.97033333333

    2.AlexNet

    1. basenet: alexnet (image size: 224 * 224 * 3)
    2. dataset: cifar
    3. len(dataset): 50000, iter_size: 1562
    4. batch_size: 32
    5. optim: SGD
    6. scheduler: MultiStepLR
    7. milestones: [15, 20, 30]
    8. weight_decay: 1e-4
    9. gamma: 0.1
    10. momentum: 0.9
    11. lr:0.01
    12. epoch: 30
    epochtimestop1 acc (%)top5 acc (%)
    00h0min45s50.0090.62
    10h0min44s62.5093.75
    20h0min46s68.7596.88
    30h0min44s62.50100.00
    ............
    290h0min42s100.00100.00

    共计

    epochstimesavg top1 acc (%)avg top5 acc (%)
    300h22m44s86.2745333333333498.99946666666666

    3.VGG

    1. basenet: vgg16 (image size: 224 * 224 * 3)
    2. dataset: cifar
    3. len(dataset): 50000, iter_size: 1562
    4. batch_size: 32
    5. optim: SGD
    6. scheduler: MultiStepLR
    7. milestones: [15, 20, 30]
    8. weight_decay: 1e-4
    9. gamma: 0.1
    10. momentum: 0.9
    11. lr:0.01
    12. epoch: 30
    epochtimestop1 acc (%)top5 acc (%)
    00h2min46s25.0071.88
    10h2min45s53.1287.50
    20h2min44s40.6296.88
    30h2min42s34.3890.62
    ............
    290h2min44s100.00100.00

    共计

    epochstimesavg top1 acc (%)avg top5 acc (%)
    301h23m43s76.5560666666666796.441

    4.ResNet

    1. basenet: resnet18
    2. dataset: ImageNet
    3. image size: 224 * 224 * 3 (可自定义)
    4. batch_size: 32
    5. optim: SGD
    6. scheduler: MultiStepLR
    7. milestones: [15, 20, 30]
    8. weight_decay: 1e-4
    9. gamma: 0.1
    10. momentum: 0.9
    11. lr:0.001
    12. epoch: 30
    epochtimestop1 acc (%)top5 acc (%)
    04h22min38s28.1243.75
    13h59min35s34.3859.38
    23h58min0s65.6284.38
    33h48min56s46.8875.00
    43h54min36s53.1275.00
    53h49min35s56.2571.88
    ............

    未完...

  • 相关阅读:
    WSL2 安装与使用
    Go 封装http请求包Get、Post
    什么是云手机?云手机有什么用?
    MySQL索引
    NPDP产品经理知识(产品创新种的市场调研)
    Python爬虫编程思想(154):使用Scrapy处理登录页面
    整理指定文件夹下的所有文件,以类树状图显示并生成对应超链接
    springboot毕设项目个人博客的设计与实现i03nz(java+VUE+Mybatis+Maven+Mysql)
    震惊--Nginx的map指令还能这样用
    认识matlab
  • 原文地址:https://blog.csdn.net/XiaoyYidiaodiao/article/details/125505058