knn算法python实现代码
时间: 2024-05-13 16:12:17 浏览: 151
KNN算法是一种常用的机器学习算法,可以用于分类和回归。其原理是通过计算待分类数据与训练数据之间的距离,选取距离最近的k个数据进行分类或回归。
以下是一个简单的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, y):
self.X_train = X
self.y_train = y
def predict(self, X):
y_pred = [self._predict(x) for x in X]
return np.array(y_pred)
def _predict(self, x):
distances = [np.sqrt(np.sum((x - x_train)**2)) for x_train in self.X_train]
k_indices = np.argsort(distances)[:self.k]
k_nearest_labels = [self.y_train[i] for i in k_indices]
most_common = Counter(k_nearest_labels).most_common(1)
return most_common
```
其中,fit方法用于训练模型,predict方法用于预测结果,_predict方法用于预测单个样本。
阅读全文