generated from LufsX/Experiment-kNN
This commit is contained in:
+11
-7
@@ -41,16 +41,20 @@ name = "李劲"
|
||||
"""
|
||||
|
||||
|
||||
def classify(input_vector, dataSet, labels, k=3):
|
||||
cov_matrix = np.cov(dataSet, rowvar=False)
|
||||
inv_cov_matrix = np.linalg.inv(cov_matrix)
|
||||
# 计算欧氏距离
|
||||
diffMat = dataSet - input_vector
|
||||
left_term = np.dot(diffMat, inv_cov_matrix)
|
||||
mahalanobis_distances = np.sqrt(np.sum(left_term * diffMat, axis=1))
|
||||
k_indices = np.argsort(mahalanobis_distances)[:k]
|
||||
euclidean_distances = np.sqrt(np.sum(diffMat ** 2, axis=1))
|
||||
|
||||
# 获取距离最近的 k 个样本的索引
|
||||
k_indices = np.argsort(euclidean_distances)[:k]
|
||||
|
||||
# 获取最近邻样本的标签
|
||||
k_nearest_labels = [labels[i] for i in k_indices]
|
||||
|
||||
# 找出出现次数最多的标签
|
||||
most_common = max(set(k_nearest_labels), key=k_nearest_labels.count)
|
||||
return most_common
|
||||
|
||||
return most_common
|
||||
|
||||
def load_dataset(directory):
|
||||
features = []
|
||||
|
||||
Reference in New Issue
Block a user