# https://discuss.pytorch.org/t/how-to-get-the-module-names-of-nn-sequential/39682
# looping through modules but get the one with a specific name
import torch
import torch.nn as nn
from collections import OrderedDict
params = OrderedDict([
('fc0', nn.Linear(in_features=4,out_features=4)),
('ReLU0', nn.ReLU()),
('fc1L:final', nn.Linear(in_features=4,out_features=1))
])
mdl = nn.Sequential(params)
# throws error
# mdl['fc0']
for m in mdl.children():
print(m)
print()
for m in mdl.modules():
print(m)
print()
for name, m in mdl.named_modules():
print(name)
print(m)
print()
for name, m in mdl.named_children():
print(name)
print(m)
For example, to scale a specific layer by a scalar c I did the following:
weight_name = 'fc2.weight'
c = 100
for name, param in model.named_parameters():
if param.requires_grad:
if name == weight_name:
param.data = c*param.data