Feature selection

原文:http://scikit-learn.org/stable/modules/feature_selection.html

The classes in the sklearn.feature_selection module can be used for feature selection/dimensionality reduction on sample sets, either to improve estimators’ accuracy scores or to boost their performance on very high-dimensional datasets.

1.13.1. Removing features with low variance

VarianceThreshold is a simple baseline approach to feature selection. It removes all features whose variance doesn’t meet some threshold. By default, it removes all zero-variance features, i.e. features that have the same value in all samples.

As an example, suppose that we have a dataset with boolean features, and we want to remove all features that are either one or zero (on or off) in more than 80% of the samples. Boolean features are Bernoulli random variables, and the variance of such variables is given by

\mathrm{Var}[X] = p(1 - p)

so we can select using the threshold .8 (1 .8):

>>>
>>> from sklearn.feature_selection import VarianceThreshold
>>> X = [[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 1], [0, 1, 0], [0, 1, 1]] >>> sel = VarianceThreshold(threshold=(.8 * (1 - .8))) >>> sel.fit_transform(X) array([[0, 1],  [1, 0],  [0, 0],  [1, 1],  [1, 0],  [1, 1]]) 

As expected, VarianceThreshold has removed the first column, which has a probability p = 5/6 > .8 of containing a zero.

1.13.2. Univariate feature selection

Univariate feature selection works by selecting the best features based on univariate statistical tests. It can be seen as a preprocessing step to an estimator. Scikit-learn exposes feature selection routines as objects that implement the transformmethod:

  • SelectKBest removes all but the k highest scoring features

  • SelectPercentile removes all but a user-specified highest scoring percentage of features

  • using common univariate statistical tests for each feature: false positive rate SelectFpr, false discovery rateSelectFdr, or family wise error SelectFwe.

  • GenericUnivariateSelect allows to perform univariate feature

    selection with a configurable strategy. This allows to select the best univariate selection strategy with hyper-parameter search estimator.

For instance, we can perform a \chi^2 test to the samples to retrieve only the two best features as follows:

>>>
>>> from sklearn.datasets import load_iris
>>> from sklearn.feature_selection import SelectKBest >>> from sklearn.feature_selection import chi2 >>> iris = load_iris() >>> X, y = iris.data, iris.target >>> X.shape (150, 4) >>> X_new = SelectKBest(chi2, k=2).fit_transform(X, y) >>> X_new.shape (150, 2) 

These objects take as input a scoring function that returns univariate p-values:

  • For regression: f_regression
  • For classification: chi2 or f_classif

Feature selection with sparse data

If you use sparse data (i.e. data represented as sparse matrices), only chi2 will deal with the data without making it dense.

Warning

 

Beware not to use a regression scoring function with a classification problem, you will get useless results.

Examples:

Univariate Feature Selection

1.13.3. Recursive feature elimination

Given an external estimator that assigns weights to features (e.g., the coefficients of a linear model), recursive feature elimination (RFE) is to select features by recursively considering smaller and smaller sets of features. First, the estimator is trained on the initial set of features and weights are assigned to each one of them. Then, features whose absolute weights are the smallest are pruned from the current set features. That procedure is recursively repeated on the pruned set until the desired number of features to select is eventually reached.

RFECV performs RFE in a cross-validation loop to find the optimal number of features.

Examples:

  • Recursive feature elimination: A recursive feature elimination example showing the relevance of pixels in a digit classification task.
  • Recursive feature elimination with cross-validation: A recursive feature elimination example with automatic tuning of the number of features selected with cross-validation.

1.13.4. Feature selection using SelectFromModel

SelectFromModel is a meta-transformer that can be used along with any estimator that has a coef_ or feature_importances_attribute after fitting. The features are considered unimportant and removed, if the corresponding coef_ orfeature_importances_ values are below the provided threshold parameter. Apart from specifying the threshold numerically, there are build-in heuristics for finding a threshold using a string argument. Available heuristics are “mean”, “median” and float multiples of these like “0.1*mean”.

For examples on how it is to be used refer to the sections below.

