【问题标题】:Find integer nearest-neighbour in a dict在字典中查找整数最近邻居
【发布时间】:2015-05-19 14:35:44
【问题描述】:

我有一个 dict 接受整数键:

a = {}
a[1] = 100
a[55] = 101
a[127] = 102

我希望在询问时能够带最近的邻居:

a[20] # should return a[1] = 100
a[58] # should return a[55] = 101
a[167] # should return a[127] = 102

有没有一种 Python 的方法可以做到这一点?(我想这可以通过循环所有 dict 来完成,但这可能不是最优雅的解决方案?)


双索引的相同问题(整数也是):

 b[90, 1] = 100, b[90, 55] = 101, b[90, 127] = 102
 b[70, 1] = 40, b[70, 45] = 41, b[70, 107] = 42

我希望能够得到b[73, 40] = b[70, 45] = 41,即2D 平面中的最近邻。

【问题讨论】:

  • 距离平局你想要什么?
  • 你的意思是你想要两个?或者两者都会做?请注意,对于 2-d 情况,可以有 4-way tie
  • @wim 不,如果允许使用真正的密钥,则可以有无限数量的联系。
  • @wim 不是无限的,但圆上的所有离散点都是平局。
  • 如果你想要高效,numpy/scipy 可能是最好的方法,例如stackoverflow.com/questions/10818546/…

标签: python algorithm dictionary nearest-neighbor


【解决方案1】:

类似的东西:

class CustomDict(dict):
    def __getitem__(self, key):
        try:
            return dict.__getitem__(self, key)
        except KeyError:
            closest_key = min(self.keys(), key=lambda x: abs(x - key))
            return dict.__getitem__(self, closest_key)

或者这个:

class CustomDict(dict):
    def __getitem__(self, key):
        if key in self:
            return dict.__getitem__(self, key)
        else:
            closest_key = min(self.keys(), key=lambda x: abs(x - key))
            return dict.__getitem__(self, closest_key)

两者都给出了这个结果:

a = CustomDict()
a[1] = 100
a[55] = 101
a[127] = 102

print a[20] # prints 100
print a[58] # prints 101
print a[167] # prints 102

对于双索引版本:

class CustomDoubleDict(dict):
    def __getitem__(self, key):
        if key in self:
            return dict.__getitem__(self, key)
        else:
            closest_key = min(self.keys(), key=lambda c: (c[0] - key[0]) ** 2 + (c[1] - key[1]) ** 2)
            return dict.__getitem__(self, closest_key)


b = CustomDoubleDict()
b[90, 1] = 100
b[90, 55] = 101
b[90, 127] = 102
b[70, 1] = 40
b[70, 45] = 41
b[70, 107] = 42

print b[73, 40]  # prints 41
print b[70, 45]  # prints 41

【讨论】:

  • 感谢您的解决方案。投票者能否解释为什么这不是一个好的解决方案? (我还不明白为什么它会好或坏......)
  • 是的,如果反对者能够详细解释为什么他们认为这可能不正确,那就太好了。只是想在这里学习。 :)
  • 我投了反对票,因为每次没有完全匹配时,这都会遍历所有键。请参阅我对 O(log n) 解决方案的回答。
  • 很难选择一个被接受的答案。这是为了简单,并且是问题的快速解决方案(但不是最佳的,因为循环遍历所有键)。 jedwards 的 N 维泛化方法。以及wim对我的问题的应用程序的回答。
  • @Basj 这表明这是一个好问题,因为它吸引了许多不同的答案和讨论,干得好。
【解决方案2】:

一维情况的未测试 O(log n) 示例:

import collections
import bisect


class ProximityDict(collections.MutableMapping):
    def __init__(self, *args, **kwargs):
        self.store = dict()
        self.ordkeys = []
        self.update(dict(*args, **kwargs))

    def __getitem__(self, key):
        try: return self.store[key]
        except KeyError:
            cand = bisect.bisect_left(self.ordkeys, key)
            if cand == 0: return self.store[self.ordkeys[0]]

            return self.store[
                min(self.ordkeys[cand], self.ordkeys[cand-1],
                    key=lambda k: abs(k - key))
            ]

    def __setitem__(self, key, value):
        if not key in self.store: bisect.insort_left(self.ordkeys, key)
        self.store[key] = value

    def __delitem__(self, key):
        del self.store[key]
        del self.keys[bisect.bisect_left(self.ordkeys, key)]

    def __iter__(self):
        return iter(self.store)

    def __len__(self):
        return len(self.store)

