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


    前言

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

     一、准备工作

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

    1. import numpy as np
    2. import mindspore
    3. from mindspore import nn
    4. from mindspore import Tensor
    5. def network():
    6. model = nn.SequentialCell(
    7. nn.Flatten(),
    8. nn.Dense(28*28, 512),
    9. nn.ReLU(),
    10. nn.Dense(512, 512),
    11. nn.ReLU(),
    12. nn.Dense(512, 10))
    13. return model

    二、权重介绍

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

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

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

    1. model = network()
    2. param_dict = mindspore.load_checkpoint("model.ckpt")
    3. param_not_load = mindspore.load_param_into_net(model, param_dict)
    4. print(param_not_load)

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

     三、MindIR

    MindSpore端边云统一格式 —— MindIR

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

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

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

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

    1. mindspore.set_context(mode=mindspore.GRAPH_MODE)
    2. graph = mindspore.load("model.mindir")
    3. model = nn.GraphCell(graph)
    4. outputs = model(inputs)
    5. 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处理器,可以实现图像、视频等多种数据分析与推理计算,可广泛用于智能监控、机器人、无人机、视频服务器等场景。

    1. 环境初始化,指定硬件为Ascend 310,DeviceID为0
    2. ms::GlobalContext::SetGlobalDeviceTarget(ms::kDeviceTypeAscend310);
    3. ms::GlobalContext::SetGlobalDeviceID(0);
    4. 加载模型文件:
    5. // Load MindIR model
    6. auto graph =ms::Serialization::LoadModel(resnet_file, ms::ModelType::kMindIR);
    7. // Build model with graph object
    8. ms::Model resnet50((ms::GraphCell(graph)));
    9. ms::Status ret = resnet50.Build({});
    10. 获取模型所需输入信息:
    11. std::vector model_inputs = resnet50.GetInputs();
    12. 加载图片文件:
    13. // Readfile is a function to read images
    14. ms::MSTensor ReadFile(const std::string &file);
    15. auto image = ReadFile(image_file);
    16. 图片预处理:
    17. // Create the CPU operator provided by MindData to get the function object
    18. ms::dataset::Execute preprocessor({ms::dataset::vision::Decode(), // Decode the input to RGB format
    19. ms::dataset::vision::Resize({256}), // Resize the image to the given size
    20. ms::dataset::vision::Normalize({0.485 * 255, 0.456 * 255, 0.406 * 255},
    21. {0.229 * 255, 0.224 * 255, 0.225 * 255}), // Normalize the input
    22. ms::dataset::vision::CenterCrop({224, 224}), // Crop the input image at the center
    23. ms::dataset::vision::HWC2CHW(), // shape (H, W, C) to shape(C, H, W)
    24. });
    25. // Call the function object to get the processed image
    26. ret = preprocessor(image, &image);
    27. 执行推理:
    28. // Create outputs vector
    29. std::vector outputs;
    30. // Create inputs vector
    31. std::vector inputs;
    32. inputs.emplace_back(model_inputs[0].Name(), model_inputs[0].DataType(), model_inputs[0].Shape(),
    33. image.Data().get(), image.DataSize());
    34. // Call the Predict function of Model for inference
    35. ret = resnet50.Predict(inputs, &outputs);
    36. 获取推理结果:
    37. // Output the maximum probability to the screen
    38. std::cout << "Image: " << image_file << " infer result: " << GetMax(outputs[0]) << std::endl;

  • 相关阅读:
    计算机网络4小时速成:计算机网络基础,计网组成,计网分类,性能指标,标准化组织,计网结构模型,五层模型
    如何解决 Spring Boot Actuator 的未授权访问漏洞
    RK3588 I2C设备开发硬件检测
    代码随想录Day42 | 01背包问题| 416. 分割等和子集
    【大型软件开发】开发日志(五).net框架与C++的融合:CLR——C++如何调用C#的DLL
    小微信贷传统风控模型的痛点
    【JavaScript 逆向】猿人学 web 第二十题:新年挑战
    Acwing算法基础学习笔记(二)二分
    Mathtype公式自动转Word自带公式
    Java 基础入门,小白提升路线图
  • 原文地址:https://blog.csdn.net/weixin_50481708/article/details/127951956