数据筛选特征方法-卡方检验法

  • 卡方检验作为非参数的方法,主要是检验自变量对因变量的线性相关程度,常用于特征变量的筛选。一般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%,最终选取的特征如下:
    在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值