sklearn特征选择 保留特征名称

经过特征选择后,数据变成了array类型,并失去了特征名称,查询资料后没有找到直接保留特征名称的方法。但是有一个get_support函数,可以保留提取出来的特征索引。
于是就通过这个方法自己加几句代码,取出特征选择后的特征名称。

1.方差过滤
from sklearn.feature_selection import VarianceThreshold  # 方差过滤
selector = VarianceThreshold()
x_train1 = selector.fit_transform(x_train1)  # 方差过滤
x_test1 = selector.transform(x_test1)  

此时数据变成了array类型,没有保留特征名称。

 保留特征名称
all_name = data.columns.values.tolist()  # 获得所有的特征名称
select_name_index0 = selector.get_support(indices=True)  # 留下特征的索引值,list格式
select_name0 = []
for i in select_name_index0:
    select_name0.append(all_name[i])
2.互信息法
互信息
mic = mutual_info_classif(x_train1, y_train1, random_state=0)
k = mic.shape[0] - sum(mic <= 0)   # 获得与标签列相关的特征列个数
skb = SelectKBest(mutual_info_classif, k=k)  # 特征选择
x_train1 = skb.fit_transform(x_train1, y_train1)
x_test1 = skb.transform(x_test1)
保留特征名称
select_name_index = skb.get_support(indices=True)
select_name = []
for i in select_name_index:
    select_name.append(select_name0[i])
print(select_name)

最终结果便是select_name。
这样就可以把select_name传入graphviz函数里画图啦。

  • 13
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
下面是使用皮尔森相关系数进行特征选择Python代码: ```python import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.datasets import load_boston from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import f_regression boston = load_boston() df = pd.DataFrame(boston.data, columns=boston.feature_names) df['MEDV'] = boston.target # Compute the correlation matrix corr = df.corr() # Generate a mask for the upper triangle mask = np.triu(np.ones_like(corr, dtype=bool)) # Set up the matplotlib figure f, ax = plt.subplots(figsize=(11, 9)) # Generate a custom diverging colormap cmap = sns.diverging_palette(230, 20, as_cmap=True) # Draw the heatmap with the mask and correct aspect ratio sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}) # Using Pearson correlation coefficient for feature selection X = df.drop('MEDV', axis=1) y = df['MEDV'] selector = SelectKBest(f_regression, k=5) selector.fit(X, y) # Get the columns to keep cols = selector.get_support(indices=True) # Create a new DataFrame with the selected features X_new = X.iloc[:,cols] # Print the selected features print(X_new.columns) ``` 解释: 1. 导入必要的库,包括Pandas、NumPy、Seaborn和Matplotlib。 2. 从Scikit-learn的数据集中加载波士顿房价数据集,并将其转换为Pandas DataFrame。 3. 计算特征之间的相关性矩阵。 4. 生成一个上三角形掩码,用于绘制热图时隐藏下三角。 5. 设置绘图的大小和颜色映射。 6. 用Seaborn绘制热图,并使用上面生成的掩码隐藏下三角。 7. 用Pearson相关系数进行特征选择。首先定义自变量X和因变量y,然后使用SelectKBest类和f_regression函数进行特征选择。在这里,我们选择了五个最相关的特征。 8. 获取要保留的列的索引。 9. 创建一个新的DataFrame,其中包含所选特征。 10. 输出所选特征名称。 注意:这个例子只是一个演示,实际应用中需要根据具体问题做出相应的调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值