为什么Pytorch中打印语句有时无法打印?

问题描述 投票:0回答:2

我正在使用 pycocotools 库,并实现 DETR(用于对象检测的可变形变压器)。

我正在调试代码的一部分,该代码调用[此处][1]找到的 loadRes 函数。

我在行前和行后添加了打印语句

res = COCO()
,因为这条线
 res.dataset['images'] = [img for img in self.dataset['images']]
给出错误 (
AttributeError: 'NoneType' object has no attribute 'dataset'
)。

当我尝试跟踪代码并找到

res
的当前值(特别是为什么它是 None)时,我注意到我的打印语句没有出现在输出中,尽管在回溯中明显存在.

为什么会发生这种情况?

AttributeError                            Traceback (most recent call last)
<ipython-input-4-ff0c7180ea84> in <module>
    175 
--> 176     test_stats, coco_evaluator = evaluate(
    177         model, criterion, postprocessors, data_loader_val, base_ds, "cuda", args["output_dir"]
    178     )

~/anaconda3/lib/python3.8/site-packages/torch/autograd/grad_mode.py in decorate_context(*args, **kwargs)
     25         def decorate_context(*args, **kwargs):
     26             with self.clone():
---> 27                 return func(*args, **kwargs)
     28         return cast(F, decorate_context)
     29 

~/Desktop/traffic_sign_relevance-main/attention/engine.py in evaluate(model, criterion, postprocessors, data_loader, base_ds, device, output_dir)
    128         res = {target['image_id'].item(): output for target, output in zip(targets, results)}
    129         if coco_evaluator is not None:
--> 130             coco_evaluator.update(res)
    131 
    132         if panoptic_evaluator is not None:

~/Desktop/traffic_sign_relevance-main/attention/datasets/coco_eval.py in update(self, predictions)
     52             with open(os.devnull, 'w') as devnull:
     53                 with contextlib.redirect_stdout(devnull):
---> 54                     coco_dt = COCO.loadRes(self.coco_gt, results) if results else COCO()
     55             coco_eval = self.coco_eval[iou_type]
     56 

~/anaconda3/lib/python3.8/site-packages/pycocotools/coco.py in loadRes(self, resFile)
    316         print("In loadRes")
    317         print(type(res))
--> 318         res.dataset['images'] = [img for img in self.dataset['images']]
    319 
    320         print('Loading and preparing results...')

AttributeError: 'NoneType' object has no attribute 'dataset' ```




  [1]: https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocotools/coco.py
python pytorch nonetype
2个回答
0
投票

也许您的笔记本阻止在已安装的包内打印语句?


0
投票

发生这种情况是因为第 52、53 行阻止了 pycocotools 打印。如果您注释掉块 52-54 并从像

这样的块中取出 coco_dt = ...
 51             """
 52             with open(os.devnull, 'w') as devnull:
 53                 with contextlib.redirect_stdout(devnull):
 54                     coco_dt = COCO.loadRes(self.coco_gt, results) if results else COCO() 
 55             """
 56             coco_dt = COCO.loadRes(self.coco_gt, results) if results else COCO()
 57             coco_eval = self.coco_eval[iou_type]

您的打印报表将显示在屏幕上。

© www.soinside.com 2019 - 2024. All rights reserved.