# 隨機(jī)初始化一個(gè)二維數(shù)據(jù)集,使用朋友torch訓(xùn)練一個(gè)回歸模型
import numpy as np
import random
import matplotlib.pyplot as plt
x = np.arange(20)
y = np.array([5*x[i] + random.randint(1,20) for i in range(len(x))]) # random.randint(參數(shù)1,參數(shù)2)函數(shù)返回參數(shù)1和參數(shù)2之間的任意整數(shù)
print('-'*50)
# 打印數(shù)據(jù)集
print(x)
print(y)
import torch
x_train = torch.from_numpy(x).float()
y_train = torch.from_numpy(y).float()
# model
class LinearRegression(torch.nn.Module):
def __init__(self):
super(LinearRegression, self).__init__()
# 輸入與輸出都是一維的
self.linear = torch.nn.Linear(1,1)
def forward(self,x):
return self.linear(x)
# 新建模型,誤差函數(shù),優(yōu)化器
model = LinearRegression()
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(),0.001)
# 開始訓(xùn)練
num_epoch = 20
for i in range(num_epoch):
input_data = x_train.unsqueeze(1)
target = y_train.unsqueeze(1) # unsqueeze(1)在第二維增加一個(gè)維度
out = model(input_data)
loss = criterion(out,target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
print("Eopch:[{}/{},loss:[{:.4f}]".format(i+1,num_epoch,loss.item()))
if ((i+1)%2 == 0):
predict = model(input_data)
plt.plot(x_train.data.numpy(),predict.squeeze(1).data.numpy(),"r")
loss = criterion(predict,target)
plt.title("Loss:{:.4f}".format(loss.item()))
plt.xlabel("X")
plt.ylabel("Y")
plt.scatter(x_train,y_train)
plt.show()