Sympy lamdify 数组,形状为 (n,) [英] Sympy lambdify array with shape (n,)

查看:33
本文介绍了Sympy lamdify 数组,形状为 (n,)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前对 sympy 有以下问题":

I have the following 'issue' with sympy at the moment:

我有一个符号表达式,如 M = matrix([pi*a, sin(1)*b]) 我想 lambdify 并传递给一个数字优化器.问题是优化器需要函数来输入/输出形状为 (n,) 的 numpy 数组,特别是 NOT (n,1).

I have a symbolic expression like M = matrix([pi*a, sin(1)*b]) which I want to lambdify and pass to a numerical optimizer. The issue is that the optimizer needs the function to input/output numpy arrays of shape (n,) and specifically NOT (n,1).

现在我已经能够使用以下代码 (MWE) 实现这一点:

Now I have been able to achieve this with the following code (MWE):

import numpy as np
import sympy as sp
a, b = sp.symbols('a, b')
M = sp.Matrix([2*a, b])
f_tmp = sp.lambdify([[a,b]], M, 'numpy')
fun   = lambda x: np.reshape( f_tmp(x), (2,))

现在,这当然非常难看,因为每次评估 fun 时都需要应用重塑(这可能是很多次).有没有办法避免这个问题?Matrix 类根据定义总是二维的.我尝试使用 sympyMutableDenseNDimArray-class,但它们不能与 Lambdify 结合使用.(符号变量不被识别)

Now, this is of course extremely ugly, since the reshape needs to be applied every time fun is evaluated (which might be LOTS of times). Is there a way to avoid this problem? The Matrix class is by definition always 2 dimensional. I tried using sympy's MutableDenseNDimArray-class, but they don't work in conjunction with lambdify. (symbolic variables don't get recognized)

推荐答案

一种方法是将矩阵转换为嵌套列表并取第一行:

One way is to convert a matrix to a nested list and take the first row:

fun = sp.lambdify([[a, b]], M.T.tolist()[0], 'numpy')

现在 fun([2, 3])[4, 3].这是一个 Python 列表,而不是一个 NumPy 数组,但优化器(至少在 SciPy 中)应该可以接受.

Now fun([2, 3]) is [4, 3]. This is a Python list, not a NumPy array, but optimizers (at least those in SciPy) should be okay with that.

一个也可以

fun = sp.lambdify([[a, b]], np.squeeze(M), 'numpy')

也返回一个列表.

在我的测试中,上述内容同样快,并且比带有包装函数的版本(无论是 np.squeeze 还是 np.reshape)都快:大约 6 µs对比 9 微秒.似乎收益在于消除了一个函数调用.

In my test the above were equally fast, and faster than the version with a wrapping function (be it np.squeeze or np.reshape): about 6 µs vs 9 µs. It seems the gain is in eliminating one function call.

这篇关于Sympy lamdify 数组,形状为 (n,)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