SciKeras: Scikit-Learn API wrapper for Keras

repository·master·Indexed 42 days ago

https://github.com/adriangb/scikeras

SciKeras provides Scikit-Learn compatible wrappers for Keras models, allowing neural networks to be used within the Scikit-Learn ecosystem in Pipelines and GridSearchCV. Version 0.13.0 includes KerasClassifier, KerasRegressor, and BaseWrapper, featuring automatic target encoding, model compilation, and a parameter routing system (e.g., model__, fit__, optimizer__) for hyperparameter tuning. It serves as an API-compatible replacement for the deprecated tf.keras.wrappers.scikit_learn.

Tokens
21.9K
Snippets
60
Records
80
Agent score
51%

What's inside SciKeras

  1. What is SciKeras?

    master

    SciKeras is a Scikit-Learn wrapper for Keras/TensorFlow. It provides a Keras-based model with a standard Scikit-Learn interface, allowing you to use Keras models within Scikit-Learn workflows (such as GridSearchCV, Pipeline, or cross_val_score).

    It is designed to be the successor to the deprecated keras.wrappers.scikit_learn and offers significant improvements over the original TensorFlow implementation. If you are already familiar with both Scikit-Learn and Keras, SciKeras follows their standard syntax and mental models without requiring you to learn new concepts.

  2. Accessing training history in SciKeras

    master

    In the original TensorFlow wrappers, fit() returned a Keras History object. To comply with the Scikit-Learn API, SciKeras's fit() method returns the estimator instance (self) instead.

    To access training logs, use the history_ attribute on the fitted estimator. Note that SciKeras normalizes metric names (e.g., "mae" becomes "mean_absolute_error").

    • fit(): Resets the history_ attribute.
    • partial_fit(): Extends the history_ attribute.
       def get_model():
          ...
          model.compile(loss="mse", metrics=["mae"])
          return model
    
       clf = KerasClassifier(get_model)
    -  hist = clf.fit(...).history
    -  losses = hist["mae"]
    +  hist = clf.fit(...).history_
    +  losses = hist["mean_absolute_error"]
  3. Use sparse inputs with SciKeras

    master

    SciKeras natively supports sparse inputs for features (X). You do not need to perform any special configuration or transformations to enable sparse support; you can simply pass a sparse matrix (e.g., from scipy.sparse) directly to the .fit() method of a SciKeras wrapper like KerasRegressor or KerasClassifier.

    Using sparse inputs is particularly effective when dealing with high-cardinality categorical features that have been one-hot encoded, as it significantly reduces peak memory consumption compared to dense representations.

    from scikeras.wrappers import KerasRegressor
    # Assuming X is a scipy sparse matrix
    model = KerasRegressor(model=get_clf, loss='mse', epochs=5)
    model.fit(X, y)
  4. Initialize SciKeras wrappers

    master

    When you instantiate KerasClassifier or KerasRegressor, arguments are stored unmodified and the model remains uninstantiated. This allows for safe cloning (e.g., in GridSearchCV).

    Attributes are only initialized when .fit() or .initialize() is called. Following Scikit-Learn convention, initialized attributes end with an underscore (e.g., model_).

  5. Compatibility with TensorFlow Datasets

    master

    SciKeras does not support tf.data.Dataset objects directly.

    This limitation exists because SciKeras adheres strictly to the Scikit-Learn API, and Scikit-Learn's API is designed for in-memory data structures (like NumPy arrays or SciPy sparse matrices) rather than the lazy-evaluation model used by TensorFlow Datasets.

    If your workflow requires the performance and scalability of tf.data.Dataset, you should use TensorFlow/Keras directly instead of using the SciKeras wrappers.

  6. Tune parameters using special prefixes in GridSearchCV

    master

    SciKeras supports parameter routing via special prefixes, allowing you to access and tune deeply nested parameters within sklearn tools like GridSearchCV or Pipeline. This follows the same logic as sklearn Pipelines.

    Available Prefixes

    • model__: Used to specify parameters destined for the model callable passed to the wrapper (e.g., get_clf or get_reg). Use this for architecture settings like model__hidden_layer_sizes or model__dropout.
    • optimizer__: Used to access parameters of the optimizer (e.g., optimizer__learning_rate).
    • fit__: Used to route parameters specifically to the fit method (e.g., fit__callbacks).
    • predict__: Used to route parameters specifically to the predict method.
    • Pipeline Nesting: If the KerasClassifier or KerasRegressor is inside an sklearn.pipeline.Pipeline, prefix the parameter with the name of the estimator in the pipeline (e.g., clf__model__hidden_layer_sizes).
    # Example of parameter routing in a KerasClassifier
    clf = KerasClassifier(
        model=get_clf,
        optimizer__learning_rate=0.1,
        model__hidden_layer_sizes=(100,),
        model__dropout=0.5
    )
  7. How SciKeras data transformers work

    master

    SciKeras uses a data transformer interface to reconcile scikit-learn's expected data formats (2D arrays for X, 1D arrays for y) with Keras's ability to handle multiple inputs, multiple outputs, and higher-dimensional tensors.

    This is achieved via two scikit-learn transformers:

    1. feature_encoder: Transforms the input features (X).
    2. target_encoder: Transforms the target labels/values (y).

    During the fit lifecycle, SciKeras calls fit_transform on both encoders before passing the data to the Keras model. During predict, it applies transform to X and inverse_transform to the model's predictions to return data in the original scikit-learn format.

  8. Use Scikit-Learn style parameter routing in SciKeras

    master

    SciKeras supports parameter routing to override parameters for specific consumers (methods or class initializers). This allows you to pass parameters directly to the underlying Keras components or methods using special prefixes. All routed parameters are compatible with hyperparameter tuning (e.g., via RandomizedSearchCV), whereas passing pre-instantiated Keras objects prevents tuning of their internal parameters.

    Available Routing Prefixes

    PrefixTarget Consumer
    model__Passed to model_build_fn (or the model parameter)
    fit__Passed to keras.Model.fit
    predict__Passed to keras.Model.predict (also used by .score())
    callbacks__Used to instantiate callbacks
    optimizer__Used to instantiate optimizers
    loss__Used to instantiate losses
    metrics__Used to instantiate metrics
    score__Passed to the scoring function (scikeras.wrappers.BaseWrapper.scorer)

    Example: Routing to fit and predict

    clf = KerasClassifier(..., fit__batch_size=32, predict__batch_size=10000)
  9. Use the `meta` parameter to dynamically size Keras models

    master

    When defining a model building function for KerasClassifier or KerasRegressor, you can include a meta parameter. SciKeras automatically injects a dictionary containing metadata discovered during the fit call.

    Commonly used keys in meta include:

    • n_features_in_: The number of input features (useful for defining the Input layer shape).
    • n_classes_: The number of classes (useful for defining the output layer size in classification).
    • target_type_: The type of task (e.g., 'binary' or 'multiclass').

    Example of using meta to define input shape:

    from typing import Dict, Any
    import keras
    
    def get_clf_model(meta: Dict[str, Any]):
        model = keras.Sequential()
        # Use n_features_in_ from meta to size the input layer
        inp = keras.layers.Input(shape=(meta["n_features_in_"],))
        model.add(inp)
        return model
    from typing import Dict, Any
    import keras
    
    def get_clf_model(meta: Dict[str, Any]):
        model = keras.Sequential()
        inp = keras.layers.Input(shape=(meta["n_features_in_"],))
        model.add(inp)
        return model
  10. How SciKeras wrappers work

    master

    SciKeras provides three main wrapper classes: KerasClassifier, KerasRegressor, and BaseWrapper. BaseWrapper provides general Keras wrapping functionality, while the other two extend it for classification and regression tasks respectively.

    To use them, you define your Keras model architecture within a callable function (often called model_build_fn) and pass this function to the wrapper via the model parameter. This allows you to use Keras models within the Scikit-Learn ecosystem, enabling compatibility with tools like GridSearchCV.

    Key features include:

    • Wrapping keras.Model in an sklearn-compatible interface.
    • Automatic encoding/decoding of the target y.
    • Automatic compilation of the model (unless handled manually).
    • Making Keras objects serializable for sklearn model selection.
    def model_build_fn():
         model = Model(...)
         ...
         return model
    
    clf = KerasClassifier(model=model_build_fn)
    clf.fit(X, y)
    y_pred = clf.predict(X_valid)