-
卡方检验作为非参数的方法,主要是检验自变量对因变量的线性相关程度,常用于特征变量的筛选。一般sklearn包中的函数SelectKBest和SelectPercentile即可实现。
-
本文以SelectPercentile为例
# -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
from sklearn.feature_selection import SelectPercentile
from sklearn.feature_selection import chi2
class Chi2Select():
def __init__(self):
pass
# 卡方检验特征筛选
def Chi2Func(self,data_final,flag,spec_score):
#保留百分比的最高得分的特征
selector = SelectPercentile (chi2, percentile=spec_score)
selector.fit(data_final,flag)
return selector
# 加载及调用
def load_transform(self):
path = r'E:\programGao\csdnProgram'
data = pd.read_excel(path + '/dataset.xlsx', 'all')
x = np.array(data.iloc[:,2:])
y = np.array(data['flag'])
print('查看初始数据 : \n', x)
selector = self.Chi2Func(x, y, spec_score=90)# 保留90%的最高得分特征
print('特征得分 : \n', selector.scores_)
print('特征得分的p_value值 : \n', selector.pvalues_)
print('筛选后保留特征 : \n', selector.get_support(indices=True))
print('还原保留特征 : \n', selector.transform(x))
if __name__ == '__main__':
Chi2Select().load_transform()
-
查看scores和p-values
-
可以看出0,1,4的特征得分较高,且p值较小,特征也比较显著
-
本次chi2选取的百分比阈值为90%,最终选取的特征如下: