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

Posted CV-杨帆

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了02google 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

以上是关于02google Colab |pytorch Dataset类代码实战 免费GPU google Colaboratory 使用教程的主要内容,如果未能解决你的问题,请参考以下文章

如何确保所有 PyTorch 代码充分利用 Google Colab 上的 GPU

Google Colab 中的不完整图表

如何使用opencv在google colab上播放视频?

链接到 google colab 项目,以便学生必须复制和修改

如何在 google colab 中运行 matlab .m 文件

Pytorch transforms.RandomRotation() 在 Google Colab 上不起作用