python-如何正确选择k个最佳数值特征?

我试图对一个名为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的值

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注