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)[source]#

实现 k 最近邻投票的分类器。

Read more in the User Guide.

参数:
n_neighborsint, default=5

Number of neighbors to use by default for kneighbors queries.

weights{‘uniform’, ‘distance’}, callable 或 None, 默认值=’uniform’

预测中使用的权重函数。可能的值:

  • ‘uniform’:均匀权重。邻域中的所有点都具有相同的权重。

  • ‘distance’:按距离的倒数对点进行加权。在这种情况下,查询点越近的邻居将比越远的邻居具有更大的影响力。

  • [callable] : 一个用户定义的函数,它接受一个距离数组,并返回一个具有相同形状的数组,其中包含权重。

Refer to the example entitled Nearest Neighbors Classification showing the impact of the weights parameter on the decision boundary.

algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’

用于计算最近邻居的算法

  • ‘ball_tree’ 将使用 BallTree

  • ‘kd_tree’ 将使用 KDTree

  • 'brute' 将使用暴力搜索。

  • ‘auto’ will attempt to decide the most appropriate algorithm based on the values passed to fit method.

注意:对稀疏输入进行拟合将覆盖此参数的设置,使用暴力方法。

leaf_sizeint, default=30

传递给 BallTree 或 KDTree 的叶子大小。这会影响构建和查询的速度,以及存储树所需的内存。最佳值取决于问题的性质。

pfloat, default=2

Minkowski 度量的幂参数。当 p = 1 时,这相当于使用 manhattan_distance (l1),而 p = 2 时使用 euclidean_distance (l2)。对于任意 p,使用 minkowski_distance (l_p)。此参数预期为正数。

metricstr or callable, default=’minkowski’

用于距离计算的度量。默认为“minkowski”,当 p = 2 时,它会产生标准的欧几里得距离。有关有效的度量值,请参阅scipy.spatial.distance的文档以及distance_metrics中列出的度量。

如果 metric 为 “precomputed”,则 X 被假定为一个距离矩阵,并且在 fit 时必须是方形的。X 可以是 稀疏图,在这种情况下,只有“非零”元素可能被视为邻居。

如果 metric 是可调用函数,它接受表示 1D 向量的两个数组作为输入,并且必须返回一个值来指示这些向量之间的距离。这适用于 Scipy 的度量,但效率低于将度量名称作为字符串传递。

metric_paramsdict, default=None

度量函数的附加关键字参数。

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.

属性:
classes_array of shape (n_classes,)

分类器已知的类别标签

effective_metric_str or callble

使用的距离度量。它将与 metric 参数相同或其同义词,例如,如果 metric 参数设置为 'minkowski' 且 p 参数设置为 2,则为 'euclidean'。

effective_metric_params_dict

度量函数的附加关键字参数。对于大多数度量,将与 metric_params 参数相同,但如果 effective_metric_ 属性设置为 'minkowski',也可能包含 p 参数值。

n_features_in_int

拟合 期间看到的特征数。

0.24 版本新增。

feature_names_in_shape 为 (n_features_in_,) 的 ndarray

fit 期间看到的特征名称。仅当 X 具有全部为字符串的特征名称时才定义。

1.0 版本新增。

n_samples_fit_int

拟合数据中的样本数量。

outputs_2d_bool

False when y’s shape is (n_samples, ) or (n_samples, 1) during fit otherwise True.

另请参阅

RadiusNeighborsClassifier

Classifier based on neighbors within a fixed radius.

KNeighborsRegressor

基于 k 最近邻的回归。

RadiusNeighborsRegressor

基于固定半径内邻居的回归。

NearestNeighbors

用于实现邻居搜索的无监督学习器。

注意事项

有关 `algorithm` 和 `leaf_size` 选择的讨论,请参阅在线文档中的 最近邻

警告

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

示例

>>> 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.666 0.333]]
fit(X, y)[source]#

Fit the k-nearest neighbors classifier from the training dataset.

参数:
X{类数组, 稀疏矩阵},形状为 (n_samples, n_features) 或 (n_samples, n_samples) 如果 metric='precomputed'

训练数据。

y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs)

目标值。

返回:
selfKNeighborsClassifier

The fitted k-nearest neighbors classifier.

get_metadata_routing()[source]#

获取此对象的元数据路由。

请查阅 用户指南,了解路由机制如何工作。

返回:
routingMetadataRequest

封装路由信息的 MetadataRequest

get_params(deep=True)[source]#

获取此估计器的参数。

参数:
deepbool, default=True

如果为 True,将返回此估计器以及包含的子对象(如果它们是估计器)的参数。

返回:
paramsdict

参数名称映射到其值。

kneighbors(X=None, n_neighbors=None, return_distance=True)[source]#

找到一个点的 K-邻居。

