简体   繁体   English

如何仅使用numpy和without循环重写给定的最近邻居函数?

[英]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. 我有一个使用python的最近邻算法的作业。 I have a given code in pure python that contains a loop. 我在纯python中有一个包含循环的给定代码。 I have to rewrite and configure the function only using numpy and without loops. 我必须使用numpy和without循环重写和配置该函数。

I have an unlabeled point u, that needs to be classified, a distance function and a training set (X, Y). 我有一个未标记的点u,需要分类,距离函数和训练集(X,Y)。 The function that I have to write should return the label of the point that has the smallest distance to u. 我必须编写的函数应该返回与u具有最小距离的点的标签。

Here is the function written in pure python that I have to rewrite: 这是用纯python编写的函数,我必须重写:

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. 在Python中重写循环的过程称为矢量化。 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? 我建议你看看这个问题: 向量化 循环NumPy 在numpy / scipy中向量化循环吗? vectorizing a for loop in python 矢量化python中的for循环

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Python使用最近邻算法对数据进行分类? - How can I classify data with the nearest-neighbor algorithm using Python? 在 3D 空间中以最小最近邻距离和最大密度随机采样给定点 - Sample given points stochastically in a 3D space with minimum nearest-neighbor distance and maximum density 如何在 numpy 中找到最近的邻居? - How to find the nearest neighbor in numpy? 如何在不存储重复值的情况下使用最近邻居对numpy数组进行升采样? - How to upsample numpy array with nearest neighbor without storing repeated values? 如何在数据立方体中搜索具有除 NaN 以外的值的最近邻点? - How to search for a nearest-neighbor point with a value else than NaN in a datacube? 在该应用中使用的最佳最近邻居算法是什么? - What would be the best nearest-neighbor algorithm to use for this application? 如何在给定距离内优化Postgis中的最近邻居查询? - how to optimize nearest neighbor query in postgis within given distance? 使用RegularGridInterpolator时如何仅在边界外使用最近邻插值 - How can I use nearest neighbor interpolation only outside of bounds when using RegularGridInterpolator 以最小最近邻距离在 3D 空间中生成随机点 - Generate random points in 3D space with minimum nearest-neighbor distance 在不使用 resize() 的情况下调整 python 中的图像大小 - 最近邻 - Resize image in python without using resize() - nearest neighbor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM