你的代码很少出错。在my vector a should be of dimension 10, but it isn't!
这是因为你不会在列表中只添加10个元素。看看你的逻辑。在for t in range(0,10,1):
for j in range(0, len(c)):
if c[j]>t/10:
a.append(sum(c[j]>t))
对于每个阈值,t,每次迭代一个c中的所有12个项目,并向列表中追加一些内容。总的来说,你有120个项目。你应该做的是(在伪代码中):
^{pr2}$
numpy.where()提供满足条件的数组中的索引,因此您只需计算每次获得的索引数。我们将得到完整的解决方案是片刻。在
另一个潜在的错误是t/10,在python2中是整数除法,对于所有阈值都将返回0。正确的方法是使用t/10.强制浮点除法。如果您使用的是python3,那么默认情况下会得到浮点除法,所以这可能不是问题。请注意,您做了c[j] > t,其中t介于0和10之间。总的来说,你的c[j] > t逻辑是错误的。你想对所有的元素使用一个计数器,就像其他答案告诉你的那样,或者把它全部分解成一行行的列表理解。在
最后,这里有一个充分利用numpy的解决方案。在import numpy as np
c = np.array([0.3, 0.2, 0.3, 0.6, 0.9, 0.1, 0.2, 0.5, 0.3, 0.5, 0.7, 0.1])
thresh = np.arange(0, 1, 0.1)
counts = np.empty(thresh.shape, dtype=int)
for i, t in enumerate(thresh):
counts[i] = len(np.where(c > t)[0])
print counts
输出:[12 10 8 5 5 3 2 1 1 0]
让numpy处理引擎盖下的循环比Python级别的循环更快。用于演示:import timeit
head = """
import numpy as np
c = np.array([0.3, 0.2, 0.3, 0.6, 0.9, 0.1, 0.2, 0.5, 0.3, 0.5, 0.7, 0.1])
thresh = np.arange(0, 1, 0.1)
"""
numpy_where = """
for t in thresh:
len(np.where(c > t)[0])
"""
python_loop = """
for t in thresh:
len([element for element in c if element > t])
"""
n = 10000
for test in [numpy_where, python_loop]:
print timeit.timeit(test, setup=head, number=n)
在我的电脑上会产生以下计时结果。在0.231292377372
0.321743753994