线性回归和岭回归代码详解及Demo

19 篇文章 3 订阅
11 篇文章 0 订阅

最近有小伙伴问我说,有没有sklearn的代码详解,前面博客讲的有点偏理论了。接受了小伙伴的意见,以后大管就理论和代码穿插着聊吧。今天咱就来聊一聊sklearn中线性回归和岭回归(L2正则)的代码详解吧。

sklearn.linear_model.LinearRegression

      使用的方法是最小线性二乘回归,线性回归拟合系数w = (w1,…,wp)的线性模型,以最小化数据集中观测目标与线性逼近预测目标之间的残差平方和。

调用函数:

sklearn.linear_model.LinearRegression(fit_intercept=True, normalize=False, copy_X=True, n_jobs=None)

参数: 

fit_intercept:bool, optional, default True 当选择true时使用截距,设置为False时,不使用截距。

Normalize:bool,optional, default False 是否要进行规范化(默认忽略),当fit_intercept为false时,默认关闭规范化,当把规范化开启时则回归前对回归量X进行归一化处理,即减去均值,然后除以l2-范数。如果您希望标准化,请使用sklearn.预处理。在使用normalize=False调用对估计量的拟合之前调用StandardScaler。

copy_X:bool, optional, default True 如果为真,输入的X会被复制;否则,它可能被覆盖。

n_jobs:int or None, optional (default=None)用于要计算作业的数量,默认为None,当大于1时或者计算量足够大时开启加速。None意味着为1,-1表示使用所有的处理器。

属性:

coef_:array of shape (n_features, ) or (n_targets, n_features)线性回归的系数,如果输入为2维的,那输出也是2维数组(n_targets, n_features),如果输入是一维的,

那输出就是长度为n_features的一维数组。

rank_:int 当输入X是稠密的时为矩阵X的秩

singular_:array of shape (min(X, y),) 矩阵X的奇异值,当X为稠密的时可用。

intercept_:float or array of shape of (n_targets,) 线性模型中的独立项(线性模型为一次时的截距)。如果fit_intercept = False,则将其设置为0.0。

示例代码:

import numpy as np
>>> from sklearn.linear_model import LinearRegression
>>> X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
>>> # y = 1 * x_0 + 2 * x_1 + 3
>>> y = np.dot(X, np.array([1, 2])) + 3
>>> reg = LinearRegression().fit(X, y)
>>> reg.score(X, y)
1.0
>>> reg.coef_
array([1., 2.])
>>> reg.intercept_
3.0000...
>>> reg.predict(np.array([[3, 5]]))
array([16.])

fit(self, X, y[, sample_weight]) 训练模型 :

X{array-like, sparse matrix} of shape (n_samples, n_features) 训练数据集

yarray-like of shape (n_samples,) or (n_samples, n_targets) 标签值。如果有必要,会转换成X的形状。

sample_weightarray-like of shape (n_samples,), default=None 默认为false,每个样本独立的权值。

get_params(self[, deep])  获取此模型的参数 :deepbool, default=True 如果为真,将返回此估计器的参数以及包含的作为估计器的子对象,返回值:paramsmapping of string to any 参数名映射到它们的值

predict(self, X)  使用此线性模型来预测值   :Xarray_like or sparse matrix, shape (n_samples, n_features) 输入样本,返回值为预测的值。

