Spec-Zone.ru › scikit-learn

Note

Go to the end to download the full example code or to run this example in your browser via JupyterLite or Binder.

Visualizing the probabilistic predictions of a VotingClassifier

Plot the predicted class probabilities in a toy dataset predicted by three different classifiers and averaged by the VotingClassifier.

First, three linear classifiers are initialized. Two are spline models with interaction terms, one using constant extrapolation and the other using periodic extrapolation. The third classifier is a Nystroem with the default “rbf” kernel.

In the first part of this example, these three classifiers are used to demonstrate soft-voting using VotingClassifier with weighted average. We set weights=[2, 1, 3], meaning the constant extrapolation spline model’s predictions are weighted twice as much as the periodic spline model’s, and the Nystroem model’s predictions are weighted three times as much as the periodic spline.

The second part demonstrates how soft predictions can be converted into hard predictions.

# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause

We first generate a noisy XOR dataset, which is a binary classification task.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.colors import ListedColormap

n_samples = 500
rng = np.random.default_rng(0)
feature_names = ["Feature #0", "Feature #1"]
common_scatter_plot_params = dict(
    cmap=ListedColormap(["tab:red", "tab:blue"]),
    edgecolor="white",
    linewidth=1,
)

xor = pd.DataFrame(
    np.random.RandomState(0).uniform(low=-1, high=1, size=(n_samples, 2)),
    columns=feature_names,
)
noise = rng.normal(loc=0, scale=0.1, size=(n_samples, 2))
target_xor = np.logical_xor(
    xor["Feature #0"] + noise[:, 0] > 0, xor["Feature #1"] + noise[:, 1] > 0
)

X = xor[feature_names]
y = target_xor.astype(np.int32)

fig, ax = plt.subplots()
ax.scatter(X["Feature #0"], X["Feature #1"], c=y, **common_scatter_plot_params)
ax.set_title("The XOR dataset")
plt.show()
The XOR dataset

Due to the inherent non-linear separability of the XOR dataset, tree-based models would often be preferred. However, appropriate feature engineering combined with a linear model can yield effective results, with the added benefit of producing better-calibrated probabilities for samples located in the transition regions affected by noise.

We define and fit the models on the whole dataset.

from sklearn.ensemble import VotingClassifier
from sklearn.kernel_approximation import Nystroem
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, SplineTransformer, StandardScaler

clf1 = make_pipeline(
    SplineTransformer(degree=2, n_knots=2),
    PolynomialFeatures(interaction_only=True),
    LogisticRegression(C=10),
)
clf2 = make_pipeline(
    SplineTransformer(
        degree=2,
        n_knots=4,
        extrapolation="periodic",
        include_bias=True,
    ),
    PolynomialFeatures(interaction_only=True),
    LogisticRegression(C=10),
)
clf3 = make_pipeline(
    StandardScaler(),
    Nystroem(gamma=2, random_state=0),
    LogisticRegression(C=10),
)
weights = [2, 1, 3]
eclf = VotingClassifier(
    estimators=[
        ("constant splines model", clf1),
        ("periodic splines model", clf2),
        ("nystroem model", clf3),
    ],
    voting="soft",
    weights=weights,
)

clf1.fit(X, y)
clf2.fit(X, y)
clf3.fit(X, y)
eclf.fit(X, y)
VotingClassifier(estimators=[('constant splines model',
                              Pipeline(steps=[('splinetransformer',
                                               SplineTransformer(degree=2,
                                                                 n_knots=2)),
                                              ('polynomialfeatures',
                                               PolynomialFeatures(interaction_only=True)),
                                              ('logisticregression',
                                               LogisticRegression(C=10))])),
                             ('periodic splines model',
                              Pipeline(steps=[('splinetransformer',
                                               SplineTransformer(degree=2,
                                                                 extrapolation='periodic',
                                                                 n_knots=4)),
                                              ('polynomialfeatures',
                                               PolynomialFeatures(interaction_only=True)),
                                              ('logisticregression',
                                               LogisticRegression(C=10))])),
                             ('nystroem model',
                              Pipeline(steps=[('standardscaler',
                                               StandardScaler()),
                                              ('nystroem',
                                               Nystroem(gamma=2,
                                                        random_state=0)),
                                              ('logisticregression',
                                               LogisticRegression(C=10))]))],
                 voting='soft', weights=[2, 1, 3])
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
estimators estimators: list of (str, estimator) tuples

Invoking the ``fit`` method on the ``VotingClassifier`` will fit clones
of those original estimators that will be stored in the class attribute
``self.estimators_``. An estimator can be set to ``'drop'`` using
:meth:`set_params`.

.. versionchanged:: 0.21
``'drop'`` is accepted. Using None was deprecated in 0.22 and
support was removed in 0.24.
[('constant splines model', ...), ('periodic splines model', ...), ...]
voting voting: {'hard', 'soft'}, default='hard'

If 'hard', uses predicted class labels for majority rule voting.
Else if 'soft', predicts the class label based on the argmax of
the sums of the predicted probabilities, which is recommended for
an ensemble of well-calibrated classifiers.
'soft'
weights weights: array-like of shape (n_classifiers,), default=None

Sequence of weights (`float` or `int`) to weight the occurrences of
predicted class labels (`hard` voting) or class probabilities
before averaging (`soft` voting). Uses uniform weights if `None`.
[2, 1, ...]
n_jobs n_jobs: int, default=None

The number of jobs to run in parallel for ``fit``.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.

.. versionadded:: 0.18
None
flatten_transform flatten_transform: bool, default=True

Affects shape of transform output only when voting='soft'
If voting='soft' and flatten_transform=True, transform method returns
matrix with shape (n_samples, n_classifiers * n_classes). If
flatten_transform=False, it returns
(n_classifiers, n_samples, n_classes).
True
verbose verbose: bool, default=False

If True, the time elapsed while fitting will be printed as it
is completed.

.. versionadded:: 0.23
False
Fitted attributes
Name Type Value
classes_ classes_: ndarray of shape (n_classes,)

The classes labels.
ndarray[int32](2,) [0,1]
estimators_ estimators_: list of classifiers

The collection of fitted sub-estimators as defined in ``estimators``
that are not 'drop'. Note that sub-estimators are always fitted on
integer-encoded labels (see ``le_`` attribute). When ``y`` contains
non-integer class labels (e.g. strings), use ``le_.inverse_transform``
to map predictions back to the original label space.
list [Pipeline(step...ssion(C=10))]), Pipeline(step...ssion(C=10))]), Pipeline(step...ssion(C=10))])]
feature_names_in_ feature_names_in_: ndarray of shape (`n_features_in_`,)

