KNNPython代码
时间: 2024-05-16 08:15:52 浏览: 129
knn的python代码
以下是一个简单的KNN分类器的Python代码示例:
```python
import numpy as np
from collections import Counter
class KNN():
def __init__(self, k=3):
self.k = k
def fit(self, X_train, y_train):
self.X_train = X_train
self.y_train = y_train
def predict(self, X_test):
predictions = []
for x in X_test:
distances = []
for i, x_train in enumerate(self.X_train):
distance = np.sqrt(np.sum(np.square(x - x_train)))
distances.append((distance, i))
distances = sorted(distances)
k_nearest_neighbors = [self.y_train[i] for d, i in distances[:self.k]]
most_common = Counter(k_nearest_neighbors).most_common(1)
predictions.append(most_common[0][0])
return predictions
```
这个KNN分类器使用欧几里得距离计算距离,并且返回最常见的k个邻居的分类标签的众数作为预测结果。在使用之前,需要将要训练的数据和对应的标签传递给`fit()`函数。在进行预测时,将测试数据传递给`predict()`函数,它会返回一个包含预测标签的列表。
阅读全文