动手学深度学习----线性回归的简洁实现

线性回归的简洁实现—调用pytorch中封装好的函数

#线性回归的简洁实现
import numpy as np
import torch
from torch.utils import data
from d2l import torch as d2l
from torch import nn  # nn是神经网络的缩写


true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = d2l.synthetic_data(true_w, true_b, 1000)  # 生成features和 labels


def load_array(data_arrays, batch_size, is_train=True):
    dataset = data.TensorDataset(*data_arrays)  # 将features, labels传入TensorDataset 得到pytorch的dataset
    return data.DataLoader(dataset, batch_size, shuffle=is_train)   # DataLoader每次从dataset中挑选batch_size个样本 shuffle随机打乱


batch_size = 10
data_iter = load_array((features, labels), batch_size)
next(iter(data_iter))

net = nn.Sequential(nn.Linear(2, 1))  # 线性层 2是输入维度  1是输出维度      Sequential是将层按顺序放在sequential容器里
net[0].weight.data.normal_(0, 0.01)  # net[0]是第一层  data.normal_(0, 0.01) 使用均值为0 方差为0.01的正态分布替换掉data
net[0].bias.data.fill_(0)   # 将偏差设成0
loss = nn.MSELoss()
trainer = torch.optim.SGD(net.parameters(), lr=0.03)  # net.parameters()传入所有参数

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}')  # 打印l 格式为浮点型f


你可能感兴趣的:(#,深度学习,python,pytorch,线性回归)