Python keras.wrappers.scikit_learn.KerasClassifier() Examples

The following are 30 code examples of keras.wrappers.scikit_learn.KerasClassifier(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module keras.wrappers.scikit_learn , or try the search function .
Example #1
def load_pipeline_keras() -> Pipeline:
    """Load a Keras Pipeline from disk."""

    dataset = joblib.load(config.PIPELINE_PATH)

    build_model = lambda: load_model(config.MODEL_PATH)

    classifier = KerasClassifier(build_fn=build_model,
                                 batch_size=config.BATCH_SIZE,
                                 validation_split=10,
                                 epochs=config.EPOCHS,
                                 verbose=2,
                                 callbacks=m.callbacks_list,
                                 # image_size = config.IMAGE_SIZE
                                 )

    classifier.classes_ = joblib.load(config.CLASSES_PATH)
    classifier.model = build_model()

    return Pipeline([
        ('dataset', dataset),
        ('cnn_model', classifier)
    ]) 
Example #2
Source Project: modAL   Author: modAL-python   File: keras_integration.py    License: MIT License 7 votes vote down vote up
def create_keras_model():
    """
    This function compiles and returns a Keras model.
    Should be passed to KerasClassifier in the Keras scikit-learn API.
    """

    model = Sequential()
    model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)))
    model.add(Conv2D(64, (3, 3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.25))
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(10, activation='softmax'))

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

    return model


# create the classifier 
Example #3
Source Project: hyperparameter_hunter   Author: HunterMcGushion   File: mnist_example.py    License: MIT License 6 votes vote down vote up
def execute():
    train_df, holdout_df = prep_data()

    env = Environment(
        train_dataset=train_df,
        results_path="HyperparameterHunterAssets",
        metrics=["roc_auc_score"],
        target_column=[f"target_{_}" for _ in range(10)],  # 10 classes (one-hot-encoded output)
        holdout_dataset=holdout_df,
        cv_type="StratifiedKFold",
        cv_params=dict(n_splits=3, shuffle=True, random_state=True),
    )

    exp = CVExperiment(KerasClassifier, build_fn_exp, dict(batch_size=64, epochs=10, verbose=1))

    opt = BayesianOptPro(iterations=10, random_state=32)
    opt.forge_experiment(KerasClassifier, build_fn_opt, dict(batch_size=64, epochs=10, verbose=0))
    opt.go() 
