class sklearn.mixture.BayesianGaussianMixture(*, n_components=1, covariance_type='full', tol=0.001, reg_covar=1e-06, max_iter=100, n_init=1, init_params='kmeans', weight_concentration_prior_type='dirichlet_process', weight_concentration_prior=None, mean_precision_prior=None, mean_prior=None, degrees_of_freedom_prior=None, covariance_prior=None, random_state=None, warm_start=False, verbose=0, verbose_interval=10) [source]

Variational Bayesian estimation of a Gaussian mixture. This class allows to infer an approximate posterior distribution over the parameters of a Gaussian mixture distribution. The effective number of components can be inferred from the data. This class implements two types of prior for the weights distribution: a finite mixture model with Dirichlet distribution and an infinite mixture model with the Dirichlet Process. In practice Dirichlet Process inference algorithm is approximated and uses a truncated distribution with a fixed maximum number of components (called the Stick-breaking representation). The number of components actually used almost always depends on the data.  New in version 0.18.  Read more in the User Guide.  Parameters

n_componentsint, default=1

The number of mixture components. Depending on the data and the value of the weight_concentration_prior the model can decide to not use all the components by setting some component weights_ to values very close to zero. The number of effective components is therefore smaller than n_components.
covariance_type{‘full’, ‘tied’, ‘diag’, ‘spherical’}, default=’full’

String describing the type of covariance parameters to use. Must be one of: 'full' (each component has its own general covariance matrix),
'tied' (all components share the same general covariance matrix),
'diag' (each component has its own diagonal covariance matrix),
'spherical' (each component has its own single variance).

tolfloat, default=1e-3

The convergence threshold. EM iterations will stop when the lower bound average gain on the likelihood (of the training data with respect to the model) is below this threshold.
reg_covarfloat, default=1e-6

Non-negative regularization added to the diagonal of covariance. Allows to assure that the covariance matrices are all positive.
max_iterint, default=100

The number of EM iterations to perform.
n_initint, default=1

The number of initializations to perform. The result with the highest lower bound value on the likelihood is kept.
init_params{‘kmeans’, ‘random’}, default=’kmeans’

The method used to initialize the weights, the means and the covariances. Must be one of: 'kmeans' : responsibilities are initialized using kmeans.
'random' : responsibilities are initialized randomly.

weight_concentration_prior_typestr, default=’dirichlet_process’

String describing the type of the weight concentration prior. Must be one of: 'dirichlet_process' (using the Stick-breaking representation),
'dirichlet_distribution' (can favor more uniform weights).

weight_concentration_priorfloat | None, default=None.

The dirichlet concentration of each component on the weight distribution (Dirichlet). This is commonly called gamma in the literature. The higher concentration puts more mass in the center and will lead to more components being active, while a lower concentration parameter will lead to more mass at the edge of the mixture weights simplex. The value of the parameter must be greater than 0. If it is None, it’s set to 1. / n_components.
mean_precision_priorfloat | None, default=None.

The precision prior on the mean distribution (Gaussian). Controls the extent of where means can be placed. Larger values concentrate the cluster means around mean_prior. The value of the parameter must be greater than 0. If it is None, it is set to 1.
mean_priorarray-like, shape (n_features,), default=None.

The prior on the mean distribution (Gaussian). If it is None, it is set to the mean of X.
degrees_of_freedom_priorfloat | None, default=None.

The prior of the number of degrees of freedom on the covariance distributions (Wishart). If it is None, it’s set to n_features.
covariance_priorfloat or array-like, default=None.

The prior on the covariance distribution (Wishart). If it is None, the emiprical covariance prior is initialized using the covariance of X. The shape depends on covariance_type: (n_features, n_features) if 'full',
(n_features, n_features) if 'tied',
(n_features)             if 'diag',
float                    if 'spherical'

random_stateint, RandomState instance or None, default=None

Controls the random seed given to the method chosen to initialize the parameters (see init_params). In addition, it controls the generation of random samples from the fitted distribution (see the method sample). Pass an int for reproducible output across multiple function calls. See Glossary.
warm_startbool, default=False

If ‘warm_start’ is True, the solution of the last fitting is used as initialization for the next call of fit(). This can speed up convergence when fit is called several times on similar problems. See the Glossary.
verboseint, default=0

Enable verbose output. If 1 then it prints the current initialization and each iteration step. If greater than 1 then it prints also the log probability and the time needed for each step.
verbose_intervalint, default=10

Number of iteration done before the next print.    Attributes

weights_array-like of shape (n_components,)

The weights of each mixture components.
means_array-like of shape (n_components, n_features)

The mean of each mixture component.
covariances_array-like

The covariance of each mixture component. The shape depends on covariance_type: (n_components,)                        if 'spherical',
(n_features, n_features)               if 'tied',
(n_components, n_features)             if 'diag',
(n_components, n_features, n_features) if 'full'

precisions_array-like

The precision matrices for each component in the mixture. A precision matrix is the inverse of a covariance matrix. A covariance matrix is symmetric positive definite so the mixture of Gaussian can be equivalently parameterized by the precision matrices. Storing the precision matrices instead of the covariance matrices makes it more efficient to compute the log-likelihood of new samples at test time. The shape depends on covariance_type: (n_components,)                        if 'spherical',
(n_features, n_features)               if 'tied',
(n_components, n_features)             if 'diag',
(n_components, n_features, n_features) if 'full'

precisions_cholesky_array-like

The cholesky decomposition of the precision matrices of each mixture component. A precision matrix is the inverse of a covariance matrix. A covariance matrix is symmetric positive definite so the mixture of Gaussian can be equivalently parameterized by the precision matrices. Storing the precision matrices instead of the covariance matrices makes it more efficient to compute the log-likelihood of new samples at test time. The shape depends on covariance_type: (n_components,)                        if 'spherical',
(n_features, n_features)               if 'tied',
(n_components, n_features)             if 'diag',
(n_components, n_features, n_features) if 'full'

converged_bool

True when convergence was reached in fit(), False otherwise.
n_iter_int

Number of step used by the best fit of inference to reach the convergence.
lower_bound_float

Lower bound value on the likelihood (of the training data with respect to the model) of the best fit of inference.
weight_concentration_prior_tuple or float

The dirichlet concentration of each component on the weight distribution (Dirichlet). The type depends on weight_concentration_prior_type: (float, float) if 'dirichlet_process' (Beta parameters),
float          if 'dirichlet_distribution' (Dirichlet parameters).
 The higher concentration puts more mass in the center and will lead to more components being active, while a lower concentration parameter will lead to more mass at the edge of the simplex.
weight_concentration_array-like of shape (n_components,)

The dirichlet concentration of each component on the weight distribution (Dirichlet).
mean_precision_prior_float

The precision prior on the mean distribution (Gaussian). Controls the extent of where means can be placed. Larger values concentrate the cluster means around mean_prior. If mean_precision_prior is set to None, mean_precision_prior_ is set to 1.
mean_precision_array-like of shape (n_components,)

The precision of each components on the mean distribution (Gaussian).
mean_prior_array-like of shape (n_features,)

The prior on the mean distribution (Gaussian).
degrees_of_freedom_prior_float

The prior of the number of degrees of freedom on the covariance distributions (Wishart).
degrees_of_freedom_array-like of shape (n_components,)

The number of degrees of freedom of each components in the model.
covariance_prior_float or array-like

The prior on the covariance distribution (Wishart). The shape depends on covariance_type: (n_features, n_features) if 'full',
(n_features, n_features) if 'tied',
(n_features)             if 'diag',
float                    if 'spherical'
      See also
GaussianMixture

Finite Gaussian mixture fit with EM.    References
1
Bishop, Christopher M. (2006). “Pattern recognition and machine learning”. Vol. 4 No. 4. New York: Springer.
2
Hagai Attias. (2000). “A Variational Bayesian Framework for Graphical Models”. In Advances in Neural Information Processing Systems 12.
3
Blei, David M. and Michael I. Jordan. (2006). “Variational inference for Dirichlet process mixtures”. Bayesian analysis 1.1   Examples >>> import numpy as np
>>> from sklearn.mixture import BayesianGaussianMixture
>>> X = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [12, 4], [10, 7]])
>>> bgm = BayesianGaussianMixture(n_components=2, random_state=42).fit(X)
>>> bgm.means_
array([[2.49... , 2.29...],
       [8.45..., 4.52... ]])
>>> bgm.predict([[0, 0], [9, 3]])
array([0, 1])
 Methods
fit(X[, y]) Estimate model parameters with the EM algorithm.
fit_predict(X[, y]) Estimate model parameters using X and predict the labels for X.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict the labels for the data samples in X using trained model.
predict_proba(X) Predict posterior probability of each component given the data.
sample([n_samples]) Generate random samples from the fitted Gaussian distribution.
score(X[, y]) Compute the per-sample average log-likelihood of the given data X.
score_samples(X) Compute the weighted log probabilities for each sample.
set_params(**params) Set the parameters of this estimator.
fit(X, y=None) [source]

Estimate model parameters with the EM algorithm. The method fits the model n_init times and sets the parameters with which the model has the largest likelihood or lower bound. Within each trial, the method iterates between E-step and M-step for max_iter times until the change of likelihood or lower bound is less than tol, otherwise, a ConvergenceWarning is raised. If warm_start is True, then n_init is ignored and a single initialization is performed upon the first call. Upon consecutive calls, training starts where it left off.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns
 self

fit_predict(X, y=None) [source]

Estimate model parameters using X and predict the labels for X. The method fits the model n_init times and sets the parameters with which the model has the largest likelihood or lower bound. Within each trial, the method iterates between E-step and M-step for max_iter times until the change of likelihood or lower bound is less than tol, otherwise, a ConvergenceWarning is raised. After fitting, it predicts the most probable label for the input data points.  New in version 0.20.   Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

labelsarray, shape (n_samples,)

Component labels.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

predict(X) [source]

Predict the labels for the data samples in X using trained model.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

labelsarray, shape (n_samples,)

Component labels.

predict_proba(X) [source]

Predict posterior probability of each component given the data.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

resparray, shape (n_samples, n_components)

Returns the probability each Gaussian (state) in the model given each sample.

sample(n_samples=1) [source]

Generate random samples from the fitted Gaussian distribution.  Parameters

n_samplesint, default=1

Number of samples to generate.    Returns

Xarray, shape (n_samples, n_features)

Randomly generated sample
yarray, shape (nsamples,)

Component labels

score(X, y=None) [source]

Compute the per-sample average log-likelihood of the given data X.  Parameters

Xarray-like of shape (n_samples, n_dimensions)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

log_likelihoodfloat

Log likelihood of the Gaussian mixture given X.

score_samples(X) [source]

Compute the weighted log probabilities for each sample.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

log_probarray, shape (n_samples,)

Log probabilities of each data point in X.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


sklearn.mixture.BayesianGaussianMixture
class sklearn.mixture.BayesianGaussianMixture(*, n_components=1, covariance_type='full', tol=0.001, reg_covar=1e-06, max_iter=100, n_init=1, init_params='kmeans', weight_concentration_prior_type='dirichlet_process', weight_concentration_prior=None, mean_precision_prior=None, mean_prior=None, degrees_of_freedom_prior=None, covariance_prior=None, random_state=None, warm_start=False, verbose=0, verbose_interval=10) [source]

Variational Bayesian estimation of a Gaussian mixture. This class allows to infer an approximate posterior distribution over the parameters of a Gaussian mixture distribution. The effective number of components can be inferred from the data. This class implements two types of prior for the weights distribution: a finite mixture model with Dirichlet distribution and an infinite mixture model with the Dirichlet Process. In practice Dirichlet Process inference algorithm is approximated and uses a truncated distribution with a fixed maximum number of components (called the Stick-breaking representation). The number of components actually used almost always depends on the data.  New in version 0.18.  Read more in the User Guide.  Parameters

n_componentsint, default=1

The number of mixture components. Depending on the data and the value of the weight_concentration_prior the model can decide to not use all the components by setting some component weights_ to values very close to zero. The number of effective components is therefore smaller than n_components.
covariance_type{‘full’, ‘tied’, ‘diag’, ‘spherical’}, default=’full’

String describing the type of covariance parameters to use. Must be one of: 'full' (each component has its own general covariance matrix),
'tied' (all components share the same general covariance matrix),
'diag' (each component has its own diagonal covariance matrix),
'spherical' (each component has its own single variance).

tolfloat, default=1e-3

The convergence threshold. EM iterations will stop when the lower bound average gain on the likelihood (of the training data with respect to the model) is below this threshold.
reg_covarfloat, default=1e-6

Non-negative regularization added to the diagonal of covariance. Allows to assure that the covariance matrices are all positive.
max_iterint, default=100

The number of EM iterations to perform.
n_initint, default=1

The number of initializations to perform. The result with the highest lower bound value on the likelihood is kept.
init_params{‘kmeans’, ‘random’}, default=’kmeans’

The method used to initialize the weights, the means and the covariances. Must be one of: 'kmeans' : responsibilities are initialized using kmeans.
'random' : responsibilities are initialized randomly.

weight_concentration_prior_typestr, default=’dirichlet_process’

String describing the type of the weight concentration prior. Must be one of: 'dirichlet_process' (using the Stick-breaking representation),
'dirichlet_distribution' (can favor more uniform weights).

weight_concentration_priorfloat | None, default=None.

The dirichlet concentration of each component on the weight distribution (Dirichlet). This is commonly called gamma in the literature. The higher concentration puts more mass in the center and will lead to more components being active, while a lower concentration parameter will lead to more mass at the edge of the mixture weights simplex. The value of the parameter must be greater than 0. If it is None, it’s set to 1. / n_components.
mean_precision_priorfloat | None, default=None.

The precision prior on the mean distribution (Gaussian). Controls the extent of where means can be placed. Larger values concentrate the cluster means around mean_prior. The value of the parameter must be greater than 0. If it is None, it is set to 1.
mean_priorarray-like, shape (n_features,), default=None.

The prior on the mean distribution (Gaussian). If it is None, it is set to the mean of X.
degrees_of_freedom_priorfloat | None, default=None.

The prior of the number of degrees of freedom on the covariance distributions (Wishart). If it is None, it’s set to n_features.
covariance_priorfloat or array-like, default=None.

The prior on the covariance distribution (Wishart). If it is None, the emiprical covariance prior is initialized using the covariance of X. The shape depends on covariance_type: (n_features, n_features) if 'full',
(n_features, n_features) if 'tied',
(n_features)             if 'diag',
float                    if 'spherical'

random_stateint, RandomState instance or None, default=None

Controls the random seed given to the method chosen to initialize the parameters (see init_params). In addition, it controls the generation of random samples from the fitted distribution (see the method sample). Pass an int for reproducible output across multiple function calls. See Glossary.
warm_startbool, default=False

If ‘warm_start’ is True, the solution of the last fitting is used as initialization for the next call of fit(). This can speed up convergence when fit is called several times on similar problems. See the Glossary.
verboseint, default=0

Enable verbose output. If 1 then it prints the current initialization and each iteration step. If greater than 1 then it prints also the log probability and the time needed for each step.
verbose_intervalint, default=10

Number of iteration done before the next print.    Attributes

weights_array-like of shape (n_components,)

The weights of each mixture components.
means_array-like of shape (n_components, n_features)

The mean of each mixture component.
covariances_array-like

The covariance of each mixture component. The shape depends on covariance_type: (n_components,)                        if 'spherical',
(n_features, n_features)               if 'tied',
(n_components, n_features)             if 'diag',
(n_components, n_features, n_features) if 'full'

precisions_array-like

The precision matrices for each component in the mixture. A precision matrix is the inverse of a covariance matrix. A covariance matrix is symmetric positive definite so the mixture of Gaussian can be equivalently parameterized by the precision matrices. Storing the precision matrices instead of the covariance matrices makes it more efficient to compute the log-likelihood of new samples at test time. The shape depends on covariance_type: (n_components,)                        if 'spherical',
(n_features, n_features)               if 'tied',
(n_components, n_features)             if 'diag',
(n_components, n_features, n_features) if 'full'

precisions_cholesky_array-like

The cholesky decomposition of the precision matrices of each mixture component. A precision matrix is the inverse of a covariance matrix. A covariance matrix is symmetric positive definite so the mixture of Gaussian can be equivalently parameterized by the precision matrices. Storing the precision matrices instead of the covariance matrices makes it more efficient to compute the log-likelihood of new samples at test time. The shape depends on covariance_type: (n_components,)                        if 'spherical',
(n_features, n_features)               if 'tied',
(n_components, n_features)             if 'diag',
(n_components, n_features, n_features) if 'full'

converged_bool

True when convergence was reached in fit(), False otherwise.
n_iter_int

Number of step used by the best fit of inference to reach the convergence.
lower_bound_float

Lower bound value on the likelihood (of the training data with respect to the model) of the best fit of inference.
weight_concentration_prior_tuple or float

The dirichlet concentration of each component on the weight distribution (Dirichlet). The type depends on weight_concentration_prior_type: (float, float) if 'dirichlet_process' (Beta parameters),
float          if 'dirichlet_distribution' (Dirichlet parameters).
 The higher concentration puts more mass in the center and will lead to more components being active, while a lower concentration parameter will lead to more mass at the edge of the simplex.
weight_concentration_array-like of shape (n_components,)

The dirichlet concentration of each component on the weight distribution (Dirichlet).
mean_precision_prior_float

The precision prior on the mean distribution (Gaussian). Controls the extent of where means can be placed. Larger values concentrate the cluster means around mean_prior. If mean_precision_prior is set to None, mean_precision_prior_ is set to 1.
mean_precision_array-like of shape (n_components,)

The precision of each components on the mean distribution (Gaussian).
mean_prior_array-like of shape (n_features,)

The prior on the mean distribution (Gaussian).
degrees_of_freedom_prior_float

The prior of the number of degrees of freedom on the covariance distributions (Wishart).
degrees_of_freedom_array-like of shape (n_components,)

The number of degrees of freedom of each components in the model.
covariance_prior_float or array-like

The prior on the covariance distribution (Wishart). The shape depends on covariance_type: (n_features, n_features) if 'full',
(n_features, n_features) if 'tied',
(n_features)             if 'diag',
float                    if 'spherical'
      See also
GaussianMixture

Finite Gaussian mixture fit with EM.    References
1
Bishop, Christopher M. (2006). “Pattern recognition and machine learning”. Vol. 4 No. 4. New York: Springer.
2
Hagai Attias. (2000). “A Variational Bayesian Framework for Graphical Models”. In Advances in Neural Information Processing Systems 12.
3
Blei, David M. and Michael I. Jordan. (2006). “Variational inference for Dirichlet process mixtures”. Bayesian analysis 1.1   Examples >>> import numpy as np
>>> from sklearn.mixture import BayesianGaussianMixture
>>> X = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [12, 4], [10, 7]])
>>> bgm = BayesianGaussianMixture(n_components=2, random_state=42).fit(X)
>>> bgm.means_
array([[2.49... , 2.29...],
       [8.45..., 4.52... ]])
>>> bgm.predict([[0, 0], [9, 3]])
array([0, 1])
 Methods
fit(X[, y]) Estimate model parameters with the EM algorithm.
fit_predict(X[, y]) Estimate model parameters using X and predict the labels for X.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict the labels for the data samples in X using trained model.
predict_proba(X) Predict posterior probability of each component given the data.
sample([n_samples]) Generate random samples from the fitted Gaussian distribution.
score(X[, y]) Compute the per-sample average log-likelihood of the given data X.
score_samples(X) Compute the weighted log probabilities for each sample.
set_params(**params) Set the parameters of this estimator.
fit(X, y=None) [source]

Estimate model parameters with the EM algorithm. The method fits the model n_init times and sets the parameters with which the model has the largest likelihood or lower bound. Within each trial, the method iterates between E-step and M-step for max_iter times until the change of likelihood or lower bound is less than tol, otherwise, a ConvergenceWarning is raised. If warm_start is True, then n_init is ignored and a single initialization is performed upon the first call. Upon consecutive calls, training starts where it left off.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns
 self

fit_predict(X, y=None) [source]

Estimate model parameters using X and predict the labels for X. The method fits the model n_init times and sets the parameters with which the model has the largest likelihood or lower bound. Within each trial, the method iterates between E-step and M-step for max_iter times until the change of likelihood or lower bound is less than tol, otherwise, a ConvergenceWarning is raised. After fitting, it predicts the most probable label for the input data points.  New in version 0.20.   Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

labelsarray, shape (n_samples,)

Component labels.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

predict(X) [source]

Predict the labels for the data samples in X using trained model.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

labelsarray, shape (n_samples,)

Component labels.

predict_proba(X) [source]

Predict posterior probability of each component given the data.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

resparray, shape (n_samples, n_components)

Returns the probability each Gaussian (state) in the model given each sample.

sample(n_samples=1) [source]

Generate random samples from the fitted Gaussian distribution.  Parameters

n_samplesint, default=1

Number of samples to generate.    Returns

Xarray, shape (n_samples, n_features)

Randomly generated sample
yarray, shape (nsamples,)

Component labels

score(X, y=None) [source]

Compute the per-sample average log-likelihood of the given data X.  Parameters

Xarray-like of shape (n_samples, n_dimensions)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

log_likelihoodfloat

Log likelihood of the Gaussian mixture given X.

score_samples(X) [source]

Compute the weighted log probabilities for each sample.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

log_probarray, shape (n_samples,)

Log probabilities of each data point in X.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

 Examples using sklearn.mixture.BayesianGaussianMixture

  Gaussian Mixture Model Ellipsoids

  Gaussian Mixture Model Sine Curve

  Concentration Prior Type Analysis of Variation Bayesian Gaussian Mixture


fit(X, y=None) [source]

Estimate model parameters with the EM algorithm. The method fits the model n_init times and sets the parameters with which the model has the largest likelihood or lower bound. Within each trial, the method iterates between E-step and M-step for max_iter times until the change of likelihood or lower bound is less than tol, otherwise, a ConvergenceWarning is raised. If warm_start is True, then n_init is ignored and a single initialization is performed upon the first call. Upon consecutive calls, training starts where it left off.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns
 self


fit_predict(X, y=None) [source]

Estimate model parameters using X and predict the labels for X. The method fits the model n_init times and sets the parameters with which the model has the largest likelihood or lower bound. Within each trial, the method iterates between E-step and M-step for max_iter times until the change of likelihood or lower bound is less than tol, otherwise, a ConvergenceWarning is raised. After fitting, it predicts the most probable label for the input data points.  New in version 0.20.   Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

labelsarray, shape (n_samples,)

Component labels.


get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.


predict(X) [source]

Predict the labels for the data samples in X using trained model.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

labelsarray, shape (n_samples,)

Component labels.


predict_proba(X) [source]

Predict posterior probability of each component given the data.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

resparray, shape (n_samples, n_components)

Returns the probability each Gaussian (state) in the model given each sample.


sample(n_samples=1) [source]

Generate random samples from the fitted Gaussian distribution.  Parameters

n_samplesint, default=1

Number of samples to generate.    Returns

Xarray, shape (n_samples, n_features)

Randomly generated sample
yarray, shape (nsamples,)

Component labels


score(X, y=None) [source]

Compute the per-sample average log-likelihood of the given data X.  Parameters

Xarray-like of shape (n_samples, n_dimensions)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

log_likelihoodfloat

Log likelihood of the Gaussian mixture given X.


