NameError Appears

Asked 2 months ago, Updated 2 months ago, 3 views

I would like to execute the following code, but an error appears.
I would appreciate it if you could tell me how to solve it.
The original code can be found in data-science-from-scratch/nearest_neighbors.py.
I'm just starting to learn Python, and I'd like to show you the results of k = 1, 3, 5, 7 near k.

import path

def knn_classify(k, labeled_points, new_point):
    """each labeled point should be a pair (point, label)"""
    # order the labeled points from nearest to farest
    by_distance=sorted(labeled_points,
                         key=lambda point_label: distance(point_label, new_point))
    # find the labels for the k closeest
    k_nearest_labels = [label for_, label in by_distance[:k]]
    return majority_vote(k_nearest_labels)

cities=[(-86.75, 33.56666666667, 'Python'), (-88.25, 30.683333333333333, 'Python'), (-112.01666666667, 33.4333333333333, 'Java')]
cities=[[longitude, latitude], language) for longitude, latitude, language incities ]

forkin [1,3,5,7]:
    num_correct = 0    
    For city incities
        location, actual_language = city
        other_cities = [other_city for other_city incities]
                        if other_city!=city]
        predicted_language = knn_classify(k, other_cities, location) 
        if predicated_language==actual_language:
            num_correct+=1
    print(k, "neighbor[s]", num_correct, "correct out of", len(cities) )

When executing the above code, an error appears as follows:

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 predicated_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,
---->8key=lambda point_label: distance(point_label, new_point))
      9 
     10# find the labels for the k closeest

<ipython-input-32-1bab7195f6b1>in<lambda>(point_label)
      6# order the labeled points from nearest to farthest
      7 by_distance=sorted(labeled_points,
---->8key=lambda point_label: distance(point_label, new_point))
      9 
     10# find the labels for the k closeest

NameError: name 'distance' is not defined

python

2022-09-30 13:50

1 Answers

I'm not familiar with python, but...

The distance method is

 from linear_algebra import distance

As declared here, linear_algebra.py is required.
(So, if you try to load linear_algebra.py, you'll need something else for the potato-zuru style.)

Also, the majority_vote method seems to be missing.
This is included in the original code nearest_neighbors.py.


2022-09-30 13:50

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.