【问题标题】:Matrix multiplication in numpynumpy中的矩阵乘法
【发布时间】:2013-12-04 11:16:17
【问题描述】:

我在 numpy 中有 2 个布尔矩阵,并使用 .dot() 函数将它们相乘,得到的结果是一个布尔矩阵。

如果我在做矩阵乘法并且元素是 1 或 0,有没有办法在乘法过程中得到各个元素的乘积之和?

即结果矩阵中的元素应该是 0 或非零整数。

提前致谢。

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    使用astype 转换为int

    演示:

    >>> import numpy as np
    >>> np.random.seed(5)
    >>> a = np.random.random([3,3]) > 0.5
    >>> b = np.random.random([3,3]) > 0.5
    

    现在 a, b 是 dtype bool 的数组:

    >>> a
    array([[False,  True, False],
           [ True, False,  True],
           [ True,  True, False]], dtype=bool)
    

    将它们作为整数相乘:

    >>> np.dot(a.astype(np.int), b.astype(np.int))
    array([[0, 0, 1],
           [0, 0, 1],
           [0, 0, 2]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      • 2016-05-11
      • 2021-09-26
      • 2012-02-12
      • 2012-11-19
      相关资源
      最近更新 更多