0

I have this piece of code:

n = np.load(matrix)["arr_0"]
shape = n.shape
##colsums and rowsums
rows = {}
cols = {}
for i in xrange(shape[0]): #row
    rows[i] = np.sum(n[i,:])
for j in xrange(shape[1]): #cols
    cols[j] = np.sum(n[:,j])
##looping over bins
for i in xrange(shape[0]): #row
    print i
    for j in xrange(shape[1]): #column
        if rows[i] == 0 or cols[j] == 0:
            continue
        n[i,j] = n[i,j]/math.sqrt(rows[i]*cols[j])

It basically loops over a numpy matrix with shape (50000,50000) and I need to divide each value for the square root of the product of the sum of the corresponding column by the sum of the corresponding row. My implementation takes ages. Do you have any suggestions to improve its performance?

1
  • There is usually no need for explicitly using loops when using np.array. If you are then you are probably over-complicating something. Commented Jul 4, 2016 at 12:51

2 Answers 2

2

You can simply take the sums individually on each axis, then take the outer product, then the square root. This can be condensed a bit but it gives you an idea how to vectorize it.

# Sum of rows and columns
a = numpy.sum(data, axis=1)
b = numpy.sum(data, axis=0)

# Product of sum and columns
c = numpy.outer(a,b)

# The square root...
d = numpy.sqrt(c)

# ...a nd the division
data /= d
Sign up to request clarification or add additional context in comments.

3 Comments

TypeError: ufunc 'divide' output (typecode 'd') could not be coerced to provided output parameter (typecode 'h') according to the casting rule ''same_kind''
There is a type difference between data and d, you can just do data = data/d instead, or find/fix the type difference.
I think that it throws the error since I have rows and columns which sum is 0. So, invalid division.
1

Here's a one-liner solution using np.where and NumPy broadcasting -

np.where((rows[:,None]==0) | (cols==0),n,n/np.sqrt((rows[:,None]*cols)))

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.