【问题标题】:Python: faster function for kernel evaluationPython:更快的内核评估函数
【发布时间】:2014-09-14 12:02:01
【问题描述】:

我有一个类似下面的函数来评估实例 x 和 y 之间的内核:

def my_hik(x, y):
     """Histogram-Intersection-Kernel """
     summe = 0
     for i in xrange(len(x)):
         summe += min(x[i],y[i])
     return summe
     #return np.sum(np.min(np.array([[x],[y]]),0))

metrics.pairwise.pairwise_kernels(instances, metric=my_hik, n_jobs=-1)

我用 sklearns pairwise_kernels-function 来调用它。但是我的数据(大约 3000 个具有一百个属性的实例)似乎太大了,一个矩阵的计算需要几分钟(因为该函数被称为 9*10^6 次)。有没有办法让函数运行得更快?

【问题讨论】:

    标签: python numpy scipy scikit-learn


    【解决方案1】:
    def fast_hik(x, y):
        return np.minimum(x, y).sum()
    

    时间安排:

    >>> x = np.random.randn(100)
    >>> y = np.random.randn(100)
    >>> %timeit my_hik(x, y)
    10000 loops, best of 3: 50.3 µs per loop
    >>> %timeit fast_hik(x, y)
    100000 loops, best of 3: 5.55 µs per loop
    

    为更长的向量获得更大的加速:

    >>> x = np.random.randn(1000)
    >>> y = np.random.randn(1000)
    >>> %timeit my_hik(x, y)
    1000 loops, best of 3: 498 µs per loop
    >>> %timeit fast_hik(x, y)
    100000 loops, best of 3: 7.92 µs per loop
    

    【讨论】:

    猜你喜欢
    • 2018-05-02
    • 2016-04-20
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 2019-06-03
    • 2013-09-03
    • 1970-01-01
    相关资源
    最近更新 更多