|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from logging import getLogger |
| 4 | +from pathlib import Path |
| 5 | +from typing import Any, Callable |
| 6 | + |
| 7 | +import matplotlib.pyplot as plt |
| 8 | +import numpy as np |
| 9 | +from matplotlib.figure import Figure |
| 10 | +from pandas import DataFrame, Series, Timestamp |
| 11 | +from sklearn.base import BaseEstimator, TransformerMixin |
| 12 | +from typing_extensions import Self |
| 13 | + |
| 14 | +from .types import TXPandas |
| 15 | + |
| 16 | +LOG = getLogger(__name__) |
| 17 | + |
| 18 | + |
| 19 | +class ReportNonFinite(BaseEstimator, TransformerMixin): |
| 20 | + """Report non-finite values in X or y.""" |
| 21 | + |
| 22 | + def __init__( |
| 23 | + self, |
| 24 | + *, |
| 25 | + on_fit: bool = False, |
| 26 | + on_fit_y: bool = False, |
| 27 | + on_transform: bool = True, |
| 28 | + plot: bool = True, |
| 29 | + calc_corr: bool = False, |
| 30 | + callback: Callable[[dict[str, DataFrame | Series]], None] | None = None, |
| 31 | + callback_figure: Callable[[Figure], None] |
| 32 | + | None = lambda fig: Path("sklearn_utilities_info/ReportNonFinite").mkdir( # type: ignore |
| 33 | + parents=True, exist_ok=True |
| 34 | + ) |
| 35 | + or fig.savefig( |
| 36 | + Path("sklearn_utilities_info/ReportNonFinite") |
| 37 | + / f"{Timestamp.now().isoformat().replace(':', '-')}.png" |
| 38 | + ), |
| 39 | + ) -> None: |
| 40 | + """Report non-finite values in X or y. |
| 41 | +
|
| 42 | + Parameters |
| 43 | + ---------- |
| 44 | + on_fit : bool, optional |
| 45 | + Whether to report non-finite values in X during fit, by default False |
| 46 | + on_fit_y : bool, optional |
| 47 | + Whether to report non-finite values in y during fit, by default False |
| 48 | + on_transform : bool, optional |
| 49 | + Whether to report non-finite values in X during transform, by default True |
| 50 | + plot : bool, optional |
| 51 | + Whether to plot the report result, by default True |
| 52 | + calc_corr : bool, optional |
| 53 | + Whether to calculate the correlation of non-finite values, by default False |
| 54 | + callback : Callable[[dict[str, DataFrame | Series]], None] | None, optional |
| 55 | + The callback function, by default None |
| 56 | + callback_figure : _type_, optional |
| 57 | + The callback function for figure, by default |
| 58 | + `lambda fig: |
| 59 | + Path("sklearn-utilities/ReportNonFinite").mkdir(parents=True, exist_ok=True) |
| 60 | + or fig.savefig(Path("sklearn-utilities/ReportNonFinite") / |
| 61 | + f"{Timestamp.now().isoformat().replace(':', '-')}.png")` |
| 62 | + """ |
| 63 | + self.on_fit = on_fit |
| 64 | + self.on_fit_y = on_fit_y |
| 65 | + self.on_transform = on_transform |
| 66 | + self.plot = plot |
| 67 | + self.calc_corr = calc_corr |
| 68 | + self.callback = callback |
| 69 | + self.callback_figure = callback_figure |
| 70 | + |
| 71 | + def fit(self, X: DataFrame, y: Any = None, **fit_params: Any) -> Self: |
| 72 | + if self.on_fit: |
| 73 | + try: |
| 74 | + self._report(X, "fit") |
| 75 | + except Exception as e: |
| 76 | + LOG.warning(f"Failed to report non-finite values in X during fit: {e}") |
| 77 | + LOG.exception(e) |
| 78 | + |
| 79 | + if self.on_fit_y: |
| 80 | + try: |
| 81 | + DataFrame(y) |
| 82 | + except Exception as e: |
| 83 | + LOG.warning(f"Failed to convert y to DataFrame during fit: {e}") |
| 84 | + LOG.exception(e) |
| 85 | + |
| 86 | + try: |
| 87 | + self._report(DataFrame(y), "fit_y") |
| 88 | + except Exception as e: |
| 89 | + LOG.warning(f"Failed to report non-finite values in y during fit: {e}") |
| 90 | + LOG.exception(e) |
| 91 | + return self |
| 92 | + |
| 93 | + def transform(self, X: TXPandas, y: Any = None, **fit_params: Any) -> TXPandas: |
| 94 | + if self.on_transform: |
| 95 | + try: |
| 96 | + self._report(X, "transform") |
| 97 | + except Exception as e: |
| 98 | + LOG.warning( |
| 99 | + f"Failed to report non-finite values in X during transform: {e}" |
| 100 | + ) |
| 101 | + LOG.exception(e) |
| 102 | + return X |
| 103 | + |
| 104 | + def _report(self, X: TXPandas, caller: str = "") -> TXPandas: |
| 105 | + """Report non-finite values in X. |
| 106 | +
|
| 107 | + Parameters |
| 108 | + ---------- |
| 109 | + X : TXPandas |
| 110 | + Input data. |
| 111 | + caller : str, optional |
| 112 | + The caller name used in the log message, by default "". |
| 113 | +
|
| 114 | + Returns |
| 115 | + ------- |
| 116 | + TXPandas |
| 117 | + Input data. |
| 118 | + """ |
| 119 | + is_na = X.isna() |
| 120 | + is_inf = X.isin([np.inf, -np.inf]) |
| 121 | + is_non_finite = is_na | is_inf |
| 122 | + |
| 123 | + d: dict[str, DataFrame | Series] = { |
| 124 | + "nan_rate_by_column": is_na.mean(), |
| 125 | + "inf_rate_by_column": is_inf.mean(), |
| 126 | + "nan_rate_by_row": is_na.mean(axis=1), |
| 127 | + "inf_rate_by_row": is_inf.mean(axis=1), |
| 128 | + } |
| 129 | + d = d | { |
| 130 | + "non_finite_rate_by_column": d["nan_rate_by_column"] |
| 131 | + + d["inf_rate_by_column"], |
| 132 | + "non_finite_rate_by_row": d["nan_rate_by_row"] + d["inf_rate_by_row"], |
| 133 | + } |
| 134 | + |
| 135 | + if self.calc_corr: |
| 136 | + d["nan_rate_corr_by_column"] = is_na.corr() |
| 137 | + d["inf_rate_corr_by_column"] = is_inf.corr() |
| 138 | + d["non_finite_rate_corr_by_column"] = is_non_finite.corr() |
| 139 | + |
| 140 | + LOG.info(f"Non-finite values in X during {caller}: {d}") |
| 141 | + |
| 142 | + if self.plot: |
| 143 | + import seaborn as sns |
| 144 | + |
| 145 | + fig, axes = plt.subplots(3, 3 if self.calc_corr else 2, figsize=(20, 10)) |
| 146 | + fig.suptitle(f"Non-finite values in X during {caller}") |
| 147 | + d["nan_rate_by_column"].plot( |
| 148 | + ax=axes[0, 0], |
| 149 | + kind="bar", |
| 150 | + title="NaN rate By column", |
| 151 | + xlabel="column name", |
| 152 | + ylabel="NaN rate", |
| 153 | + ) |
| 154 | + d["inf_rate_by_column"].plot( |
| 155 | + ax=axes[1, 0], |
| 156 | + kind="bar", |
| 157 | + title="Inf rate By column", |
| 158 | + xlabel="column name", |
| 159 | + ylabel="Inf rate", |
| 160 | + ) |
| 161 | + d["non_finite_rate_by_column"].plot( |
| 162 | + ax=axes[2, 0], |
| 163 | + kind="bar", |
| 164 | + title="Non-finite rate By column", |
| 165 | + xlabel="column name", |
| 166 | + ylabel="Non-finite rate", |
| 167 | + ) |
| 168 | + d["nan_rate_by_row"].plot( |
| 169 | + ax=axes[0, 1], |
| 170 | + kind="line", |
| 171 | + title="NaN rate By row", |
| 172 | + xlabel="row index", |
| 173 | + ylabel="NaN rate", |
| 174 | + ) |
| 175 | + d["inf_rate_by_row"].plot( |
| 176 | + ax=axes[1, 1], |
| 177 | + kind="line", |
| 178 | + title="Inf rate By row", |
| 179 | + xlabel="row index", |
| 180 | + ylabel="Inf rate", |
| 181 | + ) |
| 182 | + d["non_finite_rate_by_row"].plot( |
| 183 | + ax=axes[2, 1], |
| 184 | + kind="line", |
| 185 | + title="Non-finite rate By row", |
| 186 | + xlabel="row index", |
| 187 | + ylabel="Non-finite rate", |
| 188 | + ) |
| 189 | + if self.calc_corr: |
| 190 | + sns.heatmap( |
| 191 | + d["nan_rate_corr_by_column"], ax=axes[0, 2], vmin=-1, vmax=1 |
| 192 | + ) |
| 193 | + axes[0, 2].set_title("NaN rate Corr By column") |
| 194 | + sns.heatmap( |
| 195 | + d["inf_rate_corr_by_column"], ax=axes[1, 2], vmin=-1, vmax=1 |
| 196 | + ) |
| 197 | + axes[1, 2].set_title("Inf rate Corr By column") |
| 198 | + sns.heatmap( |
| 199 | + d["non_finite_rate_corr_by_column"], ax=axes[2, 2], vmin=-1, vmax=1 |
| 200 | + ) |
| 201 | + axes[2, 2].set_title("Non-finite rate Corr By column") |
| 202 | + |
| 203 | + # tight layout |
| 204 | + plt.tight_layout() |
| 205 | + |
| 206 | + # callback |
| 207 | + if self.callback_figure is not None: |
| 208 | + self.callback_figure(fig) |
| 209 | + |
| 210 | + if self.callback is not None: |
| 211 | + self.callback(d) |
| 212 | + return X |
0 commit comments