|
| 1 | +# Copyright 2024 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Transformers for missing value imputation. This module is styled after |
| 16 | +scikit-learn's preprocessing module: https://scikit-learn.org/stable/modules/impute.html.""" |
| 17 | + |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +import typing |
| 21 | +from typing import Any, List, Literal, Optional, Tuple, Union |
| 22 | + |
| 23 | +import bigframes_vendored.sklearn.impute._base |
| 24 | + |
| 25 | +from bigframes.core import log_adapter |
| 26 | +from bigframes.ml import base, core, globals, utils |
| 27 | +import bigframes.pandas as bpd |
| 28 | + |
| 29 | + |
| 30 | +@log_adapter.class_logger |
| 31 | +class SimpleImputer( |
| 32 | + base.Transformer, |
| 33 | + bigframes_vendored.sklearn.impute._base.SimpleImputer, |
| 34 | +): |
| 35 | + |
| 36 | + __doc__ = bigframes_vendored.sklearn.impute._base.SimpleImputer.__doc__ |
| 37 | + |
| 38 | + def __init__( |
| 39 | + self, |
| 40 | + strategy: Literal["mean", "median", "most_frequent"] = "mean", |
| 41 | + ): |
| 42 | + self.strategy = strategy |
| 43 | + self._bqml_model: Optional[core.BqmlModel] = None |
| 44 | + self._bqml_model_factory = globals.bqml_model_factory() |
| 45 | + self._base_sql_generator = globals.base_sql_generator() |
| 46 | + |
| 47 | + # TODO(garrettwu): implement __hash__ |
| 48 | + def __eq__(self, other: Any) -> bool: |
| 49 | + return ( |
| 50 | + type(other) is SimpleImputer |
| 51 | + and self.strategy == other.strategy |
| 52 | + and self._bqml_model == other._bqml_model |
| 53 | + ) |
| 54 | + |
| 55 | + def _compile_to_sql( |
| 56 | + self, |
| 57 | + columns: List[str], |
| 58 | + X=None, |
| 59 | + ) -> List[Tuple[str, str]]: |
| 60 | + """Compile this transformer to a list of SQL expressions that can be included in |
| 61 | + a BQML TRANSFORM clause |
| 62 | +
|
| 63 | + Args: |
| 64 | + columns: |
| 65 | + A list of column names to transform. |
| 66 | + X: |
| 67 | + The Dataframe with training data. |
| 68 | +
|
| 69 | + Returns: a list of tuples of (sql_expression, output_name)""" |
| 70 | + return [ |
| 71 | + ( |
| 72 | + self._base_sql_generator.ml_imputer( |
| 73 | + column, self.strategy, f"imputer_{column}" |
| 74 | + ), |
| 75 | + f"imputer_{column}", |
| 76 | + ) |
| 77 | + for column in columns |
| 78 | + ] |
| 79 | + |
| 80 | + @classmethod |
| 81 | + def _parse_from_sql(cls, sql: str) -> tuple[SimpleImputer, str]: |
| 82 | + """Parse SQL to tuple(SimpleImputer, column_label). |
| 83 | +
|
| 84 | + Args: |
| 85 | + sql: SQL string of format "ML.IMPUTER({col_label}, {strategy}) OVER()" |
| 86 | +
|
| 87 | + Returns: |
| 88 | + tuple(SimpleImputer, column_label)""" |
| 89 | + s = sql[sql.find("(") + 1 : sql.find(")")] |
| 90 | + col_label, strategy = s.split(", ") |
| 91 | + return cls(strategy[1:-1]), col_label # type: ignore[arg-type] |
| 92 | + |
| 93 | + def fit( |
| 94 | + self, |
| 95 | + X: Union[bpd.DataFrame, bpd.Series], |
| 96 | + y=None, # ignored |
| 97 | + ) -> SimpleImputer: |
| 98 | + (X,) = utils.convert_to_dataframe(X) |
| 99 | + |
| 100 | + compiled_transforms = self._compile_to_sql(X.columns.tolist(), X) |
| 101 | + transform_sqls = [transform_sql for transform_sql, _ in compiled_transforms] |
| 102 | + |
| 103 | + self._bqml_model = self._bqml_model_factory.create_model( |
| 104 | + X, |
| 105 | + options={"model_type": "transform_only"}, |
| 106 | + transforms=transform_sqls, |
| 107 | + ) |
| 108 | + |
| 109 | + # The schema of TRANSFORM output is not available in the model API, so save it during fitting |
| 110 | + self._output_names = [name for _, name in compiled_transforms] |
| 111 | + return self |
| 112 | + |
| 113 | + def transform(self, X: Union[bpd.DataFrame, bpd.Series]) -> bpd.DataFrame: |
| 114 | + if not self._bqml_model: |
| 115 | + raise RuntimeError("Must be fitted before transform") |
| 116 | + |
| 117 | + (X,) = utils.convert_to_dataframe(X) |
| 118 | + |
| 119 | + df = self._bqml_model.transform(X) |
| 120 | + return typing.cast( |
| 121 | + bpd.DataFrame, |
| 122 | + df[self._output_names], |
| 123 | + ) |
0 commit comments