注意
转到末尾 下载完整的示例代码或通过 JupyterLite 或 Binder 在浏览器中运行此示例。
使用 Pipeline 和 GridSearchCV 选择降维方法#
此示例构建了一个管道,用于执行降维,然后使用支持向量分类器进行预测。它演示了如何使用 GridSearchCV 和 Pipeline 在单个 CV 运行中优化不同类型的估计器——在网格搜索期间比较了无监督的 PCA 和 NMF 降维方法与单变量特征选择方法。
此外,可以使用 memory 参数实例化 Pipeline,以记忆管道中的转换器,避免一遍又一遍地拟合相同的转换器。
请注意,当转换器的拟合成本很高时,使用 memory 来启用缓存会变得很有用。
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
对 Pipeline 和 GridSearchCV 的说明#
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import NMF, PCA
from sklearn.feature_selection import SelectKBest, mutual_info_classif
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler
from sklearn.svm import LinearSVC
X, y = load_digits(return_X_y=True)
pipe = Pipeline(
[
("scaling", MinMaxScaler()),
# the reduce_dim stage is populated by the param_grid
("reduce_dim", "passthrough"),
("classify", LinearSVC(dual=False, max_iter=10000)),
]
)
N_FEATURES_OPTIONS = [2, 4, 8]
C_OPTIONS = [1, 10, 100, 1000]
param_grid = [
{
"reduce_dim": [PCA(iterated_power=7), NMF(max_iter=1_000)],
"reduce_dim__n_components": N_FEATURES_OPTIONS,
"classify__C": C_OPTIONS,
},
{
"reduce_dim": [SelectKBest(mutual_info_classif)],
"reduce_dim__k": N_FEATURES_OPTIONS,
"classify__C": C_OPTIONS,
},
]
reducer_labels = ["PCA", "NMF", "KBest(mutual_info_classif)"]
grid = GridSearchCV(pipe, n_jobs=1, param_grid=param_grid)
grid.fit(X, y)
在 Pipeline 中缓存转换器#
有时值得存储特定转换器的状态,因为它可以再次使用。在 GridSearchCV 中使用管道会触发这种情况。因此,我们使用参数 memory 来启用缓存。
警告
请注意,此示例只是一个说明,因为对于这个特定情况,拟合 PCA 不一定比加载缓存慢。因此,当转换器的拟合成本很高时,才使用 memory 构造函数参数。
from shutil import rmtree
from joblib import Memory
# Create a temporary folder to store the transformers of the pipeline
location = "cachedir"
memory = Memory(location=location, verbose=10)
cached_pipe = Pipeline(
[("reduce_dim", PCA()), ("classify", LinearSVC(dual=False, max_iter=10000))],
memory=memory,
)
# This time, a cached pipeline will be used within the grid search
# Delete the temporary cache before exiting
memory.clear(warn=False)
rmtree(location)
PCA 拟合仅在评估 LinearSVC 分类器的 C 参数的第一个配置时计算。其他 C 配置将触发加载缓存的 PCA 估计器数据,从而节省处理时间。因此,当拟合转换器成本很高时,使用 memory 缓存管道非常有益。
脚本总运行时间: (0 minutes 42.909 seconds)
相关示例