score_samples(X) [source]

Compute the weighted log probabilities for each sample.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

log_probarray, shape (n_samples,)

Log probabilities of each data point in X.


set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


class sklearn.mixture.GaussianMixture(n_components=1, *, covariance_type='full', tol=0.001, reg_covar=1e-06, max_iter=100, n_init=1, init_params='kmeans', weights_init=None, means_init=None, precisions_init=None, random_state=None, warm_start=False, verbose=0, verbose_interval=10) [source]

Gaussian Mixture. Representation of a Gaussian mixture model probability distribution. This class allows to estimate the parameters of a Gaussian mixture distribution. Read more in the User Guide.  New in version 0.18.   Parameters

n_componentsint, default=1

The number of mixture components.
covariance_type{‘full’, ‘tied’, ‘diag’, ‘spherical’}, default=’full’

String describing the type of covariance parameters to use. Must be one of:  ‘full’

each component has its own general covariance matrix  ‘tied’

all components share the same general covariance matrix  ‘diag’

each component has its own diagonal covariance matrix  ‘spherical’

each component has its own single variance
tolfloat, default=1e-3

The convergence threshold. EM iterations will stop when the lower bound average gain is below this threshold.
reg_covarfloat, default=1e-6

Non-negative regularization added to the diagonal of covariance. Allows to assure that the covariance matrices are all positive.
max_iterint, default=100

The number of EM iterations to perform.
n_initint, default=1

The number of initializations to perform. The best results are kept.
init_params{‘kmeans’, ‘random’}, default=’kmeans’

The method used to initialize the weights, the means and the precisions. Must be one of: 'kmeans' : responsibilities are initialized using kmeans.
'random' : responsibilities are initialized randomly.

weights_initarray-like of shape (n_components, ), default=None

The user-provided initial weights. If it is None, weights are initialized using the init_params method.
means_initarray-like of shape (n_components, n_features), default=None

The user-provided initial means, If it is None, means are initialized using the init_params method.
precisions_initarray-like, default=None

The user-provided initial precisions (inverse of the covariance matrices). If it is None, precisions are initialized using the ‘init_params’ method. The shape depends on ‘covariance_type’: (n_components,)                        if 'spherical',
(n_features, n_features)               if 'tied',
(n_components, n_features)             if 'diag',
(n_components, n_features, n_features) if 'full'

random_stateint, RandomState instance or None, default=None

Controls the random seed given to the method chosen to initialize the parameters (see init_params). In addition, it controls the generation of random samples from the fitted distribution (see the method sample). Pass an int for reproducible output across multiple function calls. See Glossary.
warm_startbool, default=False

If ‘warm_start’ is True, the solution of the last fitting is used as initialization for the next call of fit(). This can speed up convergence when fit is called several times on similar problems. In that case, ‘n_init’ is ignored and only a single initialization occurs upon the first call. See the Glossary.
verboseint, default=0

Enable verbose output. If 1 then it prints the current initialization and each iteration step. If greater than 1 then it prints also the log probability and the time needed for each step.
verbose_intervalint, default=10

Number of iteration done before the next print.    Attributes

weights_array-like of shape (n_components,)

The weights of each mixture components.
means_array-like of shape (n_components, n_features)

The mean of each mixture component.
covariances_array-like

The covariance of each mixture component. The shape depends on covariance_type: (n_components,)                        if 'spherical',
(n_features, n_features)               if 'tied',
(n_components, n_features)             if 'diag',
(n_components, n_features, n_features) if 'full'

precisions_array-like

The precision matrices for each component in the mixture. A precision matrix is the inverse of a covariance matrix. A covariance matrix is symmetric positive definite so the mixture of Gaussian can be equivalently parameterized by the precision matrices. Storing the precision matrices instead of the covariance matrices makes it more efficient to compute the log-likelihood of new samples at test time. The shape depends on covariance_type: (n_components,)                        if 'spherical',
(n_features, n_features)               if 'tied',
(n_components, n_features)             if 'diag',
(n_components, n_features, n_features) if 'full'

precisions_cholesky_array-like

The cholesky decomposition of the precision matrices of each mixture component. A precision matrix is the inverse of a covariance matrix. A covariance matrix is symmetric positive definite so the mixture of Gaussian can be equivalently parameterized by the precision matrices. Storing the precision matrices instead of the covariance matrices makes it more efficient to compute the log-likelihood of new samples at test time. The shape depends on covariance_type: (n_components,)                        if 'spherical',
(n_features, n_features)               if 'tied',
(n_components, n_features)             if 'diag',
(n_components, n_features, n_features) if 'full'

converged_bool

True when convergence was reached in fit(), False otherwise.
n_iter_int

Number of step used by the best fit of EM to reach the convergence.
lower_bound_float

Lower bound value on the log-likelihood (of the training data with respect to the model) of the best fit of EM.      See also
BayesianGaussianMixture

Gaussian mixture model fit with a variational inference.    Examples >>> import numpy as np
>>> from sklearn.mixture import GaussianMixture
>>> X = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]])
>>> gm = GaussianMixture(n_components=2, random_state=0).fit(X)
>>> gm.means_
array([[10.,  2.],
       [ 1.,  2.]])
>>> gm.predict([[0, 0], [12, 3]])
array([1, 0])
 Methods
aic(X) Akaike information criterion for the current model on the input X.
bic(X) Bayesian information criterion for the current model on the input X.
fit(X[, y]) Estimate model parameters with the EM algorithm.
fit_predict(X[, y]) Estimate model parameters using X and predict the labels for X.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict the labels for the data samples in X using trained model.
predict_proba(X) Predict posterior probability of each component given the data.
sample([n_samples]) Generate random samples from the fitted Gaussian distribution.
score(X[, y]) Compute the per-sample average log-likelihood of the given data X.
score_samples(X) Compute the weighted log probabilities for each sample.
set_params(**params) Set the parameters of this estimator.
aic(X) [source]

Akaike information criterion for the current model on the input X.  Parameters

Xarray of shape (n_samples, n_dimensions)
  Returns

aicfloat

The lower the better.

bic(X) [source]

Bayesian information criterion for the current model on the input X.  Parameters

Xarray of shape (n_samples, n_dimensions)
  Returns

bicfloat

The lower the better.

fit(X, y=None) [source]

Estimate model parameters with the EM algorithm. The method fits the model n_init times and sets the parameters with which the model has the largest likelihood or lower bound. Within each trial, the method iterates between E-step and M-step for max_iter times until the change of likelihood or lower bound is less than tol, otherwise, a ConvergenceWarning is raised. If warm_start is True, then n_init is ignored and a single initialization is performed upon the first call. Upon consecutive calls, training starts where it left off.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns
 self

fit_predict(X, y=None) [source]

Estimate model parameters using X and predict the labels for X. The method fits the model n_init times and sets the parameters with which the model has the largest likelihood or lower bound. Within each trial, the method iterates between E-step and M-step for max_iter times until the change of likelihood or lower bound is less than tol, otherwise, a ConvergenceWarning is raised. After fitting, it predicts the most probable label for the input data points.  New in version 0.20.   Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

labelsarray, shape (n_samples,)

Component labels.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

predict(X) [source]

Predict the labels for the data samples in X using trained model.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

labelsarray, shape (n_samples,)

Component labels.

predict_proba(X) [source]

Predict posterior probability of each component given the data.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

resparray, shape (n_samples, n_components)

Returns the probability each Gaussian (state) in the model given each sample.

sample(n_samples=1) [source]

Generate random samples from the fitted Gaussian distribution.  Parameters

n_samplesint, default=1

Number of samples to generate.    Returns

Xarray, shape (n_samples, n_features)

Randomly generated sample
yarray, shape (nsamples,)

Component labels

score(X, y=None) [source]

Compute the per-sample average log-likelihood of the given data X.  Parameters

Xarray-like of shape (n_samples, n_dimensions)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

log_likelihoodfloat

