generated from LufsX/Challenge-kNN
This commit is contained in:
+13
-11
@@ -1,6 +1,6 @@
|
||||
# function.py
|
||||
import numpy as np
|
||||
|
||||
from numpy.linalg import inv, det
|
||||
"""
|
||||
挑战说明:
|
||||
- 自行编写实现 KNN 分类算法。
|
||||
@@ -51,20 +51,22 @@ def classify0(inX, dataSet, labels, k=3):
|
||||
返回值:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
# 计算协方差矩阵及其逆
|
||||
covariance_matrix = np.cov(dataSet, rowvar=False)
|
||||
inv_covmat = inv(covariance_matrix)
|
||||
mean = np.mean(dataSet, axis=0)
|
||||
cov_inv = inv(np.cov(dataSet, rowvar=False))
|
||||
|
||||
# 计算马氏距离
|
||||
distances = np.array([mahalanobis(inX, dataSet[i], inv_covmat) for i in range(dataSet.shape[0])])
|
||||
# 计算输入样本与每个训练样本之间的马氏距离
|
||||
distances = []
|
||||
for data in dataSet:
|
||||
diff = inX - data
|
||||
distance = np.sqrt(np.dot(np.dot(diff, cov_inv), diff.T))
|
||||
distances.append(distance)
|
||||
|
||||
# 对距离进行排序并找到最近的k个邻居
|
||||
sortedDistIndices = distances.argsort()[:k]
|
||||
|
||||
# 进行简单投票
|
||||
distances = np.array(distances)
|
||||
sortedDistIndices = distances.argsort()
|
||||
classCount = {}
|
||||
for i in sortedDistIndices:
|
||||
voteIlabel = labels[i]
|
||||
for i in range(k):
|
||||
voteIlabel = labels[sortedDistIndices[i]]
|
||||
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
|
||||
|
||||
# 返回出现次数最多的类别
|
||||
|
||||
Reference in New Issue
Block a user