generated from LufsX/Challenge-kNN
This commit is contained in:
+5
-5
@@ -1,7 +1,7 @@
|
||||
# function.py
|
||||
import time
|
||||
from numpy.linalg import inv
|
||||
from numpy import sum, argpartition, bincount, argmax, cov, loadtxt
|
||||
from numpy import sum, argpartition, bincount, argmax, cov, loadtxt, array
|
||||
|
||||
"""
|
||||
挑战说明:
|
||||
@@ -40,7 +40,7 @@ name = "向兴宇"
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def classify0(inX, dataSet, labels, k=8, _cache={"VI": None}):
|
||||
def classify0(inX, dataSet, labels, k=[3, 7, 8], _cache={"VI": None}):
|
||||
"""
|
||||
KNN 分类算法。
|
||||
|
||||
@@ -65,13 +65,13 @@ def classify0(inX, dataSet, labels, k=8, _cache={"VI": None}):
|
||||
distances = sum(diff @ _cache["VI"] * diff, axis=1)
|
||||
|
||||
# 对距离排序,获取前 k 个最近的样本索引
|
||||
sortedDistIndices = argpartition(distances, 8)[:8]
|
||||
sortedDistIndices = argpartition(distances, k[-1])[: k[-1]]
|
||||
|
||||
# 统计前 k 个样本的标签
|
||||
classCount = bincount(labels[sortedDistIndices])
|
||||
classCount = array([bincount(labels[sortedDistIndices[:x]]).argmax() for x in k])
|
||||
|
||||
# 返回出现次数最多的标签
|
||||
return argmax(classCount)
|
||||
return argmax(bincount(classCount))
|
||||
|
||||
|
||||
def load_data(file_path):
|
||||
|
||||
Reference in New Issue
Block a user