Instead of iterating over the coordinates using Python (GaryBishop answer), you can have numpy do the loop, which is a significant acceleration (timing below):
def sparse_mult(a, b, coords) : rows, cols = zip(*coords) rows, r_idx = np.unique(rows, return_inverse=True) cols, c_idx = np.unique(cols, return_inverse=True) C = np.dot(a[rows, :], b[:, cols]) return C[r_idx, c_idx] >>> A = np.arange(12).reshape(3, 4) >>> B = np.arange(15).reshape(3, 5) >>> np.dot(AT, B) array([[100, 112, 124, 136, 148], [115, 130, 145, 160, 175], [130, 148, 166, 184, 202], [145, 166, 187, 208, 229]]) >>> sparse_mult(AT, B, [(0, 0), (1, 2), (2, 4), (3, 3)]) array([100, 145, 202, 208])
sparse_mult returns a flattened array of values ββin the coordinates that you specify as a list of tuples. I am not very good at sparse matrix formats, so I donβt know how to determine CSC from the above data, but the following work:
>>> coords = [(0, 0), (1, 2), (2, 4), (3, 3)] >>> sparse.coo_matrix((sparse_mult(AT, B, coords), zip(*coords))).tocsc() <4x5 sparse matrix of type '<type 'numpy.int32'>' with 4 stored elements in Compressed Sparse Column format>
This is a time of various alternatives:
>>> import timeit >>> a = np.random.rand(2000, 3000) >>> b = np.random.rand(3000, 5000) >>> timeit.timeit('np.dot(a,b)[[0, 0, 1999, 1999], [0, 4999, 0, 4999]]', 'from __main__ import np, a, b', number=1) 5.848562187263569 >>> timeit.timeit('sparse_mult(a, b, [(0, 0), (0, 4999), (1999, 0), (1999, 4999)])', 'from __main__ import np, a, b, sparse_mult', number=1) 0.0018596387374678613 >>> np.dot(a,b)[[0, 0, 1999, 1999], [0, 4999, 0, 4999]] array([ 758.76351111, 750.32613815, 751.4614542 , 758.8989648 ]) >>> sparse_mult(a, b, [(0, 0), (0, 4999), (1999, 0), (1999, 4999)]) array([ 758.76351111, 750.32613815, 751.4614542 , 758.8989648 ])