我在 Sklearn 的 Pipeline()
类中使用 SelectKBest()
将特征数量从 30 个减少到 5 个最佳特征。当我安装分类器时,我通过特征选择得到了与预期不同的测试结果。但是,我在代码中发现了一个错误,该错误似乎不会在运行时导致实际错误。
当我调用 predict()
时,我意识到它仍然被给予所有 30 个特征作为输入,就好像特征选择没有发生一样。尽管我只根据 5 个最佳特征训练模型。如果给 SVM 提供 30 个特征来预测一个类,如果它只接受 5 个最佳特征的训练,肯定会崩溃吗?
在我的 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 个最佳特征进行训练?
最佳答案
您的代码是正确的,并且没有理由它会抛出任何错误。您对管道对象和模型本身感到困惑,模型本身只是管道的一个 block 。
在您的示例中,管道采用 30 个特征,对其进行缩放,选择 5 个最佳特征,然后根据这 5 个最佳特征训练 SVM。因此,您的 SVM 已经接受了 5 个最佳特征的训练,但您仍然需要将所有 30 个特征传递到您的管道,因为您的管道期望数据以与训练期间相同的格式出现。
关于machine-learning - 如何使用 SelectKBest 选择的特征来训练模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61257982/