sklean 数据集特征提取

来源:互联网 发布:曼秀雷敦洗面奶 知乎 编辑:程序博客网 时间:2024/06/06 15:02

1 利用地方差的方法减少特征数也及(PCA)

去除那些方差不满足基本设定的门限值得特征,特别是方差值为零的,因为方差值为零,那么数据集在该方向上比较密集,这数据无法通过学习来分类,因此该维度上的向量对特征的分类没有太多用处,因此可以去除该维度的特征,以减少计算复杂度。

例如,假设我们有一个具有布尔功能的数据集,我们想要删除在超过80%的样本中要么是一个或零(on或off)的所有特性。布尔特征是伯努利随机变量,并给出了这些变量的方差

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

我们可以选择门限是0.8*(1-0.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]])

就像预期的一样,删除了数据集的第一列,该列为零的概率p=5/6.0.8

2单变量特征选择

单变量特征选择是通过单变量统计测试选择最佳的特征变量,他可以被看做是对估计器的预处理步骤。

scikit- learn将特征选择例程作为实现转换方法的对象公开:

1 选择最好的K个特征,留下得分最好的K个特征,去掉其他的特征维度

2 按百分率选择,去掉除用户指定的百分率高的特征维度

对每个特性使用通用的单变量统计测试,假阳性率的选择,错误发现率的选择,或家庭明智的错误选择。

允许使用可配置策略执行单特性选择。这使得我们可以使用超参数搜索估计器来选择最优的单变量选择策略

例如,我们可以对样本进行\chi^2 测试,以获取以下两个最佳特性:

>>> 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)
这些对象以输入一个计分函数作为输入,它返回单变量分数和p值(为分数只有SelectKBestSelectPercentile)

  • For regression: f_regressionmutual_info_regression
  • For classification: chi2f_classifmutual_info_classif
基于f检验的方法估计了两个随机变量之间的线性依赖程度。另一方面,互信息方法可以捕获任何类型的统计依赖项,但作为非参数,

它们需要更多的样本来进行准确的估计。

注意不要使用带有分类问题的回归评分功能,您将会得到无用的结果。

单特征选择

print(__doc__)import numpy as npimport matplotlib.pyplot as pltfrom sklearn import datasets, svmfrom sklearn.feature_selection import SelectPercentile, f_classif# ############################################################################## Import some data to play with# The iris datasetiris = datasets.load_iris()# Some noisy data not correlatedE = np.random.uniform(0, 0.1, size=(len(iris.data), 20))# Add the noisy data to the informative featuresX = np.hstack((iris.data, E))y = iris.targetplt.figure(1)plt.clf()X_indices = np.arange(X.shape[-1])# ############################################################################## Univariate feature selection with F-test for feature scoring# We use the default selection function: the 10% most significant featuresselector = SelectPercentile(f_classif, percentile=10)selector.fit(X, y)scores = -np.log10(selector.pvalues_)scores /= scores.max()plt.bar(X_indices - .45, scores, width=.2,        label=r'Univariate score ($-Log(p_{value})$)', color='darkorange',        edgecolor='black')# ############################################################################## Compare to the weights of an SVMclf = svm.SVC(kernel='linear')clf.fit(X, y)svm_weights = (clf.coef_ ** 2).sum(axis=0)svm_weights /= svm_weights.max()plt.bar(X_indices - .25, svm_weights, width=.2, label='SVM weight',        color='navy', edgecolor='black')clf_selected = svm.SVC(kernel='linear')clf_selected.fit(selector.transform(X), y)svm_weights_selected = (clf_selected.coef_ ** 2).sum(axis=0)svm_weights_selected /= svm_weights_selected.max()plt.bar(X_indices[selector.get_support()] - .05, svm_weights_selected,        width=.2, label='SVM weights after selection', color='c',        edgecolor='black')plt.title("Comparing feature selection")plt.xlabel('Feature number')plt.yticks(())plt.axis('tight')plt.legend(loc='upper right')plt.show()
3 基于L1的特征选择

用L1规范对线性模型进行了处理,得到了稀疏解:他们的许多估计系数都为零。当目标是降低数据的维度时使用另一个分类器,可以单独使用feature_selection.SelectFromModel,来选择非零系数。

在稀疏估计方面, linear_model.Lasso对于回归问题特别有效, linear_model.LogisticRegression 和svm.LinearSVC对于分类的稀疏特别有用

>>> 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)
在SVM和逻辑回归方面,参数C控制系数率,C越小,选择的特征就越少。对于Lasso来说,alpha参数越高,选择的特征就越少。
4基于树的特征选择

给于书的估计器可以被用来计算特征的重要性,与sklearn.feature_selection可以用于减去不相关的特征

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)
特征的提取经常被作为管道的一部分,特征提取经常被用在机器学习的数据预处理阶段,因此建议使用 sklearn.pipeline.Pipeline:

clf = Pipeline([  ('feature_selection', SelectFromModel(LinearSVC(penalty="l1"))),  ('classification', RandomForestClassifier())])clf.fit(X, y)
在这段代码中,我们使用了sklearn . svm。LinearSVC加上sklearn.feature_selection。SelectFromModel以评估特性的重要性,并选择最相关的特性。这时,一个sklearn.ensemble。随机森林分类器被训练在转换的输出上,即只使用相关的特征。您可以使用其他特性选择方法和分类器来执行类似的操作,这些方法提供了一种评估特性输入的方法