使用`map`而不是`for`循环,通过迭代列表长度并使用列表值。

huangapple go评论77阅读模式
英文:

Using map instead of a for loop by iterating over list length and using list values

问题

在我的程序中,我有6种不同的模型和每个模型都有6个索引。我想通过循环遍历index张量来计算索引的频率,以确定哪个模型领先。

index张量表示每次运行的索引频率,包含4096个值,范围在0到5之间。

我的当前代码如下:

freq = [0]*6
for idx in index:
    freq[idx] += 1

但这需要很长时间(单次调用需要0.3秒,我调用这个循环500,000次),使代码运行非常慢。因此,我决定使用一个map函数来加速这个循环,改写如下:

freq = [0]*6
freq = list(map(lambda x: freq[x] + 1 , index))

但它不像预期的那样工作。freq只是为index的每个元素添加了1,最后得到一个长度为4096的充满1的列表。

正确的输出应该如下所示:

[433, 732, 271, 1628, 711, 321]

这些值相加等于4096。

index的一个示例:

tensor([4, 3, 1,  ..., 4, 5, 1], device='cuda:0')

其中包含4096个元素。如何修复这个map函数?

提前感谢您的帮助!

英文:

In my program I have 6 different models and 6 indexes for each of them. I want to count the index frequency by looping over an index tensor to see which one of my models is getting ahead.

index tensor is here frequency of indexes for each run and contains 4096 values between 0-5.

My current code looks like:

freq = [0]*6
for idx in index:
    freq[idx] += 1

But that takes so long(single call takes 0.3s and I call this loop 500.000 times) and makes the code very slow. So I decided to speed this loop with a map function and wrote this instead:

freq = [0]*6
freq = list(map(lambda x: freq[x] + 1 , index))

But it doesn't work as its supposed to. freq just adds 1 for each element of index and at the end it gives a list full of 1's with a length of 4096.

A proper output would look like:

[433, 732, 271, 1628, 711, 321]

which adds up to 4096.

An example for index

tensor([4, 3, 1,  ..., 4, 5, 1], device='cuda:0')

which has 4096 elements. How could I fix that map function?

Thanks in advance!

答案1

得分: 1

这应该可以解决问题(假设x是您的输入向量):

import numpy as np
from collections import Counter
x=np.random.randint(1,7, size=4096)

y=Counter(x)
res=np.array(sorted(y.items(), key=lambda x: x[0]))[:, 1]

输出(这是均匀分布):

[722 639 665 683 697 690]
英文:

This should do the trick (assuming x is your input vector):

import numpy as np
from collections import Counter
x=np.random.randint(1,7, size=4096)

y=Counter(x)
res=np.array(sorted(y.items(), key=lambda x: x[0]))[:, 1]

Output (it's uniform distribution):

[722 639 665 683 697 690]

huangapple
  • 本文由 发表于 2020年1月4日 00:35:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/59582100.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定