code:
'''用pytorch实现线性回归'''
'''
1,准备数据
2,设计模型
3,构造损失函数和优化器
4,训练周期:前馈,反馈,更新
'''
import torch
x_data = torch.Tensor([[1.0], [2.0], [3.0]]) # 1.0 对应x的第一行
y_data = torch.Tensor([[2.0], [4.0], [6.0]])
class LinearModel(torch.nn.Module):
def __init__(self):
super(LinearModel, self).__init__()
self.linear = torch.nn.Linear(1, 1)
def forward(self, x):
y_pred = self.linear(x) # !!! linear里面就有权重w! -> w*x+b / w.T*x+b
return y_pred
model = LinearModel() #可直接被调用 callable
criterion = torch.nn.MSELoss(size_average = False)
optimizer = torch.optim.SGD(model.parameters(), lr = 0.01)
for epoch in range(100):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
print(epoch, loss)
optimizer.zero_grad()
loss.backward()
optimizer.step() # step函数用来更新
print('w =', model.linear.weight.item())
print('b = ', model.linear.bias.item())
x_test = torch.Tensor([[4.0]])
y_test = model(x_test)
print('y_pred = ',y_test.data)
效果图:
code:
不同的优化器: