美文网首页
ML:自己动手实现单变量线性回归算法

ML:自己动手实现单变量线性回归算法

作者: ACphart | 来源:发表于2018-09-05 00:46 被阅读19次

    介绍

    • 注意:这里的代码都是在Jupyter Notebook中运行,原始的.ipynb文件可以在我的GitHub主页上下载 https://github.com/acphart/Hand_on_ML_Algorithm 其中的LinearRegression_single_variabel.ipynb,直接在Jupyter Notebook中打开运行即可,里面还有其他的机器学习算法实现,喜欢可以顺便给个star哦 ~~~

    这里是实现单变量线性回归算法的训练过程

    import numpy as np
    import matplotlib.pyplot as plt
    from IPython.core.interactiveshell import InteractiveShell
    
    InteractiveShell.ast_node_interactivity = 'all'
    

    生成模拟数据

    • 模拟数据的内在模式是 y = 2.0x_0 + 2.9x_1 \quad (x_0 = 1)
    • 也就是一个一次函数,我们在数据中加入随机噪声,就得到了模拟数据
    np.random.seed(20180822)
    
    m = 100
    Theta = [[2.0], [2.9]]
    
    x0 = np.ones((m,1))
    x1 = np.linspace(-2, 5, m).reshape(m, 1)
    
    X = np.hstack((x0, x1))
    y = np.dot(X, Theta) + 2.0*np.random.randn(100,1)
    
    _ = plt.scatter(x1, y)
    

    损失函数、梯度函数

    • 这是实现的主要工作,定义我们的损失函数和梯度函数
    • 损失函数是 Loss(\theta, X) = \frac{1}{2m}\sum_{i = 1}^m[h_\theta(x^{(i)}) - y^{(i)}]^2
    • 梯度函数是 \frac{\partial}{\partial \theta_j} Loss(\theta, X) = \frac{1}{m}\sum_{i = 1}^m[h_\theta(x^{(i)}) - y^{(i)}]x_j^{(i)}
    • 这里基本的优化就是把循环求和操作向量化:
      Loss(\theta, X) = \frac{1}{2m}[h_\theta(X) - y]^T[h_\theta(X) - y]
      \nabla Loss(\theta, X) = \frac{1}{m}X^T[h_\theta(X) - y]
    def loss_func(X, y, theta,):
        loss = np.dot(X, theta) - y
        return 1./(2*m) * np.dot(loss.T, loss)
    
    def grad_func(X, y, theta):
        loss = np.dot(X, theta) - y
        return 1./m * np.dot(X.T, loss)
    
    

    梯度下降

    • 我们的假设函数为: h_\theta(x) = \theta_0 x_0+ \theta_1 x_1 \quad (x_0 = 1)
    • 在梯度下降训练过程中,我们利用颜色的深浅把拟合直线画出来,我们可以看到拟合的效果越来越好
    # 设置学习率和收敛停止的开关
    alpha = 0.01
    accuracy = 1e-5
    
    # 初始化参数
    theta = np.random.randn(2,1)*0.1
    
    i = 1
    index = 1
    c = np.array([0.8, 0.8, 0.8])   # 设置颜色,颜色逐渐加深
    grad = grad_func(X, y, theta)   # 初始梯度
    while not np.all(abs(grad) < accuracy):
        theta = theta - alpha*grad
        grad = grad_func(X, y, theta)
        
        # 作出学习过程
        i = i+1
        if i%index == 0:
            _ = plt.plot(x1, np.dot(X, theta), color=c)
            c = c - 0.1
            index = index*4
    
    _ = plt.scatter(x1, y, alpha=0.7)
    theta    
    
    • 输出算法训练后拟合的参数,和我们的模式函数的参数很接近,想要更好的结果还可以修改收敛停止的开关。
        array([[ 2.0953245],
               [ 2.9086616]])
    

    相关文章

      网友评论

          本文标题:ML:自己动手实现单变量线性回归算法

          本文链接:https://www.haomeiwen.com/subject/vbrsiftx.html