knn算法python代码
时间: 2023-10-13 18:19:30 浏览: 63
下面是一个简单的 Python 实现 KNN 算法的例子:
```python
from collections import Counter
import math
def euclidean_distance(x1, x2):
distance = 0
for i in range(len(x1)):
distance += (x1[i] - x2[i]) ** 2
return math.sqrt(distance)
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 y_pred
def _predict(self, x):
distances = [euclidean_distance(x, x_train) for x_train in self.X_train]
k_indices = sorted(range(len(distances)), key=lambda i: distances[i])[: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[0][0]
```
使用方法:
```python
# 创建 KNN 对象并拟合数据
knn = KNN(k=3)
knn.fit(X_train, y_train)
# 预测测试集数据
y_pred = knn.predict(X_test)
```
其中,`X_train` 和 `y_train` 分别是训练集的特征和标签,`X_test` 是测试集的特征,`y_pred` 是预测结果。`k` 是 KNN 算法中的超参数,表示选取最近邻的个数。
阅读全文