Files
Challenge-KNN/function.py
T
heart20003 0d1754a486
Gitea Actions Challenge Test / Challenge-Actions (push) Successful in 10s
更新 function.py
2024-10-17 16:16:42 +08:00

69 lines
2.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# function.py
import numpy as np
"""
挑战说明:
- 自行编写实现 KNN 分类算法。
- 函数输入: 待分类的样本 inX, 训练数据集 dataSet, 训练集对应的标签 labels。
- 函数返回: 预测的分类标签。
注意事项:
- 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。
- 在 function.py 中实现 KNN 分类算法。
- 自动评测脚本仅会加载 classify0 函数,请勿修改函数名。
- 训练集在本目录下的 datingTrainSet2.tsv 中。
- 评测数据集在本目录下的 datingTestSet2.tsv 中。
挑战环境:
- CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz
- OS: Ubuntu 22.04.4 LTS
- Python: 3.10.12
- numpy: 2.1.1
"""
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423204"
name = "陈垣豪"
"""
参数说明:
- inX (numpy array): 输入待分类的样本。
- dataSet (numpy array): 训练数据集。
- labels (list or numpy array): 训练集对应的标签。
- k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。
返回值:
- int: 预测的分类标签。
"""
def classify0(inX, 数据集, 标签, k=3):
# 计算协方差矩阵并求其逆矩阵
cov_matrix = np.cov(数据集,rowvar=False)
inv_cov_matrix = np.linalg.inv(cov_matrix)
# 计算马氏距离
diff = dataSet - inX
distances = np.sum(diff @ inv_cov_matrix * diff, axis=1)
# 获取距离最小的 k 个样本的索引
sorted_indices = np.argsort(distances)[:k]
# 获取 k 个最近邻的标签
nearest_labels = [labels[i] for i in sorted_indices]
# 统计 k 个最近邻中每个类别的出现次数
label_count = {}
for label in nearest_labels:
if label in label_count:
label_count[label] += 1
else:
label_count[label] = 1
# 找到出现次数最多的标签
predicted_label = max(label_count, key=label_count.get)
return predicted_label提高准确率