You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PyTorch Dataset和DataLoader加载数据集时遇AttributeError报错求助

解决PyTorch DataLoader报错:AttributeError: '_MultiProcessingDataLoaderIter' object has no attribute 'next'

错误原因

  1. 迭代器调用方式错误:Python 3迭代器遵循新协议,需使用内置next()函数获取下一个元素,而非直接调用迭代器对象的.next()方法(这是Python 2的写法),PyTorch的DataLoader迭代器也遵循这一规则。
  2. 代码缩进错误:你的代码中dataset = WineDataset()和train_loader的定义被缩进在WineDataset类内部,导致它们成为类属性而非全局变量,会引发后续使用问题。

修正步骤

1. 修正类定义缩进

将数据集和DataLoader的实例化代码移出类定义:

import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader

class WineDataset(Dataset):

    def __init__(self):
        xy = np.loadtxt('./data/wine.csv', delimiter=',', dtype=np.float32, skiprows=1)
        self.n_samples = xy.shape[0]
        self.x_data = torch.from_numpy(xy[:, 1:])
        self.y_data = torch.from_numpy(xy[:, [0]])

    def __getitem__(self, index):
        return self.x_data[index], self.y_data[index]

    def __len__(self):
        return self.n_samples

# 移出类定义,作为全局代码执行
dataset = WineDataset()
        
train_loader = DataLoader(dataset=dataset,
                          batch_size=4,
                          shuffle=True,
                          num_workers=2)

2. 使用正确的迭代方式

方式一:for循环遍历(推荐用于训练循环)

# 遍历多个epoch
for epoch in range(3):
    for batch_idx, (features, labels) in enumerate(train_loader):
        # 处理批次数据逻辑
        print(f"Epoch {epoch+1}, Batch {batch_idx+1}")
        print(f"Features shape: {features.shape}, Labels shape: {labels.shape}")

方式二:迭代器+内置next()获取单批次

# 创建迭代器
loader_iter = iter(train_loader)
# 获取下一个批次
features, labels = next(loader_iter)
print(f"Features shape: {features.shape}, Labels shape: {labels.shape}")

关键提醒

  • 禁止使用loader_iter.next()或train_loader.next()的写法,这是Python 2的遗留语法,PyTorch 1.x+版本在Python 3环境下不再支持。
  • num_workers设置不影响该错误,因为核心问题是迭代器调用方式错误,而非多进程加载问题。

内容的提问来源于stack exchange,提问作者Adham Enaya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:05:23