二维情况更烦人(您需要将键存储在四叉树中),但可以采用类似的方式。

我没有编码删除也有“接近”行为,但你也可以这样做。

【讨论】:

  • 您的 ProximityDict 不是 dict 对象,它依赖于有序键。问题是Is there a pythonic way of doing this? 不是 Is there a fast way to do this?。 Pythonic 简单易懂,快在后。
  • 它仍然是 pythonic 代码,并且问题清楚地表明他们知道明显的 O(n) 解决方案,因此无需提供 O(n)回答海事组织。 +1
  • @wim 提问者要求提供一种 pythonic 的方式,imo 这意味着一种利用各种语法机会来生成易于阅读和可维护的代码的方式。他的 for 循环注释不是关于性能,而是“优雅”(他的话,不是我的话)。话虽如此,orlp 仍然得到了我的支持,尽管没有处理二维(也有人问过)。
  • @TimothéeJeannin 我的ProximityDict 继承自collections.MutableMapping,据我所知,这是解决此问题的最佳方式。你是什​​么意思我依赖有序键?我自己明确地跟踪有序键。
【解决方案3】:

选项 1:

维护一个单独且有序的键列表(或使用OrderedDict)。使用二分搜索找到最近的键。这应该是 O(log n)。

方案二:(如果数据不是很大很稀疏)

由于您提到字典是静态的,因此请通过字典以填充所有缺失值一次。保持最大和最小键,并覆盖__getitem__,以便高于最大值或低于最小值的键返回正确的值。这应该是 O(1)。

选项 3:

只要每次都在键上使用循环,它将是 O(n)。在您的应用程序中尝试一下,您可能会发现这个简单的解决方案无论如何都非常快速且足够。

【讨论】:

  • 我在字典中有大约 2000 个元素,但它们可能会在 i 和 [1, 127] 中使用 a[i,j] 和 j 进行搜索。所以选项 2 意味着用
  • 是的,没问题。不过,使用 numpy ndarray 比使用 dict 更好。由于您的数据是数字的,因此您肯定会通过这种方式获得更好的性能和内存占用。
  • 其实我简化了一点,但是值不是数字,它们是 Sound 对象。我的目的是用Samples[Midinote, Velocity] = Sound('mysound.wav') 编写一个采样器。有时,您只有几个 .wav 文件,并且您希望能够针对任何 MIDI 音符值和任何力度(在 MIDI 键盘上)进行演奏。这就是为什么我需要 Samples[60, 43] 来使用 MiddleC-60-Velocity50.wav 如果没有适用于velocity=43 的样本。
  • 好的,那么带有元组键的 dict 就可以了(或 object 的 ndarray)。请务必确保重复值不是副本,而是对同一 Sound 对象的引用。
  • 对于限制在 1, 127 中的搜索键,简单(选项 3)解决方案可能非常有用,甚至可能是最快的!
【解决方案4】:

如何使用min 和适当的按键功能:

>>> b ={(90, 55): 101, (90, 127): 102, (90, 1): 100}
>>> def nearest(x,y):
...   m=min(((i,j) for i,j in b ),key= lambda v:abs(v[0]-x)+abs(v[1]-y))
...   return b[m]
... 
>>> nearest(40,100)
102
>>> nearest(90,100)
102
>>> b
{(90, 55): 101, (90, 127): 102, (90, 1): 100}
>>> nearest(90,10)
100

前面的答案是我建议的pythonic答案,但如果您寻找一种快速的方法,您可以使用scipy.spatial.KDTree:

class scipy.spatial.KDTree(data, leafsize=10)

kd-tree 用于快速最近邻查找

该类提供了一组 k 维点的索引,可用于快速查找任何点的最近邻居。

也可以看看http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.html#scipy-spatial-ckdtree

和http://docs.scipy.org/doc/scipy/reference/spatial.distance.html#module-scipy.spatial.distance

【讨论】:

  • 这会遍历每个索引的每个键。
  • @orlp 我只是想建议一个 pythoinc 答案!
  • KDTree 方法看起来很有前途。
  • 感谢这个 pythonic 解决方案,以及另一个针对速度进行了优化的解决方案。
  • @Kasra,您打算实施 KDTree 方法吗?如果没有,我将修改我的课程以使用 KDTree(如果我有时间,也许有一天会对其进行基准测试)
【解决方案5】:

