使用SymPy

时间:2018-06-05 23:28:05

标签: python sympy symbolic-math

我正在尝试使用SymPy以符号形式处理多元正态分布。但是,它似乎无法实现我想要取幂的矩阵表达式求值为标量。这是代码:

from sympy import *
    # Sample size, number of covariates
n, k = symbols('n k')
    # Data
X = MatrixSymbol('X', n, k)
y = MatrixSymbol('y', n, 1)
    # Parameters
beta = MatrixSymbol('beta', k, 1)
Sigma = MatrixSymbol('Sigma', n, n)
# Exponent expression, OK:
(-Rational(1, 2)*(y - X*beta).T*Sigma*(y - X*beta))
# Trying to use as exponent, not OK:
exp(-Rational(1, 2)*(y - X*beta).T*Sigma*(y - X*beta))

以下错误消息:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-76-62c854b75962> in <module>()
----> 1 exp((-Rational(1, 2)*(y - X*beta).T*Sigma*(y - X*beta)))

D:\Programming\Anaconda3\lib\site-packages\sympy\core\function.py in __new__(cls, *args, **options)
    425 
    426         evaluate = options.get('evaluate', global_evaluate[0])
--> 427         result = super(Function, cls).__new__(cls, *args, **options)
    428         if not evaluate or not isinstance(result, cls):
    429             return result

D:\Programming\Anaconda3\lib\site-packages\sympy\core\function.py in __new__(cls, *args, **options)
    248 
    249         if evaluate:
--> 250             evaluated = cls.eval(*args)
    251             if evaluated is not None:
    252                 return evaluated

D:\Programming\Anaconda3\lib\site-packages\sympy\functions\elementary\exponential.py in eval(cls, arg)
    300 
    301         elif arg.is_Matrix:
--> 302             return arg.exp()
    303 
    304     @property

AttributeError: 'MatMul' object has no attribute 'exp'

1 个答案:

答案 0 :(得分:1)

指数函数不支持矩阵表达式;它需要一个显式矩阵,意味着一个具有明确条目的明确大小的矩阵(可以是符号)。要从矩阵表达式中获取显式矩阵,请使用as_explicit方法。

exp((-Rational(1, 2)*(y - X*beta).T*Sigma*(y - X*beta)).as_explicit())

返回1×1矩阵,即

Matrix([[exp(Sum(-y[_k, 0]*Sum(Sigma[_k, _k]*y[_k, 0], (_k, 0, n - 1)) + y[_k, 0]*Sum(Sigma[_k, _k]*Sum(X[_k, _k]*beta[_k, 0], (_k, 0, k - 1)), (_k, 0, n - 1)) + Sum(Sigma[_k, _k]*y[_k, 0], (_k, 0, n - 1))*Sum(X[_k, _k]*beta[_k, 0], (_k, 0, k - 1)) - Sum(Sigma[_k, _k]*Sum(X[_k, _k]*beta[_k, 0], (_k, 0, k - 1)), (_k, 0, n - 1))*Sum(X[_k, _k]*beta[_k, 0], (_k, 0, k - 1)), (_k, 0, n - 1))/2)]])

或者你可以做到

exp((-Rational(1, 2)*(y - X*beta).T*Sigma*(y - X*beta)).as_explicit()[0, 0])

从1乘1矩阵下降到标量。