MindSpore:【课程作业经验】使用NPU进行MindSpore模型训练
准备工作
使用MindSpore进行模型训练需要做以下的准备工作
- 训练的网络模型
- 训练数据以及数据处理
- 训练回调函数
- 启动训练的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