dvdios
dvdios

Reputation: 76

Elementwise mean of dot product in Python (numpy)

I have two numpy matrixes (or sparse equivalents) like:

>>> A = numpy.array([[1,0,2],[3,0,0],[4,5,0],[0,2,2]])
>>> A
array([[1, 0, 2],
       [3, 0, 0],
       [4, 5, 0],
       [0, 2, 2]])
>>> B = numpy.array([[2,3],[3,4],[5,0]])
>>> B
array([[2, 3],
       [3, 4],
       [5, 0]])

>>> C = mean_dot_product(A, B)
>>> C
array([[6   ,  3],
       [6   ,  9],
       [11.5, 16],
       [8   ,  8]])

where C[i, j] = sum(A[i,k] * B[k,j]) / count_nonzero(A[i,k] * B[k,j])

There is a fast way to preform this operation in numpy?

A non ideal solution is:

>>> maskA = A > 0
>>> maskB = B > 0

>>> maskA.dtype=numpy.uint8
>>> maskB.dtype=numpy.uint8

>>> D = replace_zeros_with_ones(numpy.dot(maskA,maskB)) 

>>> C = numpy.dot(A,B) / D

Anyone have a better algorithm?

Further, if A or B are sparse matrix, making them dense (replacing zeros with ones) make memory occupation expolde!

Upvotes: 2

Views: 1076

Answers (1)

HYRY
HYRY

Reputation: 97331

Why you need replace_zeros_with_ones? I delete this line and run your code and get the right result.

You can do this by only one line if all the numbers are not negtaive:

np.dot(A, B)/np.dot(np.sign(A), np.sign(B))

Upvotes: 1

Related Questions