简体   繁体   中英

How to rewrite a given nearest-neighbor function with only using numpy and without loops?

I have a homework on nearest neighbor algorithm using python. I have a given code in pure python that contains a loop. I have to rewrite and configure the function only using numpy and without loops.

I have an unlabeled point u, that needs to be classified, a distance function and a training set (X, Y). The function that I have to write should return the label of the point that has the smallest distance to u.

Here is the function written in pure python that I have to rewrite:

def pynearest(u, X, Y, distance=pydistance):
    xbest = None
    ybest = None
    dbest = float('inf')

    for x, y in zip(X, Y):
        d = distance(u, x)
        if d < dbest:
            ybest = y
            xbest = x
            dbest = d

    return ybest

The process of rewriting for loops in Python is called vectorization. To solve this, you generally have to use indexes to retrieve the values in your matrix. I would suggest you to look at this questions: Vectorizing for loops NumPy vectorizing a for loop in numpy/scipy? vectorizing a for loop in python

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM