如何将 SymPy 表达式转换为 NumPy?

How can I convert a SymPy expression to NumPy?

如何将 sympy 表达式转换为 numpy 代码?例如,假设我这是表达式的代码:

expression = 2 * x/y + 10 * sympy.exp(x) # Assuming that x and y are predefined from sympy.symbols

我想从 expression 转到这个:

np_expression = "np.dot(2, np.dot(x, np.linalg.pinv(y))) + np.dot(10, np.exp(x))"

请注意 xy 是矩阵,但我们可以假设形状将匹配

实数示例如下:

a = np.array([1,2],[3,4])
b = np.array([5,6],[7,8])

expression = 2 * a/b + 10 # These would be sympy symbols rather than numbers

结果是这样的:

np_expression = "np.dot(2, np.dot(5, np.linalg.pinv(9))) + 10"
In [1]: expr = 2 *x/y + 10 * exp(x)
In [3]: f = lambdify((x,y), expr)
In [4]: help(f)
_lambdifygenerated(x, y)
    Created with lambdify. Signature:
    
    func(x, y)
    
    Expression:
    
    2*x/y + 10*exp(x)
    
    Source code:
    
    def _lambdifygenerated(x, y):
        return 2*x/y + 10*exp(x)

对于特定的输入,数组或其他:

In [5]: f(np.arange(1,5)[:,None], np.arange(1,4))
Out[5]: 
array([[ 29.18281828,  28.18281828,  27.84948495],
       [ 77.89056099,  75.89056099,  75.22389432],
       [206.85536923, 203.85536923, 202.85536923],
       [553.98150033, 549.98150033, 548.648167  ]])
In [6]: f(1,1)
Out[6]: 29.18281828459045
In [7]: f(2,3)
Out[7]: 75.22389432263984
In [8]: f(np.arange(1,4),np.arange(1,4))
Out[8]: array([ 29.18281828,  75.89056099, 202.85536923])

适用普通阵列广播规则。请注意 x/y 是 element-wise。我不确定 lambdify 会转换成 dotinv 代码。

正在尝试您的 numpy 代码:

In [9]: np.dot(2, np.dot(2,np.linalg.pinv(3)))+10*np.exp(2)
---------------------------------------------------------------------------
LinAlgError                               Traceback (most recent call last)
<ipython-input-9-6cae91f0e0f8> in <module>
----> 1 np.dot(2, np.dot(2,np.linalg.pinv(3)))+10*np.exp(2)
 ....

LinAlgError: 0-dimensional array given. Array must be at least two-dimensional

我们必须将 y 更改为二维数组,例如[[3]]:

In [10]: np.dot(2, np.dot(2,np.linalg.pinv([[3]])))+10*np.exp(2)
Out[10]: array([[75.22389432]])