1. 背景:
使用 mindspore 学习神经网络,打卡第7天;
2. 训练的内容:
使用 mindspore 的模型训练的常见用法,基本上是将前几章节的功能串起来
3. 常见的用法小节:
模型训练的常见流程,如数据加载,神经网路网络定义,损失函数定义,优化器定义,训练,测试,验证等步骤
3.1 构建数据集:
首先从数据集 Dataset加载代码,构建数据集
# 首先从数据集 Dataset加载代码,构建数据集
import mindspore
from mindspore import nn
from mindspore.dataset import vision, transforms
from mindspore.dataset import MnistDataset# Download data from open datasets
from download import downloadurl = "https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/" \"notebook/datasets/MNIST_Data.zip"
path = download(url, "./", kind="zip", replace=True)def datapipe(path, 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 = MnistDataset(path)dataset = dataset.map(image_transforms, 'image')dataset = dataset.map(label_transform, 'label')dataset = dataset.batch(batch_size)return datasettrain_dataset = datapipe('MNIST_Data/train', batch_size=64)
test_dataset = datapipe('MNIST_Data/test', batch_size=64)
3.2 构建神经网络模型
从网络构建中加载代码,构建一个神经网络模型
# 从网络构建中加载代码,构建一个神经网络模型
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 logitsmodel = Network()
3.3 定义损失函数与优化器
定义超参(Hyperparameters),损失函数(LossFunction)和优化器(Optimizer)
# 定义超参(Hyperparameters),损失函数(LossFunction)和优化器(Optimizer)
epochs = 3
batch_size = 64
learning_rate = 1e-2# 损失函数(loss function)用于评估模型的预测值(logits)和目标值(targets)之间的误差。
# 结合了nn.LogSoftmax和负对数似然(nn.NLLLoss)
loss_fn = nn.CrossEntropyLoss()# 模型优化(Optimization)
# 在每个训练中调整模型参数,减少模型误差的过程
optimizer = nn.SGD(model.trainable_params(), learning_rate=learning_rate)
3.4 定义训练函数
定义训练函数
# 训练与评估
# Define forward function
def forward_fn(data, label):logits = model(data)loss = loss_fn(logits, label)return loss, logits# Get gradient function
grad_fn = mindspore.value_and_grad(forward_fn, None, optimizer.parameters, has_aux=True)# Define function of one-step training
def train_step(data, label):(loss, _), grads = grad_fn(data, label)optimizer(grads)return lossdef train_loop(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(), batchprint(f"loss: {loss:>7f} [{current:>3d}/{size:>3d}]")
3.5 定义测试函数
定义测试函数
# 测试函数:
def test_loop(model, dataset, loss_fn):num_batches = dataset.get_dataset_size()model.set_train(False)total, test_loss, correct = 0, 0, 0for 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_batchescorrect /= totalprint(f"Test: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
3.6 实例化训练与测试,并运行
实例化训练与测试,并运行
# 实例化的损失函数和优化器传入 train_loop 和 test_loop 中
loss_fn = nn.CrossEntropyLoss()
optimizer = nn.SGD(model.trainable_params(), learning_rate=learning_rate)for t in range(epochs):print(f"Epoch {t+1}\n-------------------------------")train_loop(model, train_dataset)test_loop(model, test_dataset, loss_fn)
print("Done!")
相关链接:
- https://xihe.mindspore.cn/events/mindspore-training-camp
- https://gitee.com/mindspore/docs/blob/r2.3.0rc2/tutorials/source_zh_cn/beginner/train.ipynb