更新:在此答案中对两种方法进行基准测试后,second 方法明显更好,以至于它应该几乎绝对首选。


以下方法以相同的方式处理 n-维度:

class NearestDict(dict):
    def __init__(self, ndims):
        super(NearestDict, self).__init__()
        self.ndims = ndims

    # Enforce dimensionality
    def __setitem__(self, key, val):
        if not isinstance(key, tuple): key = (key,)
        if len(key) != self.ndims: raise KeyError("key must be %d dimensions" % self.ndims)
        super(NearestDict, self).__setitem__(key, val)

    @staticmethod
    def __dist(ka, kb):
        assert len(ka) == len(kb)
        return sum((ea-eb)**2 for (ea, eb) in zip(ka, kb))

    # Helper method and might be of use
    def nearest_key(self, key):
        if not isinstance(key, tuple): key = (key,)
        nk = min((k for k in self), key=lambda k: NearestDict.__dist(key, k))
        return nk

    def __missing__(self, key):
        if not isinstance(key, tuple): key = (key,)
        if len(key) != self.ndims: raise KeyError("key must be %d dimensions" % self.ndims)
        return self[self.nearest_key(key)]

演示:

a = NearestDict(1)
a[1] = 100
a[55] = 101
a[127] = 102
print a[20]    # 100
print a[58]    # 100
print a[167]   # 102
print a.nearest_key(20)     # (1,)
print a.nearest_key(58)     # (55,)
print a.nearest_key(127)    # (127,)

b = NearestDict(2)
b[90, 1]   = 100
b[90, 55]  = 101
b[90, 127] = 102
b[70, 1]   = 40
b[70, 45]  = 41
b[70, 107] = 42
print b[73, 40] # 41
print b.nearest_key((73,40)) # (70, 45)

请注意,如果键存在,则查找不会比标准字典查找慢。如果键不存在,则计算每个现有键之间的距离。没有任何东西被缓存,虽然我想你可以解决这个问题。

编辑:

根据Kasra's answer 建议的方法,以下方法使用scipy's cKDTree 实现与上述相同的类:

请注意,还有一个额外的可选参数regenOnAdd,它允许您推迟(重新)构建 KDTree,直到您完成(大部分)插入操作:

from scipy.spatial import cKDTree

class KDDict(dict):
    def __init__(self, ndims, regenOnAdd=False):
        super(KDDict, self).__init__()
        self.ndims = ndims
        self.regenOnAdd = regenOnAdd
        self.__keys = []
        self.__tree = None
        self.__stale = False

    # Enforce dimensionality
    def __setitem__(self, key, val):
        if not isinstance(key, tuple): key = (key,)
        if len(key) != self.ndims: raise KeyError("key must be %d dimensions" % self.ndims)
        self.__keys.append(key)
        self.__stale = True
        if self.regenOnAdd: self.regenTree()
        super(KDDict, self).__setitem__(key, val)

    def regenTree(self):
        self.__tree = cKDTree(self.__keys)
        self.__stale = False

    # Helper method and might be of use
    def nearest_key(self, key):
        if not isinstance(key, tuple): key = (key,)
        if self.__stale: self.regenTree()
        _, idx = self.__tree.query(key, 1)
        return self.__keys[idx]

    def __missing__(self, key):
        if not isinstance(key, tuple): key = (key,)
        if len(key) != self.ndims: raise KeyError("key must be %d dimensions" % self.ndims)
        return self[self.nearest_key(key)]

输出与上述方法相同。

基准测试结果

为了了解这三种方法(NearestDict、KDDict(True)(插入时再生)和KDDict(False)(延迟再生))的性能,我简要地对它们进行了基准测试。

我进行了 3 次不同的测试。在测试中保持不变的参数是:

  • 测试迭代次数:每个测试我做了 5 次,用了最少的时间。 (注意 timeit.repeat 默认为 3)。
  • 点边界:我生成了 0 范围内的整数关键点
  • 查找次数:我分别对插入和查找进行计时。以下三个测试都使用了 10,000 次查找。

第一个测试使用了 4 个维度的键和 1000 次插入。

{'NDIMS':4,'NITER':5,'NELEMS':1000,'NFINDS':10000,'DIM_LB':0,'DIM_UB':1000,'SCORE_MUL':100} 插入::NearestDict 0.125 插入::KDDict(regen) 35.957 插入::KDDict(延迟)0.174 搜索::NearestDict 2636.965 搜索::KDDict(regen) 49.965 搜索::KDDict(延迟) 51.880

第二个测试使用了 4 个维度和 100 次插入的键。我想改变插入的数量,看看这两种方法在字典密度变化时的表现如何。

{'NDIMS':4,'NITER':5,'NELEMS':100,'NFINDS':10000,'DIM_LB':0,'DIM_UB':1000,'SCORE_MUL':100} 插入::NearestDict 0.013 插入::KDDict(regen) 0.629 插入::KDDict(延迟) 0.018 搜索::NearestDict 247.920 搜索::KDDict(regen) 44.523 搜索::KDDict(defer) 44.718

第三个测试使用了 100 次插入(与第二个测试一样),但使用了 12 个维度。我想看看随着关键维度的增加,这些方法的表现如何。

{'NDIMS':12,'NITER':5,'NELEMS':100,'NFINDS':10000,'DIM_LB':0,'DIM_UB':1000,'SCORE_MUL':100} 插入::NearestDict 0.013 插入::KDDict(regen) 0.722 插入::KDDict(延迟) 0.017 搜索::NearestDict 405.092 搜索::KDDict(regen) 49.046 搜索::KDDict(延迟) 50.601

讨论

KDDict 连续重新生成 (KDDict(True)) 会稍微快一点(查找时)或相当慢一点(插入时)。正因为如此,我将把它排除在讨论之外,专注于NearestDict 和KDDict(False),现在简称为KDDict

结果出人意料地支持具有延迟再生的 KDDict。

对于插入,在所有情况下,KDDict 的表现都比 NearestDict 稍差。这是意料之中的,因为额外的列表追加操作。

对于搜索,在所有情况下,KDDict 的表现明显优于 NearestDict。

随着字典稀疏度的降低/密度的增加,NearestDict 的性能下降幅度比 KDDict 大得多。从 100 个键到 1000 个键时,NearestDict 搜索时间增加了 9.64 倍,而 KDDict 搜索时间仅增加了 0.16 倍。

随着字典维数的增加,NearestDict 的性能下降幅度大于KDDict。从 4 维到 12 维时,NearestDict 搜索时间增加了 0.64 倍,而 KDDict 搜索时间仅增加了 0.13 倍。

鉴于此,以及两个类的相对复杂性,如果您可以访问 scipy 工具包,强烈建议使用KDDict 方法。

【讨论】:

  • 这会遍历每个非精确索引的所有可能键。
  • @orlp 我刚刚编辑了它。我同意。可以实现某种过滤(这些键比其他候选键更差),或者缓存,或者更合适的散列方案可以为大型字典改善这一点。
  • 喜欢 N 维的可能性!
  • 感谢所有关于这个问题的研究!
【解决方案6】:

这里有一个主要依赖于 map/filter 操作的 pythonic 解决方案

class NeirestSearchDictionnary1D(dict):
    """ An extended dictionnary that returns the value that is the nearest to 
    the requested key. As it's key distance is defined for simple number 
    values, trying to add other keys will throw error. """
    def __init__(self):
        """ Constructor of the dictionnary.
        It only allow to initialze empty dict """
        dict.__init__(self)

    def keyDistance(self, key1, key2):
        """ returns a distance between 2 dic keys """
        return abs(key1-key2)

    def __setitem__(self, key, value):
        """ override  the addition of a couple in the dict."""
        #type checking
        if not (isinstance(key, int) or isinstance(key, float)):
            raise TypeError("The key of such a "+ type(self) + "must be a simple numerical value")
        else:
            dict.__setitem__(self, key, value)

    def __getitem__(self, key):
        """ Override the getting item operation """
        #compute the minial distance
        minimalDistance = min(map(lambda x : self.keyDistance(key, x), self.keys()))
        #get the list of key that minimize the distance
        resultSetKeys = filter(lambda x : self.keyDistance(key, x) <= minimalDistance, self.keys())
        #return the values binded to the keys minimizing the distances.
        return list(map(lambda x : dict.__getitem__(self, x), resultSetKeys))

if __name__ == "__main__":

    dic = NeirestSearchDictionnary1D()
    dic[1] = 100
    dic[55] = 101
    dic[57] = 102
    dic[127] = 103
    print("the entire dict :", dic)
    print("dic of '20'", dic[20])
    print("dic of '56'", dic[56])

显然,您可以轻松地将其扩展到 2D 维度。

【讨论】:

    猜你喜欢
    • 2020-11-05
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    相关资源
    最近更新 更多