Examples

  • Feature selection using SelectFromModel and LassoCV: Selecting the two most important features from the Boston dataset without knowing the threshold beforehand.

1.13.4.1. L1-based feature selection

Linear models penalized with the L1 norm have sparse solutions: many of their estimated coefficients are zero. When the goal is to reduce the dimensionality of the data to use with another classifier, they can be used along withfeature_selection.SelectFromModel to select the non-zero coefficients. In particular, sparse estimators useful for this purpose are the linear_model.Lasso for regression, and of linear_model.LogisticRegression and svm.LinearSVC for classification:

>>>
>>> from sklearn.svm import LinearSVC
>>> from sklearn.datasets import load_iris >>> from sklearn.feature_selection import SelectFromModel >>> iris = load_iris() >>> X, y = iris.data, iris.target >>> X.shape (150, 4) >>> lsvc = LinearSVC(C=0.01, penalty="l1", dual=False).fit(X, y) >>> model = SelectFromModel(lsvc, prefit=True) >>> X_new = model.transform(X) >>> X_new.shape (150, 3) 

With SVMs and logistic-regression, the parameter C controls the sparsity: the smaller C the fewer features selected. With Lasso, the higher the alpha parameter, the fewer features selected.

Examples:

  • Classification of text documents using sparse features: Comparison of different algorithms for document classification including L1-based feature selection.

L1-recovery and compressive sensing

For a good choice of alpha, the Lasso can fully recover the exact set of non-zero variables using only few observations, provided certain specific conditions are met. In particular, the number of samples should be “sufficiently large”, or L1 models will perform at random, where “sufficiently large” depends on the number of non-zero coefficients, the logarithm of the number of features, the amount of noise, the smallest absolute value of non-zero coefficients, and the structure of the design matrix X. In addition, the design matrix must display certain specific properties, such as not being too correlated.

There is no general rule to select an alpha parameter for recovery of non-zero coefficients. It can by set by cross-validation (LassoCV or LassoLarsCV), though this may lead to under-penalized models: including a small number of non-relevant variables is not detrimental to prediction score. BIC (LassoLarsIC) tends, on the opposite, to set high values of alpha.

Reference Richard G. Baraniuk “Compressive Sensing”, IEEE Signal Processing Magazine [120] July 2007http://dsp.rice.edu/files/cs/baraniukCSlecture07.pdf

1.13.4.2. Randomized sparse models

The limitation of L1-based sparse models is that faced with a group of very correlated features, they will select only one. To mitigate this problem, it is possible to use randomization techniques, reestimating the sparse model many times perturbing the design matrix or sub-sampling data and counting how many times a given regressor is selected.

RandomizedLasso implements this strategy for regression settings, using the Lasso, while RandomizedLogisticRegression uses the logistic regression and is suitable for classification tasks. To get a full path of stability scores you can uselasso_stability_path.

../_images/plot_sparse_recovery_0031.png

Note that for randomized sparse models to be more powerful than standard F statistics at detecting non-zero features, the ground truth model should be sparse, in other words, there should be only a small fraction of features non zero.

Examples:

  • Sparse recovery: feature selection for sparse linear models: An example comparing different feature selection approaches and discussing in which situation each approach is to be favored.

References:

  • N. Meinshausen, P. Buhlmann, “Stability selection”, Journal of the Royal Statistical Society, 72 (2010)http://arxiv.org/pdf/0809.2932
  • F. Bach, “Model-Consistent Sparse Estimation through the Bootstrap” http://hal.inria.fr/hal-00354771/

1.13.4.3. Tree-based feature selection

Tree-based estimators (see the sklearn.tree module and forest of trees in the sklearn.ensemble module) can be used to compute feature importances, which in turn can be used to discard irrelevant features (when coupled with thesklearn.feature_selection.SelectFromModel meta-transformer):