返回每个点的邻居的索引和距离。

参数:
X{类数组, 稀疏矩阵},形状为 (n_queries, n_features),如果 metric == ‘precomputed’ 则为 (n_queries, n_indexed),默认=None

查询点或点集。如果未提供,则返回每个索引点的邻居。在这种情况下,查询点不被视为其自身的邻居。

n_neighborsint, default=None

每个样本所需的邻居数量。默认值为构造函数中传递的值。

return_distance布尔值,默认=True

是否返回距离。

返回:
neigh_distndarray,形状为 (n_queries, n_neighbors)

表示到点的长度的数组,仅当 return_distance=True 时存在。

neigh_indndarray,形状为 (n_queries, n_neighbors)

总体矩阵中最近点的索引。

示例

在以下示例中,我们从表示我们数据集的数组构建了一个 NearestNeighbors 类,并询问哪个点离 [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]]))

正如您所看到的,它返回 [[0.5]] 和 [[2]],这意味着该元素距离为 0.5,并且是样本中的第三个元素(索引从 0 开始)。您还可以查询多个点。

>>> 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]#

计算 X 中点的 k-Neighbors(加权)图。

参数:
X{类数组, 稀疏矩阵},形状为 (n_queries, n_features),如果 metric == ‘precomputed’ 则为 (n_queries, n_indexed),默认=None

查询点或点集。如果未提供,则返回每个索引点的邻居。在这种情况下,查询点不被视为其自身的邻居。对于 metric='precomputed',形状应为 (n_queries, n_indexed)。否则,形状应为 (n_queries, n_features)。

n_neighborsint, default=None

每个样本的邻居数量。默认值为构造函数中传递的值。

mode{‘connectivity’, ‘distance’}, default=’connectivity’

返回矩阵的类型:‘connectivity’ 将返回包含 1 和 0 的连通性矩阵,‘distance’ 中边是点之间的距离,距离类型取决于 NearestNeighbors 类中选择的度量参数。

返回:
A稀疏矩阵,形状为 (n_queries, n_samples_fit)

n_samples_fit 是拟合数据中的样本数量。A[i, j] 给出连接 ij 的边的权重。矩阵为 CSR 格式。

另请参阅

NearestNeighbors.radius_neighbors_graph

计算 X 中点的 Neighbors(加权)图。

示例

>>> 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.

参数:
X{array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, or None

测试样本。如果为 None,则返回所有索引点的预测;在这种情况下,点不被视为其自身的邻居。

返回:
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.

参数:
X{array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, or None

测试样本。如果为 None,则返回所有索引点的预测;在这种情况下,点不被视为其自身的邻居。

返回:
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.

在多标签分类中,这是子集准确率 (subset accuracy),这是一个严格的指标,因为它要求每个样本的每个标签集都被正确预测。

参数:
Xarray-like of shape (n_samples, n_features), or None

Test samples. If None, predictions for all indexed points are used; in this case, points are not considered their own neighbors. This means that knn.fit(X, y).score(None, y) implicitly performs a leave-one-out cross-validation procedure and is equivalent to cross_val_score(knn, X, y, cv=LeaveOneOut()) but typically much faster.

yshape 为 (n_samples,) 或 (n_samples, n_outputs) 的 array-like

X 的真实标签。

sample_weightshape 为 (n_samples,) 的 array-like, default=None

样本权重。

返回:
scorefloat

self.predict(X) 相对于 y 的平均准确率。

set_params(**params)[source]#

设置此估计器的参数。

此方法适用于简单的估计器以及嵌套对象(如 Pipeline)。后者具有 <component>__<parameter> 形式的参数,以便可以更新嵌套对象的每个组件。

参数:
**paramsdict

估计器参数。

返回:
selfestimator instance

估计器实例。

set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') KNeighborsClassifier[source]#

配置是否应请求元数据以传递给 score 方法。

请注意,此方法仅在以下情况下相关:此估计器用作 元估计器 中的子估计器,并且通过 enable_metadata_routing=True 启用了元数据路由(请参阅 sklearn.set_config)。请查看 用户指南 以了解路由机制的工作原理。

每个参数的选项如下:

  • True:请求元数据,如果提供则传递给 score。如果未提供元数据,则忽略该请求。

  • False:不请求元数据,元估计器不会将其传递给 score

  • None:不请求元数据,如果用户提供元数据,元估计器将引发错误。

  • str:应将元数据以给定别名而不是原始名称传递给元估计器。

默认值 (sklearn.utils.metadata_routing.UNCHANGED) 保留现有请求。这允许您更改某些参数的请求而不更改其他参数。

在版本 1.3 中新增。

参数:
sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

score 方法中 sample_weight 参数的元数据路由。

返回:
selfobject

更新后的对象。