MMCV 加载模型配置文件

mmcv.Config 类

  • 支持的配置文件类型包括:'.py', '.json', '.yaml', '.yml'

1,读取模型配置文件

from mmcv import Config

cfg = Config.fromfile(args.config)

2, Config.fromfile()

    def fromfile(filename,
                 use_predefined_variables=True,
                 import_custom_modules=True):
        # 将文件转换为字典
        cfg_dict, cfg_text = Config._file2dict(filename,
                                               use_predefined_variables)
        # 加载预定的??
           
        if import_custom_modules and cfg_dict.get('custom_imports', None):
            import_modules_from_strings(**cfg_dict['custom_imports'])
        return Config(cfg_dict, cfg_text=cfg_text, filename=filename)

3, Config._file2dict(filename, use_predefined_variables)

  def _file2dict(filename, use_predefined_variables=True):
        # 判断该文件是否存在
        filename = osp.abspath(osp.expanduser(filename))
        check_file_exist(filename)
        # 判断该文件类型是否符合要求
        fileExtname = osp.splitext(filename)[1]
        if fileExtname not in ['.py', '.json', '.yaml', '.yml']:
            raise IOError('Only py/yml/yaml/json type are supported now!')
        #创建缓存配置文件
        with tempfile.TemporaryDirectory() as temp_config_dir:
            temp_config_file = tempfile.NamedTemporaryFile(
                dir=temp_config_dir, suffix=fileExtname)
            if platform.system() == 'Windows':
                temp_config_file.close()
            temp_config_name = osp.basename(temp_config_file.name)
            # Substitute predefined variables
            if use_predefined_variables:
                Config._substitute_predefined_vars(filename,
                                                   temp_config_file.name)
            else:
                shutil.copyfile(filename, temp_config_file.name)
            # Substitute base variables from placeholders to strings
            base_var_dict = Config._pre_substitute_base_vars(
                temp_config_file.name, temp_config_file.name)

            if filename.endswith('.py'):
                temp_module_name = osp.splitext(temp_config_name)[0]
                sys.path.insert(0, temp_config_dir)
                Config._validate_py_syntax(filename)
                mod = import_module(temp_module_name)
                sys.path.pop(0)
                cfg_dict = {
                    name: value
                    for name, value in mod.__dict__.items()
                    if not name.startswith('__')
                }
                # delete imported module
                del sys.modules[temp_module_name]
            elif filename.endswith(('.yml', '.yaml', '.json')):
                import mmcv
                cfg_dict = mmcv.load(temp_config_file.name)
            # close temp file
            temp_config_file.close()

        # check deprecation information
        if DEPRECATION_KEY in cfg_dict:
            deprecation_info = cfg_dict.pop(DEPRECATION_KEY)
            warning_msg = f'The config file {filename} will be deprecated ' \
                'in the future.'
            if 'expected' in deprecation_info:
                warning_msg += f' Please use {deprecation_info["expected"]} ' \
                    'instead.'
            if 'reference' in deprecation_info:
                warning_msg += ' More information can be found at ' \
                    f'{deprecation_info["reference"]}'
            warnings.warn(warning_msg, DeprecationWarning)

        cfg_text = filename + '\n'
        with open(filename, 'r', encoding='utf-8') as f:
            # Setting encoding explicitly to resolve coding issue on windows
            cfg_text += f.read()

        if BASE_KEY in cfg_dict:
            cfg_dir = osp.dirname(filename)
            base_filename = cfg_dict.pop(BASE_KEY)
            base_filename = base_filename if isinstance(
                base_filename, list) else [base_filename]

            cfg_dict_list = list()
            cfg_text_list = list()
            for f in base_filename:
                _cfg_dict, _cfg_text = Config._file2dict(osp.join(cfg_dir, f))
                cfg_dict_list.append(_cfg_dict)
                cfg_text_list.append(_cfg_text)

            base_cfg_dict = dict()
            for c in cfg_dict_list:
                duplicate_keys = base_cfg_dict.keys() & c.keys()
                if len(duplicate_keys) > 0:
                    raise KeyError('Duplicate key is not allowed among bases. '
                                   f'Duplicate keys: {duplicate_keys}')
                base_cfg_dict.update(c)

            # Substitute base variables from strings to their actual values
            cfg_dict = Config._substitute_base_vars(cfg_dict, base_var_dict,
                                                    base_cfg_dict)

            base_cfg_dict = Config._merge_a_into_b(cfg_dict, base_cfg_dict)
            cfg_dict = base_cfg_dict

            # merge cfg_text
            cfg_text_list.append(cfg_text)
            cfg_text = '\n'.join(cfg_text_list)

        return cfg_dict, cfg_text

