基础网络模型搭建代码
import torch import numpy as np import matplotlib.pyplot as plt # 1 数据准备,使用torch。tensor进行 x_data = torch.tensor([[1.0],[2.0],[3.0]]) y_data = torch.tensor([[2.0],[4.0],[6.0]]) # 2 解释:定义一个类,继承Module,然后进行初始化操作 class LinearModel(torch.nn.Module): def __init__(self): super(LinearModel,self).__init__() self.linear = torch.nn.Linear(1,1) # self.linear = torch.nn.Linear(1,1) 定义一个可变长的,只用输入输入和输出即可 def forward(self,x): y_pred = self.linear(x) return y_pred model = LinearModel() # 创建一个类LinearModel # criterion = torch.nn.MSELoss(size_average=False) # 使用size_average出现一个userwarning,please use reduction='sum' instead. 按照提示修改如下 criterion = torch.nn.MSELoss(reduction='sum') # 应该是函数已经更新了 optimizer = torch.optim.SGD(model.parameters(),lr = 0.01) for epoch in range(1000): #使用100轮训练效果不好,说明还没有达到最优,可以修改更多轮数进行查看,效果有所改善 y_pred = model(x_data) loss = criterion(y_pred,y_data) print(epoch,loss) # 可以看到这里出现直接可以打印的loss.那是因为在内部调用了__str__,实现的打印 optimizer.zero_grad() # 涉及到权重的计算需要清零 loss.backward() # 进行反向传播 optimizer.step() # 进行更新 # output weight and bias print('w = ',model.linear.weight.item()) print('b = ',model.linear.bias.item()) # test model x_test = torch.tensor([[4.0]]) y_test = model(x_test) print('y_pred',y_test.data)