[英]Python: Improve the speed of Euclidean distance calculation in a class
我有一個 class 組件,用於計算 2 個字典中 arrays 中最后一個元素之間的歐幾里得距離。 一個字典包含 blob 的跟蹤軌跡( r
),另一個字典包含 blob 的更新值( b
)。 class的方法基於歐幾里得距離尋找出現或消失的軌跡。 最后,他們將r
字典重新排序為與b
字典的最佳匹配。
我測試了這個colab 筆記本中的功能,它按預期工作,但是當我在我的代碼上實現它時,程序變慢了。
謝謝你。
from scipy.spatial import distance as dist
class finder:
def disappeared(self,r,b):
values = {}
indexes = {}
diss = {}
new_results = {}
new_positions = {}
le = len(r) - len(b)
for i in r:
xr = r[i]["x"][-1]
yr = r[i]["y"][-1]
for k in b:
xb = b[k]["x"][-1]
yb = b[k]["y"][-1]
D = dist.cdist([(xb,yb)],[(xr,yr)])
values[str(i) +"/" + str(k)] = D
indexes[str(i) +"/" + str(k)] = (i,k)
if le > 0:
le -= 1
maxval = max(values,key=values.get)
r_ind = indexes[maxval][0]
b_ind = indexes[maxval][1]
print("Found Disappeared", maxval)
diss[r_ind] = r[r_ind]
else:
minval = min(values,key=values.get)
r_ind = indexes[minval][0]
b_ind = indexes[minval][1]
new_positions[b_ind] = r[r_ind]
del values[minval]
for m,n in enumerate(new_positions):
new_results[m] = new_positions[n]
return(new_results,diss)
def appeared(self,r,b):
values = {}
indexes = {}
appr = {}
new_results = {}
new_positions = {}
le = len(b) - len(r)
for i in b:
xb = b[i]["x"][-1]
yb = b[i]["y"][-1]
for k in r:
xr = r[k]["x"][-1]
yr = r[k]["y"][-1]
D = dist.cdist([(xr,yr)],[(xb,yb)])
values[str(k) +"/" + str(i)] = D
indexes[str(k) +"/" + str(i)] = (k,i)
if le > 0:
le -= 1
maxval = max(values,key=values.get)
r_ind = indexes[maxval][0]
b_ind = indexes[maxval][1]
print("Found Appeared", maxval)
appr[b_ind] = b[b_ind]
new_positions[r_ind] = b[b_ind]
else:
minval = min(values,key=values.get)
r_ind = indexes[minval][0]
b_ind = indexes[minval][1]
new_positions[b_ind] = r[r_ind]
del values[minval]
for m,n in enumerate(new_positions):
new_results[m] = new_positions[n]
return(new_results)
大部分時間可能都花在訪問字典和格式化字符串上。
這里有一些你可以做的事情來優化disappeared()
:
只訪問b
的值一次:
# at start of function ...
lastB = [ (k,v["x"][-1],v["y"][-1]) for k,v in b.items() ]
...
for k,xb,yb in lastB: # replaces for k in b: and the assignments of xb,yb
...
訪問r
時獲取值和鍵:
for i,v in r.items():
xr = v["x"][-1]
yr = v["y"][-1]
使用元組而不是字符串作為values
,您根本不需要indexes
:
# index it with a tuple
values[(k,i)] = D
...
# replace the whole maxval logic.
r_ind,b_ind,_ = max(values.items(),key=lambda kv:kv[1])
...
# replace the whole minval logic.
r_ind,b_ind,_ = min(values.items(),key=lambda kv:kv[1])
...
del values[r_ind,b_ind]
無需重新訪問每個鍵即可生成新結果:
new_result = dict(enumerate(new_positions.values()))
可以對appeared()
進行相同的改進,因為它幾乎是相同的。
這段代碼真的有效嗎? 這些行看起來完全錯誤:
for i in r:
xr = r[i]["x"][-1]
yr = r[i]["y"][-1]
i
是r
的元素。 您不會將其用作r
的索引。 當然應該是:
for i in r:
xr = i["x"][-1]
yr = i["y"][-1]
對於for k in b
循環也是如此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.