logger.info(f'load model from: {self.pretrained}')

时间: 2023-06-19 08:06:41 浏览: 44
这行代码是使用 Python 的 logging 模块记录程序运行信息。在这里,记录了模型加载的信息,即从哪里加载预训练模型。其中,f-string 是一种Python 3.6及以上版本中的字符串格式化方式,用于将表达式嵌入到字符串中,以方便输出变量等信息。在这里,使用了 f-string 来输出 self.pretrained 变量的值。
相关问题

logger = get_root_logger() logger.info(f'load model from: {self.pretrained}')

这段代码是使用Python logging模块中的get_root_logger函数来获取一个logger对象,然后使用该logger对象记录一条INFO级别的日志,日志内容为"load model from: {self.pretrained}",其中self.pretrained是一个变量,表示预训练模型的路径。这个日志信息可以用来跟踪程序运行过程中的关键信息,以便于后续的调试和分析。

if pretrained: self.pretrained = pretrained if isinstance(self.pretrained, str): self.apply(_init_weights) logger = get_root_logger() logger.info(f'load model from: {self.pretrained}') checkpoint = torch.load(self.pretrained, map_location='cpu') state_dict = checkpoint['model'] state_dict['patch_embed.proj.weight'] = state_dict['patch_embed.proj.weight'].unsqueeze(2).repeat(1,1,self.patch_size[0],1,1) / self.patch_size[0]

这段代码是在构建模型时,如果预训练参数存在,则加载预训练参数。首先检查预训练参数是否为字符串类型,如果是,则调用_init_weights函数对模型参数进行初始化,并打印日志信息。然后使用torch.load函数加载预训练参数,其中map_location参数指定了将预训练参数加载到CPU上。接下来获取预训练参数中的模型参数,并将patch_embed.proj.weight参数重复扩展到与输入图像的分辨率相同,以便进行卷积操作。最后将参数除以patch_size[0]以进行归一化处理。

相关推荐

class PrototypicalCalibrationBlock: def __init__(self, cfg): super().__init__() self.cfg = cfg self.device = torch.device(cfg.MODEL.DEVICE) self.alpha = self.cfg.TEST.PCB_ALPHA self.imagenet_model = self.build_model() self.dataloader = build_detection_test_loader(self.cfg, self.cfg.DATASETS.TRAIN[0]) self.roi_pooler = ROIPooler(output_size=(1, 1), scales=(1 / 32,), sampling_ratio=(0), pooler_type="ROIAlignV2") self.prototypes = self.build_prototypes() self.exclude_cls = self.clsid_filter() def build_model(self): logger.info("Loading ImageNet Pre-train Model from {}".format(self.cfg.TEST.PCB_MODELPATH)) if self.cfg.TEST.PCB_MODELTYPE == 'resnet': imagenet_model = resnet101() else: raise NotImplementedError state_dict = torch.load(self.cfg.TEST.PCB_MODELPATH) imagenet_model.load_state_dict(state_dict) imagenet_model = imagenet_model.to(self.device) imagenet_model.eval() return imagenet_model def build_prototypes(self): all_features, all_labels = [], [] for index in range(len(self.dataloader.dataset)): inputs = [self.dataloader.dataset[index]] assert len(inputs) == 1 # load support images and gt-boxes img = cv2.imread(inputs[0]['file_name']) # BGR img_h, img_w = img.shape[0], img.shape[1] ratio = img_h / inputs[0]['instances'].image_size[0] inputs[0]['instances'].gt_boxes.tensor = inputs[0]['instances'].gt_boxes.tensor * ratio boxes = [x["instances"].gt_boxes.to(self.device) for x in inputs] # extract roi features features = self.extract_roi_features(img, boxes) all_features.append(features.cpu().data) gt_classes = [x['instances'].gt_classes for x in inputs] all_labels.append(gt_classes[0].cpu().data)

