🍠Python简单线性回归算法实现及应用示例
Python | 简单线性回归 SLR | TensorFlow.js
Python线性回归算法实现
简单线性回归,是一种使用单个特征预测响应的方法。 它是机器学习爱好者了解的最基本的机器学习模型之一。 在线性回归中,我们假设两个变量,即因变量和自变量是线性相关的。 因此,我们尝试找到一个线性函数,作为特征或自变量 (x) 的函数,尽可能准确地预测响应值 (y)。 让我们考虑一个数据集,其中每个特征 x 都有一个响应 y 值:
为了一般性,我们定义:
x 作为特征向量,比如
y 作为响应向量,比如
对于 n 个观测值(在上面的示例中,n=10)。上述数据集的散点图如下所示:
现在,任务是在上面的散点图中找到一条最适合的线,以便我们可以预测任何新特征值的响应。 (即数据集中不存在 x 的值)这条线称为回归线。 回归线的方程表示为:
- 表示第 i 个观测值的预测响应值。 
- 和是回归系数,分别表示回归线的 y 截距和斜率。 
为了创建我们的模型,我们必须“学习”或估计回归系数 和 的值。一旦我们估计了这些系数,我们就可以使用该模型来预测响应!
在本文中,我们将使用最小二乘法原理。
这里, 是第 i 个观测值的残差。因此,我们的目标是最小化总残差。我们将平方误差或成本函数 J 定义为:
我们的任务是找到使 最小的 和 的值!不涉及数学细节,我们在这里展示结果:
其中 是 y 和 x 的交叉偏差之和:
是 x 的偏差平方和:
我们可以使用Python语言来学习线性回归模型的系数。为了绘制输入数据和最佳拟合线,我们将使用 Matplotlib 库。它是最常用的用于绘制图表的 Python 库之一。
import numpy as np
import matplotlib.pyplot as plt
def estimate_coef(x, y):
    # number of observations/points
    n = np.size(x)
    # mean of x and y vector
    m_x = np.mean(x)
    m_y = np.mean(y)
    # calculating cross-deviation and deviation about x
    SS_xy = np.sum(y*x) - n*m_y*m_x
    SS_xx = np.sum(x*x) - n*m_x*m_x
    # calculating regression coefficients
    b_1 = SS_xy / SS_xx
    b_0 = m_y - b_1*m_x
    return (b_0, b_1)
def plot_regression_line(x, y, b):
    # plotting the actual points as scatter plot
    plt.scatter(x, y, color = "m",
            marker = "o", s = 30)
    # predicted response vector
    y_pred = b[0] + b[1]*x
    # plotting the regression line
    plt.plot(x, y_pred, color = "g")
    # putting labels
    plt.xlabel('x')
    plt.ylabel('y')
    # function to show plot
    plt.show()
def main():
    # observations / data
    x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])
    # estimating coefficients
    b = estimate_coef(x, y)
    print("Estimated coefficients:\nb_0 = {} \
        \nb_1 = {}".format(b[0], b[1]))
    # plotting regression line
    plot_regression_line(x, y, b)
if __name__ == "__main__":
    main()
输出:
Estimated coefficients:
b_0 = -0.0586206896552
b_1 = 1.45747126437多元线性回归
Python简单线性回归建立电视广播报纸销售额模型
Python简单线性回归分析职场经验和薪水关系
TensorFlow.js创建简单线性回归
Last updated
Was this helpful?
