pytorch框架实现线性回归

pytorch框架实现线性回归

基础知识:call(),魔术方法的使用。

#__call___(): 使得类对象具有类似函数的功能。
class A():
    def __call__(self):
        print('i can be called like a function')
a = A()
a()  #结果:i can be called like a function

1、调用pytorch框架,创建张量w,求解动态计算图(dynamic computational graph)。

import torch

# 1、prepare dataset
# x,y是矩阵,3行1列 也就是说总共有3个数据,每个数据只有1个特征,其是mini-bach的形式,每个bach中有三个数据
x_data = torch.tensor([[1.0], [2.0], [3.0]])
y_data = torch.tensor([[2.0], [4.0], [6.0]])

2、通过class(类),设计线性模型。目的是为了前向传播forward,即计算y hat(预测值)

# 2、design model using class
"""
our model class should be inherit from nn.Module, which is base class for all neural network modules.
member methods __init__() and forward() have to be implemented
class nn.linear contain two member Tensors: weight and bias
class nn.Linear has implemented the magic method __call__(),which enable the instance of the class can
be called just like a function.Normally the forward() will be called 
"""

class LinearModel(torch.nn.Module):
    def __init__(self):
        super(LinearModel, self).__init__()
        # (1,1)是指输入x和输出y的特征维度,这里数据集中的x和y的特征都是1维的
        # 该线性层需要学习的参数是w和b  获取w/b的方式分别是~linear.weight/linear.bias
        self.linear = torch.nn.Linear(1, 1)   # (1,1)是指输入x和输出y的特征维度,这里数据集中的x和y的特征都是1维的

    def forward(self, x):
        y_pred = self.linear(x)     ##实现了__call___: 使得类对象具有类似函数的功能。
        return y_pred
        
model = LinearModel()  #创建线性模型,model

3、计算loss是为了进行反向传播,optimizer是为了更新梯度。
本实例是批量数据处理,不要被optimizer = torch.optim.SGD(model.parameters(), lr = 0.01)误导了,以为见了SGD就是随机梯度下降。要看传进来的数据是单个的还是批量的。这里的x_data是3个数据,是一个batch,调用的PyTorch API是 torch.optim.SGD,但这里的SGD不是随机梯度下降,而是批量梯度下降。也就是说,梯度下降算法使用的是随机梯度下降,还是批量梯度下降,还是mini-batch梯度下降,用的API都是 torch.optim.SGD。

# 3、construct loss and optimizer
# criterion = torch.nn.MSELoss(size_average = False)
criterion = torch.nn.MSELoss(reduction='sum')  #此时是把所有的损失相加,而不求平均
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)  # model.parameters()自动完成参数的初始化操作

4、进行100轮的循环训练,①前向传播,求y hat (输入的预测值)②根据y_hat和y_label(y_data)计算loss③反向传播 backward (计算梯度)④根据梯度,更新参数

# 4、training cycle forward, backward, update
for epoch in range(100):
    y_pred = model(x_data)  # forward:predict     1、算预测值
    loss = criterion(y_pred, y_data)  # forward: loss    2、算损失
    print(epoch, loss.item())

    optimizer.zero_grad()  # the grad computer by .backward() will be accumulated. so before backward, remember set the grad to zero,梯度清零
    loss.backward()  # backward: autograd,自动计算梯度    3、反馈,进行梯度运算
    optimizer.step()  # update 参数,即更新w和b的值    4、优化,更新参数(w,b)

print('w = ', model.linear.weight.item())
print('b = ', model.linear.bias.item())
#5、对训练的模型参数进行测试。
x_test = torch.tensor([[4.0]])
y_test = model(x_test)
print('y_pred = ', y_test.data)  #result:y_pred =  tensor([[7.6951]])
# print('y_pred = ', y_test.item()) #结果为:y_pred =  7.461838245391846

程序执行后的结果,显示了经过每轮的训练之后,模型的损失值是多少;经过100轮的训练之后,输出最后模型参数w和b的值;最终当输入张量为“4”时,模型的测试值。
pytorch框架实现线性回归_第1张图片

你可能感兴趣的:(pytorch深度学习,pytorch,python,深度学习)