Search code examples
luatorch

torch7: Obtaining the Frequency of an Element in a Tensor


I am looking for some efficient way (or a combination of ways) to count the number of instances (i.e. obtain frequency) of a given element in any general torch.Tensor.

By efficient, I mean something other than the trivial iterative method to search through each element of the given tensor and something which can take advantage of the parallelism offered by the GPUs.

I have looked at the documentation provided at tensor.md and maths.md but was not able to find something which could help me.


Solution

  • Just formulating Alex's comment as an answer. I found it useful for my own work. Example:

    t = torch.Tensor({1, 2, 3, 1, 4, 2, 2, 2, 3, 0})
    frequency = t:eq(2):sum() -- frequency of 2 in t