如何实现主分量数的随机搜索优化?



我正在尝试为 MLPClassifier 实现随机搜索优化。我已经成功地优化了"hidden_layer_sizes"、"求解器"和"激活"。但是我在优化主组件数量时遇到了问题。由于此参数用于创建 PCA 以转换训练数据集,并且不会作为参数传递给 MLPClassifier 函数,因此我无法像其他超参数一样将其传递到"参数"字典中。

# PCA 
nof_prin_components = 200  # PARAMETER for optimisation in expereiments
pca = PCA(n_components=nof_prin_components, whiten=True).fit(X)
# applies PCA to the train and test images to calculate the principal components
# n_components sets the number of components to keep
X_train_pca = pca.transform(X) 
parameters = {
'hidden_layer_sizes': [150,200,250,300,400],
'solver': ['sgd', 'adam', 'lbfgs'],
'activation': ['relu', 'tanh', 'identity', 'logistics']
}
#Function that performs the actual hyperparameter tuning to return the best set of parameters and the best score
def tuning(clf, parameters, iterations, X, y):
randomSearch = RandomizedSearchCV(clf, param_distributions=parameters, n_jobs=-1, n_iter=iterations, cv=6) 
#n_jobs=-1 ensures that all the cores of cpu will work
randomSearch.fit(X,y)
params = randomSearch.best_params_
score = randomSearch.best_score_
return params, score
clf = MLPClassifier(batch_size=256, verbose=True, early_stopping=True)
parameters_after_tuning, score_after_tuning = tuning(clf, parameters, 20, X_train_pca, y);
print(parameters_after_tuning)
print(score_after_tuning)

我尝试使用管道,但不知道如何实现它。

#Sklearn pipelines for number of principle components random search
pca1 = PCA(n_components=100, whiten=True).fit(X)
pca2 = PCA(n_components=200, whiten=True).fit(X)
pca3 = PCA(n_components=300, whiten=True).fit(X)
pca4 = PCA(n_components=400, whiten=True).fit(X)
estimators = [('pca 1', pca1), ('pca 2', pca2), ('pca 3', pca3), ('pca 4', pca4)]
pipe = Pipeline(estimators)
pipe[0]

有什么帮助吗?

我认为最有效的做法是将MLPClassifierPCA放入一个Pipeline对象中,并微调这个单一的管道。若要为管道的每个步骤定义随机搜索的参数,只需指定步骤的名称及其参数,以__(两个下划线(分隔。在您的情况下,它看起来像这样:

pipeline = Pipeline(steps=[
('pca', PCA(whiten=True)),
('clf', MLPClassifier(batch_size=256, verbose=True, early_stopping=True))
])
parameters = {
'pca__n_components': [100, 200, 300, 400],
'clf__hidden_layer_sizes': [150, 200, 250, 300, 400],
'clf__solver': ['sgd', 'adam', 'lbfgs'],
'clf__activation': ['relu', 'tanh', 'identity', 'logistics']
}

当传递给RandomizedSearchCV时,整个管道将被微调,因此返回PCAMLPClassifier的最佳参数。

parameters_after_tuning, score_after_tuning = tuning(pipeline, parameters, 20, X, y)

请注意,您不再需要将转换后的数据集X_train_pca传递给RandomizedSearchCV而是X,因为转换现在是管道的一部分。

有关如何使用Pipeline的更多信息,请参阅其文档和用户指南。

最新更新