【问题标题】:Matrix Multiplication of NxM in PythonPython中NxM的矩阵乘法
【发布时间】:2020-05-03 12:48:01
【问题描述】:

我在 Python 中有 2 个矩阵:形状为 (4,1) 的矩阵 A 和形状为 (4,4) 的矩阵 B。 我使用列表中的数据形成了 2 个矩阵。

valList 数据看起来像

00200030
00200030
00200030
00200030
00480051
FFF0004B
FFF0004B

我将每个项目转换为一个 32 位整数,然后使用这些数据形成矩阵。

for item in valList:
    int(item,32)

B_RC = createMatrix(rows,1,valList)
B = np.array(B_RC)
print B

A_RC = valList[rows:rows + (rows * cols)]
A = np.array(A_RC).reshape( (rows,cols))
print A

def createMatrix(rowCount, colCount, dataList):   
    mat = []
    for i in range (rowCount):
        rowList = []
        for j in range (colCount):
            if dataList[j] not in mat:
                rowList.append(dataList[i])
        mat.append(rowList)

    return mat

我想将这两个矩阵相乘。 我使用了 numpy,但下面的代码出现以下错误:

>>> C=np.matmul(B,A)

error: ufunc 'matmul' did not contain a loop with signature matching types dtype('S8') dtype('S8') dtype('S8')

我应该使用什么功能?

【问题讨论】:

  • 我认为问题出在您的 AB 矩阵的数据类型上。您能否在问题中发布它们的值?
  • 我假设 dataList 包含所有数字,那么您需要在运行 C 之前更改 numpy 数组的数据类型,例如 A = A.astype("float64")B = B.astype("float64")
  • 我试过这个......它让我无法将字符串转换为浮点数:我在列表中的数据项是例如 FFBCFFA2
  • 那么,您愿意如何对字符串执行点积?
  • 如何将字符串列表转换为 32 位十六进制数?

标签: python numpy matrix matrix-multiplication


【解决方案1】:

Python 为这些用例提供了运算符:

A * B  # dot-product
A @ B  # matrix-multiplication

矩阵乘法运算符是右结合的。

如果您需要这些作为函数参数:

import operator
operator.matmul(A, B)

【讨论】:

  • 我不认为这个答案解决了用户的错误,因为他们在使用matmul 时得到的错误是“错误:ufunc'matmul'没有包含签名匹配类型dtype(' S8') dtype('S8') dtype('S8') "
【解决方案2】:

正如 cmets 中所讨论的,矩阵 AB 具有以 32 为底的十六进制值,写为 str。而要进行点积,我们首先需要使用内置函数 int(value, base) 将这些值转换为整数。

在这里,我创建了一个小例子来解释这个过程应该如何进行:

>>> import numpy as np

>>> A = np.array([[int("FFBCFFA2", 32)],
                  [int("FFBCFFA2", 32)],
                  [int("FFBCFFA2", 32)],
                  [int("FFBCFFA2", 32)]])
>>> A.shape
(4,1)
>>>
>>> B = np.array([[int("FFBCFFA2", 32), int("FFBCFFA2", 32), int("FFBCFFA2", 32), int("FFBCFFA2", 32)],
                  [int("FFBCFFA2", 32), int("FFBCFFA2", 32), int("FFBCFFA2", 32), int("FFBCFFA2", 32)],
                  [int("FFBCFFA2", 32), int("FFBCFFA2", 32), int("FFBCFFA2", 32), int("FFBCFFA2", 32)],
                  [int("FFBCFFA2", 32), int("FFBCFFA2", 32), int("FFBCFFA2", 32), int("FFBCFFA2", 32)]])
>>> B.shape
(4,4)
>>>
>>> C = np.matmul(A, B)
[[6956274410837382160]
 [6956274410837382160]
 [6956274410837382160]
 [6956274410837382160]]

如我们所见,点积的输出是数字,您可以使用hex() 方法将这些值转换回十六进制值:

>>> hex(C[0][0])
0x6089a6b8821a1410

编辑

以下是将valList转换为int的正确方法:

valList = list(map(lambda x: int(x,32), valList))

【讨论】:

  • 我更新了我的查询...我在使用表单矩阵函数之前尝试将列表更改为 32 位,错误似乎保持不变..您可以看看更新的代码吗?
猜你喜欢
  • 2011-11-20
  • 1970-01-01
  • 2017-03-12
  • 1970-01-01
  • 1970-01-01
  • 2012-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多