'import specific module from the class by different name as string variable
I wanna get a module from a class with different name (string variable). However, the content has same form of string as the original module name. For example
import timm
model_configs = timm.models.resnet.default_cfgs['resnet34'] #this one works
target_network_root = 'resnet'
model_configs = timm.models.target_network_root.default_cfgs['resnet34'] #this one doesn't work
Since, the target_network_root can change, I might export another network than resnet, I like to call specific module from timm.models as variable. I really appreciate your support.
Solution 1:[1]
You can use getattr()
For example:
getattr(timm.models, target_network_root)
=> timm.models.resnet
Solution 2:[2]
if your goal is to load different models form it; this is the right approach:
import timm
list_of_resnet_models = timm.list_models('resnet*',pretrained=True)
#you can fill in this list with some models of your own like: #['resnet34','resnet50','...'] #whatever existing model in timm
model = timm.create_model(list_of_resnet_models[0],pretrained=True)
print(model.default_cfg)
later you can pass different indices of list_of_resnet_models to load other models!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TeRe |
| Solution 2 | Sadra |
