人工智能之机器学习-逻辑回归、回归(Regression)-Pytorch快速实现

人工智能之机器学习-逻辑回归、回归(Regression)-Pytorch快速实现

谢谢:
https://zhuanlan.zhihu.com/p/74874291?utm_source=com.youdao.note
https://zhuanlan.zhihu.com/p/86982616
https://zhuanlan.zhihu.com/p/127972563

先把宝可梦之王李老师的课件拿出来
人工智能之机器学习-逻辑回归、回归(Regression)-Pytorch快速实现

概述

人工智能之机器学习-逻辑回归、回归(Regression)-Pytorch快速实现
先给出直观的描述。

回归问题是机器学习三个基本模型的重要组成部分,其功能是对变量之间的关系进行建模和分析。

回归问题多用来预测一个具体的数值,如预测房价、未来的天气情况等等。例如我们根据一个地区的若干年的PM2.5数值变化来估计某一天该地区的PM2.5值大小,预测值与当天实际数值大小越接近,回归分析算法的可信度越高。

面对一个回归问题,我们可以简单描述一下它的求解过程:

选定训练模型,即我们为程序选定一个求解框架,如线性回归模型(Linear Regression)等。
导入训练集 train_set,即给模型提供大量可供学习参考的正确数据。
选择合适的学习算法,让程序通过训练集中的大量输入输出结果,不断优化输入数据和输出数据的相关性,从而提高模型的预测精度。
训练后,模型可以预测结果。我们为程序提供了一组新的输入数据,模型根据训练集的学习结果预测出这组输入对应的输出值。

Mr. Li Hongyi Li said:
人工智能之机器学习-逻辑回归、回归(Regression)-Pytorch快速实现
关键的loss,也是训练所要做的事情
人工智能之机器学习-逻辑回归、回归(Regression)-Pytorch快速实现

直接上pytorch

注意:这里使用cpu模式,可以增加todevice的cuda判断使用cuda加速运算。

网络建设

class LinearRegression(torch.nn.Module):
    """
    Linear Regressoin Module, the input features and output 
    features are defaults both 1
    """
    def __init__(self):
        super().__init__()
        self.linear = torch.nn.Linear(1,1)
        
    def forward(self,x):
        out = self.linear(x)
        return out

人工智能之机器学习-逻辑回归、回归(Regression)-Pytorch快速实现

设置优化器

self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.learning_rate)
torch.optim.Adam(params,lr,betas, eps=,weight_decay,amsgrad)

人工智能之机器学习-逻辑回归、回归(Regression)-Pytorch快速实现

选择损失函数

这里使用最为常用的mseloss方法

self.loss_function = torch.nn.MSELoss()

人工智能之机器学习-逻辑回归、回归(Regression)-Pytorch快速实现

开始训练(炼金术)

import torch 
import matplotlib.pyplot as plt

def create_linear_data(nums_data, if_plot= False):
    """
    Create data for linear model
    Args:
        nums_data: how many data points that wanted
    Returns:
        x with shape (nums_data, 1)
    """
    x = torch.linspace(0,1,nums_data)
    x = torch.unsqueeze(x,dim=1)
    k = 2
    y = k * x + torch.rand(x.size())
    
    if if_plot:
        plt.scatter(x.numpy(),y.numpy(),c=x.numpy())
        plt.show()
    data = {"x":x, "y":y}
    return data

data = create_linear_data(300, if_plot=True)
print(data["x"].size())

def train(self, data, model_save_path="model.pth"):
        """
        Train the model and save the parameters
        Args:
            model_save_path: saved name of model
            data: (x, y) = data, and y = kx + b
        Returns: 
            None
        """
        x = data["x"]
        y = data["y"]
        for epoch in range(self.epoches):
            prediction = self.model(x)
            loss = self.loss_function(prediction, y)

            self.optimizer.zero_grad()
            loss.backward()
            self.optimizer.step()

            if epoch % 500 == 0:
                print("epoch: {}, loss is: {}".format(epoch, loss.item()))
        torch.save(self.model.state_dict(), "linear.pth")

测试模式(nograd)

def test(self, x, model_path="linear.pth"):
        """
        Reload and test the model, plot the prediction
        Args:
            model_path: the model's path and name
            data: (x, y) = data, and y = kx + b
        Returns:
            None
        """
        x = data["x"]
        y = data["y"]
        self.model.load_state_dict(torch.load(model_path))
        prediction = self.model(x)
        
        plt.scatter(x.numpy(), y.numpy(), c=x.numpy())
        plt.plot(x.numpy(), prediction.detach().numpy(), color="r")
        plt.show()

高级指南

这块想要进阶只能在dataloader和batch上下文章了,加快训练速度并且提升模型泛化能力,其他的好像没有什么可以做的了。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2022年3月24日 下午12:18
下一篇 2022年3月24日

相关推荐