snowflake.ml.modeling.linear_model.LogisticRegressionCV¶
- class snowflake.ml.modeling.linear_model.LogisticRegressionCV(*, Cs=10, fit_intercept=True, cv=None, dual=False, penalty='l2', scoring=None, solver='lbfgs', tol=0.0001, max_iter=100, class_weight=None, n_jobs=None, verbose=0, refit=True, intercept_scaling=1.0, multi_class='auto', random_state=None, l1_ratios=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 CV (aka logit, MaxEnt) classifier For more details on this class, see sklearn.linear_model.LogisticRegressionCV
- 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.
- Cs: int or list of floats, default=10
Each of the values in Cs describes the inverse of regularization strength. If Cs is as an int, then a grid of Cs values are chosen in a logarithmic scale between 1e-4 and 1e4. 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.
- cv: int or cross-validation generator, default=None
The default cross-validation generator used is Stratified K-Folds. If an integer is provided, then it is the number of folds used. See the module
sklearn.model_selection
module for the list of possible cross-validation objects.- 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.
- penalty: {‘l1’, ‘l2’, ‘elasticnet’}, default=’l2’
Specify the norm of the penalty:
‘l2’: add a L2 penalty term (used by default);
‘l1’: add a L1 penalty term;
‘elasticnet’: both L1 and L2 penalty terms are added.
- scoring: str or callable, default=None
A string (see model evaluation documentation) or a scorer callable object / function with signature
scorer(estimator, X, y)
. For a list of scoring functions that can be used, look atsklearn.metrics
. The default scoring option used is ‘accuracy’.
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’ might be slower in
LogisticRegressionCV
because it does not handle warm-starting. ‘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’]
‘liblinear’ - [‘l1’, ‘l2’]
‘newton-cg’ - [‘l2’]
‘newton-cholesky’ - [‘l2’]
‘sag’ - [‘l2’]
‘saga’ - [‘elasticnet’, ‘l1’, ‘l2’]
- tol: float, default=1e-4
Tolerance for stopping criteria.
- max_iter: int, default=100
Maximum number of iterations of the optimization algorithm.
- 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.
- n_jobs: int, default=None
Number of CPU cores used during the cross-validation loop.
None
means 1 unless in ajoblib.parallel_backend
context.-1
means using all processors. See Glossary for more details.- verbose: int, default=0
For the ‘liblinear’, ‘sag’ and ‘lbfgs’ solvers set verbose to any positive number for verbosity.
- refit: bool, default=True
If set to True, the scores are averaged across all folds, and the coefs and the C that corresponds to the best score is taken, and a final refit is done using these parameters. Otherwise the coefs, intercepts and C that correspond to the best scores across folds are averaged.
- 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.
- 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’.
- random_state: int, RandomState instance, default=None
Used when solver=’sag’, ‘saga’ or ‘liblinear’ to shuffle the data. Note that this only applies to the solver and not the cross-validation generator. See Glossary for details.
- l1_ratios: list of float, default=None
The list of Elastic-Net mixing parameter, with
0 <= l1_ratio <= 1
. Only used ifpenalty='elasticnet'
. A value of 0 is equivalent to usingpenalty='l2'
, while 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.LogisticRegressionCV.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]) LogisticRegressionCV ¶
Fit the model according to the given training data For more details on this function, see sklearn.linear_model.LogisticRegressionCV.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.LogisticRegressionCV.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.LogisticRegressionCV.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.LogisticRegressionCV.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 ¶
Score using the scoring option on the given test data and labels For more details on this function, see sklearn.linear_model.LogisticRegressionCV.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]]]) LogisticRegressionCV ¶
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.LogisticRegressionCV 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