使用scikit管道测试模型,但仅在

2024-04-19 05:03:15 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个用于数据的管道,它进行预处理,并在最后有一个估计器。现在,如果我只想在管道的最后一步更改估计器/模型,那么在不重新对相同的数据进行预处理的情况下,如何做到这一点呢。下面是一个代码示例

pipe = make_pipeline(
    ColumnSelector(columns),
    CategoricalEncoder(categories),
    FunctionTransformer(pd.get_dummies, validate=False),
    StandardScaler(scale),
    LogisticRegression(),
)

现在我想把模型改为使用Ridge或其他模型,而不是logisticsetreaction。在不重新进行预处理的情况下,如何做到这一点?在

编辑:我可以从以下类型的管道中获取转换后的数据吗

^{pr2}$

Tags: columns数据代码模型示例make管道pipeline
1条回答
网友
1楼 · 发布于 2024-04-19 05:03:15

对于计算开销很大的变压器,可以使用caching。由于您没有提供transformer,这里是sklearn示例的一个扩展,其中使用缓存管道对两个模型进行网格搜索:

from tempfile import mkdtemp
from shutil import rmtree
from sklearn.externals.joblib import Memory
from sklearn.pipeline import Pipeline
from sklearn.decomposition import PCA
from sklearn.svm import LinearSVC
from sklearn.linear_model import ElasticNet
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import load_digits

# Create a temporary folder to store the transformers of the pipeline
cachedir = mkdtemp()
memory = Memory(cachedir=cachedir, verbose=10)

# the pipeline
pipe = Pipeline([('reduce_dim', PCA()),
                ('classify', LinearSVC())],
                memory=memory)
# models to try
param_grid = {"classify" : [LinearSVC(), ElasticNet()]}

# do the gridsearch on the models
grid = GridSearchCV(pipe, param_grid=param_grid)
digits = load_digits()
grid.fit(digits.data, digits.target)

# delete the temporary cache before exiting
rmtree(cachedir)

编辑:

当您关注问题中的模型,并且this question关注参数时,我不会认为它是完全重复的。然而,建议的解决方案与此处设置的param_网格相结合也是一个好的,甚至更好的解决方案,具体取决于您的具体问题。在

相关问题 更多 >