从头开始简单理解线性回归(附Python 实现)

liftword3周前 (04-11)技术文章15

本文讨论了线性回归的基础知识及其在 Python 编程语言中的实现。 线性回归是一种统计方法,用于对因变量与一组给定的自变量之间的关系进行建模。

注意:在本文中,为简单起见,我们将因变量称为标签,将自变量称为特征。 为了提供对线性回归的基本理解,我们从线性回归的最基本版本开始,即Simple linear regression。

简单线性回归

简单线性回归是一种使用单一特征预测标签的方法。假设这两个变量是线性相关的。因此,我们试图找到一个线性函数,它尽可能准确地预测标签值 (y) 作为特征或自变量 (x) 的函数。让我们考虑一个数据集,其中每个特征 x 都有一个标签值 y:

68b56fb0cd5ca_OZFe9y

为了一般性,我们定义: x 为特征向量,即 x = [x_1, x_2, …., x_n], y 为标签向量,即 y = [y_1, y_2, …., y_n] 对于n 个观测值(在上例中, n=10). 上述数据集的散点图如下所示:

我们在小数据集上的 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()

输出:

估计系数:
b_0 = -0.0586206896552 
b_1 = 1.45747126437

获得的图表如下所示:

多元线性回归


如前所述,最小二乘法倾向于确定总残差最小的。 我们在这里直接给出结果:

其中 ' 表示矩阵的转置,而 -1 表示逆矩阵。 知道最小二乘估计 b',多元线性回归模型现在可以估计为:

其中是估计的标签向量。 注意:可以在此处找到在多元线性回归中获得最小二乘估计的完整推导。

使用 Scikit-learn 对波士顿房价数据集进行多元线性回归技术的 Python 实现。

import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model, metrics

# load the boston dataset
boston = datasets.load_boston(return_X_y=False)

# defining feature matrix(X) and response vector(y)
X = boston.data
y = boston.target

# splitting X and y into training and testing sets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4,
             random_state=1)

# create linear regression object
reg = linear_model.LinearRegression()

# train the model using the training sets
reg.fit(X_train, y_train)

# regression coefficients
print('Coefficients: ', reg.coef_)

# variance score: 1 means perfect prediction
print('Variance score: {}'.format(reg.score(X_test, y_test)))

# plot for residual error

## setting plot style
plt.style.use('fivethirtyeight')

## plotting residual errors in training data
plt.scatter(reg.predict(X_train), reg.predict(X_train) - y_train,
   color = "green", s = 10, label = 'Train data')

## plotting residual errors in test data
plt.scatter(reg.predict(X_test), reg.predict(X_test) - y_test,
   color = "blue", s = 10, label = 'Test data')

## plotting line for zero residual error
plt.hlines(y = 0, xmin = 0, xmax = 50, linewidth = 2)

## plotting legend
plt.legend(loc = 'upper right')

## plot title
plt.title("Residual errors")

## method call for showing the plot
plt.show()

输出:

Coefficients: 
[ -8.80740828e-02 6.72507352e-02 5.10280463e-02 2.18879172e+00 -1.72283734e+01 3.62985243e+00 
2.13933641e-03 -1.36531300e+00 2.88788067e-01 -1.22618657e 
-02 -8.36014969e -01 9.53058061e-03 
-5.05036163e-01]
方差得分:0.720898784611

残留误差图如下所示:

下面给出了线性回归模型对应用它的数据集所做的基本假设:

  • 线性关系:标签和特征变量之间的关系应该是线性的。可以使用散点图测试线性假设。如下所示,第一个图表示线性相关的变量,而第二个和第三个图中的变量很可能是非线性的。因此,第一个图将使用线性回归给出更好的预测。

  • 很少或没有多重共线性:假设数据中很少或没有多重共线性。当特征(或自变量)彼此不独立时,就会出现多重共线性。
  • 很少或没有自相关:另一个假设是数据中很少或没有自相关。当残差彼此不独立时,就会出现自相关。
  • 同方差性:同方差性描述了一种情况,其中误差项(即自变量和因变量之间关系中的“噪声”或随机扰动)在自变量的所有值中都相同。如下所示,图 1 具有同方差性,而图 2 具有异方差性。

相关文章

python zip函数可以实现同时遍历多列表,以及矩阵转置等

zip 函数是Python的内置函数,用于将多个可迭代对象中对应位置的元素打包成元组,并返回一个由这些元组组成的迭代器。 概念看不懂没关系,我们来举个简单例子。比如有两个列表x=["a","b","c...

矩阵的转置

有关矩阵的讲解,在之前我已经提过了,矩阵是一个数表,大家一定要记清楚!下面我们来说一说矩阵的转置,首先来了解一下定义:定义:把一个m×n矩阵A的行换成同序数的列而得到的n×m矩阵,称为矩阵A的转置矩阵...

C++矩阵转置

C++矩阵转置看了很多网山有关矩阵转置的代码,大部分还用了中间变量,本人亲测矩阵转置代码无误,望对广大C++初学者有所帮助!题目如下:写一个函数,使给定的一个二维数组(3x3)转置,即行列互换。Inp...

4.NumPy数组操作

4.NumPy数组操作4.1改变NumPy数组维度前面已经学习了怎样使用reshape函数,接下来我们来学习展开数组ravelravel函数完成展平数组的操作。import numpy as npb...

Python推导式功能:一行代码搞定复杂逻辑

对话实录小白:(抓狂)我写了 10 行循环,同事用 1 行就搞定了!专家:(掏出魔杖)掌握推导式,代码瞬间瘦身!三大推导式1. 列表推导式传统写法需要先创建一个空列表,然后通过循环逐个计算并添加元素。...

Python中zip()函数详解:合并、解压与高效数据处理

在Python中,zip() 是一个非常实用的内置函数,用于将多个可迭代对象(如列表、元组、字符串等)合并成一个元组的列表。它通过将输入的每个可迭代对象的元素按位置配对,生成一个迭代器,其中每个元素是...