首页 > 解决方案 > 在 Dynet 中添加 numpy 数组和表达式的正确方法?

问题描述

在 Dynet 中添加参数和 numpy 生成的数组的正确方法是什么?例如,当我尝试以下操作时:

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)

标签: neural-networknlpdynet

解决方案


推荐阅读