以下のコードを実行したいのですがエラーが出てしまいます。
解決方法を教えていただけると幸いです。
元のコードはdata-science-from-scratch/nearest_neighbors.pyにあります。
現在Pythonを学び始めたばかりなのですが、したいこととしてはk近傍方でk=1,3,5,7でどのような結果になるのか示したいと認識しています。
import math
def knn_classify(k, labeled_points, new_point):
"""each labeled point should be a pair (point, label)"""
# order the labeled points from nearest to farthest
by_distance = sorted(labeled_points,
key=lambda point_label: distance(point_label, new_point))
# find the labels for the k closest
k_nearest_labels = [label for _, label in by_distance[:k]]
return majority_vote(k_nearest_labels)
cities = [(-86.75,33.5666666666667,'Python'),(-88.25,30.6833333333333,'Python'),(-112.016666666667,33.4333333333333,'Java')]
cities = [([longitude, latitude], language) for longitude, latitude, language in cities]
for k in [1,3,5,7]:
num_correct = 0
for city in cities:
location,actual_language = city
other_cities = [other_city for other_city in cities
if other_city != city]
predicted_language = knn_classify(k, other_cities, location)
if predicted_language == actual_language:
num_correct += 1
print (k, "neighbor[s]", num_correct, "correct out of", len(cities) )
上記のコードを実行した時に以下のようにエラーが表示されてしまいます。
NameError Traceback (most recent call last)
<ipython-input-32-1bab7195f6b1> in <module>()
26 if other_city != city]
27
---> 28 predicted_language = knn_classify(k, other_cities, location)
29
30 if predicted_language == actual_language:
<ipython-input-32-1bab7195f6b1> in knn_classify(k, labeled_points, new_point)
6 # order the labeled points from nearest to farthest
7 by_distance = sorted(labeled_points,
----> 8 key=lambda point_label: distance(point_label, new_point))
9
10 # find the labels for the k closest
<ipython-input-32-1bab7195f6b1> in <lambda>(point_label)
6 # order the labeled points from nearest to farthest
7 by_distance = sorted(labeled_points,
----> 8 key=lambda point_label: distance(point_label, new_point))
9
10 # find the labels for the k closest
NameError: name 'distance' is not defined