昇思25天学习打卡营第02天 | 快速入门

昇思25天学习打卡营第02天 | 快速入门

数据准备

MindSpore通过DatasetTransforms实现高效的数据预处理

使用download下载数据,并创建数据集对象:

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)

train_dataset = MnistDataset('MNIST_Data/train')
test_dataset = MnistDataset('MNIST_Data/test')

数据集中的数据可以通过create_tuple_iteratorcreate_dict_iterator进行访问:

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

原始的数据通常不能满足需求,需要通过数据流水线(Data Processing Pipeline)指定map、batch、shuffle等操作进行处理,并将数据打包为指定大小的batch:

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
	
train_dataset = datapipe(train_dataset, 64)
test_dataset = datapipe(test_dataset, 64)

网络构建

通过继承nn.Cell类,并重写__init__construct方法来自定义网络结构。

# 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)

__init__方法中的dense_relu_sequential定义了网络的层次结构,由Dense和ReLU组成。
construct方法描述对输入数据的变换。

模型训练

一个模型的训练需要经过三个步骤:

  1. 正向计算:计算模型的预测值,并于正确标签求loss;
  2. 反向传播:利用自动微分机制,求模型参数对loss的梯度值;
    3.参数优化: 根据梯度值更新参数。

MindSpore使用函数式自动微分机制,因此需要实现:

  1. 定义正向计算函数:
loss_fn = nn.CrossEntropyLoss()
optimizer = nn.SGD(model.trainable_params(), 1e-2)

def forward_fn(data, label):
	logits = model(data)
	loss = loss_fn(logits, label)
	return loss, logits
  1. 使用value_and_grad获得梯度计算函数:
grad_fn = mindspore.value_and_grad(forward_fn, None, optimizer.parameters, has_aux=True)
  1. 定义训练函数,使用set_train设置为训练模式,执行正向计算、反向传播和参数优化:
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

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!")

模型保存

通过save_checkpoint保存模型的参数:

mindspore.save_checkpoint(model, "model.ckpt")
print("Saved Model to model.ckpt")

加载模型

模型的加载分为两步:

  1. 重新实例化网络模型:
model = Network()
  1. 加载模型参数,并加载至模型上:
param_dict = mindspore.load_checkpoint("model.ckpt")
param_not_load, _ = mindspore.load_param_into_net(model, param_dict)
print(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

总结

通过这一节的内容,对一个网络的诞生有了大概的认识,从原始数据到数据集的处理,简单网络结构的搭建,训练中自动微分机制的使用方法等都有了一定的了解。此外还有模型的保存与加载方法,为之后的深入学习奠定了基础。

打卡

在这里插入图片描述

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吉拉尔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值