Python 将图像数据从pandas加载到pytorch

Python 将图像数据从pandas加载到pytorch,python,pandas,deep-learning,pytorch,Python,Pandas,Deep Learning,Pytorch,我是pytorch的新手,以前曾在keras和fastai工作过。 目前正在尝试图像回归任务,挑战是我必须从pandas dataframe加载数据。 数据帧结构: ID Path Score fig1 /folder/fig1.jpg 2 fig2 /folder/fig2.jpg 3 ..... 我以前曾直接从文件夹将图像加载到pytorch,因为这是一项简单的分类任务,但现在有点卡住了 我查看了pytorch论坛,但不知道如何实现。 任何帮助都将不胜感激。数据集 您必须使

我是pytorch的新手,以前曾在keras和fastai工作过。 目前正在尝试图像回归任务,挑战是我必须从pandas dataframe加载数据。 数据帧结构:

ID   Path   Score
fig1  /folder/fig1.jpg  2
fig2  /folder/fig2.jpg  3
.....
我以前曾直接从文件夹将图像加载到pytorch,因为这是一项简单的分类任务,但现在有点卡住了

我查看了pytorch论坛,但不知道如何实现。 任何帮助都将不胜感激。

数据集 您必须使用
torch.utils.data.Dataset
结构来定义它。 下面是如何在普通的
pytorch
中执行此操作(我使用
pillow
加载图像并
torchvision
将其转换为
torch.Tensor
对象):

或者,您可以使用(免责声明:无耻的自我宣传,因为我是作者…),它允许您将
路径
分数
解耦如下:

import torchvision
from PIL import Image

import torchdata


class ImageDataset(torchdata.datasets.FilesDataset):
    def __getitem__(self, index):
        return Image.open(self.files[index])


class Labels(torchdata.Dataset):
    def __init__(self, scores):
        super().__init__()
        self.scores = scores

    def __len__(self):
        return len(self.scores)

    def __getitem__(self, index):
        return self.scores[index]

# to_numpy for convenience
# I assume all your images are in /folder and have *.jpg extension
dataset = ImageDataset.from_folder("/folder", regex="*.jpg").map(
    torchvision.transforms.ToTensor()
) | Labels(dataframe["Score"].to_numpy())
dataloader = torch.utils.data.DataLoader(dataset, batch_size=64, shuffle=True)

for images, scores in dataloader:
    # Rest of your code to train neural network or smth
    ...
(或者您可以像在常规的
pytorch
中一样实现它,但是继承自
torchdata.Dataset
并在构造函数中调用
super()。\uuuuu init\uuuu()

torchdata
允许您轻松缓存图像,或通过
.map
应用一些其他转换,如图所示,或在注释中询问

数据加载器 无论您选择哪种方式,都应该将数据集包装在
torch.utils.data.DataLoader
中,以创建批并对其进行迭代,如下所示:

import torchvision
from PIL import Image

import torchdata


class ImageDataset(torchdata.datasets.FilesDataset):
    def __getitem__(self, index):
        return Image.open(self.files[index])


class Labels(torchdata.Dataset):
    def __init__(self, scores):
        super().__init__()
        self.scores = scores

    def __len__(self):
        return len(self.scores)

    def __getitem__(self, index):
        return self.scores[index]

# to_numpy for convenience
# I assume all your images are in /folder and have *.jpg extension
dataset = ImageDataset.from_folder("/folder", regex="*.jpg").map(
    torchvision.transforms.ToTensor()
) | Labels(dataframe["Score"].to_numpy())
dataloader = torch.utils.data.DataLoader(dataset, batch_size=64, shuffle=True)

for images, scores in dataloader:
    # Rest of your code to train neural network or smth
    ...
在循环中处理这些图像和分数