import torch
#准备训练集
x_data=torch.Tensor([[1.0],[2.0],[3.0]])
y_data=torch.Tensor([[2.0],[4.0],[6.0]])
#设计模型
class LinearModel(torch.nn.Module):#nn.Module以下大部分继承于这个
def __init__(self):
super(LinearModel,self).__init__()#guding
self.linear=torch.nn.Linear(1,1)#,Linear可以自动反向传播,结构就像wx+b输入输出维度,还有一个bias
def forward(self,x):
y_pred=self.linear(x)#实现了可调用对象
return y_pred
model=LinearModel()
#准备损失函数和优化器
criterion =torch.nn.MSELoss(size_average=False)
optimizer=torch.optim.SGD(model.parameters(),lr=0.01)#model.parameters()可以找到所有参数,优化器不唯一,Rprop,Adagrad,Adam,Adamax,ASGD,LBFGS,RMSprop,
#循环训练
#1,forward,backward,更新
for epoch in range(1000):
y_pred=model(x_data)
loss=criterion(y_pred,y_data)
print(epoch,loss)
optimizer.zero_grad()#优化,所有权重清零
loss.backward()
optimizer.step()#更新
#Output weight and bias
print("w=",model.linear.weight.item())#类后item()
print("b=",model.linear.bias.item())
#Test Model
x_test=torch.Tensor([4.0])
y_test=model(x_test)
print("y_print=",y_test.data)#数据后data
不同优化器