如何将Keras模型插入scikit-learn管道? [英] How to insert Keras model into scikit-learn pipeline?

查看:89
本文介绍了如何将Keras模型插入scikit-learn管道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Scikit-Learn自定义管道(sklearn.pipeline.Pipeline)与RandomizedSearchCV结合使用以进行超参数优化.效果很好.

I'm using a Scikit-Learn custom pipeline (sklearn.pipeline.Pipeline) in conjunction with RandomizedSearchCV for hyper-parameter optimization. This works great.

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

Now I would like to insert a Keras model as a first step into the pipeline. Parameters of the model should be optimized. The computed (fitted) Keras model should then be used later on in the pipeline by other steps, so I think I have to store the model as a global variable so that the other pipeline steps can use it. Is this right?

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

I know that Keras offers some wrappers for the Scikit-Learn API but the problem is that these wrappers already do classification / regression but I only want to compute the Keras model and nothing else.

这怎么办?

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

For example I have a method which returns the model:

def create_model(file_path, argument2,...):
    ...
    return model

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

The method needs some fixed parameters like a file path etc. but X and y is not needed (or can be ignored). The parameters of the model should be optimized (number of layers etc.).

推荐答案

您需要先将Keras模型包装为Scikit学习模型,然后按常规进行操作.

You need to wrap your Keras model as a Scikit learn model first, and then just proceed as normal.

这是一个简单的示例(为简洁起见,我省略了导入)

Here's a quick example (I've omitted the imports for brevity)

这里是完整的博客文章,其中包含一个示例以及其他示例: 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)

这篇关于如何将Keras模型插入scikit-learn管道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