Skip to content

Solution

This section documents the solution components of the neural_network module.

solution

Defines sklearn.neural_network solution interoperability.

This module provides functionality for interacting with scikit-learn's neural network models.

CLASS DESCRIPTION
MLPRegressorSolution

A Pydantic model representation of scikit-learn's MLPRegressor.

Variables

Loss An annotated type for handling loss values in scikit-learn models.

Loss module-attribute

Loss = Annotated[
    Any,
    BeforeValidator(lambda x: x),
    PlainSerializer(lambda x: b64encode(dumps(x))),
]

Annotated type for serialization and validation of scikit-learn loss objects.

This type encodes a pickle serialized representation of a loss object as a base64 string, to ensure that loss objects can be safely serialized and deserialized.

MLPRegressorSolution

Bases: BaseModel

MLP Regressor scikit-learn model representation.

You can import the MLPRegressorSolution class directly from neural_network:

from nextmv_sklearn.neural_network import MLPRegressorSolution

This class provides a Pydantic model representation of scikit-learn's MLPRegressor model, enabling serialization, deserialization, and conversion between model formats.

PARAMETER DESCRIPTION

loss_

The current loss computed with the loss function.

TYPE: float DEFAULT: 0.0

best_loss_

The minimum loss reached by the solver throughout fitting.

TYPE: float DEFAULT: 0.0

loss_curve_

Loss value evaluated at the end of each training step.

TYPE: list[float64]

validation_scores_

The score at each iteration on a held-out validation set.

TYPE: list[float]

best_validation_score_

The best validation score (i.e. R2 score) that triggered the early stopping.

TYPE: float

t_

The number of training samples seen by the solver during fitting.

TYPE: int DEFAULT: 0

coefs_

The ith element in the list represents the weight matrix corresponding to layer i.

TYPE: list[ndarray]

intercepts_

The ith element in the list represents the bias vector corresponding to layer i + 1.

TYPE: list[ndarray]

n_features_in_

Number of features seen during fit.

TYPE: int DEFAULT: 0

feature_names_in_

Names of features seen during fit.

TYPE: ndarray

n_iter_

The number of iterations the solver has run.

TYPE: int DEFAULT: 0

n_layers_

Number of layers.

TYPE: int DEFAULT: 0

n_outputs_

Number of outputs.

TYPE: int DEFAULT: 0

out_activation_

Name of the output activation function.

TYPE: str

Examples:

>>> from sklearn.neural_network import MLPRegressor
>>> from nextmv_sklearn.neural_network import MLPRegressorSolution
>>>
>>> # Create and train a sklearn MLPRegressor
>>> regressor = MLPRegressor(hidden_layer_sizes=(100, 50), max_iter=500)
>>> regressor.fit(X_train, y_train)
>>>
>>> # Convert to MLPRegressorSolution for serialization
>>> solution = MLPRegressorSolution.from_model(regressor)
>>> solution_dict = solution.to_dict()
>>>
>>> # Later, recreate the solution and convert back to sklearn model
>>> restored_solution = MLPRegressorSolution.from_dict(solution_dict["attributes"])
>>> restored_model = restored_solution.to_model()

best_loss_ class-attribute instance-attribute

best_loss_: float = 0.0

The minimum loss reached by the solver throughout fitting.

best_validation_score_ class-attribute instance-attribute

best_validation_score_: Optional[float] = None

The best validation score (i.e. R2 score) that triggered the early stopping.

coefs_ class-attribute instance-attribute

coefs_: list[ndarray] = None

The ith element in the list represents the weight matrix corresponding to layer i.

feature_names_in_ class-attribute instance-attribute

feature_names_in_: ndarray = None

Names of features seen during fit.

from_dict classmethod

from_dict(data: dict[str, Any]) -> MLPRegressorSolution

Creates a MLPRegressorSolution instance from a dictionary.

PARAMETER DESCRIPTION
data

Dictionary containing the model attributes.

TYPE: dict[str, Any]

RETURNS DESCRIPTION
MLPRegressorSolution

Instance of MLPRegressorSolution.

Examples:

>>> solution_dict = {"loss_": 0.15, "n_layers_": 3, "n_outputs_": 1}
>>> solution = MLPRegressorSolution.from_dict(solution_dict)
Source code in nextmv-scikit-learn/nextmv_sklearn/neural_network/solution.py
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "MLPRegressorSolution":
    """
    Creates a MLPRegressorSolution instance from a dictionary.

    Parameters
    ----------
    data : dict[str, Any]
        Dictionary containing the model attributes.

    Returns
    -------
    MLPRegressorSolution
        Instance of MLPRegressorSolution.

    Examples
    --------
    >>> solution_dict = {"loss_": 0.15, "n_layers_": 3, "n_outputs_": 1}
    >>> solution = MLPRegressorSolution.from_dict(solution_dict)
    """

    if "loss_curve_" in data:
        data["loss_curve_"] = [np.float64(val) for val in data["loss_curve_"]]

    if "coefs_" in data:
        data["coefs_"] = [np.array([np.float64(col) for col in row]) for row in data["coefs_"]]

    if "intercepts_" in data:
        data["intercepts_"] = [np.array([np.float64(col) for col in row]) for row in data["intercepts_"]]

    for key, value in cls.__annotations__.items():
        if key in data and value is ndarray:
            data[key] = np.array(data[key])

    return cls(**data)

