snowflake.ml.modeling.linear_model.LogisticRegression¶
- class snowflake.ml.modeling.linear_model.LogisticRegression(*, penalty='l2', dual=False, tol=0.0001, C=1.0, fit_intercept=True, intercept_scaling=1, class_weight=None, random_state=None, solver='lbfgs', max_iter=100, multi_class='auto', verbose=0, warm_start=False, n_jobs=None, l1_ratio=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
Logistic Regression (aka logit, MaxEnt) classifier For more details on this class, see sklearn.linear_model.LogisticRegression
- 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.
- penalty: {‘l1’, ‘l2’, ‘elasticnet’, None}, default=’l2’
Specify the norm of the penalty:
None: no penalty is added;
‘l2’: add a L2 penalty term and it is the default choice;
‘l1’: add a L1 penalty term;
‘elasticnet’: both L1 and L2 penalty terms are added.
- dual: bool, default=False
Dual or primal formulation. Dual formulation is only implemented for l2 penalty with liblinear solver. Prefer dual=False when n_samples > n_features.
- tol: float, default=1e-4
Tolerance for stopping criteria.
- C: float, default=1.0
Inverse of regularization strength; must be a positive float. Like in support vector machines, smaller values specify stronger regularization.
- fit_intercept: bool, default=True
Specifies if a constant (a.k.a. bias or intercept) should be added to the decision function.
- intercept_scaling: float, default=1
Useful only when the solver ‘liblinear’ is used and self.fit_intercept is set to True. In this case, x becomes [x, self.intercept_scaling], i.e. a “synthetic” feature with constant value equal to intercept_scaling is appended to the instance vector. The intercept becomes
intercept_scaling * synthetic_feature_weight
.Note! the synthetic feature weight is subject to l1/l2 regularization as all other features. To lessen the effect of regularization on synthetic feature weight (and therefore on the intercept) intercept_scaling has to be increased.
- class_weight: dict or ‘balanced’, default=None
Weights associated with classes in the form
{class_label: weight}
. If not given, all classes are supposed to have weight one.The “balanced” mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as
n_samples / (n_classes * np.bincount(y))
.Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified.
- random_state: int, RandomState instance, default=None
Used when
solver
== ‘sag’, ‘saga’ or ‘liblinear’ to shuffle the data. See Glossary for details.
solver: {‘lbfgs’, ‘liblinear’, ‘newton-cg’, ‘newton-cholesky’, ‘sag’, ‘saga’}, default=’lbfgs’
Algorithm to use in the optimization problem. Default is ‘lbfgs’. To choose a solver, you might want to consider the following aspects:
For small datasets, ‘liblinear’ is a good choice, whereas ‘sag’ and ‘saga’ are faster for large ones;
For multiclass problems, only ‘newton-cg’, ‘sag’, ‘saga’ and ‘lbfgs’ handle multinomial loss;
‘liblinear’ is limited to one-versus-rest schemes.
‘newton-cholesky’ is a good choice for n_samples >> n_features, especially with one-hot encoded categorical features with rare categories. Note that it is limited to binary classification and the one-versus-rest reduction for multiclass classification. Be aware that the memory usage of this solver has a quadratic dependency on n_features because it explicitly computes the Hessian matrix.
‘lbfgs’ - [‘l2’, None]
‘liblinear’ - [‘l1’, ‘l2’]
‘newton-cg’ - [‘l2’, None]
‘newton-cholesky’ - [‘l2’, None]
‘sag’ - [‘l2’, None]
‘saga’ - [‘elasticnet’, ‘l1’, ‘l2’, None]
- max_iter: int, default=100
Maximum number of iterations taken for the solvers to converge.
- multi_class: {‘auto’, ‘ovr’, ‘multinomial’}, default=’auto’
If the option chosen is ‘ovr’, then a binary problem is fit for each label. For ‘multinomial’ the loss minimised is the multinomial loss fit across the entire probability distribution, even when the data is binary. ‘multinomial’ is unavailable when solver=’liblinear’. ‘auto’ selects ‘ovr’ if the data is binary, or if solver=’liblinear’, and otherwise selects ‘multinomial’.
- verbose: int, default=0
For the liblinear and lbfgs solvers set verbose to any positive number for verbosity.
- warm_start: bool, default=False
When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. Useless for liblinear solver. See the Glossary.
- n_jobs: int, default=None
Number of CPU cores used when parallelizing over classes if multi_class=’ovr’”. This parameter is ignored when the
solver
is set to ‘liblinear’ regardless of whether ‘multi_class’ is specified or not.None
means 1 unless in ajoblib.parallel_backend
context.-1
means using all processors. See Glossary for more details.- l1_ratio: float, default=None
The Elastic-Net mixing parameter, with
0 <= l1_ratio <= 1
. Only used ifpenalty='elasticnet'
. Settingl1_ratio=0
is equivalent to usingpenalty='l2'
, while settingl1_ratio=1
is equivalent to usingpenalty='l1'
. For0 < l1_ratio <1
, the penalty is a combination of L1 and L2.
Base class for all transformers.
Methods
- decision_function(dataset: Union[DataFrame, DataFrame], output_cols_prefix: str = 'decision_function_') Union[DataFrame, DataFrame] ¶
Predict confidence scores for samples For more details on this function, see sklearn.linear_model.LogisticRegression.decision_function
- Raises:
TypeError: Supported dataset types: snowpark.DataFrame, pandas.DataFrame.
- Args:
- dataset: Union[snowflake.snowpark.DataFrame, pandas.DataFrame]
Snowpark or Pandas DataFrame.
- output_cols_prefix: str
Prefix for the response columns
- Returns:
Output dataset with results of the decision function for the samples in input dataset.
- fit(dataset: Union[DataFrame, DataFrame]) LogisticRegression ¶
Fit the model according to the given training data For more details on this function, see sklearn.linear_model.LogisticRegression.fit
- Raises:
TypeError: Supported dataset types: snowpark.DataFrame, pandas.DataFrame.
- Args:
- dataset: Union[snowflake.snowpark.DataFrame, pandas.DataFrame]
Snowpark or Pandas DataFrame.
- Returns:
self
- fit_transform(dataset: Union[DataFrame, DataFrame]) Union[Any, ndarray[Any, dtype[Any]]] ¶
- 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 parameters for this transformer.
- Args:
- 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.
- Args:
- 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 class labels for samples in X For more details on this function, see sklearn.linear_model.LogisticRegression.predict
- Raises:
TypeError: Supported dataset types: snowpark.DataFrame, pandas.DataFrame.
- Args:
- dataset: Union[snowflake.snowpark.DataFrame, pandas.DataFrame]
Snowpark or Pandas DataFrame.
- Returns:
Transformed dataset.
- predict_log_proba(dataset: Union[DataFrame, DataFrame], output_cols_prefix: str = 'predict_log_proba_') Union[DataFrame, DataFrame] ¶
Probability estimates For more details on this function, see sklearn.linear_model.LogisticRegression.predict_proba
- Raises:
TypeError: Supported dataset types: snowpark.DataFrame, pandas.DataFrame.
- Args:
- dataset: Union[snowflake.snowpark.DataFrame, pandas.DataFrame]
Snowpark or Pandas DataFrame.
- output_cols_prefix: str
Prefix for the response columns
- Returns:
Output dataset with log probability of the sample for each class in the model.
- predict_proba(dataset: Union[DataFrame, DataFrame], output_cols_prefix: str = 'predict_proba_') Union[DataFrame, DataFrame] ¶
Probability estimates For more details on this function, see sklearn.linear_model.LogisticRegression.predict_proba
- Raises:
TypeError: Supported dataset types: snowpark.DataFrame, pandas.DataFrame.
- Args:
- 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.
- score(dataset: Union[DataFrame, DataFrame]) float ¶
Return the mean accuracy on the given test data and labels For more details on this function, see sklearn.linear_model.LogisticRegression.score
- Raises:
TypeError: Supported dataset types: snowpark.DataFrame, pandas.DataFrame.
- Args:
- dataset: Union[snowflake.snowpark.DataFrame, pandas.DataFrame]
Snowpark or Pandas DataFrame.
- Returns:
Score.
- set_drop_input_cols(drop_input_cols: Optional[bool] = False) None ¶
- set_input_cols(input_cols: Optional[Union[str, Iterable[str]]]) LogisticRegression ¶
Input columns setter.
- Args:
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.
- Args:
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.
- Args:
output_cols: A single output column or multiple output columns.
- Returns:
self
- set_params(**params: Dict[str, Any]) None ¶
Set the parameters of this transformer.
The method works on simple transformers as well as on nested objects. The latter have parameters of the form
<component>__<parameter>
so that it’s possible to update each component of a nested object.- Args:
**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.
- Args:
- 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.
- Args:
sample_weight_col: A single column that represents sample weight.
- Returns:
self
- to_sklearn() Any ¶
Get sklearn.linear_model.LogisticRegression object.
Attributes
- model_signatures¶
Returns model signature of current class.
- Raises:
exceptions.SnowflakeMLException: If estimator is not fitted, then model signature cannot be inferred
- Returns:
Dict[str, ModelSignature]: each method and its input output signature