[英]Python: How to iterate an n-dimensional matrix?
I have a matrix with shape (1 , 255, 13, 13), so I have 13x13=169 elements and for each of this elements I have a array of 255 elements. 我有一个形状矩阵(1,255,13,13),所以我有13x13 = 169个元素,对于每个元素,我有一个255个元素的数组。
I want to iterate over the fourth element of the 255 array and count how many elements are greater than 0.5. 我想迭代255数组的第四个元素并计算有多少元素大于0.5。
This code doesn't work but help to understand what I want: 此代码不起作用,但有助于理解我想要的内容:
out = net.forward()
count1=0
count2=0
for i in out[0]:
for j in out[2]:
for a in out[3]:
for b in out[1]:
if b[3]> 0.5:
count1+=1
else:
count2+=1
What is the best way to do this? 做这个的最好方式是什么?
if I understand you correctly: 如果我理解正确的话:
def give_counts(out):
"""Count the fourth element of each cell if it is >0.5
>>> x = [0, 0, 0, 3] # should show up in counts1
>>> o = [0, 0, 0, 0] # should show up in counts2
>>> out = [[x, o, o],
... [x, x, x],
... [o, o, x]]
>>> counts1, counts2 = give_counts(out)
>>> assert counts1 == 5
>>> assert counts2 == 4
"""
values = (True if col[3] > 0.5 else False for row in out for col in row)
counts = collections.Counter(values)
return counts[True], counts[False]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.