[d2l]线性回归的简单实现

生成数据集

true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = d2l.sythetic.data(true_w, true_b, 1000)

读取数据集

def load_array(data_arrays, batch_size):
	#创建Tensor类型数据集
	dataset = data.TensorDataset(*data_arrys)
	return data.DataLoader(dataset, batch_size, shufftle=True)


batch_size = 10
# data.DataLoder类型
data_iter = load_array((features, labels), batch_size)

创建线性模型

net = nn.Sequential(nn.Linear(2, 1))

初始化模型

net[0].weight.data.normal_(0, 0.01)
net[0].bias.data.fill_(0)

定义损失函数

loss = 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:
		# loss(y_hat, y)
		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}')

你可能感兴趣的:(d2l,线性回归,深度学习,算法)