我rfe对caret库中的功能有疑问.在插入符号主页链接上,他们提供以下RFE算法:
算法
对于这个例子,我使用rfe具有3倍交叉验证的功能和具有线性SVM和5倍交叉验证的列车功能.
library(kernlab)
library(caret)
data(iris)
# parameters for the tune function, used for fitting the svm
trControl <- trainControl(method = "cv", number = 5)
# parameters for the RFE function
rfeControl <- rfeControl(functions = caretFuncs, method = "cv",
number= 4, verbose = FALSE )
rf1 <- rfe(as.matrix(iris[,1:4]), as.factor(iris[,5]) ,sizes = c( 2,3) ,
rfeControl = rfeControl, trControl = trControl, method = "svmLinear")
Run Code Online (Sandbox Code Playgroud)
rfe 将数据(150个样本)分成3倍train功能将在训练集(100个样本)上运行,具有5倍交叉验证以调整模型参数 - …我一直在尝试使用插入包来应用递归功能选择.我需要的是ref使用AUC作为性能测量.谷歌搜索了一个月后,我无法使该过程正常工作.这是我用过的代码:
library(caret)
library(doMC)
registerDoMC(cores = 4)
data(mdrr)
subsets <- c(1:10)
ctrl <- rfeControl(functions=caretFuncs,
method = "cv",
repeats =5, number = 10,
returnResamp="final", verbose = TRUE)
trainctrl <- trainControl(classProbs= TRUE)
caretFuncs$summary <- twoClassSummary
set.seed(326)
rf.profileROC.Radial <- rfe(mdrrDescr, mdrrClass, sizes=subsets,
rfeControl=ctrl,
method="svmRadial",
metric="ROC",
trControl=trainctrl)
Run Code Online (Sandbox Code Playgroud)
执行此脚本时,我得到以下结果:
Recursive feature selection
Outer resampling method: Cross-Validation (10 fold)
Resampling performance over subset size:
Variables Accuracy Kappa AccuracySD KappaSD Selected
1 0.7501 0.4796 0.04324 0.09491
2 0.7671 0.5168 0.05274 0.11037
3 0.7671 0.5167 0.04294 0.09043
4 0.7728 …Run Code Online (Sandbox Code Playgroud) 我试图从 sklearn 中相当大的一组特征(~6,100,000)中获取特征的排名。这是我迄今为止的代码:
train, test = train_test_split(rows, test_size=0.2, random_state=310)
train, val = train_test_split(train, test_size=0.25, random_state=310)
train_target = [i[-1] for i in train]
svc = SVC(verbose=5, random_state=310, kernel='linear')
svc.fit([i[1:-1] for i in train], train_target)
model=svc
rfe = RFE(model, verbose=5, step=1, n_features_to_select=1)
rfe.fit([i[1:-1] for i in train], train_target)
rank = rfe.ranking_
Run Code Online (Sandbox Code Playgroud)
模型的每次训练大约需要 10 分钟。对于 6,100,000 个特征,这意味着数十年的计算时间。实际上115.9岁。有更好的方法来做到这一点吗?我知道 rfe 需要最后一次淘汰的结果,但是有什么方法可以通过并行化或以不同的方式获得排名来加快速度吗?我可以使用数千个节点(感谢我工作的公司!),所以任何类型的并行性都很棒!
我确实有线性 SVM 超平面的列表系数。排序这些很容易,但是正在这样做的论文将由斯坦福大学数据科学教授审阅,他对使用非排名算法进行排名持强烈保留态度......以及非斯坦福大学校友,例如我。:P
我可以采用更大的值step,但这会消除对所有功能进行实际排名的能力。相反,我会对 100,000 或 10,000 个功能的组进行排名,但这并不是很有帮助。
编辑:nSV 可能有用,所以我将其包含在下面:
obj = -163.983323, rho = -0.999801
nSV = 182, nBSV …Run Code Online (Sandbox Code Playgroud) 我正在使用sklearn使用RFECV模块通过交叉验证执行递归功能消除.RFE涉及在全套特征上重复训练估计器,然后移除信息量最少的特征,直到收敛到最佳数量的特征.
为了通过估算器获得最佳性能,我想为每个特征数量选择最佳超参数(为清晰起见而编辑).估计器是一个线性SVM,所以我只关注C参数.
最初,我的代码如下.但是,这只是在开始时对C进行了一次网格搜索,然后在每次迭代时使用相同的C.
from sklearn.cross_validation import StratifiedKFold
from sklearn.feature_selection import RFECV
from sklearn import svm, grid_search
def get_best_feats(data,labels,c_values):
parameters = {'C':c_values}
# svm1 passed to clf which is used to grid search the best parameters
svm1 = SVC(kernel='linear')
clf = grid_search.GridSearchCV(svm1, parameters, refit=True)
clf.fit(data,labels)
#print 'best gamma',clf.best_params_['gamma']
# svm2 uses the optimal hyperparameters from svm1
svm2 = svm.SVC(C=clf.best_params_['C'], kernel='linear')
#svm2 is then passed to RFECVv as the estimator for recursive feature elimination
rfecv = RFECV(estimator=svm2, step=1, cv=StratifiedKFold(labels, 5)) …Run Code Online (Sandbox Code Playgroud) 受此启发:http : //scikit-learn.org/stable/auto_examples/feature_selection/plot_rfe_with_cross_validation.html#sphx-glr-auto-examples-feature-selection-plot-rfe-with-cross-validation-py
我想知道是否有办法获得特定分数的功能:
在这种情况下,我想知道,当#Features = 10 时,选择的哪 10 个特征给出了那个峰值。
有任何想法吗?
编辑:
这是用于获取该图的代码:
from sklearn.feature_selection import RFECV
from sklearn.model_selection import KFold,StratifiedKFold #for K-fold cross validation
from sklearn.ensemble import RandomForestClassifier #Random Forest
# The "accuracy" scoring is proportional to the number of correct classifications
#kfold = StratifiedKFold(n_splits=10, random_state=1) # k=10, split the data into 10 equal parts
model_Linear_SVM=svm.SVC(kernel='linear', probability=True)
rfecv = RFECV(estimator=model_Linear_SVM, step=1, cv=kfold,scoring='accuracy') #5-fold cross-validation
rfecv = rfecv.fit(X, y)
print('Optimal number of features :', rfecv.n_features_)
print('Best features :', X.columns[rfecv.support_]) …Run Code Online (Sandbox Code Playgroud) I am using RFECV for feature selection in scikit-learn. I would like to compare the result of a simple linear model (X,y) with that of a log transformed model (using X, log(y))
Simple Model:
RFECV and cross_val_score provide the same result (we need to compare the average score of cross-validation across all folds with the score of RFECV for all features: 0.66 = 0.66, no problem, results are reliable)
Log Model: the Problem: …
我想使用AUC作为性能指标,但RFE仅支持RMSE,RSquared,Accuracy,Kappa.如何使用auc等自定义指标?
我正在尝试在scikit-learn中使用递归功能消除(RFE)功能,但不断收到错误ValueError: coef_ is only available when using a linear kernel.我正在尝试使用rbf内核为支持向量分类器(SVC)执行功能选择.来自网站的这个例子执行得很好:
print(__doc__)
from sklearn.svm import SVC
from sklearn.cross_validation import StratifiedKFold
from sklearn.feature_selection import RFECV
from sklearn.datasets import make_classification
from sklearn.metrics import zero_one_loss
# Build a classification task using 3 informative features
X, y = make_classification(n_samples=1000, n_features=25, n_informative=3,
n_redundant=2, n_repeated=0, n_classes=8,
n_clusters_per_class=1, random_state=0)
# Create the RFE object and compute a cross-validated score.
svc = SVC(kernel="linear")
rfecv = RFECV(estimator=svc, step=1, cv=StratifiedKFold(y, 2),
scoring='accuracy')
rfecv.fit(X, y)
print("Optimal number of features : …Run Code Online (Sandbox Code Playgroud) 我正在使用递归特征估计(RFE)进行特征选择。其工作原理是迭代地采用估计器(例如 SVM 分类器),将其拟合到数据,并删除权重(系数)最低的特征。
我能够将其拟合到数据并执行特征选择。然而,我随后想从 RFE 中恢复每个特征的学习权重。
我使用以下代码来初始化分类器对象和 RFE 对象,并将它们拟合到数据中。
svc = SVC(C=1, kernel="linear")
rfe = RFE(estimator=svc, n_features_to_select=300, step=0.1)
rfe.fit(all_training, training_labels)
Run Code Online (Sandbox Code Playgroud)
然后我尝试打印系数
print ('coefficients',svc.coef_)
Run Code Online (Sandbox Code Playgroud)
并收到:
AttributeError: 'RFE' object has no attribute 'dual_coef_'
Run Code Online (Sandbox Code Playgroud)
根据sklearn 文档,分类器对象应该具有此属性:
coef_ : array, shape = [n_class-1, n_features]
Weights assigned to the features (coefficients in the primal problem). This is only
available in the case of a linear kernel.
coef_ is a readonly property derived from dual_coef_ and support_vectors_.
Run Code Online (Sandbox Code Playgroud)
我使用的是线性内核,所以这不是问题。
谁能解释为什么我无法恢复系数?有办法解决这个问题吗?
我正在使用 RFE 技术和 statsmodels 库在汽车数据集上构建线性回归模型。我的最终模型的 p 值远在 5% 以内,并且 F 统计量很高。预测变量的 VIF 值远低于 5,但常数项(截距)的 VIF 为 8.18。我使用add_constant方法将常量添加到模型中。以下是我的疑惑:
这些是我的结果:


我是机器学习新手,也是第一次在此网站上发布问题。如果需要更多信息来回答我的问题,请告诉我。
我正在使用bayesglm逻辑回归问题.它是150行和2000个变量的数据集.我试图做变量选择,通常看glmnet在caret::rfe.然而,没有一种方法bayesglm.
反正有手动定义方法rfe吗?
我有一个由分类数据和数值数据组成的数据集,具有 124 个特征。为了降低其维度,我想删除不相关的特征。然而,为了针对特征选择算法运行数据集,我使用 get_dummies 对其进行了热编码,这将特征数量增加到 391 个。
In[16]:
X_train.columns
Out[16]:
Index([u'port_7', u'port_9', u'port_13', u'port_17', u'port_19', u'port_21',
...
u'os_cpes.1_2', u'os_cpes.1_1'], dtype='object', length=391)
Run Code Online (Sandbox Code Playgroud)
根据生成的数据,我可以通过交叉验证运行递归特征消除,如Scikit Learn 示例所示:
其产生:
鉴于识别的特征的最佳数量是 8,我如何识别特征名称?我假设我可以将它们提取到一个新的 DataFrame 中以用于分类算法?
[编辑]
在这篇文章的帮助下,我实现了以下目标:
def column_index(df, query_cols):
cols = df.columns.values
sidx = np.argsort(cols)
return sidx[np.searchsorted(cols, query_cols, sorter = sidx)]
feature_index = []
features = []
column_index(X_dev_train, X_dev_train.columns.values)
for num, i in enumerate(rfecv.get_support(), start=0):
if i == True:
feature_index.append(str(num))
for num, i in enumerate(X_dev_train.columns.values, start=0):
if str(num) in feature_index:
features.append(X_dev_train.columns.values[num]) …Run Code Online (Sandbox Code Playgroud) machine-learning feature-selection python-2.7 scikit-learn rfe
使用 RFE,您可以获得特征的重要性等级,但现在我只能使用包内的模型和参数,例如:lmFuncs(linear model),rfFuncs(random forest)
似乎
caretFuncs
Run Code Online (Sandbox Code Playgroud)
可以对自己的模型和参数做一些自定义设置,但是我不知道细节,正式文档没有给出细节,我想在这个RFE过程中应用svm和gbm,因为这是我当前使用的模型训练,有人知道吗?
rfe ×13
scikit-learn ×7
python ×6
r ×5
r-caret ×5
svm ×3
auc ×1
bayesglm ×1
constants ×1
python-2.7 ×1