scikit_feature_selection实战

在进行李宏毅HW01作业时,需进行特征选择。
选用scikit-learn 中的feature_selection.
参考:
selectkbest
feature selection
在这里插入图片描述
在这里插入图片描述

实战注意点:

  1. chi 2 适用于非零的参数, 如果报错,换用 f_classif
    在这里插入图片描述
model = SelectKBest(f_classif, k=4)
X_new1 = model.fit_transform(x, y)
X_new1.shape
  1. 计算结果中可能出现inf, 影响最后特征重要性的排序。 建议把model.score_打印出来查看,如果有inf,用零填充。
scores = model.scores_
where_are_inf = np.isinf(scores)
scores[where_are_inf] = 0

在这里插入图片描述
3. 将前面的特征索引提取出来

代码

import math
import numpy as np

import pandas as pd
import os
import csv

from sklearn.feature_selection import SelectKBest, chi2, f_classif
from sklearn.preprocessing import MinMaxScaler

def feature_select(feature_data,label_data,k=4,column=None):
    model = SelectKBest(f_classif,k=k)
    X_new = model.fit(feature_data,label_data)
    scores = model.scores_
    where_are_inf = np.isinf(scores)
    scores[where_are_inf] = 0
    indices = np.argsort(scores)[::-1]
    if column:
        k_best_features = [column[i] for i in indices[0:k].tolist()]
        print('k best features are:',k_best_features)
    return X_new,indices[:k]+1 # add column id index  原来第一行是 id ,索引要加上

if __name__ == '__main__':
    train_data = pd.read_csv('./covid.train.csv').values
    x = train_data[:, 1:-1]  # pass first column id
    y = train_data[:, -1]
    x_selected, indices_selected = feature_select(x, y, 4)
    print(indices_selected)  # array([101,  85,  69,  53])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

闪闪发亮的小星星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值