Matrix multiplication is associative, so you can always first compute W * X
:
>>> X.T.dot(W.dot(X))
array([[9, 9, 9],
[9, 9, 9],
[9, 9, 9]])
If you really have to compute X.T * W
, the first dense, the second sparse, you can let the sparse matrix __mul__
method take care of it for you:
>>> X.T * W
array([[1, 4],
[1, 4],
[1, 4]])
Actually, for your use case, if you use np.matrix
instead of np.array
, your particular operation becomes surprisingly neat to code:
>>> Y = np.matrix(X)
>>> Y.T * W * Y
matrix([[9, 9, 9],
[9, 9, 9],
[9, 9, 9]])