赞
踩
01-基本介绍
昇思MindSpore介绍
昇思MindSpore是一个全场景深度学习框架,旨在实现易开发、高效执行、全场景统一部署三大目标。
总体架构:
02-快速入门
通过MindSpore的API实现简单的深度学习模型
1、导入minspore库
- import mindspore
- from mindspore import nn
- from mindspore.dataset import vision, transforms
- from mindspore.dataset import MnistDataset
2、通过download下载数据集,使用以下命令进行安装
pip install download
然后使用一下命令行下载数据集
- # 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)
执行结果为:
数据集目录为:
获取数据对象,并打印数据集中包含的数据列名,用于dataset的预处理。
- train_dataset = MnistDataset('MNIST_Data/train')
- test_dataset = MnistDataset('MNIST_Data/test')
-
- print(train_dataset.get_col_names())
得知其中含有image和label两个标签。
MindSpore的dataset使用数据处理流水线(Data Processing Pipeline),需指定map、batch、shuffle等操作。这里我们使用map对图像数据及标签进行变换处理,然后将处理好的数据集打包为大小为64的batch。
可使用create_tuple_iterator 或create_dict_iterator对数据集进行迭代访问,查看数据和标签的shape和datatype。
- def datapipe(dataset, batch_size):
- image_transforms = [
- vision.Rescale(1.0 / 255.0, 0),
- vision.Normalize(mean=(0.1307,), std=(0.3081,)),
- vision.HWC2CHW()
- ]
- 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
-
- # Map vision transforms and batch dataset
- train_dataset = datapipe(train_dataset, 64)
- test_dataset = datapipe(test_dataset, 64)
-
- 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
-
- 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
3、网络构建
mindspore.nn类是构建所有网络的基类,也是网络的基本单元。当用户需要自定义网络时,可以继承nn.Cell类,并重写__init__方法和construct方法。__init__包含所有网络层的定义,construct中包含数据Tensor的变换过程。
- # Define model
- class Network(nn.Cell):
- def __init__(self):
- super().__init__()
- self.flatten = nn.Flatten()
- self.dense_relu_sequential = nn.SequentialCell(
- nn.Dense(28*28, 512),
- nn.ReLU(),
- nn.Dense(512, 512),
- nn.ReLU(),
- nn.Dense(512, 10)
- )
-
- def construct(self, x):
- x = self.flatten(x)
- logits = self.dense_relu_sequential(x)
- return logits
-
- model = Network()
- print(model)
执行结果为:
4、模型训练
在模型训练中,一个完整的训练过程(step)需要实现以下三步:
MindSpore使用函数式自动微分机制,因此针对上述步骤需要实现:
- # Instantiate loss function and optimizer
- loss_fn = nn.CrossEntropyLoss()
- optimizer = nn.SGD(model.trainable_params(), 1e-2)
-
- # 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}]")
定义测试函数,用于评估模型的性能
- 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在不断提高。
- 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!")
在此设置三轮,3个epoch,训练的loss在不断下降。准确率也逐步升高。
Epoch 1 ------------------------------- loss: 2.305289 [ 0/938] loss: 1.624348 [100/938] loss: 1.104460 [200/938] loss: 0.502375 [300/938] loss: 0.648946 [400/938] loss: 0.319905 [500/938] loss: 0.481640 [600/938] loss: 0.321123 [700/938] loss: 0.442546 [800/938] loss: 0.273236 [900/938] Test: Accuracy: 90.8%, Avg loss: 0.322175 Epoch 2 ------------------------------- loss: 0.217165 [ 0/938] loss: 0.264473 [100/938] loss: 0.318727 [200/938] loss: 0.392735 [300/938] loss: 0.398939 [400/938] loss: 0.339206 [500/938] loss: 0.165617 [600/938] loss: 0.166550 [700/938] loss: 0.466447 [800/938] loss: 0.273829 [900/938] Test: Accuracy: 92.8%, Avg loss: 0.258895 Epoch 3 ------------------------------- loss: 0.168608 [ 0/938] loss: 0.218002 [100/938] loss: 0.167067 [200/938] loss: 0.239305 [300/938] loss: 0.178461 [400/938] loss: 0.296701 [500/938] loss: 0.285426 [600/938] loss: 0.159142 [700/938] loss: 0.189556 [800/938] loss: 0.243780 [900/938] Test: Accuracy: 94.0%, Avg loss: 0.211683 Done!
5、保存模型
- # Save checkpoint
- mindspore.save_checkpoint(model, "model.ckpt")
- print("Saved Model to model.ckpt")
模型保存在当前路径下:
6、加载模型
加载保存的权重分为两步:
- # 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)
param_not_load
是未被加载的参数列表,为空时代表所有参数均加载成功。
加载后的模型可以直接用于预测推理。
- 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
结果为:
Predicted: "[1 0 1 9 0 1 9 8 2 5]", Actual: "[1 0 1 9 0 1 9 8 2 5]"
最后打印时间啦,今天的学习到这儿。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。