最终返回值

#cfg_dict
{'model': 
{'type': 'Recognizer2D', 
'backbone': {...}, 
'cls_head': {...}, 
'train_cfg': None, 'test_cfg': {...}}, 
'optimizer': 
{'type': 'SGD', 
'constructor': 'TSMOptimizerConstructor',
'paramwise_cfg': {...}, 
'lr': 0.01, 
'momentum': 0.9, 
'weight_decay': 0.0001}, 
'optimizer_config': 
{'grad_clip': {...}}, 
'lr_config': 
{'policy': 'step', 'step': [...]}, 
'total_epochs': 50, 
'checkpoint_config': {'interval': 5}, 
'log_config': {'interval': 20, 'hooks': [...]}, 
'dist_params': {'backend': 'nccl'}, 
'log_level': 'INFO', 
'load_from': None, 'resume_from': None, 'workflow': [(...)], 
'opencv_num_threads': 0, 
'mp_start_method': 'fork', ...}

# cfg_text 返回配置文件的文本内容

4, Config中auto_argparser生成参数解析文件

Config (path: configs/recognition/tsm/tsm_r50_1x1x8_50e_kinetics400_rgb.py): {'model': {'type': 'Recognizer2D', 'backbone': {'type': 'ResNetTSM', 'pretrained': 'torchvision://resnet50', 'depth': 50, 'norm_eval': False, 'shift_div': 8}, 'cls_head': {'type': 'TSMHead', 'num_classes': 400, 'in_channels': 2048, 'spatial_type': 'avg', 'consensus': {'type': 'AvgConsensus', 'dim': 1}, 'dropout_ratio': 0.5, 'init_std': 0.001, 'is_shift': True}, 'train_cfg': None, 'test_cfg': {'average_clips': 'prob'}}, 'optimizer': {'type': 'SGD', 'constructor': 'TSMOptimizerConstructor', 'paramwise_cfg': {'fc_lr5': True}, 'lr': 0.01, 'momentum': 0.9, 'weight_decay': 0.0001}, 'optimizer_config': {'grad_clip': {'max_norm': 20, 'norm_type': 2}}, 'lr_config': {'policy': 'step', 'step': [20, 40]}, 'total_epochs': 50, 'checkpoint_config': {'interval': 5}, 'log_config': {'interval': 20, 'hooks': [{'type': 'TextLoggerHook'}]}, 'dist_params': {'backend': 'nccl'}, 'log_level': 'INFO', 'load_from': None, 'resume_from': None, 'workflow': [('train', 1)], 'opencv_num_threads': 0, 'mp_start_method': 'fork', 'dataset_type': 'RawframeDataset', 'data_root': 'data/kinetics400/rawframes_train', 'data_root_val': 'data/kinetics400/rawframes_val', 'ann_file_train': 'data/kinetics400/kinetics400_train_list_rawframes.txt', 'ann_file_val': 'data/kinetics400/kinetics400_val_list_rawframes.txt', 'ann_file_test': 'data/kinetics400/kinetics400_val_list_rawframes.txt', 'img_norm_cfg': {'mean': [123.675, 116.28, 103.53], 'std': [58.395, 57.12, 57.375], 'to_bgr': False}, 'train_pipeline': [{'type': 'SampleFrames', 'clip_len': 1, 'frame_interval': 1, 'num_clips': 8}, {'type': 'RawFrameDecode'}, {'type': 'Resize', 'scale': (-1, 256)}, {'type': 'MultiScaleCrop', 'input_size': 224, 'scales': (1, 0.875, 0.75, 0.66), 'random_crop': False, 'max_wh_scale_gap': 1, 'num_fixed_crops': 13}, {'type': 'Resize', 'scale': (224, 224), 'keep_ratio': False}, {'type': 'Flip', 'flip_ratio': 0.5}, {'type': 'Normalize', 'mean': [123.675, 116.28, 103.53], 'std': [58.395, 57.12, 57.375], 'to_bgr': False}, {'type': 'FormatShape', 'input_format': 'NCHW'}, {'type': 'Collect', 'keys': ['imgs', 'label'], 'meta_keys': []}, {'type': 'ToTensor', 'keys': ['imgs', 'label']}], 'val_pipeline': [{'type': 'SampleFrames', 'clip_len': 1, 'frame_interval': 1, 'num_clips': 8, 'test_mode': True}, {'type': 'RawFrameDecode'}, {'type': 'Resize', 'scale': (-1, 256)}, {'type': 'CenterCrop', 'crop_size': 224}, {'type': 'Normalize', 'mean': [123.675, 116.28, 103.53], 'std': [58.395, 57.12, 57.375], 'to_bgr': False}, {'type': 'FormatShape', 'input_format': 'NCHW'}, {'type': 'Collect', 'keys': ['imgs', 'label'], 'meta_keys': []}, {'type': 'ToTensor', 'keys': ['imgs']}], 'test_pipeline': [{'type': 'SampleFrames', 'clip_len': 1, 'frame_interval': 1, 'num_clips': 8, 'test_mode': True}, {'type': 'RawFrameDecode'}, {'type': 'Resize', 'scale': (-1, 256)}, {'type': 'CenterCrop', 'crop_size': 224}, {'type': 'Normalize', 'mean': [123.675, 116.28, 103.53], 'std': [58.395, 57.12, 57.375], 'to_bgr': False}, {'type': 'FormatShape', 'input_format': 'NCHW'}, {'type': 'Collect', 'keys': ['imgs', 'label'], 'meta_keys': []}, {'type': 'ToTensor', 'keys': ['imgs']}], 'data': {'videos_per_gpu': 8, 'workers_per_gpu': 2, 'test_dataloader': {'videos_per_gpu': 1}, 'train': {'type': 'RawframeDataset', 'ann_file': 'data/kinetics400/kinetics400_train_list_rawframes.txt', 'data_prefix': 'data/kinetics400/rawframes_train', 'pipeline': [{'type': 'SampleFrames', 'clip_len': 1, 'frame_interval': 1, 'num_clips': 8}, {'type': 'RawFrameDecode'}, {'type': 'Resize', 'scale': (-1, 256)}, {'type': 'MultiScaleCrop', 'input_size': 224, 'scales': (1, 0.875, 0.75, 0.66), 'random_crop': False, 'max_wh_scale_gap': 1, 'num_fixed_crops': 13}, {'type': 'Resize', 'scale': (224, 224), 'keep_ratio': False}, {'type': 'Flip', 'flip_ratio': 0.5}, {'type': 'Normalize', 'mean': [123.675, 116.28, 103.53], 'std': [58.395, 57.12, 57.375], 'to_bgr': False}, {'type': 'FormatShape', 'input_format': 'NCHW'}, {'type': 'Collect', 'keys': ['imgs', 'label'], 'meta_keys': []}, {'type': 'ToTensor', 'keys': ['imgs', 'label']}]}, 'val': {'type': 'RawframeDataset', 'ann_file': 'data/kinetics400/kinetics400_val_list_rawframes.txt', 'data_prefix': 'data/kinetics400/rawframes_val', 'pipeline': [{'type': 'SampleFrames', 'clip_len': 1, 'frame_interval': 1, 'num_clips': 8, 'test_mode': True}, {'type': 'RawFrameDecode'}, {'type': 'Resize', 'scale': (-1, 256)}, {'type': 'CenterCrop', 'crop_size': 224}, {'type': 'Normalize', 'mean': [123.675, 116.28, 103.53], 'std': [58.395, 57.12, 57.375], 'to_bgr': False}, {'type': 'FormatShape', 'input_format': 'NCHW'}, {'type': 'Collect', 'keys': ['imgs', 'label'], 'meta_keys': []}, {'type': 'ToTensor', 'keys': ['imgs']}]}, 'test': {'type': 'RawframeDataset', 'ann_file': 'data/kinetics400/kinetics400_val_list_rawframes.txt', 'data_prefix': 'data/kinetics400/rawframes_val', 'pipeline': [{'type': 'SampleFrames', 'clip_len': 1, 'frame_interval': 1, 'num_clips': 8, 'test_mode': True}, {'type': 'RawFrameDecode'}, {'type': 'Resize', 'scale': (-1, 256)}, {'type': 'CenterCrop', 'crop_size': 224}, {'type': 'Normalize', 'mean': [123.675, 116.28, 103.53], 'std': [58.395, 57.12, 57.375], 'to_bgr': False}, {'type': 'FormatShape', 'input_format': 'NCHW'}, {'type': 'Collect', 'keys': ['imgs', 'label'], 'meta_keys': []}, {'type': 'ToTensor', 'keys': ['imgs']}]}}, 'evaluation': {'interval': 5, 'metrics': ['top_k_accuracy', 'mean_class_accuracy']}, 'work_dir': './work_dirs/tsm_r50_1x1x8_100e_kinetics400_rgb/'}

