knn算法的python代码
时间: 2024-03-10 08:41:37 浏览: 75
K最近邻(K-nearest neighbors,KNN)算法是种常用的分类和回归算法。它的基本思想是通过计算待分类样本与训练集中各个样本之间的距离,选取距离最近的K个样本作为邻居,然后根据邻居的标签进行投票或者计算平均值来确定待分类样本的类别或者数值。
下面是一个简单的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):
y_pred = [self._predict(x) for x in X]
return np.array(y_pred)
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]
```
使用示例:
```python
# 创建训练集和标签
X_train = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11]])
y_train = np.array(['red', 'red', 'blue', 'blue', 'red', 'blue'])
# 创建KNN分类器对象
knn = KNN(k=3)
# 训练模型
knn.fit(X_train, y_train)
# 创建测试集
X_test = np.array([[1, 1], [2, 3], [6, 9], [8, 9]])
# 预测测试集的标签
y_pred = knn.predict(X_test)
print(y_pred) # 输出预测结果
```
希望以上代码能够帮助到你!
阅读全文