【课程作业经验】使用NPU进行MindSpore模型训练

准备工作

使用MindSpore进行模型训练需要做以下的准备工作

  1. 训练的网络模型
  2. 训练数据以及数据处理
  3. 训练回调函数
  4. 启动训练的python脚本

网络模型

MindSpore提供了一个MindVision的开源网络工具箱,其中包含了很多的网络结构以及预训练数据,但在云端的NPU环境中 (当时使用的是mindspore_1.5.1-cann_5.0.3-py_3.7-euler_2.8.3-aarch64) ,会直接报错,因此需要我们自己编写网络结构。

编写网络结构可以参考MindSpore的官网,以下是一个简单的ResNet18的网络结构。
编写网络结构的要点在于,在 __init__ 方法中定义网络中不同层的结构,在 construct 方法中设置不同层之间的连接关系。

import mindspore.nn as nn

class ResBlock2RT(nn.Cell):
    def __init__(self, in_channel):
        super(ResBlock2RT, self).__init__()
        self.seq = nn.SequentialCell(
            [
                nn.Conv2d(in_channel, in_channel, kernel_size=3, stride=1),
                nn.BatchNorm2d(in_channel),
                nn.ReLU(),
                nn.Conv2d(in_channel, in_channel, kernel_size=3, stride=1),
                nn.BatchNorm2d(in_channel),
            ])
        self.relu = nn.ReLU()

    def construct(self, x):
        x = self.seq(x) + x
        return self.relu(x)

class ResBlock2DS(nn.Cell):
    def __init__(self, in_channel, out_channel, stride):
        super(ResBlock2DS, self).__init__()
        self.seq = nn.SequentialCell(
            [
                nn.Conv2d(in_channel, out_channel, 3, stride=stride),
                nn.BatchNorm2d(out_channel),
                nn.ReLU(),
                nn.Conv2d(out_channel, out_channel, 3, stride=1),
                nn.BatchNorm2d(out_channel),
            ])
        self.shortup = nn.SequentialCell(
            [
                nn.Conv2d(in_channel, out_channel, 1, stride=stride),
                nn.BatchNorm2d(out_channel),
            ])
        self.relu = nn.ReLU()

    def construct(self, x):
        y = self.seq(x) + self.shortup(x)
        return self.relu(y)

class ResNet18(nn.Cell):
    def __init__(self, class_num=10, input_size=224):
        super(ResNet18, self).__init__()
        self.PreProcess = nn.SequentialCell([
            nn.Conv2d(3, 64, 7, stride=2),
            nn.BatchNorm2d(64),
            nn.MaxPool2d(kernel_size=3, stride=2, pad_mode='same'),
        ])
        self.ResBlock = nn.SequentialCell([
            ResBlock2RT(64),
            ResBlock2RT(64),
            ResBlock2DS(64, 128, 2),
            ResBlock2RT(128),
            ResBlock2DS(128, 256, 2),
            ResBlock2RT(256),
           
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值