TypeError Traceback (most recent call last) /tmp/ipykernel_1045/245448921.py in <module> 1 dataset_path = ABSADatasetList.Restaurant14 ----> 2 sent_classifier = Trainer(config=apc_config_english, 3 dataset=dataset_path, # train set and test set will be automatically detected 4 checkpoint_save_mode=1, # =None to avoid save model 5 auto_device=True # automatic choose CUDA or CPU /tmp/ipykernel_1045/296492999.py in __init__(self, config, dataset, from_checkpoint, checkpoint_save_mode, auto_device) 84 config.model_path_to_save = None 85 ---> 86 self.train() 87 88 def train(self): /tmp/ipykernel_1045/296492999.py in train(self) 96 config.seed = s 97 if self.checkpoint_save_mode: ---> 98 model_path.append(self.train_func(config, self.from_checkpoint, self.logger)) 99 else: 100 # always return the last trained model if dont save trained model /tmp/ipykernel_1045/4269211813.py in train4apc(opt, from_checkpoint_path, logger) 494 load_checkpoint(trainer, from_checkpoint_path) 495 --> 496 return trainer.run() /tmp/ipykernel_1045/4269211813.py in run(self) 466 criterion = nn.CrossEntropyLoss() 467 self._reset_params() --> 468 return self._train(criterion) 469 470 /tmp/ipykernel_1045/4269211813.py in _train(self, criterion) 153 return self._k_fold_train_and_evaluate(criterion) 154 else: --> 155 return self._train_and_evaluate(criterion) 156 157 def _train_and_evaluate(self, criterion): /tmp/ipykernel_1045/4269211813.py in _train_and_evaluate(self, criterion) 190 191 for epoch in range(self.opt.num_epoch): --> 192 iterator = tqdm(self.train_dataloaders[0]) 193 for i_batch, sample_batched in enumerate(iterator): 194 global_step += 1 TypeError: 'module' object is not callable

Traceback (most recent call last): File "DT_001_X01_P01.py", line 150, in DT_001_X01_P01.Module.load_model File "/home/kejia/Server/tf/Bin_x64/DeepLearning/DL_Lib_02/mmdet/apis/inference.py", line 42, in init_detector checkpoint = load_checkpoint(model, checkpoint, map_location=map_loc) File "/home/kejia/Server/tf/Bin_x64/DeepLearning/DL_Lib_02/mmcv/runner/checkpoint.py", line 529, in load_checkpoint checkpoint = _load_checkpoint(filename, map_location, logger) File "/home/kejia/Server/tf/Bin_x64/DeepLearning/DL_Lib_02/mmcv/runner/checkpoint.py", line 467, in _load_checkpoint return CheckpointLoader.load_checkpoint(filename, map_location, logger) File "/home/kejia/Server/tf/Bin_x64/DeepLearning/DL_Lib_02/mmcv/runner/checkpoint.py", line 244, in load_checkpoint return checkpoint_loader(filename, map_location) File "/home/kejia/Server/tf/Bin_x64/DeepLearning/DL_Lib_02/mmcv/runner/checkpoint.py", line 261, in load_from_local checkpoint = torch.load(filename, map_location=map_location) File "torch/serialization.py", line 594, in load return _load(opened_zipfile, map_location, pickle_module, **pickle_load_args) File "torch/serialization.py", line 853, in _load result = unpickler.load() File "torch/serialization.py", line 845, in persistent_load load_tensor(data_type, size, key, _maybe_decode_ascii(location)) File "torch/serialization.py", line 834, in load_tensor loaded_storages[key] = restore_location(storage, location) File "torch/serialization.py", line 175, in default_restore_location result = fn(storage, location) File "torch/serialization.py", line 157, in _cuda_deserialize return obj.cuda(device) File "torch/_utils.py", line 71, in _cuda with torch.cuda.device(device): File "torch/cuda/__init__.py", line 225, in __enter__ self.prev_idx = torch._C._cuda_getDevice() File "torch/cuda/__init__.py", line 164, in _lazy_init "Cannot re-initialize CUDA in forked subprocess. " + msg) RuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the 'spawn' start method ('异常抛出', None) DT_001_X01_P01 load_model ret=1, version=V1.0.0.0

最新推荐

recommend-type

ansys maxwell

ansys maxwell
recommend-type

matlab基于不确定性可达性优化的自主鲁棒操作.zip

matlab基于不确定性可达性优化的自主鲁棒操作.zip
recommend-type

pytest-2.8.0.zip

文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。
recommend-type

信息安全课程实验C++实现DES等算法源代码

信息安全课程实验C++实现DES等算法源代码
recommend-type

基于知识图谱的医疗诊断知识问答系统python源码+项目说明.zip

环境 python >= 3.6 pyahocorasick==1.4.2 requests==2.25.1 gevent==1.4.0 jieba==0.42.1 six==1.15.0 gensim==3.8.3 matplotlib==3.1.3 Flask==1.1.1 numpy==1.16.0 bert4keras==0.9.1 tensorflow==1.14.0 Keras==2.3.1 py2neo==2020.1.1 tqdm==4.42.1 pandas==1.0.1 termcolor==1.1.0 itchat==1.3.10 ahocorasick==0.9 flask_compress==1.9.0 flask_cors==3.0.10 flask_json==0.3.4 GPUtil==1.4.0 pyzmq==22.0.3 scikit_learn==0.24.1 效果展示 为能最简化使用该系统,不需要繁杂的部署各种七七八八的东西,当前版本使用的itchat将问答功能集成到微信做演示,这需要你的微信能登入网页微信才能使用itchat;另外对话上下文并没
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

2. 通过python绘制y=e-xsin(2πx)图像

可以使用matplotlib库来绘制这个函数的图像。以下是一段示例代码: ```python import numpy as np import matplotlib.pyplot as plt def func(x): return np.exp(-x) * np.sin(2 * np.pi * x) x = np.linspace(0, 5, 500) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('y = e^{-x} sin(2πx)') plt.show() ``` 运行这段
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。