How to insert Keras model into scikit-learn pipeline?

后端 未结 2 853
孤街浪徒
孤街浪徒 2020-12-24 06:26

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

2条回答
  •  囚心锁ツ
    2020-12-24 06:56

    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)

    Here is a full blog post with this one and many other examples: Scikit-learn Pipeline Examples

    # 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)
    

提交回复
热议问题