没有'torch.utils.data.dataset'

运行时出现“ModuleNotFoundError: No module named 'torch.utils.data.dataset'
怎么解决

这个错误是因为你的环境中缺少PyTorch,导致找不到torch.utils.data.dataset模块。
可以这样解决:

  1. 安装PyTorch。目前有两种安装方式:
  1. 安装完成后,重启IDE或者Kernel,就可以导入torch.utils.data.dataset了。
  2. 如果还是不行,可能是环境变量设置的问题,可以尝试:
  • 重启电脑
  • 手动设置环境变量:在Path里添加Python和PyTorch的安装路径。
不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 这篇博客: torch.utils.data中的 1. torch.utils.data.Dataset类 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:
     class torch.utils.data.Dataset
    • 源码:
    class Dataset(object):
        """An abstract class representing a Dataset.
    
        All other datasets should subclass it. All subclasses should override
        ``__len__``, that provides the size of the dataset, and ``__getitem__``,
        supporting integer indexing in range from 0 to len(self) exclusive.
        """
    
        def __getitem__(self, index):
            raise NotImplementedError
    
        def __len__(self):
            raise NotImplementedError
    
        def __add__(self, other):
            return ConcatDataset([self, other])
    
    • 作用: 创建数据集,有__getitem__(self, index)函数来根据索引序号获取图片和标签, 有__len__(self)函数来获取数据集的长度.
    • 其他的数据集类必须是torch.utils.data.Dataset的子类,比如说torchvision.ImageFolder.
    • 一个用来表示数据集的抽象类,其他所有的数据集都应该是这个类的子类,并且需要重写__len____getitem__

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^