Search code examples
neural-networknlpdynet

calling parameters by name in dynet


Is there a way to call a parameter by its name in dynet:

def dosomething(model):
    temp = model.get_parameter("temp") #something like this?
    ...

def create():
    Model = ParameterCollection()
    temp = Model.add_parameters((2,2))
    ...
    dosomething(Model) 

Solution

  • You cannot do so directly, using dynet API.

    Each parameter has a name, that you can specify with the keyword argument name. Example:

    pW = model.add_parameter((12, 12), name="W")
    

    However (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.

    So you cannot retrieve the corresponding parameter based on the ParameterCollection object and the name (well, you could but I would not advise it).


    So the usual practice to achieve when you need is to use a dictionary:

    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()