You are viewing documentation about an older version (1.7.0). View latest version

snowflake.ml.modeling.ensemble.HistGradientBoostingRegressor

class snowflake.ml.modeling.ensemble.HistGradientBoostingRegressor(*, loss='squared_error', quantile=None, learning_rate=0.1, max_iter=100, max_leaf_nodes=31, max_depth=None, min_samples_leaf=20, l2_regularization=0.0, max_features=1.0, max_bins=255, categorical_features='warn', monotonic_cst=None, interaction_cst=None, warm_start=False, early_stopping='auto', scoring='loss', validation_fraction=0.1, n_iter_no_change=10, tol=1e-07, verbose=0, random_state=None, input_cols: Optional[Union[str, Iterable[str]]] = None, output_cols: Optional[Union[str, Iterable[str]]] = None, label_cols: Optional[Union[str, Iterable[str]]] = None, passthrough_cols: Optional[Union[str, Iterable[str]]] = None, drop_input_cols: Optional[bool] = False, sample_weight_col: Optional[str] = None)

Bases: BaseTransformer

Histogram-based Gradient Boosting Regression Tree For more details on this class, see sklearn.ensemble.HistGradientBoostingRegressor

Parameters:
  • input_cols (Optional[Union[str, List[str]]]) – A string or list of strings representing column names that contain features. If this parameter is not specified, all columns in the input DataFrame except the columns specified by label_cols, sample_weight_col, and passthrough_cols parameters are considered input columns. Input columns can also be set after initialization with the set_input_cols method.

  • label_cols (Optional[Union[str, List[str]]]) – A string or list of strings representing column names that contain labels. Label columns must be specified with this parameter during initialization or with the set_label_cols method before fitting.

  • output_cols (Optional[Union[str, List[str]]]) – A string or list of strings representing column names that will store the output of predict and transform operations. The length of output_cols must match the expected number of output columns from the specific predictor or transformer class used. If you omit this parameter, output column names are derived by adding an OUTPUT_ prefix to the label column names for supervised estimators, or OUTPUT_<IDX>for unsupervised estimators. These inferred output column names work for predictors, but output_cols must be set explicitly for transformers. In general, explicitly specifying output column names is clearer, especially if you don’t specify the input column names. To transform in place, pass the same names for input_cols and output_cols. be set explicitly for transformers. Output columns can also be set after initialization with the set_output_cols method.

  • sample_weight_col (Optional[str]) – A string representing the column name containing the sample weights. This argument is only required when working with weighted datasets. Sample weight column can also be set after initialization with the set_sample_weight_col method.

  • passthrough_cols (Optional[Union[str, List[str]]]) – A string or a list of strings indicating column names to be excluded from any operations (such as train, transform, or inference). These specified column(s) will remain untouched throughout the process. This option is helpful in scenarios requiring automatic input_cols inference, but need to avoid using specific columns, like index columns, during training or inference. Passthrough columns can also be set after initialization with the set_passthrough_cols method.

  • drop_input_cols (Optional[bool], default=False) – If set, the response of predict(), transform() methods will not contain input columns.

  • loss ({'squared_error', 'absolute_error', 'gamma', 'poisson', 'quantile'}, default='squared_error') – The loss function to use in the boosting process. Note that the “squared error”, “gamma” and “poisson” losses actually implement “half least squares loss”, “half gamma deviance” and “half poisson deviance” to simplify the computation of the gradient. Furthermore, “gamma” and “poisson” losses internally use a log-link, “gamma” requires y > 0 and “poisson” requires y >= 0. “quantile” uses the pinball loss.

  • quantile (float, default=None) – If loss is “quantile”, this parameter specifies which quantile to be estimated and must be between 0 and 1.

  • learning_rate (float, default=0.1) – The learning rate, also known as shrinkage. This is used as a multiplicative factor for the leaves values. Use 1 for no shrinkage.

  • max_iter (int, default=100) – The maximum number of iterations of the boosting process, i.e. the maximum number of trees.

  • max_leaf_nodes (int or None, default=31) – The maximum number of leaves for each tree. Must be strictly greater than 1. If None, there is no maximum limit.

  • max_depth (int or None, default=None) – The maximum depth of each tree. The depth of a tree is the number of edges to go from the root to the deepest leaf. Depth isn’t constrained by default.

  • min_samples_leaf (int, default=20) – The minimum number of samples per leaf. For small datasets with less than a few hundred samples, it is recommended to lower this value since only very shallow trees would be built.

  • l2_regularization (float, default=0) – The L2 regularization parameter penalizing leaves with small hessians. Use 0 for no regularization (default).

  • max_features (float, default=1.0) – Proportion of randomly chosen features in each and every node split. This is a form of regularization, smaller values make the trees weaker learners and might prevent overfitting. If interaction constraints from interaction_cst are present, only allowed features are taken into account for the subsampling.

  • max_bins (int, default=255) – The maximum number of bins to use for non-missing values. Before training, each feature of the input array X is binned into integer-valued bins, which allows for a much faster training stage. Features with a small number of unique values may use less than max_bins bins. In addition to the max_bins bins, one more bin is always reserved for missing values. Must be no larger than 255.

  • categorical_features (array-like of {bool, int, str} of shape (n_features) or shape (n_categorical_features,), default=None) –

    Indicates the categorical features.

    • None: no feature will be considered categorical.

    • boolean array-like: boolean mask indicating categorical features.

    • integer array-like: integer indices indicating categorical features.

    • str array-like: names of categorical features (assuming the training data has feature names).

    • ”from_dtype”: dataframe columns with dtype “category” are considered to be categorical features. The input must be an object exposing a __dataframe__ method such as pandas or polars DataFrames to use this feature.

    For each categorical feature, there must be at most max_bins unique categories. Negative values for categorical features encoded as numeric dtypes are treated as missing values. All categorical values are converted to floating point numbers. This means that categorical values of 1.0 and 1 are treated as the same category.

    Read more in the User Guide.

  • monotonic_cst (array-like of int of shape (n_features) or dict, default=None) –

    Monotonic constraint to enforce on each feature are specified using the following integer values:

    • 1: monotonic increase

    • 0: no constraint

    • -1: monotonic decrease

    If a dict with str keys, map feature to monotonic constraints by name. If an array, the features are mapped to constraints by position. See monotonic_cst_features_names for a usage example.

    Read more in the User Guide.

  • interaction_cst ({"pairwise", "no_interactions"} or sequence of lists/tuples/sets of int, default=None) –

    Specify interaction constraints, the sets of features which can interact with each other in child node splits.

    Each item specifies the set of feature indices that are allowed to interact with each other. If there are more features than specified in these constraints, they are treated as if they were specified as an additional set.

    The strings “pairwise” and “no_interactions” are shorthands for allowing only pairwise or no interactions, respectively.

    For instance, with 5 features in total, interaction_cst=[{0, 1}] is equivalent to interaction_cst=[{0, 1}, {2, 3, 4}], and specifies that each branch of a tree will either only split on features 0 and 1 or only split on features 2, 3 and 4.

  • warm_start (bool, default=False) – When set to True, reuse the solution of the previous call to fit and add more estimators to the ensemble. For results to be valid, the estimator should be re-trained on the same data only. See the Glossary.

  • early_stopping ('auto' or bool, default='auto') – If ‘auto’, early stopping is enabled if the sample size is larger than 10000. If True, early stopping is enabled, otherwise early stopping is disabled.

  • scoring (str or callable or None, default='loss') – Scoring parameter to use for early stopping. It can be a single string (see scoring_parameter) or a callable (see scoring). If None, the estimator’s default scorer is used. If scoring='loss', early stopping is checked w.r.t the loss value. Only used if early stopping is performed.

  • validation_fraction (int or float or None, default=0.1) – Proportion (or absolute size) of training data to set aside as validation data for early stopping. If None, early stopping is done on the training data. Only used if early stopping is performed.

  • n_iter_no_change (int, default=10) – Used to determine when to “early stop”. The fitting process is stopped when none of the last n_iter_no_change scores are better than the n_iter_no_change - 1 -th-to-last one, up to some tolerance. Only used if early stopping is performed.

  • tol (float, default=1e-7) – The absolute tolerance to use when comparing scores during early stopping. The higher the tolerance, the more likely we are to early stop: higher tolerance means that it will be harder for subsequent iterations to be considered an improvement upon the reference score.

  • verbose (int, default=0) – The verbosity level. If not zero, print some information about the fitting process.

  • random_state (int, RandomState instance or None, default=None) – Pseudo-random number generator to control the subsampling in the binning process, and the train/validation data split if early stopping is enabled. Pass an int for reproducible output across multiple function calls. See Glossary.

