generated from LufsX/Challenge-kNN
62 lines
1.8 KiB
Python
62 lines
1.8 KiB
Python
import numpy as np
|
|
import os
|
|
|
|
"""
|
|
请在这里填写学号和姓名,不填写即成绩无效。
|
|
"""
|
|
id = "202210423124"
|
|
name = "刘子豪"
|
|
|
|
def classify0(input_vector, dataSet, labels, k=3):
|
|
"""
|
|
KNN 分类算法。
|
|
|
|
Args:
|
|
- input_vector (numpy array): 输入待分类的样本。
|
|
- dataSet (numpy array): 训练数据集。
|
|
- labels (list or numpy array): 训练集对应的标签。
|
|
- k (int): kNN 算法参数,请**自行设置默认值**。
|
|
|
|
Returns:
|
|
- int: 预测的分类标签。
|
|
"""
|
|
# 计算输入向量与训练集中每个样本的欧氏距离
|
|
distances = np.linalg.norm(dataSet - input_vector, axis=1)
|
|
|
|
# 按照距离从小到大排序并获取前k个距离最小的索引
|
|
sorted_indices = distances.argsort()[:k]
|
|
|
|
# 统计前k个最近邻的标签
|
|
nearest_labels = [labels[i] for i in sorted_indices]
|
|
|
|
# 返回出现次数最多的标签
|
|
predicted_label = max(set(nearest_labels), key=nearest_labels.count)
|
|
|
|
return predicted_label
|
|
|
|
def load_data(file_path):
|
|
"""
|
|
从 TSV 文件中加载数据集。
|
|
|
|
Args:
|
|
- file_path (str): TSV 文件路径。
|
|
|
|
Returns:
|
|
- np.array: 特征数据。
|
|
- np.array: 标签数据。
|
|
"""
|
|
data = np.loadtxt(file_path, delimiter='\t')
|
|
data_set = data[:, :-1] # 假设最后一列是标签
|
|
labels = data[:, -1].astype(int)
|
|
return data_set, labels
|
|
|
|
if __name__ == "__main__":
|
|
# 以下代码可用于测试,可自行随意修改
|
|
train_file = "datingTrainSet2.tsv"
|
|
train_data, train_labels = load_data(train_file)
|
|
|
|
# 示例测试样本,确保维度与训练数据一致
|
|
test_sample = np.array([65915, 3.868359, 0.128078])
|
|
prediction = classify0(test_sample, train_data, train_labels)
|
|
print(f"预测的分类标签: {prediction}")
|