Log likelihood of the Gaussian mixture given X.

score_samples(X) [source]

Compute the weighted log probabilities for each sample.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

log_probarray, shape (n_samples,)

Log probabilities of each data point in X.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


sklearn.mixture.GaussianMixture
class sklearn.mixture.GaussianMixture(n_components=1, *, covariance_type='full', tol=0.001, reg_covar=1e-06, max_iter=100, n_init=1, init_params='kmeans', weights_init=None, means_init=None, precisions_init=None, random_state=None, warm_start=False, verbose=0, verbose_interval=10) [source]

Gaussian Mixture. Representation of a Gaussian mixture model probability distribution. This class allows to estimate the parameters of a Gaussian mixture distribution. Read more in the User Guide.  New in version 0.18.   Parameters

n_componentsint, default=1

The number of mixture components.
covariance_type{‘full’, ‘tied’, ‘diag’, ‘spherical’}, default=’full’

String describing the type of covariance parameters to use. Must be one of:  ‘full’

each component has its own general covariance matrix  ‘tied’

all components share the same general covariance matrix  ‘diag’

each component has its own diagonal covariance matrix  ‘spherical’

each component has its own single variance
tolfloat, default=1e-3

The convergence threshold. EM iterations will stop when the lower bound average gain is below this threshold.
reg_covarfloat, default=1e-6

Non-negative regularization added to the diagonal of covariance. Allows to assure that the covariance matrices are all positive.
max_iterint, default=100

The number of EM iterations to perform.
n_initint, default=1

The number of initializations to perform. The best results are kept.
init_params{‘kmeans’, ‘random’}, default=’kmeans’

The method used to initialize the weights, the means and the precisions. Must be one of: 'kmeans' : responsibilities are initialized using kmeans.
'random' : responsibilities are initialized randomly.

weights_initarray-like of shape (n_components, ), default=None

The user-provided initial weights. If it is None, weights are initialized using the init_params method.
means_initarray-like of shape (n_components, n_features), default=None

The user-provided initial means, If it is None, means are initialized using the init_params method.
precisions_initarray-like, default=None

The user-provided initial precisions (inverse of the covariance matrices). If it is None, precisions are initialized using the ‘init_params’ method. The shape depends on ‘covariance_type’: (n_components,)                        if 'spherical',
(n_features, n_features)               if 'tied',
(n_components, n_features)             if 'diag',
(n_components, n_features, n_features) if 'full'

random_stateint, RandomState instance or None, default=None

Controls the random seed given to the method chosen to initialize the parameters (see init_params). In addition, it controls the generation of random samples from the fitted distribution (see the method sample). Pass an int for reproducible output across multiple function calls. See Glossary.
warm_startbool, default=False

If ‘warm_start’ is True, the solution of the last fitting is used as initialization for the next call of fit(). This can speed up convergence when fit is called several times on similar problems. In that case, ‘n_init’ is ignored and only a single initialization occurs upon the first call. See the Glossary.
verboseint, default=0

Enable verbose output. If 1 then it prints the current initialization and each iteration step. If greater than 1 then it prints also the log probability and the time needed for each step.
verbose_intervalint, default=10

Number of iteration done before the next print.    Attributes

weights_array-like of shape (n_components,)

The weights of each mixture components.
means_array-like of shape (n_components, n_features)

The mean of each mixture component.
covariances_array-like

The covariance of each mixture component. The shape depends on covariance_type: (n_components,)                        if 'spherical',
(n_features, n_features)               if 'tied',
(n_components, n_features)             if 'diag',
(n_components, n_features, n_features) if 'full'

precisions_array-like

The precision matrices for each component in the mixture. A precision matrix is the inverse of a covariance matrix. A covariance matrix is symmetric positive definite so the mixture of Gaussian can be equivalently parameterized by the precision matrices. Storing the precision matrices instead of the covariance matrices makes it more efficient to compute the log-likelihood of new samples at test time. The shape depends on covariance_type: (n_components,)                        if 'spherical',
(n_features, n_features)               if 'tied',
(n_components, n_features)             if 'diag',
(n_components, n_features, n_features) if 'full'

precisions_cholesky_array-like

The cholesky decomposition of the precision matrices of each mixture component. A precision matrix is the inverse of a covariance matrix. A covariance matrix is symmetric positive definite so the mixture of Gaussian can be equivalently parameterized by the precision matrices. Storing the precision matrices instead of the covariance matrices makes it more efficient to compute the log-likelihood of new samples at test time. The shape depends on covariance_type: (n_components,)                        if 'spherical',
(n_features, n_features)               if 'tied',
(n_components, n_features)             if 'diag',
(n_components, n_features, n_features) if 'full'

converged_bool

True when convergence was reached in fit(), False otherwise.
n_iter_int

Number of step used by the best fit of EM to reach the convergence.
lower_bound_float

Lower bound value on the log-likelihood (of the training data with respect to the model) of the best fit of EM.      See also
BayesianGaussianMixture

Gaussian mixture model fit with a variational inference.    Examples >>> import numpy as np
>>> from sklearn.mixture import GaussianMixture
>>> X = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]])
>>> gm = GaussianMixture(n_components=2, random_state=0).fit(X)
>>> gm.means_
array([[10.,  2.],
       [ 1.,  2.]])
>>> gm.predict([[0, 0], [12, 3]])
array([1, 0])
 Methods
aic(X) Akaike information criterion for the current model on the input X.
bic(X) Bayesian information criterion for the current model on the input X.
fit(X[, y]) Estimate model parameters with the EM algorithm.
fit_predict(X[, y]) Estimate model parameters using X and predict the labels for X.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict the labels for the data samples in X using trained model.
predict_proba(X) Predict posterior probability of each component given the data.
sample([n_samples]) Generate random samples from the fitted Gaussian distribution.
score(X[, y]) Compute the per-sample average log-likelihood of the given data X.
score_samples(X) Compute the weighted log probabilities for each sample.
set_params(**params) Set the parameters of this estimator.
aic(X) [source]

Akaike information criterion for the current model on the input X.  Parameters

Xarray of shape (n_samples, n_dimensions)
  Returns

aicfloat

The lower the better.

bic(X) [source]

Bayesian information criterion for the current model on the input X.  Parameters

Xarray of shape (n_samples, n_dimensions)
  Returns

bicfloat

The lower the better.

fit(X, y=None) [source]

Estimate model parameters with the EM algorithm. The method fits the model n_init times and sets the parameters with which the model has the largest likelihood or lower bound. Within each trial, the method iterates between E-step and M-step for max_iter times until the change of likelihood or lower bound is less than tol, otherwise, a ConvergenceWarning is raised. If warm_start is True, then n_init is ignored and a single initialization is performed upon the first call. Upon consecutive calls, training starts where it left off.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns
 self

fit_predict(X, y=None) [source]

Estimate model parameters using X and predict the labels for X. The method fits the model n_init times and sets the parameters with which the model has the largest likelihood or lower bound. Within each trial, the method iterates between E-step and M-step for max_iter times until the change of likelihood or lower bound is less than tol, otherwise, a ConvergenceWarning is raised. After fitting, it predicts the most probable label for the input data points.  New in version 0.20.   Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

labelsarray, shape (n_samples,)

Component labels.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

predict(X) [source]

Predict the labels for the data samples in X using trained model.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

labelsarray, shape (n_samples,)

Component labels.

predict_proba(X) [source]

Predict posterior probability of each component given the data.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

resparray, shape (n_samples, n_components)

Returns the probability each Gaussian (state) in the model given each sample.

sample(n_samples=1) [source]

Generate random samples from the fitted Gaussian distribution.  Parameters

n_samplesint, default=1

Number of samples to generate.    Returns

Xarray, shape (n_samples, n_features)

Randomly generated sample
yarray, shape (nsamples,)

Component labels

score(X, y=None) [source]

Compute the per-sample average log-likelihood of the given data X.  Parameters

Xarray-like of shape (n_samples, n_dimensions)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

