[MindSpore新年新版本体验]MindSpore1.1实现简单线性函数拟合

一、运行环境(Vmware虚拟机环境)

操作系统:Ubuntu 18.04

CPU:Intel i7

内存:2GB

Anconda版本:Anconda 2020.11

MindSpore版本:1.1.0

二、MindSpore安装

根据安装文档,采用pypi安装

执行命令:

1pip install https://ms-release.obs.cn-north-4.myhuaweicloud.com/1.1.0/MindSpore/cpu/ubuntu_aarch64/mindspore-1.1.0-cp37-cp37m-linux_aarch64.whl --trusted-host http://ms-release.obs.cn-north-4.myhuaweicloud.com -i https://pypi.tuna.tsinghua.edu.cn/simple

打开jupyterlab引入mindspore验证一下安装版本

运行结果显示1.1.0说明MindSpore1.1.0安装完成了

三、实现简单线性函数拟合

这部分内容参考:https://www.mindspore.cn/tutorial/training/zh-CN/r1.1/quick_start/linear_regression.html

回归问题算法通常是利用一系列属性来预测一个值,预测的值是连续的。例如给出一套房子的一些特征数据,如面积、卧室数等等来预测房价,利用最近一周的气温变化和卫星云图来预测未来的气温情况等。如果一套房子实际价格为500万元,通过回归分析的预测值为499万元,则认为这是一个比较好的回归分析。在机器学习问题中,常见的回归分析有线性回归、多项式回归、逻辑回归等。本例子介绍线性回归算法,并通过MindSpore进行线性回归AI训练体验。
第一部分,MindSpore运行配置,定义数据集生成函数及可视化展示

from mindspore import contextimport numpy as npimport matplotlib.pyplot as plt #设置MindSpore运行配置context.set_context(mode=context.GRAPH_MODE, device_target="CPU") #定义数据集生成函数def get_data(num, w=2.0, b=3.0): for _ in range(num): x = np.random.uniform(-10.0, 10.0) noise = np.random.normal(0, 1) y = x * w + b + noise yield np.array([x]).astype(np.float32), np.array([y]).astype(np.float32)#可视化展示_data = list(get_data(50))x_target_label = np.array([-10, 10, 0.1])y_target_label = x_target_label * 2 + 3x__label,y__label = zip(*_data) plt.scatter(x__label, y__label, color="red", s=5)plt.plot(x_target_label, y_target_label, color="green")plt.("Eval data")plt.show()

执行结果


上图中绿色线条部分为目标函数,红点部分为验证数据_data。
第二部分:定义数据增强函数

#定义数据增强函数from mindspore import dataset as ds def create_dataset(num_data, batch_size=16, repeat_size=1): input_data = ds.GeneratorDataset(list(get_data(num_data)), column_names=['data', 'label'],num_parallel_workers=2) input_data = input_data.batch(batch_size) input_data = input_data.repeat(repeat_size) return input_data #使用数据集增强函数生成训练数据,并查看训练数据的格式。data_number = 1600batch_number = 16repeat_number = 1 ds_train = create_dataset(data_number, batch_size=batch_number, repeat_size=repeat_number)print("The dataset size of ds_train:", ds_train.get_dataset_size())dict_datasets = next(ds_train.create_dict_iterator()) print(dict_datasets.keys())print("The x label value shape:", dict_datasets["data"].shape)print("The y label value shape:", dict_datasets["label"].shape)

第三部分:定义训练网络

#定义训练网络from mindspore.common.initializer import Normalfrom mindspore import nn class LinearNet(nn.Cell): def __init__(self): super(LinearNet, self).__init__() self.fc = nn.Dense(1, 1, Normal(0.02), Normal(0.02)) def construct(self, x): x = self.fc(x) return x net = LinearNet()model_params = net.trainable_params()print(model_params) #可视化from mindspore import Tensor x_model_label = np.array([-10, 10, 0.1])y_model_label = (x_model_label * Tensor(model_params[0]).asnumpy()[0][0] + Tensor(model_params[1]).asnumpy()[0]) plt.scatter(x_eval_label, y_eval_label, color="red", s=5)plt.plot(x_model_label, y_model_label, color="blue")plt.plot(x_target_label, y_target_label, color="green")plt.show()

运行结果:


第四部分:定义前向传播网络与反向传播网络并关联

from mindspore import Modelimport matplotlib.pyplot as pltimport time net = LinearNet()net_loss = nn.loss.MSELoss()opt = nn.Momentum(net.trainable_params(), learning_rate=0.005, momentum=0.9)model = Model(net, net_loss, opt) def plot_model_and_datasets(net, eval_data): weight = net.trainable_params()[0] bias = net.trainable_params()[1] x = np.arange(-10, 10, 0.1) y = x * Tensor(weight).asnumpy()[0][0] + Tensor(bias).asnumpy()[0] x1, y1 = zip(*eval_data) x_target = x y_target = x_target * 2 + 3 plt.axis([-11, 11, -20, 25]) plt.scatter(x1, y1, color="red", s=5) plt.plot(x, y, color="blue") plt.plot(x_target, y_target, color="green") plt.show() time.sleep(0.02) #定义回调函数from IPython import displayfrom mindspore.train.callback import Callback class ImageShowCallback(Callback): def __init__(self, net, eval_data): http://self.net = net self.eval_data = eval_data def step_end(self, run_context): plot_model_and_datasets(self.net, self.eval_data) display.clear_output(wait=True)

第四部分:执行训练
 

from mindspore.train.callback import LossMonitor epoch = 1imageshow_cb = ImageShowCallback(net, eval_data)model.train(epoch, ds_train, callbacks=[imageshow_cb], dataset_sink_mode=False) plot_model_and_datasets(net,eval_data)print(net.trainable_params()[0], "\n%s" % net.trainable_params()[1])


四、出现的问题
在执行数据增强和执行训练的时候报一下错误:

RuntimeError: Thread ID 139848515852096 Unexpected error. GeneratorDataset's num_workers=4, this value is not within the required range of [1, cpu_thread_cnt=2].Line of code : 429File : /home/jenkins/agent-working-dir/workspace/Compile_CPU_X86_Ubuntu/mindspore/mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/http://dataset_node.cc

具体原因还在琢磨

转自文章链接:[MindSpore新年新版本体验]MindSpore1.1实现简单线性函数拟合_MindSpore_昇腾论坛_华为云论坛

感谢作者的努力与分享,侵权立删!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值