简体   繁体   English

从 class 以不同的名称作为字符串变量导入特定模块

[英]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).我想从 class 中获取一个具有不同名称(字符串变量)的模块。 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 re.net, I like to call specific module from timm.models as variable.由于 target.network_root 可以更改,我可能会导出另一个 .network 而不是 re.net,我喜欢从 timm.models 调用特定模块作为变量。 I really appreciate your support.非常感谢您的支持。

You can use getattr()你可以使用 getattr()

For example:例如:

getattr(timm.models, target_network_root)

=> timm.models.resnet

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_re.net_models to load other models!稍后您可以通过list_of_re.net_models的不同索引来加载其他模型!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM