knn Python代码实现
时间: 2023-06-06 14:05:05 浏览: 121
当然可以!下面是一个简单的knn Python代码实现:
```python
import numpy as np
from collections import Counter
def euclidean_distance(x1, x2):
return np.sqrt(np.sum((x1 - x2)**2))
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):
predicted_labels = [self._predict(x) for x in X]
return np.array(predicted_labels)
def _predict(self, x):
distances = [euclidean_distance(x, x_train) 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[0][0]
```
这个代码实现了一个简单的KNN分类器,其中欧式距离被用于计算相似度。使用方法如下:
```python
X_train = np.array([[1,2], [2,4], [3,2], [3,4]])
y_train = np.array([0, 0, 1, 1])
knn = KNN(k=3)
knn.fit(X_train, y_train)
X_test = np.array([[1,3], [2,1]])
predictions = knn.predict(X_test)
print(predictions)
```
输出应该是一个包含两个数字的数组,代表对应的测试样本的预测标签。
阅读全文