我正在尝试从60000个功能中选择数百个,为此,我想使用mutual_info_classif。
但我发现,与使用SelectKBest相比,直接使用mutual\u info\u classif会得到不同的结果
为了演示,我定义了一个小df,其中只有一列与目标相关:
A B C D E target
0 1 1 1 1 1 1
1 2 3 2 2 2 0
2 3 3 3 3 3 0
3 4 3 4 4 4 0
4 5 1 5 5 5 1
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import mutual_info_classif
df = pd.DataFrame({'A':[1,2,3,4,5],
'B':[1,3,3,3,1],
'C':[1,2,3,4,5],
'D':[1,2,3,4,5],
'E':[1,2,3,4,5],
'target':[1,0,0,0,1]})
X = df.drop(['target'],axis=1)
y = df.target
threshold = 3 # the number of most relevant features
然后,我使用相互信息分类获得MI分数:
high_score_features1 = []
feature_scores = mutual_info_classif(X, y, random_state=0, n_neighbors=3,discrete_features='auto')
for score, f_name in sorted(zip(feature_scores, X.columns), reverse=True)[:threshold]:
print(f_name, score)
high_score_features1.append(f_name)
feature_scores
输出:
B 0.48333333333333306
E 0.0
D 0.0
array([0. , 0.48333333, 0. , 0. , 0. ])
然后我使用SelectKBest,为了确保使用相同的参数,我使用自己的调用:
def my_func(X, y):
return mutual_info_classif(X, y, random_state=0, n_neighbors=3, discrete_features='auto')
high_score_features1=[]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
f_selector = SelectKBest(score_func=my_func, k=threshold)
f_selector.fit(X_train, y_train)
for score, f_name in sorted(zip(f_selector.scores_, X.columns), reverse=True)[:threshold]:
print(f_name, score)
high_score_features1.append(f_name)
f_selector.scores_
输出:
B 0.8333333333333331
E 0.0
D 0.0
array([0. , 0.83333333, 0. , 0. , 0. ])
我不了解差异的来源,也不确定哪种方法更可靠地用于我的真实数据
看起来,直接使用
mutual_info_classif
模型和使用SelectKBest
模型得到不同结果的原因是,在不同的数据集上拟合它们。您的SelectKBest
模型正在训练集上拟合,而您的mutual_info_classif
模型正在拟合整个数据。如果在训练数据上拟合两个模型,则两个模型给出相同的输出相关问题 更多 >
编程相关推荐