如何使用 SelectKBest 选择的特征训练模型?

How to train model with features selected by SelectKBest?

我在 Sklearn 的 Pipeline() class 中使用 SelectKBest() 将特征数量从 30 个减少到 5 个最佳特征。当我适合 classifer 时,我得到了与预期的特征选择不同的测试结果。但是,我在我的代码中发现了一个错误,该错误似乎不会在运行时导致实际错误。

当我调用 predict() 时,我意识到它仍然被赋予所有 30 个特征作为输入,就好像没有进行特征选择一样。尽管我只在 5 个最佳特征上训练了模型。如果仅针对 5 个最佳特征进行训练,肯定会向 SVM 提供 30 个特征来预测 class 会崩溃吗?

在我的 train_model(df) 函数中,我的代码如下所示:

def train_model(df):
    x,y = balance_dataset(df)
    X_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 0)

    feature_selection = SelectKBest()

    pipe = Pipeline([('sc', preprocessing.MinMaxScaler()),
                    ('feature_selection', feature_selection),
                    ('SVM', svm.SVC(decision_function_shape = 'ovr', kernel = 'poly'))])

    candidate_parameters = [{'SVM__C': [0.01, 0.1, 1], 'SVM__gamma': [0.01, 0.1, 1], 'feature_selection__k': [5]}]

    clf = GridSearchCV(estimator = pipe, param_grid = candidate_parameters, cv = 5, n_jobs = -1)
    clf.fit(X_train, y_train )

    return clf 

然而这是当我调用 trade():

时发生的事情
def trade(df):
    clf = train_model(df) 

    for index, row in trading_set.iterrows(): 

        features = row[:-3] #features is now an array of 30 features, even though model is only trained on 5

        if trade_balance > 0:
            trades[index] = trade_balance
            if clf.predict(features) == 1: #So this should crash and give an input Shape error, but it doesn't
            #Rest of code unneccesary#

所以我的问题是,我怎么知道模型真的只接受了 5 个最佳特征的训练?

您的代码是正确的,没有理由会抛出任何错误。您对管道对象和模型本身感到困惑,模型本身只是管道的一个块。

在您的示例中,管道采用 30 个特征,缩放它们,选择 5 个最佳特征,然后在这 5 个最佳特征上训练 SVM。因此,您的 SVM 已经接受了 5 个最佳特征的训练,但您仍然需要将所有 30 个特征传递给您的管道,因为您的管道希望数据以与训练期间相同的格式输入。