文章目录
昇思MindSpore快速入门
简单的深度学习模型Pipeline
1、处理数据集
python
import mindspore
from mindspore import nn
from mindspore.dataset import vision, transforms
from mindspore.dataset import MnistDataset
从from mindspore.dataset import MnistDataset
中可以看到本节快速入门课程选择的是最经典的Mnist手写数字识别,带领新用户快速熟悉基于Mindspore玩转深度学习的完整Pipeline.
还是按照官方文档走一遍流程吧,没有MnistDataset可以通过mindspore的华为云镜像链接下载:
python
# Download data from open datasets
from download import download
url = "https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/" \
"notebook/datasets/MNIST_Data.zip"
path = download(url, "./", kind="zip", replace=True)
bash
Downloading data from https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/notebook/datasets/MNIST_Data.zip (10.3 MB)
file_sizes: 100%|███████████████████████████| 10.8M/10.8M [00:00<00:00, 128MB/s]
Extracting zip file...
Successfully downloaded / unzipped to ./
MNIST数据集目录结构如下:
MNIST_Data
└── train
├── train-images-idx3-ubyte (60000个训练图片)
├── train-labels-idx1-ubyte (60000个训练标签)
└── test
├── t10k-images-idx3-ubyte (10000个测试图片)
├── t10k-labels-idx1-ubyte (10000个测试标签)
数据下载完成后,获得数据集对象。
导入train_dataset和test_dataset路径:
python
train_dataset = MnistDataset('MNIST_Data/train')
test_dataset = MnistDataset('MNIST_Data/test')
打印数据集中包含的数据列名,查看mnist_xxx.ubyte文件内有哪些信息:
python
print(train_dataset.get_col_names())
# print_log:
# ['image', 'label']
显然包含的是图像和标签两列数据。
2、MindSpore 数据预处理Pipeline
MindSpore通过指定map、batch、shuffle等操作的datapipe函数实现dataset的数据处理流水线(Data Processing Pipeline),
类似于Pytorch中的Dataloader;
python
def datapipe(dataset, batch_size):
image_transforms = [
vision.Rescale(1.0 / 255.0, 0), # 灰度值归一化
vision.Normalize(mean=(0.1307,), std=(0.3081,)), # 标准化处理,减少后续训练时出现梯度消失或爆炸的可能性
vision.HWC2CHW() # 转化为Channel, Hight, Width格式
]
label_transform = transforms.TypeCast(mindspore.int32)
dataset = dataset.map(image_transforms, 'image')
dataset = dataset.map(label_transform, 'label')
dataset = dataset.batch(batch_size)
return dataset
通过调用datapipe生成train_dataset, test_dataset:
python
# Map vision transforms and batch dataset
train_dataset = datapipe(train_dataset, 64)
test_dataset = datapipe(test_dataset, 64)
可使用create_tuple_iterator 或 create_dict_iterator 对数据集进行迭代访问,查看数据和标签的shape和datatype.
python
for image, label in test_dataset.create_tuple_iterator():
print(f"Shape of image [N, C, H, W]: {image.shape} {image.dtype}")
print(f"Shape of label: {label.shape} {label.dtype}")
break
# print_log:
# Shape of image [N, C, H, W]: (64, 1, 28, 28) Float32
# Shape of label: (64,) Int32
for data in test_dataset.create_dict_iterator():
print(f"Shape of image [N, C, H, W]: {data['image'].shape} {data['image'].dtype}")
print(f"Shape of label: {data['label'].shape} {data['label'].dtype}")
break
# print_log:
# Shape of image [N, C, H, W]: (64, 1, 28, 28) Float32
# Shape of label: (64,) Int32
3、网络构建
来到核心的网络构建部分:
和torch.nn的使用方法类似,mindspore.nn类是构建所有网络的基类,也是网络的基本单元。当用户需要自定义网络时,可以继承nn.Cell类,并重写__init__方法和construct方法。__init__包含所有网络层的定义,construct中包含数据(Tensor)的变换过程:
python
# Define model
class Network(nn.Cell):
def __init__(self):
super().__init__()
self.flatten = nn.Flatten() # 从mindspore.nn导入Flatten()
self.dense_relu_sequential = nn.SequentialCell( # 创建MLP序贯模型,Dense层之间通过ReLU激活函数连接
nn.Dense(28*28, 512), # 输入维度是28*28=784个通道数(mnist一张图片是28*28),输出通道为512
nn.ReLU(), #
nn.Dense(512, 512),
nn.ReLU(),
nn.Dense(512, 10) # 输入维度是512,输出维度为10,因为数字分类0-9总共10个数用于十分类.
)
def construct(self, x): # 构建前向传播
x = self.flatten(x)
logits = self.dense_relu_sequential(x)
return logits
model = Network()
print(model) # 打印模型
# print_log
# Network<
# (flatten): Flatten<>
# (dense_relu_sequential): SequentialCell<
# (0): Dense<input_channels=784, output_channels=512, has_bias=True>
# (1): ReLU<>
# (2): Dense<input_channels=512, output_channels=512, has_bias=True>
# (3): ReLU<>
# (4): Dense<input_channels=512, output_channels=10, has_bias=True>
# >
# >
模型中,引入ReLU激活函数非常关键,因为如果没有非线性激活函数,无论网络有多少层,最终网络的输出都只能是输入的线性函数,这限制了网络的表达能力,通过激活函数可以为网络添加非线性的学习能力,并缓解梯度消失,具体原理可以在网上找到很多底层、详细的文本 or 视频教程,这里不再赘述。
4、模型训练
在模型训练中,一个完整的训练过程(step)需要实现以下三步:
- 正向计算(前向传播):模型预测结果(logits),并与正确标签(label)求预测损失(loss)。
- 反向传播:利用自动微分机制,自动求模型参数(parameters)对于loss的梯度(gradients)。
- 参数优化:将梯度更新到参数上。
python
# Instantiate loss function and optimizer,定义损失函数和优化器
loss_fn = nn.CrossEntropyLoss()
optimizer = nn.SGD(model.trainable_params(), 1e-2) # 采用随机梯度下降SGD进行最优化,学习率为0.02
# 1. Define forward function,定义前向传播函数
def forward_fn(data, label):
logits = model(data)
loss = loss_fn(logits, label)
return loss, logits
# 2. Get gradient function,获取针对某些参数求解的梯度
grad_fn = mindspore.value_and_grad(forward_fn, None, optimizer.parameters, has_aux=True)
# 3. Define function of one-step training
def train_step(data, label):
(loss, _), grads = grad_fn(data, label)
optimizer(grads)
return loss
def train(model, dataset):
size = dataset.get_dataset_size()
model.set_train()
for batch, (data, label) in enumerate(dataset.create_tuple_iterator()):
loss = train_step(data, label)
if batch % 100 == 0:
loss, current = loss.asnumpy(), batch
print(f"loss: {loss:>7f} [{current:>3d}/{size:>3d}]")
除此之外,我们还要评估模型性能:
python
def test(model, dataset, loss_fn):
num_batches = dataset.get_dataset_size()
model.set_train(False)
total, test_loss, correct = 0, 0, 0
for data, label in dataset.create_tuple_iterator():
pred = model(data)
total += len(data)
test_loss += loss_fn(pred, label).asnumpy()
correct += (pred.argmax(1) == label).asnumpy().sum()
test_loss /= num_batches
correct /= total
print(f"Test: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
训练过程需多次迭代数据集,一次完整的迭代称为一轮(epoch);
在每一轮,遍历训练集进行训练,结束后使用测试集进行预测,评估模型训练的效果;
打印每一轮的loss值和预测准确率(Accuracy),可以看到loss在不断下降,Accuracy在不断提高。
python
epochs = 3
for t in range(epochs):
print(f"Epoch {t+1}\n-------------------------------")
train(model, train_dataset)
test(model, test_dataset, loss_fn)
print("Done!")
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),'Wayn_Fan-sail')
# print_log
Epoch 1
-------------------------------
loss: 2.306374 [ 0/938]
loss: 1.686383 [100/938]
loss: 0.893529 [200/938]
loss: 0.670526 [300/938]
loss: 0.719987 [400/938]
loss: 0.421256 [500/938]
loss: 0.425218 [600/938]
loss: 0.260933 [700/938]
loss: 0.235322 [800/938]
loss: 0.320854 [900/938]
Test:
Accuracy: 90.7%, Avg loss: 0.319222
Epoch 2
-------------------------------
loss: 0.321319 [ 0/938]
loss: 0.388391 [100/938]
loss: 0.193415 [200/938]
loss: 0.314022 [300/938]
loss: 0.137470 [400/938]
loss: 0.206924 [500/938]
loss: 0.220165 [600/938]
loss: 0.384074 [700/938]
loss: 0.266177 [800/938]
loss: 0.327695 [900/938]
Test:
Accuracy: 92.8%, Avg loss: 0.249175
Epoch 3
-------------------------------
loss: 0.365470 [ 0/938]
loss: 0.207864 [100/938]
loss: 0.340846 [200/938]
loss: 0.397548 [300/938]
loss: 0.217730 [400/938]
loss: 0.115968 [500/938]
loss: 0.230911 [600/938]
loss: 0.300184 [700/938]
loss: 0.429506 [800/938]
loss: 0.448235 [900/938]
Test:
Accuracy: 93.6%, Avg loss: 0.215008
Done!
2024-06-27 11:49:50 Wayn_Fan-sail
5、保存模型
python
# Save checkpoint
mindspore.save_checkpoint(model, "model.ckpt")
print("Saved Model to model.ckpt")
通过mindspore的save_checkpoint将模型训练好的参数保存进.ckpt文件,方便下一次训练或推理使用。
6、加载模型
python
# Instantiate a random initialized model
model = Network() # 重新实例化模型对象,构造模型
# Load checkpoint and load parameter to model
param_dict = mindspore.load_checkpoint("model.ckpt") # 加载模型参数,并将其加载至模型上
param_not_load, _ = mindspore.load_param_into_net(model, param_dict)
print(param_not_load)
7、模型推理
python
model.set_train(False)
for data, label in test_dataset:
pred = model(data)
predicted = pred.argmax(1)
print(f'Predicted: "{predicted[:10]}", Actual: "{label[:10]}"')
break
加载后的模型可以直接用于预测推理。