Skleran-线性模型-Ridge/岭回归

Ridge/岭回归

在这里插入图片描述

sklearn.linear_model.Ridge

class 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
	正则化强度;必须是正浮点数。正则化改善了问题的条件,降低了估计的方差。较大的值指定更强的正则化。
fit_intercept:bool, default=True
	是否计算此模型的截距。如果设置为false,计算中将不使用截距(数据预计已居中)。
normalize:bool, default=False
	当fit_intercept设置为False时,忽略此参数。如果为真,则回归前,通过减去平均值并除以l2范数,
	对回归数X进行归一化。
copy_X:bool, default=True
	如果为True,将复制X;否则,可能会覆盖它。
max_iter:int, default=None
	共轭梯度求解器的最大迭代次数。 默认值由scipy.sparse.linalg确定。
tol:float, default=1e-3
	解决方案的精度。
solver:{‘auto’, ‘svd’, ‘cholesky’, ‘lsqr’, ‘sparse_cg’, ‘sag’, ‘saga’}, default=’auto’
	要在计算例程中使用的解算器:
		“auto”根据数据类型自动选择解算器。
		“svd”使用X的奇异值分解来计算ridge系数。对于奇异矩阵比“cholesky”更稳定。
		“cholesky”使用标准的scipy.linalg.solve函数来获得封闭形式的解决方案。
		“sparse_cg”使用scipy.sparse.linalg.cg中的共轭梯度解算器。作为一种迭代算法,
		这个解算器比cholesky更适合于大规模数据
		“lsqr”使用专用的正则化最小二乘例程scipy.sparse.linalg.lsqr。它是最快的,并且使用迭代过程。
		“sag”使用随机平均梯度下降,“saga”使用其无偏且更灵活的版本saga。这两种方法都使用迭代过程,
		并且当n_样本和n_特征都较大时,通常比其他求解器更快。
		
random_state:int, RandomState instance, default=None
	伪随机数生成器的种子

属性:

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解算器。其他解算器将不返回任何值。

方法:

fit(self, X, y[, sample_weight])		拟合岭回归模型。
	参数:
		X:{ndarray, sparse matrix} of shape (n_samples, n_features)
		训练数据
		y:ndarray of shape (n_samples,) or (n_samples, n_targets)
		目标值
		sample_weight:float or ndarray of shape (n_samples,), default=None
		每个样本的单独权重。
	返回:
		Self:returns an instance of self.
get_params(self, deep=True)		获取此估计器的参数。
	参数:
		deep:bool, default=True
		如果为True,则返回此估计器的参数以及包含的子对象(即估计器)。
	返回:
		params:mapping of string to any
		映射到其值的参数名。
predict(self, X)		用线性模型预测
		参数:Xarray_like or sparse matrix, shape (n_samples, n_features)
		
		返回:Carray, shape (n_samples,)
score(self, X, y, sample_weight=None)
	返回预测的决定系数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
		样本权重。
	返回:
		scorefloat
		得分
set_params(self, **params)
	设置此估计器的参数。
	参数:
		**params:dict
		估计参数
	返回:
		Self:object
		估计实例

例子

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/6/17 21:28
# @Author  : LaoChen

"""
岭回归基本上是最小化最小二乘函数的惩罚版本。
惩罚shrinks回归系数的值。与标准线性回归相比,尽管每个维的数据点较少,
但预测的斜率要稳定得多,直线本身的方差也大大减小。
"""

import numpy as np
import matplotlib.pyplot as plt

from sklearn import linear_model

X_train = np.c_[.5, 1].T
y_train = [.5, 1]
X_test = np.c_[0, 2].T

np.random.seed(0)

classifiers = dict(ols=linear_model.LinearRegression(),
                   ridge=linear_model.Ridge(alpha=.1))

for name, clf in classifiers.items():
    fig, ax = plt.subplots(figsize=(4, 3))

    for _ in range(6):
        this_X = .1 * np.random.normal(size=(2, 1)) + X_train
        clf.fit(this_X, y_train)

        ax.plot(X_test, clf.predict(X_test), color='gray')
        ax.scatter(this_X, y_train, s=3, c='gray', marker='o', zorder=10)

    clf.fit(X_train, y_train)
    ax.plot(X_test, clf.predict(X_test), linewidth=2, color='blue')
    ax.scatter(X_train, y_train, s=30, c='red', marker='+', zorder=10)

    ax.set_title(name)
    ax.set_xlim(0, 2)
    ax.set_ylim((0, 1.6))
    ax.set_xlabel('X')
    ax.set_ylabel('y')

    fig.tight_layout()

plt.show()

sklearn.linear_model.RidgeClassifier

使用岭回归的分类器,这个分类器首先将目标值转换成{-1,1},然后将问题作为一个回归任务(在多类情况下为多输出回归)。

class sklearn.linear_model.RidgeClassifier(alpha=1.0, fit_intercept=True, normalize=False, 
copy_X=True, max_iter=None, tol=0.001, class_weight=None, solver='auto', random_state=None)
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import RidgeClassifier
X, y = load_breast_cancer(return_X_y=True)
clf = RidgeClassifier().fit(X, y)
clf.score(X, y)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值