Build a text report showing the rules of a decision tree.
Note that backwards compatibility may not be supported.
The decision tree estimator to be exported. It can be an instance of DecisionTreeClassifier or DecisionTreeRegressor.
A list of length n_features containing the feature names. If None generic names will be used (“feature_0”, “feature_1”, …).
Only the first max_depth levels of the tree are exported. Truncated branches will be marked with “…”.
Number of spaces between edges. The higher it is, the wider the result.
Number of decimal digits to display.
If true the classification weights will be exported on each leaf. The classification weights are the number of samples each class.
Text summary of all the rules in the decision tree.


An extremely randomized tree classifier.
Extra-trees differ from classic decision trees in the way they are built. When looking for the best split to separate the samples of a node into two groups, random splits are drawn for each of the max_features randomly selected features and the best split among those is chosen. When max_features is set 1, this amounts to building a totally random decision tree.
Warning: Extra-trees should only be used within ensemble methods.
Read more in the User Guide.
The function to measure the quality of a split. Supported criteria are “gini” for the Gini impurity and “entropy” for the information gain.
The strategy used to choose the split at each node. Supported strategies are “best” to choose the best split and “random” to choose the best random split.
The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples.
The minimum number of samples required to split an internal node:
Changed in version 0.18: Added float values for fractions.
The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least min_samples_leaf training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression.
Changed in version 0.18: Added float values for fractions.
The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided.
The number of features to consider when looking for the best split:
Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than max_features features.
Used to pick randomly the max_features used at each split. See Glossary for details.
Grow a tree with max_leaf_nodes in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes.
A node will be split if this split induces a decrease of the impurity greater than or equal to this value.
The weighted impurity decrease equation is the following:
where N is the total number of samples, N_t is the number of samples at the current node, N_t_L is the number of samples in the left child, and N_t_R is the number of samples in the right child.
N, N_t, N_t_R and N_t_L all refer to the weighted sum, if sample_weight is passed.
New in version 0.19.
Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf.
Deprecated since version 0.19: min_impurity_split has been deprecated in favor of min_impurity_decrease in 0.19. The default value of min_impurity_split has changed from 1e-7 to 0 in 0.23 and it will be removed in 1.0 (renaming of 0.25). Use min_impurity_decrease instead.
Weights associated with classes in the form {class_label: weight}. If None, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y.
Note that for multioutput (including multilabel) weights should be defined for each class of every column in its own dict. For example, for four-class multilabel classification weights should be [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of [{1:1}, {2:5}, {3:1}, {4:1}].
The “balanced” mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as n_samples / (n_classes * np.bincount(y))
For multi-output, the weights of each column of y will be multiplied.
Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified.
Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ccp_alpha will be chosen. By default, no pruning is performed. See Minimal Cost-Complexity Pruning for details.
New in version 0.22.
The classes labels (single output problem), or a list of arrays of class labels (multi-output problem).
The inferred value of max_features.
The number of classes (for single output problems), or a list containing the number of classes for each output (for multi-output problems).
Return the feature importances.
The number of features when fit is performed.
The number of outputs when fit is performed.
The underlying Tree object. Please refer to help(sklearn.tree._tree.Tree) for attributes of Tree object and Understanding the decision tree structure for basic usage of these attributes.
See also
An extremely randomized tree regressor.
An extra-trees classifier.
An extra-trees regressor.
The default values for the parameters controlling the size of the trees (e.g. max_depth, min_samples_leaf, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values.
P. Geurts, D. Ernst., and L. Wehenkel, “Extremely randomized trees”, Machine Learning, 63(1), 3-42, 2006.
apply(X[, check_input])
Return the index of the leaf that each sample is predicted as.
cost_complexity_pruning_path(X, y[, …])
Compute the pruning path during Minimal Cost-Complexity Pruning.
decision_path(X[, check_input])
Return the decision path in the tree.
fit(X, y[, sample_weight, check_input, …])
Build a decision tree classifier from the training set (X, y).
get_depth()
Return the depth of the decision tree.
get_n_leaves()
Return the number of leaves of the decision tree.
get_params([deep])
Get parameters for this estimator.
predict(X[, check_input])
Predict class or regression value for X.
predict_log_proba(X)
Predict class log-probabilities of the input samples X.
predict_proba(X[, check_input])
Predict class probabilities of the input samples X.
score(X, y[, sample_weight])
Return the mean accuracy on the given test data and labels.
set_params(**params)
Set the parameters of this estimator.
Return the index of the leaf that each sample is predicted as.
New in version 0.17.
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within [0; self.tree_.node_count), possibly with gaps in the numbering.
Compute the pruning path during Minimal Cost-Complexity Pruning.
See Minimal Cost-Complexity Pruning for details on the pruning process.
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
The target values (class labels) as integers or strings.
Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. Splits are also ignored if they would result in any single class carrying a negative weight in either child node.
Dictionary-like object, with the following attributes.
Effective alphas of subtree during pruning.
Sum of the impurities of the subtree leaves for the corresponding alpha value in ccp_alphas.
Return the decision path in the tree.
New in version 0.18.
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes.
Return the feature importances.
The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance.
Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative.
Normalized total reduction of criteria by feature (Gini importance).
Build a decision tree classifier from the training set (X, y).
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
The target values (class labels) as integers or strings.
Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. Splits are also ignored if they would result in any single class carrying a negative weight in either child node.
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
This parameter is deprecated and has no effect. It will be removed in 1.1 (renaming of 0.26).
Deprecated since version 0.24.
Fitted estimator.
Return the depth of the decision tree.
The depth of a tree is the maximum distance between the root and any leaf.
The maximum depth of the tree.
Return the number of leaves of the decision tree.
Number of leaves.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Predict class or regression value for X.
For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned.
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
The predicted classes, or the predict values.
Predict class log-probabilities of the input samples X.
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
Predict class probabilities of the input samples X.
The predicted class probability is the fraction of samples of the same class in a leaf.
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
Return the mean accuracy on the given test data and labels.
In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.
Test samples.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.
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.
Estimator parameters.
Estimator instance.


Return the index of the leaf that each sample is predicted as.
New in version 0.17.
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within [0; self.tree_.node_count), possibly with gaps in the numbering.


Compute the pruning path during Minimal Cost-Complexity Pruning.
See Minimal Cost-Complexity Pruning for details on the pruning process.
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
The target values (class labels) as integers or strings.
Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. Splits are also ignored if they would result in any single class carrying a negative weight in either child node.
Dictionary-like object, with the following attributes.
Effective alphas of subtree during pruning.
Sum of the impurities of the subtree leaves for the corresponding alpha value in ccp_alphas.


Return the decision path in the tree.
New in version 0.18.
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes.


Return the feature importances.
The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance.
Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative.
Normalized total reduction of criteria by feature (Gini importance).


Build a decision tree classifier from the training set (X, y).
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
The target values (class labels) as integers or strings.
Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. Splits are also ignored if they would result in any single class carrying a negative weight in either child node.
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
This parameter is deprecated and has no effect. It will be removed in 1.1 (renaming of 0.26).
Deprecated since version 0.24.
Fitted estimator.


Return the depth of the decision tree.
The depth of a tree is the maximum distance between the root and any leaf.
The maximum depth of the tree.


Return the number of leaves of the decision tree.
Number of leaves.


Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.


Predict class or regression value for X.
For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned.
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
The predicted classes, or the predict values.


Predict class log-probabilities of the input samples X.
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.


Predict class probabilities of the input samples X.
The predicted class probability is the fraction of samples of the same class in a leaf.
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.


Return the mean accuracy on the given test data and labels.
In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.
Test samples.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.


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.
Estimator parameters.
Estimator instance.


An extremely randomized tree regressor.
Extra-trees differ from classic decision trees in the way they are built. When looking for the best split to separate the samples of a node into two groups, random splits are drawn for each of the max_features randomly selected features and the best split among those is chosen. When max_features is set 1, this amounts to building a totally random decision tree.
Warning: Extra-trees should only be used within ensemble methods.
Read more in the User Guide.
The function to measure the quality of a split. Supported criteria are “mse” for the mean squared error, which is equal to variance reduction as feature selection criterion and “mae” for the mean absolute error.
New in version 0.18: Mean Absolute Error (MAE) criterion.
New in version 0.24: Poisson deviance criterion.
The strategy used to choose the split at each node. Supported strategies are “best” to choose the best split and “random” to choose the best random split.
The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples.
The minimum number of samples required to split an internal node:
Changed in version 0.18: Added float values for fractions.
The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least min_samples_leaf training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression.
Changed in version 0.18: Added float values for fractions.
The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided.
The number of features to consider when looking for the best split:
Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than max_features features.
Used to pick randomly the max_features used at each split. See Glossary for details.
A node will be split if this split induces a decrease of the impurity greater than or equal to this value.
The weighted impurity decrease equation is the following:
where N is the total number of samples, N_t is the number of samples at the current node, N_t_L is the number of samples in the left child, and N_t_R is the number of samples in the right child.
N, N_t, N_t_R and N_t_L all refer to the weighted sum, if sample_weight is passed.
New in version 0.19.
Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf.
Deprecated since version 0.19: min_impurity_split has been deprecated in favor of min_impurity_decrease in 0.19. The default value of min_impurity_split has changed from 1e-7 to 0 in 0.23 and it will be removed in 1.0 (renaming of 0.25). Use min_impurity_decrease instead.
Grow a tree with max_leaf_nodes in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes.
Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ccp_alpha will be chosen. By default, no pruning is performed. See Minimal Cost-Complexity Pruning for details.
New in version 0.22.
The inferred value of max_features.
The number of features when fit is performed.
Return the feature importances.
The number of outputs when fit is performed.
The underlying Tree object. Please refer to help(sklearn.tree._tree.Tree) for attributes of Tree object and Understanding the decision tree structure for basic usage of these attributes.
See also
An extremely randomized tree classifier.
An extra-trees classifier.
An extra-trees regressor.
The default values for the parameters controlling the size of the trees (e.g. max_depth, min_samples_leaf, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values.
P. Geurts, D. Ernst., and L. Wehenkel, “Extremely randomized trees”, Machine Learning, 63(1), 3-42, 2006.
apply(X[, check_input])
Return the index of the leaf that each sample is predicted as.
cost_complexity_pruning_path(X, y[, …])
Compute the pruning path during Minimal Cost-Complexity Pruning.
decision_path(X[, check_input])
Return the decision path in the tree.
fit(X, y[, sample_weight, check_input, …])
Build a decision tree regressor from the training set (X, y).
get_depth()
Return the depth of the decision tree.
get_n_leaves()
Return the number of leaves of the decision tree.
get_params([deep])
Get parameters for this estimator.
predict(X[, check_input])
Predict class or regression value for X.
score(X, y[, sample_weight])
Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params)
Set the parameters of this estimator.
Return the index of the leaf that each sample is predicted as.
New in version 0.17.
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within [0; self.tree_.node_count), possibly with gaps in the numbering.
Compute the pruning path during Minimal Cost-Complexity Pruning.
See Minimal Cost-Complexity Pruning for details on the pruning process.
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
The target values (class labels) as integers or strings.
Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. Splits are also ignored if they would result in any single class carrying a negative weight in either child node.
Dictionary-like object, with the following attributes.
Effective alphas of subtree during pruning.
Sum of the impurities of the subtree leaves for the corresponding alpha value in ccp_alphas.
Return the decision path in the tree.
New in version 0.18.
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes.
Return the feature importances.
The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance.
Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative.
Normalized total reduction of criteria by feature (Gini importance).
Build a decision tree regressor from the training set (X, y).
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
The target values (real numbers). Use dtype=np.float64 and order='C' for maximum efficiency.
Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node.
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
This parameter is deprecated and has no effect. It will be removed in 1.1 (renaming of 0.26).
Deprecated since version 0.24.
Fitted estimator.
Return the depth of the decision tree.
The depth of a tree is the maximum distance between the root and any leaf.
The maximum depth of the tree.
Return the number of leaves of the decision tree.
Number of leaves.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Predict class or regression value for X.
For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned.
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
The predicted classes, or the predict values.
Return the coefficient of determination \(R^2\) of the prediction.
The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
True values for X.
Sample weights.
\(R^2\) of self.predict(X) wrt. y.
The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).
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.
Estimator parameters.
Estimator instance.


Build a decision tree regressor from the training set (X, y).
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
The target values (real numbers). Use dtype=np.float64 and order='C' for maximum efficiency.
Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node.
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
This parameter is deprecated and has no effect. It will be removed in 1.1 (renaming of 0.26).
Deprecated since version 0.24.
Fitted estimator.


Return the coefficient of determination \(R^2\) of the prediction.
The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
True values for X.
Sample weights.
\(R^2\) of self.predict(X) wrt. y.
The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).


