有没有办法避免这种循环从而优化代码?
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
注意:
dist_
和TLabels
都是相同形状的numpy数组(t,1)
最佳答案
我不确定您到底想做什么,但您是否知道scipy.ndimage.measurements
用于在带有标签的数组上计算?看起来你想要这样的东西:
cLoss = len(dist_) - sum(TLabels * scipy.ndimage.measurements.sum(TLabels,dist_,dist_) / len(dist_))