我试图学习SymPy,我想弄清楚如何做一个很酷的任务,以象征性的方式得出normal equations最小二乘问题。
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&#39; x)^ { - 1} x&#39; y之类的结果。 SymPy有可能吗?
答案 0 :(得分:1)
不,SymPy没有内置这种级别的抽象矩阵演算。为了能够区分矩阵,它们必须具有特定的大小,并且可以填充您可以区分的内容:我在下面举例说明。也就是说,您可能对this project感兴趣,Demo通过公理化某些规则来实现SymPy中抽象矩阵演算的元素。
以下是您可以使用SymPy进行符号最小二乘的实际示例。使用符号变量填充矩阵可以使用symarray
(使用a_0_0
表示法)来完成。然后计算残差,区分和求解。
from sympy import *
m = 3
n = 2
x = Matrix(symarray('x', (m, n)))
y = Matrix(symarray('y', (m, 1)))
b = Matrix(symarray('b', (n, 1)))
z = (y-x*b).dot(y-x*b)
vars = [b[i,0] for i in range(n)]
eqs = [z.diff(b) for b in vars]
print solve(eqs, vars)
输出虽然正确但并不具有启发性:
{b_0_0: ((x_0_1**2 + x_1_1**2 + x_2_1**2)*(x_0_0*y_0_0 + x_1_0*y_1_0 + x_2_0*y_2_0) - (x_0_0*x_0_1 + x_1_0*x_1_1 + x_2_0*x_2_1)*(x_0_1*y_0_0 + x_1_1*y_1_0 + x_2_1*y_2_0))/((x_0_0**2 + x_1_0**2 + x_2_0**2)*(x_0_1**2 + x_1_1**2 + x_2_1**2) - (x_0_0*x_0_1 + x_1_0*x_1_1 + x_2_0*x_2_1)**2), b_1_0: ((x_0_0**2 + x_1_0**2 + x_2_0**2)*(x_0_1*y_0_0 + x_1_1*y_1_0 + x_2_1*y_2_0) - (x_0_0*x_0_1 + x_1_0*x_1_1 + x_2_0*x_2_1)*(x_0_0*y_0_0 + x_1_0*y_1_0 + x_2_0*y_2_0))/((x_0_0**2 + x_1_0**2 + x_2_0**2)*(x_0_1**2 + x_1_1**2 + x_2_1**2) - (x_0_0*x_0_1 + x_1_0*x_1_1 + x_2_0*x_2_1)**2)}