京公网安备 11010802034615号
经营许可证编号:京B2-20210330
特征选择是一个重要的数据预处理过程,获得数据之后要先进行特征选择然后再训练模型。主要作用:1、降维 2、去除不相关特征。
特征选择方法包含:子集搜索和子集评价两个问题。
子集搜索包含前向搜索、后向搜索、双向搜索等。
子集评价方法包含:信息增益,交叉熵,相关性,余弦相似度等评级准则。
两者结合起来就是特征选择方法,例如前向搜索与信息熵结合,显然与决策树很相似。
常见特征选择有三类方法:过滤式(filter),包裹式(wrapper)和嵌入式(embedding).————见周志华老师《机器学习》11章。
1. 过滤式(filter)
过滤式方法先对数据集进行特征选择,再训练学习器。两者分裂开来。Relief是一种著名的过滤式特征选择方法,设计了一种相关统计量来度量特征重要性。
sklearn模块中有一些特征选择的方法。
sklearn官方文档
(1)* Removing features with low variance*
特征筛选的时候,对于特征全0,全1 ,多数1,多数0的要删去。利用sklearn中模块,可如下操作(个人认为属于过滤式的)。
代码如下:
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]])
(2)利用单变量特征选择(统计测试方法)。
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 transform method:
SelectKBest选择排名排在前n个的变量
SelectPercentile 选择排名排在前n%的变量
其他指标: false positive rate SelectFpr, false discovery rate SelectFdr, or family wise error SelectFwe 和 GenericUnivariateSelect。
对于regression问题:用f_regression函数。
对于classification问题:用chi2或者f_classif函数。
例如:利用 F-test for feature scoring
We use the default selection function: the 10% most significant features**
代码来源
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets, svm
from sklearn.feature_selection import SelectPercentile, f_classif
###############################################################################
# import some data to play with
# The iris dataset
iris = datasets.load_iris() #数据本身(150,4)
# Some noisy data not correlated
E = np.random.uniform(0, 0.1, size=(len(iris.data), 20))
#添加(150,20)的随机噪声
# Add the noisy data to the informative features
X = np.hstack((iris.data, E))
print X.shape #(150,24)维度
y = iris.target
###############################################################################
plt.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 features
selector = 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='g')
###############################################################################
# Compare to the weights of an SVM
clf = 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='r')
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='b')
plt.title("Comparing feature selection")
plt.xlabel('Feature number')
plt.yticks(())
plt.axis('tight')
plt.legend(loc='upper right')
plt.show()
P值越小,显著性越高。负对数也越大。前4个有明显的显著性。(后20个无显著性)

2.包裹式(wrapper)
与过滤式机器学习不考虑后续学习器不同,包裹式特征选择直接把最终要使用的学习器性能作为特征子集的评价标准。由于包裹式特征选择的方法直接针对给定学习器进行优化,包裹式特征一般回避过滤式要好。LVW是一种典型的方法。采用随机策略搜索特征子集,而每次特征子集的评价都需要训练学习器,开销很大。
3.嵌入式(embedding)
嵌入式特征选择将特征选择过程和机器训练过程融合为一体。两者在同一优化过程中完成,即在学习器训练过程中自动进行了特征选择。
例如:L1正则化(Lasso,注意L2岭回归并不会降低维度)
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)
基于树的特征选取
对于树模型选择特征属于上面哪一种,感觉是包裹式,并不确定。
sklearn 提供例子:
class sklearn.ensemble.ExtraTreesClassifier(n_estimators=10, criterion=’gini’, max_depth=None, min_samples_split=2……)
分类标准 默认基尼系数,还可以设成信息熵增益。
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.ensemble import ExtraTreesClassifier
# Build a classification task using 3 informative features
X, y = make_classification(n_samples=1000,
n_features=10,
n_informative=3,
n_redundant=0,
n_repeated=0,
n_classes=2,
random_state=0,
shuffle=False)
# Build a forest and compute the feature importances
forest = ExtraTreesClassifier(n_estimators=250,
random_state=0)
forest.fit(X, y)
importances = forest.feature_importances_
std = np.std([tree.feature_importances_ for tree in forest.estimators_],
axis=0)
indices = np.argsort(importances)[::-1]
# Print the feature ranking
print("Feature ranking:")
for f in range(X.shape[1]):
print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))
# Plot the feature importances of the forest
plt.figure()
plt.title("Feature importances")
plt.bar(range(X.shape[1]), importances[indices],
color="r", yerr=std[indices], align="center")
plt.xticks(range(X.shape[1]), indices)
plt.xlim([-1, X.shape[1]])
plt.show()
特征重要性如图所示

