Dot product that handle the sparse matrix case correctly.
When False, a and b both being sparse will yield sparse output. When True, output will always be a dense array.
Sparse if a and b are sparse and dense_output=False.
>>> from scipy.sparse import csr_matrix
>>> from sklearn.utils.extmath import safe_sparse_dot
>>> X = csr_matrix([[1, 2], [3, 4], [5, 6]])
>>> dot_product = safe_sparse_dot(X, X.T)
>>> dot_product.toarray()
array([[ 5, 11, 17],
[11, 25, 39],
[17, 39, 61]])
© 2007–2025 The scikit-learn developers
Licensed under the 3-clause BSD License.
https://scikit-learn.org/1.6/modules/generated/sklearn.utils.extmath.safe_sparse_dot.html