如何在 Julia 中使用 SymPy 对字符串列表进行 lambdify?

How to lambdify a list of strings with SymPy in Julia?

在 Julia 中使用 SymPy,如何转换示例输入

feature_names = ["1", "x", "y", "z", "x^2", "x y", "x z", "y^2", "y z", "z^2"]

进入可调用方法 f(x, y, z) 其中 returns 表达式的求值

julia >>> f(1, 2, 3)
julia >>> 10-element Vector{float64}:
          [1, 1, 2, 3, 1, 2, 3, 4, 6, 9]

在 Julia 中你可以这样做:

using SymPy
@vars x y z

feature_names = [1, x, y, z, x^2, x*y, x*z, y^2, y*z, z^2]

f(a,b,c) = feature_names.evalf(subs=Dict(x=>a,y=>b,z=>c)) |> N |> vec

f(1,2,3) # [1.0,1.0,2.0,...]

或者更笼统地说:

solveMultipleSympyFunctions(values,sympy_symbols,expressions) = expressions.evalf(subs=Dict(zip(sympy_symbols,values))) |> N |> vec

solveMultipleSympyFunctions([1,2,3],[x,y,z],feature_names)

N(.)函数是检索一个数值输出而不是一个仍然是符号的数字,vec()是将输出,即矩阵形式,转换为向量作为在你的请求中。最后,|>是管道符(只是为了方便,不用写vec(N(...))

编辑:

我确实尝试了几种从字符串向量开始表达式的方法,但是 none 以上方法有效:

feature_names_string = ["1", "x", "y", "z", "x^2", "x*y", "x*z", "y^2", "y*z", "z^2"]
feature_names = symbols.(feature_names_string)
feature_names = symbols.(Symbol.(feature_names_string))
feature_names = sympy.Function.(feature_names_string)
feature_names = convert.(Sym,sympy.Function.(feature_names_string))
feature_names = Sym(feature_names_string)
feature_names = Sym.(feature_names_string)
feature_names = Sym.(sympy.Function.(feature_names_string))
feature_names = sympy.Function.(Sym.(feature_names_string))

这与您的要求不完全相同,因为像“x y”这样的表达式不适用于 sympify,所以我不得不根据需要添加 *,但使用 sympifyfree_symbols 允许自动化:

feature_names = ["1", "x", "y", "z", "x^2", "x*y", "x*z", "y^2", "y*z", "z^2"]

using SymPy
function F(feature_names)

    xs = sympy.sympify.(feature_names)
    vars = free_symbols(xs)
    function(as...)
        subs.(xs, (vars .=> as)...)
    end
end

λ = F(feature_names)
λ(1,2,3)

lamda 中变量的排序是通过对字符串化符号调用 sortperm 来确定的,因为这就是 free_symbols 排序的方式。