【问题标题】:Wondering why scipy.spatial.distance.sqeuclidean is twice slower than numpy.sum((y1-y2)**2)想知道为什么 scipy.spatial.distance.sqeuclidean 比 numpy.sum((y1-y2)**2) 慢两倍
【发布时间】:2020-12-14 23:04:51
【问题描述】:

这是我的代码

import numpy as np
import time
from scipy.spatial import distance

y1=np.array([0,0,0,0,1,0,0,0,0,0])
y2=np.array([0. , 0.1, 0. , 0. , 0.7, 0.2, 0. , 0. , 0. , 0. ])

start_time = time.time()
for i in range(1000000):
    distance.sqeuclidean(y1,y2)
print("--- %s seconds ---" % (time.time() - start_time))

---15.212640523910522 秒---

start_time = time.time()
for i in range(1000000):
    np.sum((y1-y2)**2)
print("--- %s seconds ---" % (time.time() - start_time))

---8.381187438964844---秒

我认为 Scipy 已经过优化,所以它应该更快。

我们将不胜感激。

【问题讨论】:

  • scipy 在后台使用 numpy,因此它无法击败普通的 numpy(假设良好的 numpy 编码)。如果您检查 sqeuclidean 的代码,您会看到它添加了一堆检查 + 额外选项,这通常会带来边际成本,但如果这个成本伤害了您并且您不关心额外的 scipy 优惠,那么不要使用它...

标签: python performance numpy scipy matrix-multiplication


【解决方案1】:

这是一个更全面的比较(归功于@Divakar 的benchit 包):

def m1(y1,y2):
  return distance.sqeuclidean(y1,y2)

def m2(y1,y2):
  return np.sum((y1-y2)**2)

in_ = {n:[np.random.rand(n), np.random.rand(n)] for n in [10,100,1000,10000,20000]}

scipy 对更大的数组更有效。对于较小的数组,调用函数的开销很可能超过它的好处。根据source,scipy计算np.dot(y1-y2,y1-y2)

如果您想要更快的解决方案,请直接使用np.dot,而无需额外的行和函数调用:

def m3(y1,y2):
  y_d = y1-y2
  return np.dot(y_d,y_d)

【讨论】:

    猜你喜欢
    • 2015-04-18
    • 2021-04-12
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 2014-10-04
    • 2018-01-16
    • 2015-08-03
    相关资源
    最近更新 更多