from_model classmethod

from_model(model: MLPRegressor) -> MLPRegressorSolution

Creates a MLPRegressorSolution instance from a scikit-learn MLPRegressor model.

PARAMETER DESCRIPTION
model

scikit-learn MLPRegressor model.

TYPE: MLPRegressor

RETURNS DESCRIPTION
MLPRegressorSolution

Instance of MLPRegressorSolution.

Examples:

>>> from sklearn.neural_network import MLPRegressor
>>> regressor = MLPRegressor().fit(X, y)
>>> solution = MLPRegressorSolution.from_model(regressor)
Source code in nextmv-scikit-learn/nextmv_sklearn/neural_network/solution.py
@classmethod
def from_model(cls, model: neural_network.MLPRegressor) -> "MLPRegressorSolution":
    """
    Creates a MLPRegressorSolution instance from a scikit-learn
    MLPRegressor model.

    Parameters
    ----------
    model : MLPRegressor
        scikit-learn MLPRegressor model.

    Returns
    -------
    MLPRegressorSolution
        Instance of MLPRegressorSolution.

    Examples
    --------
    >>> from sklearn.neural_network import MLPRegressor
    >>> regressor = MLPRegressor().fit(X, y)
    >>> solution = MLPRegressorSolution.from_model(regressor)
    """

    data = {}
    for key in cls.__annotations__:
        try:
            data[key] = getattr(model, key)
        except AttributeError:
            pass

    return cls(**data)

intercepts_ class-attribute instance-attribute

intercepts_: list[ndarray] = None

The ith element in the list represents the bias vector corresponding to layer i + 1.

loss_ class-attribute instance-attribute

loss_: float = 0.0

The current loss computed with the loss function.

loss_curve_ class-attribute instance-attribute

loss_curve_: list[float64] = None

Loss value evaluated at the end of each training step.

model_config class-attribute instance-attribute

model_config = ConfigDict(arbitrary_types_allowed=True)

n_features_in_ class-attribute instance-attribute

n_features_in_: int = 0

Number of features seen during fit.

n_iter_ class-attribute instance-attribute

n_iter_: int = 0

The number of iterations the solver has run.

n_layers_ class-attribute instance-attribute

n_layers_: int = 0

Number of layers.

n_outputs_ class-attribute instance-attribute

n_outputs_: int = 0

Number of output.

out_activation_ class-attribute instance-attribute

out_activation_: str = None

Name of the output activation function.

t_ class-attribute instance-attribute

t_: int = 0

The number of training samples seen by the solver during fitting.

to_dict

to_dict() -> dict

Convert a data model instance to a dict with associated class info.

RETURNS DESCRIPTION
dict

Dictionary containing class information and model attributes.

Examples:

>>> solution = MLPRegressorSolution.from_model(regressor)
>>> solution_dict = solution.to_dict()
>>> print(solution_dict["class"]["name"])
'MLPRegressorSolution'
Source code in nextmv-scikit-learn/nextmv_sklearn/neural_network/solution.py
def to_dict(self) -> dict:
    """
    Convert a data model instance to a dict with associated class info.

    Returns
    -------
    dict
        Dictionary containing class information and model attributes.

    Examples
    --------
    >>> solution = MLPRegressorSolution.from_model(regressor)
    >>> solution_dict = solution.to_dict()
    >>> print(solution_dict["class"]["name"])
    'MLPRegressorSolution'
    """

    d = self.model_dump(mode="json", exclude_none=True, by_alias=True)

    t = type(self)
    return {
        "class": {
            "module": t.__module__,
            "name": t.__name__,
        },
        "attributes": d,
    }

to_model

to_model() -> MLPRegressor

Transforms the MLPRegressorSolution instance into a scikit-learn MLPRegressor model.

RETURNS DESCRIPTION
MLPRegressor

scikit-learn MLPRegressor model.

Examples:

>>> solution = MLPRegressorSolution.from_dict(solution_data)
>>> model = solution.to_model()
>>> predictions = model.predict(X_test)
Source code in nextmv-scikit-learn/nextmv_sklearn/neural_network/solution.py
def to_model(self) -> neural_network.MLPRegressor:
    """
    Transforms the MLPRegressorSolution instance into a scikit-learn
    MLPRegressor model.

    Returns
    -------
    MLPRegressor
        scikit-learn MLPRegressor model.

    Examples
    --------
    >>> solution = MLPRegressorSolution.from_dict(solution_data)
    >>> model = solution.to_model()
    >>> predictions = model.predict(X_test)
    """

    m = neural_network.MLPRegressor()
    for key in self.model_fields:
        setattr(m, key, self.__dict__[key])

    return m

validation_scores_ class-attribute instance-attribute

validation_scores_: Optional[list[float]] = None

The score at each iteration on a held-out validation set.