python eval 的用处

定义的网络,有三个模块组成:

class RecModel(nn.Module):
    def __init__(self, config):
        super().__init__()
        assert 'in_channels' in config, 'in_channels must in model config'
        backbone_type = config.backbone.pop('type')
        assert backbone_type in backbone_dict, f'backbone.type must in {backbone_dict}'
        self.backbone = backbone_dict[backbone_type](config.in_channels, **config.backbone)

        neck_type = config.neck.pop('type')
        assert neck_type in neck_dict, f'neck.type must in {neck_dict}'
        self.neck = neck_dict[neck_type](self.backbone.out_channels, **config.neck)

        head_type = config.head.pop('type')
        assert head_type in head_dict, f'head.type must in {head_dict}'
        self.head = head_dict[head_type](self.neck.out_channels, **config.head)

        self.name = f'RecModel_{backbone_type}_{neck_type}_{head_type}'

现在需要finetune模型,冻结一些参数。
在配置文件中写了需要finetune的层, 'fine_tune_stage': [ 'backbone','neck', 'head'],
整个网络就三个模块,'fine_tune_stage': [ 'backbone','neck', 'head'],
然后看哪个模块不在配置文件的'fine_tune_stage'里面,就说明需要冻结参数。


def get_fine_tune_params(net, finetune_stage):
    """
    获取需要优化的参数
    Args:
        net:
    Returns: 需要优化的参数
    """

    # aa = net.backbone
    # aaa = net.module.backbone  #net = nn.DataParallel(net) 之后需要加module

    all_stage = ['backbone', 'neck', 'head']
    for stage_ in all_stage:
        if stage_ not in finetune_stage:
            stage_now = eval("net.module." + stage_)
            for name, value in stage_now.named_parameters():
                value.requires_grad = False

eval好啊,写个string类型的就可以代表函数名字。
一开始实验了一下aaa = net.module.backbone确实可以把模块提取出来,然后问题来了,如何来写,写if语句是可以,分三个情况写出来。这样不简洁。

stage_now = eval("net.module." + stage_)

这句可以搞定!!!

python eval 语法
eval() 函数用来执行一个字符串表达式,并返回表达式的值。

eval(expression[, globals[, locals]])
expression -- 表达式。
globals -- 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
locals -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。

>>>x = 7
>>> eval( '3 * x' )
21
>>> eval('pow(2,2)')
4
>>> eval('2 + 2')
4
>>> n=81
>>> eval("n + 4")
85

举几个例子感受一下,字符串与list、tuple、dict的转化。

a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
b = eval(a)
b
Out[3]: [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
type(b)
Out[4]: list
a = "{1: 'a', 2: 'b'}"
b = eval(a)
b
Out[7]: {1: 'a', 2: 'b'}
type(b)
Out[8]: dict
a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
b = eval(a)
b
Out[11]: ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))

https://blog.csdn.net/liuchunming033/article/details/87643041
Python:eval的妙用和慎用 https://blog.csdn.net/lu8000/article/details/44217499?utm_medium=distribute.pc_relevant.none-task-blog-2~default~BlogCommendFromMachineLearnPai2~default-1.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~BlogCommendFromMachineLearnPai2~default-1.control

posted @ 2021-05-26 19:27  无左无右  阅读(365)  评论(0编辑  收藏  举报