Skleran-线性模型-ElasticNetCV

ElasticNetCV

在这里插入图片描述

sklearn.linear_model.ElasticNet

class sklearn.linear_model.ElasticNet(alpha=1.0, *, l1_ratio=0.5, fit_intercept=True, 
normalize=False, precompute=False, max_iter=1000, copy_X=True, tol=0.0001, warm_start=False, 
positive=False, random_state=None, selection='cyclic')

参数:

alpha:float, default=1.0
	乘以惩罚条件的常数。默认为1.0。alpha=0相当于一个普通的最小二乘,由LinearRegression对象求解。
	出于数值原因,不建议使用alpha=0。
l1_ratio:float, default=0.5
	ElasticNet混合参数, 对于l1_ratio =0,惩罚是L2惩罚。对于l1_ratio =1,这是l1惩罚。
	对于0< l1_ratio <1,惩罚是l1和L2的组合。
fit_intercept:bool, default=True
	是否应该估计截距。如果为False,则假定数据已居中。
normalize:bool, default=False
	当fit_intercept设置为False时,忽略此参数。如果为真,则回归前,通过减去平均值并除以l2范数,
	对回归数X进行归一化。
precompute:bool or array-like of shape (n_features, n_features), default=False
	是否使用预计算的程序矩阵加快计算速度。
max_iter:int, default=1000
	最大迭代次数
copy_X:bool, default=True
	如果为True,将复制X;否则,可能会覆盖它。
tol:float, default=1e-4
	优化公差:如果更新小于tol,则优化代码检查双间隙的最优性,并继续,直到它小于tol。
warm_start:bool, default=False
	当设置为True时,重用上一个调用的解决方案以适应初始化,否则,只需删除上一个解决方案。
positive:bool, default=False
	当设置为True时,强制系数为正。
random_state:int, RandomState instance, default=None
	选择要更新的随机特征的伪随机数生成器的种子。
selection:{‘cyclic’, ‘random’}, default=’cyclic’
	如果设置为“随机”,则每次迭代都会更新一个随机系数,而不是默认情况下按顺序在特征上循环

属性:

coef_:ndarray of shape (n_features,) or (n_targets, n_features)
	参数向量(成本函数公式中的w)
sparse_coef_:sparse matrix of shape (n_features, 1) or (n_targets, n_features)
	拟合系数的稀疏表示_
intercept_:float or ndarray of shape (n_targets,)
	决策函数中的独立项。
n_iter_:list of int
	为达到指定公差而运行的迭代次数。

另见
ElasticNetCV
弹性网络模型经交叉验证,具有最佳的模型选择.
SGDRegressor
通过增量训练实现弹性网络回归。
SGDClassifier
用弹性净罚实现Logistic回归(SGDClassifier(loss=“log”, penalty=“elasticnet”)).
方法:

__init__(self, alpha=1.0, *, l1_ratio=0.5, fit_intercept=True, normalize=False,
 precompute=False, max_iter=1000, copy_X=True, tol=0.0001, warm_start=False, 
 positive=False, random_state=None, selection='cyclic')
初始化
fit(self, X, y, sample_weight=None, check_input=True)
参数
X:{ndarray, sparse matrix} of (n_samples, n_features)
数据
y:{ndarray, sparse matrix} of shape (n_samples,) or (n_samples, n_targets)
标签
sample_weight:float or array-like of shape (n_samples,), default=None
样本权重
check_input:bool, default=True
允许绕过多个输入检查。
get_params(self, deep=True)
获取参数。
参数:
deepbool, default=True
如果为True,则返回此估计器的参数以及包含的子对象(即估计器)。
	返回:
		params:mapping of string to any
		映射到其值的参数名。
alphas:ndarray, default=None

precompute:‘auto’, bool or array-like of shape (n_features, n_features), default=’auto’

Xy:array-like of shape (n_features,) or (n_features, n_outputs), default=None

copy_X:bool, default=True

coef_init:ndarray of shape (n_features, ), default=None
系数的初始值。
verbose:bool or int, default=False

return_n_iter:bool, default=False
是否返回迭代次数
positive:bool, default=False

check_input:bool, default=True

**params:kwargs

返回:
alphas:ndarray of shape (n_alphas,)

coefs:ndarray of shape (n_features, n_alphas) or (n_outputs, n_features, n_alphas)

dual_gaps:ndarray of shape (n_alphas,)

n_iters:list of int
predict(self, X)
参数:
X:array_like or sparse matrix, shape (n_samples, n_features)
返回:
C:array, 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
		估计实例

实例

import numpy as np
from sklearn import linear_model

# #############################################################################
# Generate sample data
n_samples_train, n_samples_test, n_features = 75, 150, 500
np.random.seed(0)
coef = np.random.randn(n_features)
coef[50:] = 0.0  # only the top 10 features are impacting the model
X = np.random.randn(n_samples_train + n_samples_test, n_features)
y = np.dot(X, coef)

# Split train and test data
X_train, X_test = X[:n_samples_train], X[n_samples_train:]
y_train, y_test = y[:n_samples_train], y[n_samples_train:]

# #############################################################################
# Compute train and test errors
alphas = np.logspace(-5, 1, 60)
enet = linear_model.ElasticNet(l1_ratio=0.7, max_iter=10000)
train_errors = list()
test_errors = list()
for alpha in alphas:
    enet.set_params(alpha=alpha)
    enet.fit(X_train, y_train)
    train_errors.append(enet.score(X_train, y_train))
    test_errors.append(enet.score(X_test, y_test))

i_alpha_optim = np.argmax(test_errors)
alpha_optim = alphas[i_alpha_optim]
print("Optimal regularization parameter : %s" % alpha_optim)

# Estimate the coef_ on full data with optimal regularization parameter
enet.set_params(alpha=alpha_optim)
coef_ = enet.fit(X, y).coef_

# #############################################################################
# Plot results functions

import matplotlib.pyplot as plt
plt.subplot(2, 1, 1)
plt.semilogx(alphas, train_errors, label='Train')
plt.semilogx(alphas, test_errors, label='Test')
plt.vlines(alpha_optim, plt.ylim()[0], np.max(test_errors), color='k',
           linewidth=3, label='Optimum on test')
plt.legend(loc='lower left')
plt.ylim([0, 1.2])
plt.xlabel('Regularization parameter')
plt.ylabel('Performance')

# Show estimated coef_ vs true coef
plt.subplot(2, 1, 2)
plt.plot(coef, label='True coef')
plt.plot(coef_, label='Estimated coef')
plt.legend()
plt.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.26)
plt.show()

sklearn.linear_model.MultiTaskElasticNet

在这里插入图片描述

class sklearn.linear_model.MultiTaskElasticNet(alpha=1.0, *, l1_ratio=0.5, fit_intercept=True, 
normalize=False, copy_X=True, max_iter=1000, tol=0.0001, warm_start=False, 
random_state=None, selection='cyclic')

>>> from sklearn import linear_model
>>> clf = linear_model.MultiTaskElasticNet(alpha=0.1)
>>> clf.fit([[0,0], [1, 1], [2, 2]], [[0, 0], [1, 1], [2, 2]])
MultiTaskElasticNet(alpha=0.1)
>>> print(clf.coef_)
[[0.45663524 0.45612256]
 [0.45663524 0.45612256]]
>>> print(clf.intercept_)
[0.0872422 0.0872422]
  • 0
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值