Skip to content

Utils Reference

Model persistence (save_model, load_model) and the synthetic dataset helper used throughout the tutorials (make_donor_dataset).

philanthropy.utils

Generic helpers: model persistence and deprecated aliases.

save_model(model, path, *, features=None, target=None)

Persist model to path as a PhilanthroPy bundle.

Parameters:

Name Type Description Default
model fitted estimator

Any PhilanthroPy or scikit-learn estimator.

required
path str or Path

Output path (.joblib by convention).

required
features list of str

Ordered feature-column names the model was trained on.

None
target str

Name of the target column.

None

Returns:

Type Description
path

The path it was written to (for chaining).

Source code in philanthropy/utils/_persistence.py
def save_model(
    model: Any,
    path: PathLike,
    *,
    features: Optional[Sequence[str]] = None,
    target: Optional[str] = None,
) -> PathLike:
    """Persist ``model`` to ``path`` as a PhilanthroPy bundle.

    Parameters
    ----------
    model : fitted estimator
        Any PhilanthroPy or scikit-learn estimator.
    path : str or pathlib.Path
        Output path (``.joblib`` by convention).
    features : list of str, optional
        Ordered feature-column names the model was trained on.
    target : str, optional
        Name of the target column.

    Returns
    -------
    path
        The ``path`` it was written to (for chaining).
    """
    import sklearn

    bundle = {
        "model": model,
        "features": features,
        "target": target,
        "philanthropy_version": __version__,
        "sklearn_version": sklearn.__version__,
    }
    joblib.dump(bundle, path)
    return path

load_model(path)

Load a bundle written by :func:save_model.

Warns (does not raise) when the stored PhilanthroPy or scikit-learn version differs from the running environment, since an estimator un-pickled under a different scikit-learn can silently misbehave.

Parameters:

Name Type Description Default
path str or Path

Bundle path.

required

Returns:

Type Description
dict

The bundle: {"model", "features", "target", "philanthropy_version", "sklearn_version"}.

Raises:

Type Description
ValueError

If the file is not a PhilanthroPy bundle.

Source code in philanthropy/utils/_persistence.py
def load_model(path: PathLike) -> Dict[str, Any]:
    """Load a bundle written by :func:`save_model`.

    Warns (does not raise) when the stored PhilanthroPy or scikit-learn version
    differs from the running environment, since an estimator un-pickled under a
    different scikit-learn can silently misbehave.

    Parameters
    ----------
    path : str or pathlib.Path
        Bundle path.

    Returns
    -------
    dict
        The bundle: ``{"model", "features", "target", "philanthropy_version",
        "sklearn_version"}``.

    Raises
    ------
    ValueError
        If the file is not a PhilanthroPy bundle.
    """
    bundle = joblib.load(path)
    if not isinstance(bundle, dict) or "model" not in bundle:
        raise ValueError(f"{path} is not a PhilanthroPy model bundle.")
    _warn_on_version_mismatch(bundle)
    return bundle

make_donor_dataset(*args, **kwargs)

Deprecated alias for :func:philanthropy.datasets.make_donor_dataset.

Source code in philanthropy/utils/__init__.py
def make_donor_dataset(*args: Any, **kwargs: Any) -> pd.DataFrame:
    """Deprecated alias for :func:`philanthropy.datasets.make_donor_dataset`."""
    warnings.warn(
        "philanthropy.utils.make_donor_dataset is deprecated and will be "
        "removed in 0.8.0; import make_donor_dataset from philanthropy.datasets "
        "instead.",
        DeprecationWarning,
        stacklevel=2,
    )
    from ..datasets import make_donor_dataset as _make_donor_dataset

    return _make_donor_dataset(*args, **kwargs)