如何将Keras模型插入scikit-learn管道?

mac*_*ery 23 pipeline machine-learning scikit-learn hyperparameters keras

我正在使用Scikit-Learn自定义管道(sklearn.pipeline.Pipeline)和RandomizedSearchCV超参数优化.这非常有效.

现在我想插入一个Keras模型作为管道的第一步.应优化模型的参数.然后,计算(拟合)的Keras模型应该在管道中通过其他步骤使用,因此我认为我必须将模型存储为全局变量,以便其他管道步骤可以使用它.这是正确的吗?

我知道Keras为Scikit-Learn API提供了一些包装器,但问题是这些包装器已经进行了分类/回归,但我只想计算Keras模型而没有别的.

如何才能做到这一点?

例如,我有一个返回模型的方法:

def create_model(file_path, argument2,...):
    ...
    return model
Run Code Online (Sandbox Code Playgroud)

该方法需要一些固定的参数,如文件路径等,但不需要(或可以忽略)X和y.应优化模型的参数(层数等).

Fel*_*ida 13

您需要先将Keras模型包装为Scikit学习模型,然后才能正常进行.

这是一个简单的例子(我为了简洁省略了导入)

这是一篇包含许多其他示例的完整博客文章:Scikit-learn管道示例

# create a function that returns a model, taking as parameters things you
# want to verify using cross-valdiation and model selection
def create_model(optimizer='adagrad',
                 kernel_initializer='glorot_uniform', 
                 dropout=0.2):
    model = Sequential()
    model.add(Dense(64,activation='relu',kernel_initializer=kernel_initializer))
    model.add(Dropout(dropout))
    model.add(Dense(1,activation='sigmoid',kernel_initializer=kernel_initializer))

    model.compile(loss='binary_crossentropy',optimizer=optimizer, metrics=['accuracy'])

    return model

# wrap the model using the function you created
clf = KerasRegressor(build_fn=create_model,verbose=0)

# just create the pipeline
pipeline = Pipeline([
    ('clf',clf)
])

pipeline.fit(X_train, y_train)
Run Code Online (Sandbox Code Playgroud)