"""----------------------线性回归-----------------------------"""
import torch
from torch import nn, optim
from torch.autograd import Variable
import numpy as np
import matplotlib.pyplot as plt
#1.-----首先我们需要给出一系列的点作为线性回归的数据,使用numpy来存储这些点。----
x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168],
[9.779], [6.182], [7.59], [2.167], [7.042],
[10.791], [5.313], [7.997], [3.1]], dtype=np.float32)
y_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573],
[3.366], [2.596], [2.53], [1.221], [2.827],
[3.465], [1.65], [2.904], [1.3]], dtype=np.float32)
#--------------------------------------------------------------------
#2.np数据转换为torch数据
x_train = torch.from_numpy(x_train)
y_train = torch.from_numpy(y_train)
#3.基本的网络构建类模板
class LinearRegression(nn.Module):
def __init__(self):
super(LinearRegression, self).__init__()
# 可以添加各种网络层 这里是建立线性回归模型
"""这里的nn.Linear表示的是:y = w * x + b,因为输入x_train是[batch_size=15,input_size=1]的张量,
输出y_train是[batch_size=15,output_size=1],参数in_features=input_size为1, out_features=output_size为1"""
self.linear = nn.Linear(in_features=1, out_features=1)
def forward(self, x):
out = self.linear(x)
return out
model = LinearRegression()
#4.定义loss(误差)和优化函数
criterion = nn.MSELoss() #均方损失函数 计算公式:loss(xi,yi)=(∑(xi−yi)^2)/i 输出向量
optimizer = optim.SGD(model.parameters(), lr=1e-4) #随机梯度下降函数 Q := Q - ρ∑((Yi - H(x^i))x^i) Q从0到j每一个Q这么算
#5.开始训练
"""第一个循环表示每个epoch,接着开始前向传播,然后计算loss,然后反向传播,
接着优化参数,特别注意的是在每次反向传播的时候需要将参数的梯度归零,即zero_grad()"""
num_epochs = 10000
for epoch in range(num_epochs):
inputs = Variable(x_train) #------------创建 variable(变量)inputs
target = Variable(y_train) #------------创建 variable(变量)target(类别)
# forward 向前传播
out = model(inputs) #---------inputs变量的操作,所以out有 grad_fn 属性
loss = criterion(out, target) #-----------target变量的操作,所以loss有 grad_fn 属性
# backward 反向传播
optimizer.zero_grad()#梯度归0
loss.backward()#反向传播,自动求导,得到每个参数的梯度:
optimizer.step()#更新参数
if (epoch + 1) % 20 == 0:
print('Epoch[{}/{}], loss: {:.6f}'.format(epoch+1, num_epochs, loss.item()))
#6.开始测试模型
model.eval()#让model变成测试模式
predict = model(Variable(x_train))
predict = predict.data.numpy() #torch数据转换为np数据
plt.plot(x_train.numpy(), y_train.numpy(), 'ro', label='Original data') #画点,坐标为x_train.numpy()和y_train.numpy() ro:红色的圆圈
plt.plot(x_train.numpy(), predict, label='Fitting Line')#画线
# 显示图例
plt.legend()#设置图例位置
plt.show()
#7.保存模型
# 只保存模型参数
torch.save(model.state_dict(), 'F:/PycharmProjects/pytorch-beginner-master/01-Linear Regression/linear.pth')
#保存整个神经网络的模型结构以及参数
torch.save(model,'F:/PycharmProjects/pytorch-beginner-master/01-Linear Regression/linear1.pth')
#8.加载模型
#加载只保存模型参数的模型
model = LinearRegression()
mm = torch.load('F:/PycharmProjects/pytorch-beginner-master/01-Linear Regression/linear.pth')
model.load_state_dict(mm)
model.eval()
for key,v in mm.items():
print('key: ', key)
print('v: ', v)
predict = model(Variable(x_train))
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()
#加载保存整个参数的模型
model1 = torch.load('F:/PycharmProjects/pytorch-beginner-master/01-Linear Regression/linear1.pth')
model1.eval()
predict = model1(Variable(x_train))
predict = predict.data.numpy()
plt.plot(x_train.numpy(), y_train.numpy(), 'ro', label='Original data1')
plt.plot(x_train.numpy(), predict, label='Fitting Line1')
plt.legend()
plt.show()
pytorch线性回归代码实现 测试,保存,加载模型 有详细注释
最新推荐文章于 2022-12-28 15:18:20 发布