import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
# Hyper-parameters 设置超参数
input_size = 1
output_size = 1
num_epochs = 60
learning_rate = 0.001
# Toy dataset 加载数据集
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)
# Linear regression model 定义模型
model = nn.Linear(input_size,output_size)
# Loss and optimizer 定义损失函数和优化器
critertion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
# Train the model
for epoch in range(num_epochs):
# Convert numpy arrays to torch tensors
inputs = torch.from_numpy(x_train)
targets = torch.from_numpy(y_train)
# Farward pass
outputs = model(inputs)
loss = critertion(outputs, targets)
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
if(epoch+1) % 5 == 0: # 每五轮输出损失函数值
print('Epoch [{} / {}], Loss :{:.4f}'.format(epoch+1, num_epochs, loss.item()))
# Plot the graph
predicted = model(torch.from_numpy(x_train)).detach().numpy() # detach就是截断反向传播的梯度流
plt.plot(x_train, y_train,'ro', label='Original data') # r o表示红色圈
plt.plot(x_train,predicted,label='Fitted line')
plt.legend() # plt.legend()函数主要的作用就是给图加上图例,plt.legend([x,y,z])里面的参数使用的是list的的形式将图表的的名称喂给这和函数
plt.show()
# Save the model checkpoint
torch.save(model.state_dict(), 'model.ckpt') # model.ckpt是四个文件
Linear_regression
最新推荐文章于 2023-10-05 12:01:45 发布