You need to enable JavaScript to run this app. PyTorch配置torchvision MNIST的DataLoader实现shuffle触发属性错误
优惠活动
大模型
产品
解决方案
定价
更多

PyTorch配置torchvision MNIST的DataLoader实现shuffle触发属性错误

问题排查与修正

核心错误定位

  • 首次运行抛出的AttributeError: module 'torch.utils.data' has no attribute 'Dataloader',本质是API拼写大小写不匹配:PyTorch 内置的数据加载类为驼峰命名的DataLoader,其中字母L为大写,你写的Dataloader(L小写)无法被模块识别,PyTorch API对大小写严格敏感,单个字母的差异就会触发属性找不到的报错。
  • 第二次调整代码后抛出的AttributeError: type object 'Variable' has no attribute 'DataLoader',是完全走错了API调用路径:DataLoader本身就定义在torch.utils.data模块下,和autograd模块没有归属关系;且从PyTorch 0.4版本开始,Variable类就已被正式弃用,功能完全合并到原生Tensor类中,通过autograd.Variable调用任何方法本身就不符合当前版本的API逻辑。

隐藏的语法问题

查看你第二次调整的代码,test数据集初始化的代码行存在括号缺失:transforms.Compose([transforms.ToTensor()])末尾少了对应的右括号,就算修正DataLoader的调用路径,这行代码也会触发Python语法报错。

修正后可直接运行的完整代码

import torch
import numpy as np
import torchvision
from torchvision import transforms, datasets


train = datasets.MNIST("", train=True, download=True,
                       transform = transforms.Compose([transforms.ToTensor()]))

test = datasets.MNIST("", train=False, download=True,
                       transform = transforms.Compose([transforms.ToTensor()]))

# 修正DataLoader的大小写拼写,保留原有shuffle参数实现数据集打乱逻辑
trainset = torch.utils.data.DataLoader(train, batch_size=10, shuffle=True)
testset = torch.utils.data.DataLoader(test, batch_size=10, shuffle=True)

for data in trainset:
    print(data)
    break

内容的提问来源于stack exchange,提问作者max the computer science fox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.14 12:45:04