Names of features seen during :term:`fit`. Only defined if the
underlying estimators expose such an attribute when fit.

.. versionadded:: 1.0
ndarray[object](2,) ['Feature #0','Feature #1']
le_ le_: :class:`~sklearn.preprocessing.LabelEncoder`

Transformer used to encode the labels during fit and decode during
prediction. Sub-estimators in ``estimators_`` are fitted on the
integer-encoded labels produced by this encoder.
LabelEncoder LabelEncoder()
n_features_in_ n_features_in_: int

Number of features seen during :term:`fit`. Only defined if the
underlying classifier exposes such an attribute when fit.

.. versionadded:: 0.24
int 2
named_estimators_ named_estimators_: :class:`~sklearn.utils.Bunch`

Attribute to access any fitted sub-estimators by name.

.. versionadded:: 0.20
Bunch {'constant sp...sion(C=10))])}
Parameters
n_knots n_knots: int, default=5

Number of knots of the splines if `knots` equals one of
{'uniform', 'quantile'}. Must be larger or equal 2. Ignored if `knots`
is array-like.
2
degree degree: int, default=3

The polynomial degree of the spline basis. Must be a non-negative
integer.
2
knots knots: {'uniform', 'quantile'} or array-like of shape (n_knots, n_features), default='uniform'

Set knot positions such that first knot <= features <= last knot.

- If 'uniform', `n_knots` number of knots are distributed uniformly
from min to max values of the features.
- If 'quantile', they are distributed uniformly along the quantiles of
the features.
- If an array-like is given, it directly specifies the sorted knot
positions including the boundary knots. Note that, internally,
`degree` number of knots are added before the first knot, the same
after the last knot.
'uniform'
extrapolation extrapolation: {'error', 'constant', 'linear', 'continue', 'periodic'}, default='constant'

If 'error', values outside the min and max values of the training
features raises a `ValueError`. If 'constant', the value of the
splines at minimum and maximum value of the features is used as
constant extrapolation. If 'linear', a linear extrapolation is used.
If 'continue', the splines are extrapolated as is, i.e. option
`extrapolate=True` in :class:`scipy.interpolate.BSpline`. If
'periodic', periodic splines with a periodicity equal to the distance
between the first and last knot are used. Periodic splines enforce
equal function values and derivatives at the first and last knot.
For example, this makes it possible to avoid introducing an arbitrary
jump between Dec 31st and Jan 1st in spline features derived from a
naturally periodic "day-of-year" input feature. In this case it is
recommended to manually set the knot values to control the period.
'constant'
include_bias include_bias: bool, default=True

If False, then the last spline element inside the data range
of a feature is dropped. As B-splines sum to one over the spline basis
functions for each data point, they implicitly include a bias term,
i.e. a column of ones. It acts as an intercept term in a linear models.
True
order order: {'C', 'F'}, default='C'

Order of output array in the dense case. `'F'` order is faster to compute, but
may slow down subsequent estimators.
'C'
handle_missing handle_missing: {'error', 'zeros'}, default='error'

Specifies the way missing values are handled.

- 'error' : Raise an error if `np.nan` values are present during :meth:`fit`.
- 'zeros' : Encode splines of missing values with values `0`.

Note that `handle_missing='zeros'` differs from first imputing missing values
with zeros and then creating the spline basis. The latter creates spline basis
functions which have non-zero values at the missing values
whereas this option simply sets all spline basis function values to zero at the
missing values.

.. versionadded:: 1.8
'error'
sparse_output sparse_output: bool, default=False

Will return sparse CSR matrix if set True else will return an array.

.. versionadded:: 1.2
False
Fitted attributes
Name Type Value
bsplines_ bsplines_: list of shape (n_features,)

List of BSplines objects, one for each feature.
list [<scipy.interp...x784129da8dd0>, <scipy.interp...x784129da8f50>]
feature_names_in_ feature_names_in_: ndarray of shape (`n_features_in_`,)

Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.

.. versionadded:: 1.0
ndarray[object](2,) ['Feature #0','Feature #1']
n_features_in_ n_features_in_: int

The total number of input features.
int 2
n_features_out_ n_features_out_: int

The total number of output features, which is computed as
`n_features * n_splines`, where `n_splines` is
the number of bases elements of the B-splines,
`n_knots + degree - 1` for non-periodic splines and
`n_knots - 1` for periodic ones.
If `include_bias=False`, then it is only
`n_features * (n_splines - 1)`.
int 6
6 features
Feature #0_sp_0
Feature #0_sp_1
Feature #0_sp_2
Feature #1_sp_0
Feature #1_sp_1
Feature #1_sp_2
Parameters
interaction_only interaction_only: bool, default=False

If `True`, only interaction features are produced: features that are
products of at most `degree` *distinct* input features, i.e. terms with
power of 2 or higher of the same input feature are excluded:

- included: `x[0]`, `x[1]`, `x[0] * x[1]`, etc.
- excluded: `x[0] ** 2`, `x[0] ** 2 * x[1]`, etc.
True
degree degree: int or tuple (min_degree, max_degree), default=2

If a single int is given, it specifies the maximal degree of the
polynomial features. If a tuple `(min_degree, max_degree)` is passed,
then `min_degree` is the minimum and `max_degree` is the maximum
polynomial degree of the generated features. Note that `min_degree=0`
and `min_degree=1` are equivalent as outputting the degree zero term is
determined by `include_bias`.
2
include_bias include_bias: bool, default=True

If `True` (default), then include a bias column, the feature in which
all polynomial powers are zero (i.e. a column of ones - acts as an
intercept term in a linear model).
True
order order: {'C', 'F'}, default='C'

Order of output array in the dense case. `'F'` order is faster to
compute, but may slow down subsequent estimators.

.. versionadded:: 0.21
'C'
Fitted attributes
Name Type Value
n_features_in_ n_features_in_: int

Number of features seen during :term:`fit`.

.. versionadded:: 0.24
int 6
n_output_features_ n_output_features_: int

The total number of polynomial output features. The number of output
features is computed by iterating over all suitably sized combinations
of input features.
int 22
powers_ powers_: ndarray of shape (`n_output_features_`, `n_features_in_`)

`powers_[i, j]` is the exponent of the jth input in the ith output.
ndarray[int64](22, 6) [[0,0,0,0,0,0], [1,0,0,0,0,0], [0,1,0,0,0,0], ..., [0,0,0,1,1,0], [0,0,0,1,0,1], [0,0,0,0,1,1]]
22 features
1
x0
x1
x2
x3
x4
x5
x0 x1
x0 x2
x0 x3
x0 x4
x0 x5
x1 x2
x1 x3
x1 x4
x1 x5
x2 x3
x2 x4
x2 x5
x3 x4
x3 x5
x4 x5
Parameters
C C: float, default=1.0

Inverse of regularization strength; must be a positive float.
Like in support vector machines, smaller values specify stronger
regularization. `C=np.inf` results in unpenalized logistic regression.
For a visual example on the effect of tuning the `C` parameter
with an L1 penalty, see:
:ref:`sphx_glr_auto_examples_linear_model_plot_logistic_path.py`.
10
penalty penalty: {'l1', 'l2', 'elasticnet', None}, default='l2'

Specify the norm of the penalty:

- `None`: no penalty is added;
- `'l2'`: add an L2 penalty term and it is the default choice;
- `'l1'`: add an L1 penalty term;
- `'elasticnet'`: both L1 and L2 penalty terms are added.

.. warning::
Some penalties may not work with some solvers. See the parameter
`solver` below, to know the compatibility between the penalty and
solver.

.. versionadded:: 0.19
l1 penalty with SAGA solver (allowing 'multinomial' + L1)

.. deprecated:: 1.8
`penalty` was deprecated in version 1.8 and will be removed in 1.10.
Use `l1_ratio` and `C` instead. `l1_ratio=0` for `penalty='l2'`,
`l1_ratio=1` for `penalty='l1'`, `l1_ratio` set to any float between 0 and 1
for `penalty='elasticnet'`, and `C=np.inf` for `penalty=None`.
'deprecated'
l1_ratio l1_ratio: float, default=0.0

The Elastic-Net mixing parameter, with `0 <= l1_ratio <= 1`. Setting
`l1_ratio=1` gives a pure L1-penalty, setting `l1_ratio=0` a pure L2-penalty.
Any value between 0 and 1 gives an Elastic-Net penalty of the form
`l1_ratio * L1 + (1 - l1_ratio) * L2`.

.. warning::
Certain values of `l1_ratio`, i.e. some penalties, may not work with some
solvers. See the parameter `solver` below, to know the compatibility between
the penalty and solver.

.. versionchanged:: 1.8
Default value changed from None to 0.0.

.. deprecated:: 1.8
`None` is deprecated and will be removed in version 1.10. Always use
`l1_ratio` to specify the penalty type.
0.0
dual dual: bool, default=False

Dual (constrained) or primal (regularized, see also
:ref:`this equation <regularized-logistic-loss>`) formulation. Dual formulation
is only implemented for l2 penalty with liblinear solver. Prefer `dual=False`
when n_samples > n_features.
False
tol tol: float, default=1e-4

Tolerance for stopping criteria.
0.0001
fit_intercept fit_intercept: bool, default=True

Specifies if a constant (a.k.a. bias or intercept) should be
added to the decision function.
True
intercept_scaling 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 or 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.
1
class_weight 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.

.. versionadded:: 0.17
*class_weight='balanced'*
None
random_state random_state: int, RandomState instance, default=None

Used when ``solver`` == 'sag', 'saga' or 'liblinear' to shuffle the
data. See :term:`Glossary <random_state>` for details.
None
solver 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:

- 'lbfgs' is a good default solver because it works reasonably well for a wide
class of problems.
- For :term:`multiclass` problems (`n_classes >= 3`), all solvers except
'liblinear' minimize the full multinomial loss, 'liblinear' will raise an
error.
- 'newton-cholesky' is a good choice for
`n_samples` >> `n_features * n_classes`, especially with one-hot encoded
categorical features with rare categories. Be aware that the memory usage
of this solver has a quadratic dependency on `n_features * n_classes`
because it explicitly computes the full Hessian matrix.
- For small datasets, 'liblinear' is a good choice, whereas 'sag'
and 'saga' are faster for large ones;
- 'liblinear' can only handle binary classification by default. To apply a
one-versus-rest scheme for the multiclass setting one can wrap it with the
:class:`~sklearn.multiclass.OneVsRestClassifier`.

.. warning::
The choice of the algorithm depends on the penalty chosen (`l1_ratio=0`
for L2-penalty, `l1_ratio=1` for L1-penalty and `0 < l1_ratio < 1` for
Elastic-Net) and on (multinomial) multiclass support:

================= ======================== ======================
solver l1_ratio multinomial multiclass
================= ======================== ======================
'lbfgs' l1_ratio=0 yes
'liblinear' l1_ratio=1 or l1_ratio=0 no
'newton-cg' l1_ratio=0 yes
'newton-cholesky' l1_ratio=0 yes
'sag' l1_ratio=0 yes
'saga' 0<=l1_ratio<=1 yes
================= ======================== ======================

.. note::
'sag' and 'saga' fast convergence is only guaranteed on features
with approximately the same scale. You can preprocess the data with
a scaler from :mod:`sklearn.preprocessing`.

.. seealso::
Refer to the :ref:`User Guide <Logistic_regression>` for more
information regarding :class:`LogisticRegression` and more specifically the
:ref:`Table <logistic_regression_solvers>`
summarizing solver/penalty supports.

.. versionadded:: 0.17
Stochastic Average Gradient (SAG) descent solver. Multinomial support in
version 0.18.
.. versionadded:: 0.19
SAGA solver.
.. versionchanged:: 0.22
The default solver changed from 'liblinear' to 'lbfgs' in 0.22.
.. versionadded:: 1.2
newton-cholesky solver. Multinomial support in version 1.6.
'lbfgs'
max_iter max_iter: int, default=100

Maximum number of iterations taken for the solvers to converge.
100
verbose verbose: int, default=0

For the liblinear and lbfgs solvers set verbose to any positive
number for verbosity.
0
warm_start 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 :term:`the Glossary <warm_start>`.

.. versionadded:: 0.17
*warm_start* to support *lbfgs*, *newton-cg*, *sag*, *saga* solvers.
False
n_jobs n_jobs: int, default=None

Does not have any effect.

.. deprecated:: 1.8
`n_jobs` is deprecated in version 1.8 and will be removed in 1.10.
None
Fitted attributes
Name Type Value
classes_ classes_: ndarray of shape (n_classes, )

A list of class labels known to the classifier.
ndarray[int32](2,) [0,1]
coef_ coef_: ndarray or CSR matrix of shape (1, n_features) or (n_classes, n_features)

Coefficients of the features in the decision function.

`coef_` is of shape (1, n_features) when the given problem is binary.

By default, it will be created as a dense array, but can be turned to
sparse (CSR format) through :meth:`sparsify` (which can be beneficial
under L1 regularization when many coefficients are zero), and back to
dense through :meth:`densify`.
ndarray[float64](1, 22) [[ 0.07,-0.36, 0.71,...,-0.73, 0.03, 0.64]]
intercept_ intercept_: ndarray of shape (1,) or (n_classes,)

Intercept (a.k.a. bias) added to the decision function.

If `fit_intercept` is set to False, the intercept is set to zero.
`intercept_` is of shape (1,) when the given problem is binary.
ndarray[float64](1,) [0.12]
n_features_in_ n_features_in_: int

Number of features seen during :term:`fit`.

.. versionadded:: 0.24
int 22
n_iter_ n_iter_: ndarray of shape (1, )

Actual number of iterations for all classes.

.. versionchanged:: 0.20

In SciPy <= 1.0.0 the number of lbfgs iterations may exceed
``max_iter``. ``n_iter_`` will now report at most ``max_iter``.
ndarray[int32](1,) [16]
Parameters
n_knots n_knots: int, default=5

Number of knots of the splines if `knots` equals one of
{'uniform', 'quantile'}. Must be larger or equal 2. Ignored if `knots`
is array-like.
4
degree degree: int, default=3

The polynomial degree of the spline basis. Must be a non-negative
integer.
2
extrapolation extrapolation: {'error', 'constant', 'linear', 'continue', 'periodic'}, default='constant'

If 'error', values outside the min and max values of the training
features raises a `ValueError`. If 'constant', the value of the
splines at minimum and maximum value of the features is used as
constant extrapolation. If 'linear', a linear extrapolation is used.
If 'continue', the splines are extrapolated as is, i.e. option
`extrapolate=True` in :class:`scipy.interpolate.BSpline`. If
'periodic', periodic splines with a periodicity equal to the distance
between the first and last knot are used. Periodic splines enforce
equal function values and derivatives at the first and last knot.
For example, this makes it possible to avoid introducing an arbitrary
jump between Dec 31st and Jan 1st in spline features derived from a
naturally periodic "day-of-year" input feature. In this case it is
recommended to manually set the knot values to control the period.
'periodic'
knots knots: {'uniform', 'quantile'} or array-like of shape (n_knots, n_features), default='uniform'

Set knot positions such that first knot <= features <= last knot.

- If 'uniform', `n_knots` number of knots are distributed uniformly
from min to max values of the features.
- If 'quantile', they are distributed uniformly along the quantiles of
the features.
- If an array-like is given, it directly specifies the sorted knot
positions including the boundary knots. Note that, internally,
`degree` number of knots are added before the first knot, the same
after the last knot.
'uniform'
include_bias include_bias: bool, default=True

If False, then the last spline element inside the data range
of a feature is dropped. As B-splines sum to one over the spline basis
functions for each data point, they implicitly include a bias term,
i.e. a column of ones. It acts as an intercept term in a linear models.
True
order order: {'C', 'F'}, default='C'

Order of output array in the dense case. `'F'` order is faster to compute, but
may slow down subsequent estimators.
'C'
handle_missing handle_missing: {'error', 'zeros'}, default='error'

Specifies the way missing values are handled.

- 'error' : Raise an error if `np.nan` values are present during :meth:`fit`.
- 'zeros' : Encode splines of missing values with values `0`.

Note that `handle_missing='zeros'` differs from first imputing missing values
with zeros and then creating the spline basis. The latter creates spline basis
functions which have non-zero values at the missing values
whereas this option simply sets all spline basis function values to zero at the
missing values.

.. versionadded:: 1.8
'error'
sparse_output sparse_output: bool, default=False

Will return sparse CSR matrix if set True else will return an array.

.. versionadded:: 1.2
False
Fitted attributes
Name Type Value
bsplines_ bsplines_: list of shape (n_features,)

List of BSplines objects, one for each feature.
list [<scipy.interp...x784129da92d0>, <scipy.interp...x784129f772d0>]
feature_names_in_ feature_names_in_: ndarray of shape (`n_features_in_`,)

Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.

.. versionadded:: 1.0
ndarray[object](2,) ['Feature #0','Feature #1']
n_features_in_ n_features_in_: int

The total number of input features.
int 2
n_features_out_ n_features_out_: int

The total number of output features, which is computed as
`n_features * n_splines`, where `n_splines` is
the number of bases elements of the B-splines,
`n_knots + degree - 1` for non-periodic splines and
`n_knots - 1` for periodic ones.
If `include_bias=False`, then it is only
`n_features * (n_splines - 1)`.
int 6
6 features
Feature #0_sp_0
Feature #0_sp_1
Feature #0_sp_2
Feature #1_sp_0
Feature #1_sp_1
Feature #1_sp_2
Parameters
interaction_only interaction_only: bool, default=False

If `True`, only interaction features are produced: features that are
products of at most `degree` *distinct* input features, i.e. terms with
power of 2 or higher of the same input feature are excluded:

- included: `x[0]`, `x[1]`, `x[0] * x[1]`, etc.
- excluded: `x[0] ** 2`, `x[0] ** 2 * x[1]`, etc.
True
degree degree: int or tuple (min_degree, max_degree), default=2

If a single int is given, it specifies the maximal degree of the
polynomial features. If a tuple `(min_degree, max_degree)` is passed,
then `min_degree` is the minimum and `max_degree` is the maximum
polynomial degree of the generated features. Note that `min_degree=0`
and `min_degree=1` are equivalent as outputting the degree zero term is
determined by `include_bias`.
2
include_bias include_bias: bool, default=True

If `True` (default), then include a bias column, the feature in which
all polynomial powers are zero (i.e. a column of ones - acts as an
intercept term in a linear model).
True
order order: {'C', 'F'}, default='C'

Order of output array in the dense case. `'F'` order is faster to
compute, but may slow down subsequent estimators.

.. versionadded:: 0.21
'C'
Fitted attributes
Name Type Value
n_features_in_ n_features_in_: int

Number of features seen during :term:`fit`.

.. versionadded:: 0.24
int 6
n_output_features_ n_output_features_: int

The total number of polynomial output features. The number of output
features is computed by iterating over all suitably sized combinations
of input features.
int 22
powers_ powers_: ndarray of shape (`n_output_features_`, `n_features_in_`)

`powers_[i, j]` is the exponent of the jth input in the ith output.
ndarray[int64](22, 6) [[0,0,0,0,0,0], [1,0,0,0,0,0], [0,1,0,0,0,0], ..., [0,0,0,1,1,0], [0,0,0,1,0,1], [0,0,0,0,1,1]]
22 features
1
x0
x1
x2
x3
x4
x5
x0 x1
x0 x2
x0 x3
x0 x4
x0 x5
x1 x2
x1 x3
x1 x4
x1 x5
x2 x3
x2 x4
x2 x5
x3 x4
x3 x5
x4 x5
Parameters
C C: float, default=1.0

Inverse of regularization strength; must be a positive float.
Like in support vector machines, smaller values specify stronger
regularization. `C=np.inf` results in unpenalized logistic regression.
For a visual example on the effect of tuning the `C` parameter
with an L1 penalty, see:
:ref:`sphx_glr_auto_examples_linear_model_plot_logistic_path.py`.
10
penalty penalty: {'l1', 'l2', 'elasticnet', None}, default='l2'

Specify the norm of the penalty:

- `None`: no penalty is added;
- `'l2'`: add an L2 penalty term and it is the default choice;
- `'l1'`: add an L1 penalty term;
- `'elasticnet'`: both L1 and L2 penalty terms are added.

.. warning::
Some penalties may not work with some solvers. See the parameter
`solver` below, to know the compatibility between the penalty and
solver.

.. versionadded:: 0.19
l1 penalty with SAGA solver (allowing 'multinomial' + L1)

.. deprecated:: 1.8
`penalty` was deprecated in version 1.8 and will be removed in 1.10.
Use `l1_ratio` and `C` instead. `l1_ratio=0` for `penalty='l2'`,
`l1_ratio=1` for `penalty='l1'`, `l1_ratio` set to any float between 0 and 1
for `penalty='elasticnet'`, and `C=np.inf` for `penalty=None`.
'deprecated'
l1_ratio l1_ratio: float, default=0.0

The Elastic-Net mixing parameter, with `0 <= l1_ratio <= 1`. Setting
`l1_ratio=1` gives a pure L1-penalty, setting `l1_ratio=0` a pure L2-penalty.
Any value between 0 and 1 gives an Elastic-Net penalty of the form
`l1_ratio * L1 + (1 - l1_ratio) * L2`.

.. warning::
Certain values of `l1_ratio`, i.e. some penalties, may not work with some
solvers. See the parameter `solver` below, to know the compatibility between
the penalty and solver.

.. versionchanged:: 1.8
Default value changed from None to 0.0.

.. deprecated:: 1.8
`None` is deprecated and will be removed in version 1.10. Always use
`l1_ratio` to specify the penalty type.
0.0
dual dual: bool, default=False

Dual (constrained) or primal (regularized, see also
:ref:`this equation <regularized-logistic-loss>`) formulation. Dual formulation
is only implemented for l2 penalty with liblinear solver. Prefer `dual=False`
when n_samples > n_features.
False
tol tol: float, default=1e-4

Tolerance for stopping criteria.
0.0001
fit_intercept fit_intercept: bool, default=True

Specifies if a constant (a.k.a. bias or intercept) should be
added to the decision function.
True
intercept_scaling 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 or 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.
1
class_weight 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.

.. versionadded:: 0.17
*class_weight='balanced'*
None
random_state random_state: int, RandomState instance, default=None

Used when ``solver`` == 'sag', 'saga' or 'liblinear' to shuffle the
data. See :term:`Glossary <random_state>` for details.
None
solver 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:

- 'lbfgs' is a good default solver because it works reasonably well for a wide
class of problems.
- For :term:`multiclass` problems (`n_classes >= 3`), all solvers except
'liblinear' minimize the full multinomial loss, 'liblinear' will raise an
error.
- 'newton-cholesky' is a good choice for
`n_samples` >> `n_features * n_classes`, especially with one-hot encoded
categorical features with rare categories. Be aware that the memory usage
of this solver has a quadratic dependency on `n_features * n_classes`
because it explicitly computes the full Hessian matrix.
- For small datasets, 'liblinear' is a good choice, whereas 'sag'
and 'saga' are faster for large ones;
- 'liblinear' can only handle binary classification by default. To apply a
one-versus-rest scheme for the multiclass setting one can wrap it with the
:class:`~sklearn.multiclass.OneVsRestClassifier`.

.. warning::
The choice of the algorithm depends on the penalty chosen (`l1_ratio=0`
for L2-penalty, `l1_ratio=1` for L1-penalty and `0 < l1_ratio < 1` for
Elastic-Net) and on (multinomial) multiclass support:

================= ======================== ======================
solver l1_ratio multinomial multiclass
================= ======================== ======================
'lbfgs' l1_ratio=0 yes
'liblinear' l1_ratio=1 or l1_ratio=0 no
'newton-cg' l1_ratio=0 yes
'newton-cholesky' l1_ratio=0 yes
'sag' l1_ratio=0 yes
'saga' 0<=l1_ratio<=1 yes
================= ======================== ======================

.. note::
'sag' and 'saga' fast convergence is only guaranteed on features
with approximately the same scale. You can preprocess the data with
a scaler from :mod:`sklearn.preprocessing`.

.. seealso::
Refer to the :ref:`User Guide <Logistic_regression>` for more
information regarding :class:`LogisticRegression` and more specifically the
:ref:`Table <logistic_regression_solvers>`
summarizing solver/penalty supports.

.. versionadded:: 0.17
Stochastic Average Gradient (SAG) descent solver. Multinomial support in
version 0.18.
.. versionadded:: 0.19
SAGA solver.
.. versionchanged:: 0.22
The default solver changed from 'liblinear' to 'lbfgs' in 0.22.
.. versionadded:: 1.2
newton-cholesky solver. Multinomial support in version 1.6.
'lbfgs'
max_iter max_iter: int, default=100

Maximum number of iterations taken for the solvers to converge.
100
verbose verbose: int, default=0

For the liblinear and lbfgs solvers set verbose to any positive
number for verbosity.
0
warm_start 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 :term:`the Glossary <warm_start>`.

.. versionadded:: 0.17
*warm_start* to support *lbfgs*, *newton-cg*, *sag*, *saga* solvers.
False
n_jobs n_jobs: int, default=None

Does not have any effect.

.. deprecated:: 1.8
`n_jobs` is deprecated in version 1.8 and will be removed in 1.10.
None
Fitted attributes
Name Type Value
classes_ classes_: ndarray of shape (n_classes, )

A list of class labels known to the classifier.
ndarray[int32](2,) [0,1]
coef_ coef_: ndarray or CSR matrix of shape (1, n_features) or (n_classes, n_features)

Coefficients of the features in the decision function.

`coef_` is of shape (1, n_features) when the given problem is binary.

By default, it will be created as a dense array, but can be turned to
sparse (CSR format) through :meth:`sparsify` (which can be beneficial
under L1 regularization when many coefficients are zero), and back to
dense through :meth:`densify`.
ndarray[float64](1, 22) [[-0.01,-0.2 ,-0.54,..., 0.91, 2.07,-2.42]]
intercept_ intercept_: ndarray of shape (1,) or (n_classes,)

Intercept (a.k.a. bias) added to the decision function.

If `fit_intercept` is set to False, the intercept is set to zero.
`intercept_` is of shape (1,) when the given problem is binary.
ndarray[float64](1,) [-0.]
n_features_in_ n_features_in_: int

Number of features seen during :term:`fit`.

.. versionadded:: 0.24
int 22
n_iter_ n_iter_: ndarray of shape (1, )

Actual number of iterations for all classes.

.. versionchanged:: 0.20

In SciPy <= 1.0.0 the number of lbfgs iterations may exceed
``max_iter``. ``n_iter_`` will now report at most ``max_iter``.
ndarray[int32](1,) [22]
Parameters
copy copy: bool, default=True

If False, try to avoid a copy and do inplace scaling instead.
This is not guaranteed to always work inplace; e.g. if the data is
not a NumPy array or scipy.sparse CSR matrix, a copy may still be
returned.
True
with_mean with_mean: bool, default=True

If True, center the data before scaling.
This does not work (and will raise an exception) when attempted on
sparse matrices, because centering them entails building a dense
matrix which in common use cases is likely to be too large to fit in
memory.
True
with_std with_std: bool, default=True

If True, scale the data to unit variance (or equivalently,
unit standard deviation).
True
Fitted attributes
Name Type Value
feature_names_in_ feature_names_in_: ndarray of shape (`n_features_in_`,)

Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.

.. versionadded:: 1.0
ndarray[object](2,) ['Feature #0','Feature #1']
mean_ mean_: ndarray of shape (n_features,) or None

The mean value for each feature in the training set.
Equal to ``None`` when ``with_mean=False`` and ``with_std=False``.
ndarray[float64](2,) [ 0.01,-0.02]
n_features_in_ n_features_in_: int

Number of features seen during :term:`fit`.

.. versionadded:: 0.24
int 2
n_samples_seen_ n_samples_seen_: int or ndarray of shape (n_features,)

The number of samples processed by the estimator for each feature.
If there are no missing samples, the ``n_samples_seen`` will be an
integer, otherwise it will be an array of dtype int. If
`sample_weights` are used it will be a float (if no missing data)
or an array of dtype float that sums the weights seen so far.
Will be reset on new calls to fit, but increments across
``partial_fit`` calls.
float64 500
scale_ scale_: ndarray of shape (n_features,) or None

Per feature relative scaling of the data to achieve zero mean and unit
variance. Generally this is calculated using `np.sqrt(var_)`. If a
variance is zero, we can't achieve unit variance, and the data is left
as-is, giving a scaling factor of 1. `scale_` is equal to `None`
when `with_std=False`.

.. versionadded:: 0.17
*scale_*
ndarray[float64](2,) [0.57,0.59]
var_ var_: ndarray of shape (n_features,) or None

The variance for each feature in the training set. Used to compute
`scale_`. Equal to ``None`` when ``with_mean=False`` and
``with_std=False``.
ndarray[float64](2,) [0.33,0.35]
2 features
Feature #0
Feature #1
Parameters
gamma gamma: float, default=None

Gamma parameter for the RBF, laplacian, polynomial, exponential chi2
and sigmoid kernels. Interpretation of the default value is left to
the kernel; see the documentation for sklearn.metrics.pairwise.
Ignored by other kernels.
2
random_state random_state: int, RandomState instance or None, default=None

Pseudo-random number generator to control the uniform sampling without
replacement of `n_components` of the training data to construct the
basis kernel.
Pass an int for reproducible output across multiple function calls.
See :term:`Glossary <random_state>`.
0
kernel kernel: str or callable, default='rbf'

Kernel map to be approximated. A callable should accept two arguments
and the keyword arguments passed to this object as `kernel_params`, and
should return a floating point number.
'rbf'
coef0 coef0: float, default=None

Zero coefficient for polynomial and sigmoid kernels.
Ignored by other kernels.
None
degree degree: float, default=None

Degree of the polynomial kernel. Ignored by other kernels.
None
kernel_params kernel_params: dict, default=None

Additional parameters (keyword arguments) for kernel function passed
as callable object.
None
n_components n_components: int, default=100

Number of features to construct.
How many data points will be used to construct the mapping.
100
n_jobs n_jobs: int, default=None

The number of jobs to use for the computation. This works by breaking
down the kernel matrix into `n_jobs` even slices and computing them in
parallel.

``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.

.. versionadded:: 0.24
None
Fitted attributes
Name Type Value
component_indices_ component_indices_: ndarray of shape (n_components)

Indices of ``components_`` in the training set.
ndarray[int64](100,) [ 90,254,283,...,440, 60,208]
components_ components_: ndarray of shape (n_components, n_features)

Subset of training points used to construct the feature map.
ndarray[float64](100, 2) [[-1.18, 0.45], [-0.87,-0.15], [ 0.13, 1.48], ..., [ 0.78,-0.68], [ 0.77, 0.04], [-1.3 ,-1.62]]
n_features_in_ n_features_in_: int

Number of features seen during :term:`fit`.

.. versionadded:: 0.24
int 2
normalization_ normalization_: ndarray of shape (n_components, n_components)

Normalization matrix needed for embedding.
Square root of the kernel matrix on ``components_``.
ndarray[float64](100, 100) [[1179.99, 29.85, 6.59,..., 2.13, -0.24, -0.02], [ 29.85, 31.15, -0.73,..., 0.64, -1.17, 0.04], [ 6.59, -0.73, 31.71,..., 0.49, -2.09, 0.02], ..., [ 2.13, 0.64, 0.49,..., 12.36, -3.56, 0.02], [ -0.24, -1.17, -2.09,..., -3.56, 31.67, 0. ], [ -0.02, 0.04, 0.02,..., 0.02, 0. , 8.87]]
100 features
nystroem0
nystroem1
nystroem2
nystroem3
nystroem4
nystroem5
nystroem6
nystroem7
nystroem8
nystroem9
nystroem10
nystroem11
nystroem12
nystroem13
nystroem14
nystroem15
nystroem16
nystroem17
nystroem18
nystroem19
nystroem20
nystroem21
nystroem22
nystroem23
nystroem24
nystroem25
nystroem26
nystroem27
nystroem28
nystroem29
nystroem30
nystroem31
nystroem32
nystroem33
nystroem34
nystroem35
nystroem36
nystroem37
nystroem38
nystroem39
nystroem40
nystroem41
nystroem42
nystroem43
nystroem44
nystroem45
nystroem46
nystroem47
nystroem48
nystroem49
nystroem50
nystroem51
nystroem52
nystroem53
nystroem54
nystroem55
nystroem56
nystroem57
nystroem58
nystroem59
nystroem60
nystroem61
nystroem62
nystroem63
nystroem64
nystroem65
nystroem66
nystroem67
nystroem68
nystroem69
nystroem70
nystroem71
nystroem72
nystroem73
nystroem74
nystroem75
nystroem76
nystroem77
nystroem78
nystroem79
nystroem80
nystroem81
nystroem82
nystroem83
nystroem84
nystroem85
nystroem86
nystroem87
nystroem88
nystroem89
nystroem90
nystroem91
nystroem92
nystroem93
nystroem94
nystroem95
nystroem96
nystroem97
nystroem98
nystroem99
Parameters
C C: float, default=1.0

Inverse of regularization strength; must be a positive float.
Like in support vector machines, smaller values specify stronger
regularization. `C=np.inf` results in unpenalized logistic regression.
For a visual example on the effect of tuning the `C` parameter
with an L1 penalty, see:
:ref:`sphx_glr_auto_examples_linear_model_plot_logistic_path.py`.
10
penalty penalty: {'l1', 'l2', 'elasticnet', None}, default='l2'

Specify the norm of the penalty:

- `None`: no penalty is added;
- `'l2'`: add an L2 penalty term and it is the default choice;
- `'l1'`: add an L1 penalty term;
- `'elasticnet'`: both L1 and L2 penalty terms are added.

.. warning::
Some penalties may not work with some solvers. See the parameter
`solver` below, to know the compatibility between the penalty and
solver.

.. versionadded:: 0.19
l1 penalty with SAGA solver (allowing 'multinomial' + L1)

.. deprecated:: 1.8
`penalty` was deprecated in version 1.8 and will be removed in 1.10.
Use `l1_ratio` and `C` instead. `l1_ratio=0` for `penalty='l2'`,
`l1_ratio=1` for `penalty='l1'`, `l1_ratio` set to any float between 0 and 1
for `penalty='elasticnet'`, and `C=np.inf` for `penalty=None`.
'deprecated'
l1_ratio l1_ratio: float, default=0.0

The Elastic-Net mixing parameter, with `0 <= l1_ratio <= 1`. Setting
`l1_ratio=1` gives a pure L1-penalty, setting `l1_ratio=0` a pure L2-penalty.
Any value between 0 and 1 gives an Elastic-Net penalty of the form
`l1_ratio * L1 + (1 - l1_ratio) * L2`.

.. warning::
Certain values of `l1_ratio`, i.e. some penalties, may not work with some
solvers. See the parameter `solver` below, to know the compatibility between
the penalty and solver.

.. versionchanged:: 1.8
Default value changed from None to 0.0.

.. deprecated:: 1.8
`None` is deprecated and will be removed in version 1.10. Always use
`l1_ratio` to specify the penalty type.
0.0
dual dual: bool, default=False

Dual (constrained) or primal (regularized, see also
:ref:`this equation <regularized-logistic-loss>`) formulation. Dual formulation
is only implemented for l2 penalty with liblinear solver. Prefer `dual=False`
when n_samples > n_features.
False
tol tol: float, default=1e-4

Tolerance for stopping criteria.
0.0001
fit_intercept fit_intercept: bool, default=True

Specifies if a constant (a.k.a. bias or intercept) should be
added to the decision function.
True
intercept_scaling 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 or 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.
1
class_weight 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.

.. versionadded:: 0.17
*class_weight='balanced'*
None
random_state random_state: int, RandomState instance, default=None

Used when ``solver`` == 'sag', 'saga' or 'liblinear' to shuffle the
data. See :term:`Glossary <random_state>` for details.
None
solver 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:

- 'lbfgs' is a good default solver because it works reasonably well for a wide
class of problems.
- For :term:`multiclass` problems (`n_classes >= 3`), all solvers except
'liblinear' minimize the full multinomial loss, 'liblinear' will raise an
error.
- 'newton-cholesky' is a good choice for
`n_samples` >> `n_features * n_classes`, especially with one-hot encoded
categorical features with rare categories. Be aware that the memory usage
of this solver has a quadratic dependency on `n_features * n_classes`
because it explicitly computes the full Hessian matrix.
- For small datasets, 'liblinear' is a good choice, whereas 'sag'
and 'saga' are faster for large ones;
- 'liblinear' can only handle binary classification by default. To apply a
one-versus-rest scheme for the multiclass setting one can wrap it with the
:class:`~sklearn.multiclass.OneVsRestClassifier`.

.. warning::
The choice of the algorithm depends on the penalty chosen (`l1_ratio=0`
for L2-penalty, `l1_ratio=1` for L1-penalty and `0 < l1_ratio < 1` for
Elastic-Net) and on (multinomial) multiclass support:

================= ======================== ======================
solver l1_ratio multinomial multiclass
================= ======================== ======================
'lbfgs' l1_ratio=0 yes
'liblinear' l1_ratio=1 or l1_ratio=0 no
'newton-cg' l1_ratio=0 yes
'newton-cholesky' l1_ratio=0 yes
'sag' l1_ratio=0 yes
'saga' 0<=l1_ratio<=1 yes
================= ======================== ======================

.. note::
'sag' and 'saga' fast convergence is only guaranteed on features
with approximately the same scale. You can preprocess the data with
a scaler from :mod:`sklearn.preprocessing`.

.. seealso::
Refer to the :ref:`User Guide <Logistic_regression>` for more
information regarding :class:`LogisticRegression` and more specifically the
:ref:`Table <logistic_regression_solvers>`
summarizing solver/penalty supports.

.. versionadded:: 0.17
Stochastic Average Gradient (SAG) descent solver. Multinomial support in
version 0.18.
.. versionadded:: 0.19
SAGA solver.
.. versionchanged:: 0.22
The default solver changed from 'liblinear' to 'lbfgs' in 0.22.
.. versionadded:: 1.2
newton-cholesky solver. Multinomial support in version 1.6.
'lbfgs'
max_iter max_iter: int, default=100

Maximum number of iterations taken for the solvers to converge.
100
verbose verbose: int, default=0

For the liblinear and lbfgs solvers set verbose to any positive
number for verbosity.
0
warm_start 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 :term:`the Glossary <warm_start>`.

.. versionadded:: 0.17
*warm_start* to support *lbfgs*, *newton-cg*, *sag*, *saga* solvers.
False
n_jobs n_jobs: int, default=None

Does not have any effect.

.. deprecated:: 1.8
`n_jobs` is deprecated in version 1.8 and will be removed in 1.10.
None
Fitted attributes
Name Type Value
classes_ classes_: ndarray of shape (n_classes, )

A list of class labels known to the classifier.
ndarray[int32](2,) [0,1]
coef_ coef_: ndarray or CSR matrix of shape (1, n_features) or (n_classes, n_features)

Coefficients of the features in the decision function.

`coef_` is of shape (1, n_features) when the given problem is binary.

By default, it will be created as a dense array, but can be turned to
sparse (CSR format) through :meth:`sparsify` (which can be beneficial
under L1 regularization when many coefficients are zero), and back to
dense through :meth:`densify`.
ndarray[float64](1, 100) [[ 1.09,-1.54,-0.87,..., 1.69,-0.69,-1.07]]
intercept_ intercept_: ndarray of shape (1,) or (n_classes,)

Intercept (a.k.a. bias) added to the decision function.

If `fit_intercept` is set to False, the intercept is set to zero.
`intercept_` is of shape (1,) when the given problem is binary.
ndarray[float64](1,) [0.23]
n_features_in_ n_features_in_: int

Number of features seen during :term:`fit`.

.. versionadded:: 0.24
int 100
n_iter_ n_iter_: ndarray of shape (1, )

Actual number of iterations for all classes.

.. versionchanged:: 0.20

In SciPy <= 1.0.0 the number of lbfgs iterations may exceed
``max_iter``. ``n_iter_`` will now report at most ``max_iter``.
ndarray[int32](1,) [17]
6 features
votingclassifier_constant splines model0
votingclassifier_constant splines model1
votingclassifier_periodic splines model0
votingclassifier_periodic splines model1
votingclassifier_nystroem model0
votingclassifier_nystroem model1


Finally we use DecisionBoundaryDisplay to plot the predicted probabilities. By using a diverging colormap (such as "RdBu"), we can ensure that darker colors correspond to predict_proba close to either 0 or 1, and white corresponds to predict_proba of 0.5.

from itertools import product

from sklearn.inspection import DecisionBoundaryDisplay

fig, axarr = plt.subplots(2, 2, sharex="col", sharey="row", figsize=(10, 8))
for idx, clf, title in zip(
    product([0, 1], [0, 1]),
    [clf1, clf2, clf3, eclf],
    [
        "Splines with\nconstant extrapolation",
        "Splines with\nperiodic extrapolation",
        "RBF Nystroem",
        "Soft Voting",
    ],
):
    disp = DecisionBoundaryDisplay.from_estimator(
        clf,
        X,
        response_method="predict_proba",
        plot_method="pcolormesh",
        cmap="RdBu",
        alpha=0.8,
        ax=axarr[idx[0], idx[1]],
    )
    axarr[idx[0], idx[1]].scatter(
        X["Feature #0"],
        X["Feature #1"],
        c=y,
        **common_scatter_plot_params,
    )
    axarr[idx[0], idx[1]].set_title(title)
    fig.colorbar(disp.surface_, ax=axarr[idx[0], idx[1]], label="Probability estimate")

plt.show()
Splines with constant extrapolation, Splines with periodic extrapolation, RBF Nystroem, Soft Voting

As a sanity check, we can verify for a given sample that the probability predicted by the VotingClassifier is indeed the weighted average of the individual classifiers’ soft-predictions.

In the case of binary classification such as in the present example, the predict_proba arrays contain the probability of belonging to class 0 (here in red) as the first entry, and the probability of belonging to class 1 (here in blue) as the second entry.

test_sample = pd.DataFrame({"Feature #0": [-0.5], "Feature #1": [1.5]})
predict_probas = [est.predict_proba(test_sample).ravel() for est in eclf.estimators_]
for (est_name, _), est_probas in zip(eclf.estimators, predict_probas):
    print(f"{est_name}'s predicted probabilities: {est_probas}")
constant splines model's predicted probabilities: [0.11272662 0.88727338]
periodic splines model's predicted probabilities: [0.99726573 0.00273427]
nystroem model's predicted probabilities: [0.3185838 0.6814162]
print(
    "Weighted average of soft-predictions: "
    f"{np.dot(weights, predict_probas) / np.sum(weights)}"
)
Weighted average of soft-predictions: [0.3630784 0.6369216]

We can see that manual calculation of predicted probabilities above is equivalent to that produced by the VotingClassifier:

print(
    "Predicted probability of VotingClassifier: "
    f"{eclf.predict_proba(test_sample).ravel()}"
)
Predicted probability of VotingClassifier: [0.3630784 0.6369216]

To convert soft predictions into hard predictions when weights are provided, the weighted average predicted probabilities are computed for each class. Then, the final class label is then derived from the class label with the highest average probability, which corresponds to the default threshold at predict_proba=0.5 in the case of binary classification.

print(
    "Class with the highest weighted average of soft-predictions: "
    f"{np.argmax(np.dot(weights, predict_probas) / np.sum(weights))}"
)
Class with the highest weighted average of soft-predictions: 1

This is equivalent to the output of VotingClassifier’s predict method:

print(f"Predicted class of VotingClassifier: {eclf.predict(test_sample).ravel()}")
Predicted class of VotingClassifier: [1]

Soft votes can be thresholded as for any other probabilistic classifier. This allows you to set a threshold probability at which the positive class will be predicted, instead of simply selecting the class with the highest predicted probability.

from sklearn.model_selection import FixedThresholdClassifier

eclf_other_threshold = FixedThresholdClassifier(
    eclf, threshold=0.7, response_method="predict_proba"
).fit(X, y)
print(
    "Predicted class of thresholded VotingClassifier: "
    f"{eclf_other_threshold.predict(test_sample)}"
)
Predicted class of thresholded VotingClassifier: [0]

Total running time of the script: (0 minutes 0.713 seconds)

Launch binder
Launch JupyterLite

Download Jupyter notebook: plot_voting_decision_regions.ipynb

Download Python source code: plot_voting_decision_regions.py

Download zipped: plot_voting_decision_regions.zip

Related examples

Plot classification probability

Polynomial and Spline interpolation

Comparison of Calibration of Classifiers

Examples of Using FrozenEstimator

© 2007–2026 The scikit-learn developers
Licensed under the 3-clause BSD License.
https://scikit-learn.org/1.9/auto_examples/ensemble/plot_voting_decision_regions.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API