Plot a decision tree.
The sample counts that are shown are weighted with any sample_weights that might be present.
The visualization is fit automatically to the size of the axis. Use the figsize or dpi arguments of plt.figure to control the size of the rendering.
Read more in the User Guide.
New in version 0.21.
The decision tree to be plotted.
The maximum depth of the representation. If None, the tree is fully generated.
Names of each of the features. If None, generic names will be used (“X[0]”, “X[1]”, …).
Names of each of the target classes in ascending numerical order. Only relevant for classification and not supported for multi-output. If True, shows a symbolic representation of the class name.
Whether to show informative labels for impurity, etc. Options include ‘all’ to show at every node, ‘root’ to show only at the top root node, or ‘none’ to not show at any node.
When set to True, paint nodes to indicate majority class for classification, extremity of values for regression, or purity of node for multi-output.
When set to True, show the impurity at each node.
When set to True, show the ID number on each node.
When set to True, change the display of ‘values’ and/or ‘samples’ to be proportions and percentages respectively.
This parameter has no effect on the matplotlib tree visualisation and it is kept here for backward compatibility.
Deprecated since version 0.23: rotate is deprecated in 0.23 and will be removed in 1.0 (renaming of 0.25).
When set to True, draw node boxes with rounded corners and use Helvetica fonts instead of Times-Roman.
Number of digits of precision for floating point in the values of impurity, threshold and value attributes of each node.
Axes to plot to. If None, use current axis. Any previous content is cleared.
Size of text font. If None, determined automatically to fit figure.
List containing the artists for the annotation boxes making up the tree.


Get a list of all estimators from sklearn.
This function crawls the module and gets all classes that inherit from BaseEstimator. Classes that are defined in test-modules are not included.
Which kind of estimators should be returned. If None, no filter is applied and all estimators are returned. Possible values are ‘classifier’, ‘regressor’, ‘cluster’ and ‘transformer’ to get estimators only of these specific types, or a list of these to get the estimators that fit at least one of the types.
List of (name, class), where name is the class name as string and class is the actuall type of the class.


Find the minimum value of an array over positive values
Returns a huge value if none of the values are positive


Throw a ValueError if X contains NaN or infinity.


Converts an array-like to an array of floats.
The new dtype will be np.float32 or np.float64, depending on the original type. The function can create a copy or modify the argument depending on the argument copy.
If True, a copy of X will be created. If False, a copy may still be returned if X’s dtype is not a floating point type.
Whether to raise an error on np.inf, np.nan, pd.NA in X. The possibilities are:
New in version 0.20: force_all_finite accepts the string 'allow-nan'.
Changed in version 0.23: Accepts pd.NA and converts it into np.nan
An array of type float.


Container object exposing keys as attributes.
Bunch objects are sometimes used as an output for functions and methods. They extend dictionaries by enabling values to be accessed by key, bunch["value_key"], or by an attribute, bunch.value_key.


Input validation on an array, list, sparse matrix or similar.
By default, the input is checked to be a non-empty 2D array containing only finite values. If the dtype of the array is object, attempt converting to float, raising on failure.
Input object to check / convert.
String[s] representing allowed sparse matrix formats, such as ‘csc’, ‘csr’, etc. If the input is sparse but not in the allowed format, it will be converted to the first listed format. True allows the input to be any format. False means that a sparse matrix input will raise an error.
If a CSR, CSC, COO or BSR sparse matrix is supplied and accepted by accept_sparse, accept_large_sparse=False will cause it to be accepted only if its indices are stored with a 32-bit dtype.
New in version 0.20.
Data type of result. If None, the dtype of the input is preserved. If “numeric”, dtype is preserved unless array.dtype is object. If dtype is a list of types, conversion on the first type is only performed if the dtype of the input is not in the list.
Whether an array will be forced to be fortran or c-style. When order is None (default), then if copy=False, nothing is ensured about the memory layout of the output array; otherwise (copy=True) the memory layout of the returned array is kept as close as possible to the original array.
Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion.
Whether to raise an error on np.inf, np.nan, pd.NA in array. The possibilities are:
New in version 0.20: force_all_finite accepts the string 'allow-nan'.
Changed in version 0.23: Accepts pd.NA and converts it into np.nan
Whether to raise a value error if array is not 2D.
Whether to allow array.ndim > 2.
Make sure that the array has a minimum number of samples in its first axis (rows for a 2D array). Setting to 0 disables this check.
Make sure that the 2D array has some minimum number of features (columns). The default value of 1 rejects empty datasets. This check is only enforced when the input data has effectively 2 dimensions or is originally 1D and ensure_2d is True. Setting to 0 disables this check.
If passed, include the name of the estimator in warning messages.
The converted and validated array.


