|
| 1 | +# ruff: noqa |
| 2 | +""" |
| 3 | +======================================= |
| 4 | +Release Highlights for scikit-learn 1.4 |
| 5 | +======================================= |
| 6 | +
|
| 7 | +.. currentmodule:: sklearn |
| 8 | +
|
| 9 | +We are pleased to announce the release of scikit-learn 1.4! Many bug fixes |
| 10 | +and improvements were added, as well as some new key features. We detail |
| 11 | +below a few of the major features of this release. **For an exhaustive list of |
| 12 | +all the changes**, please refer to the :ref:`release notes <changes_1_4>`. |
| 13 | +
|
| 14 | +To install the latest version (with pip):: |
| 15 | +
|
| 16 | + pip install --upgrade scikit-learn |
| 17 | +
|
| 18 | +or with conda:: |
| 19 | +
|
| 20 | + conda install -c conda-forge scikit-learn |
| 21 | +
|
| 22 | +""" |
| 23 | + |
| 24 | +# %% |
| 25 | +# HistGradientBoosting Natively Supports Categorical DTypes in DataFrames |
| 26 | +# ----------------------------------------------------------------------- |
| 27 | +# :class:`ensemble.HistGradientBoostingClassifier` and |
| 28 | +# :class:`ensemble.HistGradientBoostingRegressor` now directly supports dataframes with |
| 29 | +# categorical features. Here we have a dataset with a mixture of |
| 30 | +# categorical and numerical features: |
| 31 | +from sklearn.datasets import fetch_openml |
| 32 | + |
| 33 | +X_adult, y_adult = fetch_openml("adult", version=2, return_X_y=True) |
| 34 | + |
| 35 | +# Remove redundant and non-feature columns |
| 36 | +X_adult = X_adult.drop(["education-num", "fnlwgt"], axis="columns") |
| 37 | +X_adult.dtypes |
| 38 | + |
| 39 | +# %% |
| 40 | +# By setting `categorical_features="from_dtype"`, the gradient boosting classifier |
| 41 | +# treats the columns with categorical dtypes as categorical features in the |
| 42 | +# algorithm: |
| 43 | +from sklearn.ensemble import HistGradientBoostingClassifier |
| 44 | +from sklearn.model_selection import train_test_split |
| 45 | +from sklearn.metrics import roc_auc_score |
| 46 | + |
| 47 | +X_train, X_test, y_train, y_test = train_test_split(X_adult, y_adult, random_state=0) |
| 48 | +hist = HistGradientBoostingClassifier(categorical_features="from_dtype") |
| 49 | + |
| 50 | +hist.fit(X_train, y_train) |
| 51 | +y_decision = hist.decision_function(X_test) |
| 52 | +print(f"ROC AUC score is {roc_auc_score(y_test, y_decision)}") |
| 53 | + |
| 54 | +# %% |
| 55 | +# Polars output in `set_output` |
| 56 | +# ----------------------------- |
| 57 | +# scikit-learn's transformers now support polars output with the `set_output` API. |
| 58 | +import polars as pl |
| 59 | +from sklearn.preprocessing import StandardScaler |
| 60 | +from sklearn.preprocessing import OneHotEncoder |
| 61 | +from sklearn.compose import ColumnTransformer |
| 62 | + |
| 63 | +df = pl.DataFrame( |
| 64 | + {"height": [120, 140, 150, 110, 100], "pet": ["dog", "cat", "dog", "cat", "cat"]} |
| 65 | +) |
| 66 | +preprocessor = ColumnTransformer( |
| 67 | + [ |
| 68 | + ("numerical", StandardScaler(), ["height"]), |
| 69 | + ("categorical", OneHotEncoder(sparse_output=False), ["pet"]), |
| 70 | + ], |
| 71 | + verbose_feature_names_out=False, |
| 72 | +) |
| 73 | +preprocessor.set_output(transform="polars") |
| 74 | + |
| 75 | +df_out = preprocessor.fit_transform(df) |
| 76 | +print(f"Output type: {type(df_out)}") |
| 77 | + |
| 78 | +# %% |
| 79 | +# Missing value support for Random Forest |
| 80 | +# --------------------------------------- |
| 81 | +# The classes :class:`ensemble.RandomForestClassifier` and |
| 82 | +# :class:`ensemble.RandomForestRegressor` now support missing values. When training |
| 83 | +# every individual tree, the splitter evaluates each potential threshold with the |
| 84 | +# missing values going to the left and right nodes. More details in the |
| 85 | +# :ref:`User Guide <tree_missing_value_support>`. |
| 86 | +import numpy as np |
| 87 | +from sklearn.ensemble import RandomForestClassifier |
| 88 | + |
| 89 | +X = np.array([0, 1, 6, np.nan]).reshape(-1, 1) |
| 90 | +y = [0, 0, 1, 1] |
| 91 | + |
| 92 | +forest = RandomForestClassifier(random_state=0).fit(X, y) |
| 93 | +forest.predict(X) |
| 94 | + |
| 95 | +# %% |
| 96 | +# Add support for monotonic constraints in tree-based models |
| 97 | +# ---------------------------------------------------------- |
| 98 | +# While we added support for monotonic constraints in histogram-based gradient boosting |
| 99 | +# in scikit-learn 0.23, we now support this feature for all other tree-based models as |
| 100 | +# trees, random forests, extra-trees, and exact gradient boosting. Here, we show this |
| 101 | +# feature for random forest on a regression problem. |
| 102 | +import matplotlib.pyplot as plt |
| 103 | +from sklearn.inspection import PartialDependenceDisplay |
| 104 | +from sklearn.ensemble import RandomForestRegressor |
| 105 | + |
| 106 | +n_samples = 500 |
| 107 | +rng = np.random.RandomState(0) |
| 108 | +X = rng.randn(n_samples, 2) |
| 109 | +noise = rng.normal(loc=0.0, scale=0.01, size=n_samples) |
| 110 | +y = 5 * X[:, 0] + np.sin(10 * np.pi * X[:, 0]) - noise |
| 111 | + |
| 112 | +rf_no_cst = RandomForestRegressor().fit(X, y) |
| 113 | +rf_cst = RandomForestRegressor(monotonic_cst=[1, 0]).fit(X, y) |
| 114 | + |
| 115 | +disp = PartialDependenceDisplay.from_estimator( |
| 116 | + rf_no_cst, |
| 117 | + X, |
| 118 | + features=[0], |
| 119 | + feature_names=["feature 0"], |
| 120 | + line_kw={"linewidth": 4, "label": "unconstrained", "color": "tab:blue"}, |
| 121 | +) |
| 122 | +PartialDependenceDisplay.from_estimator( |
| 123 | + rf_cst, |
| 124 | + X, |
| 125 | + features=[0], |
| 126 | + line_kw={"linewidth": 4, "label": "constrained", "color": "tab:orange"}, |
| 127 | + ax=disp.axes_, |
| 128 | +) |
| 129 | +disp.axes_[0, 0].plot( |
| 130 | + X[:, 0], y, "o", alpha=0.5, zorder=-1, label="samples", color="tab:green" |
| 131 | +) |
| 132 | +disp.axes_[0, 0].set_ylim(-3, 3) |
| 133 | +disp.axes_[0, 0].set_xlim(-1, 1) |
| 134 | +disp.axes_[0, 0].legend() |
| 135 | +plt.show() |
| 136 | + |
| 137 | +# %% |
| 138 | +# Enriched estimator displays |
| 139 | +# --------------------------- |
| 140 | +# Estimators displays have been enriched: if we look at `forest`, defined above: |
| 141 | +forest |
| 142 | + |
| 143 | +# %% |
| 144 | +# One can access the documentation of the estimator by clicking on the icon "?" on |
| 145 | +# the top right corner of the diagram. |
| 146 | +# |
| 147 | +# In addition, the display changes color, from orange to blue, when the estimator is |
| 148 | +# fitted. You can also get this information by hovering on the icon "i". |
| 149 | +from sklearn.base import clone |
| 150 | + |
| 151 | +clone(forest) # the clone is not fitted |
| 152 | + |
| 153 | +# %% |
| 154 | +# Metadata Routing Support |
| 155 | +# ------------------------ |
| 156 | +# Many meta-estimators and cross-validation routines now support metadata |
| 157 | +# routing, which are listed in the :ref:`user guide |
| 158 | +# <_metadata_routing_models>`. For instance, this is how you can do a nested |
| 159 | +# cross-validation with sample weights and :class:`~model_selection.GroupKFold`: |
| 160 | +import sklearn |
| 161 | +from sklearn.metrics import get_scorer |
| 162 | +from sklearn.datasets import make_regression |
| 163 | +from sklearn.linear_model import Lasso |
| 164 | +from sklearn.model_selection import GridSearchCV, cross_validate, GroupKFold |
| 165 | + |
| 166 | +# For now by default metadata routing is disabled, and need to be explicitly |
| 167 | +# enabled. |
| 168 | +sklearn.set_config(enable_metadata_routing=True) |
| 169 | + |
| 170 | +n_samples = 100 |
| 171 | +X, y = make_regression(n_samples=n_samples, n_features=5, noise=0.5) |
| 172 | +rng = np.random.RandomState(7) |
| 173 | +groups = rng.randint(0, 10, size=n_samples) |
| 174 | +sample_weights = rng.rand(n_samples) |
| 175 | +estimator = Lasso().set_fit_request(sample_weight=True) |
| 176 | +hyperparameter_grid = {"alpha": [0.1, 0.5, 1.0, 2.0]} |
| 177 | +scoring_inner_cv = get_scorer("neg_mean_squared_error").set_score_request( |
| 178 | + sample_weight=True |
| 179 | +) |
| 180 | +inner_cv = GroupKFold(n_splits=5) |
| 181 | + |
| 182 | +grid_search = GridSearchCV( |
| 183 | + estimator=estimator, |
| 184 | + param_grid=hyperparameter_grid, |
| 185 | + cv=inner_cv, |
| 186 | + scoring=scoring_inner_cv, |
| 187 | +) |
| 188 | + |
| 189 | +outer_cv = GroupKFold(n_splits=5) |
| 190 | +scorers = { |
| 191 | + "mse": get_scorer("neg_mean_squared_error").set_score_request(sample_weight=True) |
| 192 | +} |
| 193 | +results = cross_validate( |
| 194 | + grid_search, |
| 195 | + X, |
| 196 | + y, |
| 197 | + cv=outer_cv, |
| 198 | + scoring=scorers, |
| 199 | + return_estimator=True, |
| 200 | + params={"sample_weight": sample_weights, "groups": groups}, |
| 201 | +) |
| 202 | +print("cv error on test sets:", results["test_mse"]) |
| 203 | + |
| 204 | +# Setting the flag to the default `False` to avoid interference with other |
| 205 | +# scripts. |
| 206 | +sklearn.set_config(enable_metadata_routing=False) |
0 commit comments