DEAP的人类可读输出

时间:2017-05-23 06:38:46

标签: python deap

我正在使用DEAP对数据表进行符号回归,即找到最适合数据的函数。不幸的是,我找不到以人类可读格式获得结果的方法。例如,如果我这样做

best_ind = tools.selBest(pop, 1)[0]
print("Best individual is %s" % (best_ind))

我的输出可能看起来像

Best individual is add(mul(add(x, 2), div(y, add(x, y))), 1)

但人类难以解释。有没有办法以看起来更像

的方式打印结果
(x+2)*(y/(x+y))+1

2 个答案:

答案 0 :(得分:1)

您可以先使用sympy.simplify

开始
import sympy

expr = "Add(x, 2)"
sympy.simplify(expr)  # x + 2

然而,同情者想要添加,mul等大写。您还需要将Div(a, b)翻译为Mul(a, 1/b)

您可以通过更改primitive.format方法来执行此操作:

def convert_inverse_prim(prim, args):
    """
    Convert inverse prims according to:
    [Dd]iv(a,b) -> Mul[a, 1/b]
    [Ss]ub(a,b) -> Add[a, -b]
    We achieve this by overwriting the corresponding format method of the sub and div prim.
    """
    prim = copy.copy(prim)
    prim.name = re.sub(r'([A-Z])', lambda pat: pat.group(1).lower(), prim.name)    # lower all capital letters

    converter = {
        'sub': lambda *args_: "Add({}, Mul(-1,{}))".format(*args_),
        'div': lambda *args_: "Mul({}, Pow({}, -1))".format(*args_)
    }
    prim_formatter = converter.get(prim.name, prim.format)

    return prim_formatter(*args)

此代码取自glyph

答案 1 :(得分:0)

这个小小的对我来说很管用:

from sympy import sympify

locals = {
    'sub': lambda x, y : x - y,
    'div': lambda x, y : x/y,
    'mul': lambda x, y : x*y,
    'add': lambda x, y : x + y,
    'neg': lambda x    : -x,
    'pow': lambda x, y : x**y,
}

# ind = 'div(add(div(x, mul(y, y)), 1), mul(x, y))'
print(f'original: {ind}')
expr = sympify(str(ind) , locals=locals)
print(f'simplified: {expr}')

输出:

original: div(add(div(x, mul(y, y)), 1), mul(x, y))
simplified: (x/y**2 + 1)/(x*y)

当显示在 Jupyter 笔记本中时,它甚至会显示 LaTex:

display(expr)

enter image description here