Check that all arrays have consistent first dimensions.
Checks whether all objects in arrays have the same shape or length.
Objects that will be checked for consistent length.


Turn seed into a np.random.RandomState instance
If seed is None, return the RandomState singleton used by np.random. If seed is an int, return a new RandomState instance seeded with seed. If seed is already a RandomState instance, return it. Otherwise raise ValueError.


Validate scalar parameters type and value.
The scalar parameter to validate.
The name of the parameter to be printed in error messages.
Acceptable data types for the parameter.
The minimum valid value the parameter can take. If None (default) it is implied that the parameter does not have a lower bound.
The maximum valid value the parameter can take. If None (default) it is implied that the parameter does not have an upper bound.
If the parameter’s type does not match the desired type.
If the parameter’s value violates the given bounds.


Input validation for standard estimators.
Checks X and y for consistent length, enforces X to be 2D and y 1D. By default, X is checked to be non-empty and containing only finite values. Standard input checks are also applied to y, such as checking that y does not have np.nan or np.inf targets. For multi-label y, set multi_output=True to allow 2D and sparse y. If the dtype of X is object, attempt converting to float, raising on failure.
Input data.
Labels.
String[s] representing allowed sparse matrix formats, such as ‘csc’, ‘csr’, etc. If the input is sparse but not in the allowed format, it will be converted to the first listed format. True allows the input to be any format. False means that a sparse matrix input will raise an error.
If a CSR, CSC, COO or BSR sparse matrix is supplied and accepted by accept_sparse, accept_large_sparse will cause it to be accepted only if its indices are stored with a 32-bit dtype.
New in version 0.20.
Data type of result. If None, the dtype of the input is preserved. If “numeric”, dtype is preserved unless array.dtype is object. If dtype is a list of types, conversion on the first type is only performed if the dtype of the input is not in the list.
Whether an array will be forced to be fortran or c-style.
Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion.
Whether to raise an error on np.inf, np.nan, pd.NA in X. This parameter does not influence whether y can have np.inf, np.nan, pd.NA values. The possibilities are:
New in version 0.20: force_all_finite accepts the string 'allow-nan'.
Changed in version 0.23: Accepts pd.NA and converts it into np.nan
Whether to raise a value error if X is not 2D.
Whether to allow X.ndim > 2.
Whether to allow 2D y (array or sparse matrix). If false, y will be validated as a vector. y cannot have np.nan or np.inf values if multi_output=True.
Make sure that X has a minimum number of samples in its first axis (rows for a 2D array).
Make sure that the 2D array has some minimum number of features (columns). The default value of 1 rejects empty datasets. This check is only enforced when X has effectively 2 dimensions or is originally 1D and ensure_2d is True. Setting to 0 disables this check.
Whether to ensure that y has a numeric type. If dtype of y is object, it is converted to float64. Should only be used for regression algorithms.
If passed, include the name of the estimator in warning messages.
The converted and validated X.
The converted and validated y.


Estimate class weights for unbalanced datasets.
If ‘balanced’, class weights will be given by n_samples / (n_classes * np.bincount(y)). If a dictionary is given, keys are classes and values are corresponding class weights. If None is given, the class weights will be uniform.
Array of the classes occurring in the data, as given by np.unique(y_org) with y_org the original class labels.
Array of original class labels per sample.
Array with class_weight_vect[i] the weight for i-th class.
The “balanced” heuristic is inspired by Logistic Regression in Rare Events Data, King, Zen, 2001.