Base class for all transformers.

Methods

fit(dataset: Union[DataFrame, DataFrame]) BaseEstimator

Runs universal logics for all fit implementations.

fit_transform(dataset: Union[DataFrame, DataFrame], output_cols_prefix: str = 'fit_transform_') Union[DataFrame, DataFrame]

Method not supported for this class.

Raises:

TypeError – Supported dataset types: snowpark.DataFrame, pandas.DataFrame.

Parameters:

dataset – Union[snowflake.snowpark.DataFrame, pandas.DataFrame] Snowpark or Pandas DataFrame.

output_cols_prefix: Prefix for the response columns :returns: Transformed dataset.

get_input_cols() List[str]

Input columns getter.

Returns:

Input columns.

get_label_cols() List[str]

Label column getter.

Returns:

Label column(s).

get_output_cols() List[str]

Output columns getter.

Returns:

Output columns.

get_params(deep: bool = True) Dict[str, Any]

Get the snowflake-ml parameters for this transformer.

Parameters:

deep – If True, will return the parameters for this transformer and contained subobjects that are transformers.

Returns:

Parameter names mapped to their values.

get_passthrough_cols() List[str]

Passthrough columns getter.

Returns:

Passthrough column(s).

get_sample_weight_col() Optional[str]

Sample weight column getter.

