我正在尝试使用 Sympy在 IPython Notebook 中分解估计过程。能够在每一步都显示完整的线性方程来伴随数据操作将非常有用。举一个简单的回归示例,我有以下设置:
from sympy import *
from sympy.abc import epsilon
y=MatrixSymbol('y',5,1)
x=MatrixSymbol('x',5,2)
b=MatrixSymbol('b',2,1)
e=MatrixSymbol('epsilon',5,1)
我可以打印每个组件...
y.as_explicit()
(b*x).as_explicit()
e.as_explicit()
...但是我无法在 Sympy 中找到一种允许显示完整方程的方法(以下是使用 online latex editor 呈现的):
基本上任何时候我使用等号运算符都被合理地视为赋值,加法运算符转换 矩阵符号 进入 垫添加 对象,不支持
as_explict()
方法。对此问题的任何想法将不胜感激。
最佳答案
如果您调用MatAdd
构造函数显式,它不评估。要创建等式,请使用 Eq
.似乎有一个渲染,但在 Unicode pretty-print 中带有加号,我打开了 https://github.com/sympy/sympy/issues/2747为了。
In [14]: Eq(y.as_explicit(), MatAdd((x*b).as_explicit(), (e).as_explicit()))
Out[14]:
⎡y₀₀⎤ = ⎡x₀₀⋅b₀₀ + x₀₁⋅b₁₀⎤ + ⎡ε₀₀⎤
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎢y₁₀⎥ ⎢x₁₀⋅b₀₀ + x₁₁⋅b₁₀⎥ ⎢ε₁₀⎥
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎢y₂₀⎥ ⎢x₂₀⋅b₀₀ + x₂₁⋅b₁₀⎥ ⎢ε₂₀⎥
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎢y₃₀⎥ ⎢x₃₀⋅b₀₀ + x₃₁⋅b₁₀⎥ ⎢ε₃₀⎥
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎣y₄₀⎦ ⎣x₄₀⋅b₀₀ + x₄₁⋅b₁₀⎦ ⎣ε₄₀⎦
不过,LaTeX 打印似乎是正确的:
In [16]: print(latex(Eq(y.as_explicit(), MatAdd((x*b).as_explicit(), (e).as_explicit()))))
\left[\begin{matrix}y_{0, 0}\\y_{1, 0}\\y_{2, 0}\\y_{3, 0}\\y_{4, 0}\end{matrix}\right] = \left[\begin{matrix}x_{0, 0} b_{0, 0} + x_{0, 1} b_{1, 0}\\x_{1, 0} b_{0, 0} + x_{1, 1} b_{1, 0}\\x_{2, 0} b_{0, 0} + x_{2, 1} b_{1, 0}\\x_{3, 0} b_{0, 0} + x_{3, 1} b_{1, 0}\\x_{4, 0} b_{0, 0} + x_{4, 1} b_{1, 0}\end{matrix}\right] + \left[\begin{matrix}\epsilon_{0, 0}\\\epsilon_{1, 0}\\\epsilon_{2, 0}\\\epsilon_{3, 0}\\\epsilon_{4, 0}\end{matrix}\right]
您可以使用
MatMul
如果您不想评估 x*b
:In [18]: Eq(y.as_explicit(), MatAdd(MatMul(x.as_explicit(),b.as_explicit()), (e).as_explicit()))
Out[18]:
⎡y₀₀⎤ = ⎡x₀₀ x₀₁⎤⋅⎡b₀₀⎤ + ⎡ε₀₀⎤
⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎢y₁₀⎥ ⎢x₁₀ x₁₁⎥ ⎣b₁₀⎦ ⎢ε₁₀⎥
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎢y₂₀⎥ ⎢x₂₀ x₂₁⎥ ⎢ε₂₀⎥
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎢y₃₀⎥ ⎢x₃₀ x₃₁⎥ ⎢ε₃₀⎥
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎣y₄₀⎦ ⎣x₄₀ x₄₁⎦ ⎣ε₄₀⎦
In [19]: print(latex(Eq(y.as_explicit(), MatAdd(MatMul(x.as_explicit(),b.as_explicit()), (e).as_explicit()))))
\left\[\begin{matrix}y_{0, 0}\\y_{1, 0}\\y_{2, 0}\\y_{3, 0}\\y_{4, 0}\end{matrix}\right\] = \left\[\begin{matrix}x_{0, 0} & x_{0, 1}\\x_{1, 0} & x_{1, 1}\\x_{2, 0} & x_{2, 1}\\x_{3, 0} & x_{3, 1}\\x_{4, 0} & x_{4, 1}\end{matrix}\right\] \left\[\begin{matrix}b_{0, 0}\\b_{1, 0}\end{matrix}\right\] + \left\[\begin{matrix}\epsilon_{0, 0}\\\epsilon_{1, 0}\\\epsilon_{2, 0}\\\epsilon_{3, 0}\\\epsilon_{4, 0}\end{matrix}\right\]
关于python - Sympy - 以密集矩阵形式显示完整方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20886891/