我正在尝试使用R包在SVM中应用特征选择(例如递归特征选择).我已经安装了Weka,它支持LibSVM中的功能选择,但我没有找到任何SVM语法或类似的例子.一个简短的例子将是一个很大的帮助.
我在sklearn中使用了RandomForestClassifier来确定数据集中的重要功能.我如何能够返回实际的特征名称(我的变量标记为x1,x2,x3等)而不是它们的相对名称(它告诉我重要的特征是'12','22'等).下面是我目前用于返回重要功能的代码.
important_features = []
for x,i in enumerate(rf.feature_importances_):
if i>np.average(rf.feature_importances_):
important_features.append(str(x))
print important_features
Run Code Online (Sandbox Code Playgroud)
另外,为了理解索引,我能够找出实际上重要的特征"12"(它是变量x14).当我将变量x14移动到训练数据集的0索引位置并再次运行代码时,它应该告诉我特征'0'很重要,但它没有,它就像它看不到那个特征已经列出的第一个功能实际上是我第一次运行代码时列出的第二个功能(功能'22').
我想也许feature_importances_实际上是使用第一列(我放置了x14)作为训练数据集其余部分的一种ID,因此在选择重要特征时忽略它.谁能解释这两个问题呢?提前感谢您的任何帮助.
编辑
以下是我存储功能名称的方法:
tgmc_reader = csv.reader(csvfile)
row = tgmc_reader.next() #Header contains feature names
feature_names = np.array(row)
Run Code Online (Sandbox Code Playgroud)
然后我加载了数据集和目标类
tgmc_x, tgmc_y = [], []
for row in tgmc_reader:
tgmc_x.append(row[3:]) #This says predictors start at the 4th column, columns 2 and 3 are just considered ID variables.
tgmc_y.append(row[0]) #Target column is the first in the dataset
Run Code Online (Sandbox Code Playgroud)
然后继续将数据集拆分为测试和训练部分.
from sklearn.cross_validation import train_test_split
x_train, x_test, y_train, y_test = train_test_split(tgmc_x, tgmc_y, test_size=.10, …Run Code Online (Sandbox Code Playgroud) 我有一组使用图像处理提取的240个特征.目标是在训练后将测试用例分为7个不同的类.对于每个类,有大约60个观察值(即,每个类有大约60个特征向量,每个向量具有240个组件).
许多研究论文和书籍利用顺序前向搜索或顺序后向搜索从特征向量中选择最佳特征.下图给出了顺序前向搜索算法.

任何这样的算法都使用一些标准来区分特征.一种常见的方法是使用Bhattacharyya距离作为标准.Bhattacharyya距离是分布之间的分歧类型度量.在一些研究和研究中,我发现给定A类的矩阵M1,该类包含该类的所有60个特征向量,使得它具有n = 60行和m = 240列(因为总共有240个特征)并且类BI的类似矩阵M2可以找出它们之间的Bhattacharyya距离并找到它们的相互依赖性.
我的问题是如何整合这两者.如何将Bhattacharyya距离作为选择算法中最佳特征的标准,如上所述.
有没有办法从 Scikit-learn 中使用的模型(或使用过的训练数据的整个表)中获取特征(属性)列表?我正在使用一些预处理,如特征选择,我想知道被选择的特征和被删除的特征。例如,我使用随机森林分类器和递归特征消除。
python artificial-intelligence feature-selection scikit-learn
我有以下管道来在语料库上执行机器学习.它首先提取文本,用于TfidfVectorizer提取n-gram,然后选择最佳特征.没有功能选择步骤,管道工作正常.然而,有了它,我得到了
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/sklearn/pipeline.py", line 90, in __init__
names, estimators = zip(*steps)
TypeError: zip argument #1 must support iteration
Run Code Online (Sandbox Code Playgroud)
在SGDClassifier().
pipeline = Pipeline([
# Use FeatureUnion to combine the features
('features', FeatureUnion(
transformer_list=[
# N-GRAMS
('ngrams', Pipeline([
('extractor', TextExtractor(normalized=True)), # returns a list of strings
('vectorizer', TfidfVectorizer(analyzer='word', strip_accents='ascii', use_idf=True, norm="l2", min_df=3, max_df=0.90)),
('feature_selection', SelectPercentile(score_func=chi2, percentile=70)),
])),
],,
)),
('clf', Pipeline([
SGDClassifier(n_jobs=-1, verbose=0)
])),
])
Run Code Online (Sandbox Code Playgroud) 我正在做PCA,我对哪些原始功能最重要感兴趣.让我用一个例子来说明这一点:
import numpy as np
from sklearn.decomposition import PCA
X = np.array([[1,-1, -1,-1], [1,-2, -1,-1], [1,-3, -2,-1], [1,1, 1,-1], [1,2,1,-1], [1,3, 2,-0.5]])
print(X)
Run Code Online (Sandbox Code Playgroud)
哪个输出:
[[ 1. -1. -1. -1. ]
[ 1. -2. -1. -1. ]
[ 1. -3. -2. -1. ]
[ 1. 1. 1. -1. ]
[ 1. 2. 1. -1. ]
[ 1. 3. 2. -0.5]]
Run Code Online (Sandbox Code Playgroud)
直观地,人们已经可以说特征1和特征4由于它们的低方差而不是非常重要.让我们在这个集合上应用pca:
pca = PCA(n_components=2)
pca.fit_transform(X)
comps = pca.components_
Run Code Online (Sandbox Code Playgroud)
输出:
array([[ 0. , 0.8376103 , 0.54436943, 0.04550712],
[-0. , 0.54564656, -0.8297757 , …Run Code Online (Sandbox Code Playgroud) xgboost的绘图API说明:
xgboost.plot_importance(booster, ax=None, height=0.2, xlim=None, ylim=None, title='Feature importance', xlabel='F score', ylabel='Features', importance_type='weight', max_num_features=None, grid=True, **kwargs)¶
Run Code Online (Sandbox Code Playgroud)
绘制基于拟合树木的重要性.
参数:
booster (Booster, XGBModel or dict) – Booster or XGBModel instance, or dict taken by Booster.get_fscore()
...
max_num_features (int, default None) – Maximum number of top features displayed on plot. If None, all features will be displayed.
Run Code Online (Sandbox Code Playgroud)
但是,在我的实现中,运行:
booster_ = XGBClassifier(learning_rate=0.1, max_depth=3, n_estimators=100,
silent=False, objective='binary:logistic', nthread=-1,
gamma=0, min_child_weight=1, max_delta_step=0, subsample=1,
colsample_bytree=1, colsample_bylevel=1, reg_alpha=0,
reg_lambda=1, scale_pos_weight=1, base_score=0.5, seed=0)
booster_.fit(X_train, y_train)
from xgboost import …Run Code Online (Sandbox Code Playgroud) 我正在使用带有python的spark 2.2.我正在使用ml.feature模块中的PCA.我正在使用VectorAssembler将我的功能提供给PCA.为了澄清,假设我有一个包含三列col1,col2和col3的表,那么我正在做:
from pyspark.ml.feature import VectorAssembler
assembler = VectorAssembler(inputCols=table.columns, outputCol="features")
df = assembler.transform(table).select("features")
from pyspark.ml.feature import PCA
pca = PCA(k=2, inputCol="features", outputCol="pcaFeatures")
model = pca.fit(df)
Run Code Online (Sandbox Code Playgroud)
这时我运行了2个组件的PCA,我可以看看它的值:
m = model.pc.values.reshape(3, 2)
Run Code Online (Sandbox Code Playgroud)
它对应于3(=我原始表中的列数)行和2(=我的PCA中的组件数)列.我的问题是这里的三行是否与我在上面的向量汇编程序中指定输入列的顺序相同?为进一步澄清,上述矩阵对应于:
| PC1 | PC2 |
---------|-----|-----|
col1 | | |
---------|-----|-----|
col2 | | |
---------|-----|-----|
col3 | | |
---------+-----+-----+
Run Code Online (Sandbox Code Playgroud)
请注意,此处的示例仅为了清楚起见.在我真正的问题中,我正在处理~1600列和一堆选择.我在spark文档中找不到任何明确的答案.我想这样做从原始表中选择最佳列/功能,以根据主要组件训练我的模型.还是有别的/更好的火花ML PCA,我应该看着推断这样的结果?
或者我不能使用PCA,并且必须使用其他技术,如spearman排名等?
尝试使用 BorutaPy 进行特征选择。但出现 TypeError: '(slice(None, None, None), array([0, 1, 2, 3, 4]))' 是无效键。
from sklearn.ensemble import RandomForestClassifier
from boruta import BorutaPy
rf = RandomForestClassifier(n_jobs=-1, max_depth=4)
# define Boruta feature selection method
feat_selector = BorutaPy(rf, n_estimators='auto', verbose=2, random_state=1)
X = train_dt[['age', 'menopause', 'tumor_size', 'inv_nodes', 'node_caps',
'deg_malig', 'breast', 'breast_quad', 'irradiat']]
Y = train_dt.label
# find all relevant features - 5 features should be selected
feat_selector.fit(x, y)
# check selected features - first 5 features are selected
feat_selector.support_
# check ranking of features …Run Code Online (Sandbox Code Playgroud) python machine-learning feature-extraction feature-selection
我正在尝试使用管道来提供集成投票分类器,因为我希望集成学习器使用在不同特征集上训练的模型。为此,我遵循了[1]中提供的教程。
以下是迄今为止我可以开发的代码。
y = df1.index
x = preprocessing.scale(df1)
phy_features = ['A', 'B', 'C']
phy_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
phy_processer = ColumnTransformer(transformers=[('phy', phy_transformer, phy_features)])
fa_features = ['D', 'E', 'F']
fa_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
fa_processer = ColumnTransformer(transformers=[('fa', fa_transformer, fa_features)])
pipe_phy = Pipeline(steps=[('preprocessor', phy_processer ),('classifier', SVM)])
pipe_fa = Pipeline(steps=[('preprocessor', fa_processer ),('classifier', SVM)])
ens = VotingClassifier(estimators=[pipe_phy, pipe_fa])
cv = KFold(n_splits=10, random_state=None, shuffle=True)
for train_index, test_index in cv.split(x):
x_train, x_test = x[train_index], x[test_index]
y_train, y_test = y[train_index], y[test_index]
ens.fit(x_train,y_train)
print(ens.score(x_test, …Run Code Online (Sandbox Code Playgroud) python pipeline feature-selection scikit-learn ensemble-learning
python ×6
scikit-learn ×5
pca ×2
algorithm ×1
apache-spark ×1
data-mining ×1
pipeline ×1
pyspark ×1
r ×1
svm ×1
weka ×1
xgboost ×1