score(self, X, y[, sample_weight]) 返回预测的决定系数R^2。系数R^2定义为(1 - u/v),其中u为残差平方和((y_true - y_pred) ** 2).sum(), v为总平方和((y_true - y_true.mean() ** 2).sum()。最好的分数是1.0,也可能是负数(因为模型可能会任意变差)。如果一个常数模型总是预测y的期望值,而不考虑输入特性,则会得到R^2的0.0分。X:array-like of shape (n_samples, n_features) 测试样本,y:array-like of shape (n_samples,) or (n_samples, n_outputs) 样本X的真实值,sample_weightarray-like of shape (n_samples,), default=None  样本的权重,返回值:score(float) R^2系数。

set_params(self, \*\*params)  设置此估计器的参数。该方法既适用于简单的估计器,也适用于嵌套对象(如管道)。后者具有__的参数,因此可以更新嵌套对象的每个组件。

**params(dict) 估计的参数,返回值,估计的实例。

下面我们使用它来写一段代码吧

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()

 最后的输出结果:

Coefficients:  [938.23786125]

Mean squared error: 2548.07

Coefficient of determination: 0.47

sklearn.linear_model.Ridge

该模型解决了损失函数为线性最小二乘函数、正则化为l2范数的回归模型

最小化目标函数:||y - Xw||^2_2 + alpha * ||w||^2_2。

调用函数

sklearn.linear_model.Ridge(alpha=1.0, fit_intercept=True, normalize=False, copy_X=True, max_iter=None, tol=0.001, solver='auto', random_state=None)

参数

alpha{float, ndarray of shape (n_targets,)}, default=1.0  正则化强度;必须是正的浮点型。正则化改进了问题的条件,减少了估计的方差。值越大正则化强度越强。在其他线性模型如逻辑回归或线性svc中,对应的是C^-1。如果传递了一个数组,则假定惩罚是特定于目标的。因此它们在数量上必须一致

fit_intercept:bool, optional, default True 当选择true时使用截距,设置为False时,不使用截距。

Normalize:bool,optional, default False 是否要进行规范化(默认忽略),当fit_intercept为false时,默认关闭规范化,当把规范化开启时则回归前对回归量X进行归一化处理,即减去均值,然后除以l2-范数。如果您希望标准化,请使用sklearn.预处理。在使用normalize=False调用对估计量的拟合之前调用StandardScaler。

copy_X:bool, optional, default True 如果为真,输入的X会被复制;否则,它可能被覆盖。

max_iterint, default=None 共轭梯度求解器的最大迭代次数。对于“sparse_cg”和“lsqr”求解器,默认值由sci .sparse.linalg确定。对于“sag”求解器,默认值是1000。

tolfloat, default=1e-3 设置解的精度,默认是1e-3

solver{‘auto’, ‘svd’, ‘cholesky’, ‘lsqr’, ‘sparse_cg’, ‘sag’, ‘saga’}, default=’auto’ 选择求解的方式

默认为auto’根据数据类型自动选择求解器

svd '使用X的奇异值分解来计算脊线系数。对于奇异矩阵比‘cholesky’更稳定。

cholesky用的是标准的scipy.linalg函数

“sparse_cg”使用了sci .sparse.linalg.cg中的共轭梯度求解器。作为一种迭代算法,该求解器比‘cholesky’更适用于大规模数据(可能设置为tol和max_iter)。

“lsqr”使用专用的正则化最小二乘例程sci .sparse.linalg.lsqr。它是最快的,并使用迭代过程。

sag使用的是随机平均梯度下降法,saga使用的是改进版的无偏算法saga。这两种方法都使用迭代过程,并且在n_samples和n_features都很大的情况下,通常比其他求解器更快。请注意,“sag”和“saga”的快速收敛只能保证在大致相同的尺度上。您可以使用来自sklearn.preprocessing的标量对数据进行预处理。

random_stateint, RandomState instance, default=None 当数据变换时使用的伪随机数生成器的种子。如果是int, random_state是随机数生成器使用的种子;如果RandomState实例,random_state是随机数生成器;如果没有,随机数生成器就是np.random使用的RandomState实例。当求解器为 ' sag '时使用。

属性

coef_ndarray of shape (n_features,) or (n_targets, n_features) 输出权重向量

intercept_float or ndarray of shape (n_targets,) 线性模型中的独立项(线性模型为一次时的截距)。如果fit_intercept = False,则将其设置为0.0。

n_iter_None or ndarray of shape (n_targets,)  每个目标的实际迭代次数。仅适用于sag和lsqr解决方案。其他解决程序将返回None。

示例代码:

>>> from sklearn.linear_model import Ridge
>>> import numpy as np
>>> n_samples, n_features = 10, 5
>>> rng = np.random.RandomState(0)
>>> y = rng.randn(n_samples)
>>> X = rng.randn(n_samples, n_features)
>>> clf = Ridge(alpha=1.0)
>>> clf.fit(X, y)
Ridge()

fit(self, X, y, sample_weight=None)  训练模型 :X {array-like, sparse matrix} of shape (n_samples, n_features) 训练数据集,

y:array-like of shape (n_samples,) or (n_samples, n_targets) 标签值。如果有必要,会转换成X的形状,

sample_weight:array-like of shape (n_samples,), default=None 默认为false,每个样本独立的权值

get_params(self[, deep])  获取此模型的参数 :deepbool, default=True 如果为真,将返回此估计器的参数以及包含的作为估计器的子对象返回值:paramsmapping of string to any 参数名映射到它们的值。

predict(self, X)  使用此线性模型来预测值 ,X:array_like or sparse matrix, shape (n_samples, n_features) 输入样本,返回值为预测的值。

score(self, X, y[, sample_weight]) 返回预测的决定系数R^2。

系数R^2定义为(1 - u/v),其中u为残差平方和((y_true - y_pred) ** 2).sum(), v为总平方和((y_true - y_true.mean() ** 2).sum()。最好的分数是1.0,也可能是负数(因为模型可能会任意变差)。如果一个常数模型总是预测y的期望值,而不考虑输入特性,则会得到R^2的0.0分。X:array-like of shape (n_samples, n_features) 测试样本,y:array-like of shape (n_samples,) or (n_samples, n_outputs) 样本X的真实值,sample_weight:array-like of shape (n_samples,), default=None  样本的权重返回值:返回值:score(float) R^2系数。

set_params(self, \*\*params)  设置此估计器的参数。该方法既适用于简单的估计器,也适用于嵌套对象(如管道)。后者具有__的参数,因此可以更新嵌套对象的每个组件。

**params(dict) 估计的参数,返回值,估计的实例。

下面我们使用它来写一段代码来看一看正则化强度与权重的变化关系:

import matplotlib.pyplot as plt
import numpy as np

from sklearn.datasets import make_regression
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error

clf = Ridge()

X, y, w = make_regression(n_samples=10, n_features=10, coef=True,
                          random_state=1, bias=3.5)

coefs = []
errors = []

alphas = np.logspace(-6, 6, 200)

# Train the model with different regularisation strengths
for a in alphas:
    clf.set_params(alpha=a)
    clf.fit(X, y)
    coefs.append(clf.coef_)
    errors.append(mean_squared_error(clf.coef_, w))

# Display results
plt.figure(figsize=(20, 6))

plt.subplot(121)
ax = plt.gca()
ax.plot(alphas, coefs)
ax.set_xscale('log')
plt.xlabel('alpha')
plt.ylabel('weights')
plt.title('Ridge coefficients as a function of the regularization')
plt.axis('tight')

plt.subplot(122)
ax = plt.gca()
ax.plot(alphas, errors)
ax.set_xscale('log')
plt.xlabel('alpha')
plt.ylabel('error')
plt.title('Coefficient error as a function of the regularization')
plt.axis('tight')

plt.show()

 输出结果为:

更多内容请扫描下方二维码关注小编公众号:程序员大管

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值