generated from LufsX/Challenge-kNN
This commit is contained in:
+22
@@ -38,6 +38,28 @@ name = "吴俊煯"
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def euclidean_distance(instance1, instance2, length):
|
||||
"""
|
||||
计算两个实例之间的欧几里得距离
|
||||
"""
|
||||
distance = 0
|
||||
for x in range(length):
|
||||
distance += (instance1[x] - instance2[x]) ** 2
|
||||
return np.sqrt(distance)
|
||||
|
||||
def get_neighbors(train, test_row, k=4):
|
||||
"""
|
||||
获取测试实例的 k 个最近邻
|
||||
"""
|
||||
distances = []
|
||||
length = len(test_row) - 1 # 假设最后一列是标签
|
||||
for index in range(len(train)):
|
||||
dist = euclidean_distance(test_row, train[index], length)
|
||||
distances.append((train[index], dist))
|
||||
distances.sort(key=lambda tup: tup[1])
|
||||
neighbors = distances[:k]
|
||||
return neighbors
|
||||
|
||||
def classify0(inX, dataSet, labels,k=4):
|
||||
"""
|
||||
KNN 分类算法。
|
||||
|
||||
Reference in New Issue
Block a user