How to get a specific parameter matrix (tensor) of a model by its name in pytorch?

Question:

I have trained my model in pytorch. Now I want to extract a specific parameters tensor by its name (not all tensors). How can I do that?

print(myModel.parameters)

OUTPUT:

<bound method Module.parameters of ANN(
  (fc1): Linear(in_features=2, out_features=4, bias=True)
  (fc2): Linear(in_features=4, out_features=1, bias=True)
)>

For example, I only want to get fc1.weight and fc1.bias.

Asked By: Amin Kaveh

||

Answers:

You can access sub-modules with the dot notation directly, while parameters returns a iterator over all tensors without providing keys:

>>> myModel.fc1.weight
>>> myModel.fc1.bias
Answered By: Ivan