使用tensor与自动求导编写并训练一个线性回归器

import torch
import numpy as np
import torch.optim as optim
print(torch.__version__)

#生成训练数据

x = torch.rand(30,2)*10 - 5 
w0 = torch.tensor([2,-1],dtype = torch.float32)
b0 = torch.tensor([1.7],dtype = torch.float32)
y = torch.matmul(x,w0) + b0 + torch.randn(30) #受随机噪声污染的y
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
xarr = x.numpy()
yarr = y.numpy()
fig = plt.figure(0, figsize=(4, 3))
plt.clf()
ax = Axes3D(fig, elev=45, azim=100)
ax.scatter(x[:, 0], x[:, 1], y)
plt.show()

 使用tensor与自动求导编写并训练一个线性回归器_第1张图片

 

#编写模型并训练

def linearReg(x, w, b):
    y = torch.matmul(x, w) + b
    return y
def lossfn(y, y_hat):
    e=(y-y_hat)**2
    loss=e.mean()
    return loss

def train_modle(x, y, w, b, epochs, lr=0.1):
    optimizer = optim.SGD([w,b], lr=lr)
    for epoch in range(1, 1+epochs):

        optimizer.zero_grad()
        y_pred = linearReg(x, w, b)
        loss = lossfn(y_pred, y)
        loss.backward()
        optimizer.step()
        print('EP0CH=%d,LOSS=%f,b=%f'%(epoch,loss.detach().numpy(),b.detach().numpy()),w)
        continue
    return w,b

w = torch.tensor([0.0,0.0], requires_grad=True)
b = torch.tensor([0.0],requires_grad=True)
w, b = train_modle(x, y, w, b, epochs=20, lr=0.1)

 训练过程使用tensor与自动求导编写并训练一个线性回归器_第2张图片

你可能感兴趣的:(pytorch,机器学习)