亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Pytorch 中創建自定義數據加載器?

如何在 Pytorch 中創建自定義數據加載器?

MMMHUHU 2023-03-16 15:33:39
我有一個包含圖像路徑的文件,我想加載到 Pytorch 中,同時利用內置的數據加載器功能(多進程加載管道、數據擴充等)。def create_links():    data_dir = "/myfolder"    full_path_list = []    assert os.path.isdir(data_dir)    for _, _, filenames in os.walk(data_dir):        for filename in filenames:            full_path_list.append(os.path.join(data_dir, filename))    with open(config.data.links_file, 'w+') as links_file:        for full_path in full_path_list:            links_file.write(f"{full_path}\n")def read_links_file_to_list():    config = ConfigProvider.config()    links_file_path = config.data.links_file    if not os.path.isfile(links_file_path):        raise RuntimeError("did you forget to create a file with links to images? Try using 'create_links()'")    with open(links_file_path, 'r') as links_file:        return links_file.readlines()所以我有一個文件列表(或一個生成器,或任何有效的東西)file_list = read_links_file_to_list(),.我如何圍繞它構建一個 Pytorch 數據加載器,我將如何使用它?
查看完整描述

1 回答

?
MYYA

TA貢獻1868條經驗 獲得超4個贊

你想要的是一個Custom Dataset。該__getitem__方法是您應用數據增強等轉換的地方。為了讓您了解它在實踐中的樣子,您可以看看我前幾天寫的這個自定義數據集:


class GTSR43Dataset(Dataset):

    """German Traffic Sign Recognition dataset."""

    def __init__(self, root_dir, train_file, transform=None):

        self.root_dir = root_dir

        self.train_file_path = train_file

        self.label_df = pd.read_csv(os.path.join(self.root_dir, self.train_file_path))

        self.transform = transform

        self.classes = list(self.label_df['ClassId'].unique())


    def __getitem__(self, idx):

        """Return (image, target) after resize and preprocessing."""

        img = os.path.join(self.root_dir, self.label_df.iloc[idx, 7])

        

        X = Image.open(img)

        y = self.class_to_index(self.label_df.iloc[idx, 6])


        if self.transform:

            X = self.transform(X)


        return X, y

    

    def class_to_index(self, class_name):

        """Returns the index of a given class."""

        return self.classes.index(class_name)

    

    def index_to_class(self, class_index):

        """Returns the class of a given index."""

        return self.classes[class_index] 

    

    def get_class_count(self):

        """Return a list of label occurences"""

        cls_count = dict(self.label_df.ClassId.value_counts())

#         cls_percent = list(map(lambda x: (1 - x / sum(cls_count)), cls_count))

        return cls_count

    

    def __len__(self):

        """Returns the length of the dataset."""

        return len(self.label_df)


查看完整回答
反對 回復 2023-03-16
  • 1 回答
  • 0 關注
  • 130 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號