【发布时间】:2020-10-26 19:52:23
【问题描述】:
dot向量和矩阵的乘法(稀疏)怎么做?
它适用于向量(ndarray 类型)和普通矩阵(ndarray 类型)。
import numpy as np
import pandas as pd
from scipy import sparse
x1 = np.arange(8).reshape((2, 4)) * 10
x2 = np.arange(4).reshape((2, 2))
x1
# array([[ 0, 10, 20, 30],
# [40, 50, 60, 70]])
x2
# array([[0, 1],
# [2, 3]])
# works
x2[1,].dot(x1)
# array([120, 170, 220, 270])
但不适用于稀疏矩阵(变成元素)
x1 = sparse.csr_matrix(x1)
x2[1,].dot(x1)
# array([<2x4 sparse matrix of type '<class 'numpy.int32'>'
# with 7 stored elements in Compressed Sparse Row format>,
# <2x4 sparse matrix of type '<class 'numpy.int32'>'
# with 7 stored elements in Compressed Sparse Row format>], dtype=object)
我该怎么做
【问题讨论】:
-
x2[1]*x1可能会起作用。或x2[1]@x1。无论哪种方式,都可以让稀疏矩阵控制乘法。x2.dot(...)使用x2.dot(np.array(x1))这是错误的。x2.dot(x1.A)也应该可以工作。 -
@hpaulj 使用
@有效!谢谢你!
标签: python scipy sparse-matrix numpy-ndarray