generated from LufsX/Challenge-kNN
132 lines
3.9 KiB
Python
132 lines
3.9 KiB
Python
# 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 = "202210423109"
|
|
name = "孔祥芷"
|
|
|
|
|
|
"""
|
|
参数说明:
|
|
- inX (numpy array): 输入待分类的样本。
|
|
- dataSet (numpy array): 训练数据集。
|
|
- labels (list or numpy array): 训练集对应的标签。
|
|
返回值:
|
|
- int: 预测的分类标签。
|
|
"""
|
|
|
|
|
|
# 这里写自己的代码实现
|
|
|
|
def load_data(file_path):
|
|
"""
|
|
加载 TSV 格式数据文件。
|
|
|
|
Args:
|
|
- file_path (str): 文件路径。
|
|
|
|
Returns:
|
|
- features (numpy array): 特征数据。
|
|
- labels (numpy array): 标签数据。
|
|
"""
|
|
data = np.loadtxt(file_path, delimiter="\t")
|
|
features = data[:, :-1]
|
|
labels = data[:, -1].astype(int)
|
|
return features, labels
|
|
|
|
|
|
def classify0(inX, dataSet, labels, k=3):
|
|
"""
|
|
KNN 分类算法。
|
|
|
|
Args:
|
|
- inX (numpy array): 输入待分类的样本。
|
|
- dataSet (numpy array): 训练数据集。
|
|
- labels (list or numpy array): 训练集对应的标签。
|
|
- k (int): KNN 算法参数。
|
|
|
|
Returns:
|
|
- int: 预测的分类标签。
|
|
"""
|
|
dists = np.sqrt(((dataSet - inX) ** 2).sum(axis=1))
|
|
sorted_index = np.argsort(dists)
|
|
class_count = {}
|
|
for i in range(k):
|
|
vote_label = labels[sorted_index[i]]
|
|
class_count[vote_label] = class_count.get(vote_label, 0) + 1
|
|
sorted_class_count = sorted(class_count.items(), key=lambda item: item[1], reverse=True)
|
|
if sorted_class_count:
|
|
return sorted_class_count[0][0]
|
|
else:
|
|
return -1
|
|
|
|
if __name__ == "__main__":
|
|
# 加载数据
|
|
def load_data(file_path):
|
|
data = np.loadtxt(file_path, delimiter="\t")
|
|
features = data[:, :-1]
|
|
labels = data[:, -1].astype(int)
|
|
return features, labels
|
|
|
|
train_file_path = "datingTrainSet2.tsv"
|
|
test_file_path = "datingTestSet2.tsv"
|
|
|
|
train_features, train_labels = load_data(train_file_path)
|
|
test_features, test_labels = load_data(test_file_path)
|
|
|
|
# 归一化特征
|
|
def normalize(features):
|
|
min_vals = features.min(axis=0)
|
|
max_vals = features.max(axis=0)
|
|
ranges = max_vals - min_vals
|
|
normalized = (features - min_vals) / ranges
|
|
normalized[ranges == 0] = 0 # 防止除以零
|
|
return normalized
|
|
|
|
train_features = normalize(train_features)
|
|
test_features = normalize(test_features)
|
|
|
|
correct_count = 0
|
|
for i in range(len(test_features)):
|
|
test_feature = test_features[i].reshape(1, -1)
|
|
predict_label = classify0(test_feature, train_features, train_labels, k=3)
|
|
if predict_label == -1:
|
|
continue
|
|
correct_count += (predict_label == test_labels[i])
|
|
|
|
accuracy = correct_count / len(test_features)
|
|
print(f"Accuracy: {accuracy:.2f}")
|
|
correct_count = 0
|
|
for i in range(len(test_features)):
|
|
test_feature = test_features[i].reshape(1, -1)
|
|
predict_label = classify0(test_feature, train_features, train_labels, k=3)
|
|
if predict_label == -1:
|
|
continue
|
|
correct_count += (predict_label == test_labels[i])
|
|
|
|
accuracy = correct_count / len(test_features)
|
|
print(f"Accuracy: {accuracy:.2f}")
|