更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 31s

This commit is contained in:
cy
2024-10-15 20:51:26 +08:00
parent 0f89bbabd8
commit 995f9fc7d5
+3 -2
View File
@@ -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]