How can i use module.name

m0 is a module of my model.I want to do something when name of m0 is ‘conv1’.How can I do it?

If you mean that you have a module called conv1 in a model named m0, you can access it with this command:

m0.conv1

There are some errors in my statement.My code show as below.

for layer_id in range(len(model)):
    m0 = old_modules[layer_id]

I want to make a restriction on m0 when its name is conv1.

Maybe this would work:

for name, module in model.named_modules():
    if 'conv1' in name:
        print('found')
1 Like

Thanks.m0 is a module.I need to judge whether the name of m0 is ‘conv1’.

for layer_id in range(len(model)):
    m1 = new_modules[layer_id]
    if isinstance(m0, nn.Conv2d):
       if m0.name == 'conv1':   # m0.name is a kind of expression, I don't know how to call it.
            idx1 = [0, 1]

This is the judgment I need to make.

1 Like

Would my suggestion not work on your model?
How did you define new_modules? Standard nn.Modules wouldn’t have the name attribute, so you should stick to named_modules() at one point (but I’m unsure how your classes are defined).

1 Like

It can’t solve my problem.m0 is a layer in my model.

if isinstance(m0, nn.Conv2d):
        for name,module in m0.named_modules():
            if 'conv1' in name:
                m1.weight.data = m0.weight.data.clone()
2 Likes

m0 seems to be undefined in the first condition, so you would probably have to move it inside.
Also, you are calling m0.named_modules(), while you should call it on the model.
After that m1 would be undefined, so you would have to add some more information what you are trying to do.

If you just want to access m0 and m1, which are names of two modules, you could use:

model.m0
model.m1

m0 has been defined.I will try other way.This judgement is important for my experiment.Thank you for your help.