首页 > 编程知识 正文

orb特征提取流程,特征选择框架

时间:2023-05-04 00:09:18 阅读:265635 作者:1412

文章目录 机器学习中的特征特征的重要性 特征提取和特征选择去除方差较小的特征单变量特征选择 (Univariate feature selection)F检验与互信息 其他特征选择方法重复性特征删除:用模型选择: 并入pipeline

机器学习中的特征

在机器学习和模式识别中,特征是在观测现象中的一种独立、可测量的属性。选择信息量大的、有差别性的、独立的特征是模式识别、分类和回归问题的关键一步。
最初的原始特征数据集可能太大,或者信息冗余,因此在机器学习的应用中,一个初始步骤就是选择特征的子集,或构建一套新的特征集,减少功能来促进算法的学习,提高泛化能力和可解释性。
在机器视觉中,一幅图像是一个观测,但是特征可能是图中的一条线;在自然语言处理中,一个文本是一个观测,但是其中的段落或者词频可能才是一种特征;在语音识别中,一段语音是一个观测,但是一个词或者音素才是一种特征。

特征的重要性

在特征选择时, 经常根据重要性, 将重要的特征选择出来放入训练集合. 相关系数和独立变量方法是常用的方法。
在构建模型的过程中, 有时候也会用到一些复杂的预测模型进行特征的重要性评价和选择, 例如多元自适应回归样条法( Multivariate Adaptive Regression Splines, MARS), 随机森林( Random Forest), 梯度提升机( Gradient Boosted Machines)等.

特征提取和特征选择 特征提取
对原始观测进行降维以便于建模的过程, 对于表格式的数据, 可以用主成分分析PCA, 聚类等方法; 对于图像数据, 可以用线(line)/边缘(edge)提取, 对于视频, 音频数据, 很多数字信号处理的方法都可以用于特征提取.特征选择
特征选择是自动地选择出对于问题最重要的特征子集的过程. 由于不同特征对模型准确度的影响程度不同, 特征选择算法用评分排序, 或者用反复实验来搜索出特征子集, 自动创建并评估模型得到最佳特征子集. 另外还有一些方法将特征选择作为模型的附加功能, 例如逐步回归法( stepwise regression)
sklearn的feature_selection模块在特征选择和样本集合降维上, 用来提高模型的正确率或者提高他们在高维度数据上的表现.

特征选择的方法可以大致分为:

Filter: 过滤法, 按照方差或者相关性对特征评分, 根据阈值选择特征Wrapper: 包装法, 根据目标函数(预测效果评分), 选择/排除若干特征

特征选择的目的:

降维, 增强模型泛化能力, 减少过拟合便于理解特征和标签之间的关系 去除方差较小的特征

VarianceThreshold是一个简单的特征选择基准方法, 该方法就是去除所有没有达到指定阈值的特征. 默认是去除所有零方差的数据, 例如那些在所有样本中都一样的特征.

举例来说, 我们有一个数据集合, 所有的数据都是布尔值, 我们想去掉80%的概率上不是0就是1的特征维度, 对于布尔型的数据来说, 服从伯努利分布, 理论方差为:
Var[X]=p(1-p)

from sklearn.feature_selection import VarianceThresholdX=[[0 0 1], [0 1 0], [1 0 0], [0 1 1], [0 1 0], [0 1 1]]sel = VarianceThreshold(threshold=(0.8*(1-0.8)))sel.fit_transform(X) 单变量特征选择 (Univariate feature selection)

单变量特征选择是对每个变量单独做统计分析, 之后再根据统计指标来判断变量是否重要.

问题类型统计指标分类问题卡方检验, f_classif, 互信息( mutual_info_classif)回归问题皮尔逊相关系数(f_regression), 互信息回归(mutual_info_regression)

其他形式:

SelectKBest: 仅保留得分K名以内的所有特征(TOP k)SelectPercentile 仅保留指定前k百分比的数据(TOP k%)单变量检验, 例如假阳性比例SelectFpr, 伪发现率 SelectFdr, 族系误差率SelectFwe.GenericUnivariateSelect 允许设置特征选择参数, 不同的选择策略可以使用超参数调优, 从而找到最佳单变量特征选择策略.

总的来说, 基于F检验的算法是用F检验估计来计算不同变量之间的线性依赖度(degree of linear dependency), 基于互信息的算法可以捕获到任意一种统计依赖关系, 但是作为一种非参数检验方法, 需要大量的样本才能得到比较准确的结果.

如果数据的稀疏性很强, 可以选择chi2, mutual_info_regression, mutual_info_classif 这些特征选择方法.

F检验与互信息

sklearn的官方教程给出了关于F检验和互信息区别的说明. 假设有3个特征 x1, x2, x3 都服从[0,1]正态分布,
目标函数如下:
y=x_1+sin(6pix_2)+0.1*N(0,1)
显然, y的取值与x_3完全不相关. 下面这段代码用了F检验和互信息两种方法给出了x与y之间的依赖关系.

