I have two arrays p and alpha, and I want to <=-compare each element of p with each element of alpha, and then aggregate (count) over the first axis. My code:
s = np.sum(np.less_equal.outer(p, alpha), axis=0)
p is at least one- but possibly multidimensional, and can have dimensions like 100 × 1000000. alpha is one-dimensional and has typically 100 to 1000 elements.
The problem is that np.less_equal.outer creates an intermediate array, which in the worst case can be of size 100 × 1000000 × 1000 = 1011 elements, close to 1 TB, far beyond my memory capacity.
My approach is to split the computation up along the first axis:
s = np.zeros(shape=(*p.shape[1:], len(alpha)), dtype='int64')
for pr in p:
s += np.less_equal.outer(pr, alpha)
That seems to work, but I'm wondering whether NumPy has tools to make this more efficient (vectorized)?