log_likelihoodfloat

Log likelihood of the Gaussian mixture given X.

score_samples(X) [source]

Compute the weighted log probabilities for each sample.  Parameters

Xarray-like of shape (n_samples, n_features)

List of n_features-dimensional data points. Each row corresponds to a single data point.    Returns

log_probarray, shape (n_samples,)

Log probabilities of each data point in X.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

 Examples using sklearn.mixture.GaussianMixture

  Comparing different clustering algorithms on toy datasets

  Density Estimation for a Gaussian mixture

  Gaussian Mixture Model Ellipsoids

  Gaussian Mixture Model Selection

  GMM covariances

  Gaussian Mixture Model Sine Curve


aic(X) [source]

Akaike information criterion for the current model on the input X.  Parameters

Xarray of shape (n_samples, n_dimensions)
  Returns

aicfloat

The lower the better.


bic(X) [source]

Bayesian information criterion for the current model on the input X.  Parameters

Xarray of shape (n_samples, n_dimensions)
  Returns

bicfloat

The lower the better.


sklearn.model_selection.check_cv(cv=5, y=None, *, classifier=False) [source]

Input checker utility for building a cross-validator  Parameters

cvint, cross-validation generator or an iterable, default=None

Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 5-fold cross validation, - integer, to specify the number of folds. - CV splitter, - An iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if classifier is True and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used. Refer User Guide for the various cross-validation strategies that can be used here.  Changed in version 0.22: cv default value changed from 3-fold to 5-fold.
yarray-like, default=None

The target variable for supervised learning problems.
classifierbool, default=False

Whether the task is a classification task, in which case stratified KFold will be used.    Returns

checked_cva cross-validator instance.

The return value is a cross-validator which generates the train/test splits via the split method.


sklearn.model_selection.cross_validate(estimator, X, y=None, *, groups=None, scoring=None, cv=None, n_jobs=None, verbose=0, fit_params=None, pre_dispatch='2*n_jobs', return_train_score=False, return_estimator=False, error_score=nan) [source]

Evaluate metric(s) by cross-validation and also record fit/score times. Read more in the User Guide.  Parameters

estimatorestimator object implementing ‘fit’

The object to use to fit the data.
Xarray-like of shape (n_samples, n_features)

The data to fit. Can be for example a list, or an array.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

The target variable to try to predict in the case of supervised learning.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set. Only used in conjunction with a “Group” cv instance (e.g., GroupKFold).
scoringstr, callable, list, tuple, or dict, default=None

Strategy to evaluate the performance of the cross-validated model on the test set. If scoring represents a single score, one can use:  a single string (see The scoring parameter: defining model evaluation rules); a callable (see Defining your scoring strategy from metric functions) that returns a single value.  If scoring reprents multiple scores, one can use:  a list or tuple of unique strings; a callable returning a dictionary where the keys are the metric names and the values are the metric scores; a dictionary with metric names as keys and callables a values.  See Specifying multiple metrics for evaluation for an example.
cvint, cross-validation generator or an iterable, default=None

Determines the cross-validation splitting strategy. Possible inputs for cv are:  None, to use the default 5-fold cross validation, int, to specify the number of folds in a (Stratified)KFold,
CV splitter, An iterable yielding (train, test) splits as arrays of indices.  For int/None inputs, if the estimator is a classifier and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used. Refer User Guide for the various cross-validation strategies that can be used here.  Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold.
n_jobsint, default=None

Number of jobs to run in parallel. Training the estimator and computing the score are parallelized over the cross-validation splits. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
verboseint, default=0

The verbosity level.
fit_paramsdict, default=None

Parameters to pass to the fit method of the estimator.
pre_dispatchint or str, default=’2*n_jobs’

Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be:  None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs An int, giving the exact number of total jobs that are spawned A str, giving an expression as a function of n_jobs, as in ‘2*n_jobs’
return_train_scorebool, default=False

Whether to include train scores. Computing training scores is used to get insights on how different parameter settings impact the overfitting/underfitting trade-off. However computing the scores on the training set can be computationally expensive and is not strictly required to select the parameters that yield the best generalization performance.  New in version 0.19.   Changed in version 0.21: Default value was changed from True to False
return_estimatorbool, default=False

Whether to return the estimators fitted on each split.  New in version 0.20.
error_score‘raise’ or numeric, default=np.nan

Value to assign to the score if an error occurs in estimator fitting. If set to ‘raise’, the error is raised. If a numeric value is given, FitFailedWarning is raised.  New in version 0.20.     Returns

scoresdict of float arrays of shape (n_splits,)

Array of scores of the estimator for each run of the cross validation. A dict of arrays containing the score/time arrays for each scorer is returned. The possible keys for this dict are:
test_score

The score array for test scores on each cv split. Suffix _score in test_score changes to a specific metric like test_r2 or test_auc if there are multiple scoring metrics in the scoring parameter.
train_score

The score array for train scores on each cv split. Suffix _score in train_score changes to a specific metric like train_r2 or train_auc if there are multiple scoring metrics in the scoring parameter. This is available only if return_train_score parameter is True.
fit_time

The time for fitting the estimator on the train set for each cv split.
score_time

