generated from LufsX/Challenge-kNN
This commit is contained in:
+10
-10
@@ -49,25 +49,25 @@ def classify0(inX, dataSet, labels, k=3):
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- dataSet (numpy array): 训练数据集。
|
||||
- labels (list or numpy array): 训练集对应的标签。
|
||||
- k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。
|
||||
- k (int): kNN 算法参数。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
|
||||
|
||||
# 计算待分类样本与数据集中每个样本的距离
|
||||
distances = np.sqrt(np.sum((dataSet - inX) ** 2, axis=1))
|
||||
# 计算输入样本与数据集中每个样本的欧氏距离
|
||||
diffMat = np.tile(inX, (dataSet.shape[0], 1)) - dataSet
|
||||
sqDiffMat = diffMat ** 2
|
||||
sqDistances = sqDiffMat.sum(axis=1)
|
||||
distances = sqDistances ** 0.5
|
||||
|
||||
# 获取距离最近的k个样本的索引
|
||||
sortedDistIndices = np.argsort(distances)
|
||||
# 对距离进行排序,选择距离最小的 k 个样本
|
||||
sortedDistIndices = distances.argsort()
|
||||
classCount = {}
|
||||
|
||||
# 遍历距离最近的k个样本
|
||||
# 遍历距离最小的 k 个样本,统计每个类别的出现次数
|
||||
for i in range(k):
|
||||
voteIlabel = labels[sortedDistIndices[i]]
|
||||
# 统计每个类别的出现次数
|
||||
classCount[voteIlabel] = classCount.getvoteIlabel, classCount.getvoteIlabel + 1)
|
||||
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
|
||||
|
||||
# 选择出现次数最多的类别作为预测标签
|
||||
sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)
|
||||
|
||||
Reference in New Issue
Block a user