KNN使用马氏距离的python代码
时间: 2023-11-12 16:45:52 浏览: 131
以下是使用Python实现KNN算法,并使用马氏距离进行距离度量的示例代码:
```python
import numpy as np
from scipy.spatial.distance import mahalanobis
def knn(X_train, y_train, X_test, k):
y_pred = []
for i in range(len(X_test)):
distances = []
for j in range(len(X_train)):
distance = mahalanobis(X_test[i], X_train[j])
distances.append((distance, y_train[j]))
distances.sort(key=lambda x: x[0])
neighbors = distances[:k]
labels = [neighbor[1] for neighbor in neighbors]
unique, counts = np.unique(labels, return_counts=True)
y_pred.append(unique[np.argmax(counts)])
return y_pred
# 示例用法
X_train = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
y_train = np.array([0, 0, 1, 1])
X_test = np.array([[4, 5], [2, 3]])
k = 3
predictions = knn(X_train, y_train, X_test, k)
print(predictions)
```
在上述示例中,`X_train`是训练数据的特征向量,`y_train`是对应的类标签。`X_test`是测试数据的特征向量。参数`k`表示选择最近邻居的数量。函数`knn`返回预测的类标签列表`y_pred`。
请注意,此代码使用了`scipy`库中的`mahalanobis`函数来计算马氏距离。确保已经安装了`scipy`库,并正确导入了相关模块。
阅读全文