上述的所有源于sklearn上的特征选取部分,细节[here]。
数据分析咨询请扫描二维码
若不方便扫码,搜微信号:CDAshujufenxi
CDA数据分析师 出品 作者:李诗怡 一、数据处理概述 定义: 在正式开展数据分析之前,对原始采集的数据进行整理、修正、加工和精 ...
2026-11-06一、为什么数据要先标准化 拿到一份数据,各列的量纲往往完全不同:年龄单位是"岁"(约 20~60),收入单位是"元"(几千到几万) ...
2026-11-06一、为什么 Python 成了统计分析的主流工具 十年前做统计分析,主流选择是 SPSS、SAS、Stata。现在越来越多的研究者、分析师转向 ...
2026-11-06核心资源推荐 CDA教材(2025):https://edu.cda.cn/goods/show/3151CDA模拟题(2025):https://edu.cda.cn/goods/show/2845CD ...
2026-11-06核心资源推荐 CDA教材(2025):https://edu.cda.cn/goods/show/3151CDA模拟题(2025):https://edu.cda.cn/goods/show/2845CD ...
2026-11-06“大学生必备证书有哪些”最容易被答成一张越长越好的清单。但校招筛选的真实逻辑是:证书要对应你投的岗位任务,并且在校期间确 ...
2026-11-05大学期间能报的证书,先别急着看“含金量榜单”。更实用的第一步是问:我现在这个身份、这个学历,符合报考条件吗? 很多证书宣 ...
2026-11-05大学期间能考的证书很多,但真正需要先回答的是两个问题:当前有没有报考资格,以及这张证书对应什么岗位任务。 前者决定你能不 ...
2026-11-05先把结论说清楚:真正“只有在校大学生能考、毕业就彻底没资格”的证书数量不多,主要集中在语言类考试的部分专项、面向高校学生 ...
2026-11-05上班族问“考什么证书有用”,真正要解决的不是找一张“最值钱”的证,而是判断哪张证能嵌进你现有的岗位任务。同样一张证书,做 ...
2026-11-05职称证书不是统一的考试项目。同样“考职称”,经济、会计、统计、审计、软考走全国统一考试,工程、教师、卫生等系列多数走评审 ...
2026-11-0533岁选证书,最怕两件事:一是被“适合女生”的清单带着走,考完发现岗位用不上;二是投入大半年,报名时才发现学历、专业或工作 ...
2026-11-05“女生容易考的证书”这个问题,真正难的不是找一份名单,而是判断“容易”到底指什么。报名条件宽松、考试通过率高、拿证后能找 ...
2026-11-05“女生适合考什么证书”这类搜索,背后往往是同一个困惑:网上榜单太多,口径却说不清楚。有人把培训证书和职业资格混在一起排, ...
2026-11-05先把结论说清楚:没有一张证书对所有人都“又好考又实用”。同一个证,对在校生可能报名门槛都过不了,对有三年工作经验的人却只 ...
2026-11-05“考证书有哪些”这个问题,如果只想要一份名单,网上能搜到成百上千个。但真正有用的答案不是“有哪些”,而是“它们分别是什么 ...
2026-11-05“考什么证好一点”这句话,十个人问可能有十个意思。有人想问哪个证容易过,有人想知道哪个证找工作管用,还有人关心哪个证长期 ...
2026-11-05“考哪些证书最吃香”很难用一张榜单回答。同一张证书,在有的岗位是硬门槛,在另一些岗位只是加分项;对在校生和在职者的价值也 ...
2026-11-05家庭主妇能考的证书不少,但真正值得花时间的,不是“哪个证热门”,而是先确认你当前能不能报,再按每周可投入时间和未来出口缩 ...
2026-11-05“国家认证的职业技能证书”并不是某一本证书的正式名称,而是一句被大量使用的宣传口径。它可能指向人社部门的国家职业资格、备 ...
2026-11-05