"""
通常情况下,提取整个网络要比提取整个网络中的参数要慢点
"""
import torch
from torch.autograd import Variable
import matplotlib.pyplot as plt
# 数据
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
y = x.pow(2) + 0.2*torch.rand(x.size()) # 增加噪声
x, y = Variable(x, requires_grad=False), Variable(y, requires_grad=False)
# 保存网络
def save():
net1 = torch.nn.Sequential(
torch.nn.Linear(1, 10),
torch.nn.ReLU(),
torch.nn.Linear(10, 1)
)
optimizer = torch.optim.SGD(net1.parameters(), lr=0.5)
loss_func = torch.nn.MSELoss()
for t in range(100):
prediction = net1(x)
loss = loss_func(prediction, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 画图
plt.figure(1, figsize=(10, 3))
plt.subplot(131)
plt.title('Net1')
plt.scatter(x.data.numpy(), y.data.numpy())
plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)
# 保存网络的两种方式
torch.save(net1, 'net.pkl') # 保存整个网络
torch.save(net1.state_dict(), 'net_params.pkl') # 保存整个网络的参数
def restore_net():
# 提取网络'net.pkl',命名为net2用于后面的预测
net2 = torch.load('net.pkl')
prediction = net2(x)
# 画图
plt.subplot(132)
plt.title('Net2')
plt.scatter(x.data.numpy(), y.data.numpy())
plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)
def restore_params():
# 提取网络参数的话,必须搭建一个和网络参数相匹配的网络
net3 = torch.nn.Sequential(
torch.nn.Linear(1, 10),
torch.nn.ReLU(),
torch.nn.Linear(10, 1)
)
# 加载网络参数'net_params.pkl',送入上面搭建的网络中去
net3.load_state_dict(torch.load('net_params.pkl'))
prediction = net3(x)
# 画图
plt.subplot(133)
plt.title('Net3')
plt.scatter(x.data.numpy(), y.data.numpy())
plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)
plt.show()
# 保存网络
save()
# 提取整个网络
restore_net()
# 只提取网络中的参数
restore_params()