Skip to content

sklearn wrappers save checkpoints without required attributes #21143

New issue

Have a question about this project? No Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “No Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? No Sign in to your account

Open
giladpn opened this issue Apr 7, 2025 · 0 comments
Open

sklearn wrappers save checkpoints without required attributes #21143

giladpn opened this issue Apr 7, 2025 · 0 comments
Assignees

Comments

@giladpn
Copy link

giladpn commented Apr 7, 2025

Hi.

I am switching from the old scikeras wrappers to the newer keras.api.wrappers.SKLearnClassifier and have encountered an issue.

My workflow includes saving checkpoints:

    callbacks = None
    if saved_dir is not None and model_name is not None:
        model_path = f'./{saved_dir}/_{model_name}_model.keras'
        callbacks = [
            keras.callbacks.ModelCheckpoint(
                filepath=model_path,
                save_best_only=True,
                verbose=1 if verbose else 0,
            ),
            keras.callbacks.EarlyStopping(
                patience=patience,
                verbose=1 if verbose else 0,
            ),]

    model = keras.api.wrappers.SKLearnClassifier(model=nn_create(**kwargs),
                    fit_kwargs={'callbacks': callbacks, }
                    )

    model_with_learning_history = model.fit(
        X_train, y_train,
        validation_split=validation_split,
        epochs=epochs,
        batch_size=32,
    )

Later, I want to load one of these checkpoints, and make sure it is wrapped as a scikit-learn object. I do

    keras_native_model: keras.models.Model = keras.models.load_model(
        f'{saved_dir}/_{model_name}_model.keras'
    )
    model = keras.api.wrappers.SKLearnClassifier(keras_native_model)
    preds = model.predict(X_test)

However, the predict fails for the following reasons:

predict depends in its own code on a line raw_output = self.model_.predict(X) and on a line self._target_encoder.inverse_transform(y). But the attributes model_ and _target_encoder are set in fit() AFTER the checkpoints are saved.

I am currently setting these attributes manually to get things working. Have I missed something or is this a bug?

Thank you for the support.

No Sign up for free to join this conversation on GitHub. Already have an account? No Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants