#线性回归简洁实现
import numpy as np
import torch
from torch.utils import data
from d2l import torch as d2l
true_w = torch.tensor([2,-3.4])
true_b = 4.2
features,labels = d2l.synthetic_data(true_w,true_b,1000)#根据参数生成人造数据集
def load_array(data_arrays,batch_size,is_train = True):
# 构造一个pytorch数据迭代器
# 将输入的两类数据进行一一对应
dataset = data.TensorDataset(*data_arrays)
#重新排序
return data.DataLoader(dataset,batch_size,shuffle=is_train)
batch_size = 10
data_iter = load_array((features,labels),batch_size)
#nn是神经网络的缩写
from torch import nn
#Sequential 一个有序的容器 神经网络模块按照传入构造器的顺序依次被添加到计算图中执行
net = nn.Sequential(nn.Linear(2,1))#输入维度是2 输出维度是1
#这两步是初始化权重和偏差
net[0].weight.data.normal_(0,0.01)#net[0]是指容器里面的第一层 也就是linear
net[0].bias.data.fill_(0)
loss = nn.MSELoss()#均方损失
trainer = torch.optim.SGD(net.parameters(),lr=0.03)
num_epochs = 3
for epoch in range(num_epochs):
for x,y in data_iter:
l = loss(net(x),y)
trainer.zero_grad()
l.backward()
trainer.step()#调用函数进行模型更新
l = loss(net(features),labels)
print(f'epoch {epoch+1}, loss {l:f}')
08-线性回归简洁实现部分 动手深度学习
最新推荐文章于 2024-09-09 23:51:40 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)