Asil
Asil

Reputation: 884

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

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!

Upvotes: 0

Views: 270

Answers (1)

Georgina Skibinski
Georgina Skibinski

Reputation: 13387

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]

Upvotes: 1

Related Questions