1

Is there a way to replace the following python list comprehension with a numpy function that doesn't work with loops?

a = np.array([0, 1, 1, 1, 0, 3])

bins = np.bincount(a)
>>> bins: [2 3 0 1]


a_counts = [bins[val] for val in y_true]
>>> a_counts: [2, 3, 3, 3, 2, 1]

So the basic idea is to generate an array where the actual values are replaced by the number of occurrences of that specific value in the array.

I want to do this calculation in a custom keras loss function which, to my knowledge, doesn't work with loops or list comprehensions.

3 Answers 3

3

You just need to index the result from np.bincount with a:

a = np.array([0, 1, 1, 1, 0, 3])
bins = np.bincount(a)
a_counts = bins[a]

print(a_counts)
# array([2, 3, 3, 3, 2, 1], dtype=int64)
Sign up to request clarification or add additional context in comments.

1 Comment

Little follow up question: I tried doing the same thing in keras using tf backend with the same arrays: python bins = k.tf.bincount(y_true) y_true_counts = bins[y_true] Unfortunately I get the following error: Shape must be rank 1 but is rank 2 for 'strided_slice_10' (op: 'StridedSlice') with input shapes: [?], [1,6], [1,6], [1].
0

Or use collections.Counter:

from collections import Counter
l = [0, 1, 1, 1, 0, 3]
print(Counter(l))

Which Outputs:

Counter({1: 3, 0: 2, 3: 1})

Comments

0

If you want to avoid loops, you may use pandas library:

import pandas as pd
import numpy as np
a = np.array([0, 1, 1, 1, 0, 3])
a_counts = pd.value_counts(a)[a].values
>>> a_counts: array([2, 3, 3, 3, 2, 1], dtype=int64)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.