ValueError:添加Keras图层时,格式错误的节点或带有ast.literal_eval()的字符串 [英] ValueError: malformed node or string with ast.literal_eval() when adding a Keras layer

查看:76
本文介绍了ValueError:添加Keras图层时,格式错误的节点或带有ast.literal_eval()的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个评估字符串的Keras模型.如果我执行以下操作:

I want to build a Keras Model evaluating strings. If I do the following:

from keras.models import Sequential
from keras.layers import Dense

model = Sequential()
model.add(Dense(units=10, input_shape=(10,), activation='softmax'))

工作正常.我可以看到model.summary().

It works fine. And I can see the model.summary().

但是,当我使用ast.literal_eval()

from keras.models import Sequential
from keras.layers import Dense
import ast

model = Sequential()
code = "model.add( Dense( input_shape=(10,), units=10, activation='softmax' ) )"
ast.literal_eval(code)

它使我下一个ValueError:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.5/ast.py", line 84, in literal_eval
    return _convert(node_or_string)
  File "/usr/lib/python3.5/ast.py", line 83, in _convert
    raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: <_ast.Call object at 0x7efc40c90e10>

如果我使用eval而不是ast.literal_eval,它也可以工作.

If I use eval instead of ast.literal_eval it works too.

我正在使用python3.5.

I'm using python3.5.

推荐答案

一个大错误:literal_eval仅适用于文字.在这种情况下,我有一个电话.

A big mistake: literal_eval only works for literals. In this case, I have a Call.

函数literal_eval首先解析字符串.

从/usr/lib/python3.5/ast.py:第38-46行

def literal_eval(node_or_string):
    """
    Safely evaluate an expression node or a string containing a Python
    expression.  The string or node provided may only consist of the following
    Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
    sets, booleans, and None.
    """
    if isinstance(node_or_string, str):
        node_or_string = parse(node_or_string, mode='eval')

此时,node_or_stringExpression的实例.然后,literal_eval获取尸体.

At this point, node_or_string is an instance of Expression. Then, literal_eval get the body.

从/usr/lib/python3.5/ast.py:第47-48行

    if isinstance(node_or_string, Expression):
        node_or_string = node_or_string.body

最后,literal_eval检查主体的类型(node_or_string).

And finally, literal_eval checks the type of the body (node_or_string).

从/usr/lib/python3.5/ast.py:第49-84行

    def _convert(node):
        if isinstance(node, (Str, Bytes)):
            return node.s
        elif isinstance(node, Num):
            return node.n
        elif isinstance(node, Tuple):
            return tuple(map(_convert, node.elts))
        elif isinstance(node, List):
            return list(map(_convert, node.elts))
        elif isinstance(node, Set):
            return set(map(_convert, node.elts))
        elif isinstance(node, Dict):
            return dict((_convert(k), _convert(v)) for k, v
                        in zip(node.keys, node.values))
        elif isinstance(node, NameConstant):
            return node.value
        elif isinstance(node, UnaryOp) and \
             isinstance(node.op, (UAdd, USub)) and \
             isinstance(node.operand, (Num, UnaryOp, BinOp)):
            operand = _convert(node.operand)
            if isinstance(node.op, UAdd):
                return + operand
            else:
                return - operand
        elif isinstance(node, BinOp) and \
             isinstance(node.op, (Add, Sub)) and \
             isinstance(node.right, (Num, UnaryOp, BinOp)) and \
             isinstance(node.left, (Num, UnaryOp, BinOp)):
            left = _convert(node.left)
            right = _convert(node.right)
            if isinstance(node.op, Add):
                return left + right
            else:
                return left - right
        raise ValueError('malformed node or string: ' + repr(node))
    return _convert(node_or_string)

例如,如果初始代码是ast.literal_eval('1+1'),则现在node_or_string将是BinOp的实例.但在以下情况下:

If the initial code was ast.literal_eval('1+1') (for example), now node_or_string would be an instance of BinOp. But in the case of:

code = "model.add( Dense( input_shape=(10,), units=10, activation='softmax' ) )"
ast.literal_eval(code)

主体将是Call的实例,该实例不会出现在该函数的有效类型中.

The body will be an instance of Call, which does not appear among the valid types of the function.

例如:

import ast

code_nocall = "1+1"
node = ast.parse(code_nocall, mode='eval')
body = node.body
print(type(body)) # Returns <class '_ast.BinOp'>

code_call = "print('hello')"
node = ast.parse(code_call, mode='eval')
body = node.body
print(type(body)) # Returns <class '_ast.Call'>

解决方案

到目前为止,我发现最好的解决方案是手动执行此过程,而不直接使用eval.使用此功能:

Solution

The best solution I have found so far, to not use eval directly, is to perform the process manually. With this function:

import ast

def eval_code(code):
    parsed = ast.parse(code, mode='eval')
    fixed = ast.fix_missing_locations(parsed)
    compiled = compile(fixed, '<string>', 'eval')
    eval(compiled)

现在可以使用了:

eval_code("print('hello world')")

from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
code = "model.add( Dense( input_shape=(10,), units=10, activation='softmax' ) )"
eval_code(code)

这篇关于ValueError:添加Keras图层时,格式错误的节点或带有ast.literal_eval()的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