1

I have a Python function call like so:

import torchvision
model = torchvision.models.resnet18(pretrained=configs.use_trained_models)

Which works fine.

If I attempt to make it dynamic:

import torchvision
model_name = 'resnet18'
model = torchvision.models[model_name](pretrained=configs.use_trained_models)

then it fails with:

TypeError: 'module' object is not subscriptable

Which makes sense since model is a module which exports a bunch of things, including the resnet functions:

# __init__.py for the "models" module
...
from .resnet import * 
...

How can I call this function dynamically without knowing ahead of time its name (other than that I get a string with the function name)?

asked Feb 2, 2021 at 23:04

2 Answers 2

3

You can use the getattr function:

import torchvision
model_name = 'resnet18'
model = getattr(torchvision.models, model_name)(pretrained=configs.use_trained_models)

This essentially is along the lines the same as the dot notation just in function form accepting a string to retrieve the attribute/method.

answered Feb 2, 2021 at 23:10
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thanks a lot!
2

The new APIs since Aug 2022 are as follows:

# returns list of available model names
torchvision.models.list_models()
# returns specified model with pretrained common weights
torchvision.models.get_model("alexnet", weights="DEFAULT")
# returns specified model with pretrained=False
torchvision.models.get_model("alexnet", weights=None)
# returns specified model with specified pretrained weights
torchvision.models.get_model("alexnet", weights=ResNet50_Weights.IMAGENET1K_V2)

Reference: https://pytorch.org/blog/easily-list-and-initialize-models-with-new-apis-in-torchvision/

answered Feb 14, 2023 at 1:58

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.