我正在尝试学习SymPy,想要了解如何通过符号计算来执行一个酷炫的任务,即对最小二乘问题进行正规方程求导。
from sympy import *
init_session()
x, y, b = Matrix(), Matrix(), Matrix()
sqNorm = (y - x*b).dot(y- x*b)
solve(diff(sqNorm, b), b)
当我运行它时,我得到
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/sympy/core/function.py", line 1638, in diff
return Derivative(f, *symbols, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/sympy/core/function.py", line 1005, in __new__
if v._diff_wrt:
File "/usr/local/lib/python2.7/dist-packages/sympy/matrices/matrices.py", line 3084, in __getattr__
"%s has no attribute %s." % (self.__class__.__name__, attr))
AttributeError: ImmutableMatrix has no attribute _diff_wrt.
我希望得到类似于(x'x)^{-1}x'y的结果。在SymPy中是否可能实现?
Matrix()
是空矩阵,这不是你想要的。你应该能够使用MatrixSymbol,但看起来它还不支持微分。 - asmeurer