【发布时间】:2020-07-30 03:35:16
【问题描述】:
我在 Sklearn 的 Pipeline() 类中使用 SelectKBest() 将特征数量从 30 个减少到 5 个最佳特征。当我拟合分类器时,我会得到与特征选择不同的测试结果。但是我在我的代码中发现了一个错误,它似乎不会在运行时导致实际错误。
当我致电predict() 时,我意识到它仍然被赋予所有 30 个特征作为输入,就好像没有进行特征选择一样。尽管我只对模型进行了 5 个最佳特征的训练。如果只对 5 个最佳特征进行训练,是否给 SVM 提供 30 个特征来预测一个类会崩溃?
在我的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 个最佳特征的训练?
【问题讨论】:
标签: machine-learning scikit-learn pipeline feature-selection