import random
from torch import nn
import torch
from torch.utils import data
def synthetic_data(w,b,num):
feature=torch.normal(0,0.1,(num,len(w)))
label=torch.matmul(feature,w)+b
label+=torch.normal(0,0.1,label.shape)
return feature,label
def load_data(data_array,batch_size,is_Train=True):
dataset=data.TensorDataset(*data_array)
datasets=data.DataLoader(dataset,batch_size,shuffle=is_Train)
return datasets
w=torch.tensor([2,-3.4])
b=4.2
feature,label=synthetic_data(w,b,20)
epoch=10
lr=0.01
batch_size=5
data_loader=load_data((feature,label),batch_size)
net=nn.Sequential(nn.Linear(2,1))
net[0].weight.data.normal_(0,0.1)
net[0].bias.data.fill_(0)
loss=nn.MSELoss()#均方误差
trainer=torch.optim.SGD(net.parameters(),lr)
for i in range(epoch):
for x,y in data_loader:
l=loss(net(x),y)
trainer.zero_grad()
l.backward()
trainer.step()
l=loss(net(feature),label)
print("epoch:",i,"loss",l)
pytorch实现线性回归
最新推荐文章于 2024-02-18 23:36:30 发布