python利用决策树进行特征选择
python利用决策树进行特征选择(注释部分为绘图功能),最后输出特征排序:
import numpy as np
import tflearn
from tflearn.layers.core import dropout
from tflearn.layers.normalization import batch_normalization
from tflearn.data_utils import to_categorical
from sklearn.model_selection import train_test_split
import sys
import pandas as pd
from pandas import Series,DataFrame
import matplotlib.pyplot as plt data_train = pd.read_csv("feature_with_dnn_todo2.dat")
print(data_train.info())
import matplotlib.pyplot as plt
print(data_train.columns) """
for col in data_train.columns[:]:
fig = plt.figure(figsize=(, ), dpi=)
fig.set(alpha=0.2)
plt.figure()
data_train[data_train.label == 0.0][col].plot()
data_train[data_train.label == 1.0][col].plot()
data_train[data_train.label == 2.0][col].plot()
data_train[data_train.label == 3.0][col].plot()
data_train[data_train.label == 4.0][col].plot()
plt.xlabel(u"sample data id")
plt.ylabel(col)
plt.title(col)
plt.legend((u'white', u'cdn',u'tunnel', u"msad", "todo"),loc='best')
plt.show()
""" from sklearn.ensemble import ExtraTreesClassifier
X = data_train.iloc[:,:]
y = data_train['label'].tolist() print(X.columns) X = X.values.tolist()
print(X[-:])
print("-------------")
print(y[-:]) # preprocess data
from sklearn.preprocessing import StandardScaler
#X = StandardScaler().fit_transform(X)
from sklearn.preprocessing import MinMaxScaler
X = MinMaxScaler().fit_transform(X)
from sklearn.preprocessing import Normalizer
#X=Normalizer().fit_transform(X) # abnormal data process
"""
for i,n in enumerate(y):
if n == 4.0:
y[i]=
""" import collections
print(collections.Counter(y)) print("just change to 2 classify !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
for i,n in enumerate(y):
if n != 2.0:
y[i]=
else:
y[i]=
print(collections.Counter(y))
#print(X.shape) from imblearn.over_sampling import SMOTE
X, y = SMOTE().fit_sample(X, y)
print(sorted(collections.Counter(y).items())) import sys
clf = ExtraTreesClassifier()
print(dir(clf))
X_new = clf.fit(X, y)
print (clf.feature_importances_ )
names = [u'flow_cnt', u'len(srcip_arr)', u'len(dstip_arr)', u'subdomain_num',
u'uniq_subdomain_ratio', u'np.average(dns_request_len_arr)',
u'np.average(dns_reply_len_arr)', u'np.average(subdomain_tag_num_arr)',
u'np.average(subdomain_len_arr)',
u'np.average(subdomain_weird_len_arr)',
u'np.average(subdomain_entropy_arr)', u'A_rr_type_ratio',
u'incommon_rr_type_rato', u'valid_ipv4_ratio', u'uniq_valid_ipv4_ratio',
u'request_reply_ratio', u'np.max(dns_request_len_arr)',
u'np.max(dns_reply_len_arr)', u'np.max(subdomain_tag_num_arr)',
u'np.max(subdomain_len_arr)', u'np.max(subdomain_weird_len_arr)',
u'np.max(subdomain_entropy_arr)', u'avg_distance', u'std_distance']
print "Features sorted by their score:"
print sorted(zip(clf.feature_importances_, names), reverse=True)
其中,
from imblearn.over_sampling import SMOTE
X, y = SMOTE().fit_sample(X, y)
print(sorted(collections.Counter(y).items())) 是使用smote算法补齐样本不均衡的情况。
加如下代码可以看score!
from sklearn.cross_validation import cross_val_score
scores = cross_val_score(clf, X, y)
print(scores.mean()) 官方文档:
1.13. Feature selection
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

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
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 transform method:
SelectKBestremoves all but thehighest scoring features
SelectPercentileremoves 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 errorSelectFwe.GenericUnivariateSelectallows 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
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 scores and p-values (or only scores for SelectKBest and SelectPercentile):
- For regression:
f_regression,mutual_info_regression- For classification:
chi2,f_classif,mutual_info_classif
The methods based on F-test estimate the degree of linear dependency between two random variables. On the other hand, mutual information methods can capture any kind of statistical dependency, but being nonparametric, they require more samples for accurate estimation.
Feature selection with sparse data
If you use sparse data (i.e. data represented as sparse matrices), chi2, mutual_info_regression, mutual_info_classif 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.
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 the importance of each feature is obtained either through a coef_ attribute or through a feature_importances_ attribute. Then, the least important features are pruned from current set of 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_ or feature_importances_ values are below the provided threshold parameter. Apart from specifying the threshold numerically, there are built-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 with feature_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:
- sphx_glr_auto_examples_text_document_classification_20newsgroups.py: 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 2007 http://users.isr.ist.utl.pt/~aguiar/CS_notes.pdf
1.13.4.2. 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 the sklearn.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.
参考:https://blog.csdn.net/code_caq/article/details/74066899
sklearn中实现如下:
from sklearn.datasets import load_boston
from sklearn.ensemble import RandomForestRegressor
import numpy as np
#Load boston housing dataset as an example
boston = load_boston()
X = boston["data"]
print type(X),X.shape
Y = boston["target"]
names = boston["feature_names"]
print names
rf = RandomForestRegressor()
rf.fit(X, Y)
print "Features sorted by their score:"
print sorted(zip(map(lambda x: round(x, 4), rf.feature_importances_), names), reverse=True)
结果如下:
Features sorted by their score:
[(0.5104, 'RM'), (0.2837, 'LSTAT'), (0.0812, 'DIS'), (0.0303, 'CRIM'), (0.0294, 'NOX'), (0.0176, 'PTRATIO'), (0.0134, 'AGE'), (0.0115, 'B'), (0.0089, 'TAX'), (0.0077, 'INDUS'), (0.0051, 'RAD'), (0.0006, 'ZN'), (0.0004, 'CHAS')]
from:https://blog.csdn.net/lming_08/article/details/39210409
RandomForest algorithm :
有两个class,分别处理分类和回归,RandomForestClassifier and RandomForestRegressor classes。样本提取时允许replacement(a
bootstrap sample),在随机选取的部分(而不是全部的)features上进行划分,与原论文的vote方法不同,scikit-learn通过平均每个分类器的预测概率(averaging their probabilistic prediction)来生成最终结果。
Extremely
Randomized Trees :
有两个class,分别处理分类和回归, ExtraTreesClassifier and ExtraTreesRegressor classes。默认使用所有样本,但划分时features随机选取部分。
给个比较例子:
>>> from sklearn.cross_validation import cross_val_score
>>> from sklearn.datasets import make_blobs
>>> from sklearn.ensemble import RandomForestClassifier
>>> from sklearn.ensemble import ExtraTreesClassifier
>>> from sklearn.tree import DecisionTreeClassifier >>> X, y = make_blobs(n_samples=10000, n_features=10, centers=100,
... random_state=0) >>> clf = DecisionTreeClassifier(max_depth=None, min_samples_split=1,
... random_state=0)
>>> scores = cross_val_score(clf, X, y)
>>> scores.mean()
0.97... >>> clf = RandomForestClassifier(n_estimators=10, max_depth=None,
... min_samples_split=1, random_state=0)
>>> scores = cross_val_score(clf, X, y)
>>> scores.mean()
0.999... >>> clf = ExtraTreesClassifier(n_estimators=10, max_depth=None,
... min_samples_split=1, random_state=0)
>>> scores = cross_val_score(clf, X, y)
>>> scores.mean() > 0.999
True
几点说明:
1)参数:最主要的调节参数是 n_estimators and max_features ,经验最好数据是,回归问题设置 max_features=n_features ,分类问题设置max_features=sqrt(n_features)(n_features是数据集的features个数).; 设置max_depth=None 并且结合min_samples_split=1 (i.e.,
when fully developing the trees)经常导致好的结果;但切记,最好的参数还是通过CV调出来的。
2)默认机制:random
forests, bootstrap samples are used by default (bootstrap=True)
while the default strategy for extra-trees is to use the whole dataset (bootstrap=False).
3)并行:设置n_jobs=k 保证使用机器的k个cores;设置n_jobs=-1 使用所有可用的cores。
4)特征重要性评估:一个决策树,节点在越高的分支,相应的特征对最终预测结果的contribute越大。这里的大,是指影响输入数据集的比例比较大(the fraction
of the input samples is large)。所以,对于某一个randomized tree,可以通过 The expected
fraction of the samples they contribute to can thus be used as an estimate of the relative
importance of the features.,然后对于 n_estimators 个randomized
tree,通过averaging those
expected activity rates over several randomized trees,达到区分特征重要性、特征选择的目的。但上面的叙述没什么X用,属性 feature_importances_ 已经保留了该重要性记录。。。。
python利用决策树进行特征选择的更多相关文章
- [Python] 利用Django进行Web开发系列(二)
1 编写第一个静态页面——Hello world页面 在上一篇博客<[Python] 利用Django进行Web开发系列(一)>中,我们创建了自己的目录mysite. Step1:创建视图 ...
- python利用or在列表解析中调用多个函数.py
python利用or在列表解析中调用多个函数.py """ python利用or在列表解析中调用多个函数.py 2016年3月15日 05:08:42 codegay & ...
- python 利用 ogr 写入shp文件,数据格式
python 利用 ogr 写入 shp 文件, 定义shp文件中的属性字段(field)的数据格式为: OFTInteger # 整型 OFTIntegerList # 整型list OFTReal ...
- Python利用pandas处理Excel数据的应用
Python利用pandas处理Excel数据的应用 最近迷上了高效处理数据的pandas,其实这个是用来做数据分析的,如果你是做大数据分析和测试的,那么这个是非常的有用的!!但是其实我们平时在做 ...
- python利用Trie(前缀树)实现搜索引擎中关键字输入提示(学习Hash Trie和Double-array Trie)
python利用Trie(前缀树)实现搜索引擎中关键字输入提示(学习Hash Trie和Double-array Trie) 主要包括两部分内容:(1)利用python中的dict实现Trie:(2) ...
- python 利用 setup.py 手动安装第三方类库
python 利用 setup.py 手动安装第三方类库 由于我在mac使用时,装了python3,默认有python2的环境,使用 pip 安装第三方类库时,老是安装到 python2的环境上: 在 ...
- python 利用栈实现复杂计算器
#第五周的作业--多功能计算器#1.实现加减乘除及括号的优先级的解析,不能使用eval功能,print(eval(equation))#2.解析复杂的计算,与真实的计算器结果一致#用户输入 1 - 2 ...
- 杂项之python利用pycrypto实现RSA
杂项之python利用pycrypto实现RSA 本节内容 pycrypto模块简介 RSA的公私钥生成 RSA使用公钥加密数据 RSA使用私钥解密密文 破解博客园登陆 pycrypto模块简介 py ...
- python利用kruskal求解最短路径的问题
python利用kruskal算法求解最短路径的问题,修改参数后可以直接使用 def kruskal(): """ kruskal 算法 ""&quo ...
随机推荐
- C 的指针和内存泄漏
引言 对于任何使用 C 语言的人,如果问他们 C 语言的最大烦恼是什么,其中许多人可能会回答说是指针和内存泄漏.这些的确是消耗了开发人员大多数调试时间的事项.指针和内存泄漏对某些开发人员来说似乎令人畏 ...
- Python浅拷贝copy()与深拷贝deepcopy()区别
其实呢,浅拷贝copy()与深拷贝deepcopy()之间的区分必须要涉及到python对于数据的存储方式. 首先直接上结论: —–我们寻常意义的复制就是深复制,即将被复制对象完全再复制一遍作为独立的 ...
- Leetcode 321.拼接最大数
拼接最大数 给定长度分别为 m 和 n 的两个数组,其元素由 0-9 构成,表示两个自然数各位上的数字.现在从这两个数组中选出 k (k <= m + n) 个数字拼接成一个新的数,要求从同一个 ...
- 使用dd命令快速生成大文件或者小文件的方法
使用dd命令快速生成大文件或者小文件的方法 转载请说明出处:http://blog.csdn.net/cywosp/article/details/9674757 在程序的测试中有些场 ...
- noip 2010 数字统计
数位dp解水题 luogu1179 dp[i][j]表示 有i位,且首位是j(包括0) 的 ‘2’的个数 dp[i][j]={ Σ(dp[i-1][k]),j!=2; Σ(dp[i-1][k])+va ...
- [luoguP3258] [JLOI2014]松鼠的新家(lca + 树上差分)
传送门 需要把一条路径上除了终点外的所有数都 + 1, 比如,给路径 s - t 上的权值 + 1,可以先求 x = lca(s,t) 类似数列上差分的思路,可以给 s 和 f[t] 的权值 + 1, ...
- 潜伏者(codevs 1171)
题目描述 Description [问题描述]R 国和S 国正陷入战火之中,双方都互派间谍,潜入对方内部,伺机行动.历尽艰险后,潜伏于 S 国的R 国间谍小C 终于摸清了S 国军用密码的编码规则:1. ...
- FATE---hdu2159(二重背包)
FATE Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submis ...
- 洛谷——P1547 Out of Hay
P1547 Out of Hay 题目背景 奶牛爱干草 题目描述 Bessie 计划调查N (2 <= N <= 2,000)个农场的干草情况,它从1号农场出发.农场之间总共有M (1 & ...
- HDU 3966
树链剖分 练模板: 用的 是HH的线段树 虽然之前是我不用的摸板 修改区间 求点值: CODE: #pragma comment(linker,"/STACK:1024000000,1024 ...
highest scoring features