The time for scoring the estimator on the test set for each cv split. (Note time for scoring on the train set is not included even if return_train_score is set to True
estimator

The estimator objects for each cv split. This is available only if return_estimator parameter is set to True.        See also
cross_val_score

Run cross-validation for single metric evaluation.
cross_val_predict

Get predictions from each split of cross-validation for diagnostic purposes.
sklearn.metrics.make_scorer

Make a scorer from a performance metric or loss function.    Examples >>> from sklearn import datasets, linear_model
>>> from sklearn.model_selection import cross_validate
>>> from sklearn.metrics import make_scorer
>>> from sklearn.metrics import confusion_matrix
>>> from sklearn.svm import LinearSVC
>>> diabetes = datasets.load_diabetes()
>>> X = diabetes.data[:150]
>>> y = diabetes.target[:150]
>>> lasso = linear_model.Lasso()
 Single metric evaluation using cross_validate >>> cv_results = cross_validate(lasso, X, y, cv=3)
>>> sorted(cv_results.keys())
['fit_time', 'score_time', 'test_score']
>>> cv_results['test_score']
array([0.33150734, 0.08022311, 0.03531764])
 Multiple metric evaluation using cross_validate (please refer the scoring parameter doc for more information) >>> scores = cross_validate(lasso, X, y, cv=3,
...                         scoring=('r2', 'neg_mean_squared_error'),
...                         return_train_score=True)
>>> print(scores['test_neg_mean_squared_error'])
[-3635.5... -3573.3... -6114.7...]
>>> print(scores['train_r2'])
[0.28010158 0.39088426 0.22784852]


sklearn.model_selection.cross_val_predict(estimator, X, y=None, *, groups=None, cv=None, n_jobs=None, verbose=0, fit_params=None, pre_dispatch='2*n_jobs', method='predict') [source]

Generate cross-validated estimates for each input data point The data is split according to the cv parameter. Each sample belongs to exactly one test set, and its prediction is computed with an estimator fitted on the corresponding training set. Passing these predictions into an evaluation metric may not be a valid way to measure generalization performance. Results can differ from cross_validate and cross_val_score unless all tests sets have equal size and the metric decomposes over samples. Read more in the User Guide.  Parameters

estimatorestimator object implementing ‘fit’ and ‘predict’

The object to use to fit the data.
Xarray-like of shape (n_samples, n_features)

The data to fit. Can be, for example a list, or an array at least 2d.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

The target variable to try to predict in the case of supervised learning.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set. Only used in conjunction with a “Group” cv instance (e.g., GroupKFold).
cvint, cross-validation generator or an iterable, default=None

Determines the cross-validation splitting strategy. Possible inputs for cv are:  None, to use the default 5-fold cross validation, int, to specify the number of folds in a (Stratified)KFold,
CV splitter, An iterable yielding (train, test) splits as arrays of indices.  For int/None inputs, if the estimator is a classifier and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used. Refer User Guide for the various cross-validation strategies that can be used here.  Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold.
n_jobsint, default=None

Number of jobs to run in parallel. Training the estimator and predicting are parallelized over the cross-validation splits. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
verboseint, default=0

The verbosity level.
fit_paramsdict, defualt=None

Parameters to pass to the fit method of the estimator.
pre_dispatchint or str, default=’2*n_jobs’

Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be:  None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs An int, giving the exact number of total jobs that are spawned A str, giving an expression as a function of n_jobs, as in ‘2*n_jobs’
method{‘predict’, ‘predict_proba’, ‘predict_log_proba’, ‘decision_function’}, default=’predict’

The method to be invoked by estimator.    Returns

predictionsndarray

This is the result of calling method. Shape:  When method is ‘predict’ and in special case where method is ‘decision_function’ and the target is binary: (n_samples,) When method is one of {‘predict_proba’, ‘predict_log_proba’, ‘decision_function’} (unless special case above): (n_samples, n_classes) If estimator is multioutput, an extra dimension ‘n_outputs’ is added to the end of each shape above.       See also
cross_val_score

Calculate score for each CV split.
cross_validate

Calculate one or more scores and timings for each CV split.    Notes In the case that one or more classes are absent in a training portion, a default score needs to be assigned to all instances for that class if method produces columns per class, as in {‘decision_function’, ‘predict_proba’, ‘predict_log_proba’}. For predict_proba this value is 0. In order to ensure finite output, we approximate negative infinity by the minimum finite float value for the dtype in other cases. Examples >>> from sklearn import datasets, linear_model
>>> from sklearn.model_selection import cross_val_predict
>>> diabetes = datasets.load_diabetes()
>>> X = diabetes.data[:150]
>>> y = diabetes.target[:150]
>>> lasso = linear_model.Lasso()
>>> y_pred = cross_val_predict(lasso, X, y, cv=3)


sklearn.model_selection.cross_val_score(estimator, X, y=None, *, groups=None, scoring=None, cv=None, n_jobs=None, verbose=0, fit_params=None, pre_dispatch='2*n_jobs', error_score=nan) [source]

Evaluate a score by cross-validation Read more in the User Guide.  Parameters

estimatorestimator object implementing ‘fit’

The object to use to fit the data.
Xarray-like of shape (n_samples, n_features)

The data to fit. Can be for example a list, or an array.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

The target variable to try to predict in the case of supervised learning.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set. Only used in conjunction with a “Group” cv instance (e.g., GroupKFold).
scoringstr or callable, default=None

A str (see model evaluation documentation) or a scorer callable object / function with signature scorer(estimator, X, y) which should return only a single value. Similar to cross_validate but only a single metric is permitted. If None, the estimator’s default scorer (if available) is used.
cvint, cross-validation generator or an iterable, default=None

Determines the cross-validation splitting strategy. Possible inputs for cv are:  None, to use the default 5-fold cross validation, int, to specify the number of folds in a (Stratified)KFold,
CV splitter, An iterable yielding (train, test) splits as arrays of indices.  For int/None inputs, if the estimator is a classifier and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used. Refer User Guide for the various cross-validation strategies that can be used here.  Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold.
n_jobsint, default=None

Number of jobs to run in parallel. Training the estimator and computing the score are parallelized over the cross-validation splits. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
verboseint, default=0

The verbosity level.
fit_paramsdict, default=None

Parameters to pass to the fit method of the estimator.
pre_dispatchint or str, default=’2*n_jobs’

Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be:  None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs An int, giving the exact number of total jobs that are spawned A str, giving an expression as a function of n_jobs, as in ‘2*n_jobs’
error_score‘raise’ or numeric, default=np.nan

Value to assign to the score if an error occurs in estimator fitting. If set to ‘raise’, the error is raised. If a numeric value is given, FitFailedWarning is raised.  New in version 0.20.     Returns

scoresndarray of float of shape=(len(list(cv)),)

Array of scores of the estimator for each run of the cross validation.      See also
cross_validate

To run cross-validation on multiple metrics and also to return train scores, fit times and score times.
cross_val_predict

Get predictions from each split of cross-validation for diagnostic purposes.
sklearn.metrics.make_scorer

Make a scorer from a performance metric or loss function.    Examples >>> from sklearn import datasets, linear_model
>>> from sklearn.model_selection import cross_val_score
>>> diabetes = datasets.load_diabetes()
>>> X = diabetes.data[:150]
>>> y = diabetes.target[:150]
>>> lasso = linear_model.Lasso()
>>> print(cross_val_score(lasso, X, y, cv=3))
[0.33150734 0.08022311 0.03531764]


class sklearn.model_selection.GridSearchCV(estimator, param_grid, *, scoring=None, n_jobs=None, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', error_score=nan, return_train_score=False) [source]

Exhaustive search over specified parameter values for an estimator. Important members are fit, predict. GridSearchCV implements a “fit” and a “score” method. It also implements “score_samples”, “predict”, “predict_proba”, “decision_function”, “transform” and “inverse_transform” if they are implemented in the estimator used. The parameters of the estimator used to apply these methods are optimized by cross-validated grid-search over a parameter grid. Read more in the User Guide.  Parameters

estimatorestimator object.

This is assumed to implement the scikit-learn estimator interface. Either estimator needs to provide a score function, or scoring must be passed.
param_griddict or list of dictionaries

Dictionary with parameters names (str) as keys and lists of parameter settings to try as values, or a list of such dictionaries, in which case the grids spanned by each dictionary in the list are explored. This enables searching over any sequence of parameter settings.
scoringstr, callable, list, tuple or dict, default=None

Strategy to evaluate the performance of the cross-validated model on the test set. If scoring represents a single score, one can use:  a single string (see The scoring parameter: defining model evaluation rules); a callable (see Defining your scoring strategy from metric functions) that returns a single value.  If scoring reprents multiple scores, one can use:  a list or tuple of unique strings; a callable returning a dictionary where the keys are the metric names and the values are the metric scores; a dictionary with metric names as keys and callables a values.  See Specifying multiple metrics for evaluation for an example.
n_jobsint, default=None

Number of jobs to run in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.  Changed in version v0.20: n_jobs default changed from 1 to None
pre_dispatchint, or str, default=n_jobs

Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be:  None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs An int, giving the exact number of total jobs that are spawned A str, giving an expression as a function of n_jobs, as in ‘2*n_jobs’
cvint, cross-validation generator or an iterable, default=None

Determines the cross-validation splitting strategy. Possible inputs for cv are:  None, to use the default 5-fold cross validation, integer, to specify the number of folds in a (Stratified)KFold,
CV splitter, An iterable yielding (train, test) splits as arrays of indices.  For integer/None inputs, if the estimator is a classifier and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used. Refer User Guide for the various cross-validation strategies that can be used here.  Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold.
refitbool, str, or callable, default=True

Refit an estimator using the best found parameters on the whole dataset. For multiple metric evaluation, this needs to be a str denoting the scorer that would be used to find the best parameters for refitting the estimator at the end. Where there are considerations other than maximum score in choosing a best estimator, refit can be set to a function which returns the selected best_index_ given cv_results_. In that case, the best_estimator_ and best_params_ will be set according to the returned best_index_ while the best_score_ attribute will not be available. The refitted estimator is made available at the best_estimator_ attribute and permits using predict directly on this GridSearchCV instance. Also for multiple metric evaluation, the attributes best_index_, best_score_ and best_params_ will only be available if refit is set and all of them will be determined w.r.t this specific scorer. See scoring parameter to know more about multiple metric evaluation.  Changed in version 0.20: Support for callable added.
verboseint

Controls the verbosity: the higher, the more messages.  >1 : the computation time for each fold and parameter candidate is displayed; >2 : the score is also displayed; >3 : the fold and candidate parameter indexes are also displayed together with the starting time of the computation.
error_score‘raise’ or numeric, default=np.nan

Value to assign to the score if an error occurs in estimator fitting. If set to ‘raise’, the error is raised. If a numeric value is given, FitFailedWarning is raised. This parameter does not affect the refit step, which will always raise the error.
return_train_scorebool, default=False

If False, the cv_results_ attribute will not include training scores. Computing training scores is used to get insights on how different parameter settings impact the overfitting/underfitting trade-off. However computing the scores on the training set can be computationally expensive and is not strictly required to select the parameters that yield the best generalization performance.  New in version 0.19.   Changed in version 0.21: Default value was changed from True to False     Attributes

cv_results_dict of numpy (masked) ndarrays

A dict with keys as column headers and values as columns, that can be imported into a pandas DataFrame. For instance the below given table
param_kernel param_gamma param_degree split0_test_score … rank_t…
‘poly’ – 2 0.80 … 2
‘poly’ – 3 0.70 … 4
‘rbf’ 0.1 – 0.80 … 3
‘rbf’ 0.2 – 0.93 … 1   will be represented by a cv_results_ dict of: {
'param_kernel': masked_array(data = ['poly', 'poly', 'rbf', 'rbf'],
                             mask = [False False False False]...)
'param_gamma': masked_array(data = [-- -- 0.1 0.2],
                            mask = [ True  True False False]...),
'param_degree': masked_array(data = [2.0 3.0 -- --],
                             mask = [False False  True  True]...),
'split0_test_score'  : [0.80, 0.70, 0.80, 0.93],
'split1_test_score'  : [0.82, 0.50, 0.70, 0.78],
'mean_test_score'    : [0.81, 0.60, 0.75, 0.85],
'std_test_score'     : [0.01, 0.10, 0.05, 0.08],
'rank_test_score'    : [2, 4, 3, 1],
'split0_train_score' : [0.80, 0.92, 0.70, 0.93],
'split1_train_score' : [0.82, 0.55, 0.70, 0.87],
'mean_train_score'   : [0.81, 0.74, 0.70, 0.90],
'std_train_score'    : [0.01, 0.19, 0.00, 0.03],
'mean_fit_time'      : [0.73, 0.63, 0.43, 0.49],
'std_fit_time'       : [0.01, 0.02, 0.01, 0.01],
'mean_score_time'    : [0.01, 0.06, 0.04, 0.04],
'std_score_time'     : [0.00, 0.00, 0.00, 0.01],
'params'             : [{'kernel': 'poly', 'degree': 2}, ...],
}
 NOTE The key 'params' is used to store a list of parameter settings dicts for all the parameter candidates. The mean_fit_time, std_fit_time, mean_score_time and std_score_time are all in seconds. For multi-metric evaluation, the scores for all the scorers are available in the cv_results_ dict at the keys ending with that scorer’s name ('_<scorer_name>') instead of '_score' shown above. (‘split0_test_precision’, ‘mean_train_precision’ etc.)
best_estimator_estimator

Estimator that was chosen by the search, i.e. estimator which gave highest score (or smallest loss if specified) on the left out data. Not available if refit=False. See refit parameter for more information on allowed values.
best_score_float

Mean cross-validated score of the best_estimator For multi-metric evaluation, this is present only if refit is specified. This attribute is not available if refit is a function.
best_params_dict

Parameter setting that gave the best results on the hold out data. For multi-metric evaluation, this is present only if refit is specified.
best_index_int

The index (of the cv_results_ arrays) which corresponds to the best candidate parameter setting. The dict at search.cv_results_['params'][search.best_index_] gives the parameter setting for the best model, that gives the highest mean score (search.best_score_). For multi-metric evaluation, this is present only if refit is specified.
scorer_function or a dict

Scorer function used on the held out data to choose the best parameters for the model. For multi-metric evaluation, this attribute holds the validated scoring dict which maps the scorer key to the scorer callable.
n_splits_int

The number of cross-validation splits (folds/iterations).
refit_time_float

Seconds used for refitting the best model on the whole dataset. This is present only if refit is not False.  New in version 0.20.
multimetric_bool

Whether or not the scorers compute several metrics.      See also
ParameterGrid

Generates all the combinations of a hyperparameter grid.
train_test_split

Utility function to split the data into a development set usable for fitting a GridSearchCV instance and an evaluation set for its final evaluation.
sklearn.metrics.make_scorer

Make a scorer from a performance metric or loss function.    Notes The parameters selected are those that maximize the score of the left out data, unless an explicit score is passed in which case it is used instead. If n_jobs was set to a value higher than one, the data is copied for each point in the grid (and not n_jobs times). This is done for efficiency reasons if individual jobs take very little time, but may raise errors if the dataset is large and not enough memory is available. A workaround in this case is to set pre_dispatch. Then, the memory is copied only pre_dispatch many times. A reasonable value for pre_dispatch is 2 *
n_jobs. Examples >>> from sklearn import svm, datasets
>>> from sklearn.model_selection import GridSearchCV
>>> iris = datasets.load_iris()
>>> parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}
>>> svc = svm.SVC()
>>> clf = GridSearchCV(svc, parameters)
>>> clf.fit(iris.data, iris.target)
GridSearchCV(estimator=SVC(),
             param_grid={'C': [1, 10], 'kernel': ('linear', 'rbf')})
>>> sorted(clf.cv_results_.keys())
['mean_fit_time', 'mean_score_time', 'mean_test_score',...
 'param_C', 'param_kernel', 'params',...
 'rank_test_score', 'split0_test_score',...
 'split2_test_score', ...
 'std_fit_time', 'std_score_time', 'std_test_score']
 Methods
decision_function(X) Call decision_function on the estimator with the best found parameters.
fit(X[, y, groups]) Run fit with all sets of parameters.
get_params([deep]) Get parameters for this estimator.
inverse_transform(Xt) Call inverse_transform on the estimator with the best found params.
predict(X) Call predict on the estimator with the best found parameters.
predict_log_proba(X) Call predict_log_proba on the estimator with the best found parameters.
predict_proba(X) Call predict_proba on the estimator with the best found parameters.
score(X[, y]) Returns the score on the given data, if the estimator has been refit.
score_samples(X) Call score_samples on the estimator with the best found parameters.
set_params(**params) Set the parameters of this estimator.
transform(X) Call transform on the estimator with the best found parameters.
decision_function(X) [source]

Call decision_function on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports decision_function.  Parameters

Xindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.

fit(X, y=None, *, groups=None, **fit_params) [source]

Run fit with all sets of parameters.  Parameters

Xarray-like of shape (n_samples, n_features)

Training vector, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples, n_output) or (n_samples,), default=None

