scikit-learn学习笔记:1.1 广义线性模型-普通的最小二乘(Ordinary Least Squares)

1.1. 广义线性模型(Generalized Linear Models)

接下来的部分是一组回归的方法,其中目标值是被期望是输入变量的线性组合。用数学符号表示,如果 y^ 是预计的值。

y^(w,x)=w0+w1x1+...+wpxp

在整个模块中,我们设计向量 w=(w1,...,wp) 作为coef_并且 w0 作为intercept_
用广义的线性模型来执行分类,见逻辑回归(Logistic regression)。

1.1.1普通的最小二乘(Ordinary Least Squares)

LinearRegression是用参数 w=(w1,...,wp) 去拟合线性模型,并且最小化在数据中观察到的响应的残差平方和,并且通过线性近似来对响应进行预测。数学上它的形式是:

minwXwy22

LinearRegression将使用fitmethod阵列X、y并且将用线性模型在它的coef_中存储参数 w

>>> from sklearn import linear_model
>>> clf = linear_model.LinearRegression()
>>> clf.fit ([[0, 0], [1, 1], [2, 2]], [0, 1, 2])
#[[0, 0], [1, 1], [2, 2]] is X and [0, 1, 2] is y
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
>>> clf.coef_
array([ 0.5,  0.5])

然而,对于普通的最小二乘系数估计要依靠于模型项的独立性。当项是相关的并且被设计的矩阵X的纵行有一个近似线性的关系,设计的矩阵变得很接近奇异,其结果,最小二乘估计对观察到的响应中的随机错误有着很高的敏感度,产生一个很大的方差。多重共线性(multicollinearity)可能会出现,例如当数据被未经实验设计所收集的情况。

Python source code

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

# Load the diabetes dataset
diabetes = datasets.load_diabetes()


# Use only one feature
diabetes_X = diabetes.data[:, 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.target[:-20]
diabetes_y_test = diabetes.target[-20:]

# Create linear regression object
regr = linear_model.LinearRegression()

# Train the model using the training sets
regr.fit(diabetes_X_train, diabetes_y_train)

# The coefficients
print('Coefficients: \n', regr.coef_)
# The mean square error
print("Residual sum of squares: %.2f"
      % np.mean((regr.predict(diabetes_X_test) - diabetes_y_test) ** 2))
# Explained variance score: 1 is perfect prediction
print('Variance score: %.2f' % regr.score(diabetes_X_test, diabetes_y_test))

# Plot outputs
plt.scatter(diabetes_X_test, diabetes_y_test,  color='black')
plt.plot(diabetes_X_test, regr.predict(diabetes_X_test), color='blue',
         linewidth=3)

plt.xticks(())
plt.yticks(())

plt.show()

Script output:

Coefficients:
[ 938.23786125]
Residual sum of squares: 2548.07
Variance score: 0.47

你可能感兴趣的:(scikit-learn笔记,scikit)