Replicate MLPClassifier() of sklearn in keras

后端 未结 1 1392
梦毁少年i
梦毁少年i 2021-02-06 13:12

I am new to keras. I was attempting an ML problem. About the data:

It has 5 input features, 4 output classes and about 26000 records.

I had first attempted it us

相关标签:
1条回答
  • 2021-02-06 13:50

    To get a bona fide scikit estimator you can use KerasClassifier from tensorflow.keras.wrappers.scikit_learn. For example:

    from sklearn.datasets import make_classification
    from tensorflow import keras
    from tensorflow.keras.layers import Dense
    from tensorflow.keras.models import Sequential
    from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
    
    
    X, y = make_classification(
        n_samples=26000, n_features=5, n_classes=4, n_informative=3, random_state=0
    )
    
    
    def build_fn(optimizer):
        model = Sequential()
        model.add(
            Dense(200, input_dim=5, kernel_initializer="he_normal", activation="relu")
        )
        model.add(Dense(100, kernel_initializer="he_normal", activation="relu"))
        model.add(Dense(100, kernel_initializer="he_normal", activation="relu"))
        model.add(Dense(100, kernel_initializer="he_normal", activation="relu"))
        model.add(Dense(4, kernel_initializer="he_normal", activation="softmax"))
        model.compile(
            loss="categorical_crossentropy",
            optimizer=optimizer,
            metrics=[
                keras.metrics.Precision(name="precision"),
                keras.metrics.Recall(name="recall"),
                keras.metrics.AUC(name="auc"),
            ],
        )
        return model
    
    
    clf = KerasClassifier(build_fn, optimizer="rmsprop", epochs=500, batch_size=300)
    clf.fit(X, y)
    clf.predict(X)
    
    
    0 讨论(0)
提交回复
热议问题