【人工智能】Mindspore框架中保存加载模型

前言

MindSpore着重提升易用性并降低AI开发者的开发门槛,MindSpore原生适应每个场景包括端、边缘和云,并能够在按需协同的基础上,通过实现AI算法即代码,使开发态变得更加友好,显著减少模型开发时间,降低模型开发门槛。通过MindSpore自身的技术创新及MindSpore与华为昇腾AI处理器的协同优化,实现了运行态的高效,大大提高了计算性能;MindSpore也支持GPU、CPU等其它处理器。

 一、准备工作

我们需要在使用前进行模块调用的操作,这也是前期必须要操作的一个步骤。代码如下:

import numpy as np
import mindspore
from mindspore import nn
from mindspore import Tensor

def network():
    model = nn.SequentialCell(
                nn.Flatten(),
                nn.Dense(28*28, 512),
                nn.ReLU(),
                nn.Dense(512, 512),
                nn.ReLU(),
                nn.Dense(512, 10))
    return model

二、权重介绍

保存模型使用save_checkpoint接口,传入网络和指定的保存路径:

model = network()
mindspore.save_checkpoint(model, "model.ckpt")

加载模型权重,需要先创建相同模型的实例,然后使用load_checkpointload_param_into_net方法加载参数。

model = network()
param_dict = mindspore.load_checkpoint("model.ckpt")
param_not_load = mindspore.load_param_into_net(model, param_dict)
print(param_not_load)

 如果我们运行之后出现下图说明,加载成功

 三、MindIR

MindSpore端边云统一格式 —— MindIR

 MindSpore通过统一IR定义了网络的逻辑结构和算子的属性,将MindIR格式的模型文件
与硬件平台解耦,实现一次训练多次部署。
MindIR作为MindSpore的统一模型文件,同时存储了网络结构和权重参数值。同时支持
部署到云端Serving和端侧Lite平台执行推理任务。
同一个MindIR文件支持多种硬件形态的部署:
- Serving部署推理
- 端侧Lite推理部署

 MindSpore提供了云侧(训练)和端侧(推理)统一的中间表示(Intermediate Representation,IR)可使用export接口直接将模型保存为MindIR。

model = network()
inputs = Tensor(np.ones([1, 1, 28, 28]).astype(np.float32))
mindspore.export(model, inputs, file_name="model", file_format="MINDIR")

MindIR模型可以方便地通过load接口加载,传入nn.GraphCell即可进行推理。

mindspore.set_context(mode=mindspore.GRAPH_MODE)

graph = mindspore.load("model.mindir")
model = nn.GraphCell(graph)
outputs = model(inputs)
print(outputs.shape)

四、Ascend 310 AI处理器上使用MindIR模型

 Ascend 310是面向边缘场景的高能效高集成度AI处理器。Atlas 200开发者套件又称Atlas 200 Developer Kit(以下简称Atlas 200 DK),是以Atlas 200 AI加速模块为核心的开发者板形态的终端类产品,集成了海思Ascend 310 AI处理器,可以实现图像、视频等多种数据分析与推理计算,可广泛用于智能监控、机器人、无人机、视频服务器等场景。

环境初始化,指定硬件为Ascend 310,DeviceID为0:

ms::GlobalContext::SetGlobalDeviceTarget(ms::kDeviceTypeAscend310);
ms::GlobalContext::SetGlobalDeviceID(0);

加载模型文件:

// Load MindIR model
auto graph =ms::Serialization::LoadModel(resnet_file, ms::ModelType::kMindIR);
// Build model with graph object
ms::Model resnet50((ms::GraphCell(graph)));
ms::Status ret = resnet50.Build({});

获取模型所需输入信息:

std::vector<ms::MSTensor> model_inputs = resnet50.GetInputs();

加载图片文件:

// Readfile is a function to read images
ms::MSTensor ReadFile(const std::string &file);
auto image = ReadFile(image_file);

图片预处理:

// Create the CPU operator provided by MindData to get the function object
ms::dataset::Execute preprocessor({ms::dataset::vision::Decode(),  // Decode the input to RGB format
                                   ms::dataset::vision::Resize({256}),  // Resize the image to the given size
                                   ms::dataset::vision::Normalize({0.485 * 255, 0.456 * 255, 0.406 * 255},
                                                                  {0.229 * 255, 0.224 * 255, 0.225 * 255}),  // Normalize the input
                                   ms::dataset::vision::CenterCrop({224, 224}),  // Crop the input image at the center
                                   ms::dataset::vision::HWC2CHW(),  // shape (H, W, C) to shape(C, H, W)
                                  });
// Call the function object to get the processed image
ret = preprocessor(image, &image);

执行推理:

// Create outputs vector
std::vector<ms::MSTensor> outputs;
// Create inputs vector
std::vector<ms::MSTensor> inputs;
inputs.emplace_back(model_inputs[0].Name(), model_inputs[0].DataType(), model_inputs[0].Shape(),
                    image.Data().get(), image.DataSize());
// Call the Predict function of Model for inference
ret = resnet50.Predict(inputs, &outputs);

获取推理结果:

// Output the maximum probability to the screen
std::cout << "Image: " << image_file << " infer result: " << GetMax(outputs[0]) << std::endl;

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>