我试图对一个名为x_train
的pandas数据框中的特定连续数值特征应用SelectKBest()
函数,同时标签列定义为一个二元响应变量(1,0)列,称为y_train
:
from sklearn.metrics import mutual_info_scorefrom sklearn.feature_selection import SelectKBest, f_classifnumerical_features=['col1', 'col2']########################################################################def get_numerical_features(features, class_label): class_label=pd.DataFrame(class_label) fs=SelectKBest(f_classif, k='all') for feature in features: fs.fit(class_label, feature) return(print('Feature %d: %f' % (feature, fs.scores_[feature]))) ######################################################################## applying the functionget_numerical_features(features=x_train[numerical_features], class_label=y_train)
然而,当应用get_numerical_features()
时,输出如下:
TypeError: 单例数组array(‘col1′, dtype='<U4’)不能被视为有效的集合。
我遗漏了什么?
有什么方法可以将每一列转换为有效的集合吗?
数据演示
x_train=pd.DataFrame({'col1': [1, 2, 7, 10, 2], 'col2': [3, 4, 27, 3, 1]})y_train=pd.DataFrame({'label': [0, 0, 0, 1, 1]})
回答:
我遗漏了什么?
fs.scores_
实际上是一个形状为(2,)的数组,你不能用feature
来索引它。试试这样:
from sklearn.metrics import mutual_info_scorefrom sklearn.feature_selection import SelectKBest, f_classifnumerical_features=['col1', 'col2']def get_numerical_features(features, class_label): #在你的数据演示中,class_label已经是一个DataFrame fs=SelectKBest(f_classif, k='all') fs.fit(features, class_label) # 这应该在这里 for i, feature in zip(range(len(features)), features): print('Feature %s: %f' % (feature, fs.scores_[i])) # applying the functionx_train = pd.DataFrame({'col1': [1, 2, 7, 10, 2], 'col2': [3, 4, 27, 3, 1]})y_train = pd.DataFrame({'label': [0, 0, 0, 1, 1]})get_numerical_features(features=x_train[numerical_features], class_label=y_train['label']) #output: #Feature col1: 0.486076#Feature col2: 0.846043
有什么方法可以将每一列转换为有效的集合吗?
为此,你可以使用fit_transform
来自动选择得分最高的k
个特征。
fs = SelectKBest(f_classif, k=1) # 使用`all`将选择所有特征,默认值=10x_train_new = fs.fit_transform(features, class_label)print(x_train_new) # 由于k=1,这将打印得分较高的col2的值