generated from LufsX/Challenge-kNN
96 lines
2.9 KiB
Python
96 lines
2.9 KiB
Python
# function.py
|
|
import numpy as np
|
|
from numpy.linalg import inv, det
|
|
from scipy.stats import mode
|
|
"""
|
|
挑战说明:
|
|
- 自行编写实现 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 = "202210423226"
|
|
name = "潘宇豪"
|
|
|
|
|
|
"""
|
|
参数说明:
|
|
- inX (numpy array): 输入待分类的样本。
|
|
- dataSet (numpy array): 训练数据集。
|
|
- labels (list or numpy array): 训练集对应的标签。
|
|
返回值:
|
|
- int: 预测的分类标签。
|
|
"""
|
|
|
|
|
|
def classify0(inX, dataSet, labels, k):
|
|
"""
|
|
KNN classification using Mahalanobis distance for fast computation.
|
|
inX: The input sample to classify
|
|
dataSet: The training data
|
|
labels: The corresponding labels for the training data
|
|
k: The number of nearest neighbors to consider
|
|
"""
|
|
# Calculate covariance matrix and its inverse from the dataset
|
|
cov_matrix = np.cov(dataSet.T)
|
|
inv_cov_matrix = inv(cov_matrix)
|
|
|
|
# Compute the Mahalanobis distance between inX and all points in the dataset
|
|
diff = dataSet - inX
|
|
distances = np.sqrt(np.sum(np.dot(diff, inv_cov_matrix) * diff, axis=1))
|
|
|
|
# Sort by distance and return the indices of the k nearest neighbors
|
|
sorted_indices = np.argsort(distances)
|
|
|
|
# Get the labels of the k nearest neighbors
|
|
k_nearest_labels = [labels[i] for i in sorted_indices[:k]]
|
|
|
|
# Return the most common label among the k nearest neighbors
|
|
most_common_label = Counter(k_nearest_labels).most_common(1)[0][0]
|
|
|
|
return most_common_label
|
|
|
|
def load_data(file_path):
|
|
"""
|
|
加载TSV格式的数据文件。
|
|
|
|
参数:
|
|
- file_path (str): 数据文件的路径。
|
|
|
|
返回值:
|
|
- tuple: 包含特征数组和标签数组的元组。
|
|
"""
|
|
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)
|
|
# 使用一个测试样本进行测试
|
|
test_result = classify0([65915, 3.868359, 0.128078], train_data, train_labels, k=3)
|
|
print("预测结果:", test_result) |