pytorch 如何处理这样的索引类型错误?

rta7y2nd  于 2023-05-17  发布在  其他
关注(0)|答案(1)|浏览(210)

当训练论文Estimating People Flows to Better Count Them in Crowded Scenes的数据时,index = int(img_name.split('.')[0])出现了一些问题,如图片所示,index 130(1)无法更改为int类型,它说'invalid literal for int()with base '130(1)。
奇怪的是,我已经多次运行这段代码了,但是在我运行它的前几次,它说问题是'invalid literal for int()with base '049(1)'
以下是详细信息:

Traceback (most recent call last):
  File "train.py", line 253, in <module>
    main()
  File "train.py", line 58, in main
    train(train_list, model, criterion, optimizer, epoch)
  File "train.py", line 91, in train
    for i,(prev_img, img, post_img, prev_target, target, post_target ) in enumerate(train_loader):
  File "/root/miniconda3/lib/python3.8/site-packages/torch/utils/data/dataloader.py", line 435, in __next__
    data = self._next_data()
  File "/root/miniconda3/lib/python3.8/site-packages/torch/utils/data/dataloader.py", line 475, in _next_data
    data = self._dataset_fetcher.fetch(index)  # may raise StopIteration
  File "/root/miniconda3/lib/python3.8/site-packages/torch/utils/data/_utils/fetch.py", line 44, in fetch
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "/root/miniconda3/lib/python3.8/site-packages/torch/utils/data/_utils/fetch.py", line 44, in <listcomp>
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "/root/autodl-tmp/project/dataset.py", line 30, in __getitem__
    prev_img,img,post_img,prev_target, target, post_target = load_data(img_path,self.train)
  File "/root/autodl-tmp/project/image.py", line 12, in load_data
    index = int(img_name.split('.')[0])
ValueError: invalid literal for int() with base 10: '49(1)'

原始代码的一部分:

def load_data(img_path,train = True):
   img_folder = os.path.dirname(img_path)
   img_name = os.path.basename(img_path)
   # print(img_name.split('.')[0])
   index = int(img_name.split('.')[0]) #

如何处理问题并成功训练模型?我唯一的方法是直接修改数据集中图像的标签吗?
我首先尝试用“000”这样的数字替换“(”和“)”,但我很快意识到这会导致索引和标签之间的不匹配。当我试图根据索引找到图像时

我找不到名字是49(1)和130(1)的人。

ax6ht2ek

ax6ht2ek1#

错误消息中提到的问题:

File "/root/autodl-tmp/project/image.py", line 12, in load_data index = int(img_name.split('.')[0]) ValueError: invalid literal for int() with base 10: '130(1)'

字面上的意思是有一个无效的字符,不能转换为整数,在这种情况下,它是括号。
如果你想得到值的第一部分(49),你可以像这样用字符(分割:

def load_data(img_path,train = True):
   ...
   value = img_name.split('.')[0]
   if not value.isdecimal():
      value = value.split('(')[0]
   index = int(value)

相关问题