论文合作、课题指导请联系QQ2279055353
在一个线性模型里,假设有 p p p 个特征 x 1 , x 2 , … , x p x_1, x_2, \dots, x_p x1,x2,…,xp, 目标变量 y y y 的预测值 y ^ \hat{y} y^ 有下面的数学形式:
y ^ ( w , x ) = w 0 + w 1 x 1 + ⋯ + w p x p \hat{y}(w, x)=w_0+w_1 x_1+\dots+w_p x_p y^(w,x)=w0+w1x1+⋯+wpxp
其中, w = ( w 1 , w 2 , … , w p ) w=(w_1, w_2, \dots, w_p) w=(w1,w2,…,wp), w 0 w_0 w0 是截距项。
在线性模型里,假设 w 0 = 0 w_0=0 w0=0, 这可以通过数据的中心化实现。最小化目标变量的观测值与预测值的平方和的方法,称最小二乘法。数学上,它解决如下的函数极小值问题:
min w ∥ X w − y ∥ 2 2 \mathop{\min}\limits_{w} \| Xw-y\|_2^2 wmin∥Xw−y∥22
参数的最小二乘估计取决于特征之间的独立性条件。要使最小二乘估计有唯一解, X X X 的列向量需满足线性无关。若 X X X 的列线性相关,那么,最小二乘估计具有较大的方差,对目标变量的观测偏差高度敏感。这种情况称多重共线性(multicollinearity
),当数据没有经过实验设计而获得时容易产生。
在一个线性模型里,当目标变量 y y y 是数量变量时,称该模型为线性回归模型。
现在,举一个单特征的线性回归,即,一元线性回归的例子。该例使用的数据集是diabetes
. 预测模型
y ^ i = w 0 + w 1 x i \hat{y}_i=w_0+w_1 x_i y^i=w0+w1xi
它对应一条回归直线。下面,我们将观测数据与回归直线画在一张图上,观测预测误差。
print(__doc__)
# Code source: Jaques Grobler
# License: BSD 3 clause
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
# Load the diabetes dataset
diabetes_X, diabetes_y = datasets.load_diabetes(return_X_y=True)
# Use only one feature
diabetes_X = diabetes_X[:, np.newaxis, 2]
# Split the data into training/testing sets
diabetes_X_train = diabetes_X[:-20]
diabetes_X_test = diabetes_X[-20:]
# Split the targets into training/testing sets
diabetes_y_train = diabetes_y[:-20]
diabetes_y_test = diabetes_y[-20:]
# Create linear regression object
regr = linear_model.LinearRegression()
# Train the model using the training sets
regr.fit(diabetes_X_train, diabetes_y_train)
# Make predictions using the testing set
diabetes_y_pred = regr.predict(diabetes_X_test)
# The coefficients
print('Coefficients: \n', regr.coef_)
# The mean squared error
print('Mean squared error: %.2f'
% mean_squared_error(diabetes_y_test, diabetes_y_pred))
# The coefficient of determination: 1 is perfect prediction
print('Coefficient of determination: %.2f'
% r2_score(diabetes_y_test, diabetes_y_pred))
# Plot outputs
plt.scatter(diabetes_X_test, diabetes_y_test, color='black')
plt.plot(diabetes_X_test, diabetes_y_pred, color='blue', linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()