1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| import torch import numpy as np from torch import data
true_w = torch.tensor([2, -3.4]) true_b = 4.2 features, labels = d2l.synthetic_data(true_w, true_b, 1000)
def data_slice(data_arrays, batch_size, is_train = True) data_slice = data.TensorDataSet(*data_arrays) return data.DataLoader(data_slice, batch_size, is_train) batch_size = 10 data_iter = data_slice([features, labels], batch_size) next(iter(data_iter))
from torch import nn 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 = 0.3)
epochs = 3 for i in range(epochs): for X, y in data_iter: l = loss(net[X], y) trainer.zero_gard() l.backward() trainer.step() l = loss(net[features], lables) print(f'epoch {epoch + 1}, loss {l:f}) net[0].weight.data net[0].bias.data
|