代码之家  ›  专栏  ›  技术社区  ›  user3639557

在Dynet中添加numpy数组和表达式的正确方法?

  •  0
  • user3639557  · 技术社区  · 6 年前

    from dynet import *
    import numpy as np
    import numpy.matlib as npm
    
    model = ParameterCollection()
    ....
    LayerA = model.add_parameters((1, 100))
    LayerA = model.add_parameters((1, 100))
    ...
    normal = np.random.normal(npm.zeros((1, 100)), npm.ones((1, 100)))
    Layer = LayerA + cmult(LayerB,normal) # cmult is Dynet component-wise multiplication
    ...
    output = Layer.expr() * activation(...)
    

    它给了我以下的错误,

    TypeError: Argument 'x' has incorrect type (expected _dynet.Expression, got _dynet.Parameters)
    

    所以,我尝试了这个,而不是上面提到的,

    Layer = LayerA + cmult(LayerB.expr(),normal)
    

    但它给了我以下的错误,

    TypeError: Argument 'y' has incorrect type (expected _dynet.Expression, got numpy.ndarray)
    

    所以我想我可能需要把numpy数组转换成dynet表达式,

    Layer = LayerA.expr() + cmult(LayerB.expr(),inputTensor(normal))
    ...
    output = Layer * activation(...)
    

    它毫无差错地通过了,但它在我呼叫的其他地方抱怨 output.scalar_value() ,

    terminate called after throwing an instance of 'std::runtime_error'
    what():  Input tensor has more than one element, cannot convert to scalar.
    Aborted (core dumped)
    
    0 回复  |  直到 6 年前