对于Pytorch,来一个感性开始,做一个最简单的模型,让pytorch跑起来。第一步是代码;第二步看结果。
1. 代码
# -*- coding: utf-8 -*-
# @Time : 2020/3/5 16:43
# @Author : happyprince
# @FileName: demo_01.py
# @Software: PyCharm
import torch
import numpy as np
from torch import nn, optim
from torch.autograd import Variable
import matplotlib.pyplot as plt
# 初始参数
x_train = np.array([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17]],
dtype=np.float32)
y_train = np.array([[2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18]],
dtype=np.float32)
# 把数据转化成torch数据类型
x_train = torch.from_numpy(x_train)
y_train = torch.from_numpy(y_train)
# 定义一个线性模型
class LinearRegression(nn.Module):
def __init__(self):
super(LinearRegression, self).__init__()
self.line = nn.Linear(1, 1)
def forward(self, x):
out = self.line(x)
return out
# 创建模型
model = LinearRegression()
# 定义损失函数loss
critertion = nn.MSELoss()
# 定义优化器
optimizer = optim.SGD(model.parameters(), lr=1e-4)
# 开始训练
num_epochs = 500
for epoch in range(num_epochs):
inputs = Variable(x_train)
target = Variable(y_train)
# 前向计算
# 前向传播
out = model(inputs)
# 计算损失值
loss = critertion(out, target)
# 后向传播
# 梯度归零
optimizer.zero_grad()
# 反向传播
loss.backward()
# 更新参数
optimizer.step()
if (epoch + 1) % 2 == 0:
print('Epoch[{}/{}], loss: {:.6f}'.format(epoch + 1, num_epochs, loss.data.numpy()))
# 对模型设置评估状态
model.eval()
# 把数据输入模型中
predict = model(Variable(x_train))
# 把tensor数据类型转换成numpy数据类型
predict = predict.data.numpy()
# 画原数据曲线
plt.plot(x_train.numpy(), y_train.numpy(), 'ro', label='Original data')
# 画数据拟合后的典线
plt.plot(x_train.numpy(), predict, label='Fitting Line')
# 显示图例
plt.legend()
plt.show()
# 保存模型
torch.save(model.state_dict(), './linear.pth')
2.结果
2.1 日志内容
Epoch[50/500], loss: 3.118705
Epoch[100/500], loss: 0.367797
Epoch[150/500], loss: 0.043541
Epoch[200/500], loss: 0.005319
Epoch[250/500], loss: 0.000813
Epoch[300/500], loss: 0.000281
Epoch[350/500], loss: 0.000217
Epoch[400/500], loss: 0.000209
Epoch[450/500], loss: 0.000207
Epoch[500/500], loss: 0.000206