Search code examples
pythonscikit-learnjuliasympylambdify

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


Using SymPy in Julia, how can I transform the example input

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

into a callable method f(x, y, z) which returns the evaluation of the expressions like

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

Solution

  • It isn't quite what you are asking, as expressions like "x y" don't work with sympify, so I had to add * as needed, but using sympify and free_symbols allows this to be automated:

    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)
    

    The ordering of the variables in the lamda is determined calling sortperm on the stringified symbols, as that is how free_symbols orders things.