Estimate sample weights by class for unbalanced datasets.
Weights associated with classes in the form {class_label: weight}. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y.
Note that for multioutput (including multilabel) weights should be defined for each class of every column in its own dict. For example, for four-class multilabel classification weights should be [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of [{1:1}, {2:5}, {3:1}, {4:1}].
The “balanced” mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data: n_samples / (n_classes * np.bincount(y)).
For multi-output, the weights of each column of y will be multiplied.
Array of original class labels per sample.
Array of indices to be used in a subsample. Can be of length less than n_samples in the case of a subsample, or equal to n_samples in the case of a bootstrap subsample with repeated indices. If None, the sample weight will be calculated over the full sample. Only “balanced” is supported for class_weight if this is provided.
Array with sample weights as applied to the original y.


Decorator to mark a function or class as deprecated.
Issue a warning when the function is called/the class is instantiated and adds a warning to the docstring.
The optional extra argument will be appended to the deprecation message and the docstring. Note: to use this with the default value for extra, put in an empty of parentheses:
To be added to the deprecation messages.


Check if estimator adheres to scikit-learn conventions.
This estimator will run an extensive test-suite for input validation, shapes, etc, making sure that the estimator complies with scikit-learn conventions as detailed in Rolling your own estimator. Additional tests for classifiers, regressors, clustering or transformers will be run if the Estimator class inherits from the corresponding mixin from sklearn.base.
Setting generate_only=True returns a generator that yields (estimator, check) tuples where the check can be called independently from each other, i.e. check(estimator). This allows all checks to be run independently and report the checks that are failing.
scikit-learn provides a pytest specific decorator, parametrize_with_checks, making it easier to test multiple estimators.
Estimator instance to check.
Changed in version 0.24: Passing a class was deprecated in version 0.23, and support for classes was removed in 0.24.
When False, checks are evaluated when check_estimator is called. When True, check_estimator returns a generator that yields (estimator, check) tuples. The check is run by calling check(estimator).
New in version 0.22.
Generator that yields (estimator, check) tuples. Returned when generate_only=True.


Pytest specific decorator for parametrizing estimator checks.
The id of each check is set to be a pprint version of the estimator and the name of the check with its keyword arguments. This allows to use pytest -k to specify which tests to run:
Estimators to generated checks for.
Changed in version 0.24: Passing a class was deprecated in version 0.23, and support for classes was removed in 0.24. Pass an instance instead.
New in version 0.24.


Build a HTML representation of an estimator.
Read more in the User Guide.
The estimator to visualize.
HTML representation of estimator.


Compute density of a sparse vector.
The sparse vector.
The density of w, between 0 and 1.


Compute log(det(A)) for A symmetric.
Equivalent to : np.log(nl.det(A)) but more robust. It returns -Inf if det(A) is non positive or is not defined.
The matrix.


Computes an orthonormal matrix whose range approximates the range of A.
The input data matrix.
Size of the return array.
Number of power iterations used to stabilize the result.
Whether the power iterations are normalized with step-by-step QR factorization (the slowest but most accurate), ‘none’ (the fastest but numerically unstable when n_iter is large, e.g. typically 5 or larger), or ‘LU’ factorization (numerically stable but can lose slightly in accuracy). The ‘auto’ mode applies no normalization if n_iter <= 2 and switches to LU otherwise.
New in version 0.18.
The seed of the pseudo random number generator to use when shuffling the data, i.e. getting the random vectors to initialize the algorithm. Pass an int for reproducible results across multiple function calls. See Glossary.
A (size x size) projection matrix, the range of which approximates well the range of the input matrix A.
Follows Algorithm 4.3 of Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions Halko, et al., 2009 (arXiv:909) https://arxiv.org/pdf/0909.4061.pdf
An implementation of a randomized algorithm for principal component analysis A. Szlam et al. 2014


Computes a truncated randomized SVD.
Matrix to decompose.
Number of singular values and vectors to extract.
Additional number of random vectors to sample the range of M so as to ensure proper conditioning. The total number of random vectors used to find the range of M is n_components + n_oversamples. Smaller number can improve speed but can negatively impact the quality of approximation of singular vectors and singular values.
Number of power iterations. It can be used to deal with very noisy problems. When ‘auto’, it is set to 4, unless n_components is small (< .1 * min(X.shape)) n_iter in which case is set to 7. This improves precision with few components.
Changed in version 0.18.
Whether the power iterations are normalized with step-by-step QR factorization (the slowest but most accurate), ‘none’ (the fastest but numerically unstable when n_iter is large, e.g. typically 5 or larger), or ‘LU’ factorization (numerically stable but can lose slightly in accuracy). The ‘auto’ mode applies no normalization if n_iter <= 2 and switches to LU otherwise.
New in version 0.18.
Whether the algorithm should be applied to M.T instead of M. The result should approximately be the same. The ‘auto’ mode will trigger the transposition if M.shape[1] > M.shape[0] since this implementation of randomized SVD tend to be a little faster in that case.
Changed in version 0.18.
The output of a singular value decomposition is only unique up to a permutation of the signs of the singular vectors. If flip_sign is set to True, the sign ambiguity is resolved by making the largest loadings for each component in the left singular vectors positive.
The seed of the pseudo random number generator to use when shuffling the data, i.e. getting the random vectors to initialize the algorithm. Pass an int for reproducible results across multiple function calls. See Glossary.
This algorithm finds a (usually very good) approximate truncated singular value decomposition using randomization to speed up the computations. It is particularly fast on large matrices on which you wish to extract only a small number of components. In order to obtain further speed up, n_iter can be set <=2 (at the cost of loss of precision).


Dot product that handle the sparse matrix case correctly.
When False, a and b both being sparse will yield sparse output. When True, output will always be a dense array.
Sparse if a and b are sparse and dense_output=False.


Returns an array of the weighted modal (most common) value in a.
If there is more than one such value, only the first is returned. The bin-count for the modal bins is also returned.
This is an extension of the algorithm in scipy.stats.mode.
n-dimensional array of which to find mode(s).
n-dimensional array of weights for each value.
Axis along which to operate. Default is 0, i.e. the first axis.
Array of modal values.
Array of weighted counts for each mode.
See also
The value 4 appears three times: with uniform weights, the result is simply the mode of the distribution.
The value 2 has the highest score: it appears twice with weights of 1.5 and 2: the sum of these is 3.5.


Generator to create n_packs slices going up to n.
Number of slices to generate.
Number of samples. Pass n_samples when the slices are to be used for sparse matrix indexing; slicing off-the-end raises an exception, while it works for NumPy arrays.


Return the shortest path length from source to all reachable nodes.
Returns a dictionary of shortest path lengths keyed by target.
Adjacency matrix of the graph. Sparse matrix of format LIL is preferred.
Starting node for path.
Depth to stop the search - only paths of length <= cutoff are returned.


Perform a shortest-path graph search on a positive directed or undirected graph.
Array of positive distances. If vertex i is connected to vertex j, then dist_matrix[i,j] gives the distance between the vertices. If vertex i is not connected to vertex j, then dist_matrix[i,j] = 0
if True, then find the shortest path on a directed graph: only progress from a point to its neighbors, not the other way around. if False, then find the shortest path on an undirected graph: the algorithm can progress from a point to its neighbors and vice versa.
method to use. Options are ‘auto’ : attempt to choose the best method for the current problem ‘FW’ : Floyd-Warshall algorithm. O[N^3] ‘D’ : Dijkstra’s algorithm with Fibonacci stacks. O[(k+log(N))N^2]
G[i,j] gives the shortest distance from point i to point j along the graph.
As currently implemented, Dijkstra’s algorithm does not work for graphs with direction-dependent distances when directed == False. i.e., if dist_matrix[i,j] and dist_matrix[j,i] are not equal and both are nonzero, method=’D’ will not necessarily yield the correct result.
Also, these routines have not been tested for graphs with negative distances. Negative distances can lead to infinite cycles that must be handled by specialized algorithms.


Make arrays indexable for cross-validation.
Checks consistent length, passes through None, and ensures that everything can be indexed by converting sparse matrices to csr and converting non-interable objects to arrays.
List of objects to ensure sliceability.


Create a decorator for methods that are delegated to a sub-estimator
This enables ducktyping by hasattr returning True according to the sub-estimator.
Name of the sub-estimator that can be accessed as an attribute of the base object. If a list or a tuple of names are provided, the first sub-estimator that is an attribute of the base object will be used.


Check if y is in a multilabel format.
Target values.
Return True, if y is in a multilabel format, else `False.


Determine the type of data indicated by the target.
Note that this type is the most specific type that can be inferred. For example:
One of:


Extract an ordered array of unique labels.
At the moment, we also don’t allow “multiclass-multioutput” input type.
An ordered array of unique labels.


Compute the 32bit murmurhash3 of key at seed.
The underlying implementation is MurmurHash3_x86_32 generating low latency 32bits hash suitable for implementing lookup tables, Bloom filters, count min sketch or feature hashing.
The physical object to hash.
Integer seed for the hashing algorithm.
from 0 to 2 ** 32 - 1
from -(2 ** 31) to 2 ** 31 - 1


Change the default backend used by Parallel inside a with block.
If backend is a string it must match a previously registered implementation using the register_parallel_backend function.
By default the following backends are available:
‘loky’ is recommended to run functions that manipulate Python objects. ‘threading’ is a low-overhead alternative that is most efficient for functions that release the Global Interpreter Lock: e.g. I/O-bound code or CPU-bound code in a few calls to native code that explicitly releases the GIL.
In addition, if the dask and distributed Python packages are installed, it is possible to use the ‘dask’ backend for better scheduling of nested parallel calls without over-subscription and potentially distribute parallel calls over a networked cluster of several hosts.
It is also possible to use the distributed ‘ray’ backend for distributing the workload to a cluster of nodes. To use the ‘ray’ joblib backend add the following lines:
Alternatively the backend can be passed directly as an instance.
By default all available workers will be used (n_jobs=-1) unless the caller passes an explicit value for the n_jobs parameter.
This is an alternative to passing a backend='backend_name' argument to the Parallel class constructor. It is particularly useful when calling into library code that uses joblib internally but does not expose the backend argument in its own API.
Warning: this function is experimental and subject to change in a future version of joblib.
Joblib also tries to limit the oversubscription by limiting the number of threads usable in some third-party library threadpools like OpenBLAS, MKL or OpenMP. The default limit in each worker is set to max(cpu_count() // effective_n_jobs, 1) but this limit can be overwritten with the inner_max_num_threads argument which will be used to set this limit in the child processes.
New in version 0.10.


Sample integers without replacement.
Select n_samples integers from the set [0, n_population) without replacement.
The size of the set to sample from.
The number of integer to sample.
If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random.
If method == “auto”, the ratio of n_samples / n_population is used to determine which algorithm to use: If ratio is between 0 and 0.01, tracking selection is used. If ratio is between 0.01 and 0.99, numpy.random.permutation is used. If ratio is greater than 0.99, reservoir sampling is used. The order of the selected integers is undefined. If a random order is desired, the selected subset should be shuffled.
If method ==”tracking_selection”, a set based implementation is used which is suitable for n_samples <<< n_population.
If method == “reservoir_sampling”, a reservoir sampling algorithm is used which is suitable for high memory constraint or when O(n_samples) ~ O(n_population). The order of the selected integers is undefined. If a random order is desired, the selected subset should be shuffled.
If method == “pool”, a pool based algorithm is particularly fast, even faster than the tracking selection method. However, a vector containing the entire population has to be initialized. If n_samples ~ n_population, the reservoir sampling method is faster.
The sampled subsets of integer. The subset of selected integer might not be randomized, see the method argument.


Register a new Parallel backend factory.
The new backend can then be selected by passing its name as the backend argument to the Parallel class. Moreover, the default backend can be overwritten globally by setting make_default=True.
The factory can be any callable that takes no argument and return an instance of ParallelBackendBase.
Warning: this function is experimental and subject to change in a future version of joblib.
New in version 0.10.


Resample arrays or sparse matrices in a consistent way.
The default strategy implements one step of the bootstrapping procedure.
Indexable data-structures can be arrays, lists, dataframes or scipy sparse matrices with consistent first dimension.
Implements resampling with replacement. If False, this will implement (sliced) random permutations.
Number of samples to generate. If left to None this is automatically set to the first dimension of the arrays. If replace is False it should not be larger than the length of arrays.
Determines random number generation for shuffling the data. Pass an int for reproducible results across multiple function calls. See Glossary.
If not None, data is split in a stratified fashion, using this as the class labels.
Sequence of resampled copies of the collections. The original arrays are not impacted.
See also
It is possible to mix sparse and dense arrays in the same run:
Example using stratification:


Return a mask which is safe to use on X.
Data on which to apply mask.
Mask to be used on X.


Element wise squaring of array-likes and sparse matrices.
Whether to create a copy of X and operate on it or to perform inplace computation (default behaviour).


Shuffle arrays or sparse matrices in a consistent way.
This is a convenience alias to resample(*arrays, replace=False) to do random permutations of the collections.
Indexable data-structures can be arrays, lists, dataframes or scipy sparse matrices with consistent first dimension.
Determines random number generation for shuffling the data. Pass an int for reproducible results across multiple function calls. See Glossary.
Number of samples to generate. If left to None this is automatically set to the first dimension of the arrays. It should not be larger than the length of arrays.
Sequence of shuffled copies of the collections. The original arrays are not impacted.
See also
It is possible to mix sparse and dense arrays in the same run:


Compute incremental mean and variance along an axis on a CSR or CSC matrix.
last_mean, last_var are the statistics computed at the last step by this function. Both must be initialized to 0-arrays of the proper size, i.e. the number of features in X. last_n is the number of samples encountered until now.
Input data.
Axis along which the axis should be computed.
Array of means to update with the new data X. Should be of shape (n_features,) if axis=0 or (n_samples,) if axis=1.
Array of variances to update with the new data X. Should be of shape (n_features,) if axis=0 or (n_samples,) if axis=1.
Sum of the weights seen so far, excluding the current weights If not float, it should be of shape (n_samples,) if axis=0 or (n_features,) if axis=1. If float it corresponds to having same weights for all samples (or features).
If axis is set to 0 shape is (n_samples,) or if axis is set to 1 shape is (n_features,). If it is set to None, then samples are equally weighted.
New in version 0.24.
Updated feature-wise means if axis = 0 or sample-wise means if axis = 1.
Updated feature-wise variances if axis = 0 or sample-wise variances if axis = 1.
Updated number of seen samples per feature if axis=0 or number of seen features per sample if axis=1.
If weights is not None, n is a sum of the weights of the seen samples or features instead of the actual number of seen samples or features.
NaNs are ignored in the algorithm.


Inplace column scaling of a CSC/CSR matrix.
Scale each feature of the data matrix by multiplying with specific scale provided by the caller assuming a (n_samples, n_features) shape.
Matrix to normalize using the variance of the features. It should be of CSC or CSR format.
Array of precomputed feature-wise values to use for scaling.


Inplace column scaling of a CSR matrix.
Scale each feature of the data matrix by multiplying with specific scale provided by the caller assuming a (n_samples, n_features) shape.
Matrix to normalize using the variance of the features. It should be of CSR format.
Array of precomputed feature-wise values to use for scaling.


Inplace row scaling of a CSR or CSC matrix.
Scale each row of the data matrix by multiplying with specific scale provided by the caller assuming a (n_samples, n_features) shape.
Matrix to be scaled. It should be of CSR or CSC format.
Array of precomputed sample-wise values to use for scaling.


Swaps two columns of a CSC/CSR matrix in-place.
Matrix whose two columns are to be swapped. It should be of CSR or CSC format.
Index of the column of X to be swapped.
Index of the column of X to be swapped.


Swaps two rows of a CSC/CSR matrix in-place.
Matrix whose two rows are to be swapped. It should be of CSR or CSC format.
Index of the row of X to be swapped.
Index of the row of X to be swapped.


Compute mean and variance along an axis on a CSR or CSC matrix.
Input data. It can be of CSR or CSC format.
Axis along which the axis should be computed.
if axis is set to 0 shape is (n_samples,) or if axis is set to 1 shape is (n_features,). If it is set to None, then samples are equally weighted.
New in version 0.24.
If True, returns the sum of weights seen for each feature if axis=0 or each sample if axis=1.
New in version 0.24.
Feature-wise means.
Feature-wise variances.
Returned if return_sum_weights is True.


Perform is_fitted validation for estimator.
Checks if the estimator is fitted by verifying the presence of fitted attributes (ending with a trailing underscore) and otherwise raises a NotFittedError with the given message.
This utility is meant to be used internally by estimators themselves, typically in their own predict / transform methods.
estimator instance for which the check is performed.
Attribute name(s) given as string or a list/tuple of strings Eg.: ["coef_", "estimator_", ...], "coef_"
If None, estimator is considered fitted if there exist an attribute that ends with a underscore and does not start with double underscore.
The default error message is, “This %(name)s instance is not fitted yet. Call ‘fit’ with appropriate arguments before using this estimator.”
For custom messages if “%(name)s” is present in the message string, it is substituted for the estimator name.
Eg. : “Estimator, %(name)s, must be fitted before sparsifying”.
Specify whether all or any of the given attributes must exist.
If the attributes are not found.


Check that memory is joblib.Memory-like.
joblib.Memory-like means that memory can be converted into a joblib.Memory instance (typically a str denoting the location) or has the same interface (has a cache method).
If memory is not joblib.Memory-like.


Make sure that array is 2D, square and symmetric.
If the array is not symmetric, then a symmetrized version is returned. Optionally, a warning or exception is raised if the matrix is not symmetric.
Input object to check / convert. Must be two-dimensional and square, otherwise a ValueError will be raised.
Absolute tolerance for equivalence of arrays. Default = 1E-10.
If True then raise a warning if conversion is required.
If True then raise an exception if array is not symmetric.
Symmetrized version of the input array, i.e. the average of array and array.transpose(). If sparse, then duplicate entries are first summed and zeros are eliminated.


Ravel column or 1d numpy array, else raises an error.
To control display of warnings.


Checks whether the estimator’s fit method supports the given parameter.
An estimator to inspect.
The searched parameter.
Whether the parameter was found to be a named parameter of the estimator’s fit method.


Return rows, items or columns of X using indices.
Warning
This utility is documented, but private. This means that backward compatibility might be broken without any deprecation cycle.
Data from which to sample rows, items or columns. list are only supported when axis=0.
The axis along which X will be subsampled. axis=0 will select rows while axis=1 will select columns.
Subset of X on axis 0 or 1.
CSR, CSC, and LIL sparse matrices are supported. COO sparse matrices are not supported.


New in pygame 2: This module requires SDL2.
Return the number of available touch devices.
Return an integer id associated with the given index.
Return the number of fingers active for the touch device whose id is touchid.
Return a dict for the finger index active on touchid. The dict contains these keys:


Return an integer id associated with the given index.


Return a dict for the finger index active on touchid. The dict contains these keys:


Return the number of available touch devices.


Return the number of fingers active for the touch device whose id is touchid.


BufferProxy is a pygame support type, designed as the return value of the Surface.get_buffer() and Surface.get_view() methods. For all Python versions a BufferProxy object exports a C struct and Python level array interface on behalf of its parent object's buffer. For CPython 2.6 and later a new buffer interface is also exported. In pygame, BufferProxy is key to implementing the pygame.surfarray module.
BufferProxy instances can be created directly from Python code, either for a parent that exports an interface, or from a Python dict describing an object's buffer layout. The dict entries are based on the Python level array interface mapping. The following keys are recognized:
The BufferProxy class supports subclassing, instance variables, and weak references.
New in pygame 1.8.0.
Extended in pygame 1.9.2.
The Surface which returned the BufferProxy object or the object passed to a BufferProxy call.
The number of valid bytes of data exported. For discontinuous data, that is data which is not a single block of memory, the bytes within the gaps are excluded from the count. This property is equivalent to the Py_buffer C struct len field.
The buffer data as a str/bytes object. Any gaps in the exported data are removed.
Overwrite bytes in the parent object's data. The data must be C or F contiguous, otherwise a ValueError is raised. Argument buffer is a str/bytes object. An optional offset gives a start position, in bytes, within the buffer where overwriting begins. If the offset is negative or greater that or equal to the buffer proxy's length value, an IndexException is raised. If len(buffer) > proxy.length + offset, a ValueError is raised.


The number of valid bytes of data exported. For discontinuous data, that is data which is not a single block of memory, the bytes within the gaps are excluded from the count. This property is equivalent to the Py_buffer C struct len field.


The Surface which returned the BufferProxy object or the object passed to a BufferProxy call.


The buffer data as a str/bytes object. Any gaps in the exported data are removed.


Overwrite bytes in the parent object's data. The data must be C or F contiguous, otherwise a ValueError is raised. Argument buffer is a str/bytes object. An optional offset gives a start position, in bytes, within the buffer where overwriting begins. If the offset is negative or greater that or equal to the buffer proxy's length value, an IndexException is raised. If len(buffer) > proxy.length + offset, a ValueError is raised.


Pygame currently supports only Linux and v4l2 cameras.
EXPERIMENTAL!: This API may change or disappear in later pygame releases. If you use this, your code will very likely break with the next pygame release.
The Bayer to RGB function is based on:
New in pygame 1.9.0.
Allows for conversion from "RGB" to a destination colorspace of "HSV" or "YUV". The source and destination surfaces must be the same size and pixel depth. This is useful for computer vision on devices with limited processing power. Capture as small of an image as possible, transform.scale() it even smaller, and then convert the colorspace to YUV or HSV before doing any processing on it.
Checks the computer for available cameras and returns a list of strings of camera names, ready to be fed into pygame.camera.Camera.
Loads a v4l2 camera. The device is typically something like "/dev/video0". Default width and height are 640 by 480. Format is the desired colorspace of the output. This is useful for computer vision purposes. The default is RGB. The following are supported:
Opens the camera device, attempts to initialize it, and begins recording images to a buffer. The camera must be started before any of the below functions can be used.
Stops recording, uninitializes the camera, and closes it. Once a camera is stopped, the below functions cannot be used until it is started again.
If the camera supports it, get_controls will return the current settings for horizontal and vertical image flip as bools and brightness as an int. If unsupported, it will return the default values of (0, 0, 0). Note that the return values here may be different than those returned by set_controls, though these are more likely to be correct.
Allows you to change camera settings if the camera supports it. The return values will be the input values if the camera claims it succeeded or the values previously in use if not. Each argument is optional, and the desired one can be chosen by supplying the keyword, like hflip. Note that the actual settings being used by the camera may not be the same as those returned by set_controls.
Returns the current dimensions of the images being captured by the camera. This will return the actual size, which may be different than the one specified during initialization if the camera did not support that size.
If an image is ready to get, it returns true. Otherwise it returns false. Note that some webcams will always return False and will only queue a frame when called with a blocking function like get_image(). This is useful to separate the framerate of the game from that of the camera without having to use threading.
Pulls an image off of the buffer as an RGB Surface. It can optionally reuse an existing Surface to save time. The bit-depth of the surface is either 24 bits or the same as the optionally supplied Surface.
Gets an image from a camera as a string in the native pixelformat of the camera. Useful for integration with other libraries.


Loads a v4l2 camera. The device is typically something like "/dev/video0". Default width and height are 640 by 480. Format is the desired colorspace of the output. This is useful for computer vision purposes. The default is RGB. The following are supported:
Opens the camera device, attempts to initialize it, and begins recording images to a buffer. The camera must be started before any of the below functions can be used.
Stops recording, uninitializes the camera, and closes it. Once a camera is stopped, the below functions cannot be used until it is started again.
If the camera supports it, get_controls will return the current settings for horizontal and vertical image flip as bools and brightness as an int. If unsupported, it will return the default values of (0, 0, 0). Note that the return values here may be different than those returned by set_controls, though these are more likely to be correct.
Allows you to change camera settings if the camera supports it. The return values will be the input values if the camera claims it succeeded or the values previously in use if not. Each argument is optional, and the desired one can be chosen by supplying the keyword, like hflip. Note that the actual settings being used by the camera may not be the same as those returned by set_controls.
Returns the current dimensions of the images being captured by the camera. This will return the actual size, which may be different than the one specified during initialization if the camera did not support that size.
If an image is ready to get, it returns true. Otherwise it returns false. Note that some webcams will always return False and will only queue a frame when called with a blocking function like get_image(). This is useful to separate the framerate of the game from that of the camera without having to use threading.
Pulls an image off of the buffer as an RGB Surface. It can optionally reuse an existing Surface to save time. The bit-depth of the surface is either 24 bits or the same as the optionally supplied Surface.
Gets an image from a camera as a string in the native pixelformat of the camera. Useful for integration with other libraries.


If the camera supports it, get_controls will return the current settings for horizontal and vertical image flip as bools and brightness as an int. If unsupported, it will return the default values of (0, 0, 0). Note that the return values here may be different than those returned by set_controls, though these are more likely to be correct.


Pulls an image off of the buffer as an RGB Surface. It can optionally reuse an existing Surface to save time. The bit-depth of the surface is either 24 bits or the same as the optionally supplied Surface.


Gets an image from a camera as a string in the native pixelformat of the camera. Useful for integration with other libraries.


Returns the current dimensions of the images being captured by the camera. This will return the actual size, which may be different than the one specified during initialization if the camera did not support that size.


If an image is ready to get, it returns true. Otherwise it returns false. Note that some webcams will always return False and will only queue a frame when called with a blocking function like get_image(). This is useful to separate the framerate of the game from that of the camera without having to use threading.


Allows you to change camera settings if the camera supports it. The return values will be the input values if the camera claims it succeeded or the values previously in use if not. Each argument is optional, and the desired one can be chosen by supplying the keyword, like hflip. Note that the actual settings being used by the camera may not be the same as those returned by set_controls.


Opens the camera device, attempts to initialize it, and begins recording images to a buffer. The camera must be started before any of the below functions can be used.


Stops recording, uninitializes the camera, and closes it. Once a camera is stopped, the below functions cannot be used until it is started again.


Allows for conversion from "RGB" to a destination colorspace of "HSV" or "YUV". The source and destination surfaces must be the same size and pixel depth. This is useful for computer vision on devices with limited processing power. Capture as small of an image as possible, transform.scale() it even smaller, and then convert the colorspace to YUV or HSV before doing any processing on it.


Checks the computer for available cameras and returns a list of strings of camera names, ready to be fed into pygame.camera.Camera.


The cdrom module manages the CD and DVD drives on a computer. It can also control the playback of audio CDs. This module needs to be initialized before it can do anything. Each CD object you create represents a cdrom drive and must also be initialized individually before it can do most things.
Initialize the cdrom module. This will scan the system for all CD devices. The module must be initialized before any other functions will work. This automatically happens when you call pygame.init().
It is safe to call this function more than once.
Uninitialize the cdrom module. After you call this any existing CD objects will no longer work.
It is safe to call this function more than once.
Test if the cdrom module is initialized or not. This is different than the CD.init() since each drive must also be initialized individually.
Return the number of cd drives on the system. When you create CD objects you need to pass an integer id that must be lower than this count. The count will be 0 if there are no drives on the system.
You can create a CD object for each cdrom on the system. Use pygame.cdrom.get_count() to determine how many drives actually exist. The id argument is an integer of the drive, starting at zero.
The CD object is not initialized, you can only call CD.get_id() and CD.get_name() on an uninitialized drive.
It is safe to create multiple CD objects for the same drive, they will all cooperate normally.
Initialize the cdrom drive for use. The drive must be initialized for most CD methods to work. Even if the rest of pygame has been initialized.
There may be a brief pause while the drive is initialized. Avoid CD.init() if the program should not stop for a second or two.
Uninitialize a drive for use. Call this when your program will not be accessing the drive for awhile.
Test if this CDROM device is initialized. This is different than the pygame.cdrom.init() since each drive must also be initialized individually.
Playback audio from an audio cdrom in the drive. Besides the track number argument, you can also pass a starting and ending time for playback. The start and end time are in seconds, and can limit the section of an audio track played.
If you pass a start time but no end, the audio will play to the end of the track. If you pass a start time and 'None' for the end time, the audio will play to the end of the entire disc.
See the CD.get_numtracks() and CD.get_track_audio() to find tracks to playback.
Note, track 0 is the first track on the CD. Track numbers start at zero.
Stops playback of audio from the cdrom. This will also lose the current playback position. This method does nothing if the drive isn't already playing audio.
Temporarily stop audio playback on the CD. The playback can be resumed at the same point with the CD.resume() method. If the CD is not playing this method does nothing.
Note, track 0 is the first track on the CD. Track numbers start at zero.
Unpause a paused CD. If the CD is not paused or already playing, this method does nothing.
This will open the cdrom drive and eject the cdrom. If the drive is playing or paused it will be stopped.
Returns the integer id that was used to create the CD instance. This method can work on an uninitialized CD.
Return the string name of the drive. This is the system name used to represent the drive. It is often the drive letter or device name. This method can work on an uninitialized CD.
Returns True if the drive busy playing back audio.
Returns True if the drive is currently paused.
Returns both the current track and time of that track. This method works when the drive is either playing or paused.
Note, track 0 is the first track on the CD. Track numbers start at zero.
Return False if there is a cdrom currently in the drive. If the drive is empty this will return True.
Return the number of tracks on the cdrom in the drive. This will return zero of the drive is empty or has no tracks.
Determine if a track on a cdrom contains audio data. You can also call CD.num_tracks() and CD.get_all() to determine more information about the cdrom.
Note, track 0 is the first track on the CD. Track numbers start at zero.
Return a list with information for every track on the cdrom. The information consists of a tuple with four values. The audio value is True if the track contains audio data. The start, end, and length values are floating point numbers in seconds. Start and end represent absolute times on the entire disc.
Return the absolute time in seconds where at start of the cdrom track.
Note, track 0 is the first track on the CD. Track numbers start at zero.
Return a floating point value in seconds of the length of the cdrom track.
Note, track 0 is the first track on the CD. Track numbers start at zero.


You can create a CD object for each cdrom on the system. Use pygame.cdrom.get_count() to determine how many drives actually exist. The id argument is an integer of the drive, starting at zero.
The CD object is not initialized, you can only call CD.get_id() and CD.get_name() on an uninitialized drive.
It is safe to create multiple CD objects for the same drive, they will all cooperate normally.
Initialize the cdrom drive for use. The drive must be initialized for most CD methods to work. Even if the rest of pygame has been initialized.
There may be a brief pause while the drive is initialized. Avoid CD.init() if the program should not stop for a second or two.
Uninitialize a drive for use. Call this when your program will not be accessing the drive for awhile.
Test if this CDROM device is initialized. This is different than the pygame.cdrom.init() since each drive must also be initialized individually.
Playback audio from an audio cdrom in the drive. Besides the track number argument, you can also pass a starting and ending time for playback. The start and end time are in seconds, and can limit the section of an audio track played.
If you pass a start time but no end, the audio will play to the end of the track. If you pass a start time and 'None' for the end time, the audio will play to the end of the entire disc.
See the CD.get_numtracks() and CD.get_track_audio() to find tracks to playback.
Note, track 0 is the first track on the CD. Track numbers start at zero.
Stops playback of audio from the cdrom. This will also lose the current playback position. This method does nothing if the drive isn't already playing audio.
Temporarily stop audio playback on the CD. The playback can be resumed at the same point with the CD.resume() method. If the CD is not playing this method does nothing.
Note, track 0 is the first track on the CD. Track numbers start at zero.
Unpause a paused CD. If the CD is not paused or already playing, this method does nothing.
This will open the cdrom drive and eject the cdrom. If the drive is playing or paused it will be stopped.
Returns the integer id that was used to create the CD instance. This method can work on an uninitialized CD.
Return the string name of the drive. This is the system name used to represent the drive. It is often the drive letter or device name. This method can work on an uninitialized CD.
Returns True if the drive busy playing back audio.
Returns True if the drive is currently paused.
Returns both the current track and time of that track. This method works when the drive is either playing or paused.
Note, track 0 is the first track on the CD. Track numbers start at zero.
Return False if there is a cdrom currently in the drive. If the drive is empty this will return True.
Return the number of tracks on the cdrom in the drive. This will return zero of the drive is empty or has no tracks.
Determine if a track on a cdrom contains audio data. You can also call CD.num_tracks() and CD.get_all() to determine more information about the cdrom.
Note, track 0 is the first track on the CD. Track numbers start at zero.
Return a list with information for every track on the cdrom. The information consists of a tuple with four values. The audio value is True if the track contains audio data. The start, end, and length values are floating point numbers in seconds. Start and end represent absolute times on the entire disc.
Return the absolute time in seconds where at start of the cdrom track.
Note, track 0 is the first track on the CD. Track numbers start at zero.
Return a floating point value in seconds of the length of the cdrom track.
Note, track 0 is the first track on the CD. Track numbers start at zero.


This will open the cdrom drive and eject the cdrom. If the drive is playing or paused it will be stopped.


Return a list with information for every track on the cdrom. The information consists of a tuple with four values. The audio value is True if the track contains audio data. The start, end, and length values are floating point numbers in seconds. Start and end represent absolute times on the entire disc.


Returns True if the drive busy playing back audio.


Returns both the current track and time of that track. This method works when the drive is either playing or paused.
Note, track 0 is the first track on the CD. Track numbers start at zero.


Return False if there is a cdrom currently in the drive. If the drive is empty this will return True.


Returns the integer id that was used to create the CD instance. This method can work on an uninitialized CD.


Test if this CDROM device is initialized. This is different than the pygame.cdrom.init() since each drive must also be initialized individually.


Return the string name of the drive. This is the system name used to represent the drive. It is often the drive letter or device name. This method can work on an uninitialized CD.


Return the number of tracks on the cdrom in the drive. This will return zero of the drive is empty or has no tracks.


Returns True if the drive is currently paused.


Determine if a track on a cdrom contains audio data. You can also call CD.num_tracks() and CD.get_all() to determine more information about the cdrom.
Note, track 0 is the first track on the CD. Track numbers start at zero.


Return a floating point value in seconds of the length of the cdrom track.
Note, track 0 is the first track on the CD. Track numbers start at zero.


Return the absolute time in seconds where at start of the cdrom track.
Note, track 0 is the first track on the CD. Track numbers start at zero.


Initialize the cdrom drive for use. The drive must be initialized for most CD methods to work. Even if the rest of pygame has been initialized.
There may be a brief pause while the drive is initialized. Avoid CD.init() if the program should not stop for a second or two.


Temporarily stop audio playback on the CD. The playback can be resumed at the same point with the CD.resume() method. If the CD is not playing this method does nothing.
Note, track 0 is the first track on the CD. Track numbers start at zero.


Playback audio from an audio cdrom in the drive. Besides the track number argument, you can also pass a starting and ending time for playback. The start and end time are in seconds, and can limit the section of an audio track played.
If you pass a start time but no end, the audio will play to the end of the track. If you pass a start time and 'None' for the end time, the audio will play to the end of the entire disc.
See the CD.get_numtracks() and CD.get_track_audio() to find tracks to playback.
Note, track 0 is the first track on the CD. Track numbers start at zero.


Uninitialize a drive for use. Call this when your program will not be accessing the drive for awhile.


Unpause a paused CD. If the CD is not paused or already playing, this method does nothing.


Stops playback of audio from the cdrom. This will also lose the current playback position. This method does nothing if the drive isn't already playing audio.


Return the number of cd drives on the system. When you create CD objects you need to pass an integer id that must be lower than this count. The count will be 0 if there are no drives on the system.


Test if the cdrom module is initialized or not. This is different than the CD.init() since each drive must also be initialized individually.


Initialize the cdrom module. This will scan the system for all CD devices. The module must be initialized before any other functions will work. This automatically happens when you call pygame.init().
It is safe to call this function more than once.


Uninitialize the cdrom module. After you call this any existing CD objects will no longer work.
It is safe to call this function more than once.


The Color class represents RGBA color values using a value range of 0 to 255 inclusive. It allows basic arithmetic operations — binary operations +, -, *, //, %, and unary operation ~ — to create new colors, supports conversions to other color spaces such as HSV or HSL and lets you adjust single color channels. Alpha defaults to 255 (fully opaque) when not given. The arithmetic operations and correct_gamma() method preserve subclasses. For the binary operators, the class of the returned color is that of the left hand color object of the operator.
Color objects support equality comparison with other color objects and 3 or 4 element tuples of integers. There was a bug in pygame 1.8.1 where the default alpha was 0, not 255 like previously.
Color objects export the C level array interface. The interface exports a read-only one dimensional unsigned byte array of the same assigned length as the color. For CPython 2.6 and later, the new buffer interface is also exported, with the same characteristics as the array interface.
The floor division, //, and modulus, %, operators do not raise an exception for division by zero. Instead, if a color, or alpha, channel in the right hand color is 0, then the result is 0. For example:
color value (see note below for the supported formats)
Note
a newly created Color object
Color
Changed in pygame 2.0.0: Support for tuples, lists, and Color objects when creating Color objects.
Changed in pygame 1.9.2: Color objects export the C level array interface.
Changed in pygame 1.9.0: Color objects support 4-element tuples of integers.
Changed in pygame 1.8.1: New implementation of the class.
The red value of the Color.
The green value of the Color.
The blue value of the Color.
The alpha value of the Color.
The CMY representation of the Color. The CMY components are in the ranges C = [0, 1], M = [0, 1], Y = [0, 1]. Note that this will not return the absolutely exact CMY values for the set RGB values in all cases. Due to the RGB mapping from 0-255 and the CMY mapping from 0-1 rounding errors may cause the CMY values to differ slightly from what you might expect.
The HSVA representation of the Color. The HSVA components are in the ranges H = [0, 360], S = [0, 100], V = [0, 100], A = [0, 100]. Note that this will not return the absolutely exact HSV values for the set RGB values in all cases. Due to the RGB mapping from 0-255 and the HSV mapping from 0-100 and 0-360 rounding errors may cause the HSV values to differ slightly from what you might expect.
The HSLA representation of the Color. The HSLA components are in the ranges H = [0, 360], S = [0, 100], V = [0, 100], A = [0, 100]. Note that this will not return the absolutely exact HSL values for the set RGB values in all cases. Due to the RGB mapping from 0-255 and the HSL mapping from 0-100 and 0-360 rounding errors may cause the HSL values to differ slightly from what you might expect.
The I1I2I3 representation of the Color. The I1I2I3 components are in the ranges I1 = [0, 1], I2 = [-0.5, 0.5], I3 = [-0.5, 0.5]. Note that this will not return the absolutely exact I1I2I3 values for the set RGB values in all cases. Due to the RGB mapping from 0-255 and the I1I2I3 mapping from 0-1 rounding errors may cause the I1I2I3 values to differ slightly from what you might expect.
Returns the normalized RGBA values of the Color as floating point values.
Applies a certain gamma value to the Color and returns a new Color with the adjusted RGBA values.
The default Color length is 4. Colors can have lengths 1,2,3 or 4. This is useful if you want to unpack to r,g,b and not r,g,b,a. If you want to get the length of a Color do len(acolor).
New in pygame 1.9.0.
Returns a Color which is a linear interpolation between self and the given Color in RGBA space. The second parameter determines how far between self and other the result is going to be. It must be a value between 0 and 1 where 0 means self and 1 means other will be returned.
New in pygame 2.0.1.
Returns a new Color where each of the red, green and blue colour channels have been multiplied by the alpha channel of the original color. The alpha channel remains unchanged.
This is useful when working with the BLEND_PREMULTIPLIED blending mode flag for pygame.Surface.blit(), which assumes that all surfaces using it are using pre-multiplied alpha colors.
New in pygame 2.0.0.
Sets the elements of the color. See parameters for pygame.Color() for the parameters of this function. If the alpha value was not set it will not change.
New in pygame 2.0.1.


The CMY representation of the Color. The CMY components are in the ranges C = [0, 1], M = [0, 1], Y = [0, 1]. Note that this will not return the absolutely exact CMY values for the set RGB values in all cases. Due to the RGB mapping from 0-255 and the CMY mapping from 0-1 rounding errors may cause the CMY values to differ slightly from what you might expect.


Applies a certain gamma value to the Color and returns a new Color with the adjusted RGBA values.


The HSLA representation of the Color. The HSLA components are in the ranges H = [0, 360], S = [0, 100], V = [0, 100], A = [0, 100]. Note that this will not return the absolutely exact HSL values for the set RGB values in all cases. Due to the RGB mapping from 0-255 and the HSL mapping from 0-100 and 0-360 rounding errors may cause the HSL values to differ slightly from what you might expect.


The HSVA representation of the Color. The HSVA components are in the ranges H = [0, 360], S = [0, 100], V = [0, 100], A = [0, 100]. Note that this will not return the absolutely exact HSV values for the set RGB values in all cases. Due to the RGB mapping from 0-255 and the HSV mapping from 0-100 and 0-360 rounding errors may cause the HSV values to differ slightly from what you might expect.


The I1I2I3 representation of the Color. The I1I2I3 components are in the ranges I1 = [0, 1], I2 = [-0.5, 0.5], I3 = [-0.5, 0.5]. Note that this will not return the absolutely exact I1I2I3 values for the set RGB values in all cases. Due to the RGB mapping from 0-255 and the I1I2I3 mapping from 0-1 rounding errors may cause the I1I2I3 values to differ slightly from what you might expect.


Returns a Color which is a linear interpolation between self and the given Color in RGBA space. The second parameter determines how far between self and other the result is going to be. It must be a value between 0 and 1 where 0 means self and 1 means other will be returned.
New in pygame 2.0.1.


Returns the normalized RGBA values of the Color as floating point values.


Returns a new Color where each of the red, green and blue colour channels have been multiplied by the alpha channel of the original color. The alpha channel remains unchanged.
This is useful when working with the BLEND_PREMULTIPLIED blending mode flag for pygame.Surface.blit(), which assumes that all surfaces using it are using pre-multiplied alpha colors.
New in pygame 2.0.0.


The default Color length is 4. Colors can have lengths 1,2,3 or 4. This is useful if you want to unpack to r,g,b and not r,g,b,a. If you want to get the length of a Color do len(acolor).
New in pygame 1.9.0.


Sets the elements of the color. See parameters for pygame.Color() for the parameters of this function. If the alpha value was not set it will not change.
New in pygame 2.0.1.


Pygame offers control over the system hardware cursor. Pygame only supports black and white cursors for the system. You control the cursor with functions inside pygame.mouse.
This cursors module contains functions for loading and decoding various cursor formats. These allow you to easily store your cursors in external files or directly as encoded python strings.
The module includes several standard cursors. The pygame.mouse.set_cursor() function takes several arguments. All those arguments have been stored in a single tuple you can call like this:
The following variables can be passed to pygame.mouse.set_cursor function:
This module also contains a few cursors as formatted strings. You'll need to pass these to pygame.cursors.compile() function before you can use them. The example call would look like this:
The following strings can be converted into cursor bitmaps with pygame.cursors.compile() :
A sequence of strings can be used to create binary cursor data for the system cursor. This returns the binary data in the form of two tuples. Those can be passed as the third and fourth arguments respectively of the pygame.mouse.set_cursor() function.
If you are creating your own cursor strings, you can use any value represent the black and white pixels. Some system allow you to set a special toggle color for the system color, this is also called the xor color. If the system does not support xor cursors, that color will simply be black.
The height must be divisible by 8. The width of the strings must all be equal and be divisible by 8. If these two conditions are not met, ValueError is raised. An example set of cursor strings looks like this
This loads cursors for a simple subset of XBM files. XBM files are traditionally used to store cursors on UNIX systems, they are an ASCII format used to represent simple images.
Sometimes the black and white color values will be split into two separate XBM files. You can pass a second maskfile argument to load the two images into a single cursor.
The cursorfile and maskfile arguments can either be filenames or file-like object with the readlines method.
The return value cursor_args can be passed directly to the pygame.mouse.set_cursor() function.


A sequence of strings can be used to create binary cursor data for the system cursor. This returns the binary data in the form of two tuples. Those can be passed as the third and fourth arguments respectively of the pygame.mouse.set_cursor() function.
If you are creating your own cursor strings, you can use any value represent the black and white pixels. Some system allow you to set a special toggle color for the system color, this is also called the xor color. If the system does not support xor cursors, that color will simply be black.
The height must be divisible by 8. The width of the strings must all be equal and be divisible by 8. If these two conditions are not met, ValueError is raised. An example set of cursor strings looks like this


This loads cursors for a simple subset of XBM files. XBM files are traditionally used to store cursors on UNIX systems, they are an ASCII format used to represent simple images.
Sometimes the black and white color values will be split into two separate XBM files. You can pass a second maskfile argument to load the two images into a single cursor.
The cursorfile and maskfile arguments can either be filenames or file-like object with the readlines method.
The return value cursor_args can be passed directly to the pygame.mouse.set_cursor() function.