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

This commit is contained in:
2024-10-15 11:05:32 +08:00
parent 0e65dec242
commit 09eead31ab
+36 -2
View File
@@ -60,6 +60,39 @@ def classify(input_vector, dataSet, labels, k=3):
返回:
- int: 预测的分类标签。
"""
# 在 classify 函数中实现权重投票
distances = np.sum((input_vector - dataSet) ** 2, axis=1)
sorted_indices = distances.argsort()
k_nearest_distances = distances[sorted_indices[:k]]
k_nearest_labels = labels[sorted_indices[:k]]
# 计算权重(距离的倒数)
weights = 1 / k_nearest_distances
# 归一化权重
weights /= weights.sum()
# 计算加权投票
weighted_votes = np.zeros((10,))
for label, weight in zip(k_nearest_labels, weights):
weighted_votes[label] += weight
return np.argmax(weighted_votes)
# 在 load_dataset 函数中添加特征缩放
def load_dataset(directory):
feature_list = []
label_list = []
for file in os.listdir(directory):
file_path = os.path.join(directory, file)
feature_vector = img_to_vector(file_path)
feature_list.append(feature_vector)
label_list.append(int(file.split('_')[0]))
feature_matrix = np.array(feature_list)
label_array = np.array(label_list)
# 特征缩放
feature_matrix = feature_matrix / 255.0
return feature_matrix, label_array
# 计算输入向量与训练集之间的欧氏距离
distances = np.sum((input_vector - dataSet) ** 2, axis=1) ** 0.5
# 根据距离排序并获取索引
@@ -80,8 +113,8 @@ def load_dataset(directory):
- directory (str): 数据文件夹路径。
返回:
- np.array: 特征数据(Mx1024)。
- np.array: 标签数据(Mx1)。
- np.array: 特征数据(Mx1024)。
- np.array: 标签数据(Mx1)。
"""
# 初始化特征数据列表和标签列表
feature_list = []
@@ -165,3 +198,4 @@ if __name__ == "__main__":
)
print(f"预测的标签: {predicted_label}")