resnet(5)------pytorch中Dataset类的使用

1 . 安装pytorch

首先要确保你已经安装了Anaconda的环境,具体安装方法可以参照如下链接:

https://blog.csdn.net/weixin_42855758/article/details/122795125

然后就进入正式的安装步骤了。

  1. 创建一个新的虚拟环境(这里建议就叫pytorch),方便以后进入。
conda create -n pytorch python=3.8 #可以根据需求更改python环境
  1. 激活该环境
activate pytorch
  1. 安装pytorch
    这里要进入pytorch的官网(https://pytorch.org/),根据自己电脑的配置进行下载。
pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116

奇怪的是,我自己电脑选用conda下载就会报错,但是pip3反而不会(玄学?)
4. 检验pytorch是否安装完成

python
import torch
torch.cuda.is_available()

如果能显示出True且没有报错的话,说明已经安装成功啦在这里插入图片描述

tips:
如果环境里没有安装jupyter notebook的可以pip3安装一下

2. Dataset的基本使用方法

注:我这里用的是jupyter notebook,有pycharm或者vscode的同学也可以用这两个。
首先导入需要用到的库:

import torch
from torch.utils.data import Dataset
from PIL import Image
import os

然后写一个Dataset类:

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, idx):
        img_name = self.img_path[idx] # 索引图片的名字
        img_item_path = os.path.join(self.root_dir, self.label_dir, img_name) # 每一张图片的路径
        img = Image.open(img_item_path)# 打开某一张图片
        label = self.label_dir# 标签即为__init___中定义的标签
        return img,label # 返回图片和标签

    def __len__(self):
        return len(self.img_path) # 返回数据集的长度

最后在调用这个库的时候可以根据自己数据集的文件目录来进行相应的操作。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WFForstar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值