【02】google Colab |pytorch Dataset类代码实战 免费GPU google Colaboratory 使用教程

0 前言

接着上一篇:【01】google Colab 使用教程 免费GPU google Colaboratory 上运行 pytorch tensorboard

这次要说的是Dataset类代码实战,还是在google Colab (免费GPU)上操作。
b站操作视频:https://www.bilibili.com/video/BV1W8411W7d1/

1 数据集下载

需要提前准备的数据(准备了多个链接,防止失效):
1,百度云,蚂蚁蜜蜂/练手数据集:链接: https://pan.baidu.com/s/1jZoTmoFzaTLWh4lKBHVbEA 密码: 5suq
2,阿里云,https://www.aliyundrive.com/s/Ahspi5UMiaf
3,google云,https://drive.google.com/drive/folders/10BZPGiBGMgDSpI5jeLsUUViQ3uEST3b_?usp=sharing

2 代码

入口:https://drive.google.com/drive/my-drive

代码:

# Mount google drive
from google.colab import drive
drive.flush_and_unmount()
drive.mount('/content/drive', force_remount=False)

from torch.utils.data import Dataset
help(Dataset)
from torch.utils.data import Dataset
import os
import cv2 as cv
from PIL import Image
import matplotlib.pyplot as plt

class MyData(Dataset):
  def __init__(self, root_dir, label_dir):
    self.root_dir = root_dir
    self.label_dir = label_dir 
    self.path = os.path.join(self.root_dir, self.label_dir)
    self.img_path = os.listdir(self.path)
  
  def __getitem__(self, index):
    img_name = self.img_path[index]
    img_item_path = os.path.join(self.root_dir, self.label_dir, img_name)
    img = Image.open(img_item_path)
    label = self.label_dir
    return img,label
  def __len__(self):
    return len(self.img_path)

root_dir = './drive/MyDrive/AI/hymenoptera_data/train/'
ants_label_dir = "ants"
ants_dataset = MyData(root_dir,ants_label_dir)

img,label = ants_dataset[0]
plt.imshow(img)
plt.show()
label

root_dir = './drive/MyDrive/AI/hymenoptera_data/train/'
ants_label_dir = "bees"
ants_dataset = MyData(root_dir,ants_label_dir)

img,label = ants_dataset[0]
plt.imshow(img)
plt.show()
label
ls ./drive/MyDrive/AI/hymenoptera_data/train/

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

4 参考

P6. Dataset类代码实战:https://www.bilibili.com/video/BV1hE411t7RN?p=7

猜你喜欢

转载自blog.csdn.net/WhiffeYF/article/details/127247608