2

## 使用python寫出knn算法

``````import math
from collections import OrderedDict

print('各item的top 3 neighbor:')
toDataFrame={}
for y in range(len(vectors)):
distances = []
distances_dict = {}
three_item = []
##############使用 Euclidean distance
for x in range(len(vectors)):
if x==y:
continue
else:
distance = vectors[y]-vectors[x]
distances.append(math.sqrt( distance[0]*distance[0] + distance[1]*distance[1] ))

##################

# key為 index
distances_dict = dict(zip(range(len(distances)), distances))

#取出前 3 近的
d_sorted_by_value = OrderedDict(sorted(distances_dict.items(), key=lambda x: x[1]))
d_sorted_by_value_three = [i for i in d_sorted_by_value.keys()][:3]

#印出 前三 接近的
for three in range(3):
if d_sorted_by_value_three[three] >= y:
three_item.append(w2v_df.word[d_sorted_by_value_three[three]+1])
else:
three_item.append(w2v_df.word[d_sorted_by_value_three[three]])
toDataFrame[w2v_df.word[y]] = three_item

for x, y in toDataFrame.items():
print(x, y)
``````
player iT邦大師 1 級 ‧ 2019-11-06 15:42:55 檢舉

https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm

sqr( abs((a-b).x)^2 + abs((a-b).y)^2 ) ?
p39212053 iT邦新手 5 級 ‧ 2019-11-07 13:10:47 檢舉

### 1 個回答

2
Darwin Watterson
iT邦新手 1 級 ‧ 2019-11-06 16:07:01

``````bag    -2.091543    0.136671    0
book   -0.757159   -1.415790    0
crayon -1.894580    6.104396    0
...
``````

dragonH iT邦大師 1 級 ‧ 2019-11-06 16:24:11 檢舉

dragonH iT邦大師 1 級 ‧ 2019-11-06 16:39:29 檢舉

p39212053 iT邦新手 5 級 ‧ 2019-11-07 13:15:42 檢舉

p.s. 以前連公民課也拿來考試