Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 68
feat: add ml.preprocessing.KBinsDiscretizer#81
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
1f87562
feat: add ml.preprocessing.KBinsDiscretizer
ashleyxuu eae378f
fix: address all the comments
ashleyxuu fbab743
fix: address additional comments
ashleyxuu 56395e0
fix: fix the failed test
ashleyxuu 2138ff6
Merge branch 'main' into ashleyxu-add-kbins-discretizer
ashleyxuu 56a5049
Empty commit
ashleyxuu ac3c4c0
Merge branch 'main' into ashleyxu-add-kbins-discretizer
ashleyxuu ef35bde
Trigger Kokoro
ashleyxuu 17a301a
Merge branch 'main' into ashleyxu-add-kbins-discretizer
ashleyxuu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -23,6 +23,7 @@ | ||
| from bigframes.ml import base, core, globals, utils | ||
| import bigframes.pandas as bpd | ||
| import third_party.bigframes_vendored.sklearn.preprocessing._data | ||
| import third_party.bigframes_vendored.sklearn.preprocessing._discretization | ||
| import third_party.bigframes_vendored.sklearn.preprocessing._encoder | ||
| import third_party.bigframes_vendored.sklearn.preprocessing._label | ||
| @@ -44,12 +45,15 @@ def __init__(self): | ||
| def __eq__(self, other: Any) -> bool: | ||
| return type(other) is StandardScaler and self._bqml_model == other._bqml_model | ||
| def _compile_to_sql(self, columns: List[str]) -> List[Tuple[str, str]]: | ||
| def _compile_to_sql(self, columns: List[str], X=None) -> List[Tuple[str, str]]: | ||
| """Compile this transformer to a list of SQL expressions that can be included in | ||
| a BQML TRANSFORM clause | ||
| Args: | ||
| columns: a list of column names to transform | ||
| columns: | ||
| a list of column names to transform. | ||
| X (default None): | ||
| Ignored. | ||
| Returns: a list of tuples of (sql_expression, output_name)""" | ||
| return [ | ||
| @@ -124,12 +128,15 @@ def __init__(self): | ||
| def __eq__(self, other: Any) -> bool: | ||
| return type(other) is MaxAbsScaler and self._bqml_model == other._bqml_model | ||
| def _compile_to_sql(self, columns: List[str]) -> List[Tuple[str, str]]: | ||
| def _compile_to_sql(self, columns: List[str], X=None) -> List[Tuple[str, str]]: | ||
| """Compile this transformer to a list of SQL expressions that can be included in | ||
| a BQML TRANSFORM clause | ||
| Args: | ||
| columns: a list of column names to transform | ||
| columns: | ||
| a list of column names to transform. | ||
| X (default None): | ||
| Ignored. | ||
| Returns: a list of tuples of (sql_expression, output_name)""" | ||
| return [ | ||
| @@ -204,12 +211,15 @@ def __init__(self): | ||
| def __eq__(self, other: Any) -> bool: | ||
| return type(other) is MinMaxScaler and self._bqml_model == other._bqml_model | ||
| def _compile_to_sql(self, columns: List[str]) -> List[Tuple[str, str]]: | ||
| def _compile_to_sql(self, columns: List[str], X=None) -> List[Tuple[str, str]]: | ||
| """Compile this transformer to a list of SQL expressions that can be included in | ||
| a BQML TRANSFORM clause | ||
| Args: | ||
| columns: a list of column names to transform | ||
| columns: | ||
| a list of column names to transform. | ||
| X (default None): | ||
| Ignored. | ||
| Returns: a list of tuples of (sql_expression, output_name)""" | ||
| return [ | ||
| @@ -267,6 +277,124 @@ def transform(self, X: Union[bpd.DataFrame, bpd.Series]) -> bpd.DataFrame: | ||
| ) | ||
| class KBinsDiscretizer( | ||
| base.Transformer, | ||
| third_party.bigframes_vendored.sklearn.preprocessing._discretization.KBinsDiscretizer, | ||
| ): | ||
| __doc__ = ( | ||
| third_party.bigframes_vendored.sklearn.preprocessing._discretization.KBinsDiscretizer.__doc__ | ||
| ) | ||
| def __init__( | ||
ashleyxuu marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| self, | ||
| n_bins: int = 5, | ||
| strategy: Literal["uniform", "quantile"] = "quantile", | ||
| ): | ||
| if strategy != "uniform": | ||
| raise NotImplementedError( | ||
| f"Only strategy = 'uniform' is supported now, input is {strategy}." | ||
| ) | ||
| if n_bins < 2: | ||
| raise ValueError( | ||
| f"n_bins has to be larger than or equal to 2, input is {n_bins}." | ||
| ) | ||
| self.n_bins = n_bins | ||
| self.strategy = strategy | ||
| self._bqml_model: Optional[core.BqmlModel] = None | ||
| self._bqml_model_factory = globals.bqml_model_factory() | ||
| self._base_sql_generator = globals.base_sql_generator() | ||
| # TODO(garrettwu): implement __hash__ | ||
| def __eq__(self, other: Any) -> bool: | ||
| return ( | ||
| type(other) is KBinsDiscretizer | ||
| and self.n_bins == other.n_bins | ||
| and self._bqml_model == other._bqml_model | ||
| ) | ||
| def _compile_to_sql( | ||
| self, | ||
| columns: List[str], | ||
| X: bpd.DataFrame, | ||
| ) -> List[Tuple[str, str]]: | ||
| """Compile this transformer to a list of SQL expressions that can be included in | ||
| a BQML TRANSFORM clause | ||
| Args: | ||
| columns: | ||
| a list of column names to transform | ||
| X: | ||
| The Dataframe with training data. | ||
| Returns: a list of tuples of (sql_expression, output_name)""" | ||
| array_split_points = {} | ||
| if self.strategy == "uniform": | ||
| for column in columns: | ||
| min_value = X[column].min() | ||
| max_value = X[column].max() | ||
| bin_size = (max_value - min_value) / self.n_bins | ||
| array_split_points[column] = [ | ||
| min_value + i * bin_size for i in range(self.n_bins - 1) | ||
| ] | ||
| return [ | ||
| ( | ||
| self._base_sql_generator.ml_bucketize( | ||
| column, array_split_points[column], f"kbinsdiscretizer_{column}" | ||
| ), | ||
| f"kbinsdiscretizer_{column}", | ||
| ) | ||
| for column in columns | ||
| ] | ||
| @classmethod | ||
| def _parse_from_sql(cls, sql: str) -> tuple[KBinsDiscretizer, str]: | ||
| """Parse SQL to tuple(KBinsDiscretizer, column_label). | ||
| Args: | ||
| sql: SQL string of format "ML.BUCKETIZE({col_label}, array_split_points, FALSE) OVER()" | ||
| Returns: | ||
| tuple(KBinsDiscretizer, column_label)""" | ||
| s = sql[sql.find("(") + 1 : sql.find(")")] | ||
| array_split_points = s[s.find("[") + 1 : s.find("]")] | ||
| col_label = s[: s.find(",")] | ||
| n_bins = array_split_points.count(",") + 2 | ||
| return cls(n_bins, "uniform"), col_label | ||
| def fit( | ||
| self, | ||
| X: Union[bpd.DataFrame, bpd.Series], | ||
| y=None, # ignored | ||
| ) -> KBinsDiscretizer: | ||
| (X,) = utils.convert_to_dataframe(X) | ||
| compiled_transforms = self._compile_to_sql(X.columns.tolist(), X) | ||
| transform_sqls = [transform_sql for transform_sql, _ in compiled_transforms] | ||
| self._bqml_model = self._bqml_model_factory.create_model( | ||
| X, | ||
| options={"model_type": "transform_only"}, | ||
| transforms=transform_sqls, | ||
| ) | ||
| # The schema of TRANSFORM output is not available in the model API, so save it during fitting | ||
| self._output_names = [name for _, name in compiled_transforms] | ||
| return self | ||
| def transform(self, X: Union[bpd.DataFrame, bpd.Series]) -> bpd.DataFrame: | ||
| if not self._bqml_model: | ||
| raise RuntimeError("Must be fitted before transform") | ||
| (X,) = utils.convert_to_dataframe(X) | ||
| df = self._bqml_model.transform(X) | ||
| return typing.cast( | ||
| bpd.DataFrame, | ||
| df[self._output_names], | ||
| ) | ||
| class OneHotEncoder( | ||
| base.Transformer, | ||
| third_party.bigframes_vendored.sklearn.preprocessing._encoder.OneHotEncoder, | ||
| @@ -308,13 +436,15 @@ def __eq__(self, other: Any) -> bool: | ||
| and self.max_categories == other.max_categories | ||
| ) | ||
| def _compile_to_sql(self, columns: List[str]) -> List[Tuple[str, str]]: | ||
| def _compile_to_sql(self, columns: List[str], X=None) -> List[Tuple[str, str]]: | ||
| """Compile this transformer to a list of SQL expressions that can be included in | ||
| a BQML TRANSFORM clause | ||
| Args: | ||
| columns: | ||
| a list of column names to transform | ||
| a list of column names to transform. | ||
| X (default None): | ||
| Ignored. | ||
| Returns: a list of tuples of (sql_expression, output_name)""" | ||
| @@ -432,13 +562,15 @@ def __eq__(self, other: Any) -> bool: | ||
| and self.max_categories == other.max_categories | ||
| ) | ||
| def _compile_to_sql(self, columns: List[str]) -> List[Tuple[str, str]]: | ||
| def _compile_to_sql(self, columns: List[str], X=None) -> List[Tuple[str, str]]: | ||
| """Compile this transformer to a list of SQL expressions that can be included in | ||
| a BQML TRANSFORM clause | ||
| Args: | ||
| columns: | ||
| a list of column names to transform | ||
| a list of column names to transform. | ||
| X (default None): | ||
| Ignored. | ||
| Returns: a list of tuples of (sql_expression, output_name)""" | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.