Returns:

Sample weight column.

get_sklearn_args(default_sklearn_obj: Optional[object] = None, sklearn_initial_keywords: Optional[Union[str, Iterable[str]]] = None, sklearn_unused_keywords: Optional[Union[str, Iterable[str]]] = None, snowml_only_keywords: Optional[Union[str, Iterable[str]]] = None, sklearn_added_keyword_to_version_dict: Optional[Dict[str, str]] = None, sklearn_added_kwarg_value_to_version_dict: Optional[Dict[str, Dict[str, str]]] = None, sklearn_deprecated_keyword_to_version_dict: Optional[Dict[str, str]] = None, sklearn_removed_keyword_to_version_dict: Optional[Dict[str, str]] = None) Dict[str, Any]

Get sklearn keyword arguments.

This method enables modifying object parameters for special cases.

Parameters:
  • default_sklearn_obj – Sklearn object used to get default parameter values. Necessary when sklearn_added_keyword_to_version_dict is provided.

  • sklearn_initial_keywords – Initial keywords in sklearn.

  • sklearn_unused_keywords – Sklearn keywords that are unused in snowml.

  • snowml_only_keywords – snowml only keywords not present in sklearn.

  • sklearn_added_keyword_to_version_dict – Added keywords mapped to the sklearn versions in which they were added.

  • sklearn_added_kwarg_value_to_version_dict – Added keyword argument values mapped to the sklearn versions in which they were added.

  • sklearn_deprecated_keyword_to_version_dict – Deprecated keywords mapped to the sklearn versions in which they were deprecated.

  • sklearn_removed_keyword_to_version_dict – Removed keywords mapped to the sklearn versions in which they were removed.

Returns:

Sklearn parameter names mapped to their values.

predict(dataset: Union[DataFrame, DataFrame]) Union[DataFrame, DataFrame]

Predict values for X For more details on this function, see sklearn.ensemble.HistGradientBoostingRegressor.predict

Raises:

TypeError – Supported dataset types: snowpark.DataFrame, pandas.DataFrame.

Parameters:

dataset – Union[snowflake.snowpark.DataFrame, pandas.DataFrame] Snowpark or Pandas DataFrame.

Returns:

Transformed dataset.

score(dataset: Union[DataFrame, DataFrame]) float

Return the coefficient of determination of the prediction For more details on this function, see sklearn.ensemble.HistGradientBoostingRegressor.score

Raises:

TypeError – Supported dataset types: snowpark.DataFrame, pandas.DataFrame.

Parameters:

dataset – Union[snowflake.snowpark.DataFrame, pandas.DataFrame] Snowpark or Pandas DataFrame.

Returns:

Score.

score_samples(dataset: Union[DataFrame, DataFrame], output_cols_prefix: str = 'score_samples_') Union[DataFrame, DataFrame]

Method not supported for this class.

Raises:

TypeError – Supported dataset types: snowpark.DataFrame, pandas.DataFrame.

Parameters:
  • dataset – Union[snowflake.snowpark.DataFrame, pandas.DataFrame] Snowpark or Pandas DataFrame.

  • output_cols_prefix – Prefix for the response columns

Returns:

Output dataset with probability of the sample for each class in the model.

set_drop_input_cols(drop_input_cols: Optional[bool] = False) None
set_input_cols(input_cols: Optional[Union[str, Iterable[str]]]) HistGradientBoostingRegressor

Input columns setter.

Parameters:

input_cols – A single input column or multiple input columns.

Returns:

self

set_label_cols(label_cols: Optional[Union[str, Iterable[str]]]) Base

Label column setter.

Parameters:

label_cols – A single label column or multiple label columns if multi task learning.

Returns:

self

set_output_cols(output_cols: Optional[Union[str, Iterable[str]]]) Base

Output columns setter.

Parameters:

output_cols – A single output column or multiple output columns.

Returns:

self

set_params(**params: Any) None

Set the parameters of this transformer.

The method works on simple transformers as well as on sklearn compatible pipelines with nested objects, once the transformer has been fit. Nested objects have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.

Parameters:

**params – Transformer parameter names mapped to their values.

Raises:

SnowflakeMLException – Invalid parameter keys.

set_passthrough_cols(passthrough_cols: Optional[Union[str, Iterable[str]]]) Base

Passthrough columns setter.

Parameters:

passthrough_cols – Column(s) that should not be used or modified by the estimator/transformer. Estimator/Transformer just passthrough these columns without any modifications.

Returns:

self

set_sample_weight_col(sample_weight_col: Optional[str]) Base

Sample weight column setter.

Parameters:

sample_weight_col – A single column that represents sample weight.

Returns:

self

to_sklearn() Any

Get sklearn.ensemble.HistGradientBoostingRegressor object.

Attributes

model_signatures

Returns model signature of current class.

Raises:

SnowflakeMLException – If estimator is not fitted, then model signature cannot be inferred

Returns:

Dict with each method and its input output signature