generated from LufsX/Challenge-kNN
This commit is contained in:
+21
-5
@@ -40,9 +40,10 @@ name = "梅晓东"
|
||||
"""
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
import numpy as np
|
||||
import operator
|
||||
def classify0(inX, dataSet, labels, k=0):
|
||||
|
||||
def classify0(inX, dataSet, labels, k=3):
|
||||
"""
|
||||
KNN 分类算法。
|
||||
|
||||
@@ -55,10 +56,18 @@ def classify0(inX, dataSet, labels, k=0):
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
dataSetSize = dataSet.shape[0]
|
||||
|
||||
# 确保 k 不大于训练集的大小
|
||||
if k > dataSet.shape[0]:
|
||||
raise ValueError(f"k={k} cannot be greater than the number of training samples {dataSet.shape[0]}.")
|
||||
|
||||
# 计算协方差矩阵及其逆矩阵
|
||||
cov_matrix = np.cov(dataSet, rowvar=False)
|
||||
|
||||
# 防止协方差矩阵不可逆
|
||||
if np.linalg.det(cov_matrix) == 0:
|
||||
raise ValueError("Covariance matrix is singular and cannot be inverted.")
|
||||
|
||||
inv_cov_matrix = np.linalg.inv(cov_matrix)
|
||||
|
||||
# 计算马氏距离
|
||||
@@ -67,13 +76,20 @@ def classify0(inX, dataSet, labels, k=0):
|
||||
mahalanobis_distances = np.sqrt(np.sum(left_term * diffMat, axis=1))
|
||||
|
||||
# 排序距离并选择前 k 个最近邻
|
||||
sortedDistIndicies = mahalanobis_distances.argsort()
|
||||
sortedDistIndices = mahalanobis_distances.argsort()
|
||||
|
||||
classCount = {}
|
||||
for i in range(k):
|
||||
vote_label = labels[sortedDistIndicies[i]]
|
||||
vote_label = labels[sortedDistIndices[i]]
|
||||
classCount[vote_label] = classCount.get(vote_label, 0) + 1
|
||||
|
||||
# 将类计数排序
|
||||
sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
|
||||
|
||||
# 如果没有找到任何类别,抛出错误
|
||||
if not sortedClassCount:
|
||||
raise ValueError("No class votes found. Please check your training data.")
|
||||
|
||||
return sortedClassCount[0][0]
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user