b站小土堆|Dataset类代码实战

完整代码如下:

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

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
         return img,label

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

root_dir = "dataset/train"
ants_label_dir = "ants"
bees_label_dir = "bees"
ants_dataset=MyData(root_dir,ants_label_dir)
bees_dataset=MyData(root_dir,bees_label_dir)

train_dataset = ants_dataset + bees_dataset

注意:这里使用的的是相对路径,所以需要保证文件夹和改代码文件在同一个文件夹里面,且必须在同一层文件夹下面。不能说一个在第二层目录,一个在第三层目录,这样会报错,但是好像依然会输出结果emm

关于有些报错问题,应该是最开始导入torch包就出问题了,下面是我的报错:

from torch.utils.data import Dataset
Traceback (most recent call last):
  File "D:\anaconda3\envs\pytorch\Lib\site-packages\IPython\core\interactiveshell.py", line 3577, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-e380a5678ee1>", line 1, in <module>
    from torch.utils.data import Dataset
  File "D:\JetBrains\PyCharm Community Edition 2024.2\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\anaconda3\envs\pytorch\Lib\site-packages\torch\__init__.py", line 133, in <module>
    raise err
OSError: [WinError 126] 找不到指定的模块。 Error loading "D:\anaconda3\envs\pytorch\Lib\site-packages\torch\lib\torch_python.dll" or one of its dependencies.

试了很多方法,比如检查是否安装了Microsoft Visual C++ Redistributable运行库、使用工具如Dependency Walker来检查DLL的依赖关系以及一些其他问题,但是都没有得到解决。

最后博主直接从torch开始导

import torch

我靠 这也能报错凸(艹皿艹 )

那就说明我根本就是最开始的torch又出问题了 

所以直接开始重装pytorch了

步骤如下:

第一步:打开pycharm命令行

 第二步:输入pip install torch torchvision torchaudio

ps:其实我安装了anaconda,也换了清华源,我最开始pytorch就是用这玩意下载的,但是不知道为毛,每次用conda的命令下载就很慢,还是用pip直接秒下好emm

第三步:看到关键词 Successfully 就完事了

第四步:检查下是否正确安装了

根据命令行输出,pytorch已经成功安装,并且版本是 2.4.1,后缀 +cpu 表示这是一个仅支持 CPU 的版本。 

这时再回去输入import torch 应该不会报错了

如果还错,可以看看我前面写的文章:anaconda安装pytorch后,在pycharm中使用torch包出问题_anaconda自带的python在import torch报错-CSDN博客

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Ricardo_yanwu

发博客也就图一乐学到知识最重要

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

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

打赏作者

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

抵扣说明:

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

余额充值