5,cfg.merge_from_dict(args.cfg_options)

加载参数配置到py文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: mmcv config是一个用于管理深度学习模型配置文件的工具。它是开源项目MMCV(OpenMMLab Computer Vision Foundation)中的一个重要组件。 在深度学习中,模型的配置是一项非常关键的工作。通常一个深度学习模型包含了很多超参数和配置选项,这些参数和选项的设置会直接影响到模型的性能和训练结果。而mmcv config就是为了更好地管理和调整这些配置而设计的。 mmcv config采用了Python语言来编写配置文件。它提供了一个统一的配置语法和结构,让用户可以方便地定义和修改模型的各种参数和选项。使用mmcv config,用户只需要简单地编辑一个Python类,就可以完成对模型配置的定义。 mmcv config还提供了一系列的配置选项和默认值,可以大大简化模型配置的工作。用户只需要根据自己的需求修改相关的参数和选项,就可以快速地完成一个基础模型的配置。此外,mmcv config还支持继承和覆盖,用户可以基于已有的配置文件,灵活地建立自己的配置文件。 使用mmcv config,用户可以更加高效地管理和调整模型的参数和选项。这不仅有助于快速开发和迭代模型,也方便了模型的复现和共享。同时,mmcv config还提供了丰富的文档和示例,帮助用户更好地理解和使用这个工具。 总而言之,mmcv config是一个强大而灵活的深度学习模型配置工具,它提供了统一的配置语法和结构,简化了模型配置的工作,帮助用户更高效地管理和调整模型参数和选项。 ### 回答2: mmcv config是一个用于配置模型和训练过程的工具包。它是开源计算机视觉框架mmdetection中的重要组成部分。mmcv config提供了一种灵活而简洁的方式来定义模型架构、数据增强、优化器设置等,并且可以通过配置文件轻松修改这些设置。 通过mmcv config,我们可以通过简单地修改一个或多个配置文件来实现不同的训练和测试设置。例如,我们可以轻松地更改模型的深度和宽度,调整训练周期和学习率,选择适合的数据增强策略等。 mmcv config使用了Python配置文件格式,通过嵌套的字典和列表来定义各种模型和训练参数的设置。配置文件包括了多个部分,如模型、数据集、训练器和优化器等。 使用mmcv config的过程很简单。首先,我们需要创建一个配置文件,并根据需求修改其中的参数。然后,我们可以使用mmcv的工具函数来加载配置文件加载后的配置文件可以作为训练或测试的输入,以实现我们定义的模型和训练设置。 mmcv config的优势之一是它的可扩展性和灵活性。我们可以根据需要添加自定义模型、损失函数、数据增强策略等,并用它们来扩展现有的配置文件。此外,mmcv config还可以与其他计算机视觉库和工具无缝集成,如PyTorch、TensorFlow等。 总之,mmcv config是一个强大的用于配置模型和训练过程的工具包。它提供了简单易用的接口,使得配置和修改模型变得更加方便和高效。使用mmcv config,我们可以轻松地定制符合自己需求的计算机视觉模型。 ### 回答3: mmcv config是一个用于配置和管理深度学习模型的库。mmcv是开源的,并且被广泛用于各种计算机视觉领域的项目中。 mmcv config提供了一个灵活的配置文件格式,以便用户可以方便地定义和调整模型的各种参数。通过配置文件,用户可以定义模型的结构、损失函数、优化器、学习率策略等等。这使得用户能够轻松地根据需要进行模型调整和实验。 使用mmcv config进行模型配置有以下几个主要步骤: 1. 创建一个配置文件:用户需要创建一个新的配置文件,以便定义模型的各个参数。配置文件可以使用YAML格式,这样它既易于阅读又易于书写。 2. 定义模型结构:在配置文件中,用户可以指定模型的结构,定义层、卷积核大小、激活函数等等。 3. 配置数据预处理:配置文件还可以定义数据预处理的方法,比如数据增强、归一化、裁剪等等。这些预处理方法将在训练和推理过程中应用到输入数据上。 4. 设定超参数:用户可以在配置文件中设定模型的超参数,比如学习率、训练轮数、batch size等等。这些超参数会影响模型的训练和性能。 5. 运行训练或推理代码:一旦配置文件准备好,用户可以将其传递给mmcv库中的相应函数,从而开始训练或推理过程。 总的来说,mmcv config是一个强大的工具,使得模型配置变得简单和可维护。它支持各种常见的模型和任务,如目标检测、图像分割和姿态估计等等。无论是学术界还是工业界,mmcv config都是一个不可或缺的工具,用于快速构建和调整深度学习模型
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值