在dynet中按名称调用参数
calling parameters by name in dynet
有没有办法在dynet中通过名称调用参数:
def dosomething(model):
temp = model.get_parameter("temp") #something like this?
...
def create():
Model = ParameterCollection()
temp = Model.add_parameters((2,2))
...
dosomething(Model)
你不能直接这样做,使用 dynet API。
每个参数都有一个名称,您可以使用关键字参数 name
指定该名称。示例:
pW = model.add_parameter((12, 12), name="W")
然而 (source):
The names are used for identifying the parameters and the collection hierarchy when loading from disk, and in particular when loading only a subset of the objects in a saved file.
...
One can supply an optional informative name when creating the parameter or sub-collection. The supplied names are then appended with running index to avoid name clashes.
所以你不能根据 ParameterCollection
对象和名称检索相应的参数(好吧,你可以,但我不建议这样做)。
所以通常的做法是在需要时使用字典来实现:
import dynet as dy
def dosomething(model, params):
pW = params["W"]
pb = params["b"]
#...
def create():
model = dy.ParameterCollection()
params = {}
params["W"] = model.add_parameters((12, 12))
params["b"] = model.add_parameters((12, ))
#...
dosomething(model, params)
create()
有没有办法在dynet中通过名称调用参数:
def dosomething(model):
temp = model.get_parameter("temp") #something like this?
...
def create():
Model = ParameterCollection()
temp = Model.add_parameters((2,2))
...
dosomething(Model)
你不能直接这样做,使用 dynet API。
每个参数都有一个名称,您可以使用关键字参数 name
指定该名称。示例:
pW = model.add_parameter((12, 12), name="W")
然而 (source):
The names are used for identifying the parameters and the collection hierarchy when loading from disk, and in particular when loading only a subset of the objects in a saved file.
...
One can supply an optional informative name when creating the parameter or sub-collection. The supplied names are then appended with running index to avoid name clashes.
所以你不能根据 ParameterCollection
对象和名称检索相应的参数(好吧,你可以,但我不建议这样做)。
所以通常的做法是在需要时使用字典来实现:
import dynet as dy
def dosomething(model, params):
pW = params["W"]
pb = params["b"]
#...
def create():
model = dy.ParameterCollection()
params = {}
params["W"] = model.add_parameters((12, 12))
params["b"] = model.add_parameters((12, ))
#...
dosomething(model, params)
create()