Example #4
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_build_fn():
    clf = KerasClassifier(
        build_fn=build_fn_clf, hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #5
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_class_build_fn():
    class ClassBuildFnClf(object):

        def __call__(self, hidden_dims):
            return build_fn_clf(hidden_dims)

    clf = KerasClassifier(
        build_fn=ClassBuildFnClf(), hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #6
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_inherit_class_build_fn():
    class InheritClassBuildFnClf(KerasClassifier):

        def __call__(self, hidden_dims):
            return build_fn_clf(hidden_dims)

    clf = InheritClassBuildFnClf(
        build_fn=None, hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #7
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_build_fn():
    clf = KerasClassifier(
        build_fn=build_fn_clf, hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #8
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_class_build_fn():
    class ClassBuildFnClf(object):

        def __call__(self, hidden_dims):
            return build_fn_clf(hidden_dims)

    clf = KerasClassifier(
        build_fn=ClassBuildFnClf(), hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #9
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_build_fn():
    clf = KerasClassifier(
        build_fn=build_fn_clf, hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #10
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_class_build_fn():
    class ClassBuildFnClf(object):

        def __call__(self, hidden_dims):
            return build_fn_clf(hidden_dims)

    clf = KerasClassifier(
        build_fn=ClassBuildFnClf(), hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #11
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_inherit_class_build_fn():
    class InheritClassBuildFnClf(KerasClassifier):

        def __call__(self, hidden_dims):
            return build_fn_clf(hidden_dims)

    clf = InheritClassBuildFnClf(
        build_fn=None, hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #12
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_build_fn():
    clf = KerasClassifier(
        build_fn=build_fn_clf, hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #13
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_class_build_fn():
    class ClassBuildFnClf(object):

        def __call__(self, hidden_dims):
            return build_fn_clf(hidden_dims)

    clf = KerasClassifier(
        build_fn=ClassBuildFnClf(), hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #14
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_build_fn():
    clf = KerasClassifier(
        build_fn=build_fn_clf, hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #15
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_class_build_fn():
    class ClassBuildFnClf(object):

        def __call__(self, hidden_dims):
            return build_fn_clf(hidden_dims)

    clf = KerasClassifier(
        build_fn=ClassBuildFnClf(), hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #16
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_inherit_class_build_fn():
    class InheritClassBuildFnClf(KerasClassifier):

        def __call__(self, hidden_dims):
            return build_fn_clf(hidden_dims)

    clf = InheritClassBuildFnClf(
        build_fn=None, hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #17
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_build_fn():
    clf = KerasClassifier(
        build_fn=build_fn_clf, hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #18
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_class_build_fn():
    class ClassBuildFnClf(object):

        def __call__(self, hidden_dims):
            return build_fn_clf(hidden_dims)

    clf = KerasClassifier(
        build_fn=ClassBuildFnClf(), hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #19
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_build_fn():
    clf = KerasClassifier(
        build_fn=build_fn_clf, hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #20
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_class_build_fn():
    class ClassBuildFnClf(object):

        def __call__(self, hidden_dims):
            return build_fn_clf(hidden_dims)

    clf = KerasClassifier(
        build_fn=ClassBuildFnClf(), hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #21
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_inherit_class_build_fn():
    class InheritClassBuildFnClf(KerasClassifier):

        def __call__(self, hidden_dims):
            return build_fn_clf(hidden_dims)

    clf = InheritClassBuildFnClf(
        build_fn=None, hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #22
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_build_fn():
    clf = KerasClassifier(
        build_fn=build_fn_clf, hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #23
Source Project: DeepLearning_Wavelet-LSTM   Author: hello-sea   File: scikit_learn_test.py    License: MIT License 5 votes vote down vote up
def test_classify_class_build_fn():
    class ClassBuildFnClf(object):

        def __call__(self, hidden_dims):
            return build_fn_clf(hidden_dims)

    clf = KerasClassifier(
        build_fn=ClassBuildFnClf(), hidden_dims=hidden_dims,
        batch_size=batch_size, epochs=epochs)

    assert_classification_works(clf)
    assert_string_classification_works(clf) 
Example #24
Source Project: palladium   Author: ottogroup   File: model.py    License: Apache License 2.0 5 votes vote down vote up
def make_pipeline(**kw):
    # In the case of this Iris dataset, our targets are string labels,
    # and KerasClassifier doesn't like that.  So we transform the
    # targets into a one-hot encoding instead using PipeLineY.
    return PipelineY([
            ('clf', KerasClassifier(build_fn=keras_model, **kw)),
        ],
        y_transformer=LabelBinarizer(),
        predict_use_inverse=False,
        ) 
Example #25
Source Project: hyperparameter_hunter   Author: HunterMcGushion   File: multi_classification_example.py    License: MIT License 5 votes vote down vote up
def _execute():
    env = Environment(
        train_dataset=prep_data(),
        results_path="HyperparameterHunterAssets",
        metrics=["roc_auc_score"],
        target_column=[f"target_{_}" for _ in range(10)],
        cv_type="StratifiedKFold",
        cv_params=dict(n_splits=10, shuffle=True, random_state=True),
    )

    experiment = CVExperiment(
        model_initializer=KerasClassifier,
        model_init_params=build_fn,
        model_extra_params=dict(batch_size=32, epochs=10, verbose=0, shuffle=True),
    ) 
Example #26
Source Project: hyperparameter_hunter   Author: HunterMcGushion   File: experiment_example.py    License: MIT License 5 votes vote down vote up
def execute():
    env = Environment(
        train_dataset=get_breast_cancer_data(),
        results_path="HyperparameterHunterAssets",
        target_column="diagnosis",
        metrics=["roc_auc_score"],
        cv_type="StratifiedKFold",
        cv_params=dict(n_splits=5, shuffle=True, random_state=32),
    )

    experiment = CVExperiment(
        model_initializer=KerasClassifier,
        model_init_params=build_fn,
        model_extra_params=dict(
            callbacks=[
                ModelCheckpoint(
                    filepath=os.path.abspath("foo_checkpoint"), save_best_only=True, verbose=1
                ),
                ReduceLROnPlateau(patience=5),
            ],
            batch_size=32,
            epochs=10,
            verbose=0,
            shuffle=True,
        ),
    ) 
Example #27
Source Project: hyperparameter_hunter   Author: HunterMcGushion   File: image_classification_example.py    License: MIT License 5 votes vote down vote up
def _execute():
    env = Environment(
        train_dataset=prep_data(),
        results_path="HyperparameterHunterAssets",
        metrics=["roc_auc_score"],
        cv_type="StratifiedKFold",
        cv_params=dict(n_splits=3, shuffle=True, random_state=True),
    )

    experiment = CVExperiment(
        model_initializer=KerasClassifier,
        model_init_params=build_fn,
        model_extra_params=dict(batch_size=32, epochs=3, verbose=0, shuffle=True),
    ) 
Example #28
Source Project: hyperparameter_hunter   Author: HunterMcGushion   File: optimization_example.py    License: MIT License 5 votes vote down vote up
def _execute():
    #################### Environment ####################
    env = Environment(
        train_dataset=get_breast_cancer_data(target="target"),
        results_path="HyperparameterHunterAssets",
        metrics=["roc_auc_score"],
        cv_type="StratifiedKFold",
        cv_params=dict(n_splits=5, shuffle=True, random_state=32),
    )

    #################### Experimentation ####################
    experiment = CVExperiment(
        model_initializer=KerasClassifier,
        model_init_params=dict(build_fn=_build_fn_experiment),
        model_extra_params=dict(
            callbacks=[ReduceLROnPlateau(patience=5)], batch_size=32, epochs=10, verbose=0
        ),
    )

    #################### Optimization ####################
    optimizer = BayesianOptPro(iterations=10)
    optimizer.forge_experiment(
        model_initializer=KerasClassifier,
        model_init_params=dict(build_fn=_build_fn_optimization),
        model_extra_params=dict(
            callbacks=[ReduceLROnPlateau(patience=Integer(5, 10))],
            batch_size=Categorical([32, 64], transform="onehot"),
            epochs=10,
            verbose=0,
        ),
    )
    optimizer.go() 
Example #29
Source Project: hyperparameter_hunter   Author: HunterMcGushion   File: test_keras.py    License: MIT License 5 votes vote down vote up
def run_initialization_matching_optimization_0(build_fn):
    optimizer = DummyOptPro(iterations=1)
    optimizer.forge_experiment(
        model_initializer=KerasClassifier,
        model_init_params=dict(build_fn=build_fn),
        model_extra_params=dict(epochs=1, batch_size=128, verbose=0),
    )
    optimizer.go()
    return optimizer


#################### `glorot_normal` (`VarianceScaling`) #################### 
Example #30
Source Project: scikit-multilearn   Author: scikit-multilearn   File: keras.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def fit(self, X, y):
        if self.multi_class:
            self.n_classes_ = len(set(y))
        else:
            self.n_classes_ = 1

        build_callable = lambda: self.build_function(X.shape[1], self.n_classes_)
        keras_params=copy(self.keras_params)
        keras_params['build_fn']=build_callable

        self.classifier_ = KerasClassifier(**keras_params)
        self.classifier_.fit(X, y)