K-近邻算法的设计与实现python代码
时间: 2023-12-12 17:02:15 浏览: 78
K-近邻算法的python实现代码分享
5星 · 资源好评率100%
以下是K-近邻算法的Python代码实现:
```python
import numpy as np
from collections import Counter
class KNN:
def __init__(self, k):
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):
y_pred = []
for x in X_test:
distances = [np.sqrt(np.sum((x - x_train)**2)) for x_train in self.X_train]
nearest_indexes = np.argsort(distances)[:self.k]
nearest_labels = [self.y_train[i] for i in nearest_indexes]
most_common_label = Counter(nearest_labels).most_common(1)[0][0]
y_pred.append(most_common_label)
return y_pred
```
其中,`KNN`类包括以下方法:
- `__init__(self, k)`:初始化方法,传入K值。
- `fit(self, X_train, y_train)`:训练方法,传入训练集特征和标签。
- `predict(self, X_test)`:预测方法,传入测试集特征,返回预测结果。
阅读全文