import numpy as np
import torch
from torch.utils import data
from d2l import torch as d2l
#制作数据集
def syn_data(w,b,num_examples):
x = torch.normal(0,1,(num_examples,len(w)))
y = torch.matmul(x,w)+b
y=y +torch.normal(0,0.01,y.shape)
return x,y.reshape((-1,1))
true_w = torch.tensor([2,-3.4])
true_b = 4.2
features,labels = syn_data(true_w,true_b,1000)
features.size(),labels.size()
(torch.Size([1000, 2]), torch.Size([1000, 1]))
def load_array(data_arrays,batch_size,is_train = True):
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)
next(iter(data_iter))
[tensor([[-1.1608, -0.4292],
[ 0.1628, 0.2333],
[-0.5560, -1.4383],
[ 1.2361, -0.8098],
[-1.7198, -1.1891],
[ 0.4627, 0.2944],
[-0.6602, 3.0349],
[ 0.9641, -1.2316],
[ 0.4126, -1.6542],
[-0.4742, -1.3118]]),
tensor([[ 3.3469],
[ 3.7385],
[ 7.9730],
[ 9.4124],
[ 4.8162],
[ 4.1276],
[-7.4400],
[10.3130],
[10.6404],
[ 7.7050]])]
from torch import nn
net = nn.Sequential(nn.Linear(2,1))
net
Sequential(
(0): Linear(in_features=2, out_features=1, bias=True)
)
#初始化
net[0].weight.data.normal_(0,0.01)
net[0].bias.data.fill_(0)
tensor([0.])
loss = nn.MSELoss()
trainer = torch.optim.SGD(net.parameters(),lr = 0.03)
num_epochs = 10
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}')
epoch 1,loss 0.000305
epoch 2,loss 0.000095
epoch 3,loss 0.000095
epoch 4,loss 0.000095
epoch 5,loss 0.000096
epoch 6,loss 0.000097
epoch 7,loss 0.000095
epoch 8,loss 0.000096
epoch 9,loss 0.000096
epoch 10,loss 0.000096