在Python3中,如何使用品脱数量执行numpy矩阵乘法?

2024-06-11 06:14:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用(3, 3)np.matrix乘以包含pint数量信息的(3,1)np.matrix。在

此代码起作用:

import numpy as np
x = np.mat([[1,0,0],[0,1,0],[0,0,1]])
y = np.mat([[1],[0],[0]])
x * y
^{pr2}$

此代码产生错误:

^{3}$

错误是:

>>> x * y
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    x * y
  File "~/.virtualenvs/py3env/lib/python3.7/site-package
s/pint/quantity.py", line 900, in __mul__
    return self._mul_div(other, operator.mul)
  File "~/.virtualenvs/py3env/lib/python3.7/site-package
s/pint/quantity.py", line 75, in wrapped
    result = f(self, *args, **kwargs)
  File "~/.virtualenvs/py3env/lib/python3.7/site-package
s/pint/quantity.py", line 60, in wrapped
    result = f(self, *args, **kwargs)
  File "~/.virtualenvs/py3env/lib/python3.7/site-package
s/pint/quantity.py", line 866, in _mul_div
    magnitude = magnitude_op(self._magnitude, other_magnitude)
  File "~/.virtualenvs/py3env/lib/python3.7/site-package
s/numpy/matrixlib/defmatrix.py", line 215, in __mul__
    return N.dot(self, asmatrix(other))
ValueError: shapes (3,1) and (3,3) not aligned: 1 (dim 1) != 3 (dim 0)

如果我使用np.dot()我会得到一个结果,但是这些单元已经被剥离了

>>> np.dot(x, y)
~/.virtualenvs/py3env/lib/python3.7/site-packages/pint/q
uantity.py:1377: UnitStrippedWarning: The unit of the quantity is stripped
.
  warnings.warn("The unit of the quantity is stripped.", UnitStrippedWarni
ng)
matrix([[1],
        [0],
        [0]])

这是预期的行为吗?我应该能用NumPy矩阵数学来表示pint个量吗?有办法吗?在

我使用的是python3.7 数量==1.15.2 品脱==0.9


Tags: inpyselfpackagelibnplinesite
1条回答
网友
1楼 · 发布于 2024-06-11 06:14:57

正如hpaulj指出的,品脱数量类正在将订单切换到y*x

这是因为pint没有为右乘法rmul创建单独的函数,而是使用__rmul__ = __mul__

有几种方法可以解决这个问题

解决方案1

我通过修改品脱就解决了这个问题/数量.py拥有一个独立的自我。rmul功能

    def __mul__(self, other):
        return self._mul_div(other, operator.mul)

    def __rmul__(self, other):
        return self._mul_div(other, operator.mul, rmul=True)

    # __rmul__ = __mul__

和更改自身。有两个更改,可以选择交换self和other:

^{pr2}$

解决方案2

如果x是一个无量纲的品脱量,则乘法按正确的顺序给出。在

import numpy as np
import pint
ureg = pint.UnitRegistry()
x = np.mat([[1,0,0],[0,1,0],[0,0,1]]) *ureg("")
y = np.mat([[1],[0],[0]]) * ureg("m")
>>> x * y
<Quantity([[1]
 [0]
 [0]], 'meter')>

相关问题 更多 >