generated from LufsX/Experiment-kNN
This commit is contained in:
+3
-2
@@ -41,6 +41,7 @@ def classify(input_vector, dataSet, labels, k=2):
|
|||||||
Returns:
|
Returns:
|
||||||
- int: 预测的分类标签。
|
- int: 预测的分类标签。
|
||||||
"""
|
"""
|
||||||
|
sigma=1.0
|
||||||
dataSet_size = dataSet.shape[0]
|
dataSet_size = dataSet.shape[0]
|
||||||
# 计算欧氏距离
|
# 计算欧氏距离
|
||||||
diff_mat = np.tile(input_vector, (dataSet_size, 1)) - dataSet
|
diff_mat = np.tile(input_vector, (dataSet_size, 1)) - dataSet
|
||||||
@@ -52,8 +53,8 @@ def classify(input_vector, dataSet, labels, k=2):
|
|||||||
class_count = {}
|
class_count = {}
|
||||||
for i in range(k):
|
for i in range(k):
|
||||||
vote_label = labels[sorted_indices[i]]
|
vote_label = labels[sorted_indices[i]]
|
||||||
# 计算权重,这里采用简单的距离倒数作为权重
|
# 采用高斯核函数计算权重
|
||||||
weight = 1 / distances[sorted_indices[i]]
|
weight = np.exp(- sq_distances[sorted_indices[i]] / (2 * sigma ** 2))
|
||||||
class_count[vote_label] = class_count.get(vote_label, 0) + weight
|
class_count[vote_label] = class_count.get(vote_label, 0) + weight
|
||||||
sorted_class_count = sorted(class_count.items(), key=lambda x: x[1], reverse=True)
|
sorted_class_count = sorted(class_count.items(), key=lambda x: x[1], reverse=True)
|
||||||
return sorted_class_count[0][0]
|
return sorted_class_count[0][0]
|
||||||
|
|||||||
Reference in New Issue
Block a user