21Winter\ 使用torch.nn 模块进行线性回归

在pytorch之中,torch.nn 是一个非常重要的模块。

建议在学习的时候学习这部分内容的时候可以先会看一下面向对象有关的内容。这里面对于父类的继承、复写其实会有较多的涉及。

总体的思路是,我们借用pytorch这个框架,但是在继承nn这个父类的基础上写自己的子类。

我们在写子类的时候最主要的是写def __init__和def forward() 这两个方法,一个是初始化,一个是调用的时候执行什么样的操作。

其实调用pytorch框架有一个更好的优点,在使用过程之中我们可以根本不用考虑.grad或者是.requires_grad 这几个属性,优化的目标也可以直接使用.parameters返回,与之前pytorh手工进行autograd相比真的方便了很多很多。

本质上就是给很多类传入参数,使之实例化,成为程序之中可以调用的对象。

大致思路:

1. 数据来源:numpy的读取,并进行tensor转化

2. 构建自己的计算方法,得到pred的方法

3. 实例化类:

                        (1)自定义的类(如文中的Linear)

                        (2)优化器的实例化(optimizer)

                        (3)Loss函数的实例化(criterion)

4. epoch循环,进行参数的优化

                                注意其中的梯度清零

import torch
import torch.nn as nn
import numpy as np


dataset_numpy = np.loadtxt("data2.txt", delimiter=',')
dataset = torch.from_numpy(dataset_numpy[:, 0:2]).float()
y = torch.from_numpy(dataset_numpy[:, -1]).float()
#TODO: maybe we should change the defaulted type(dtype) to float in Pycharm.
#ATTENTION: when importing data from a numpy array, we should change the type to torch.float32 or errors may occur.

class Linear(nn.Module):
    def __init__(self):
        super(Linear, self).__init__()
# to inherit the parent class that has a lot of built-in functions.
        self.linear = nn.Linear(2,1)
# 实例化Linear类,self.linear是Linear这个Module特有的方法

    def forward(self, x):
        predict = self.linear(x)
        return predict
'''
When claiming a network, or a computing unit, the __init__ and __forward__ are quite essential steps.
We may get bewildered by 'linear', for they appeared twice both in __init__ and __forward__. 
But when we look into the internal codes, our puzzles may become a bit clearer.

in Line 14:
    self.linear = nn.Linear(2,1)
    -def __init__(self, in_features: int, out_features: int, bias: bool = True,
                 device=None, dtype=None) -> None:
    we use this to initialize a linear function to compute:
                y = w * x + b
    where:
                w: weights
                x: input
                b: bias value
    
in Line 17:
    we will call the objectified "linear" to return a value.
'''

model = Linear()
criterion = nn.MSELoss()
# 实例化MSE这个类,然后调用criterion的时候调用的就是这个类里面的__call__方法
optimizer = torch.optim.Adam(model.parameters(), lr=10)
# 实例化优化器.Adam类

for epoch in range(1000):
    for j in range(len(dataset)):
        pred = model(dataset[j])
        loss = criterion(pred,y[j])
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

for i in range(len(dataset)):
    pred = model(dataset[i])
    print(i,pred.item(), y[i].item())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值