generated from LufsX/Challenge-kNN
This commit is contained in:
+20
-8
@@ -25,8 +25,8 @@ import numpy as np
|
|||||||
"""
|
"""
|
||||||
请在这里填写学号和姓名,不填写即成绩无效。
|
请在这里填写学号和姓名,不填写即成绩无效。
|
||||||
"""
|
"""
|
||||||
id = "202210423xxx"
|
id = "202210423228"
|
||||||
name = "test_name"
|
name = "黎世浩"
|
||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
@@ -41,7 +41,7 @@ name = "test_name"
|
|||||||
|
|
||||||
|
|
||||||
# 这里写自己的代码实现
|
# 这里写自己的代码实现
|
||||||
def classify0(inX, dataSet, labels, k=0):
|
def classify0(inX, dataSet, labels, k=3):
|
||||||
"""
|
"""
|
||||||
KNN 分类算法。
|
KNN 分类算法。
|
||||||
|
|
||||||
@@ -56,6 +56,23 @@ def classify0(inX, dataSet, labels, k=0):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
# 计算待分类样本与数据集中每个样本的距离
|
||||||
|
distances = np.sqrt(np.sum((dataSet - inX) ** 2, axis=1))
|
||||||
|
|
||||||
|
# 获取距离最近的k个样本的索引
|
||||||
|
sortedDistIndices = np.argsort(distances)
|
||||||
|
classCount = {}
|
||||||
|
|
||||||
|
# 遍历距离最近的k个样本
|
||||||
|
for i in range(k):
|
||||||
|
voteIlabel = labels[sortedDistIndices[i]]
|
||||||
|
# 统计每个类别的出现次数
|
||||||
|
classCount[voteIlabel] = classCount.getvoteIlabel, classCount.getvoteIlabel + 1)
|
||||||
|
|
||||||
|
# 选择出现次数最多的类别作为预测标签
|
||||||
|
sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)
|
||||||
|
return sortedClassCount[0][0]
|
||||||
|
|
||||||
def load_data(file_path):
|
def load_data(file_path):
|
||||||
"""
|
"""
|
||||||
加载 TSV 格式数据文件。
|
加载 TSV 格式数据文件。
|
||||||
@@ -65,12 +82,7 @@ def load_data(file_path):
|
|||||||
labels = data[:, -1].astype(int)
|
labels = data[:, -1].astype(int)
|
||||||
return features, labels
|
return features, labels
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# 以下代码可用于测试,可自行随意修改
|
|
||||||
|
|
||||||
train_file = "datingTrainSet2.tsv"
|
train_file = "datingTrainSet2.tsv"
|
||||||
|
|
||||||
train_data, train_labels = load_data(train_file)
|
train_data, train_labels = load_data(train_file)
|
||||||
|
|
||||||
print(classify0([65915, 3.868359, 0.128078], train_data, train_labels))
|
print(classify0([65915, 3.868359, 0.128078], train_data, train_labels))
|
||||||
|
|||||||
Reference in New Issue
Block a user