>>>
>>> from sklearn.ensemble import ExtraTreesClassifier
>>> from sklearn.datasets import load_iris >>> from sklearn.feature_selection import SelectFromModel >>> iris = load_iris() >>> X, y = iris.data, iris.target >>> X.shape (150, 4) >>> clf = ExtraTreesClassifier() >>> clf = clf.fit(X, y) >>> clf.feature_importances_ array([ 0.04..., 0.05..., 0.4..., 0.4...]) >>> model = SelectFromModel(clf, prefit=True) >>> X_new = model.transform(X) >>> X_new.shape (150, 2) 

Examples:

  • Feature importances with forests of trees: example on synthetic data showing the recovery of the actually meaningful features.
  • Pixel importances with a parallel forest of trees: example on face recognition data.

1.13.5. Feature selection as part of a pipeline

Feature selection is usually used as a pre-processing step before doing the actual learning. The recommended way to do this in scikit-learn is to use a sklearn.pipeline.Pipeline:

clf = Pipeline([('feature_selection', SelectFromModel(LinearSVC(penalty="l1"))), ('classification', RandomForestClassifier()) ]) clf.fit(X, y) 

In this snippet we make use of a sklearn.svm.LinearSVC coupled with sklearn.feature_selection.SelectFromModel to evaluate feature importances and select the most relevant features. Then, a sklearn.ensemble.RandomForestClassifier is trained on the transformed output, i.e. using only relevant features. You can perform similar operations with the other feature selection methods and also classifiers that provide a way to evaluate feature importances of course. See thesklearn.pipeline.Pipeline examples for more details.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/543842.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ronald aai_AAI的完整形式是什么?

ronald aaiAAI:印度机场管理局 (AAI: Airport Authority of India) AAI is an abbreviation of the Airport Authority of India. It operates under the Ministry of Civil Aviation. It is in charge of creating, crafting, maintaining and enhancing the civil…

使用Eclipse-Maven-git做Java开发(13)--导入git仓库的代码到eclipse

2019独角兽企业重金招聘Python工程师标准>>> 前面讲到了怎么使用osc的git服务进行代码托管。至此,我们已经可以使用git进行文件的版本管理了,甚至可以进行不需要IDE的编程了,但是我们绝大多数时候还是需要IDE的,接下来…

python 三维图直方图_Python | 阶梯直方图

python 三维图直方图A histogram is a graphical technique or a type of data representation using bars of different heights such that each bar groups numbers into ranges (bins or buckets). Taller the bar higher the data falls in that bin. A Histogram is one o…

ExtJS4.2学习(21)动态菜单与表格数据展示操作总结篇2

运行效果&#xff1a; 此文介绍了根据操作左侧菜单在右面板展示相应内容。 一、主页 先看一下跳转主页的方式&#xff1a;由在webapp根目录下的index.jsp跳转至demo的index.jsp 下面是demo的index.jsp的代码 <% page language"java" contentType"text/html; …

jQuery之call()方法的使用

最近在做项目时候&#xff0c;写了几行关于DOM操作的代码&#xff0c;在方法中使用了this&#xff0c;在后期重构的时候&#xff0c;想将这段分离出来做成一个方法。 最开始想的很简单&#xff0c;就直接分离出来使用方法名称调用即可。 但是实际操作的时候没有效果&#xff0c…

github的使用

GitHub操作总结 : 总结看不明白就看下面的详细讲解. GitHub操作流程 : 第一次提交 : 方案一 : 本地创建项目根目录, 然后与远程GitHub关联, 之后的操作一样; -- 初始化git仓库 :git init ; -- 提交改变到缓存 :git commit -m description ; -- 本地git仓库关联GitHub仓库 : g…

sql更改完整模式报错_SQL的完整形式是什么?

sql更改完整模式报错SQL&#xff1a;结构化查询语言 (SQL: Structured Query Language) SQL is an abbreviation of Structured Query Language. It is a programming language developed and designed for handling structured data in Relational Database Management System…

基于微服务架构,改造企业核心系统之实践

2019独角兽企业重金招聘Python工程师标准>>> 1. 背景与挑战 随着公司国际化战略的推行以及本土业务的高速发展&#xff0c;后台支撑系统已经不堪重负。在吞吐量、稳定性以及可扩展性上都无法满足日益增长的业务需求。对于每10万元额度的合同&#xff0c;从销售团队…