Target relative to X for classification or regression; None for unsupervised learning.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set. Only used in conjunction with a “Group” cv instance (e.g., GroupKFold).
**fit_paramsdict of str -> object

Parameters passed to the fit method of the estimator

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(Xt) [source]

Call inverse_transform on the estimator with the best found params. Only available if the underlying estimator implements inverse_transform and refit=True.  Parameters

Xtindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.

predict(X) [source]

Call predict on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports predict.  Parameters

Xindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.

predict_log_proba(X) [source]

Call predict_log_proba on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports predict_log_proba.  Parameters

Xindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.

predict_proba(X) [source]

Call predict_proba on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports predict_proba.  Parameters

Xindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.

score(X, y=None) [source]

Returns the score on the given data, if the estimator has been refit. This uses the score defined by scoring where provided, and the best_estimator_.score method otherwise.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples, n_output) or (n_samples,), default=None

Target relative to X for classification or regression; None for unsupervised learning.    Returns

scorefloat

score_samples(X) [source]

Call score_samples on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports score_samples.  New in version 0.24.   Parameters

Xiterable

Data to predict on. Must fulfill input requirements of the underlying estimator.    Returns

y_scorendarray of shape (n_samples,)

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X) [source]

Call transform on the estimator with the best found parameters. Only available if the underlying estimator supports transform and refit=True.  Parameters

Xindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.