Files
Challenge-KNN/function.py
T
wujunjie 65a57d4383
Gitea Actions Challenge Test / Challenge-Actions (push) Successful in 11s
更新 function.py
2024-10-06 18:12:39 +08:00

98 lines
2.7 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 中。
挑战环境:
- Ubuntu 22.04.04 LTS
- Python 3.10.12
"""
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423217"
name = "吴俊煯"
"""
参数说明:
- inX (numpy array): 输入待分类的样本。
- dataSet (numpy array): 训练数据集。
- labels (list or numpy array): 训练集对应的标签。
返回值:
- int: 预测的分类标签。
"""
# 这里写自己的代码实现
def classify0(inX, dataSet, labels):
"""
KNN 分类算法。
Args:
- inX (numpy array): 输入待分类的样本。
- dataSet (numpy array): 训练数据集。
- labels (list or numpy array): 训练集对应的标签。
Returns:
- int: 预测的分类标签。
"""
# 获取数据集的大小
dataSetSize =dataSet.shape[0]
# 计算数据集的协方差矩阵的逆
VI = np.linalg.inv(np.cov(dataSet.T))
# 计算 Mahalanobis 距离
distances =npzeros(dataSetSize)
for i in range(dataSetSize):
distances[i]=mahalanobis(inX,dataSeti],VI)
# 对距离排序,获取前 k 个最近的样本索引
sortedDistIndices=distances.argsort)
# 统计前 k 个样本的标签
classCount ={}
for i in range(9):
voteLabel=labels[sortedDistIndices[i]]
classCount[voteLabel]=classCount.get(voteLabel,0)+1
# 返回出现次数最多的标签
sortedClasscount=sorted(classCount.items(),key=operator,itemgetter(1),reverse=True
return sortedclassCount[0][0]
def load_data(file_path):
"""
加载 TSV 格式数据文件。
"""
features = []
labels = []
with open(file_path, "r") as file:
for line in file:
values = line.strip().split("\t")
features.append([float(x) for x in values[:-1]])
labels.append(int(values[-1]))
return np.array(features), np.array(labels)
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
train_file = "datingTrainSet2.tsv"
train_data, train_labels = load_data(train_file)
print(classify0([65915, 3.868359, 0.128078], train_data, train_labels))