bkg bnc_BNC的完整形式是什么?

bkg bncBNC&#xff1a;刺刀Neill–Concelman (BNC: Bayonet Neill–Concelman) BNC is an abbreviation of "Bayonet Neill–Concelman". BNC是“刺刀Neill–Concelman”的缩写 。 It is also known as "British Naval Connector" or "Bayonet Nut …

使用visio 提示此UML形状所在的绘图页不是UML模型图的一部分 请问这个问题怎么解决?...

解决方法新建->选择软件与数据库模板->选择UML模型图->注意&#xff1a;如果不选择UML模型图的话&#xff0c;可能会出现无法编辑形状文本&#xff0c;提示“此UML形状所在的绘图页不是UML模型图的一部分&#xff0c;该形状设计用于利用UML模型图模板创建的绘图”关注…

tgc 什么意思 tgt_TGT的完整形式是什么?

tgc 什么意思 tgtTGT&#xff1a;训练有素的研究生老师 (TGT: Trained Graduate Teacher) TGT is an abbreviation of Trained Graduate Teacher. It is a title, not a teaching program that is given to a graduate person who has done completion of training in teaching…

svn的使用(Mac)

2019独角兽企业重金招聘Python工程师标准>>> 从服务器下载代码 在终端中输入svn checkout svn://localhost/mycode --username用户名 --password密码 /Users/apple/Documents/code指令意思&#xff1a;将服务器中mycode仓库的内容下载到/Users/apple/Documents/myCo…

css 中文文字字体_使用CSS的网络字体

css 中文文字字体CSS | 网络字体 (CSS | Web fonts) Web fonts allow people to use fonts that are not pre-installed in their computers. When you want to include a particular font simply include the font file on your browser and it will be downloaded. Web字体允…

C4.5决策树算法概念学习

数据挖掘一般是指从大量的数据中自动搜索隐藏于其中的有着特殊关系性的信息的过程。 •分类和聚类•分类(Classification)就是按照某种标准给对象贴标签&#xff0c;再根据标签来区分归类&#xff0c;类别数不变。•聚类(clustering)是指根据“物以类聚”的原理&#xff0c;将本…

python修改y轴刻度_Python | Y轴刻度限制

python修改y轴刻度In some cases, we need to visualize our data within some defined range rather than the whole data. For this, we generally set the y-axis scale within a limit and this ultimately helps us to visualize better. Sometimes, it acts as zooming a…

em算法示例_带有示例HTML'em'标签

em算法示例<em>标签 (<em> Tag) <em> tag in HTML is used to display the text in emphasized form. <em> tag add semantic meaning to the text, text inside it is treated as emphasized text. HTML中的<em>标记用于以强调形式显示文本。 &…

Mac OSX 安装nvm(node.js版本管理器)

我的系统 1.打开github官网https://github.com/&#xff0c;输入nvm搜索,选择creationix&#xff0f;nvm&#xff0c;打开 2.找到Install script&#xff0c;复制 curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.29.0/install.sh | bash . 3. 打开终端&#xf…

关于HTML5标签不兼容(IE6~8)

HTML5的语义化标签以及属性&#xff0c;可以让开发者非常方便地实现清晰的web页面布局&#xff0c;加上CSS3的效果渲染&#xff0c;快速建立丰富灵活的web页面显得非常简单。 比较常用的HTML5的新标签元素有&#xff1a; <header>定义页面或区段的头部&#xff1b;<na…

css网格_CSS网格容器

css网格CSS | 网格容器 (CSS | Grid Containers) There are numerous ways to display our list items or elements. For instance, we can display them in the navigation bar, in a menu bar and whatnot. Well, it would be right to say that there are many more such me…

监听文本框数据修改,特别是微信等客户端直接选择粘贴修改

2019独角兽企业重金招聘Python工程师标准>>> // 手机号码信息加载验证 $(input).bind(input propertychange, function() { initPage.checkName(); }); 转载于:https://my.oschina.net/u/1579617/blog/550488