孔乙己的线性回归

作者: readilen | 来源:发表于2019-07-29 09:49 被阅读2次

    改编自鲁迅《孔乙己》:

    在这些时候,我可以附和着笑,老板是决不责备的。而且老板见了孔乙己,也每每这样问他,引人发笑。孔乙己自己知道不能和他们谈天,便只好向孩子说话。有一回对我说道,“你学过人工智能么?”我略略点一点头。他说,“学过一点,……我便考你一考。机器学习的线性回归,你会写吗?”我想,讨饭一样的人,也配考我么?便回过脸去,不再理会。孔乙己等了许久,很恳切的说道,“不能写罢?……我教给你,记着!这些是应该记着。将来做老板的时候,必须要用的。”我暗想我和老板的等级还很远呢,而且我们老板也从不用线性回归跑数据;又好笑,又不耐烦,懒懒的答他道,“谁要你教,不就是sklearn下的LinearRegression吗?”孔乙己显出极高兴的样子,将两个指头的长指甲敲着柜台,点头说,“对呀对呀!……线性回归有四样写法,你知道么?”我愈不耐烦了,努着嘴走远。孔乙己从怀里掏出ThinkPad T60,想码字,见我毫不热心,便又叹一口气,显出极惋惜的样子。

    代码前准备

    f(x) = w^{T}x+b
    其中w叫做权重系数,b叫做偏置项。
    那么如何确定w,b呢。关键在于我们的预测值和实际值间的差距。在回归任务中,均方误差是最常用的性能度量。

    from __future__ import division, print_function, unicode_literals
    
    # Common imports
    import numpy as np
    import os
    
    # to make this notebook's output stable across runs
    np.random.seed(42)
    
    # To plot pretty figures
    %matplotlib inline
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    
    X = 2 * np.random.rand(100, 1)
    y = 4 + 3 * X + np.random.randn(100, 1)
    

    我们看看数据情况

    plt.plot(X, y, "b.")
    plt.xlabel("$x_1$", fontsize=18)
    plt.ylabel("$y$", rotation=0, fontsize=18)
    plt.axis([0, 2, 0, 15])
    save_fig("generated_data_plot")
    plt.show()
    
    image.png

    法1

    X_b = np.c_[np.ones((100, 1)), X]  # add x0 = 1 to each instance
    theta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y)
    
    theta_best
    X_new = np.array([[0], [2]])
    X_new_b = np.c_[np.ones((2, 1)), X_new]  # add x0 = 1 to each instance
    y_predict = X_new_b.dot(theta_best)
    y_predict
    
    plt.plot(X_new, y_predict, "r-")
    plt.plot(X, y, "b.")
    plt.axis([0, 2, 0, 15])
    plt.show()
    
    image.png

    法2

    from sklearn.linear_model import LinearRegression
    lin_reg = LinearRegression()
    lin_reg.fit(X, y)
    lin_reg.intercept_, lin_reg.coef_
    lin_reg.predict(X_new)
    

    法3

    LinearRegression 是基于scipy.linalg.lstsq()函数 (是标准的 "least squares")因此可以直接使用:

    theta_best_svd, residuals, rank, s = np.linalg.lstsq(X_b, y, rcond=1e-6)
    theta_best_svd
    

    法4

    使用Moore-Penrose逆矩阵计算

    np.linalg.pinv(X_b).dot(y)
    

    相关文章

      网友评论

        本文标题:孔乙己的线性回归

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