【问题标题】:how to do dot multiplication of vector and sparse matrix in python如何在python中对向量和稀疏矩阵进行点乘
【发布时间】: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


【解决方案1】:

x2[1]*x1 可能工作或x2[1]@x1。无论哪种方式,都可以让稀疏矩阵控制乘法。 x2.dot(...) 使用 x2.dot(np.array(x1)) 这是错误的。 x2.dot(x1.A) 也应该可以工作。 如果你想要简短的答案,你可以阅读这个

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-16
    • 2021-12-18
    • 1970-01-01
    • 2020-02-28
    • 2019-09-28
    • 2011-08-23
    • 2011-11-20
    • 1970-01-01
    相关资源
    最近更新 更多