doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
partial_fit(X, y, classes=None, sample_weight=None) [source] Incremental fit on a batch of samples. This method is expected to be called several times consecutively on different chunks of a dataset so as to implement out-of-core or online learning. This is especially useful when the whole dataset is too big to fit in memory at once. This method has some performance overhead hence it is better to call partial_fit on chunks of data that are as large as possible (as long as fitting in the memory budget) to hide the overhead. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. yarray-like of shape (n_samples,) Target values. classesarray-like of shape (n_classes), default=None List of all the classes that can possibly appear in the y vector. Must be provided at the first call to partial_fit, can be omitted in subsequent calls. sample_weightarray-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). Returns selfobject
sklearn.modules.generated.sklearn.naive_bayes.complementnb#sklearn.naive_bayes.ComplementNB.partial_fit
predict(X) [source] Perform classification on an array of test vectors X. Parameters Xarray-like of shape (n_samples, n_features) Returns Cndarray of shape (n_samples,) Predicted target values for X
sklearn.modules.generated.sklearn.naive_bayes.complementnb#sklearn.naive_bayes.ComplementNB.predict
predict_log_proba(X) [source] Return log-probability estimates for the test vector X. Parameters Xarray-like of shape (n_samples, n_features) Returns Carray-like of shape (n_samples, n_classes) Returns the log-probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_.
sklearn.modules.generated.sklearn.naive_bayes.complementnb#sklearn.naive_bayes.ComplementNB.predict_log_proba
predict_proba(X) [source] Return probability estimates for the test vector X. Parameters Xarray-like of shape (n_samples, n_features) Returns Carray-like of shape (n_samples, n_classes) Returns the probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_.
sklearn.modules.generated.sklearn.naive_bayes.complementnb#sklearn.naive_bayes.ComplementNB.predict_proba
score(X, y, sample_weight=None) [source] 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. Parameters Xarray-like of shape (n_samples, n_features) Test samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True labels for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat Mean accuracy of self.predict(X) wrt. y.
sklearn.modules.generated.sklearn.naive_bayes.complementnb#sklearn.naive_bayes.ComplementNB.score
set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
sklearn.modules.generated.sklearn.naive_bayes.complementnb#sklearn.naive_bayes.ComplementNB.set_params
class sklearn.naive_bayes.GaussianNB(*, priors=None, var_smoothing=1e-09) [source] Gaussian Naive Bayes (GaussianNB) Can perform online updates to model parameters via partial_fit. For details on algorithm used to update feature means and variance online, see Stanford CS tech report STAN-CS-79-773 by Chan, Golub, and LeVeque: http://i.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf Read more in the User Guide. Parameters priorsarray-like of shape (n_classes,) Prior probabilities of the classes. If specified the priors are not adjusted according to the data. var_smoothingfloat, default=1e-9 Portion of the largest variance of all features that is added to variances for calculation stability. New in version 0.20. Attributes class_count_ndarray of shape (n_classes,) number of training samples observed in each class. class_prior_ndarray of shape (n_classes,) probability of each class. classes_ndarray of shape (n_classes,) class labels known to the classifier epsilon_float absolute additive value to variances sigma_ndarray of shape (n_classes, n_features) variance of each feature per class theta_ndarray of shape (n_classes, n_features) mean of each feature per class Examples >>> import numpy as np >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) >>> Y = np.array([1, 1, 1, 2, 2, 2]) >>> from sklearn.naive_bayes import GaussianNB >>> clf = GaussianNB() >>> clf.fit(X, Y) GaussianNB() >>> print(clf.predict([[-0.8, -1]])) [1] >>> clf_pf = GaussianNB() >>> clf_pf.partial_fit(X, Y, np.unique(Y)) GaussianNB() >>> print(clf_pf.predict([[-0.8, -1]])) [1] Methods fit(X, y[, sample_weight]) Fit Gaussian Naive Bayes according to X, y get_params([deep]) Get parameters for this estimator. partial_fit(X, y[, classes, sample_weight]) Incremental fit on a batch of samples. predict(X) Perform classification on an array of test vectors X. predict_log_proba(X) Return log-probability estimates for the test vector X. predict_proba(X) Return probability estimates for the test vector 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. fit(X, y, sample_weight=None) [source] Fit Gaussian Naive Bayes according to X, y Parameters Xarray-like of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. yarray-like of shape (n_samples,) Target values. sample_weightarray-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). New in version 0.17: Gaussian Naive Bayes supports fitting with sample_weight. Returns selfobject get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. partial_fit(X, y, classes=None, sample_weight=None) [source] Incremental fit on a batch of samples. This method is expected to be called several times consecutively on different chunks of a dataset so as to implement out-of-core or online learning. This is especially useful when the whole dataset is too big to fit in memory at once. This method has some performance and numerical stability overhead, hence it is better to call partial_fit on chunks of data that are as large as possible (as long as fitting in the memory budget) to hide the overhead. Parameters Xarray-like of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. yarray-like of shape (n_samples,) Target values. classesarray-like of shape (n_classes,), default=None List of all the classes that can possibly appear in the y vector. Must be provided at the first call to partial_fit, can be omitted in subsequent calls. sample_weightarray-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). New in version 0.17. Returns selfobject predict(X) [source] Perform classification on an array of test vectors X. Parameters Xarray-like of shape (n_samples, n_features) Returns Cndarray of shape (n_samples,) Predicted target values for X predict_log_proba(X) [source] Return log-probability estimates for the test vector X. Parameters Xarray-like of shape (n_samples, n_features) Returns Carray-like of shape (n_samples, n_classes) Returns the log-probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. predict_proba(X) [source] Return probability estimates for the test vector X. Parameters Xarray-like of shape (n_samples, n_features) Returns Carray-like of shape (n_samples, n_classes) Returns the probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. score(X, y, sample_weight=None) [source] 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. Parameters Xarray-like of shape (n_samples, n_features) Test samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True labels for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat Mean accuracy of self.predict(X) wrt. y. set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
sklearn.modules.generated.sklearn.naive_bayes.gaussiannb#sklearn.naive_bayes.GaussianNB
sklearn.naive_bayes.GaussianNB class sklearn.naive_bayes.GaussianNB(*, priors=None, var_smoothing=1e-09) [source] Gaussian Naive Bayes (GaussianNB) Can perform online updates to model parameters via partial_fit. For details on algorithm used to update feature means and variance online, see Stanford CS tech report STAN-CS-79-773 by Chan, Golub, and LeVeque: http://i.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf Read more in the User Guide. Parameters priorsarray-like of shape (n_classes,) Prior probabilities of the classes. If specified the priors are not adjusted according to the data. var_smoothingfloat, default=1e-9 Portion of the largest variance of all features that is added to variances for calculation stability. New in version 0.20. Attributes class_count_ndarray of shape (n_classes,) number of training samples observed in each class. class_prior_ndarray of shape (n_classes,) probability of each class. classes_ndarray of shape (n_classes,) class labels known to the classifier epsilon_float absolute additive value to variances sigma_ndarray of shape (n_classes, n_features) variance of each feature per class theta_ndarray of shape (n_classes, n_features) mean of each feature per class Examples >>> import numpy as np >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) >>> Y = np.array([1, 1, 1, 2, 2, 2]) >>> from sklearn.naive_bayes import GaussianNB >>> clf = GaussianNB() >>> clf.fit(X, Y) GaussianNB() >>> print(clf.predict([[-0.8, -1]])) [1] >>> clf_pf = GaussianNB() >>> clf_pf.partial_fit(X, Y, np.unique(Y)) GaussianNB() >>> print(clf_pf.predict([[-0.8, -1]])) [1] Methods fit(X, y[, sample_weight]) Fit Gaussian Naive Bayes according to X, y get_params([deep]) Get parameters for this estimator. partial_fit(X, y[, classes, sample_weight]) Incremental fit on a batch of samples. predict(X) Perform classification on an array of test vectors X. predict_log_proba(X) Return log-probability estimates for the test vector X. predict_proba(X) Return probability estimates for the test vector 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. fit(X, y, sample_weight=None) [source] Fit Gaussian Naive Bayes according to X, y Parameters Xarray-like of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. yarray-like of shape (n_samples,) Target values. sample_weightarray-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). New in version 0.17: Gaussian Naive Bayes supports fitting with sample_weight. Returns selfobject get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. partial_fit(X, y, classes=None, sample_weight=None) [source] Incremental fit on a batch of samples. This method is expected to be called several times consecutively on different chunks of a dataset so as to implement out-of-core or online learning. This is especially useful when the whole dataset is too big to fit in memory at once. This method has some performance and numerical stability overhead, hence it is better to call partial_fit on chunks of data that are as large as possible (as long as fitting in the memory budget) to hide the overhead. Parameters Xarray-like of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. yarray-like of shape (n_samples,) Target values. classesarray-like of shape (n_classes,), default=None List of all the classes that can possibly appear in the y vector. Must be provided at the first call to partial_fit, can be omitted in subsequent calls. sample_weightarray-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). New in version 0.17. Returns selfobject predict(X) [source] Perform classification on an array of test vectors X. Parameters Xarray-like of shape (n_samples, n_features) Returns Cndarray of shape (n_samples,) Predicted target values for X predict_log_proba(X) [source] Return log-probability estimates for the test vector X. Parameters Xarray-like of shape (n_samples, n_features) Returns Carray-like of shape (n_samples, n_classes) Returns the log-probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. predict_proba(X) [source] Return probability estimates for the test vector X. Parameters Xarray-like of shape (n_samples, n_features) Returns Carray-like of shape (n_samples, n_classes) Returns the probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. score(X, y, sample_weight=None) [source] 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. Parameters Xarray-like of shape (n_samples, n_features) Test samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True labels for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat Mean accuracy of self.predict(X) wrt. y. set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance. Examples using sklearn.naive_bayes.GaussianNB Comparison of Calibration of Classifiers Probability Calibration curves Probability calibration of classifiers Classifier comparison Plot class probabilities calculated by the VotingClassifier Plotting Learning Curves Importance of Feature Scaling
sklearn.modules.generated.sklearn.naive_bayes.gaussiannb
fit(X, y, sample_weight=None) [source] Fit Gaussian Naive Bayes according to X, y Parameters Xarray-like of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. yarray-like of shape (n_samples,) Target values. sample_weightarray-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). New in version 0.17: Gaussian Naive Bayes supports fitting with sample_weight. Returns selfobject
sklearn.modules.generated.sklearn.naive_bayes.gaussiannb#sklearn.naive_bayes.GaussianNB.fit
get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values.
sklearn.modules.generated.sklearn.naive_bayes.gaussiannb#sklearn.naive_bayes.GaussianNB.get_params
partial_fit(X, y, classes=None, sample_weight=None) [source] Incremental fit on a batch of samples. This method is expected to be called several times consecutively on different chunks of a dataset so as to implement out-of-core or online learning. This is especially useful when the whole dataset is too big to fit in memory at once. This method has some performance and numerical stability overhead, hence it is better to call partial_fit on chunks of data that are as large as possible (as long as fitting in the memory budget) to hide the overhead. Parameters Xarray-like of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. yarray-like of shape (n_samples,) Target values. classesarray-like of shape (n_classes,), default=None List of all the classes that can possibly appear in the y vector. Must be provided at the first call to partial_fit, can be omitted in subsequent calls. sample_weightarray-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). New in version 0.17. Returns selfobject
sklearn.modules.generated.sklearn.naive_bayes.gaussiannb#sklearn.naive_bayes.GaussianNB.partial_fit
predict(X) [source] Perform classification on an array of test vectors X. Parameters Xarray-like of shape (n_samples, n_features) Returns Cndarray of shape (n_samples,) Predicted target values for X
sklearn.modules.generated.sklearn.naive_bayes.gaussiannb#sklearn.naive_bayes.GaussianNB.predict
predict_log_proba(X) [source] Return log-probability estimates for the test vector X. Parameters Xarray-like of shape (n_samples, n_features) Returns Carray-like of shape (n_samples, n_classes) Returns the log-probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_.
sklearn.modules.generated.sklearn.naive_bayes.gaussiannb#sklearn.naive_bayes.GaussianNB.predict_log_proba
predict_proba(X) [source] Return probability estimates for the test vector X. Parameters Xarray-like of shape (n_samples, n_features) Returns Carray-like of shape (n_samples, n_classes) Returns the probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_.
sklearn.modules.generated.sklearn.naive_bayes.gaussiannb#sklearn.naive_bayes.GaussianNB.predict_proba
score(X, y, sample_weight=None) [source] 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. Parameters Xarray-like of shape (n_samples, n_features) Test samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True labels for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat Mean accuracy of self.predict(X) wrt. y.
sklearn.modules.generated.sklearn.naive_bayes.gaussiannb#sklearn.naive_bayes.GaussianNB.score
set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
sklearn.modules.generated.sklearn.naive_bayes.gaussiannb#sklearn.naive_bayes.GaussianNB.set_params
class sklearn.naive_bayes.MultinomialNB(*, alpha=1.0, fit_prior=True, class_prior=None) [source] Naive Bayes classifier for multinomial models The multinomial Naive Bayes classifier is suitable for classification with discrete features (e.g., word counts for text classification). The multinomial distribution normally requires integer feature counts. However, in practice, fractional counts such as tf-idf may also work. Read more in the User Guide. Parameters alphafloat, default=1.0 Additive (Laplace/Lidstone) smoothing parameter (0 for no smoothing). fit_priorbool, default=True Whether to learn class prior probabilities or not. If false, a uniform prior will be used. class_priorarray-like of shape (n_classes,), default=None Prior probabilities of the classes. If specified the priors are not adjusted according to the data. Attributes class_count_ndarray of shape (n_classes,) Number of samples encountered for each class during fitting. This value is weighted by the sample weight when provided. class_log_prior_ndarray of shape (n_classes, ) Smoothed empirical log probability for each class. classes_ndarray of shape (n_classes,) Class labels known to the classifier coef_ndarray of shape (n_classes, n_features) Mirrors feature_log_prob_ for interpreting MultinomialNB as a linear model. Deprecated since version 0.24: coef_ is deprecated in 0.24 and will be removed in 1.1 (renaming of 0.26). feature_count_ndarray of shape (n_classes, n_features) Number of samples encountered for each (class, feature) during fitting. This value is weighted by the sample weight when provided. feature_log_prob_ndarray of shape (n_classes, n_features) Empirical log probability of features given a class, P(x_i|y). intercept_ndarray of shape (n_classes,) Mirrors class_log_prior_ for interpreting MultinomialNB as a linear model. Deprecated since version 0.24: intercept_ is deprecated in 0.24 and will be removed in 1.1 (renaming of 0.26). n_features_int Number of features of each sample. Notes For the rationale behind the names coef_ and intercept_, i.e. naive Bayes as a linear classifier, see J. Rennie et al. (2003), Tackling the poor assumptions of naive Bayes text classifiers, ICML. References C.D. Manning, P. Raghavan and H. Schuetze (2008). Introduction to Information Retrieval. Cambridge University Press, pp. 234-265. https://nlp.stanford.edu/IR-book/html/htmledition/naive-bayes-text-classification-1.html Examples >>> import numpy as np >>> rng = np.random.RandomState(1) >>> X = rng.randint(5, size=(6, 100)) >>> y = np.array([1, 2, 3, 4, 5, 6]) >>> from sklearn.naive_bayes import MultinomialNB >>> clf = MultinomialNB() >>> clf.fit(X, y) MultinomialNB() >>> print(clf.predict(X[2:3])) [3] Methods fit(X, y[, sample_weight]) Fit Naive Bayes classifier according to X, y get_params([deep]) Get parameters for this estimator. partial_fit(X, y[, classes, sample_weight]) Incremental fit on a batch of samples. predict(X) Perform classification on an array of test vectors X. predict_log_proba(X) Return log-probability estimates for the test vector X. predict_proba(X) Return probability estimates for the test vector 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. fit(X, y, sample_weight=None) [source] Fit Naive Bayes classifier according to X, y Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. yarray-like of shape (n_samples,) Target values. sample_weightarray-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). Returns selfobject get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. partial_fit(X, y, classes=None, sample_weight=None) [source] Incremental fit on a batch of samples. This method is expected to be called several times consecutively on different chunks of a dataset so as to implement out-of-core or online learning. This is especially useful when the whole dataset is too big to fit in memory at once. This method has some performance overhead hence it is better to call partial_fit on chunks of data that are as large as possible (as long as fitting in the memory budget) to hide the overhead. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. yarray-like of shape (n_samples,) Target values. classesarray-like of shape (n_classes), default=None List of all the classes that can possibly appear in the y vector. Must be provided at the first call to partial_fit, can be omitted in subsequent calls. sample_weightarray-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). Returns selfobject predict(X) [source] Perform classification on an array of test vectors X. Parameters Xarray-like of shape (n_samples, n_features) Returns Cndarray of shape (n_samples,) Predicted target values for X predict_log_proba(X) [source] Return log-probability estimates for the test vector X. Parameters Xarray-like of shape (n_samples, n_features) Returns Carray-like of shape (n_samples, n_classes) Returns the log-probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. predict_proba(X) [source] Return probability estimates for the test vector X. Parameters Xarray-like of shape (n_samples, n_features) Returns Carray-like of shape (n_samples, n_classes) Returns the probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. score(X, y, sample_weight=None) [source] 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. Parameters Xarray-like of shape (n_samples, n_features) Test samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True labels for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat Mean accuracy of self.predict(X) wrt. y. set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
sklearn.modules.generated.sklearn.naive_bayes.multinomialnb#sklearn.naive_bayes.MultinomialNB
sklearn.naive_bayes.MultinomialNB class sklearn.naive_bayes.MultinomialNB(*, alpha=1.0, fit_prior=True, class_prior=None) [source] Naive Bayes classifier for multinomial models The multinomial Naive Bayes classifier is suitable for classification with discrete features (e.g., word counts for text classification). The multinomial distribution normally requires integer feature counts. However, in practice, fractional counts such as tf-idf may also work. Read more in the User Guide. Parameters alphafloat, default=1.0 Additive (Laplace/Lidstone) smoothing parameter (0 for no smoothing). fit_priorbool, default=True Whether to learn class prior probabilities or not. If false, a uniform prior will be used. class_priorarray-like of shape (n_classes,), default=None Prior probabilities of the classes. If specified the priors are not adjusted according to the data. Attributes class_count_ndarray of shape (n_classes,) Number of samples encountered for each class during fitting. This value is weighted by the sample weight when provided. class_log_prior_ndarray of shape (n_classes, ) Smoothed empirical log probability for each class. classes_ndarray of shape (n_classes,) Class labels known to the classifier coef_ndarray of shape (n_classes, n_features) Mirrors feature_log_prob_ for interpreting MultinomialNB as a linear model. Deprecated since version 0.24: coef_ is deprecated in 0.24 and will be removed in 1.1 (renaming of 0.26). feature_count_ndarray of shape (n_classes, n_features) Number of samples encountered for each (class, feature) during fitting. This value is weighted by the sample weight when provided. feature_log_prob_ndarray of shape (n_classes, n_features) Empirical log probability of features given a class, P(x_i|y). intercept_ndarray of shape (n_classes,) Mirrors class_log_prior_ for interpreting MultinomialNB as a linear model. Deprecated since version 0.24: intercept_ is deprecated in 0.24 and will be removed in 1.1 (renaming of 0.26). n_features_int Number of features of each sample. Notes For the rationale behind the names coef_ and intercept_, i.e. naive Bayes as a linear classifier, see J. Rennie et al. (2003), Tackling the poor assumptions of naive Bayes text classifiers, ICML. References C.D. Manning, P. Raghavan and H. Schuetze (2008). Introduction to Information Retrieval. Cambridge University Press, pp. 234-265. https://nlp.stanford.edu/IR-book/html/htmledition/naive-bayes-text-classification-1.html Examples >>> import numpy as np >>> rng = np.random.RandomState(1) >>> X = rng.randint(5, size=(6, 100)) >>> y = np.array([1, 2, 3, 4, 5, 6]) >>> from sklearn.naive_bayes import MultinomialNB >>> clf = MultinomialNB() >>> clf.fit(X, y) MultinomialNB() >>> print(clf.predict(X[2:3])) [3] Methods fit(X, y[, sample_weight]) Fit Naive Bayes classifier according to X, y get_params([deep]) Get parameters for this estimator. partial_fit(X, y[, classes, sample_weight]) Incremental fit on a batch of samples. predict(X) Perform classification on an array of test vectors X. predict_log_proba(X) Return log-probability estimates for the test vector X. predict_proba(X) Return probability estimates for the test vector 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. fit(X, y, sample_weight=None) [source] Fit Naive Bayes classifier according to X, y Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. yarray-like of shape (n_samples,) Target values. sample_weightarray-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). Returns selfobject get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. partial_fit(X, y, classes=None, sample_weight=None) [source] Incremental fit on a batch of samples. This method is expected to be called several times consecutively on different chunks of a dataset so as to implement out-of-core or online learning. This is especially useful when the whole dataset is too big to fit in memory at once. This method has some performance overhead hence it is better to call partial_fit on chunks of data that are as large as possible (as long as fitting in the memory budget) to hide the overhead. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. yarray-like of shape (n_samples,) Target values. classesarray-like of shape (n_classes), default=None List of all the classes that can possibly appear in the y vector. Must be provided at the first call to partial_fit, can be omitted in subsequent calls. sample_weightarray-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). Returns selfobject predict(X) [source] Perform classification on an array of test vectors X. Parameters Xarray-like of shape (n_samples, n_features) Returns Cndarray of shape (n_samples,) Predicted target values for X predict_log_proba(X) [source] Return log-probability estimates for the test vector X. Parameters Xarray-like of shape (n_samples, n_features) Returns Carray-like of shape (n_samples, n_classes) Returns the log-probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. predict_proba(X) [source] Return probability estimates for the test vector X. Parameters Xarray-like of shape (n_samples, n_features) Returns Carray-like of shape (n_samples, n_classes) Returns the probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. score(X, y, sample_weight=None) [source] 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. Parameters Xarray-like of shape (n_samples, n_features) Test samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True labels for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat Mean accuracy of self.predict(X) wrt. y. set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance. Examples using sklearn.naive_bayes.MultinomialNB Out-of-core classification of text documents Classification of text documents using sparse features
sklearn.modules.generated.sklearn.naive_bayes.multinomialnb
fit(X, y, sample_weight=None) [source] Fit Naive Bayes classifier according to X, y Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. yarray-like of shape (n_samples,) Target values. sample_weightarray-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). Returns selfobject
sklearn.modules.generated.sklearn.naive_bayes.multinomialnb#sklearn.naive_bayes.MultinomialNB.fit
get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values.
sklearn.modules.generated.sklearn.naive_bayes.multinomialnb#sklearn.naive_bayes.MultinomialNB.get_params
partial_fit(X, y, classes=None, sample_weight=None) [source] Incremental fit on a batch of samples. This method is expected to be called several times consecutively on different chunks of a dataset so as to implement out-of-core or online learning. This is especially useful when the whole dataset is too big to fit in memory at once. This method has some performance overhead hence it is better to call partial_fit on chunks of data that are as large as possible (as long as fitting in the memory budget) to hide the overhead. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. yarray-like of shape (n_samples,) Target values. classesarray-like of shape (n_classes), default=None List of all the classes that can possibly appear in the y vector. Must be provided at the first call to partial_fit, can be omitted in subsequent calls. sample_weightarray-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). Returns selfobject
sklearn.modules.generated.sklearn.naive_bayes.multinomialnb#sklearn.naive_bayes.MultinomialNB.partial_fit
predict(X) [source] Perform classification on an array of test vectors X. Parameters Xarray-like of shape (n_samples, n_features) Returns Cndarray of shape (n_samples,) Predicted target values for X
sklearn.modules.generated.sklearn.naive_bayes.multinomialnb#sklearn.naive_bayes.MultinomialNB.predict
predict_log_proba(X) [source] Return log-probability estimates for the test vector X. Parameters Xarray-like of shape (n_samples, n_features) Returns Carray-like of shape (n_samples, n_classes) Returns the log-probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_.
sklearn.modules.generated.sklearn.naive_bayes.multinomialnb#sklearn.naive_bayes.MultinomialNB.predict_log_proba
predict_proba(X) [source] Return probability estimates for the test vector X. Parameters Xarray-like of shape (n_samples, n_features) Returns Carray-like of shape (n_samples, n_classes) Returns the probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_.
sklearn.modules.generated.sklearn.naive_bayes.multinomialnb#sklearn.naive_bayes.MultinomialNB.predict_proba
score(X, y, sample_weight=None) [source] 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. Parameters Xarray-like of shape (n_samples, n_features) Test samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True labels for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat Mean accuracy of self.predict(X) wrt. y.
sklearn.modules.generated.sklearn.naive_bayes.multinomialnb#sklearn.naive_bayes.MultinomialNB.score
set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
sklearn.modules.generated.sklearn.naive_bayes.multinomialnb#sklearn.naive_bayes.MultinomialNB.set_params
class sklearn.neighbors.BallTree(X, leaf_size=40, metric='minkowski', **kwargs) BallTree for fast generalized N-point problems Read more in the User Guide. Parameters Xarray-like of shape (n_samples, n_features) n_samples is the number of points in the data set, and n_features is the dimension of the parameter space. Note: if X is a C-contiguous array of doubles then data will not be copied. Otherwise, an internal copy will be made. leaf_sizepositive int, default=40 Number of points at which to switch to brute-force. Changing leaf_size will not affect the results of a query, but can significantly impact the speed of a query and the memory required to store the constructed tree. The amount of memory needed to store the tree scales as approximately n_samples / leaf_size. For a specified leaf_size, a leaf node is guaranteed to satisfy leaf_size <= n_points <= 2 * leaf_size, except in the case that n_samples < leaf_size. metricstr or DistanceMetric object the distance metric to use for the tree. Default=’minkowski’ with p=2 (that is, a euclidean metric). See the documentation of the DistanceMetric class for a list of available metrics. ball_tree.valid_metrics gives a list of the metrics which are valid for BallTree. Additional keywords are passed to the distance metric class. Note: Callable functions in the metric parameter are NOT supported for KDTree and Ball Tree. Function call overhead will result in very poor performance. Attributes datamemory view The training data Examples Query for k-nearest neighbors >>> import numpy as np >>> rng = np.random.RandomState(0) >>> X = rng.random_sample((10, 3)) # 10 points in 3 dimensions >>> tree = BallTree(X, leaf_size=2) >>> dist, ind = tree.query(X[:1], k=3) >>> print(ind) # indices of 3 closest neighbors [0 3 1] >>> print(dist) # distances to 3 closest neighbors [ 0. 0.19662693 0.29473397] Pickle and Unpickle a tree. Note that the state of the tree is saved in the pickle operation: the tree needs not be rebuilt upon unpickling. >>> import numpy as np >>> import pickle >>> rng = np.random.RandomState(0) >>> X = rng.random_sample((10, 3)) # 10 points in 3 dimensions >>> tree = BallTree(X, leaf_size=2) >>> s = pickle.dumps(tree) >>> tree_copy = pickle.loads(s) >>> dist, ind = tree_copy.query(X[:1], k=3) >>> print(ind) # indices of 3 closest neighbors [0 3 1] >>> print(dist) # distances to 3 closest neighbors [ 0. 0.19662693 0.29473397] Query for neighbors within a given radius >>> import numpy as np >>> rng = np.random.RandomState(0) >>> X = rng.random_sample((10, 3)) # 10 points in 3 dimensions >>> tree = BallTree(X, leaf_size=2) >>> print(tree.query_radius(X[:1], r=0.3, count_only=True)) 3 >>> ind = tree.query_radius(X[:1], r=0.3) >>> print(ind) # indices of neighbors within distance 0.3 [3 0 1] Compute a gaussian kernel density estimate: >>> import numpy as np >>> rng = np.random.RandomState(42) >>> X = rng.random_sample((100, 3)) >>> tree = BallTree(X) >>> tree.kernel_density(X[:3], h=0.1, kernel='gaussian') array([ 6.94114649, 7.83281226, 7.2071716 ]) Compute a two-point auto-correlation function >>> import numpy as np >>> rng = np.random.RandomState(0) >>> X = rng.random_sample((30, 3)) >>> r = np.linspace(0, 1, 5) >>> tree = BallTree(X) >>> tree.two_point_correlation(X, r) array([ 30, 62, 278, 580, 820]) Methods get_arrays(self) Get data and node arrays. get_n_calls(self) Get number of calls. get_tree_stats(self) Get tree status. kernel_density(self, X, h[, kernel, atol, …]) Compute the kernel density estimate at points X with the given kernel, using the distance metric specified at tree creation. query(X[, k, return_distance, dualtree, …]) query the tree for the k nearest neighbors query_radius(X, r[, return_distance, …]) query the tree for neighbors within a radius r reset_n_calls(self) Reset number of calls to 0. two_point_correlation(X, r[, dualtree]) Compute the two-point correlation function get_arrays(self) Get data and node arrays. Returns arrays: tuple of array Arrays for storing tree data, index, node data and node bounds. get_n_calls(self) Get number of calls. Returns n_calls: int number of distance computation calls get_tree_stats(self) Get tree status. Returns tree_stats: tuple of int (number of trims, number of leaves, number of splits) kernel_density(self, X, h, kernel='gaussian', atol=0, rtol=1e-08, breadth_first=True, return_log=False) Compute the kernel density estimate at points X with the given kernel, using the distance metric specified at tree creation. Parameters Xarray-like of shape (n_samples, n_features) An array of points to query. Last dimension should match dimension of training data. hfloat the bandwidth of the kernel kernelstr, default=”gaussian” specify the kernel to use. Options are - ‘gaussian’ - ‘tophat’ - ‘epanechnikov’ - ‘exponential’ - ‘linear’ - ‘cosine’ Default is kernel = ‘gaussian’ atol, rtolfloat, default=0, 1e-8 Specify the desired relative and absolute tolerance of the result. If the true result is K_true, then the returned result K_ret satisfies abs(K_true - K_ret) < atol + rtol * K_ret The default is zero (i.e. machine precision) for both. breadth_firstbool, default=False If True, use a breadth-first search. If False (default) use a depth-first search. Breadth-first is generally faster for compact kernels and/or high tolerances. return_logbool, default=False Return the logarithm of the result. This can be more accurate than returning the result itself for narrow kernels. Returns densityndarray of shape X.shape[:-1] The array of (log)-density evaluations query(X, k=1, return_distance=True, dualtree=False, breadth_first=False) query the tree for the k nearest neighbors Parameters Xarray-like of shape (n_samples, n_features) An array of points to query kint, default=1 The number of nearest neighbors to return return_distancebool, default=True if True, return a tuple (d, i) of distances and indices if False, return array i dualtreebool, default=False if True, use the dual tree formalism for the query: a tree is built for the query points, and the pair of trees is used to efficiently search this space. This can lead to better performance as the number of points grows large. breadth_firstbool, default=False if True, then query the nodes in a breadth-first manner. Otherwise, query the nodes in a depth-first manner. sort_resultsbool, default=True if True, then distances and indices of each point are sorted on return, so that the first column contains the closest points. Otherwise, neighbors are returned in an arbitrary order. Returns iif return_distance == False (d,i)if return_distance == True dndarray of shape X.shape[:-1] + (k,), dtype=double Each entry gives the list of distances to the neighbors of the corresponding point. indarray of shape X.shape[:-1] + (k,), dtype=int Each entry gives the list of indices of neighbors of the corresponding point. query_radius(X, r, return_distance=False, count_only=False, sort_results=False) query the tree for neighbors within a radius r Parameters Xarray-like of shape (n_samples, n_features) An array of points to query rdistance within which neighbors are returned r can be a single value, or an array of values of shape x.shape[:-1] if different radii are desired for each point. return_distancebool, default=False if True, return distances to neighbors of each point if False, return only neighbors Note that unlike the query() method, setting return_distance=True here adds to the computation time. Not all distances need to be calculated explicitly for return_distance=False. Results are not sorted by default: see sort_results keyword. count_onlybool, default=False if True, return only the count of points within distance r if False, return the indices of all points within distance r If return_distance==True, setting count_only=True will result in an error. sort_resultsbool, default=False if True, the distances and indices will be sorted before being returned. If False, the results will not be sorted. If return_distance == False, setting sort_results = True will result in an error. Returns countif count_only == True indif count_only == False and return_distance == False (ind, dist)if count_only == False and return_distance == True countndarray of shape X.shape[:-1], dtype=int Each entry gives the number of neighbors within a distance r of the corresponding point. indndarray of shape X.shape[:-1], dtype=object Each element is a numpy integer array listing the indices of neighbors of the corresponding point. Note that unlike the results of a k-neighbors query, the returned neighbors are not sorted by distance by default. distndarray of shape X.shape[:-1], dtype=object Each element is a numpy double array listing the distances corresponding to indices in i. reset_n_calls(self) Reset number of calls to 0. two_point_correlation(X, r, dualtree=False) Compute the two-point correlation function Parameters Xarray-like of shape (n_samples, n_features) An array of points to query. Last dimension should match dimension of training data. rarray-like A one-dimensional array of distances dualtreebool, default=False If True, use a dualtree algorithm. Otherwise, use a single-tree algorithm. Dual tree algorithms can have better scaling for large N. Returns countsndarray counts[i] contains the number of pairs of points with distance less than or equal to r[i]
sklearn.modules.generated.sklearn.neighbors.balltree#sklearn.neighbors.BallTree
sklearn.neighbors.BallTree class sklearn.neighbors.BallTree(X, leaf_size=40, metric='minkowski', **kwargs) BallTree for fast generalized N-point problems Read more in the User Guide. Parameters Xarray-like of shape (n_samples, n_features) n_samples is the number of points in the data set, and n_features is the dimension of the parameter space. Note: if X is a C-contiguous array of doubles then data will not be copied. Otherwise, an internal copy will be made. leaf_sizepositive int, default=40 Number of points at which to switch to brute-force. Changing leaf_size will not affect the results of a query, but can significantly impact the speed of a query and the memory required to store the constructed tree. The amount of memory needed to store the tree scales as approximately n_samples / leaf_size. For a specified leaf_size, a leaf node is guaranteed to satisfy leaf_size <= n_points <= 2 * leaf_size, except in the case that n_samples < leaf_size. metricstr or DistanceMetric object the distance metric to use for the tree. Default=’minkowski’ with p=2 (that is, a euclidean metric). See the documentation of the DistanceMetric class for a list of available metrics. ball_tree.valid_metrics gives a list of the metrics which are valid for BallTree. Additional keywords are passed to the distance metric class. Note: Callable functions in the metric parameter are NOT supported for KDTree and Ball Tree. Function call overhead will result in very poor performance. Attributes datamemory view The training data Examples Query for k-nearest neighbors >>> import numpy as np >>> rng = np.random.RandomState(0) >>> X = rng.random_sample((10, 3)) # 10 points in 3 dimensions >>> tree = BallTree(X, leaf_size=2) >>> dist, ind = tree.query(X[:1], k=3) >>> print(ind) # indices of 3 closest neighbors [0 3 1] >>> print(dist) # distances to 3 closest neighbors [ 0. 0.19662693 0.29473397] Pickle and Unpickle a tree. Note that the state of the tree is saved in the pickle operation: the tree needs not be rebuilt upon unpickling. >>> import numpy as np >>> import pickle >>> rng = np.random.RandomState(0) >>> X = rng.random_sample((10, 3)) # 10 points in 3 dimensions >>> tree = BallTree(X, leaf_size=2) >>> s = pickle.dumps(tree) >>> tree_copy = pickle.loads(s) >>> dist, ind = tree_copy.query(X[:1], k=3) >>> print(ind) # indices of 3 closest neighbors [0 3 1] >>> print(dist) # distances to 3 closest neighbors [ 0. 0.19662693 0.29473397] Query for neighbors within a given radius >>> import numpy as np >>> rng = np.random.RandomState(0) >>> X = rng.random_sample((10, 3)) # 10 points in 3 dimensions >>> tree = BallTree(X, leaf_size=2) >>> print(tree.query_radius(X[:1], r=0.3, count_only=True)) 3 >>> ind = tree.query_radius(X[:1], r=0.3) >>> print(ind) # indices of neighbors within distance 0.3 [3 0 1] Compute a gaussian kernel density estimate: >>> import numpy as np >>> rng = np.random.RandomState(42) >>> X = rng.random_sample((100, 3)) >>> tree = BallTree(X) >>> tree.kernel_density(X[:3], h=0.1, kernel='gaussian') array([ 6.94114649, 7.83281226, 7.2071716 ]) Compute a two-point auto-correlation function >>> import numpy as np >>> rng = np.random.RandomState(0) >>> X = rng.random_sample((30, 3)) >>> r = np.linspace(0, 1, 5) >>> tree = BallTree(X) >>> tree.two_point_correlation(X, r) array([ 30, 62, 278, 580, 820]) Methods get_arrays(self) Get data and node arrays. get_n_calls(self) Get number of calls. get_tree_stats(self) Get tree status. kernel_density(self, X, h[, kernel, atol, …]) Compute the kernel density estimate at points X with the given kernel, using the distance metric specified at tree creation. query(X[, k, return_distance, dualtree, …]) query the tree for the k nearest neighbors query_radius(X, r[, return_distance, …]) query the tree for neighbors within a radius r reset_n_calls(self) Reset number of calls to 0. two_point_correlation(X, r[, dualtree]) Compute the two-point correlation function get_arrays(self) Get data and node arrays. Returns arrays: tuple of array Arrays for storing tree data, index, node data and node bounds. get_n_calls(self) Get number of calls. Returns n_calls: int number of distance computation calls get_tree_stats(self) Get tree status. Returns tree_stats: tuple of int (number of trims, number of leaves, number of splits) kernel_density(self, X, h, kernel='gaussian', atol=0, rtol=1e-08, breadth_first=True, return_log=False) Compute the kernel density estimate at points X with the given kernel, using the distance metric specified at tree creation. Parameters Xarray-like of shape (n_samples, n_features) An array of points to query. Last dimension should match dimension of training data. hfloat the bandwidth of the kernel kernelstr, default=”gaussian” specify the kernel to use. Options are - ‘gaussian’ - ‘tophat’ - ‘epanechnikov’ - ‘exponential’ - ‘linear’ - ‘cosine’ Default is kernel = ‘gaussian’ atol, rtolfloat, default=0, 1e-8 Specify the desired relative and absolute tolerance of the result. If the true result is K_true, then the returned result K_ret satisfies abs(K_true - K_ret) < atol + rtol * K_ret The default is zero (i.e. machine precision) for both. breadth_firstbool, default=False If True, use a breadth-first search. If False (default) use a depth-first search. Breadth-first is generally faster for compact kernels and/or high tolerances. return_logbool, default=False Return the logarithm of the result. This can be more accurate than returning the result itself for narrow kernels. Returns densityndarray of shape X.shape[:-1] The array of (log)-density evaluations query(X, k=1, return_distance=True, dualtree=False, breadth_first=False) query the tree for the k nearest neighbors Parameters Xarray-like of shape (n_samples, n_features) An array of points to query kint, default=1 The number of nearest neighbors to return return_distancebool, default=True if True, return a tuple (d, i) of distances and indices if False, return array i dualtreebool, default=False if True, use the dual tree formalism for the query: a tree is built for the query points, and the pair of trees is used to efficiently search this space. This can lead to better performance as the number of points grows large. breadth_firstbool, default=False if True, then query the nodes in a breadth-first manner. Otherwise, query the nodes in a depth-first manner. sort_resultsbool, default=True if True, then distances and indices of each point are sorted on return, so that the first column contains the closest points. Otherwise, neighbors are returned in an arbitrary order. Returns iif return_distance == False (d,i)if return_distance == True dndarray of shape X.shape[:-1] + (k,), dtype=double Each entry gives the list of distances to the neighbors of the corresponding point. indarray of shape X.shape[:-1] + (k,), dtype=int Each entry gives the list of indices of neighbors of the corresponding point. query_radius(X, r, return_distance=False, count_only=False, sort_results=False) query the tree for neighbors within a radius r Parameters Xarray-like of shape (n_samples, n_features) An array of points to query rdistance within which neighbors are returned r can be a single value, or an array of values of shape x.shape[:-1] if different radii are desired for each point. return_distancebool, default=False if True, return distances to neighbors of each point if False, return only neighbors Note that unlike the query() method, setting return_distance=True here adds to the computation time. Not all distances need to be calculated explicitly for return_distance=False. Results are not sorted by default: see sort_results keyword. count_onlybool, default=False if True, return only the count of points within distance r if False, return the indices of all points within distance r If return_distance==True, setting count_only=True will result in an error. sort_resultsbool, default=False if True, the distances and indices will be sorted before being returned. If False, the results will not be sorted. If return_distance == False, setting sort_results = True will result in an error. Returns countif count_only == True indif count_only == False and return_distance == False (ind, dist)if count_only == False and return_distance == True countndarray of shape X.shape[:-1], dtype=int Each entry gives the number of neighbors within a distance r of the corresponding point. indndarray of shape X.shape[:-1], dtype=object Each element is a numpy integer array listing the indices of neighbors of the corresponding point. Note that unlike the results of a k-neighbors query, the returned neighbors are not sorted by distance by default. distndarray of shape X.shape[:-1], dtype=object Each element is a numpy double array listing the distances corresponding to indices in i. reset_n_calls(self) Reset number of calls to 0. two_point_correlation(X, r, dualtree=False) Compute the two-point correlation function Parameters Xarray-like of shape (n_samples, n_features) An array of points to query. Last dimension should match dimension of training data. rarray-like A one-dimensional array of distances dualtreebool, default=False If True, use a dualtree algorithm. Otherwise, use a single-tree algorithm. Dual tree algorithms can have better scaling for large N. Returns countsndarray counts[i] contains the number of pairs of points with distance less than or equal to r[i]
sklearn.modules.generated.sklearn.neighbors.balltree
get_arrays(self) Get data and node arrays. Returns arrays: tuple of array Arrays for storing tree data, index, node data and node bounds.
sklearn.modules.generated.sklearn.neighbors.balltree#sklearn.neighbors.BallTree.get_arrays
get_n_calls(self) Get number of calls. Returns n_calls: int number of distance computation calls
sklearn.modules.generated.sklearn.neighbors.balltree#sklearn.neighbors.BallTree.get_n_calls
get_tree_stats(self) Get tree status. Returns tree_stats: tuple of int (number of trims, number of leaves, number of splits)
sklearn.modules.generated.sklearn.neighbors.balltree#sklearn.neighbors.BallTree.get_tree_stats
kernel_density(self, X, h, kernel='gaussian', atol=0, rtol=1e-08, breadth_first=True, return_log=False) Compute the kernel density estimate at points X with the given kernel, using the distance metric specified at tree creation. Parameters Xarray-like of shape (n_samples, n_features) An array of points to query. Last dimension should match dimension of training data. hfloat the bandwidth of the kernel kernelstr, default=”gaussian” specify the kernel to use. Options are - ‘gaussian’ - ‘tophat’ - ‘epanechnikov’ - ‘exponential’ - ‘linear’ - ‘cosine’ Default is kernel = ‘gaussian’ atol, rtolfloat, default=0, 1e-8 Specify the desired relative and absolute tolerance of the result. If the true result is K_true, then the returned result K_ret satisfies abs(K_true - K_ret) < atol + rtol * K_ret The default is zero (i.e. machine precision) for both. breadth_firstbool, default=False If True, use a breadth-first search. If False (default) use a depth-first search. Breadth-first is generally faster for compact kernels and/or high tolerances. return_logbool, default=False Return the logarithm of the result. This can be more accurate than returning the result itself for narrow kernels. Returns densityndarray of shape X.shape[:-1] The array of (log)-density evaluations
sklearn.modules.generated.sklearn.neighbors.balltree#sklearn.neighbors.BallTree.kernel_density
query(X, k=1, return_distance=True, dualtree=False, breadth_first=False) query the tree for the k nearest neighbors Parameters Xarray-like of shape (n_samples, n_features) An array of points to query kint, default=1 The number of nearest neighbors to return return_distancebool, default=True if True, return a tuple (d, i) of distances and indices if False, return array i dualtreebool, default=False if True, use the dual tree formalism for the query: a tree is built for the query points, and the pair of trees is used to efficiently search this space. This can lead to better performance as the number of points grows large. breadth_firstbool, default=False if True, then query the nodes in a breadth-first manner. Otherwise, query the nodes in a depth-first manner. sort_resultsbool, default=True if True, then distances and indices of each point are sorted on return, so that the first column contains the closest points. Otherwise, neighbors are returned in an arbitrary order. Returns iif return_distance == False (d,i)if return_distance == True dndarray of shape X.shape[:-1] + (k,), dtype=double Each entry gives the list of distances to the neighbors of the corresponding point. indarray of shape X.shape[:-1] + (k,), dtype=int Each entry gives the list of indices of neighbors of the corresponding point.
sklearn.modules.generated.sklearn.neighbors.balltree#sklearn.neighbors.BallTree.query
query_radius(X, r, return_distance=False, count_only=False, sort_results=False) query the tree for neighbors within a radius r Parameters Xarray-like of shape (n_samples, n_features) An array of points to query rdistance within which neighbors are returned r can be a single value, or an array of values of shape x.shape[:-1] if different radii are desired for each point. return_distancebool, default=False if True, return distances to neighbors of each point if False, return only neighbors Note that unlike the query() method, setting return_distance=True here adds to the computation time. Not all distances need to be calculated explicitly for return_distance=False. Results are not sorted by default: see sort_results keyword. count_onlybool, default=False if True, return only the count of points within distance r if False, return the indices of all points within distance r If return_distance==True, setting count_only=True will result in an error. sort_resultsbool, default=False if True, the distances and indices will be sorted before being returned. If False, the results will not be sorted. If return_distance == False, setting sort_results = True will result in an error. Returns countif count_only == True indif count_only == False and return_distance == False (ind, dist)if count_only == False and return_distance == True countndarray of shape X.shape[:-1], dtype=int Each entry gives the number of neighbors within a distance r of the corresponding point. indndarray of shape X.shape[:-1], dtype=object Each element is a numpy integer array listing the indices of neighbors of the corresponding point. Note that unlike the results of a k-neighbors query, the returned neighbors are not sorted by distance by default. distndarray of shape X.shape[:-1], dtype=object Each element is a numpy double array listing the distances corresponding to indices in i.
sklearn.modules.generated.sklearn.neighbors.balltree#sklearn.neighbors.BallTree.query_radius
reset_n_calls(self) Reset number of calls to 0.
sklearn.modules.generated.sklearn.neighbors.balltree#sklearn.neighbors.BallTree.reset_n_calls
two_point_correlation(X, r, dualtree=False) Compute the two-point correlation function Parameters Xarray-like of shape (n_samples, n_features) An array of points to query. Last dimension should match dimension of training data. rarray-like A one-dimensional array of distances dualtreebool, default=False If True, use a dualtree algorithm. Otherwise, use a single-tree algorithm. Dual tree algorithms can have better scaling for large N. Returns countsndarray counts[i] contains the number of pairs of points with distance less than or equal to r[i]
sklearn.modules.generated.sklearn.neighbors.balltree#sklearn.neighbors.BallTree.two_point_correlation
sklearn.neighbors.DistanceMetric class sklearn.neighbors.DistanceMetric DistanceMetric class This class provides a uniform interface to fast distance metric functions. The various metrics can be accessed via the get_metric class method and the metric string identifier (see below). Examples >>> from sklearn.neighbors import DistanceMetric >>> dist = DistanceMetric.get_metric('euclidean') >>> X = [[0, 1, 2], [3, 4, 5]] >>> dist.pairwise(X) array([[ 0. , 5.19615242], [ 5.19615242, 0. ]]) Available Metrics The following lists the string metric identifiers and the associated distance metric classes: Metrics intended for real-valued vector spaces: identifier class name args distance function “euclidean” EuclideanDistance sqrt(sum((x - y)^2)) “manhattan” ManhattanDistance sum(|x - y|) “chebyshev” ChebyshevDistance max(|x - y|) “minkowski” MinkowskiDistance p sum(|x - y|^p)^(1/p) “wminkowski” WMinkowskiDistance p, w sum(|w * (x - y)|^p)^(1/p) “seuclidean” SEuclideanDistance V sqrt(sum((x - y)^2 / V)) “mahalanobis” MahalanobisDistance V or VI sqrt((x - y)' V^-1 (x - y)) Metrics intended for two-dimensional vector spaces: Note that the haversine distance metric requires data in the form of [latitude, longitude] and both inputs and outputs are in units of radians. identifier class name distance function “haversine” HaversineDistance 2 arcsin(sqrt(sin^2(0.5*dx) + cos(x1)cos(x2)sin^2(0.5*dy))) Metrics intended for integer-valued vector spaces: Though intended for integer-valued vectors, these are also valid metrics in the case of real-valued vectors. identifier class name distance function “hamming” HammingDistance N_unequal(x, y) / N_tot “canberra” CanberraDistance sum(|x - y| / (|x| + |y|)) “braycurtis” BrayCurtisDistance sum(|x - y|) / (sum(|x|) + sum(|y|)) Metrics intended for boolean-valued vector spaces: Any nonzero entry is evaluated to “True”. In the listings below, the following abbreviations are used: N : number of dimensions NTT : number of dims in which both values are True NTF : number of dims in which the first value is True, second is False NFT : number of dims in which the first value is False, second is True NFF : number of dims in which both values are False NNEQ : number of non-equal dimensions, NNEQ = NTF + NFT NNZ : number of nonzero dimensions, NNZ = NTF + NFT + NTT identifier class name distance function “jaccard” JaccardDistance NNEQ / NNZ “matching” MatchingDistance NNEQ / N “dice” DiceDistance NNEQ / (NTT + NNZ) “kulsinski” KulsinskiDistance (NNEQ + N - NTT) / (NNEQ + N) “rogerstanimoto” RogersTanimotoDistance 2 * NNEQ / (N + NNEQ) “russellrao” RussellRaoDistance NNZ / N “sokalmichener” SokalMichenerDistance 2 * NNEQ / (N + NNEQ) “sokalsneath” SokalSneathDistance NNEQ / (NNEQ + 0.5 * NTT) User-defined distance: identifier class name args “pyfunc” PyFuncDistance func Here func is a function which takes two one-dimensional numpy arrays, and returns a distance. Note that in order to be used within the BallTree, the distance must be a true metric: i.e. it must satisfy the following properties Non-negativity: d(x, y) >= 0 Identity: d(x, y) = 0 if and only if x == y Symmetry: d(x, y) = d(y, x) Triangle Inequality: d(x, y) + d(y, z) >= d(x, z) Because of the Python object overhead involved in calling the python function, this will be fairly slow, but it will have the same scaling as other distances. Methods dist_to_rdist Convert the true distance to the reduced distance. get_metric Get the given distance metric from the string identifier. pairwise Compute the pairwise distances between X and Y rdist_to_dist Convert the Reduced distance to the true distance. dist_to_rdist() Convert the true distance to the reduced distance. The reduced distance, defined for some metrics, is a computationally more efficient measure which preserves the rank of the true distance. For example, in the Euclidean distance metric, the reduced distance is the squared-euclidean distance. get_metric() Get the given distance metric from the string identifier. See the docstring of DistanceMetric for a list of available metrics. Parameters metricstring or class name The distance metric to use **kwargs additional arguments will be passed to the requested metric pairwise() Compute the pairwise distances between X and Y This is a convenience routine for the sake of testing. For many metrics, the utilities in scipy.spatial.distance.cdist and scipy.spatial.distance.pdist will be faster. Parameters Xarray-like Array of shape (Nx, D), representing Nx points in D dimensions. Yarray-like (optional) Array of shape (Ny, D), representing Ny points in D dimensions. If not specified, then Y=X. Returns ——- distndarray The shape (Nx, Ny) array of pairwise distances between points in X and Y. rdist_to_dist() Convert the Reduced distance to the true distance. The reduced distance, defined for some metrics, is a computationally more efficient measure which preserves the rank of the true distance. For example, in the Euclidean distance metric, the reduced distance is the squared-euclidean distance.
sklearn.modules.generated.sklearn.neighbors.distancemetric
class sklearn.neighbors.DistanceMetric DistanceMetric class This class provides a uniform interface to fast distance metric functions. The various metrics can be accessed via the get_metric class method and the metric string identifier (see below). Examples >>> from sklearn.neighbors import DistanceMetric >>> dist = DistanceMetric.get_metric('euclidean') >>> X = [[0, 1, 2], [3, 4, 5]] >>> dist.pairwise(X) array([[ 0. , 5.19615242], [ 5.19615242, 0. ]]) Available Metrics The following lists the string metric identifiers and the associated distance metric classes: Metrics intended for real-valued vector spaces: identifier class name args distance function “euclidean” EuclideanDistance sqrt(sum((x - y)^2)) “manhattan” ManhattanDistance sum(|x - y|) “chebyshev” ChebyshevDistance max(|x - y|) “minkowski” MinkowskiDistance p sum(|x - y|^p)^(1/p) “wminkowski” WMinkowskiDistance p, w sum(|w * (x - y)|^p)^(1/p) “seuclidean” SEuclideanDistance V sqrt(sum((x - y)^2 / V)) “mahalanobis” MahalanobisDistance V or VI sqrt((x - y)' V^-1 (x - y)) Metrics intended for two-dimensional vector spaces: Note that the haversine distance metric requires data in the form of [latitude, longitude] and both inputs and outputs are in units of radians. identifier class name distance function “haversine” HaversineDistance 2 arcsin(sqrt(sin^2(0.5*dx) + cos(x1)cos(x2)sin^2(0.5*dy))) Metrics intended for integer-valued vector spaces: Though intended for integer-valued vectors, these are also valid metrics in the case of real-valued vectors. identifier class name distance function “hamming” HammingDistance N_unequal(x, y) / N_tot “canberra” CanberraDistance sum(|x - y| / (|x| + |y|)) “braycurtis” BrayCurtisDistance sum(|x - y|) / (sum(|x|) + sum(|y|)) Metrics intended for boolean-valued vector spaces: Any nonzero entry is evaluated to “True”. In the listings below, the following abbreviations are used: N : number of dimensions NTT : number of dims in which both values are True NTF : number of dims in which the first value is True, second is False NFT : number of dims in which the first value is False, second is True NFF : number of dims in which both values are False NNEQ : number of non-equal dimensions, NNEQ = NTF + NFT NNZ : number of nonzero dimensions, NNZ = NTF + NFT + NTT identifier class name distance function “jaccard” JaccardDistance NNEQ / NNZ “matching” MatchingDistance NNEQ / N “dice” DiceDistance NNEQ / (NTT + NNZ) “kulsinski” KulsinskiDistance (NNEQ + N - NTT) / (NNEQ + N) “rogerstanimoto” RogersTanimotoDistance 2 * NNEQ / (N + NNEQ) “russellrao” RussellRaoDistance NNZ / N “sokalmichener” SokalMichenerDistance 2 * NNEQ / (N + NNEQ) “sokalsneath” SokalSneathDistance NNEQ / (NNEQ + 0.5 * NTT) User-defined distance: identifier class name args “pyfunc” PyFuncDistance func Here func is a function which takes two one-dimensional numpy arrays, and returns a distance. Note that in order to be used within the BallTree, the distance must be a true metric: i.e. it must satisfy the following properties Non-negativity: d(x, y) >= 0 Identity: d(x, y) = 0 if and only if x == y Symmetry: d(x, y) = d(y, x) Triangle Inequality: d(x, y) + d(y, z) >= d(x, z) Because of the Python object overhead involved in calling the python function, this will be fairly slow, but it will have the same scaling as other distances. Methods dist_to_rdist Convert the true distance to the reduced distance. get_metric Get the given distance metric from the string identifier. pairwise Compute the pairwise distances between X and Y rdist_to_dist Convert the Reduced distance to the true distance. dist_to_rdist() Convert the true distance to the reduced distance. The reduced distance, defined for some metrics, is a computationally more efficient measure which preserves the rank of the true distance. For example, in the Euclidean distance metric, the reduced distance is the squared-euclidean distance. get_metric() Get the given distance metric from the string identifier. See the docstring of DistanceMetric for a list of available metrics. Parameters metricstring or class name The distance metric to use **kwargs additional arguments will be passed to the requested metric pairwise() Compute the pairwise distances between X and Y This is a convenience routine for the sake of testing. For many metrics, the utilities in scipy.spatial.distance.cdist and scipy.spatial.distance.pdist will be faster. Parameters Xarray-like Array of shape (Nx, D), representing Nx points in D dimensions. Yarray-like (optional) Array of shape (Ny, D), representing Ny points in D dimensions. If not specified, then Y=X. Returns ——- distndarray The shape (Nx, Ny) array of pairwise distances between points in X and Y. rdist_to_dist() Convert the Reduced distance to the true distance. The reduced distance, defined for some metrics, is a computationally more efficient measure which preserves the rank of the true distance. For example, in the Euclidean distance metric, the reduced distance is the squared-euclidean distance.
sklearn.modules.generated.sklearn.neighbors.distancemetric#sklearn.neighbors.DistanceMetric
dist_to_rdist() Convert the true distance to the reduced distance. The reduced distance, defined for some metrics, is a computationally more efficient measure which preserves the rank of the true distance. For example, in the Euclidean distance metric, the reduced distance is the squared-euclidean distance.
sklearn.modules.generated.sklearn.neighbors.distancemetric#sklearn.neighbors.DistanceMetric.dist_to_rdist
get_metric() Get the given distance metric from the string identifier. See the docstring of DistanceMetric for a list of available metrics. Parameters metricstring or class name The distance metric to use **kwargs additional arguments will be passed to the requested metric
sklearn.modules.generated.sklearn.neighbors.distancemetric#sklearn.neighbors.DistanceMetric.get_metric
pairwise() Compute the pairwise distances between X and Y This is a convenience routine for the sake of testing. For many metrics, the utilities in scipy.spatial.distance.cdist and scipy.spatial.distance.pdist will be faster. Parameters Xarray-like Array of shape (Nx, D), representing Nx points in D dimensions. Yarray-like (optional) Array of shape (Ny, D), representing Ny points in D dimensions. If not specified, then Y=X. Returns ——- distndarray The shape (Nx, Ny) array of pairwise distances between points in X and Y.
sklearn.modules.generated.sklearn.neighbors.distancemetric#sklearn.neighbors.DistanceMetric.pairwise
rdist_to_dist() Convert the Reduced distance to the true distance. The reduced distance, defined for some metrics, is a computationally more efficient measure which preserves the rank of the true distance. For example, in the Euclidean distance metric, the reduced distance is the squared-euclidean distance.
sklearn.modules.generated.sklearn.neighbors.distancemetric#sklearn.neighbors.DistanceMetric.rdist_to_dist
class sklearn.neighbors.KDTree(X, leaf_size=40, metric='minkowski', **kwargs) KDTree for fast generalized N-point problems Read more in the User Guide. Parameters Xarray-like of shape (n_samples, n_features) n_samples is the number of points in the data set, and n_features is the dimension of the parameter space. Note: if X is a C-contiguous array of doubles then data will not be copied. Otherwise, an internal copy will be made. leaf_sizepositive int, default=40 Number of points at which to switch to brute-force. Changing leaf_size will not affect the results of a query, but can significantly impact the speed of a query and the memory required to store the constructed tree. The amount of memory needed to store the tree scales as approximately n_samples / leaf_size. For a specified leaf_size, a leaf node is guaranteed to satisfy leaf_size <= n_points <= 2 * leaf_size, except in the case that n_samples < leaf_size. metricstr or DistanceMetric object the distance metric to use for the tree. Default=’minkowski’ with p=2 (that is, a euclidean metric). See the documentation of the DistanceMetric class for a list of available metrics. kd_tree.valid_metrics gives a list of the metrics which are valid for KDTree. Additional keywords are passed to the distance metric class. Note: Callable functions in the metric parameter are NOT supported for KDTree and Ball Tree. Function call overhead will result in very poor performance. Attributes datamemory view The training data Examples Query for k-nearest neighbors >>> import numpy as np >>> rng = np.random.RandomState(0) >>> X = rng.random_sample((10, 3)) # 10 points in 3 dimensions >>> tree = KDTree(X, leaf_size=2) >>> dist, ind = tree.query(X[:1], k=3) >>> print(ind) # indices of 3 closest neighbors [0 3 1] >>> print(dist) # distances to 3 closest neighbors [ 0. 0.19662693 0.29473397] Pickle and Unpickle a tree. Note that the state of the tree is saved in the pickle operation: the tree needs not be rebuilt upon unpickling. >>> import numpy as np >>> import pickle >>> rng = np.random.RandomState(0) >>> X = rng.random_sample((10, 3)) # 10 points in 3 dimensions >>> tree = KDTree(X, leaf_size=2) >>> s = pickle.dumps(tree) >>> tree_copy = pickle.loads(s) >>> dist, ind = tree_copy.query(X[:1], k=3) >>> print(ind) # indices of 3 closest neighbors [0 3 1] >>> print(dist) # distances to 3 closest neighbors [ 0. 0.19662693 0.29473397] Query for neighbors within a given radius >>> import numpy as np >>> rng = np.random.RandomState(0) >>> X = rng.random_sample((10, 3)) # 10 points in 3 dimensions >>> tree = KDTree(X, leaf_size=2) >>> print(tree.query_radius(X[:1], r=0.3, count_only=True)) 3 >>> ind = tree.query_radius(X[:1], r=0.3) >>> print(ind) # indices of neighbors within distance 0.3 [3 0 1] Compute a gaussian kernel density estimate: >>> import numpy as np >>> rng = np.random.RandomState(42) >>> X = rng.random_sample((100, 3)) >>> tree = KDTree(X) >>> tree.kernel_density(X[:3], h=0.1, kernel='gaussian') array([ 6.94114649, 7.83281226, 7.2071716 ]) Compute a two-point auto-correlation function >>> import numpy as np >>> rng = np.random.RandomState(0) >>> X = rng.random_sample((30, 3)) >>> r = np.linspace(0, 1, 5) >>> tree = KDTree(X) >>> tree.two_point_correlation(X, r) array([ 30, 62, 278, 580, 820]) Methods get_arrays(self) Get data and node arrays. get_n_calls(self) Get number of calls. get_tree_stats(self) Get tree status. kernel_density(self, X, h[, kernel, atol, …]) Compute the kernel density estimate at points X with the given kernel, using the distance metric specified at tree creation. query(X[, k, return_distance, dualtree, …]) query the tree for the k nearest neighbors query_radius(X, r[, return_distance, …]) query the tree for neighbors within a radius r reset_n_calls(self) Reset number of calls to 0. two_point_correlation(X, r[, dualtree]) Compute the two-point correlation function get_arrays(self) Get data and node arrays. Returns arrays: tuple of array Arrays for storing tree data, index, node data and node bounds. get_n_calls(self) Get number of calls. Returns n_calls: int number of distance computation calls get_tree_stats(self) Get tree status. Returns tree_stats: tuple of int (number of trims, number of leaves, number of splits) kernel_density(self, X, h, kernel='gaussian', atol=0, rtol=1e-08, breadth_first=True, return_log=False) Compute the kernel density estimate at points X with the given kernel, using the distance metric specified at tree creation. Parameters Xarray-like of shape (n_samples, n_features) An array of points to query. Last dimension should match dimension of training data. hfloat the bandwidth of the kernel kernelstr, default=”gaussian” specify the kernel to use. Options are - ‘gaussian’ - ‘tophat’ - ‘epanechnikov’ - ‘exponential’ - ‘linear’ - ‘cosine’ Default is kernel = ‘gaussian’ atol, rtolfloat, default=0, 1e-8 Specify the desired relative and absolute tolerance of the result. If the true result is K_true, then the returned result K_ret satisfies abs(K_true - K_ret) < atol + rtol * K_ret The default is zero (i.e. machine precision) for both. breadth_firstbool, default=False If True, use a breadth-first search. If False (default) use a depth-first search. Breadth-first is generally faster for compact kernels and/or high tolerances. return_logbool, default=False Return the logarithm of the result. This can be more accurate than returning the result itself for narrow kernels. Returns densityndarray of shape X.shape[:-1] The array of (log)-density evaluations query(X, k=1, return_distance=True, dualtree=False, breadth_first=False) query the tree for the k nearest neighbors Parameters Xarray-like of shape (n_samples, n_features) An array of points to query kint, default=1 The number of nearest neighbors to return return_distancebool, default=True if True, return a tuple (d, i) of distances and indices if False, return array i dualtreebool, default=False if True, use the dual tree formalism for the query: a tree is built for the query points, and the pair of trees is used to efficiently search this space. This can lead to better performance as the number of points grows large. breadth_firstbool, default=False if True, then query the nodes in a breadth-first manner. Otherwise, query the nodes in a depth-first manner. sort_resultsbool, default=True if True, then distances and indices of each point are sorted on return, so that the first column contains the closest points. Otherwise, neighbors are returned in an arbitrary order. Returns iif return_distance == False (d,i)if return_distance == True dndarray of shape X.shape[:-1] + (k,), dtype=double Each entry gives the list of distances to the neighbors of the corresponding point. indarray of shape X.shape[:-1] + (k,), dtype=int Each entry gives the list of indices of neighbors of the corresponding point. query_radius(X, r, return_distance=False, count_only=False, sort_results=False) query the tree for neighbors within a radius r Parameters Xarray-like of shape (n_samples, n_features) An array of points to query rdistance within which neighbors are returned r can be a single value, or an array of values of shape x.shape[:-1] if different radii are desired for each point. return_distancebool, default=False if True, return distances to neighbors of each point if False, return only neighbors Note that unlike the query() method, setting return_distance=True here adds to the computation time. Not all distances need to be calculated explicitly for return_distance=False. Results are not sorted by default: see sort_results keyword. count_onlybool, default=False if True, return only the count of points within distance r if False, return the indices of all points within distance r If return_distance==True, setting count_only=True will result in an error. sort_resultsbool, default=False if True, the distances and indices will be sorted before being returned. If False, the results will not be sorted. If return_distance == False, setting sort_results = True will result in an error. Returns countif count_only == True indif count_only == False and return_distance == False (ind, dist)if count_only == False and return_distance == True countndarray of shape X.shape[:-1], dtype=int Each entry gives the number of neighbors within a distance r of the corresponding point. indndarray of shape X.shape[:-1], dtype=object Each element is a numpy integer array listing the indices of neighbors of the corresponding point. Note that unlike the results of a k-neighbors query, the returned neighbors are not sorted by distance by default. distndarray of shape X.shape[:-1], dtype=object Each element is a numpy double array listing the distances corresponding to indices in i. reset_n_calls(self) Reset number of calls to 0. two_point_correlation(X, r, dualtree=False) Compute the two-point correlation function Parameters Xarray-like of shape (n_samples, n_features) An array of points to query. Last dimension should match dimension of training data. rarray-like A one-dimensional array of distances dualtreebool, default=False If True, use a dualtree algorithm. Otherwise, use a single-tree algorithm. Dual tree algorithms can have better scaling for large N. Returns countsndarray counts[i] contains the number of pairs of points with distance less than or equal to r[i]
sklearn.modules.generated.sklearn.neighbors.kdtree#sklearn.neighbors.KDTree
sklearn.neighbors.KDTree class sklearn.neighbors.KDTree(X, leaf_size=40, metric='minkowski', **kwargs) KDTree for fast generalized N-point problems Read more in the User Guide. Parameters Xarray-like of shape (n_samples, n_features) n_samples is the number of points in the data set, and n_features is the dimension of the parameter space. Note: if X is a C-contiguous array of doubles then data will not be copied. Otherwise, an internal copy will be made. leaf_sizepositive int, default=40 Number of points at which to switch to brute-force. Changing leaf_size will not affect the results of a query, but can significantly impact the speed of a query and the memory required to store the constructed tree. The amount of memory needed to store the tree scales as approximately n_samples / leaf_size. For a specified leaf_size, a leaf node is guaranteed to satisfy leaf_size <= n_points <= 2 * leaf_size, except in the case that n_samples < leaf_size. metricstr or DistanceMetric object the distance metric to use for the tree. Default=’minkowski’ with p=2 (that is, a euclidean metric). See the documentation of the DistanceMetric class for a list of available metrics. kd_tree.valid_metrics gives a list of the metrics which are valid for KDTree. Additional keywords are passed to the distance metric class. Note: Callable functions in the metric parameter are NOT supported for KDTree and Ball Tree. Function call overhead will result in very poor performance. Attributes datamemory view The training data Examples Query for k-nearest neighbors >>> import numpy as np >>> rng = np.random.RandomState(0) >>> X = rng.random_sample((10, 3)) # 10 points in 3 dimensions >>> tree = KDTree(X, leaf_size=2) >>> dist, ind = tree.query(X[:1], k=3) >>> print(ind) # indices of 3 closest neighbors [0 3 1] >>> print(dist) # distances to 3 closest neighbors [ 0. 0.19662693 0.29473397] Pickle and Unpickle a tree. Note that the state of the tree is saved in the pickle operation: the tree needs not be rebuilt upon unpickling. >>> import numpy as np >>> import pickle >>> rng = np.random.RandomState(0) >>> X = rng.random_sample((10, 3)) # 10 points in 3 dimensions >>> tree = KDTree(X, leaf_size=2) >>> s = pickle.dumps(tree) >>> tree_copy = pickle.loads(s) >>> dist, ind = tree_copy.query(X[:1], k=3) >>> print(ind) # indices of 3 closest neighbors [0 3 1] >>> print(dist) # distances to 3 closest neighbors [ 0. 0.19662693 0.29473397] Query for neighbors within a given radius >>> import numpy as np >>> rng = np.random.RandomState(0) >>> X = rng.random_sample((10, 3)) # 10 points in 3 dimensions >>> tree = KDTree(X, leaf_size=2) >>> print(tree.query_radius(X[:1], r=0.3, count_only=True)) 3 >>> ind = tree.query_radius(X[:1], r=0.3) >>> print(ind) # indices of neighbors within distance 0.3 [3 0 1] Compute a gaussian kernel density estimate: >>> import numpy as np >>> rng = np.random.RandomState(42) >>> X = rng.random_sample((100, 3)) >>> tree = KDTree(X) >>> tree.kernel_density(X[:3], h=0.1, kernel='gaussian') array([ 6.94114649, 7.83281226, 7.2071716 ]) Compute a two-point auto-correlation function >>> import numpy as np >>> rng = np.random.RandomState(0) >>> X = rng.random_sample((30, 3)) >>> r = np.linspace(0, 1, 5) >>> tree = KDTree(X) >>> tree.two_point_correlation(X, r) array([ 30, 62, 278, 580, 820]) Methods get_arrays(self) Get data and node arrays. get_n_calls(self) Get number of calls. get_tree_stats(self) Get tree status. kernel_density(self, X, h[, kernel, atol, …]) Compute the kernel density estimate at points X with the given kernel, using the distance metric specified at tree creation. query(X[, k, return_distance, dualtree, …]) query the tree for the k nearest neighbors query_radius(X, r[, return_distance, …]) query the tree for neighbors within a radius r reset_n_calls(self) Reset number of calls to 0. two_point_correlation(X, r[, dualtree]) Compute the two-point correlation function get_arrays(self) Get data and node arrays. Returns arrays: tuple of array Arrays for storing tree data, index, node data and node bounds. get_n_calls(self) Get number of calls. Returns n_calls: int number of distance computation calls get_tree_stats(self) Get tree status. Returns tree_stats: tuple of int (number of trims, number of leaves, number of splits) kernel_density(self, X, h, kernel='gaussian', atol=0, rtol=1e-08, breadth_first=True, return_log=False) Compute the kernel density estimate at points X with the given kernel, using the distance metric specified at tree creation. Parameters Xarray-like of shape (n_samples, n_features) An array of points to query. Last dimension should match dimension of training data. hfloat the bandwidth of the kernel kernelstr, default=”gaussian” specify the kernel to use. Options are - ‘gaussian’ - ‘tophat’ - ‘epanechnikov’ - ‘exponential’ - ‘linear’ - ‘cosine’ Default is kernel = ‘gaussian’ atol, rtolfloat, default=0, 1e-8 Specify the desired relative and absolute tolerance of the result. If the true result is K_true, then the returned result K_ret satisfies abs(K_true - K_ret) < atol + rtol * K_ret The default is zero (i.e. machine precision) for both. breadth_firstbool, default=False If True, use a breadth-first search. If False (default) use a depth-first search. Breadth-first is generally faster for compact kernels and/or high tolerances. return_logbool, default=False Return the logarithm of the result. This can be more accurate than returning the result itself for narrow kernels. Returns densityndarray of shape X.shape[:-1] The array of (log)-density evaluations query(X, k=1, return_distance=True, dualtree=False, breadth_first=False) query the tree for the k nearest neighbors Parameters Xarray-like of shape (n_samples, n_features) An array of points to query kint, default=1 The number of nearest neighbors to return return_distancebool, default=True if True, return a tuple (d, i) of distances and indices if False, return array i dualtreebool, default=False if True, use the dual tree formalism for the query: a tree is built for the query points, and the pair of trees is used to efficiently search this space. This can lead to better performance as the number of points grows large. breadth_firstbool, default=False if True, then query the nodes in a breadth-first manner. Otherwise, query the nodes in a depth-first manner. sort_resultsbool, default=True if True, then distances and indices of each point are sorted on return, so that the first column contains the closest points. Otherwise, neighbors are returned in an arbitrary order. Returns iif return_distance == False (d,i)if return_distance == True dndarray of shape X.shape[:-1] + (k,), dtype=double Each entry gives the list of distances to the neighbors of the corresponding point. indarray of shape X.shape[:-1] + (k,), dtype=int Each entry gives the list of indices of neighbors of the corresponding point. query_radius(X, r, return_distance=False, count_only=False, sort_results=False) query the tree for neighbors within a radius r Parameters Xarray-like of shape (n_samples, n_features) An array of points to query rdistance within which neighbors are returned r can be a single value, or an array of values of shape x.shape[:-1] if different radii are desired for each point. return_distancebool, default=False if True, return distances to neighbors of each point if False, return only neighbors Note that unlike the query() method, setting return_distance=True here adds to the computation time. Not all distances need to be calculated explicitly for return_distance=False. Results are not sorted by default: see sort_results keyword. count_onlybool, default=False if True, return only the count of points within distance r if False, return the indices of all points within distance r If return_distance==True, setting count_only=True will result in an error. sort_resultsbool, default=False if True, the distances and indices will be sorted before being returned. If False, the results will not be sorted. If return_distance == False, setting sort_results = True will result in an error. Returns countif count_only == True indif count_only == False and return_distance == False (ind, dist)if count_only == False and return_distance == True countndarray of shape X.shape[:-1], dtype=int Each entry gives the number of neighbors within a distance r of the corresponding point. indndarray of shape X.shape[:-1], dtype=object Each element is a numpy integer array listing the indices of neighbors of the corresponding point. Note that unlike the results of a k-neighbors query, the returned neighbors are not sorted by distance by default. distndarray of shape X.shape[:-1], dtype=object Each element is a numpy double array listing the distances corresponding to indices in i. reset_n_calls(self) Reset number of calls to 0. two_point_correlation(X, r, dualtree=False) Compute the two-point correlation function Parameters Xarray-like of shape (n_samples, n_features) An array of points to query. Last dimension should match dimension of training data. rarray-like A one-dimensional array of distances dualtreebool, default=False If True, use a dualtree algorithm. Otherwise, use a single-tree algorithm. Dual tree algorithms can have better scaling for large N. Returns countsndarray counts[i] contains the number of pairs of points with distance less than or equal to r[i]
sklearn.modules.generated.sklearn.neighbors.kdtree
get_arrays(self) Get data and node arrays. Returns arrays: tuple of array Arrays for storing tree data, index, node data and node bounds.
sklearn.modules.generated.sklearn.neighbors.kdtree#sklearn.neighbors.KDTree.get_arrays
get_n_calls(self) Get number of calls. Returns n_calls: int number of distance computation calls
sklearn.modules.generated.sklearn.neighbors.kdtree#sklearn.neighbors.KDTree.get_n_calls
get_tree_stats(self) Get tree status. Returns tree_stats: tuple of int (number of trims, number of leaves, number of splits)
sklearn.modules.generated.sklearn.neighbors.kdtree#sklearn.neighbors.KDTree.get_tree_stats
kernel_density(self, X, h, kernel='gaussian', atol=0, rtol=1e-08, breadth_first=True, return_log=False) Compute the kernel density estimate at points X with the given kernel, using the distance metric specified at tree creation. Parameters Xarray-like of shape (n_samples, n_features) An array of points to query. Last dimension should match dimension of training data. hfloat the bandwidth of the kernel kernelstr, default=”gaussian” specify the kernel to use. Options are - ‘gaussian’ - ‘tophat’ - ‘epanechnikov’ - ‘exponential’ - ‘linear’ - ‘cosine’ Default is kernel = ‘gaussian’ atol, rtolfloat, default=0, 1e-8 Specify the desired relative and absolute tolerance of the result. If the true result is K_true, then the returned result K_ret satisfies abs(K_true - K_ret) < atol + rtol * K_ret The default is zero (i.e. machine precision) for both. breadth_firstbool, default=False If True, use a breadth-first search. If False (default) use a depth-first search. Breadth-first is generally faster for compact kernels and/or high tolerances. return_logbool, default=False Return the logarithm of the result. This can be more accurate than returning the result itself for narrow kernels. Returns densityndarray of shape X.shape[:-1] The array of (log)-density evaluations
sklearn.modules.generated.sklearn.neighbors.kdtree#sklearn.neighbors.KDTree.kernel_density
query(X, k=1, return_distance=True, dualtree=False, breadth_first=False) query the tree for the k nearest neighbors Parameters Xarray-like of shape (n_samples, n_features) An array of points to query kint, default=1 The number of nearest neighbors to return return_distancebool, default=True if True, return a tuple (d, i) of distances and indices if False, return array i dualtreebool, default=False if True, use the dual tree formalism for the query: a tree is built for the query points, and the pair of trees is used to efficiently search this space. This can lead to better performance as the number of points grows large. breadth_firstbool, default=False if True, then query the nodes in a breadth-first manner. Otherwise, query the nodes in a depth-first manner. sort_resultsbool, default=True if True, then distances and indices of each point are sorted on return, so that the first column contains the closest points. Otherwise, neighbors are returned in an arbitrary order. Returns iif return_distance == False (d,i)if return_distance == True dndarray of shape X.shape[:-1] + (k,), dtype=double Each entry gives the list of distances to the neighbors of the corresponding point. indarray of shape X.shape[:-1] + (k,), dtype=int Each entry gives the list of indices of neighbors of the corresponding point.
sklearn.modules.generated.sklearn.neighbors.kdtree#sklearn.neighbors.KDTree.query
query_radius(X, r, return_distance=False, count_only=False, sort_results=False) query the tree for neighbors within a radius r Parameters Xarray-like of shape (n_samples, n_features) An array of points to query rdistance within which neighbors are returned r can be a single value, or an array of values of shape x.shape[:-1] if different radii are desired for each point. return_distancebool, default=False if True, return distances to neighbors of each point if False, return only neighbors Note that unlike the query() method, setting return_distance=True here adds to the computation time. Not all distances need to be calculated explicitly for return_distance=False. Results are not sorted by default: see sort_results keyword. count_onlybool, default=False if True, return only the count of points within distance r if False, return the indices of all points within distance r If return_distance==True, setting count_only=True will result in an error. sort_resultsbool, default=False if True, the distances and indices will be sorted before being returned. If False, the results will not be sorted. If return_distance == False, setting sort_results = True will result in an error. Returns countif count_only == True indif count_only == False and return_distance == False (ind, dist)if count_only == False and return_distance == True countndarray of shape X.shape[:-1], dtype=int Each entry gives the number of neighbors within a distance r of the corresponding point. indndarray of shape X.shape[:-1], dtype=object Each element is a numpy integer array listing the indices of neighbors of the corresponding point. Note that unlike the results of a k-neighbors query, the returned neighbors are not sorted by distance by default. distndarray of shape X.shape[:-1], dtype=object Each element is a numpy double array listing the distances corresponding to indices in i.
sklearn.modules.generated.sklearn.neighbors.kdtree#sklearn.neighbors.KDTree.query_radius
reset_n_calls(self) Reset number of calls to 0.
sklearn.modules.generated.sklearn.neighbors.kdtree#sklearn.neighbors.KDTree.reset_n_calls
two_point_correlation(X, r, dualtree=False) Compute the two-point correlation function Parameters Xarray-like of shape (n_samples, n_features) An array of points to query. Last dimension should match dimension of training data. rarray-like A one-dimensional array of distances dualtreebool, default=False If True, use a dualtree algorithm. Otherwise, use a single-tree algorithm. Dual tree algorithms can have better scaling for large N. Returns countsndarray counts[i] contains the number of pairs of points with distance less than or equal to r[i]
sklearn.modules.generated.sklearn.neighbors.kdtree#sklearn.neighbors.KDTree.two_point_correlation
class sklearn.neighbors.KernelDensity(*, bandwidth=1.0, algorithm='auto', kernel='gaussian', metric='euclidean', atol=0, rtol=0, breadth_first=True, leaf_size=40, metric_params=None) [source] Kernel Density Estimation. Read more in the User Guide. Parameters bandwidthfloat, default=1.0 The bandwidth of the kernel. algorithm{‘kd_tree’, ‘ball_tree’, ‘auto’}, default=’auto’ The tree algorithm to use. kernel{‘gaussian’, ‘tophat’, ‘epanechnikov’, ‘exponential’, ‘linear’, ‘cosine’}, default=’gaussian’ The kernel to use. metricstr, default=’euclidian’ The distance metric to use. Note that not all metrics are valid with all algorithms. Refer to the documentation of BallTree and KDTree for a description of available algorithms. Note that the normalization of the density output is correct only for the Euclidean distance metric. Default is ‘euclidean’. atolfloat, default=0 The desired absolute tolerance of the result. A larger tolerance will generally lead to faster execution. rtolfloat, default=0 The desired relative tolerance of the result. A larger tolerance will generally lead to faster execution. breadth_firstbool, default=True If true (default), use a breadth-first approach to the problem. Otherwise use a depth-first approach. leaf_sizeint, default=40 Specify the leaf size of the underlying tree. See BallTree or KDTree for details. metric_paramsdict, default=None Additional parameters to be passed to the tree for use with the metric. For more information, see the documentation of BallTree or KDTree. Attributes tree_BinaryTree instance The tree algorithm for fast generalized N-point problems. See also sklearn.neighbors.KDTree K-dimensional tree for fast generalized N-point problems. sklearn.neighbors.BallTree Ball tree for fast generalized N-point problems. Examples Compute a gaussian kernel density estimate with a fixed bandwidth. >>> import numpy as np >>> rng = np.random.RandomState(42) >>> X = rng.random_sample((100, 3)) >>> kde = KernelDensity(kernel='gaussian', bandwidth=0.5).fit(X) >>> log_density = kde.score_samples(X[:3]) >>> log_density array([-1.52955942, -1.51462041, -1.60244657]) Methods fit(X[, y, sample_weight]) Fit the Kernel Density model on the data. get_params([deep]) Get parameters for this estimator. sample([n_samples, random_state]) Generate random samples from the model. score(X[, y]) Compute the total log probability density under the model. score_samples(X) Evaluate the log density model on the data. set_params(**params) Set the parameters of this estimator. fit(X, y=None, sample_weight=None) [source] Fit the Kernel Density model on the data. Parameters Xarray-like of shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. yNone Ignored. This parameter exists only for compatibility with Pipeline. sample_weightarray-like of shape (n_samples,), default=None List of sample weights attached to the data X. New in version 0.20. Returns selfobject Returns instance of object. get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. sample(n_samples=1, random_state=None) [source] Generate random samples from the model. Currently, this is implemented only for gaussian and tophat kernels. Parameters n_samplesint, default=1 Number of samples to generate. random_stateint, RandomState instance or None, default=None Determines random number generation used to generate random samples. Pass an int for reproducible results across multiple function calls. See :term: Glossary <random_state>. Returns Xarray-like of shape (n_samples, n_features) List of samples. score(X, y=None) [source] Compute the total log probability density under the model. Parameters Xarray-like of shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. yNone Ignored. This parameter exists only for compatibility with Pipeline. Returns logprobfloat Total log-likelihood of the data in X. This is normalized to be a probability density, so the value will be low for high-dimensional data. score_samples(X) [source] Evaluate the log density model on the data. Parameters Xarray-like of shape (n_samples, n_features) An array of points to query. Last dimension should match dimension of training data (n_features). Returns densityndarray of shape (n_samples,) The array of log(density) evaluations. These are normalized to be probability densities, so values will be low for high-dimensional data. set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
sklearn.modules.generated.sklearn.neighbors.kerneldensity#sklearn.neighbors.KernelDensity
sklearn.neighbors.KernelDensity class sklearn.neighbors.KernelDensity(*, bandwidth=1.0, algorithm='auto', kernel='gaussian', metric='euclidean', atol=0, rtol=0, breadth_first=True, leaf_size=40, metric_params=None) [source] Kernel Density Estimation. Read more in the User Guide. Parameters bandwidthfloat, default=1.0 The bandwidth of the kernel. algorithm{‘kd_tree’, ‘ball_tree’, ‘auto’}, default=’auto’ The tree algorithm to use. kernel{‘gaussian’, ‘tophat’, ‘epanechnikov’, ‘exponential’, ‘linear’, ‘cosine’}, default=’gaussian’ The kernel to use. metricstr, default=’euclidian’ The distance metric to use. Note that not all metrics are valid with all algorithms. Refer to the documentation of BallTree and KDTree for a description of available algorithms. Note that the normalization of the density output is correct only for the Euclidean distance metric. Default is ‘euclidean’. atolfloat, default=0 The desired absolute tolerance of the result. A larger tolerance will generally lead to faster execution. rtolfloat, default=0 The desired relative tolerance of the result. A larger tolerance will generally lead to faster execution. breadth_firstbool, default=True If true (default), use a breadth-first approach to the problem. Otherwise use a depth-first approach. leaf_sizeint, default=40 Specify the leaf size of the underlying tree. See BallTree or KDTree for details. metric_paramsdict, default=None Additional parameters to be passed to the tree for use with the metric. For more information, see the documentation of BallTree or KDTree. Attributes tree_BinaryTree instance The tree algorithm for fast generalized N-point problems. See also sklearn.neighbors.KDTree K-dimensional tree for fast generalized N-point problems. sklearn.neighbors.BallTree Ball tree for fast generalized N-point problems. Examples Compute a gaussian kernel density estimate with a fixed bandwidth. >>> import numpy as np >>> rng = np.random.RandomState(42) >>> X = rng.random_sample((100, 3)) >>> kde = KernelDensity(kernel='gaussian', bandwidth=0.5).fit(X) >>> log_density = kde.score_samples(X[:3]) >>> log_density array([-1.52955942, -1.51462041, -1.60244657]) Methods fit(X[, y, sample_weight]) Fit the Kernel Density model on the data. get_params([deep]) Get parameters for this estimator. sample([n_samples, random_state]) Generate random samples from the model. score(X[, y]) Compute the total log probability density under the model. score_samples(X) Evaluate the log density model on the data. set_params(**params) Set the parameters of this estimator. fit(X, y=None, sample_weight=None) [source] Fit the Kernel Density model on the data. Parameters Xarray-like of shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. yNone Ignored. This parameter exists only for compatibility with Pipeline. sample_weightarray-like of shape (n_samples,), default=None List of sample weights attached to the data X. New in version 0.20. Returns selfobject Returns instance of object. get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. sample(n_samples=1, random_state=None) [source] Generate random samples from the model. Currently, this is implemented only for gaussian and tophat kernels. Parameters n_samplesint, default=1 Number of samples to generate. random_stateint, RandomState instance or None, default=None Determines random number generation used to generate random samples. Pass an int for reproducible results across multiple function calls. See :term: Glossary <random_state>. Returns Xarray-like of shape (n_samples, n_features) List of samples. score(X, y=None) [source] Compute the total log probability density under the model. Parameters Xarray-like of shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. yNone Ignored. This parameter exists only for compatibility with Pipeline. Returns logprobfloat Total log-likelihood of the data in X. This is normalized to be a probability density, so the value will be low for high-dimensional data. score_samples(X) [source] Evaluate the log density model on the data. Parameters Xarray-like of shape (n_samples, n_features) An array of points to query. Last dimension should match dimension of training data (n_features). Returns densityndarray of shape (n_samples,) The array of log(density) evaluations. These are normalized to be probability densities, so values will be low for high-dimensional data. set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance. Examples using sklearn.neighbors.KernelDensity Kernel Density Estimation Kernel Density Estimate of Species Distributions Simple 1D Kernel Density Estimation
sklearn.modules.generated.sklearn.neighbors.kerneldensity
fit(X, y=None, sample_weight=None) [source] Fit the Kernel Density model on the data. Parameters Xarray-like of shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. yNone Ignored. This parameter exists only for compatibility with Pipeline. sample_weightarray-like of shape (n_samples,), default=None List of sample weights attached to the data X. New in version 0.20. Returns selfobject Returns instance of object.
sklearn.modules.generated.sklearn.neighbors.kerneldensity#sklearn.neighbors.KernelDensity.fit
get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values.
sklearn.modules.generated.sklearn.neighbors.kerneldensity#sklearn.neighbors.KernelDensity.get_params
sample(n_samples=1, random_state=None) [source] Generate random samples from the model. Currently, this is implemented only for gaussian and tophat kernels. Parameters n_samplesint, default=1 Number of samples to generate. random_stateint, RandomState instance or None, default=None Determines random number generation used to generate random samples. Pass an int for reproducible results across multiple function calls. See :term: Glossary <random_state>. Returns Xarray-like of shape (n_samples, n_features) List of samples.
sklearn.modules.generated.sklearn.neighbors.kerneldensity#sklearn.neighbors.KernelDensity.sample
score(X, y=None) [source] Compute the total log probability density under the model. Parameters Xarray-like of shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. yNone Ignored. This parameter exists only for compatibility with Pipeline. Returns logprobfloat Total log-likelihood of the data in X. This is normalized to be a probability density, so the value will be low for high-dimensional data.
sklearn.modules.generated.sklearn.neighbors.kerneldensity#sklearn.neighbors.KernelDensity.score
score_samples(X) [source] Evaluate the log density model on the data. Parameters Xarray-like of shape (n_samples, n_features) An array of points to query. Last dimension should match dimension of training data (n_features). Returns densityndarray of shape (n_samples,) The array of log(density) evaluations. These are normalized to be probability densities, so values will be low for high-dimensional data.
sklearn.modules.generated.sklearn.neighbors.kerneldensity#sklearn.neighbors.KernelDensity.score_samples
set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
sklearn.modules.generated.sklearn.neighbors.kerneldensity#sklearn.neighbors.KernelDensity.set_params
class sklearn.neighbors.KNeighborsClassifier(n_neighbors=5, *, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None, **kwargs) [source] Classifier implementing the k-nearest neighbors vote. Read more in the User Guide. Parameters n_neighborsint, default=5 Number of neighbors to use by default for kneighbors queries. weights{‘uniform’, ‘distance’} or callable, default=’uniform’ weight function used in prediction. Possible values: ‘uniform’ : uniform weights. All points in each neighborhood are weighted equally. ‘distance’ : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away. [callable] : a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights. algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’ Algorithm used to compute the nearest neighbors: ‘ball_tree’ will use BallTree ‘kd_tree’ will use KDTree ‘brute’ will use a brute-force search. ‘auto’ will attempt to decide the most appropriate algorithm based on the values passed to fit method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_sizeint, default=30 Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. pint, default=2 Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metricstr or callable, default=’minkowski’ the distance metric to use for the tree. The default metric is minkowski, and with p=2 is equivalent to the standard Euclidean metric. See the documentation of DistanceMetric for a list of available metrics. If metric is “precomputed”, X is assumed to be a distance matrix and must be square during fit. X may be a sparse graph, in which case only “nonzero” elements may be considered neighbors. metric_paramsdict, default=None Additional keyword arguments for the metric function. n_jobsint, default=None The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Doesn’t affect fit method. Attributes classes_array of shape (n_classes,) Class labels known to the classifier effective_metric_str or callble The distance metric used. It will be same as the metric parameter or a synonym of it, e.g. ‘euclidean’ if the metric parameter set to ‘minkowski’ and p parameter set to 2. effective_metric_params_dict Additional keyword arguments for the metric function. For most metrics will be same with metric_params parameter, but may also contain the p parameter value if the effective_metric_ attribute is set to ‘minkowski’. n_samples_fit_int Number of samples in the fitted data. outputs_2d_bool False when y’s shape is (n_samples, ) or (n_samples, 1) during fit otherwise True. See also RadiusNeighborsClassifier KNeighborsRegressor RadiusNeighborsRegressor NearestNeighbors Notes See Nearest Neighbors in the online documentation for a discussion of the choice of algorithm and leaf_size. Warning Regarding the Nearest Neighbors algorithms, if it is found that two neighbors, neighbor k+1 and k, have identical distances but different labels, the results will depend on the ordering of the training data. https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm Examples >>> X = [[0], [1], [2], [3]] >>> y = [0, 0, 1, 1] >>> from sklearn.neighbors import KNeighborsClassifier >>> neigh = KNeighborsClassifier(n_neighbors=3) >>> neigh.fit(X, y) KNeighborsClassifier(...) >>> print(neigh.predict([[1.1]])) [0] >>> print(neigh.predict_proba([[0.9]])) [[0.66666667 0.33333333]] Methods fit(X, y) Fit the k-nearest neighbors classifier from the training dataset. get_params([deep]) Get parameters for this estimator. kneighbors([X, n_neighbors, return_distance]) Finds the K-neighbors of a point. kneighbors_graph([X, n_neighbors, mode]) Computes the (weighted) graph of k-Neighbors for points in X predict(X) Predict the class labels for the provided data. predict_proba(X) Return probability estimates for the test data 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. fit(X, y) [source] Fit the k-nearest neighbors classifier from the training dataset. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric=’precomputed’ Training data. y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs) Target values. Returns selfKNeighborsClassifier The fitted k-nearest neighbors classifier. get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. kneighbors(X=None, n_neighbors=None, return_distance=True) [source] Finds the K-neighbors of a point. Returns indices of and distances to the neighbors of each point. Parameters Xarray-like, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. n_neighborsint, default=None Number of neighbors required for each sample. The default is the value passed to the constructor. return_distancebool, default=True Whether or not to return the distances. Returns neigh_distndarray of shape (n_queries, n_neighbors) Array representing the lengths to points, only present if return_distance=True neigh_indndarray of shape (n_queries, n_neighbors) Indices of the nearest points in the population matrix. Examples In the following example, we construct a NearestNeighbors class from an array representing our data set and ask who’s the closest point to [1,1,1] >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=1) >>> neigh.fit(samples) NearestNeighbors(n_neighbors=1) >>> print(neigh.kneighbors([[1., 1., 1.]])) (array([[0.5]]), array([[2]])) As you can see, it returns [[0.5]], and [[2]], which means that the element is at distance 0.5 and is the third element of samples (indexes start at 0). You can also query for multiple points: >>> X = [[0., 1., 0.], [1., 0., 1.]] >>> neigh.kneighbors(X, return_distance=False) array([[1], [2]]...) kneighbors_graph(X=None, n_neighbors=None, mode='connectivity') [source] Computes the (weighted) graph of k-Neighbors for points in X Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For metric='precomputed' the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features). n_neighborsint, default=None Number of neighbors for each sample. The default is the value passed to the constructor. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. Returns Asparse-matrix of shape (n_queries, n_samples_fit) n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also NearestNeighbors.radius_neighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=2) >>> neigh.fit(X) NearestNeighbors(n_neighbors=2) >>> A = neigh.kneighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 1.], [1., 0., 1.]]) predict(X) [source] Predict the class labels for the provided data. Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’ Test samples. Returns yndarray of shape (n_queries,) or (n_queries, n_outputs) Class labels for each data sample. predict_proba(X) [source] Return probability estimates for the test data X. Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’ Test samples. Returns pndarray of shape (n_queries, n_classes), or a list of n_outputs of such arrays if n_outputs > 1. The class probabilities of the input samples. Classes are ordered by lexicographic order. score(X, y, sample_weight=None) [source] 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. Parameters Xarray-like of shape (n_samples, n_features) Test samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True labels for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat Mean accuracy of self.predict(X) wrt. y. set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
sklearn.modules.generated.sklearn.neighbors.kneighborsclassifier#sklearn.neighbors.KNeighborsClassifier
sklearn.neighbors.KNeighborsClassifier class sklearn.neighbors.KNeighborsClassifier(n_neighbors=5, *, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None, **kwargs) [source] Classifier implementing the k-nearest neighbors vote. Read more in the User Guide. Parameters n_neighborsint, default=5 Number of neighbors to use by default for kneighbors queries. weights{‘uniform’, ‘distance’} or callable, default=’uniform’ weight function used in prediction. Possible values: ‘uniform’ : uniform weights. All points in each neighborhood are weighted equally. ‘distance’ : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away. [callable] : a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights. algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’ Algorithm used to compute the nearest neighbors: ‘ball_tree’ will use BallTree ‘kd_tree’ will use KDTree ‘brute’ will use a brute-force search. ‘auto’ will attempt to decide the most appropriate algorithm based on the values passed to fit method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_sizeint, default=30 Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. pint, default=2 Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metricstr or callable, default=’minkowski’ the distance metric to use for the tree. The default metric is minkowski, and with p=2 is equivalent to the standard Euclidean metric. See the documentation of DistanceMetric for a list of available metrics. If metric is “precomputed”, X is assumed to be a distance matrix and must be square during fit. X may be a sparse graph, in which case only “nonzero” elements may be considered neighbors. metric_paramsdict, default=None Additional keyword arguments for the metric function. n_jobsint, default=None The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Doesn’t affect fit method. Attributes classes_array of shape (n_classes,) Class labels known to the classifier effective_metric_str or callble The distance metric used. It will be same as the metric parameter or a synonym of it, e.g. ‘euclidean’ if the metric parameter set to ‘minkowski’ and p parameter set to 2. effective_metric_params_dict Additional keyword arguments for the metric function. For most metrics will be same with metric_params parameter, but may also contain the p parameter value if the effective_metric_ attribute is set to ‘minkowski’. n_samples_fit_int Number of samples in the fitted data. outputs_2d_bool False when y’s shape is (n_samples, ) or (n_samples, 1) during fit otherwise True. See also RadiusNeighborsClassifier KNeighborsRegressor RadiusNeighborsRegressor NearestNeighbors Notes See Nearest Neighbors in the online documentation for a discussion of the choice of algorithm and leaf_size. Warning Regarding the Nearest Neighbors algorithms, if it is found that two neighbors, neighbor k+1 and k, have identical distances but different labels, the results will depend on the ordering of the training data. https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm Examples >>> X = [[0], [1], [2], [3]] >>> y = [0, 0, 1, 1] >>> from sklearn.neighbors import KNeighborsClassifier >>> neigh = KNeighborsClassifier(n_neighbors=3) >>> neigh.fit(X, y) KNeighborsClassifier(...) >>> print(neigh.predict([[1.1]])) [0] >>> print(neigh.predict_proba([[0.9]])) [[0.66666667 0.33333333]] Methods fit(X, y) Fit the k-nearest neighbors classifier from the training dataset. get_params([deep]) Get parameters for this estimator. kneighbors([X, n_neighbors, return_distance]) Finds the K-neighbors of a point. kneighbors_graph([X, n_neighbors, mode]) Computes the (weighted) graph of k-Neighbors for points in X predict(X) Predict the class labels for the provided data. predict_proba(X) Return probability estimates for the test data 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. fit(X, y) [source] Fit the k-nearest neighbors classifier from the training dataset. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric=’precomputed’ Training data. y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs) Target values. Returns selfKNeighborsClassifier The fitted k-nearest neighbors classifier. get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. kneighbors(X=None, n_neighbors=None, return_distance=True) [source] Finds the K-neighbors of a point. Returns indices of and distances to the neighbors of each point. Parameters Xarray-like, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. n_neighborsint, default=None Number of neighbors required for each sample. The default is the value passed to the constructor. return_distancebool, default=True Whether or not to return the distances. Returns neigh_distndarray of shape (n_queries, n_neighbors) Array representing the lengths to points, only present if return_distance=True neigh_indndarray of shape (n_queries, n_neighbors) Indices of the nearest points in the population matrix. Examples In the following example, we construct a NearestNeighbors class from an array representing our data set and ask who’s the closest point to [1,1,1] >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=1) >>> neigh.fit(samples) NearestNeighbors(n_neighbors=1) >>> print(neigh.kneighbors([[1., 1., 1.]])) (array([[0.5]]), array([[2]])) As you can see, it returns [[0.5]], and [[2]], which means that the element is at distance 0.5 and is the third element of samples (indexes start at 0). You can also query for multiple points: >>> X = [[0., 1., 0.], [1., 0., 1.]] >>> neigh.kneighbors(X, return_distance=False) array([[1], [2]]...) kneighbors_graph(X=None, n_neighbors=None, mode='connectivity') [source] Computes the (weighted) graph of k-Neighbors for points in X Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For metric='precomputed' the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features). n_neighborsint, default=None Number of neighbors for each sample. The default is the value passed to the constructor. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. Returns Asparse-matrix of shape (n_queries, n_samples_fit) n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also NearestNeighbors.radius_neighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=2) >>> neigh.fit(X) NearestNeighbors(n_neighbors=2) >>> A = neigh.kneighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 1.], [1., 0., 1.]]) predict(X) [source] Predict the class labels for the provided data. Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’ Test samples. Returns yndarray of shape (n_queries,) or (n_queries, n_outputs) Class labels for each data sample. predict_proba(X) [source] Return probability estimates for the test data X. Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’ Test samples. Returns pndarray of shape (n_queries, n_classes), or a list of n_outputs of such arrays if n_outputs > 1. The class probabilities of the input samples. Classes are ordered by lexicographic order. score(X, y, sample_weight=None) [source] 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. Parameters Xarray-like of shape (n_samples, n_features) Test samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True labels for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat Mean accuracy of self.predict(X) wrt. y. set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance. Examples using sklearn.neighbors.KNeighborsClassifier Release Highlights for scikit-learn 0.24 Classifier comparison Plot the decision boundaries of a VotingClassifier Nearest Neighbors Classification Caching nearest neighbors Comparing Nearest Neighbors with and without Neighborhood Components Analysis Dimensionality Reduction with Neighborhood Components Analysis Digits Classification Exercise Classification of text documents using sparse features
sklearn.modules.generated.sklearn.neighbors.kneighborsclassifier
fit(X, y) [source] Fit the k-nearest neighbors classifier from the training dataset. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric=’precomputed’ Training data. y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs) Target values. Returns selfKNeighborsClassifier The fitted k-nearest neighbors classifier.
sklearn.modules.generated.sklearn.neighbors.kneighborsclassifier#sklearn.neighbors.KNeighborsClassifier.fit
get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values.
sklearn.modules.generated.sklearn.neighbors.kneighborsclassifier#sklearn.neighbors.KNeighborsClassifier.get_params
kneighbors(X=None, n_neighbors=None, return_distance=True) [source] Finds the K-neighbors of a point. Returns indices of and distances to the neighbors of each point. Parameters Xarray-like, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. n_neighborsint, default=None Number of neighbors required for each sample. The default is the value passed to the constructor. return_distancebool, default=True Whether or not to return the distances. Returns neigh_distndarray of shape (n_queries, n_neighbors) Array representing the lengths to points, only present if return_distance=True neigh_indndarray of shape (n_queries, n_neighbors) Indices of the nearest points in the population matrix. Examples In the following example, we construct a NearestNeighbors class from an array representing our data set and ask who’s the closest point to [1,1,1] >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=1) >>> neigh.fit(samples) NearestNeighbors(n_neighbors=1) >>> print(neigh.kneighbors([[1., 1., 1.]])) (array([[0.5]]), array([[2]])) As you can see, it returns [[0.5]], and [[2]], which means that the element is at distance 0.5 and is the third element of samples (indexes start at 0). You can also query for multiple points: >>> X = [[0., 1., 0.], [1., 0., 1.]] >>> neigh.kneighbors(X, return_distance=False) array([[1], [2]]...)
sklearn.modules.generated.sklearn.neighbors.kneighborsclassifier#sklearn.neighbors.KNeighborsClassifier.kneighbors
kneighbors_graph(X=None, n_neighbors=None, mode='connectivity') [source] Computes the (weighted) graph of k-Neighbors for points in X Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For metric='precomputed' the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features). n_neighborsint, default=None Number of neighbors for each sample. The default is the value passed to the constructor. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. Returns Asparse-matrix of shape (n_queries, n_samples_fit) n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also NearestNeighbors.radius_neighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=2) >>> neigh.fit(X) NearestNeighbors(n_neighbors=2) >>> A = neigh.kneighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 1.], [1., 0., 1.]])
sklearn.modules.generated.sklearn.neighbors.kneighborsclassifier#sklearn.neighbors.KNeighborsClassifier.kneighbors_graph
predict(X) [source] Predict the class labels for the provided data. Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’ Test samples. Returns yndarray of shape (n_queries,) or (n_queries, n_outputs) Class labels for each data sample.
sklearn.modules.generated.sklearn.neighbors.kneighborsclassifier#sklearn.neighbors.KNeighborsClassifier.predict
predict_proba(X) [source] Return probability estimates for the test data X. Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’ Test samples. Returns pndarray of shape (n_queries, n_classes), or a list of n_outputs of such arrays if n_outputs > 1. The class probabilities of the input samples. Classes are ordered by lexicographic order.
sklearn.modules.generated.sklearn.neighbors.kneighborsclassifier#sklearn.neighbors.KNeighborsClassifier.predict_proba
score(X, y, sample_weight=None) [source] 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. Parameters Xarray-like of shape (n_samples, n_features) Test samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True labels for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat Mean accuracy of self.predict(X) wrt. y.
sklearn.modules.generated.sklearn.neighbors.kneighborsclassifier#sklearn.neighbors.KNeighborsClassifier.score
set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
sklearn.modules.generated.sklearn.neighbors.kneighborsclassifier#sklearn.neighbors.KNeighborsClassifier.set_params
class sklearn.neighbors.KNeighborsRegressor(n_neighbors=5, *, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None, **kwargs) [source] Regression based on k-nearest neighbors. The target is predicted by local interpolation of the targets associated of the nearest neighbors in the training set. Read more in the User Guide. New in version 0.9. Parameters n_neighborsint, default=5 Number of neighbors to use by default for kneighbors queries. weights{‘uniform’, ‘distance’} or callable, default=’uniform’ weight function used in prediction. Possible values: ‘uniform’ : uniform weights. All points in each neighborhood are weighted equally. ‘distance’ : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away. [callable] : a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights. Uniform weights are used by default. algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’ Algorithm used to compute the nearest neighbors: ‘ball_tree’ will use BallTree ‘kd_tree’ will use KDTree ‘brute’ will use a brute-force search. ‘auto’ will attempt to decide the most appropriate algorithm based on the values passed to fit method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_sizeint, default=30 Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. pint, default=2 Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metricstr or callable, default=’minkowski’ the distance metric to use for the tree. The default metric is minkowski, and with p=2 is equivalent to the standard Euclidean metric. See the documentation of DistanceMetric for a list of available metrics. If metric is “precomputed”, X is assumed to be a distance matrix and must be square during fit. X may be a sparse graph, in which case only “nonzero” elements may be considered neighbors. metric_paramsdict, default=None Additional keyword arguments for the metric function. n_jobsint, default=None The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Doesn’t affect fit method. Attributes effective_metric_str or callable The distance metric to use. It will be same as the metric parameter or a synonym of it, e.g. ‘euclidean’ if the metric parameter set to ‘minkowski’ and p parameter set to 2. effective_metric_params_dict Additional keyword arguments for the metric function. For most metrics will be same with metric_params parameter, but may also contain the p parameter value if the effective_metric_ attribute is set to ‘minkowski’. n_samples_fit_int Number of samples in the fitted data. See also NearestNeighbors RadiusNeighborsRegressor KNeighborsClassifier RadiusNeighborsClassifier Notes See Nearest Neighbors in the online documentation for a discussion of the choice of algorithm and leaf_size. Warning Regarding the Nearest Neighbors algorithms, if it is found that two neighbors, neighbor k+1 and k, have identical distances but different labels, the results will depend on the ordering of the training data. https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm Examples >>> X = [[0], [1], [2], [3]] >>> y = [0, 0, 1, 1] >>> from sklearn.neighbors import KNeighborsRegressor >>> neigh = KNeighborsRegressor(n_neighbors=2) >>> neigh.fit(X, y) KNeighborsRegressor(...) >>> print(neigh.predict([[1.5]])) [0.5] Methods fit(X, y) Fit the k-nearest neighbors regressor from the training dataset. get_params([deep]) Get parameters for this estimator. kneighbors([X, n_neighbors, return_distance]) Finds the K-neighbors of a point. kneighbors_graph([X, n_neighbors, mode]) Computes the (weighted) graph of k-Neighbors for points in X predict(X) Predict the target for the provided data score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction. set_params(**params) Set the parameters of this estimator. fit(X, y) [source] Fit the k-nearest neighbors regressor from the training dataset. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric=’precomputed’ Training data. y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs) Target values. Returns selfKNeighborsRegressor The fitted k-nearest neighbors regressor. get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. kneighbors(X=None, n_neighbors=None, return_distance=True) [source] Finds the K-neighbors of a point. Returns indices of and distances to the neighbors of each point. Parameters Xarray-like, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. n_neighborsint, default=None Number of neighbors required for each sample. The default is the value passed to the constructor. return_distancebool, default=True Whether or not to return the distances. Returns neigh_distndarray of shape (n_queries, n_neighbors) Array representing the lengths to points, only present if return_distance=True neigh_indndarray of shape (n_queries, n_neighbors) Indices of the nearest points in the population matrix. Examples In the following example, we construct a NearestNeighbors class from an array representing our data set and ask who’s the closest point to [1,1,1] >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=1) >>> neigh.fit(samples) NearestNeighbors(n_neighbors=1) >>> print(neigh.kneighbors([[1., 1., 1.]])) (array([[0.5]]), array([[2]])) As you can see, it returns [[0.5]], and [[2]], which means that the element is at distance 0.5 and is the third element of samples (indexes start at 0). You can also query for multiple points: >>> X = [[0., 1., 0.], [1., 0., 1.]] >>> neigh.kneighbors(X, return_distance=False) array([[1], [2]]...) kneighbors_graph(X=None, n_neighbors=None, mode='connectivity') [source] Computes the (weighted) graph of k-Neighbors for points in X Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For metric='precomputed' the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features). n_neighborsint, default=None Number of neighbors for each sample. The default is the value passed to the constructor. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. Returns Asparse-matrix of shape (n_queries, n_samples_fit) n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also NearestNeighbors.radius_neighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=2) >>> neigh.fit(X) NearestNeighbors(n_neighbors=2) >>> A = neigh.kneighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 1.], [1., 0., 1.]]) predict(X) [source] Predict the target for the provided data Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’ Test samples. Returns yndarray of shape (n_queries,) or (n_queries, n_outputs), dtype=int Target values. score(X, y, sample_weight=None) [source] 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. Parameters Xarray-like of shape (n_samples, n_features) 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. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True values for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat \(R^2\) of self.predict(X) wrt. y. Notes 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_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
sklearn.modules.generated.sklearn.neighbors.kneighborsregressor#sklearn.neighbors.KNeighborsRegressor
sklearn.neighbors.KNeighborsRegressor class sklearn.neighbors.KNeighborsRegressor(n_neighbors=5, *, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None, **kwargs) [source] Regression based on k-nearest neighbors. The target is predicted by local interpolation of the targets associated of the nearest neighbors in the training set. Read more in the User Guide. New in version 0.9. Parameters n_neighborsint, default=5 Number of neighbors to use by default for kneighbors queries. weights{‘uniform’, ‘distance’} or callable, default=’uniform’ weight function used in prediction. Possible values: ‘uniform’ : uniform weights. All points in each neighborhood are weighted equally. ‘distance’ : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away. [callable] : a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights. Uniform weights are used by default. algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’ Algorithm used to compute the nearest neighbors: ‘ball_tree’ will use BallTree ‘kd_tree’ will use KDTree ‘brute’ will use a brute-force search. ‘auto’ will attempt to decide the most appropriate algorithm based on the values passed to fit method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_sizeint, default=30 Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. pint, default=2 Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metricstr or callable, default=’minkowski’ the distance metric to use for the tree. The default metric is minkowski, and with p=2 is equivalent to the standard Euclidean metric. See the documentation of DistanceMetric for a list of available metrics. If metric is “precomputed”, X is assumed to be a distance matrix and must be square during fit. X may be a sparse graph, in which case only “nonzero” elements may be considered neighbors. metric_paramsdict, default=None Additional keyword arguments for the metric function. n_jobsint, default=None The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Doesn’t affect fit method. Attributes effective_metric_str or callable The distance metric to use. It will be same as the metric parameter or a synonym of it, e.g. ‘euclidean’ if the metric parameter set to ‘minkowski’ and p parameter set to 2. effective_metric_params_dict Additional keyword arguments for the metric function. For most metrics will be same with metric_params parameter, but may also contain the p parameter value if the effective_metric_ attribute is set to ‘minkowski’. n_samples_fit_int Number of samples in the fitted data. See also NearestNeighbors RadiusNeighborsRegressor KNeighborsClassifier RadiusNeighborsClassifier Notes See Nearest Neighbors in the online documentation for a discussion of the choice of algorithm and leaf_size. Warning Regarding the Nearest Neighbors algorithms, if it is found that two neighbors, neighbor k+1 and k, have identical distances but different labels, the results will depend on the ordering of the training data. https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm Examples >>> X = [[0], [1], [2], [3]] >>> y = [0, 0, 1, 1] >>> from sklearn.neighbors import KNeighborsRegressor >>> neigh = KNeighborsRegressor(n_neighbors=2) >>> neigh.fit(X, y) KNeighborsRegressor(...) >>> print(neigh.predict([[1.5]])) [0.5] Methods fit(X, y) Fit the k-nearest neighbors regressor from the training dataset. get_params([deep]) Get parameters for this estimator. kneighbors([X, n_neighbors, return_distance]) Finds the K-neighbors of a point. kneighbors_graph([X, n_neighbors, mode]) Computes the (weighted) graph of k-Neighbors for points in X predict(X) Predict the target for the provided data score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction. set_params(**params) Set the parameters of this estimator. fit(X, y) [source] Fit the k-nearest neighbors regressor from the training dataset. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric=’precomputed’ Training data. y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs) Target values. Returns selfKNeighborsRegressor The fitted k-nearest neighbors regressor. get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. kneighbors(X=None, n_neighbors=None, return_distance=True) [source] Finds the K-neighbors of a point. Returns indices of and distances to the neighbors of each point. Parameters Xarray-like, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. n_neighborsint, default=None Number of neighbors required for each sample. The default is the value passed to the constructor. return_distancebool, default=True Whether or not to return the distances. Returns neigh_distndarray of shape (n_queries, n_neighbors) Array representing the lengths to points, only present if return_distance=True neigh_indndarray of shape (n_queries, n_neighbors) Indices of the nearest points in the population matrix. Examples In the following example, we construct a NearestNeighbors class from an array representing our data set and ask who’s the closest point to [1,1,1] >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=1) >>> neigh.fit(samples) NearestNeighbors(n_neighbors=1) >>> print(neigh.kneighbors([[1., 1., 1.]])) (array([[0.5]]), array([[2]])) As you can see, it returns [[0.5]], and [[2]], which means that the element is at distance 0.5 and is the third element of samples (indexes start at 0). You can also query for multiple points: >>> X = [[0., 1., 0.], [1., 0., 1.]] >>> neigh.kneighbors(X, return_distance=False) array([[1], [2]]...) kneighbors_graph(X=None, n_neighbors=None, mode='connectivity') [source] Computes the (weighted) graph of k-Neighbors for points in X Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For metric='precomputed' the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features). n_neighborsint, default=None Number of neighbors for each sample. The default is the value passed to the constructor. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. Returns Asparse-matrix of shape (n_queries, n_samples_fit) n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also NearestNeighbors.radius_neighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=2) >>> neigh.fit(X) NearestNeighbors(n_neighbors=2) >>> A = neigh.kneighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 1.], [1., 0., 1.]]) predict(X) [source] Predict the target for the provided data Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’ Test samples. Returns yndarray of shape (n_queries,) or (n_queries, n_outputs), dtype=int Target values. score(X, y, sample_weight=None) [source] 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. Parameters Xarray-like of shape (n_samples, n_features) 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. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True values for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat \(R^2\) of self.predict(X) wrt. y. Notes 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_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance. Examples using sklearn.neighbors.KNeighborsRegressor Face completion with a multi-output estimators Imputing missing values with variants of IterativeImputer Nearest Neighbors regression
sklearn.modules.generated.sklearn.neighbors.kneighborsregressor
fit(X, y) [source] Fit the k-nearest neighbors regressor from the training dataset. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric=’precomputed’ Training data. y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs) Target values. Returns selfKNeighborsRegressor The fitted k-nearest neighbors regressor.
sklearn.modules.generated.sklearn.neighbors.kneighborsregressor#sklearn.neighbors.KNeighborsRegressor.fit
get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values.
sklearn.modules.generated.sklearn.neighbors.kneighborsregressor#sklearn.neighbors.KNeighborsRegressor.get_params
kneighbors(X=None, n_neighbors=None, return_distance=True) [source] Finds the K-neighbors of a point. Returns indices of and distances to the neighbors of each point. Parameters Xarray-like, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. n_neighborsint, default=None Number of neighbors required for each sample. The default is the value passed to the constructor. return_distancebool, default=True Whether or not to return the distances. Returns neigh_distndarray of shape (n_queries, n_neighbors) Array representing the lengths to points, only present if return_distance=True neigh_indndarray of shape (n_queries, n_neighbors) Indices of the nearest points in the population matrix. Examples In the following example, we construct a NearestNeighbors class from an array representing our data set and ask who’s the closest point to [1,1,1] >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=1) >>> neigh.fit(samples) NearestNeighbors(n_neighbors=1) >>> print(neigh.kneighbors([[1., 1., 1.]])) (array([[0.5]]), array([[2]])) As you can see, it returns [[0.5]], and [[2]], which means that the element is at distance 0.5 and is the third element of samples (indexes start at 0). You can also query for multiple points: >>> X = [[0., 1., 0.], [1., 0., 1.]] >>> neigh.kneighbors(X, return_distance=False) array([[1], [2]]...)
sklearn.modules.generated.sklearn.neighbors.kneighborsregressor#sklearn.neighbors.KNeighborsRegressor.kneighbors
kneighbors_graph(X=None, n_neighbors=None, mode='connectivity') [source] Computes the (weighted) graph of k-Neighbors for points in X Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For metric='precomputed' the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features). n_neighborsint, default=None Number of neighbors for each sample. The default is the value passed to the constructor. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. Returns Asparse-matrix of shape (n_queries, n_samples_fit) n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also NearestNeighbors.radius_neighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=2) >>> neigh.fit(X) NearestNeighbors(n_neighbors=2) >>> A = neigh.kneighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 1.], [1., 0., 1.]])
sklearn.modules.generated.sklearn.neighbors.kneighborsregressor#sklearn.neighbors.KNeighborsRegressor.kneighbors_graph
predict(X) [source] Predict the target for the provided data Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’ Test samples. Returns yndarray of shape (n_queries,) or (n_queries, n_outputs), dtype=int Target values.
sklearn.modules.generated.sklearn.neighbors.kneighborsregressor#sklearn.neighbors.KNeighborsRegressor.predict
score(X, y, sample_weight=None) [source] 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. Parameters Xarray-like of shape (n_samples, n_features) 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. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True values for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat \(R^2\) of self.predict(X) wrt. y. Notes 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).
sklearn.modules.generated.sklearn.neighbors.kneighborsregressor#sklearn.neighbors.KNeighborsRegressor.score
set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
sklearn.modules.generated.sklearn.neighbors.kneighborsregressor#sklearn.neighbors.KNeighborsRegressor.set_params
class sklearn.neighbors.KNeighborsTransformer(*, mode='distance', n_neighbors=5, algorithm='auto', leaf_size=30, metric='minkowski', p=2, metric_params=None, n_jobs=1) [source] Transform X into a (weighted) graph of k nearest neighbors The transformed data is a sparse graph as returned by kneighbors_graph. Read more in the User Guide. New in version 0.22. Parameters mode{‘distance’, ‘connectivity’}, default=’distance’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, and ‘distance’ will return the distances between neighbors according to the given metric. n_neighborsint, default=5 Number of neighbors for each sample in the transformed sparse graph. For compatibility reasons, as each sample is considered as its own neighbor, one extra neighbor will be computed when mode == ‘distance’. In this case, the sparse graph contains (n_neighbors + 1) neighbors. algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’ Algorithm used to compute the nearest neighbors: ‘ball_tree’ will use BallTree ‘kd_tree’ will use KDTree ‘brute’ will use a brute-force search. ‘auto’ will attempt to decide the most appropriate algorithm based on the values passed to fit method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_sizeint, default=30 Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. metricstr or callable, default=’minkowski’ metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy’s metrics, but is less efficient than passing the metric name as a string. Distance matrices are not supported. Valid values for metric are: from scikit-learn: [‘cityblock’, ‘cosine’, ‘euclidean’, ‘l1’, ‘l2’, ‘manhattan’] from scipy.spatial.distance: [‘braycurtis’, ‘canberra’, ‘chebyshev’, ‘correlation’, ‘dice’, ‘hamming’, ‘jaccard’, ‘kulsinski’, ‘mahalanobis’, ‘minkowski’, ‘rogerstanimoto’, ‘russellrao’, ‘seuclidean’, ‘sokalmichener’, ‘sokalsneath’, ‘sqeuclidean’, ‘yule’] See the documentation for scipy.spatial.distance for details on these metrics. pint, default=2 Parameter for the Minkowski metric from sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metric_paramsdict, default=None Additional keyword arguments for the metric function. n_jobsint, default=1 The number of parallel jobs to run for neighbors search. If -1, then the number of jobs is set to the number of CPU cores. Attributes effective_metric_str or callable The distance metric used. It will be same as the metric parameter or a synonym of it, e.g. ‘euclidean’ if the metric parameter set to ‘minkowski’ and p parameter set to 2. effective_metric_params_dict Additional keyword arguments for the metric function. For most metrics will be same with metric_params parameter, but may also contain the p parameter value if the effective_metric_ attribute is set to ‘minkowski’. n_samples_fit_int Number of samples in the fitted data. Examples >>> from sklearn.manifold import Isomap >>> from sklearn.neighbors import KNeighborsTransformer >>> from sklearn.pipeline import make_pipeline >>> estimator = make_pipeline( ... KNeighborsTransformer(n_neighbors=5, mode='distance'), ... Isomap(neighbors_algorithm='precomputed')) Methods fit(X[, y]) Fit the k-nearest neighbors transformer from the training dataset. fit_transform(X[, y]) Fit to data, then transform it. get_params([deep]) Get parameters for this estimator. kneighbors([X, n_neighbors, return_distance]) Finds the K-neighbors of a point. kneighbors_graph([X, n_neighbors, mode]) Computes the (weighted) graph of k-Neighbors for points in X set_params(**params) Set the parameters of this estimator. transform(X) Computes the (weighted) graph of Neighbors for points in X fit(X, y=None) [source] Fit the k-nearest neighbors transformer from the training dataset. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric=’precomputed’ Training data. Returns selfKNeighborsTransformer The fitted k-nearest neighbors transformer. fit_transform(X, y=None) [source] Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters Xarray-like of shape (n_samples, n_features) Training set. yignored Returns Xtsparse matrix of shape (n_samples, n_samples) Xt[i, j] is assigned the weight of edge that connects i to j. Only the neighbors have an explicit value. The diagonal is always explicit. The matrix is of CSR format. get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. kneighbors(X=None, n_neighbors=None, return_distance=True) [source] Finds the K-neighbors of a point. Returns indices of and distances to the neighbors of each point. Parameters Xarray-like, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. n_neighborsint, default=None Number of neighbors required for each sample. The default is the value passed to the constructor. return_distancebool, default=True Whether or not to return the distances. Returns neigh_distndarray of shape (n_queries, n_neighbors) Array representing the lengths to points, only present if return_distance=True neigh_indndarray of shape (n_queries, n_neighbors) Indices of the nearest points in the population matrix. Examples In the following example, we construct a NearestNeighbors class from an array representing our data set and ask who’s the closest point to [1,1,1] >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=1) >>> neigh.fit(samples) NearestNeighbors(n_neighbors=1) >>> print(neigh.kneighbors([[1., 1., 1.]])) (array([[0.5]]), array([[2]])) As you can see, it returns [[0.5]], and [[2]], which means that the element is at distance 0.5 and is the third element of samples (indexes start at 0). You can also query for multiple points: >>> X = [[0., 1., 0.], [1., 0., 1.]] >>> neigh.kneighbors(X, return_distance=False) array([[1], [2]]...) kneighbors_graph(X=None, n_neighbors=None, mode='connectivity') [source] Computes the (weighted) graph of k-Neighbors for points in X Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For metric='precomputed' the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features). n_neighborsint, default=None Number of neighbors for each sample. The default is the value passed to the constructor. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. Returns Asparse-matrix of shape (n_queries, n_samples_fit) n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also NearestNeighbors.radius_neighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=2) >>> neigh.fit(X) NearestNeighbors(n_neighbors=2) >>> A = neigh.kneighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 1.], [1., 0., 1.]]) set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance. transform(X) [source] Computes the (weighted) graph of Neighbors for points in X Parameters Xarray-like of shape (n_samples_transform, n_features) Sample data. Returns Xtsparse matrix of shape (n_samples_transform, n_samples_fit) Xt[i, j] is assigned the weight of edge that connects i to j. Only the neighbors have an explicit value. The diagonal is always explicit. The matrix is of CSR format.
sklearn.modules.generated.sklearn.neighbors.kneighborstransformer#sklearn.neighbors.KNeighborsTransformer
sklearn.neighbors.KNeighborsTransformer class sklearn.neighbors.KNeighborsTransformer(*, mode='distance', n_neighbors=5, algorithm='auto', leaf_size=30, metric='minkowski', p=2, metric_params=None, n_jobs=1) [source] Transform X into a (weighted) graph of k nearest neighbors The transformed data is a sparse graph as returned by kneighbors_graph. Read more in the User Guide. New in version 0.22. Parameters mode{‘distance’, ‘connectivity’}, default=’distance’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, and ‘distance’ will return the distances between neighbors according to the given metric. n_neighborsint, default=5 Number of neighbors for each sample in the transformed sparse graph. For compatibility reasons, as each sample is considered as its own neighbor, one extra neighbor will be computed when mode == ‘distance’. In this case, the sparse graph contains (n_neighbors + 1) neighbors. algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’ Algorithm used to compute the nearest neighbors: ‘ball_tree’ will use BallTree ‘kd_tree’ will use KDTree ‘brute’ will use a brute-force search. ‘auto’ will attempt to decide the most appropriate algorithm based on the values passed to fit method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_sizeint, default=30 Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. metricstr or callable, default=’minkowski’ metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy’s metrics, but is less efficient than passing the metric name as a string. Distance matrices are not supported. Valid values for metric are: from scikit-learn: [‘cityblock’, ‘cosine’, ‘euclidean’, ‘l1’, ‘l2’, ‘manhattan’] from scipy.spatial.distance: [‘braycurtis’, ‘canberra’, ‘chebyshev’, ‘correlation’, ‘dice’, ‘hamming’, ‘jaccard’, ‘kulsinski’, ‘mahalanobis’, ‘minkowski’, ‘rogerstanimoto’, ‘russellrao’, ‘seuclidean’, ‘sokalmichener’, ‘sokalsneath’, ‘sqeuclidean’, ‘yule’] See the documentation for scipy.spatial.distance for details on these metrics. pint, default=2 Parameter for the Minkowski metric from sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metric_paramsdict, default=None Additional keyword arguments for the metric function. n_jobsint, default=1 The number of parallel jobs to run for neighbors search. If -1, then the number of jobs is set to the number of CPU cores. Attributes effective_metric_str or callable The distance metric used. It will be same as the metric parameter or a synonym of it, e.g. ‘euclidean’ if the metric parameter set to ‘minkowski’ and p parameter set to 2. effective_metric_params_dict Additional keyword arguments for the metric function. For most metrics will be same with metric_params parameter, but may also contain the p parameter value if the effective_metric_ attribute is set to ‘minkowski’. n_samples_fit_int Number of samples in the fitted data. Examples >>> from sklearn.manifold import Isomap >>> from sklearn.neighbors import KNeighborsTransformer >>> from sklearn.pipeline import make_pipeline >>> estimator = make_pipeline( ... KNeighborsTransformer(n_neighbors=5, mode='distance'), ... Isomap(neighbors_algorithm='precomputed')) Methods fit(X[, y]) Fit the k-nearest neighbors transformer from the training dataset. fit_transform(X[, y]) Fit to data, then transform it. get_params([deep]) Get parameters for this estimator. kneighbors([X, n_neighbors, return_distance]) Finds the K-neighbors of a point. kneighbors_graph([X, n_neighbors, mode]) Computes the (weighted) graph of k-Neighbors for points in X set_params(**params) Set the parameters of this estimator. transform(X) Computes the (weighted) graph of Neighbors for points in X fit(X, y=None) [source] Fit the k-nearest neighbors transformer from the training dataset. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric=’precomputed’ Training data. Returns selfKNeighborsTransformer The fitted k-nearest neighbors transformer. fit_transform(X, y=None) [source] Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters Xarray-like of shape (n_samples, n_features) Training set. yignored Returns Xtsparse matrix of shape (n_samples, n_samples) Xt[i, j] is assigned the weight of edge that connects i to j. Only the neighbors have an explicit value. The diagonal is always explicit. The matrix is of CSR format. get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. kneighbors(X=None, n_neighbors=None, return_distance=True) [source] Finds the K-neighbors of a point. Returns indices of and distances to the neighbors of each point. Parameters Xarray-like, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. n_neighborsint, default=None Number of neighbors required for each sample. The default is the value passed to the constructor. return_distancebool, default=True Whether or not to return the distances. Returns neigh_distndarray of shape (n_queries, n_neighbors) Array representing the lengths to points, only present if return_distance=True neigh_indndarray of shape (n_queries, n_neighbors) Indices of the nearest points in the population matrix. Examples In the following example, we construct a NearestNeighbors class from an array representing our data set and ask who’s the closest point to [1,1,1] >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=1) >>> neigh.fit(samples) NearestNeighbors(n_neighbors=1) >>> print(neigh.kneighbors([[1., 1., 1.]])) (array([[0.5]]), array([[2]])) As you can see, it returns [[0.5]], and [[2]], which means that the element is at distance 0.5 and is the third element of samples (indexes start at 0). You can also query for multiple points: >>> X = [[0., 1., 0.], [1., 0., 1.]] >>> neigh.kneighbors(X, return_distance=False) array([[1], [2]]...) kneighbors_graph(X=None, n_neighbors=None, mode='connectivity') [source] Computes the (weighted) graph of k-Neighbors for points in X Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For metric='precomputed' the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features). n_neighborsint, default=None Number of neighbors for each sample. The default is the value passed to the constructor. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. Returns Asparse-matrix of shape (n_queries, n_samples_fit) n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also NearestNeighbors.radius_neighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=2) >>> neigh.fit(X) NearestNeighbors(n_neighbors=2) >>> A = neigh.kneighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 1.], [1., 0., 1.]]) set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance. transform(X) [source] Computes the (weighted) graph of Neighbors for points in X Parameters Xarray-like of shape (n_samples_transform, n_features) Sample data. Returns Xtsparse matrix of shape (n_samples_transform, n_samples_fit) Xt[i, j] is assigned the weight of edge that connects i to j. Only the neighbors have an explicit value. The diagonal is always explicit. The matrix is of CSR format. Examples using sklearn.neighbors.KNeighborsTransformer Release Highlights for scikit-learn 0.22 Caching nearest neighbors Approximate nearest neighbors in TSNE
sklearn.modules.generated.sklearn.neighbors.kneighborstransformer
fit(X, y=None) [source] Fit the k-nearest neighbors transformer from the training dataset. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric=’precomputed’ Training data. Returns selfKNeighborsTransformer The fitted k-nearest neighbors transformer.
sklearn.modules.generated.sklearn.neighbors.kneighborstransformer#sklearn.neighbors.KNeighborsTransformer.fit
fit_transform(X, y=None) [source] Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters Xarray-like of shape (n_samples, n_features) Training set. yignored Returns Xtsparse matrix of shape (n_samples, n_samples) Xt[i, j] is assigned the weight of edge that connects i to j. Only the neighbors have an explicit value. The diagonal is always explicit. The matrix is of CSR format.
sklearn.modules.generated.sklearn.neighbors.kneighborstransformer#sklearn.neighbors.KNeighborsTransformer.fit_transform
get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values.
sklearn.modules.generated.sklearn.neighbors.kneighborstransformer#sklearn.neighbors.KNeighborsTransformer.get_params
kneighbors(X=None, n_neighbors=None, return_distance=True) [source] Finds the K-neighbors of a point. Returns indices of and distances to the neighbors of each point. Parameters Xarray-like, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. n_neighborsint, default=None Number of neighbors required for each sample. The default is the value passed to the constructor. return_distancebool, default=True Whether or not to return the distances. Returns neigh_distndarray of shape (n_queries, n_neighbors) Array representing the lengths to points, only present if return_distance=True neigh_indndarray of shape (n_queries, n_neighbors) Indices of the nearest points in the population matrix. Examples In the following example, we construct a NearestNeighbors class from an array representing our data set and ask who’s the closest point to [1,1,1] >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=1) >>> neigh.fit(samples) NearestNeighbors(n_neighbors=1) >>> print(neigh.kneighbors([[1., 1., 1.]])) (array([[0.5]]), array([[2]])) As you can see, it returns [[0.5]], and [[2]], which means that the element is at distance 0.5 and is the third element of samples (indexes start at 0). You can also query for multiple points: >>> X = [[0., 1., 0.], [1., 0., 1.]] >>> neigh.kneighbors(X, return_distance=False) array([[1], [2]]...)
sklearn.modules.generated.sklearn.neighbors.kneighborstransformer#sklearn.neighbors.KNeighborsTransformer.kneighbors
kneighbors_graph(X=None, n_neighbors=None, mode='connectivity') [source] Computes the (weighted) graph of k-Neighbors for points in X Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For metric='precomputed' the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features). n_neighborsint, default=None Number of neighbors for each sample. The default is the value passed to the constructor. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. Returns Asparse-matrix of shape (n_queries, n_samples_fit) n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also NearestNeighbors.radius_neighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=2) >>> neigh.fit(X) NearestNeighbors(n_neighbors=2) >>> A = neigh.kneighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 1.], [1., 0., 1.]])
sklearn.modules.generated.sklearn.neighbors.kneighborstransformer#sklearn.neighbors.KNeighborsTransformer.kneighbors_graph
set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
sklearn.modules.generated.sklearn.neighbors.kneighborstransformer#sklearn.neighbors.KNeighborsTransformer.set_params
transform(X) [source] Computes the (weighted) graph of Neighbors for points in X Parameters Xarray-like of shape (n_samples_transform, n_features) Sample data. Returns Xtsparse matrix of shape (n_samples_transform, n_samples_fit) Xt[i, j] is assigned the weight of edge that connects i to j. Only the neighbors have an explicit value. The diagonal is always explicit. The matrix is of CSR format.
sklearn.modules.generated.sklearn.neighbors.kneighborstransformer#sklearn.neighbors.KNeighborsTransformer.transform
sklearn.neighbors.kneighbors_graph(X, n_neighbors, *, mode='connectivity', metric='minkowski', p=2, metric_params=None, include_self=False, n_jobs=None) [source] Computes the (weighted) graph of k-Neighbors for points in X Read more in the User Guide. Parameters Xarray-like of shape (n_samples, n_features) or BallTree Sample data, in the form of a numpy array or a precomputed BallTree. n_neighborsint Number of neighbors for each sample. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, and ‘distance’ will return the distances between neighbors according to the given metric. metricstr, default=’minkowski’ The distance metric used to calculate the k-Neighbors for each sample point. The DistanceMetric class gives a list of available metrics. The default distance is ‘euclidean’ (‘minkowski’ metric with the p param equal to 2.) pint, default=2 Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metric_paramsdict, default=None additional keyword arguments for the metric function. include_selfbool or ‘auto’, default=False Whether or not to mark each sample as the first nearest neighbor to itself. If ‘auto’, then True is used for mode=’connectivity’ and False for mode=’distance’. n_jobsint, default=None The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Returns Asparse matrix of shape (n_samples, n_samples) Graph where A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also radius_neighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import kneighbors_graph >>> A = kneighbors_graph(X, 2, mode='connectivity', include_self=True) >>> A.toarray() array([[1., 0., 1.], [0., 1., 1.], [1., 0., 1.]])
sklearn.modules.generated.sklearn.neighbors.kneighbors_graph#sklearn.neighbors.kneighbors_graph
class sklearn.neighbors.LocalOutlierFactor(n_neighbors=20, *, algorithm='auto', leaf_size=30, metric='minkowski', p=2, metric_params=None, contamination='auto', novelty=False, n_jobs=None) [source] Unsupervised Outlier Detection using Local Outlier Factor (LOF) The anomaly score of each sample is called Local Outlier Factor. It measures the local deviation of density of a given sample with respect to its neighbors. It is local in that the anomaly score depends on how isolated the object is with respect to the surrounding neighborhood. More precisely, locality is given by k-nearest neighbors, whose distance is used to estimate the local density. By comparing the local density of a sample to the local densities of its neighbors, one can identify samples that have a substantially lower density than their neighbors. These are considered outliers. New in version 0.19. Parameters n_neighborsint, default=20 Number of neighbors to use by default for kneighbors queries. If n_neighbors is larger than the number of samples provided, all samples will be used. algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’ Algorithm used to compute the nearest neighbors: ‘ball_tree’ will use BallTree ‘kd_tree’ will use KDTree ‘brute’ will use a brute-force search. ‘auto’ will attempt to decide the most appropriate algorithm based on the values passed to fit method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_sizeint, default=30 Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. metricstr or callable, default=’minkowski’ metric used for the distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is “precomputed”, X is assumed to be a distance matrix and must be square. X may be a sparse matrix, in which case only “nonzero” elements may be considered neighbors. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy’s metrics, but is less efficient than passing the metric name as a string. Valid values for metric are: from scikit-learn: [‘cityblock’, ‘cosine’, ‘euclidean’, ‘l1’, ‘l2’, ‘manhattan’] from scipy.spatial.distance: [‘braycurtis’, ‘canberra’, ‘chebyshev’, ‘correlation’, ‘dice’, ‘hamming’, ‘jaccard’, ‘kulsinski’, ‘mahalanobis’, ‘minkowski’, ‘rogerstanimoto’, ‘russellrao’, ‘seuclidean’, ‘sokalmichener’, ‘sokalsneath’, ‘sqeuclidean’, ‘yule’] See the documentation for scipy.spatial.distance for details on these metrics: https://docs.scipy.org/doc/scipy/reference/spatial.distance.html pint, default=2 Parameter for the Minkowski metric from sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metric_paramsdict, default=None Additional keyword arguments for the metric function. contamination‘auto’ or float, default=’auto’ The amount of contamination of the data set, i.e. the proportion of outliers in the data set. When fitting this is used to define the threshold on the scores of the samples. if ‘auto’, the threshold is determined as in the original paper, if a float, the contamination should be in the range [0, 0.5]. Changed in version 0.22: The default value of contamination changed from 0.1 to 'auto'. noveltybool, default=False By default, LocalOutlierFactor is only meant to be used for outlier detection (novelty=False). Set novelty to True if you want to use LocalOutlierFactor for novelty detection. In this case be aware that that you should only use predict, decision_function and score_samples on new unseen data and not on the training set. New in version 0.20. n_jobsint, default=None The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Attributes negative_outlier_factor_ndarray of shape (n_samples,) The opposite LOF of the training samples. The higher, the more normal. Inliers tend to have a LOF score close to 1 (negative_outlier_factor_ close to -1), while outliers tend to have a larger LOF score. The local outlier factor (LOF) of a sample captures its supposed ‘degree of abnormality’. It is the average of the ratio of the local reachability density of a sample and those of its k-nearest neighbors. n_neighbors_int The actual number of neighbors used for kneighbors queries. offset_float Offset used to obtain binary labels from the raw scores. Observations having a negative_outlier_factor smaller than offset_ are detected as abnormal. The offset is set to -1.5 (inliers score around -1), except when a contamination parameter different than “auto” is provided. In that case, the offset is defined in such a way we obtain the expected number of outliers in training. New in version 0.20. effective_metric_str The effective metric used for the distance computation. effective_metric_params_dict The effective additional keyword arguments for the metric function. n_samples_fit_int It is the number of samples in the fitted data. References 1 Breunig, M. M., Kriegel, H. P., Ng, R. T., & Sander, J. (2000, May). LOF: identifying density-based local outliers. In ACM sigmod record. Examples >>> import numpy as np >>> from sklearn.neighbors import LocalOutlierFactor >>> X = [[-1.1], [0.2], [101.1], [0.3]] >>> clf = LocalOutlierFactor(n_neighbors=2) >>> clf.fit_predict(X) array([ 1, 1, -1, 1]) >>> clf.negative_outlier_factor_ array([ -0.9821..., -1.0370..., -73.3697..., -0.9821...]) Methods fit(X[, y]) Fit the local outlier factor detector from the training dataset. get_params([deep]) Get parameters for this estimator. kneighbors([X, n_neighbors, return_distance]) Finds the K-neighbors of a point. kneighbors_graph([X, n_neighbors, mode]) Computes the (weighted) graph of k-Neighbors for points in X set_params(**params) Set the parameters of this estimator. property decision_function Shifted opposite of the Local Outlier Factor of X. Bigger is better, i.e. large values correspond to inliers. Only available for novelty detection (when novelty is set to True). The shift offset allows a zero threshold for being an outlier. The argument X is supposed to contain new data: if X contains a point from training, it considers the later in its own neighborhood. Also, the samples in X are not considered in the neighborhood of any point. Parameters Xarray-like of shape (n_samples, n_features) The query sample or samples to compute the Local Outlier Factor w.r.t. the training samples. Returns shifted_opposite_lof_scoresndarray of shape (n_samples,) The shifted opposite of the Local Outlier Factor of each input samples. The lower, the more abnormal. Negative scores represent outliers, positive scores represent inliers. fit(X, y=None) [source] Fit the local outlier factor detector from the training dataset. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric=’precomputed’ Training data. yIgnored Not used, present for API consistency by convention. Returns selfLocalOutlierFactor The fitted local outlier factor detector. property fit_predict Fits the model to the training set X and returns the labels. Not available for novelty detection (when novelty is set to True). Label is 1 for an inlier and -1 for an outlier according to the LOF score and the contamination parameter. Parameters Xarray-like of shape (n_samples, n_features), default=None The query sample or samples to compute the Local Outlier Factor w.r.t. to the training samples. yIgnored Not used, present for API consistency by convention. Returns is_inlierndarray of shape (n_samples,) Returns -1 for anomalies/outliers and 1 for inliers. get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. kneighbors(X=None, n_neighbors=None, return_distance=True) [source] Finds the K-neighbors of a point. Returns indices of and distances to the neighbors of each point. Parameters Xarray-like, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. n_neighborsint, default=None Number of neighbors required for each sample. The default is the value passed to the constructor. return_distancebool, default=True Whether or not to return the distances. Returns neigh_distndarray of shape (n_queries, n_neighbors) Array representing the lengths to points, only present if return_distance=True neigh_indndarray of shape (n_queries, n_neighbors) Indices of the nearest points in the population matrix. Examples In the following example, we construct a NearestNeighbors class from an array representing our data set and ask who’s the closest point to [1,1,1] >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=1) >>> neigh.fit(samples) NearestNeighbors(n_neighbors=1) >>> print(neigh.kneighbors([[1., 1., 1.]])) (array([[0.5]]), array([[2]])) As you can see, it returns [[0.5]], and [[2]], which means that the element is at distance 0.5 and is the third element of samples (indexes start at 0). You can also query for multiple points: >>> X = [[0., 1., 0.], [1., 0., 1.]] >>> neigh.kneighbors(X, return_distance=False) array([[1], [2]]...) kneighbors_graph(X=None, n_neighbors=None, mode='connectivity') [source] Computes the (weighted) graph of k-Neighbors for points in X Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For metric='precomputed' the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features). n_neighborsint, default=None Number of neighbors for each sample. The default is the value passed to the constructor. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. Returns Asparse-matrix of shape (n_queries, n_samples_fit) n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also NearestNeighbors.radius_neighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=2) >>> neigh.fit(X) NearestNeighbors(n_neighbors=2) >>> A = neigh.kneighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 1.], [1., 0., 1.]]) property predict Predict the labels (1 inlier, -1 outlier) of X according to LOF. Only available for novelty detection (when novelty is set to True). This method allows to generalize prediction to new observations (not in the training set). Parameters Xarray-like of shape (n_samples, n_features) The query sample or samples to compute the Local Outlier Factor w.r.t. to the training samples. Returns is_inlierndarray of shape (n_samples,) Returns -1 for anomalies/outliers and +1 for inliers. property score_samples Opposite of the Local Outlier Factor of X. It is the opposite as bigger is better, i.e. large values correspond to inliers. Only available for novelty detection (when novelty is set to True). The argument X is supposed to contain new data: if X contains a point from training, it considers the later in its own neighborhood. Also, the samples in X are not considered in the neighborhood of any point. The score_samples on training data is available by considering the the negative_outlier_factor_ attribute. Parameters Xarray-like of shape (n_samples, n_features) The query sample or samples to compute the Local Outlier Factor w.r.t. the training samples. Returns opposite_lof_scoresndarray of shape (n_samples,) The opposite of the Local Outlier Factor of each input samples. The lower, the more abnormal. set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
sklearn.modules.generated.sklearn.neighbors.localoutlierfactor#sklearn.neighbors.LocalOutlierFactor
sklearn.neighbors.LocalOutlierFactor class sklearn.neighbors.LocalOutlierFactor(n_neighbors=20, *, algorithm='auto', leaf_size=30, metric='minkowski', p=2, metric_params=None, contamination='auto', novelty=False, n_jobs=None) [source] Unsupervised Outlier Detection using Local Outlier Factor (LOF) The anomaly score of each sample is called Local Outlier Factor. It measures the local deviation of density of a given sample with respect to its neighbors. It is local in that the anomaly score depends on how isolated the object is with respect to the surrounding neighborhood. More precisely, locality is given by k-nearest neighbors, whose distance is used to estimate the local density. By comparing the local density of a sample to the local densities of its neighbors, one can identify samples that have a substantially lower density than their neighbors. These are considered outliers. New in version 0.19. Parameters n_neighborsint, default=20 Number of neighbors to use by default for kneighbors queries. If n_neighbors is larger than the number of samples provided, all samples will be used. algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’ Algorithm used to compute the nearest neighbors: ‘ball_tree’ will use BallTree ‘kd_tree’ will use KDTree ‘brute’ will use a brute-force search. ‘auto’ will attempt to decide the most appropriate algorithm based on the values passed to fit method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_sizeint, default=30 Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. metricstr or callable, default=’minkowski’ metric used for the distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is “precomputed”, X is assumed to be a distance matrix and must be square. X may be a sparse matrix, in which case only “nonzero” elements may be considered neighbors. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy’s metrics, but is less efficient than passing the metric name as a string. Valid values for metric are: from scikit-learn: [‘cityblock’, ‘cosine’, ‘euclidean’, ‘l1’, ‘l2’, ‘manhattan’] from scipy.spatial.distance: [‘braycurtis’, ‘canberra’, ‘chebyshev’, ‘correlation’, ‘dice’, ‘hamming’, ‘jaccard’, ‘kulsinski’, ‘mahalanobis’, ‘minkowski’, ‘rogerstanimoto’, ‘russellrao’, ‘seuclidean’, ‘sokalmichener’, ‘sokalsneath’, ‘sqeuclidean’, ‘yule’] See the documentation for scipy.spatial.distance for details on these metrics: https://docs.scipy.org/doc/scipy/reference/spatial.distance.html pint, default=2 Parameter for the Minkowski metric from sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metric_paramsdict, default=None Additional keyword arguments for the metric function. contamination‘auto’ or float, default=’auto’ The amount of contamination of the data set, i.e. the proportion of outliers in the data set. When fitting this is used to define the threshold on the scores of the samples. if ‘auto’, the threshold is determined as in the original paper, if a float, the contamination should be in the range [0, 0.5]. Changed in version 0.22: The default value of contamination changed from 0.1 to 'auto'. noveltybool, default=False By default, LocalOutlierFactor is only meant to be used for outlier detection (novelty=False). Set novelty to True if you want to use LocalOutlierFactor for novelty detection. In this case be aware that that you should only use predict, decision_function and score_samples on new unseen data and not on the training set. New in version 0.20. n_jobsint, default=None The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Attributes negative_outlier_factor_ndarray of shape (n_samples,) The opposite LOF of the training samples. The higher, the more normal. Inliers tend to have a LOF score close to 1 (negative_outlier_factor_ close to -1), while outliers tend to have a larger LOF score. The local outlier factor (LOF) of a sample captures its supposed ‘degree of abnormality’. It is the average of the ratio of the local reachability density of a sample and those of its k-nearest neighbors. n_neighbors_int The actual number of neighbors used for kneighbors queries. offset_float Offset used to obtain binary labels from the raw scores. Observations having a negative_outlier_factor smaller than offset_ are detected as abnormal. The offset is set to -1.5 (inliers score around -1), except when a contamination parameter different than “auto” is provided. In that case, the offset is defined in such a way we obtain the expected number of outliers in training. New in version 0.20. effective_metric_str The effective metric used for the distance computation. effective_metric_params_dict The effective additional keyword arguments for the metric function. n_samples_fit_int It is the number of samples in the fitted data. References 1 Breunig, M. M., Kriegel, H. P., Ng, R. T., & Sander, J. (2000, May). LOF: identifying density-based local outliers. In ACM sigmod record. Examples >>> import numpy as np >>> from sklearn.neighbors import LocalOutlierFactor >>> X = [[-1.1], [0.2], [101.1], [0.3]] >>> clf = LocalOutlierFactor(n_neighbors=2) >>> clf.fit_predict(X) array([ 1, 1, -1, 1]) >>> clf.negative_outlier_factor_ array([ -0.9821..., -1.0370..., -73.3697..., -0.9821...]) Methods fit(X[, y]) Fit the local outlier factor detector from the training dataset. get_params([deep]) Get parameters for this estimator. kneighbors([X, n_neighbors, return_distance]) Finds the K-neighbors of a point. kneighbors_graph([X, n_neighbors, mode]) Computes the (weighted) graph of k-Neighbors for points in X set_params(**params) Set the parameters of this estimator. property decision_function Shifted opposite of the Local Outlier Factor of X. Bigger is better, i.e. large values correspond to inliers. Only available for novelty detection (when novelty is set to True). The shift offset allows a zero threshold for being an outlier. The argument X is supposed to contain new data: if X contains a point from training, it considers the later in its own neighborhood. Also, the samples in X are not considered in the neighborhood of any point. Parameters Xarray-like of shape (n_samples, n_features) The query sample or samples to compute the Local Outlier Factor w.r.t. the training samples. Returns shifted_opposite_lof_scoresndarray of shape (n_samples,) The shifted opposite of the Local Outlier Factor of each input samples. The lower, the more abnormal. Negative scores represent outliers, positive scores represent inliers. fit(X, y=None) [source] Fit the local outlier factor detector from the training dataset. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric=’precomputed’ Training data. yIgnored Not used, present for API consistency by convention. Returns selfLocalOutlierFactor The fitted local outlier factor detector. property fit_predict Fits the model to the training set X and returns the labels. Not available for novelty detection (when novelty is set to True). Label is 1 for an inlier and -1 for an outlier according to the LOF score and the contamination parameter. Parameters Xarray-like of shape (n_samples, n_features), default=None The query sample or samples to compute the Local Outlier Factor w.r.t. to the training samples. yIgnored Not used, present for API consistency by convention. Returns is_inlierndarray of shape (n_samples,) Returns -1 for anomalies/outliers and 1 for inliers. get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. kneighbors(X=None, n_neighbors=None, return_distance=True) [source] Finds the K-neighbors of a point. Returns indices of and distances to the neighbors of each point. Parameters Xarray-like, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. n_neighborsint, default=None Number of neighbors required for each sample. The default is the value passed to the constructor. return_distancebool, default=True Whether or not to return the distances. Returns neigh_distndarray of shape (n_queries, n_neighbors) Array representing the lengths to points, only present if return_distance=True neigh_indndarray of shape (n_queries, n_neighbors) Indices of the nearest points in the population matrix. Examples In the following example, we construct a NearestNeighbors class from an array representing our data set and ask who’s the closest point to [1,1,1] >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=1) >>> neigh.fit(samples) NearestNeighbors(n_neighbors=1) >>> print(neigh.kneighbors([[1., 1., 1.]])) (array([[0.5]]), array([[2]])) As you can see, it returns [[0.5]], and [[2]], which means that the element is at distance 0.5 and is the third element of samples (indexes start at 0). You can also query for multiple points: >>> X = [[0., 1., 0.], [1., 0., 1.]] >>> neigh.kneighbors(X, return_distance=False) array([[1], [2]]...) kneighbors_graph(X=None, n_neighbors=None, mode='connectivity') [source] Computes the (weighted) graph of k-Neighbors for points in X Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For metric='precomputed' the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features). n_neighborsint, default=None Number of neighbors for each sample. The default is the value passed to the constructor. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. Returns Asparse-matrix of shape (n_queries, n_samples_fit) n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also NearestNeighbors.radius_neighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=2) >>> neigh.fit(X) NearestNeighbors(n_neighbors=2) >>> A = neigh.kneighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 1.], [1., 0., 1.]]) property predict Predict the labels (1 inlier, -1 outlier) of X according to LOF. Only available for novelty detection (when novelty is set to True). This method allows to generalize prediction to new observations (not in the training set). Parameters Xarray-like of shape (n_samples, n_features) The query sample or samples to compute the Local Outlier Factor w.r.t. to the training samples. Returns is_inlierndarray of shape (n_samples,) Returns -1 for anomalies/outliers and +1 for inliers. property score_samples Opposite of the Local Outlier Factor of X. It is the opposite as bigger is better, i.e. large values correspond to inliers. Only available for novelty detection (when novelty is set to True). The argument X is supposed to contain new data: if X contains a point from training, it considers the later in its own neighborhood. Also, the samples in X are not considered in the neighborhood of any point. The score_samples on training data is available by considering the the negative_outlier_factor_ attribute. Parameters Xarray-like of shape (n_samples, n_features) The query sample or samples to compute the Local Outlier Factor w.r.t. the training samples. Returns opposite_lof_scoresndarray of shape (n_samples,) The opposite of the Local Outlier Factor of each input samples. The lower, the more abnormal. set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance. Examples using sklearn.neighbors.LocalOutlierFactor Comparing anomaly detection algorithms for outlier detection on toy datasets Outlier detection with Local Outlier Factor (LOF) Novelty detection with Local Outlier Factor (LOF)
sklearn.modules.generated.sklearn.neighbors.localoutlierfactor
property decision_function Shifted opposite of the Local Outlier Factor of X. Bigger is better, i.e. large values correspond to inliers. Only available for novelty detection (when novelty is set to True). The shift offset allows a zero threshold for being an outlier. The argument X is supposed to contain new data: if X contains a point from training, it considers the later in its own neighborhood. Also, the samples in X are not considered in the neighborhood of any point. Parameters Xarray-like of shape (n_samples, n_features) The query sample or samples to compute the Local Outlier Factor w.r.t. the training samples. Returns shifted_opposite_lof_scoresndarray of shape (n_samples,) The shifted opposite of the Local Outlier Factor of each input samples. The lower, the more abnormal. Negative scores represent outliers, positive scores represent inliers.
sklearn.modules.generated.sklearn.neighbors.localoutlierfactor#sklearn.neighbors.LocalOutlierFactor.decision_function
fit(X, y=None) [source] Fit the local outlier factor detector from the training dataset. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric=’precomputed’ Training data. yIgnored Not used, present for API consistency by convention. Returns selfLocalOutlierFactor The fitted local outlier factor detector.
sklearn.modules.generated.sklearn.neighbors.localoutlierfactor#sklearn.neighbors.LocalOutlierFactor.fit
property fit_predict Fits the model to the training set X and returns the labels. Not available for novelty detection (when novelty is set to True). Label is 1 for an inlier and -1 for an outlier according to the LOF score and the contamination parameter. Parameters Xarray-like of shape (n_samples, n_features), default=None The query sample or samples to compute the Local Outlier Factor w.r.t. to the training samples. yIgnored Not used, present for API consistency by convention. Returns is_inlierndarray of shape (n_samples,) Returns -1 for anomalies/outliers and 1 for inliers.
sklearn.modules.generated.sklearn.neighbors.localoutlierfactor#sklearn.neighbors.LocalOutlierFactor.fit_predict
get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values.
sklearn.modules.generated.sklearn.neighbors.localoutlierfactor#sklearn.neighbors.LocalOutlierFactor.get_params
kneighbors(X=None, n_neighbors=None, return_distance=True) [source] Finds the K-neighbors of a point. Returns indices of and distances to the neighbors of each point. Parameters Xarray-like, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. n_neighborsint, default=None Number of neighbors required for each sample. The default is the value passed to the constructor. return_distancebool, default=True Whether or not to return the distances. Returns neigh_distndarray of shape (n_queries, n_neighbors) Array representing the lengths to points, only present if return_distance=True neigh_indndarray of shape (n_queries, n_neighbors) Indices of the nearest points in the population matrix. Examples In the following example, we construct a NearestNeighbors class from an array representing our data set and ask who’s the closest point to [1,1,1] >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=1) >>> neigh.fit(samples) NearestNeighbors(n_neighbors=1) >>> print(neigh.kneighbors([[1., 1., 1.]])) (array([[0.5]]), array([[2]])) As you can see, it returns [[0.5]], and [[2]], which means that the element is at distance 0.5 and is the third element of samples (indexes start at 0). You can also query for multiple points: >>> X = [[0., 1., 0.], [1., 0., 1.]] >>> neigh.kneighbors(X, return_distance=False) array([[1], [2]]...)
sklearn.modules.generated.sklearn.neighbors.localoutlierfactor#sklearn.neighbors.LocalOutlierFactor.kneighbors
kneighbors_graph(X=None, n_neighbors=None, mode='connectivity') [source] Computes the (weighted) graph of k-Neighbors for points in X Parameters Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For metric='precomputed' the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features). n_neighborsint, default=None Number of neighbors for each sample. The default is the value passed to the constructor. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. Returns Asparse-matrix of shape (n_queries, n_samples_fit) n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also NearestNeighbors.radius_neighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=2) >>> neigh.fit(X) NearestNeighbors(n_neighbors=2) >>> A = neigh.kneighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 1.], [1., 0., 1.]])
sklearn.modules.generated.sklearn.neighbors.localoutlierfactor#sklearn.neighbors.LocalOutlierFactor.kneighbors_graph
property predict Predict the labels (1 inlier, -1 outlier) of X according to LOF. Only available for novelty detection (when novelty is set to True). This method allows to generalize prediction to new observations (not in the training set). Parameters Xarray-like of shape (n_samples, n_features) The query sample or samples to compute the Local Outlier Factor w.r.t. to the training samples. Returns is_inlierndarray of shape (n_samples,) Returns -1 for anomalies/outliers and +1 for inliers.
sklearn.modules.generated.sklearn.neighbors.localoutlierfactor#sklearn.neighbors.LocalOutlierFactor.predict
property score_samples Opposite of the Local Outlier Factor of X. It is the opposite as bigger is better, i.e. large values correspond to inliers. Only available for novelty detection (when novelty is set to True). The argument X is supposed to contain new data: if X contains a point from training, it considers the later in its own neighborhood. Also, the samples in X are not considered in the neighborhood of any point. The score_samples on training data is available by considering the the negative_outlier_factor_ attribute. Parameters Xarray-like of shape (n_samples, n_features) The query sample or samples to compute the Local Outlier Factor w.r.t. the training samples. Returns opposite_lof_scoresndarray of shape (n_samples,) The opposite of the Local Outlier Factor of each input samples. The lower, the more abnormal.
sklearn.modules.generated.sklearn.neighbors.localoutlierfactor#sklearn.neighbors.LocalOutlierFactor.score_samples
set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
sklearn.modules.generated.sklearn.neighbors.localoutlierfactor#sklearn.neighbors.LocalOutlierFactor.set_params