pytorch 使用Transformers中的image_utils时出现“不支持的图像维数”

hgqdbh6s  于 2023-01-26  发布在  其他
关注(0)|答案(1)|浏览(603)

我正在尝试遵循此HuggingFace教程https://huggingface.co/blog/fine-tune-vit
使用他们的“bean”数据集一切正常,但如果我使用自己的数据集和自己的图像,我会点击“不支持的图像维数”。我想知道这里是否有人会有如何调试这个问题的指针。

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_2042949/883871373.py in <module>
----> 1 train_results = trainer.train()
      2 trainer.save_model()
      3 trainer.log_metrics("train", train_results.metrics)
      4 trainer.save_metrics("train", train_results.metrics)
      5 trainer.save_state()

~/miniconda3/lib/python3.9/site-packages/transformers/trainer.py in train(self, resume_from_checkpoint, trial, ignore_keys_for_eval, **kwargs)
   1532             self._inner_training_loop, self._train_batch_size, args.auto_find_batch_size
   1533         )
-> 1534         return inner_training_loop(
   1535             args=args,
   1536             resume_from_checkpoint=resume_from_checkpoint,

~/miniconda3/lib/python3.9/site-packages/transformers/trainer.py in _inner_training_loop(self, batch_size, args, resume_from_checkpoint, trial, ignore_keys_for_eval)
   1754 
   1755             step = -1
-> 1756             for step, inputs in enumerate(epoch_iterator):
   1757 
   1758                 # Skip past any already trained steps if resuming training

~/miniconda3/lib/python3.9/site-packages/torch/utils/data/dataloader.py in __next__(self)
    626                 # TODO(https://github.com/pytorch/pytorch/issues/76750)
...
--> 119         raise ValueError(f"Unsupported number of image dimensions: {image.ndim}")
    120 
    121     if image.shape[first_dim] in (1, 3):

ValueError: Unsupported number of image dimensions: 2

https://github.com/huggingface/transformers/blob/main/src/transformers/image_utils.py
我试着看看我和他们的数据的形状,结果是一样的。

$ prepared_ds['train'][0:2]['pixel_values'].shape
torch.Size([2, 3, 224, 224])

我跟踪堆栈跟踪,发现错误出在infer_channel_dimension_format函数中,所以我编写了以下代码来查找有问题的映像:

from transformers.image_utils import infer_channel_dimension_format
try:
    for i, img in enumerate(prepared_ds["train"]):
        infer_channel_dimension_format(img["pixel_values"])
except ValueError as ve:
    print(i+1)

当我检查那个图像时,我看到它不像其他图像那样是RGB的。

$ ds["train"][8]
{'image': <PIL.JpegImagePlugin.JpegImageFile image mode=L size=390x540>,
 'image_file_path': '/data/alamy/img/00000/000001069.jpg',
 'labels': 0}

因此,我的解决方案是在转换中添加一个convert('RGB')

def transform(example_batch):
    # Take a list of PIL images and turn them to pixel values
    inputs = feature_extractor([x.convert("RGB") for x in example_batch['image']], return_tensors='pt')

    # Don't forget to include the labels!
    inputs['labels'] = example_batch['labels']
    return inputs

我会找时间回到这里,用一个完全可复制的例子来清理这个问题。

qpgpyjmq

qpgpyjmq1#

我今天也遇到了同样的错误,使用校对功能后,上述错误得到了解决。

def collate_fn(batch):
    return {
        'pixel_values': torch.stack([x['pixel_values'] for x in batch]),
        'labels': torch.tensor([x['labels'] for x in batch])
    }

相关问题