关键词:
【中文标题】通过应用 RFE 选择给出最佳调整 R 平方值的特征子集【英文标题】:Selecting Subset of Features that Gives Best Adjusted R-squared Value by Applying RFE 【发布时间】:2019-08-11 12:43:59 【问题描述】:我有两个目标。我想:
-
遍历特征值 1-10,然后
比较调整后的 R 平方 值。
我知道如何仅针对以下代码中显示的 1 个固定功能执行此操作。我试图循环输入selector = RFE(regr, n_features_to_select, step=1)
,但我认为我错过了这个难题的关键部分。谢谢!
from sklearn.feature_selection import RFE
regr = LinearRegression()
#parameters: estimator, n_features_to_select=None, step=1
selector = RFE(regr, 5, step=1)
selector.fit(x_train, y_train)
selector.support_
def show_best_model(support_array, columns, model):
y_pred = model.predict(X_test.iloc[:, support_array])
r2 = r2_score(y_test, y_pred)
n = len(y_pred) #size of test set
p = len(model.coef_) #number of features
adjusted_r2 = 1-(1-r2)*(n-1)/(n-p-1)
print('Adjusted R-squared: %.2f' % adjusted_r2)
j = 0;
for i in range(len(support_array)):
if support_array[i] == True:
print(columns[i], model.coef_[j])
j +=1
show_best_model(selector.support_, x_train.columns, selector.estimator_)
【问题讨论】:
我建议您将其中一个标签更改为scikit-learn
,因为您会让更多具有该专业知识的人看到您的问题。
【参考方案1】:
您可以创建自定义GridSearchCV
,它对估算器的指定参数值执行详尽搜索。
您还可以选择任何可用的评分函数,例如 Scikit-learn 中的R2 Score。但是,您可以使用给定 here 的简单公式从 R2 得分计算 Adjusted R2,然后在自定义 GridSearchCV
中实现它.
from collections import OrderedDict
from itertools import product
from sklearn.feature_selection import RFE
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_iris
from sklearn.metrics import r2_score
from sklearn.model_selection import StratifiedKFold
def customR2Score(y_true, y_pred, n, p):
"""
Workaround for the adjusted R^2 score
:param y_true: Ground Truth during iterations
:param y_pred: Y predicted during iterations
:param n: the sample size
:param p: the total number of explanatory variables in the model
:return: float, adjusted R^2 score
"""
r2 = r2_score(y_true, y_pred)
return 1 - (1 - r2) * (n - 1) / (n - p - 1)
def CustomGridSearchCV(X, Y, param_grid, n_splits=10, n_repeats=3):
"""
Perform GridSearchCV using adjusted R^2 as Scoring.
Note here we are performing GridSearchCV MANUALLY because adjusted R^2
cannot be used directly in the GridSearchCV function builtin in Scikit-learn
:param X: array_like, shape (n_samples, n_features), Samples.
:param Y: array_like, shape (n_samples, ), Target values.
:param param_grid: Dictionary with parameters names (string) as keys and lists
of parameter settings to try as values, or a list of such
dictionaries, in which case the grids spanned by each dictionary
in the list are explored. This enables searching over any
sequence of parameter settings.
:param n_splits: Number of folds. Must be at least 2. default=10
:param n_repeats: Number of times cross-validator needs to be repeated. default=3
:return: an Ordered Dictionary of the model object and information and best parameters
"""
best_model = OrderedDict()
best_model['best_params'] =
best_model['best_train_AdjR2'], best_model['best_cross_AdjR2'] = 0, 0
best_model['best_model'] = None
allParams = OrderedDict()
for key, value in param_grid.items():
allParams[key] = value
for items in product(*allParams.values()):
params =
i = 0
for k in allParams.keys():
params[k] = items[i]
i += 1
# at this point, we get different combination of parameters
model_ = RFE(**params)
avg_AdjR2_train = 0.
avg_AdjR2_cross = 0.
for rep in range(n_repeats):
skf = StratifiedKFold(n_splits=n_splits, shuffle=True)
AdjR2_train = 0.
AdjR2_cross = 0.
for train_index, cross_index in skf.split(X, Y):
x_train, x_cross = X[train_index], X[cross_index]
y_train, y_cross = Y[train_index], Y[cross_index]
model_.fit(x_train, y_train)
# find Adjusted R2 of train and cross
y_pred_train = model_.predict(x_train)
y_pred_cross = model_.predict(x_cross)
AdjR2_train += customR2Score(y_train, y_pred_train, len(y_train), model_.n_features_)
AdjR2_cross += customR2Score(y_cross, y_pred_cross, len(y_cross), model_.n_features_)
AdjR2_train /= n_splits
AdjR2_cross /= n_splits
avg_AdjR2_train += AdjR2_train
avg_AdjR2_cross += AdjR2_cross
avg_AdjR2_train /= n_repeats
avg_AdjR2_cross /= n_repeats
# store the results of the first set of parameters combination
if abs(avg_AdjR2_cross) >= abs(best_model['best_cross_AdjR2']):
best_model['best_params'] = params
best_model['best_train_AdjR2'] = avg_AdjR2_train
best_model['best_cross_AdjR2'] = avg_AdjR2_cross
best_model['best_model'] = model_
return best_model
# Dataset for testing
iris = load_iris()
X = iris.data
Y = iris.target
regr = LinearRegression()
param_grid = 'estimator': [regr], # you can try different estimator
'n_features_to_select': range(1, X.shape[1] + 1)
best_model = CustomGridSearchCV(X, Y, param_grid, n_splits=5, n_repeats=2)
print(best_model)
print(best_model['best_model'].ranking_)
print(best_model['best_model'].support_)
测试结果
OrderedDict([
('best_params', 'n_features_to_select': 3, 'estimator':
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)),
('best_train_AdjR2', 0.9286382985850505), ('best_cross_AdjR2', 0.9188172567358479),
('best_model', RFE(estimator=LinearRegression(copy_X=True, fit_intercept=True,
n_jobs=1, normalize=False), n_features_to_select=3, step=1, verbose=0))])
[1 2 1 1]
[ True False True True]
【讨论】:
@ron 如果这个答案对你有帮助,请接受它:)【参考方案2】:感谢叶海亚的回复。我还没有机会测试它。我对 python 还很陌生,所以我会尝试从你的回复中学习。
话虽如此,我找到了解决问题的方法。这是为未来的学习者准备的。
def show_best_model(support_array, columns, model):
y_pred = model.predict(X_test.iloc[:, support_array])
r2 = r2_score(y_test, y_pred)
n = len(y_pred) #size of test set
p = len(model.coef_) #number of features
adjusted_r2 = 1-(1-r2)*(n-1)/(n-p-1)
print('Adjusted R-squared: %.2f' % adjusted_r2)
j = 0;
for i in range(len(support_array)):
if support_array[i] == True:
print(columns[i], model.coef_[j])
j +=1
from sklearn.feature_selection import RFE
regr = LinearRegression()
for m in range(1,11):
selector = RFE(regr, m, step=1)
selector.fit(x_train, y_train)
if m<11:
show_best_model(selector.support_, x_train.columns, selector.estimator_)
X = df.loc[:,['Age_08_04', 'KM', 'HP', 'Weight', 'Automatic_airco']]
x_train, X_test, y_train, y_test = train_test_split(X, y,
test_size =.4,
random_state = 20)
regr = LinearRegression()
regr.fit(x_train, y_train)
y_pred = regr.predict(X_test)
print('Average error: %.2f' %mean(y_test - y_pred))
print('Mean absolute error: %.2f' %mean_absolute_error(y_test, y_pred))
print('Mean absolute error: %.2f' %(mean(abs(y_test - y_pred))))
print("Root mean squared error: %.2f"
% math.sqrt(mean_squared_error(y_test, y_pred)))
print('percentage absolute error: %.2f' %mean(abs((y_test - y_pred)/y_test)))
print('percentage absolute error: %.2f' %(mean(abs(y_test - y_pred))/mean(y_test)))
print('R-squared: %.2f' % r2_score(y_test, y_pred))
x_train = x_train.loc[:,
['Age_08_04', 'KM' , 'HP',
'Weight', 'Automatic_airco']]
X_test = X_test.loc[:,
['Age_08_04', 'KM' , 'HP',
'Weight', 'Automatic_airco']]
selector = RFE(regr, 5, step=1)
selector.fit(x_train, y_train)
show_best_model(selector.support_, x_train.columns, selector.estimator_)
【讨论】:
唯一缺少的是它不会为您比较值。您必须比较 r 平方的值,然后使用该数量的特征。 亲爱的@ron,我的方法是一种标准方法,它确实比较值并选择最好的,正如你所说,一旦你熟悉了 Python,你就会明白我的直截了当的解决方案:) 顺便说一句,如果你的意思是比较你想查看元数据,print()
是你的朋友:)R 在 RFE(递归特征消除)中使用我自己的模型来选择重要特征
】R在RFE(递归特征消除)中使用我自己的模型来选择重要特征【英文标题】:RusingmyownmodelinRFE(recursivefeatureelimination)topickimportantfeature【发布时间】:2018-11-1410:28:48【问题描述】:使用RFE,你可以得到特征的重要性等级,但现在... 查看详情
统计学里r^2表示啥意思?有啥用呢?
统计学里R^2表示:决定系数,反应因变量的全部变异能通过回归关系被自变量解释的比例。如R平方为0.8,则表示回归关系可以解释因变量80%的变异。换句话说,如果我们能控制自变量不变,则因变量的变异程度会减少80%。统计... 查看详情
插入符号 rfe + 和 ROC 中的特征选择
...:2014-02-0101:16:55【问题描述】:我一直在尝试使用caret包应用递归特征选择。我需要的是ref使用AUC作为性能指标。谷歌搜索一个月后,我无法让该过程正常工作。这是我使用的代码:library(caret)library(doMC)registerDoMC(cores=4)data 查看详情
r语言层次聚类:通过内平方和wss选择最优的聚类k值可视化不同k下的bss和wss通过calinski-harabasz指数(准则)与聚类簇个数的关系获取最优聚类簇的个数
R语言层次聚类:通过内平方和(WithinSumofSquares,WSS)选择最佳的聚类K值、以内平方和(WSS)和K的关系并通过弯头法ÿ 查看详情
单变量最小二乘回归中的多重 R 平方和调整 R 平方有啥区别?
】单变量最小二乘回归中的多重R平方和调整R平方有啥区别?【英文标题】:WhatisthedifferencebetweenMultipleR-squaredandAdjustedR-squaredinasingle-variateleastsquaresregression?单变量最小二乘回归中的多重R平方和调整R平方有什么区别?【发布时间... 查看详情
保存在 UIPicker 中选择的值的最佳方法?
...:47:21【问题描述】:我的视图中有3个UIPicker,我想在我的应用关闭时保存选定的值。我目前将NSUserDefaults用于其他所有内容。但我不确定保存UIPickers选定值的语法。谢谢我的程序员!【问题讨论】:【参考方案1】:这是你如何从... 查看详情
R中SVM-RFE算法的实现
】R中SVM-RFE算法的实现【英文标题】:ImplementationofSVM-RFEAlgorithminR【发布时间】:2016-12-1722:23:49【问题描述】:我正在使用R代码来实现来自此源http://www.uccor.edu.ar/paginas/seminarios/Software/SVM_RFE_R_implementation.pdf的SVM-RFE算法,但我做了... 查看详情
优化最佳特征的数量
...用Keras训练神经网络。每次训练我的模型时,我都会使用通过ExtraTreesClassifier()选择的Tree-basedfeatureselection选择的一组略有不同的特征。每次训练后,我在验证集上计算AUCROC,然后返回循环以使用不同的特征集再次训练 查看详情
R中的支持向量机特征选择示例
...2013-07-0522:57:27【问题描述】:我正在尝试使用R包在SVM中应用特征选择(例如递归特征选择)。我已经安装了支持LibSVM中的特征选择的Weka,但我还没有找到任何关于SVM或类似语法的示例。一个简短的例子会很有帮助。【问题讨论... 查看详情
使用 d3.js/chart.js/highcharts 在实际和预测散点图中的 R 平方最佳拟合线
】使用d3.js/chart.js/highcharts在实际和预测散点图中的R平方最佳拟合线【英文标题】:Rsquarebestfitlineinactualandprecitedscatterplotwithd3.js/chart.js/highcharts【发布时间】:2021-08-1603:14:19【问题描述】:我想在实际值和预测值的散点图中绘制rS... 查看详情
从几列中选择最小值的最佳方法是啥?
】从几列中选择最小值的最佳方法是啥?【英文标题】:What\'sthebestwaytoselecttheminimumvaluefromseveralcolumns?从几列中选择最小值的最佳方法是什么?【发布时间】:2010-09-2623:16:38【问题描述】:鉴于SQLServer2005中的下表:IDCol1Col2Col3----... 查看详情
r语言基于递归特征消除rfe(recursivefeatureelimination)进行特征筛选(featureselection)
R语言基于递归特征消除RFE(RecursiveFeatureElimination)进行特征筛选(featureselection)对一个学习任务来说,给定属性集,有些属性很有用,另一些则可能没什么用。这里的属性即称为“特征”(feature)。对当前学习任务有用的属性称... 查看详情
《数值分析》--thegreat平方逼近
...最佳平方逼近习题一、最佳平方逼近及计算定义span中会给出φi(x)\\varphi_i(x)φi(x)对应的具体函数,稍后看习题就会明白。讨论S∗(x)S^*(x)S∗(x)的计算由于I(a0,a1,..,an)I(a_0,a_1,..,a_n)I(a0,a1,..,an)是关于a0,a1,..,ana_0,a_1,..,a_na0... 查看详情
不同时间的不同 R 平方分数
...0-11-0223:57:56【问题描述】:我刚刚了解了交叉验证,当我给出不同的论点时,会有不同的结果。这是构建回归模型的代码,R平方输出约为0.5:fromsklearn.datasetsimportload_bostonfromsklearn.model_selectionimporttrai 查看详情
拟合系数/决定系数/r方/r^2的理解
先附上公式,来自wiki,然后给出个人理解:上面公式中,红圈表示的是拟合系数计算公式,SSresSS_resSSres表示真实值与预测值的差的平方之和,也就是预测值与真实值的误差。SStotSS_totSStot表示平方差... 查看详情
我通过平方实现指数有啥问题吗?
】我通过平方实现指数有啥问题吗?【英文标题】:Isthereanythingwrongwithmyimplementationofexponentialbysquaring?我通过平方实现指数有什么问题吗?【发布时间】:2014-07-3007:48:43【问题描述】:我通过在java中求平方来实现指数。并从网上... 查看详情
excel自动获得幂函数r平方
参考技术Aexcel中选择单元格插入公式,再选择数学和三角函数找到power,输入根和幂,就能自动获得幂函数R平方了。幂函数(powerfunction)是基本初等函数之一,excel中幂函数存在于数学公式中,叫做power。 查看详情
Java 会话管理的最佳选择
...在浏览器中,以后可以访问?它是否正确?如果可能,请通过编码示例给出答案。哪个是最好的:URL重写:服务器会在URL链接的末尾添加一个额外的参数表单中的隐藏参数:服务器将在HTML中的每个 查看详情