NumPy:如何避免这种循环?

far*_*awa 5 python optimization numpy

有没有办法避免这种循环,所以优化代码?

import numpy as np

cLoss = 0
dist_ = np.array([0,1,0,1,1,0,0,1,1,0]) # just an example, longer in reality
TLabels = np.array([-1,1,1,1,1,-1,-1,1,-1,-1]) # just an example, longer in reality
t = float(dist_.size)
for i in range(len(dist_)):
    labels = TLabels[dist_ == dist_[i]]
    cLoss+= 1 - TLabels[i]*(1. * np.sum(labels)/t)
print cLoss
Run Code Online (Sandbox Code Playgroud)

注意: dist_并且TLabels都是具有相同形状的numpy数组(t,1)

Tho*_*hel 2

我不确定你到底想做什么,但是你知道scipy.ndimage.measurements在带有标签的数组上进行计算吗?看起来你想要类似的东西:

cLoss =  len(dist_) - sum(TLabels * scipy.ndimage.measurements.sum(TLabels,dist_,dist_) / len(dist_))
Run Code Online (Sandbox Code Playgroud)