API Reference¶
Это справочник классов и функций scikit-learn. За более подробной информацией обращайтесь к полному руководству пользователя, поскольку исходных спецификаций классов и функций может быть недостаточно, чтобы дать полное руководство по их использованию. Для получения информации о понятиях, повторяющихся в API, смотрите Glossary of Common Terms and API Elements.
sklearn
: Настройки и информационные инструменты¶
The sklearn
module includes functions to configure global settings and
get information about the working environment.
|
Context manager for global scikit-learn configuration. |
Retrieve current values for configuration set by |
|
|
Set global scikit-learn configuration. |
Print useful debugging information" |
sklearn.base
: Базовые классы и служебные функции¶
Base classes for all estimators.
Базовые классы¶
Base class for all estimators in scikit-learn. |
|
Mixin class for all bicluster estimators in scikit-learn. |
|
Mixin class for all classifiers in scikit-learn. |
|
Mixin class for all cluster estimators in scikit-learn. |
|
Mixin class for all density estimators in scikit-learn. |
|
Mixin class for all regression estimators in scikit-learn. |
|
Mixin class for all transformers in scikit-learn. |
|
Mixin class for all meta estimators in scikit-learn. |
|
Provides |
|
Mixin class for all outlier detection estimators in scikit-learn. |
|
Mixin class for transformers that generate their own names by prefixing. |
|
Transformer mixin that performs feature selection given a support mask |
Функции¶
|
Construct a new unfitted estimator with the same parameters. |
|
Return True if the given estimator is (probably) a classifier. |
|
Return True if the given estimator is (probably) a regressor. |
sklearn.calibration
: Калибровка вероятности¶
Calibration of predicted probabilities.
Руководство пользователя: см. раздел Калибровка вероятности для более подробной информации.
Probability calibration with isotonic regression or logistic regression. |
|
Compute true and predicted probabilities for a calibration curve. |
sklearn.cluster
: Кластеризация¶
The sklearn.cluster
module gathers popular unsupervised clustering
algorithms.
Руководство пользователя: см. раздел Кластеризация и Бинарная кластеризация для более подробной информации.
Классы¶
|
Perform Affinity Propagation Clustering of data. |
Agglomerative Clustering. |
|
|
Implements the BIRCH clustering algorithm. |
|
Perform DBSCAN clustering from vector array or distance matrix. |
|
Cluster data using hierarchical density-based clustering. |
|
Agglomerate features. |
|
K-Means clustering. |
|
Bisecting K-Means clustering. |
|
Mini-Batch K-Means clustering. |
|
Mean shift clustering using a flat kernel. |
|
Estimate clustering structure from vector array. |
|
Apply clustering to a projection of the normalized Laplacian. |
|
Spectral biclustering (Kluger, 2003). |
|
Spectral Co-Clustering algorithm (Dhillon, 2001). |
Функции¶
|
Perform Affinity Propagation Clustering of data. |
|
Perform DBSCAN extraction for an arbitrary epsilon. |
|
Automatically extract clusters according to the Xi-steep method. |
|
Compute the OPTICS reachability graph. |
|
Perform DBSCAN clustering from vector array or distance matrix. |
|
Estimate the bandwidth to use with the mean-shift algorithm. |
|
Perform K-means clustering algorithm. |
|
Init n_clusters seeds according to k-means++. |
|
Perform mean shift clustering of data using a flat kernel. |
|
Apply clustering to a projection of the normalized Laplacian. |
|
Ward clustering based on a Feature matrix. |
sklearn.compose
: Составные модели¶
Meta-estimators for building composite models with transformers
In addition to its current contents, this module will eventually be home to refurbished versions of Pipeline and FeatureUnion.
Руководство пользователя: см. раздел Конвейеры и составные моделеи для более подробной информации.
|
Applies transformers to columns of an array or pandas DataFrame. |
Meta-estimator to regress on a transformed target. |
|
Construct a ColumnTransformer from the given transformers. |
|
Create a callable to select columns to be used with |
sklearn.covariance
: модели ковариации¶
The sklearn.covariance
module includes methods and algorithms to
robustly estimate the covariance of features given a set of points. The
precision matrix defined as the inverse of the covariance is also estimated.
Covariance estimation is closely related to the theory of Gaussian Graphical
Models.
Руководство пользователя: см. раздел Оценка ковариации для более подробной информации.
|
Maximum likelihood covariance estimator. |
|
An object for detecting outliers in a Gaussian distributed dataset. |
|
Sparse inverse covariance estimation with an l1-penalized estimator. |
|
Sparse inverse covariance w/ cross-validated choice of the l1 penalty. |
|
LedoitWolf Estimator. |
|
Minimum Covariance Determinant (MCD): robust estimator of covariance. |
|
Oracle Approximating Shrinkage Estimator as proposed in [R69773891e6a6-1]. |
|
Covariance estimator with shrinkage. |
|
Compute the Maximum likelihood covariance estimator. |
|
L1-penalized covariance estimator. |
|
Estimate the shrunk Ledoit-Wolf covariance matrix. |
|
Estimate the shrunk Ledoit-Wolf covariance matrix. |
|
Estimate covariance with the Oracle Approximating Shrinkage as proposed in [Rca3a42e5ec35-1]. |
|
Calculate covariance matrices shrunk on the diagonal. |
sklearn.cross_decomposition
: Перекрестное разложение (Cross decomposition)¶
Руководство пользователя: см. раздел Перекрестная декомпозиция для более подробной информации.
|
Canonical Correlation Analysis, also known as "Mode B" PLS. |
Partial Least Squares transformer and regressor. |
|
PLS regression. |
|
|
Partial Least Square SVD. |
sklearn.datasets
: Датасеты (или наборы данных)¶
The sklearn.datasets
module includes utilities to load datasets,
including methods to load and fetch popular reference datasets. It also
features some artificial data generators.
Руководство пользователя: см. раздел Утилиты загрузки наборов данных для более подробной информации.
Загрузчики (Loaders)¶
|
Delete all the content of the data home cache. |
|
Dump the dataset in svmlight / libsvm file format. |
|
Load the filenames and data from the 20 newsgroups dataset (classification). |
|
Load and vectorize the 20 newsgroups dataset (classification). |
|
Load the California housing dataset (regression). |
|
Load the covertype dataset (classification). |
|
Load the kddcup99 dataset (classification). |
|
Load the Labeled Faces in the Wild (LFW) pairs dataset (classification). |
|
Load the Labeled Faces in the Wild (LFW) people dataset (classification). |
|
Load the Olivetti faces data-set from AT&T (classification). |
|
Fetch dataset from openml by name or dataset id. |
|
Load the RCV1 multilabel dataset (classification). |
|
Loader for species distribution dataset from Phillips et. |
|
Return the path of the scikit-learn data directory. |
|
Load and return the breast cancer wisconsin dataset (classification). |
|
Load and return the diabetes dataset (regression). |
|
Load and return the digits dataset (classification). |
|
Load text files with categories as subfolder names. |
|
Load and return the iris dataset (classification). |
|
Load and return the physical exercise Linnerud dataset. |
|
Load the numpy array of a single sample image. |
Load sample images for image manipulation. |
|
|
Load datasets in the svmlight / libsvm format into sparse CSR matrix. |
|
Load dataset from multiple files in SVMlight format. |
|
Load and return the wine dataset (classification). |
Генератор данных¶
|
Generate a constant block diagonal structure array for biclustering. |
|
Generate isotropic Gaussian blobs for clustering. |
|
Generate an array with block checkerboard structure for biclustering. |
|
Make a large circle containing a smaller circle in 2d. |
|
Generate a random n-class classification problem. |
|
Generate the "Friedman #1" regression problem. |
|
Generate the "Friedman #2" regression problem. |
|
Generate the "Friedman #3" regression problem. |
|
Generate isotropic Gaussian and label samples by quantile. |
|
Generate data for binary classification used in Hastie et al. 2009, Example 10.2. |
|
Generate a mostly low rank matrix with bell-shaped singular values. |
|
Make two interleaving half circles. |
Generate a random multilabel classification problem. |
|
|
Generate a random regression problem. |
|
Generate an S curve dataset. |
|
Generate a signal as a sparse combination of dictionary elements. |
|
Generate a sparse symmetric definite positive matrix. |
Generate a random regression problem with sparse uncorrelated design. |
|
|
Generate a random symmetric, positive-definite matrix. |
|
Generate a swiss roll dataset. |
sklearn.decomposition
: Разложение матрицы (Matrix decomposition)¶
The sklearn.decomposition
module includes matrix decomposition
algorithms, including among others PCA, NMF or ICA. Most of the algorithms of
this module can be regarded as dimensionality reduction techniques.
Руководство пользователя: см. раздел Декомпозиция сигналов на компоненты (Матричная факторизация) для более подробной информации.
Dictionary learning. |
|
|
Factor Analysis (FA). |
|
FastICA: a fast algorithm for Independent Component Analysis. |
|
Incremental principal components analysis (IPCA). |
|
Kernel Principal component analysis (KPCA) [R396fc7d924b8-1]. |
Latent Dirichlet Allocation with online variational Bayes algorithm. |
|
Mini-batch dictionary learning. |
|
Mini-batch Sparse Principal Components Analysis. |
|
|
Non-Negative Matrix Factorization (NMF). |
|
Mini-Batch Non-Negative Matrix Factorization (NMF). |
|
Principal component analysis (PCA). |
|
Sparse Principal Components Analysis (SparsePCA). |
|
Sparse coding. |
|
Dimensionality reduction using truncated SVD (aka LSA). |
|
Solve a dictionary learning matrix factorization problem. |
|
Solve a dictionary learning matrix factorization problem online. |
|
Perform Fast Independent Component Analysis. |
Compute Non-negative Matrix Factorization (NMF). |
|
|
Sparse coding. |
sklearn.discriminant_analysis
: Дискриминантный анализ¶
Linear Discriminant Analysis and Quadratic Discriminant Analysis
Руководство пользователя: см. раздел Линейный Дискриминантный Анализ и Квадратичный Дискриминантный Анализ для более подробной информации.
Linear Discriminant Analysis. |
|
Quadratic Discriminant Analysis. |
sklearn.dummy
: Фиктивные модели (Dummy estimators)¶
Руководство пользователя: см. раздел Метрики и оценка: количественная оценка качества прогнозов для более подробной информации.
|
DummyClassifier makes predictions that ignore the input features. |
|
Regressor that makes predictions using simple rules. |
sklearn.ensemble
: Ансамблевые методы¶
The sklearn.ensemble
module includes ensemble-based methods for
classification, regression and anomaly detection.
Руководство пользователя: см. раздел Ансамблевые методы: Градиентный бустинг, случайные леса, бэггинг, метод голосования, стекинг для более подробной информации.
|
An AdaBoost classifier. |
|
An AdaBoost regressor. |
|
A Bagging classifier. |
|
A Bagging regressor. |
An extra-trees classifier. |
|
|
An extra-trees regressor. |
|
Gradient Boosting for classification. |
|
Gradient Boosting for regression. |
|
Isolation Forest Algorithm. |
A random forest classifier. |
|
A random forest regressor. |
|
An ensemble of totally random trees. |
|
|
Stack of estimators with a final classifier. |
|
Stack of estimators with a final regressor. |
|
Soft Voting/Majority Rule classifier for unfitted estimators. |
|
Prediction voting regressor for unfitted estimators. |
Histogram-based Gradient Boosting Regression Tree. |
|
Histogram-based Gradient Boosting Classification Tree. |
sklearn.exceptions
: Исключения и предупреждения¶
The sklearn.exceptions
module includes all custom warnings and error
classes used across scikit-learn.
Custom warning to capture convergence problems |
|
Warning used to notify implicit data conversions happening in the code. |
|
Custom warning to notify potential issues with data dimensionality. |
|
Warning used to notify the user of inefficient computation. |
|
Warning class used if there is an error while fitting the estimator. |
|
Warning raised when an estimator is unpickled with a inconsistent version. |
|
Exception class to raise if estimator is used before fitting. |
|
Warning used when the metric is invalid |
sklearn.experimental
: Эксперименты¶
The sklearn.experimental
module provides importable modules that enable
the use of experimental features or estimators.
The features and estimators that are experimental aren’t subject to deprecation cycles. Use them at your own risks!
Enables IterativeImputer |
|
Enables Successive Halving search-estimators |
sklearn.feature_extraction
: Извлечение признаков¶
The sklearn.feature_extraction
module deals with feature extraction
from raw data. It currently includes methods to extract features from text and
images.
Руководство пользователя: см. раздел Извлечение признаков для более подробной информации.
|
Transforms lists of feature-value mappings to vectors. |
Implements feature hashing, aka the hashing trick. |
Из изображений¶
The sklearn.feature_extraction.image
submodule gathers utilities to
extract features from images.
Reshape a 2D image into a collection of patches. |
|
|
Graph of the pixel-to-pixel connections. |
Graph of the pixel-to-pixel gradient connections. |
|
Reconstruct the image from all of its patches. |
|
|
Extracts patches from a collection of images. |
Из текста¶
The sklearn.feature_extraction.text
submodule gathers utilities to
build feature vectors from text documents.
|
Convert a collection of text documents to a matrix of token counts. |
Convert a collection of text documents to a matrix of token occurrences. |
|
Transform a count matrix to a normalized tf or tf-idf representation. |
|
|
Convert a collection of raw documents to a matrix of TF-IDF features. |
sklearn.feature_selection
: Выбор признаков¶
The sklearn.feature_selection
module implements feature selection
algorithms. It currently includes univariate filter selection methods and the
recursive feature elimination algorithm.
Руководство пользователя: см. раздел Отбор признаков (Feature selection) для более подробной информации.
Univariate feature selector with configurable strategy. |
|
Select features according to a percentile of the highest scores. |
|
|
Select features according to the k highest scores. |
|
Filter: Select the pvalues below alpha based on a FPR test. |
|
Filter: Select the p-values for an estimated false discovery rate. |
|
Meta-transformer for selecting features based on importance weights. |
|
Filter: Select the p-values corresponding to Family-wise error rate. |
Transformer that performs Sequential Feature Selection. |
|
|
Feature ranking with recursive feature elimination. |
|
Recursive feature elimination with cross-validation to select features. |
|
Feature selector that removes all low-variance features. |
|
Compute chi-squared stats between each non-negative feature and class. |
Compute the ANOVA F-value for the provided sample. |
|
|
Univariate linear regression tests returning F-statistic and p-values. |
|
Compute Pearson's r for each features and the target. |
Estimate mutual information for a discrete target variable. |
|
Estimate mutual information for a continuous target variable. |
sklearn.gaussian_process
: Гауссовские процессы¶
The sklearn.gaussian_process
module implements Gaussian Process
based regression and classification.
Руководство пользователя: см. раздел Гауссовские процессы для более подробной информации.
Gaussian process classification (GPC) based on Laplace approximation. |
|
Gaussian process regression (GPR). |
Ядра¶
The sklearn.gaussian_process.kernels
module implements a set of kernels that
can be combined by operators and used in Gaussian processes.
Kernel which is composed of a set of other kernels. |
|
Constant kernel. |
|
Dot-Product kernel. |
|
Exp-Sine-Squared kernel (aka periodic kernel). |
|
The Exponentiation kernel takes one base kernel and a scalar parameter \(p\) and combines them via |
|
A kernel hyperparameter's specification in form of a namedtuple. |
|
Base class for all kernels. |
|
Matern kernel. |
|
Wrapper for kernels in sklearn.metrics.pairwise. |
|
|
The |
|
Radial basis function kernel (aka squared-exponential kernel). |
Rational Quadratic kernel. |
|
|
The |
White kernel. |
sklearn.impute
: Impute¶
Transformers for missing value imputation
Руководство пользователя: см. раздел Восстановление пропущенных значений для более подробной информации.
|
Univariate imputer for completing missing values with simple strategies. |
|
Multivariate imputer that estimates each feature from all the others. |
|
Binary indicators for missing values. |
|
Imputation for completing missing values using k-Nearest Neighbors. |
sklearn.inspection
: Inspection¶
The sklearn.inspection
module includes tools for model inspection.
|
Partial dependence of |
|
Permutation importance for feature evaluation [Rd9e56ef97513-BRE]. |
Построение графика¶
|
Decisions boundary visualization. |
|
Partial Dependence Plot (PDP). |
sklearn.isotonic
: Isotonic regression¶
Руководство пользователя: см. раздел Изотоническая регрессия для более подробной информации.
|
Isotonic regression model. |
Determine whether y is monotonically correlated with x. |
|
|
Solve the isotonic regression model. |
sklearn.kernel_approximation
: Kernel Approximation¶
The sklearn.kernel_approximation
module implements several
approximate kernel feature maps based on Fourier transforms and Count Sketches.
Руководство пользователя: см. раздел Аппроксимация ядра (Kernel Approximation) для более подробной информации.
Approximate feature map for additive chi2 kernel. |
|
|
Approximate a kernel map using a subset of the training data. |
Polynomial kernel approximation via Tensor Sketch. |
|
|
Approximate a RBF kernel feature map using random Fourier features. |
|
Approximate feature map for "skewed chi-squared" kernel. |
sklearn.kernel_ridge
: Kernel Ridge Regression¶
Module sklearn.kernel_ridge
implements kernel ridge regression.
Руководство пользователя: см. раздел Ридж Регрессия ядра для более подробной информации.
|
Kernel ridge regression. |
sklearn.linear_model
: Linear Models¶
The sklearn.linear_model
module implements a variety of linear models.
Руководство пользователя: см. раздел Линейные модели для более подробной информации.
The following subsections are only rough guidelines: the same estimator can fall into multiple categories, depending on its parameters.
Linear classifiers¶
|
Logistic Regression (aka logit, MaxEnt) classifier. |
|
Logistic Regression CV (aka logit, MaxEnt) classifier. |
Passive Aggressive Classifier. |
|
|
Linear perceptron classifier. |
|
Classifier using Ridge regression. |
|
Ridge classifier with built-in cross-validation. |
|
Linear classifiers (SVM, logistic regression, etc.) with SGD training. |
|
Solves linear One-Class SVM using Stochastic Gradient Descent. |
Классические линейная регресия¶
|
Ordinary least squares Linear Regression. |
|
Linear least squares with l2 regularization. |
|
Ridge regression with built-in cross-validation. |
|
Linear model fitted by minimizing a regularized empirical loss with SGD. |
Регрессия с выбором признаков¶
Следующие модели имеют встроенные процедуры подбора переменных, но любая модель, использующий регуляризацию L1 или elastic-net, также выполняет подбор переменных: обычно это SGDRegressor
или SGDClassifier
с соответствующим штрафом.
|
Linear regression with combined L1 and L2 priors as regularizer. |
|
Elastic Net model with iterative fitting along a regularization path. |
|
Least Angle Regression model a.k.a. |
|
Cross-validated Least Angle Regression model. |
|
Linear Model trained with L1 prior as regularizer (aka the Lasso). |
|
Lasso linear model with iterative fitting along a regularization path. |
|
Lasso model fit with Least Angle Regression a.k.a. |
|
Cross-validated Lasso, using the LARS algorithm. |
|
Lasso model fit with Lars using BIC or AIC for model selection. |
|
Orthogonal Matching Pursuit model (OMP). |
Cross-validated Orthogonal Matching Pursuit model (OMP). |
Bayesian regressors¶
|
Bayesian ARD regression. |
|
Bayesian ridge regression. |
Multi-task linear regressors with variable selection¶
These estimators fit multiple regression problems (or tasks) jointly, while inducing sparse coefficients. While the inferred coefficients may differ between the tasks, they are constrained to agree on the features that are selected (non-zero coefficients).
|
Multi-task ElasticNet model trained with L1/L2 mixed-norm as regularizer. |
|
Multi-task L1/L2 ElasticNet with built-in cross-validation. |
|
Multi-task Lasso model trained with L1/L2 mixed-norm as regularizer. |
|
Multi-task Lasso model trained with L1/L2 mixed-norm as regularizer. |
Outlier-robust regressors¶
Any estimator using the Huber loss would also be robust to outliers, e.g. SGDRegressor
with loss='huber'
.
|
L2-regularized linear regression model that is robust to outliers. |
|
Linear regression model that predicts conditional quantiles. |
|
RANSAC (RANdom SAmple Consensus) algorithm. |
|
Theil-Sen Estimator: robust multivariate regression model. |
Generalized linear models (GLM) for regression¶
These models allow for response variables to have error distributions other than a normal distribution:
|
Generalized Linear Model with a Poisson distribution. |
|
Generalized Linear Model with a Tweedie distribution. |
|
Generalized Linear Model with a Gamma distribution. |
Miscellaneous¶
|
Passive Aggressive Regressor. |
|
Compute elastic net path with coordinate descent. |
|
Compute Least Angle Regression or Lasso path using the LARS algorithm [1]. |
|
The lars_path in the sufficient stats mode [1]. |
|
Compute Lasso path with coordinate descent. |
|
Orthogonal Matching Pursuit (OMP). |
|
Gram Orthogonal Matching Pursuit (OMP). |
|
Solve the ridge equation by the method of normal equations. |
sklearn.manifold
: Manifold Learning¶
The sklearn.manifold
module implements data embedding techniques.
Руководство пользователя: см. раздел Manifold learning для более подробной информации.
|
Isomap Embedding. |
|
Locally Linear Embedding. |
|
Multidimensional scaling. |
|
Spectral embedding for non-linear dimensionality reduction. |
|
T-distributed Stochastic Neighbor Embedding. |
|
Perform a Locally Linear Embedding analysis on the data. |
|
Compute multidimensional scaling using the SMACOF algorithm. |
|
Project the sample on the first eigenvectors of the graph Laplacian. |
|
Indicate to what extent the local structure is retained. |
sklearn.metrics
: Metrics¶
See the Метрики и оценка: количественная оценка качества прогнозов section and the Парные метрики, Cходство и Ядра section of the user guide for further details.
The sklearn.metrics
module includes score functions, performance metrics
and pairwise metrics and distance computations.
Model Selection Interface¶
See the Параметр scoring: определение правил оценки модели section of the user guide for further details.
|
Determine scorer from user options. |
|
Get a scorer from string. |
Get the names of all available scorers. |
|
|
Make a scorer from a performance metric or loss function. |
Classification metrics¶
See the Метрики классификации section of the user guide for further details.
|
Accuracy classification score. |
|
Compute Area Under the Curve (AUC) using the trapezoidal rule. |
|
Compute average precision (AP) from prediction scores. |
|
Compute the balanced accuracy. |
|
Compute the Brier score loss. |
|
Compute binary classification positive and negative likelihood ratios. |
|
Build a text report showing the main classification metrics. |
|
Compute Cohen's kappa: a statistic that measures inter-annotator agreement. |
|
Compute confusion matrix to evaluate the accuracy of a classification. |
|
Compute Discounted Cumulative Gain. |
|
Compute error rates for different probability thresholds. |
|
Compute the F1 score, also known as balanced F-score or F-measure. |
|
Compute the F-beta score. |
|
Compute the average Hamming loss. |
|
Average hinge loss (non-regularized). |
|
Jaccard similarity coefficient score. |
|
Log loss, aka logistic loss or cross-entropy loss. |
|
Compute the Matthews correlation coefficient (MCC). |
|
Compute a confusion matrix for each class or sample. |
|
Compute Normalized Discounted Cumulative Gain. |
|
Compute precision-recall pairs for different probability thresholds. |
Compute precision, recall, F-measure and support for each class. |
|
|
Compute the precision. |
|
Compute the recall. |
|
Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) from prediction scores. |
|
Compute Receiver operating characteristic (ROC). |
|
Top-k Accuracy classification score. |
|
Zero-one classification loss. |
Regression metrics¶
See the Метрики для задач регрессии section of the user guide for further details.
|
Explained variance regression score function. |
|
The max_error metric calculates the maximum residual error. |
|
Mean absolute error regression loss. |
|
Mean squared error regression loss. |
|
Mean squared logarithmic error regression loss. |
|
Median absolute error regression loss. |
Mean absolute percentage error (MAPE) regression loss. |
|
|
\(R^2\) (coefficient of determination) regression score function. |
|
Root mean squared logarithmic error regression loss. |
|
Root mean squared error regression loss. |
|
Mean Poisson deviance regression loss. |
|
Mean Gamma deviance regression loss. |
|
Mean Tweedie deviance regression loss. |
|
\(D^2\) regression score function, fraction of Tweedie deviance explained. |
|
Pinball loss for quantile regression. |
|
\(D^2\) regression score function, fraction of pinball loss explained. |
|
\(D^2\) regression score function, fraction of absolute error explained. |
Multilabel ranking metrics¶
See the Метрики ранжирования по нескольким критериям section of the user guide for further details.
|
Coverage error measure. |
Compute ranking-based average precision. |
|
|
Compute Ranking loss measure. |
Clustering metrics¶
See the Оценка производительности кластеризации section of the user guide for further details.
The sklearn.metrics.cluster
submodule contains evaluation metrics for
cluster analysis results. There are two forms of evaluation:
supervised, which uses a ground truth class values for each sample.
unsupervised, which does not and measures the ‘quality’ of the model itself.
|
Adjusted Mutual Information between two clusterings. |
|
Rand index adjusted for chance. |
|
Compute the Calinski and Harabasz score. |
|
Compute the Davies-Bouldin score. |
|
Compute completeness metric of a cluster labeling given a ground truth. |
|
Build a contingency matrix describing the relationship between labels. |
Pair confusion matrix arising from two clusterings [R9ca8fd06d29a-1]. |
|
|
Measure the similarity of two clusterings of a set of points. |
Compute the homogeneity and completeness and V-Measure scores at once. |
|
|
Homogeneity metric of a cluster labeling given a ground truth. |
|
Mutual Information between two clusterings. |
|
Normalized Mutual Information between two clusterings. |
|
Rand index. |
|
Compute the mean Silhouette Coefficient of all samples. |
|
Compute the Silhouette Coefficient for each sample. |
|
V-measure cluster labeling given a ground truth. |
Biclustering metrics¶
See the Оценка бикластеризации section of the user guide for further details.
|
The similarity of two sets of biclusters. |
Distance metrics¶
Uniform interface for fast distance metric functions. |
Pairwise metrics¶
See the Парные метрики, Cходство и Ядра section of the user guide for further details.
Compute the additive chi-squared kernel between observations in X and Y. |
|
|
Compute the exponential chi-squared kernel between X and Y. |
|
Compute cosine similarity between samples in X and Y. |
Compute cosine distance between samples in X and Y. |
|
Valid metrics for pairwise_distances. |
|
|
Compute the distance matrix between each pair from a vector array X and Y. |
Compute the Haversine distance between samples in X and Y. |
|
Valid metrics for pairwise_kernels. |
|
|
Compute the laplacian kernel between X and Y. |
|
Compute the linear kernel between X and Y. |
Compute the L1 distances between the vectors in X and Y. |
|
Calculate the euclidean distances in the presence of missing values. |
|
|
Compute the kernel between arrays X and optional array Y. |
|
Compute the polynomial kernel between X and Y. |
|
Compute the rbf (gaussian) kernel between X and Y. |
|
Compute the sigmoid kernel between X and Y. |
Compute the paired euclidean distances between X and Y. |
|
Compute the paired L1 distances between X and Y. |
|
Compute the paired cosine distances between X and Y. |
|
|
Compute the paired distances between X and Y. |
|
Compute the distance matrix from a vector array X and optional Y. |
|
Compute minimum distances between one point and a set of points. |
Compute minimum distances between one point and a set of points. |
|
|
Generate a distance matrix chunk by chunk with optional reduction. |
Plotting¶
See the Визуализация section of the user guide for further details.
|
Confusion Matrix visualization. |
|
DET curve visualization. |
|
Precision Recall visualization. |
|
Visualization of the prediction error of a regression model. |
|
ROC Curve visualization. |
|
Calibration curve (also known as reliability diagram) visualization. |
sklearn.mixture
: Gaussian Mixture Models¶
The sklearn.mixture
module implements mixture modeling algorithms.
Руководство пользователя: см. раздел Модели гауссовских смесей (Gaussian mixture models) для более подробной информации.
|
Variational Bayesian estimation of a Gaussian mixture. |
|
Gaussian Mixture. |
sklearn.model_selection
: Model Selection¶
Руководство пользователя: см. раздел Кросс-валидация (Cross-validation или перекрестная проверка): оценка эффективности оценок, Настройка гиперпараметров модели and Кривая обучения для более подробной информации.
Splitter Classes¶
|
K-fold iterator variant with non-overlapping groups. |
Shuffle-Group(s)-Out cross-validation iterator. |
|
|
K-Fold cross-validator. |
Leave One Group Out cross-validator. |
|
|
Leave P Group(s) Out cross-validator. |
Leave-One-Out cross-validator. |
|
Leave-P-Out cross-validator. |
|
|
Predefined split cross-validator. |
|
Repeated K-Fold cross validator. |
|
Repeated Stratified K-Fold cross validator. |
|
Random permutation cross-validator. |
|
Stratified K-Fold cross-validator. |
Stratified ShuffleSplit cross-validator. |
|
Stratified K-Fold iterator variant with non-overlapping groups. |
|
|
Time Series cross-validator. |
Splitter Functions¶
|
Input checker utility for building a cross-validator. |
|
Split arrays or matrices into random train and test subsets. |
Hyper-parameter optimizers¶
|
Exhaustive search over specified parameter values for an estimator. |
|
Search over specified parameter values with successive halving. |
|
Grid of parameters with a discrete number of values for each. |
|
Generator on parameters sampled from given distributions. |
|
Randomized search on hyper parameters. |
|
Randomized search on hyper parameters. |
Model validation¶
|
Evaluate metric(s) by cross-validation and also record fit/score times. |
|
Generate cross-validated estimates for each input data point. |
|
Evaluate a score by cross-validation. |
|
Learning curve. |
Evaluate the significance of a cross-validated score with permutations. |
|
|
Validation curve. |
Visualization¶
Learning Curve visualization. |
|
Validation Curve visualization. |
sklearn.multiclass
: Multiclass classification¶
Multiclass classification strategies¶
- This module implements multiclass learning algorithms:
one-vs-the-rest / one-vs-all
one-vs-one
error correcting output codes
The estimators provided in this module are meta-estimators: they require a base estimator to be provided in their constructor. For example, it is possible to use these estimators to turn a binary classifier or a regressor into a multiclass classifier. It is also possible to use these estimators with multiclass estimators in the hope that their accuracy or runtime performance improves.
All classifiers in scikit-learn implement multiclass classification; you only need to use this module if you want to experiment with custom multiclass strategies.
The one-vs-the-rest meta-classifier also implements a predict_proba
method,
so long as such a method is implemented by the base classifier. This method
returns probabilities of class membership in both the single label and
multilabel case. Note that in the multilabel case, probabilities are the
marginal probability that a given sample falls in the given class. As such, in
the multilabel case the sum of these probabilities over all possible labels
for a given sample will not sum to unity, as they do in the single label
case.
Руководство пользователя: см. раздел Многоклассовая классификация для более подробной информации.
|
One-vs-the-rest (OvR) multiclass strategy. |
|
One-vs-one multiclass strategy. |
|
(Error-Correcting) Output-Code multiclass strategy. |
sklearn.multioutput
: Multioutput regression and classification¶
This module implements multioutput regression and classification.
The estimators provided in this module are meta-estimators: they require a base estimator to be provided in their constructor. The meta-estimator extends single output estimators to multioutput estimators.
Руководство пользователя: см. раздел Классификаци с многими метками, Многоклассовая классификация с несколькими выходами (многозадачная классификация), and Многозадачная регрессия для более подробной информации.
|
A multi-label model that arranges binary classifiers into a chain. |
|
Multi target regression. |
|
Multi target classification. |
|
A multi-label model that arranges regressions into a chain. |
sklearn.naive_bayes
: Naive Bayes¶
The sklearn.naive_bayes
module implements Naive Bayes algorithms. These
are supervised learning methods based on applying Bayes’ theorem with strong
(naive) feature independence assumptions.
Руководство пользователя: см. раздел Наивный байесовский классификатор для более подробной информации.
|
Naive Bayes classifier for multivariate Bernoulli models. |
|
Naive Bayes classifier for categorical features. |
|
The Complement Naive Bayes classifier described in Rennie et al. (2003). |
|
Gaussian Naive Bayes (GaussianNB). |
|
Naive Bayes classifier for multinomial models. |
sklearn.neighbors
: Nearest Neighbors¶
The sklearn.neighbors
module implements the k-nearest neighbors
algorithm.
Руководство пользователя: см. раздел Ближайшие соседи (Nearest Neighbors) для более подробной информации.
|
BallTree for fast generalized N-point problems |
|
KDTree for fast generalized N-point problems |
|
Kernel Density Estimation. |
Classifier implementing the k-nearest neighbors vote. |
|
|
Regression based on k-nearest neighbors. |
|
Transform X into a (weighted) graph of k nearest neighbors. |
|
Unsupervised Outlier Detection using the Local Outlier Factor (LOF). |
Classifier implementing a vote among neighbors within a given radius. |
|
|
Regression based on neighbors within a fixed radius. |
|
Transform X into a (weighted) graph of neighbors nearer than a radius. |
|
Nearest centroid classifier. |
|
Unsupervised learner for implementing neighbor searches. |
Neighborhood Components Analysis. |
|
Compute the (weighted) graph of k-Neighbors for points in X. |
|
Compute the (weighted) graph of Neighbors for points in X. |
|
Sort a sparse graph such that each row is stored with increasing values. |
sklearn.neural_network
: Neural network models¶
The sklearn.neural_network
module includes models based on neural
networks.
Руководство пользователя: см. раздел Модели нейронных сетей (контролируемые) and Модели нейронных сетей (без контроля) для более подробной информации.
|
Bernoulli Restricted Boltzmann Machine (RBM). |
|
Multi-layer Perceptron classifier. |
|
Multi-layer Perceptron regressor. |
sklearn.pipeline
: Pipeline¶
The sklearn.pipeline
module implements utilities to build a composite
estimator, as a chain of transforms and estimators.
Руководство пользователя: см. раздел Конвейеры и составные моделеи для более подробной информации.
|
Concatenates results of multiple transformer objects. |
|
A sequence of data transformers with an optional final predictor. |
|
Construct a |
|
Construct a |
sklearn.preprocessing
: Preprocessing and Normalization¶
The sklearn.preprocessing
module includes scaling, centering,
normalization, binarization methods.
Руководство пользователя: см. раздел Предварительная обработка данных для более подробной информации.
|
Binarize data (set feature values to 0 or 1) according to a threshold. |
|
Constructs a transformer from an arbitrary callable. |
|
Bin continuous data into intervals. |
Center an arbitrary kernel matrix \(K\). |
|
|
Binarize labels in a one-vs-all fashion. |
Encode target labels with value between 0 and n_classes-1. |
|
|
Transform between iterable of iterables and a multilabel format. |
|
Scale each feature by its maximum absolute value. |
|
Transform features by scaling each feature to a given range. |
|
Normalize samples individually to unit norm. |
|
Encode categorical features as a one-hot numeric array. |
|
Encode categorical features as an integer array. |
|
Generate polynomial and interaction features. |
|
Apply a power transform featurewise to make data more Gaussian-like. |
|
Transform features using quantiles information. |
|
Scale features using statistics that are robust to outliers. |
|
Generate univariate B-spline bases for features. |
|
Standardize features by removing the mean and scaling to unit variance. |
|
Target Encoder for regression and classification targets. |
|
Augment dataset with an additional dummy feature. |
|
Boolean thresholding of array-like or scipy.sparse matrix. |
|
Binarize labels in a one-vs-all fashion. |
|
Scale each feature to the [-1, 1] range without breaking the sparsity. |
|
Transform features by scaling each feature to a given range. |
|
Scale input vectors individually to unit norm (vector length). |
|
Transform features using quantiles information. |
|
Standardize a dataset along any axis. |
|
Standardize a dataset along any axis. |
|
Parametric, monotonic transformation to make data more Gaussian-like. |
sklearn.random_projection
: Random projection¶
Random Projection transformers.
Random Projections are a simple and computationally efficient way to reduce the dimensionality of the data by trading a controlled amount of accuracy (as additional variance) for faster processing times and smaller model sizes.
The dimensions and distribution of Random Projections matrices are controlled so as to preserve the pairwise distances between any two samples of the dataset.
The main theoretical result behind the efficiency of random projection is the Johnson-Lindenstrauss lemma (quoting Wikipedia):
In mathematics, the Johnson-Lindenstrauss lemma is a result concerning low-distortion embeddings of points from high-dimensional into low-dimensional Euclidean space. The lemma states that a small set of points in a high-dimensional space can be embedded into a space of much lower dimension in such a way that distances between the points are nearly preserved. The map used for the embedding is at least Lipschitz, and can even be taken to be an orthogonal projection.
Руководство пользователя: см. раздел Случайная проекция для более подробной информации.
Reduce dimensionality through Gaussian random projection. |
|
Reduce dimensionality through sparse random projection. |
Find a 'safe' number of components to randomly project to. |
sklearn.semi_supervised
: Semi-Supervised Learning¶
The sklearn.semi_supervised
module implements semi-supervised learning
algorithms. These algorithms utilize small amounts of labeled data and large
amounts of unlabeled data for classification tasks. This module includes Label
Propagation.
Руководство пользователя: см. раздел Полуконтролируемое обучение для более подробной информации.
|
Label Propagation classifier. |
|
LabelSpreading model for semi-supervised learning. |
Self-training classifier. |
sklearn.svm
: Support Vector Machines¶
The sklearn.svm
module includes Support Vector Machine algorithms.
Руководство пользователя: см. раздел Метод опорных векторов (Support Vector Machines - SVM) для более подробной информации.
Estimators¶
|
Linear Support Vector Classification. |
|
Linear Support Vector Regression. |
|
Nu-Support Vector Classification. |
|
Nu Support Vector Regression. |
|
Unsupervised Outlier Detection. |
|
C-Support Vector Classification. |
|
Epsilon-Support Vector Regression. |
|
Return the lowest bound for C. |
sklearn.tree
: Decision Trees¶
The sklearn.tree
module includes decision tree-based models for
classification and regression.
Руководство пользователя: см. раздел Деревья решений (Decision Trees) для более подробной информации.
|
A decision tree classifier. |
|
A decision tree regressor. |
|
An extremely randomized tree classifier. |
|
An extremely randomized tree regressor. |
|
Export a decision tree in DOT format. |
|
Build a text report showing the rules of a decision tree. |
Plotting¶
|
Plot a decision tree. |
sklearn.utils
: Utilities¶
The sklearn.utils
module includes various utilities.
Developer guide: See the Utilities for Developers page for further details.
|
Container object exposing keys as attributes. |
|
Convert an array-like to an array of floats. |
|
Throw a ValueError if X contains NaN or infinity. |
|
Decorator to mark a function or class as deprecated. |
|
Build a HTML representation of an estimator. |
|
Generator to create slices containing |
|
Generator to create |
|
Make arrays indexable for cross-validation. |
|
Compute the 32bit murmurhash3 of key at seed. |
|
Resample arrays or sparse matrices in a consistent way. |
|
Return rows, items or columns of X using indices. |
|
Return a mask which is safe to use on X. |
|
Element wise squaring of array-likes and sparse matrices. |
|
Shuffle arrays or sparse matrices in a consistent way. |
Input and parameter validation¶
The sklearn.utils.validation
module includes functions to validate
input and parameters within scikit-learn estimators.
|
Input validation for standard estimators. |
|
Input validation on an array, list, sparse matrix or similar. |
|
Validate scalar parameters type and value. |
|
Check that all arrays have consistent first dimensions. |
|
Turn seed into a np.random.RandomState instance. |
|
Perform is_fitted validation for estimator. |
|
Check that |
|
Make sure that array is 2D, square and symmetric. |
|
Ravel column or 1d numpy array, else raises an error. |
Check whether the estimator's fit method supports the given parameter. |
Utilities used in meta-estimators¶
The sklearn.utils.metaestimators
module includes utilities for meta-estimators.
An attribute that is available only if check returns a truthy value. |
Utilities to handle weights based on class labels¶
The sklearn.utils.class_weight
module includes utilities for handling
weights based on class labels.
Estimate class weights for unbalanced datasets. |
|
Estimate sample weights by class for unbalanced datasets. |
Utilities to deal with multiclass target in classifiers¶
The sklearn.utils.multiclass
module includes utilities to handle
multiclass/multioutput target in classifiers.
|
Determine the type of data indicated by the target. |
Check if |
|
Extract an ordered array of unique labels. |
Utilities for optimal mathematical operations¶
The sklearn.utils.extmath
module includes utilities to perform
optimal mathematical operations in scikit-learn that are not available in SciPy.
|
Dot product that handle the sparse matrix case correctly. |
|
Compute an orthonormal matrix whose range approximates the range of A. |
|
Compute a truncated randomized SVD. |
Compute logarithm of determinant of a square matrix. |
|
Compute density of a sparse vector. |
|
|
Return an array of the weighted modal (most common) value in the passed array. |
Utilities to work with sparse matrices and arrays¶
The sklearn.utils.sparsefuncs
module includes a collection of utilities to
work with sparse matrices and arrays.
Compute incremental mean and variance along an axis on a CSR or CSC matrix. |
|
|
Inplace column scaling of a CSC/CSR matrix. |
|
Inplace row scaling of a CSR or CSC matrix. |
|
Swap two rows of a CSC/CSR matrix in-place. |
Swap two columns of a CSC/CSR matrix in-place. |
|
|
Compute mean and variance along an axis on a CSR or CSC matrix. |
Inplace column scaling of a CSR matrix. |
The sklearn.utils.sparsefuncs_fast
module includes a collection of utilities to
work with sparse matrices and arrays written in Cython.
Inplace row normalize using the l1 norm |
|
Inplace row normalize using the l2 norm |
Utilities to work with graphs¶
The sklearn.utils.graph
module includes graph utilities and algorithms.
Return the length of the shortest path from source to all reachable nodes. |
Utilities for random sampling¶
The mod:sklearn.utils.random
module includes utilities for random sampling.
Sample integers without replacement. |
Utilities to operate on arrays¶
The sklearn.utils.arrayfuncs
module includes a small collection of auxiliary
functions that operate on arrays.
Find the minimum value of an array over positive values. |
Metadata routing¶
The sklearn.utils.metadata_routing
module includes utilities to route
metadata within scikit-learn estimators.
Get a |
|
|
Validate and route input parameters. |
Stores and handles metadata routing for a router object. |
|
Contains the metadata request info of a consumer. |
|
Stores the mapping between callee and caller methods for a router. |
Scikit-learn object discovery¶
The sklearn.utils.discovery
module includes utilities to discover
objects (i.e. estimators, displays, functions) from the sklearn
package.
|
Get a list of all estimators from |
Get a list of all displays from |
|
Get a list of all functions from |
Scikit-learn compatibility checker¶
The sklearn.utils.estimator_checks
module includes various utilities to
check the compatibility of estimators with the scikit-learn API.
Check if estimator adheres to scikit-learn conventions. |
|
Pytest specific decorator for parametrizing estimator checks. |
Utilities for parallel computing¶
The sklearn.utils.parallel
customizes joblib
tools for scikit-learn usage.
|
Decorator used to capture the arguments of a function. |
|
Change the default backend used by Parallel inside a with block. |
|
Register a new Parallel backend factory. |
|
Tweak of |