保存模型

\[f(x)=ax^2+b
\]

\[D(x)=ax^2+b+noise
\]

```# save_model.py
from mindspore import context
context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
import numpy as np
from mindspore import dataset as ds
from mindspore import nn, Tensor, Model
import time
from mindspore.train.callback import Callback, LossMonitor, ModelCheckpoint
def get_data(num, a=2.0, b=3.0):
for _ in range(num):
x = np.random.uniform(-1.0, 1.0)
noise = np.random.normal(0, 0.03)
z = a * x ** 2 + b + noise
# 返回数据的时候就返回数据的平方
yield np.array([x**2]).astype(np.float32), np.array([z]).astype(np.float32)
def create_dataset(num_data, batch_size=16, repeat_size=1):
input_data = ds.GeneratorDataset(list(get_data(num_data)), column_names=['x','z'])
input_data = input_data.batch(batch_size)
input_data = input_data.repeat(repeat_size)
return input_data
data_number = 1600 # 一共产生1600组数据
batch_number = 16 # 分为16组分别进行优化
repeat_number = 2 # 重复2次，可以取到更低的损失函数值
ds_train = create_dataset(data_number, batch_size=batch_number, repeat_size=repeat_number)
class LinearNet(nn.Cell):
def __init__(self):
super(LinearNet, self).__init__()
self.fc = nn.Dense(1, 1, 0.02, 0.02)
def construct(self, x):
x = self.fc(x)
return x
net = LinearNet()
model_params = net.trainable_params()
print ('Param Shape is: {}'.format(len(model_params)))
for net_param in net.trainable_params():
print(net_param, net_param.asnumpy())
net_loss = nn.loss.MSELoss()
optim = nn.Momentum(net.trainable_params(), learning_rate=0.005, momentum=0.9)
model = Model(net, net_loss, optim)
ckpt_cb = ModelCheckpoint()
epoch = 1
# 设定每8个batch训练完成后就播报一次，这里一共播报25次
model.train(epoch, ds_train, callbacks=[LossMonitor(16), ckpt_cb], dataset_sink_mode=False)
for net_param in net.trainable_params():
print(net_param, net_param.asnumpy())```

```[email protected]:~/projects/gitlab/dechin/src/mindspore\$ sudo docker run --rm -v /dev/shm:/dev/shm -v /home/dechin/projects/gitlab/dechin/src/mindspore/:/home/ --runtime=nvidia --privileged=true swr.cn-south-1.myhuaweicloud.com/mindspore/mindspore-gpu:1.2.0 /bin/bash -c "cd /home && python save_model.py"
Param Shape is: 2
Parameter (name=fc.weight, shape=(1, 1), dtype=Float32, requires_grad=True) [[0.02]]
Parameter (name=fc.bias, shape=(1,), dtype=Float32, requires_grad=True) [0.02]
epoch: 1 step: 16, loss is 0.9980968
epoch: 1 step: 32, loss is 0.3894167
epoch: 1 step: 48, loss is 0.090543285
epoch: 1 step: 64, loss is 0.060300454
epoch: 1 step: 80, loss is 0.014248277
epoch: 1 step: 96, loss is 0.015697923
epoch: 1 step: 112, loss is 0.014582128
epoch: 1 step: 128, loss is 0.008066677
epoch: 1 step: 144, loss is 0.007225203
epoch: 1 step: 160, loss is 0.0046849623
epoch: 1 step: 176, loss is 0.006007362
epoch: 1 step: 192, loss is 0.004276552
Parameter (name=fc.weight, shape=(1, 1), dtype=Float32, requires_grad=True) [[1.8259585]]
Parameter (name=fc.bias, shape=(1,), dtype=Float32, requires_grad=True) [3.0577476]```

```[email protected]:~/projects/gitlab/dechin/src/mindspore\$ ll
total 148
drwxr-xr-x 2 1000 1000  4096 May 16 13:25 ./
drwxr-xr-x 1 root root  4096 May 15 01:55 ../
-r-------- 1 root root   211 May 16 13:25 CKP-1_196.ckpt
-r-------- 1 root root   211 May 16 13:25 CKP-1_197.ckpt
-r-------- 1 root root   211 May 16 13:25 CKP-1_198.ckpt
-r-------- 1 root root   211 May 16 13:25 CKP-1_199.ckpt
-r-------- 1 root root   211 May 16 13:25 CKP-1_200.ckpt
-r-------- 1 root root  3705 May 16 13:25 CKP-graph.meta
-rw-r--r-- 1 1000 1000  2087 May 16 13:25 save_model.py```

加载模型

```# load_model.py
from mindspore import context
context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
import mindspore.dataset as ds
from mindspore import nn, Tensor, Model
import numpy as np
class LinearNet(nn.Cell):
def __init__(self):
super(LinearNet, self).__init__()
self.fc = nn.Dense(1,1,0.02,0.02)
def construct(self, x):
print ('x:', x)
x = self.fc(x)
print ('z:', x)
return x
net = LinearNet()
net_loss = nn.loss.MSELoss()
model = Model(net, net_loss, metrics={"accuracy"})
data = {'x':np.array([[0.01],[0.25],[1],[4],[9]]).astype(np.float32),
'z':np.array([3.02,3.5,5,11,21]).astype(np.float32)}
dataset = ds.NumpySlicesDataset(data=data)
dataset = dataset.batch(1)
acc = model.eval(dataset, dataset_sink_mode=False)```

```[email protected]:~/projects/gitlab/dechin/src/mindspore\$ sudo docker run --rm -v /dev/shm:/dev/shm -v /home/dechin/projects/gitlab/dechin/src/mindspore/:/home/ --runtime=nvidia --privileged=true swr.cn-south-1.myhuaweicloud.com/mindspore/mindspore-gpu:1.2.0 /bin/bash -c "cd /home && python load_model.py"
x:
Tensor(shape=[1, 1], dtype=Float32, value=
[[ 9.00000000e+00]])
z:
Tensor(shape=[1, 1], dtype=Float32, value=
[[ 1.94898682e+01]])
x:
Tensor(shape=[1, 1], dtype=Float32, value=
[[ 2.50000000e-01]])
z:
Tensor(shape=[1, 1], dtype=Float32, value=
[[ 3.52294850e+00]])
x:
Tensor(shape=[1, 1], dtype=Float32, value=
[[ 9.99999978e-03]])
z:
Tensor(shape=[1, 1], dtype=Float32, value=
[[ 3.08499861e+00]])
x:
Tensor(shape=[1, 1], dtype=Float32, value=
[[ 1.00000000e+00]])
z:
Tensor(shape=[1, 1], dtype=Float32, value=
[[ 4.89154148e+00]])
x:
Tensor(shape=[1, 1], dtype=Float32, value=
[[ 4.00000000e+00]])
z:
Tensor(shape=[1, 1], dtype=Float32, value=
[[ 1.03659143e+01]])```