gpt4 book ai didi

python - 使用 DEAP 的人类可读输出

转载 作者:太空宇宙 更新时间:2023-11-04 08:42:00 26 4
gpt4 key购买 nike

我正在使用 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

最佳答案

Ohjeahs 的回答与提供的不一样。我修改了提供的代码并在下面提供。

import sympy
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_),
'protectedDiv': lambda *args_: "Mul({}, Pow({}, -1))".format(*args_),
'mul': lambda *args_: "Mul({},{})".format(*args_),
'add': lambda *args_: "Add({},{})".format(*args_)
}
prim_formatter = converter.get(prim.name, prim.format)

return prim_formatter(*args)

def stringify_for_sympy(f):
"""Return the expression in a human readable string.
"""
string = ""
stack = []
for node in f:
stack.append((node, []))
while len(stack[-1][1]) == stack[-1][0].arity:
prim, args = stack.pop()
string = convert_inverse_prim(prim, args)
if len(stack) == 0:
break # If stack is empty, all nodes should have been seen
stack[-1][1].append(string)
return string

sympy.simplify(stringify_for_sympy(best_ind))

关于python - 使用 DEAP 的人类可读输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44127475/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com