import numpy as npimport matplotlib.pyplot as pltfrom sklearn.feature_selection import f_regression, mutual_info_regressionnp.random.seed(0)X = np.random.rand(1000, 3)y = X[:, 0] + np.sin(6*np.pi*X[:,1]) + 0.1*np.random.randn(1000)f_test, _ = f_regression(X, y)f_test /= np.max(f_test)mi = mutual_info_regression(X, y)mi = mi/np.max(mi)plt.figure(figsize=(15,15))for ii in range(3):plt.subplot(1, 3, ii+1)plt.scatter(X[:,ii], y, edgecolor=’black’, s=20)plt.xlabel(“$x_{}$”.format(ii+1), fontsize=14)if ii in range(3):plt.ylabel(“$y$”, fontsize=14)plt.title(“F-test={:.2f}, mi={:.2f}”.format(f_test[i], mi[i]), fontsize=16)plt.show()

图中依次绘制了x_1, x_2, x_3与y之间的依赖关系, 图上标题是对应特征的统计指数(F-score和互信息), 可以看到, F-test更适合与线性关系的特征, 而互信息系数在非线性
F检验得到的是数据之间的线性关系, 因此, F-test将x_1标记为最具有识别力的参数(discriminative), 互信息可以识别变量之间任意形式(非线性的)依赖关系, 因此互信息将x_2标记为最具有识别力的参数(或者说重要特征).

下面给出了一个F 检验(ANOVA 方差检验) 与SVM的例子, 在SVM之前, 先用anova对数据做了降维.

"""=================================================SVM-Anova: SVM with univariate feature selection=================================================This example shows how to perform univariate feature selection before running aSVC (support vector classifier) to improve the classification scores."""print(__doc__)import numpy as npimport matplotlib.pyplot as pltfrom sklearn import svm, datasets, feature_selectionfrom sklearn.cross_validation import cross_val_scorefrom sklearn.pipeline import Pipeline################################################################################ Import some data to play withdigits = datasets.load_digits()y = digits.target# Throw away data, to be in the curse of dimension settingsy = y[:200]X = digits.data[:200]n_samples = len(y)X = X.reshape((n_samples, -1))# add 200 non-informative featuresX = np.hstack((X, 2 * np.random.random((n_samples, 200))))################################################################################ Create a feature-selection transform and an instance of SVM that we# combine together to have an full-blown estimator#feature_selection.f_classif:计算所提供样本的方差分析F-值anova:方差分析#feature_selection.SelectPercentile(k):只留下k值最高的一组特征,返回最终的估计器transform = feature_selection.SelectPercentile(feature_selection.f_classif)#anova:Analysis of Variance(方差分析)clf = Pipeline([('anova', transform), ('svc', svm.SVC(C=1.0))])################################################################################ Plot the cross-validation score as a function of percentile of featuresscore_means = list()score_stds = list()percentiles = (1, 3, 6, 10, 15, 20, 30, 40, 60, 80, 100)for percentile in percentiles: #clf.set_params:设置此估计器的参数。 #使用网格搜索(grid search)和交叉验证(cross validation)来选择参数. #对方差分析中的参数percentile进行调节,实现多重比较检验 #用于确定控制变量的不同水平对观测变量的影响程度如何 clf.set_params(anova__percentile=percentile) # Compute cross-validation score using 1 CPU #http://scikit-learn.org/dev/modules/generated/sklearn.model_selection. #cross_val_score.html#sklearn.model_selection.cross_val_score #cross_val_score:最简单的交叉验证方法,cv选择折数,默认是3折交叉验证 this_scores = cross_val_score(clf, X, y, n_jobs=1) score_means.append(this_scores.mean()) score_stds.append(this_scores.std())#plt.errorbar以折线形式画出均值和方差plt.errorbar(percentiles, score_means, np.array(score_stds))plt.title( 'Performance of the SVM-Anova varying the percentile of features selected')plt.xlabel('Percentile')plt.ylabel('Prediction rate')plt.axis('tight') 其他特征选择方法 重复性特征删除:

from sklearn.feature_selection import RFE

print(__doc__)from sklearn.svm import SVCfrom sklearn.datasets import load_digitsfrom sklearn.feature_selection import RFEimport matplotlib.pyplot as plt# Load the digits datasetdigits = load_digits()X = digits.images.reshape((len(digits.images), -1))y = digits.target# Create the RFE object and rank each pixelsvc = SVC(kernel="linear", C=1)rfe = RFE(estimator=svc, n_features_to_select=1, step=1)rfe.fit(X, y)ranking = rfe.ranking_.reshape(digits.images[0].shape)# Plot pixel rankingplt.matshow(ranking, cmap=plt.cm.Blues)plt.colorbar()plt.title("Ranking of pixels with RFE")plt.show()

神经影像分析中常用的searchlight方法,本质上也是一种recursive feature selection方法.

用模型选择:

from sklearn.feature_selection import SelectFromModel

>>> 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) 并入pipeline

特征选择可以作为数据处理pipeline中的一个环节, 在核心模型之前进行数据降维和特征提取.

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

参考:
特征工程: https://blog.csdn.net/jasonding1354/article/details/47171115
https://blog.csdn.net/sqiu_11/article/details/58719935
scikit learn 文档: https://scikit-learn.org/stable/modules/feature_selection.html

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。