1

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

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

进入一个可调用的方法f(x, y, z),该方法返回表达式的评估,例如

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

2 回答 2

2

在 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(...))

编辑:

我确实尝试了几种从字符串向量开始表达式的方法,但上述方法均无效:

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))
于 2021-10-05T13:38:09.663 回答
2

这不是您要问的,因为像 "x y" 这样的表达式不适用于sympify,所以我必须*根据需要添加,但是使用sympifyandfree_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事物的顺序。

于 2021-10-05T17:57:30.573 回答