RuntimeError:DataLoader 工作线程意外退出

2024-01-03

我是 PyTorch 和机器学习的新手,所以我尝试按照这里的教程进行操作:https://medium.com/@nutanbhogendrasharma/pytorch-卷积神经网络-with-mnist-dataset-4e8a4265e118 https://medium.com/@nutanbhogendrasharma/pytorch-convolutional-neural-network-with-mnist-dataset-4e8a4265e118

通过一步步复制代码,我无缘无故地得到了以下错误。我在另一台计算机上尝试了该程序,但出现语法错误。但是,我的 IDE 没有警告我任何有关语法的信息。我真的很困惑如何解决这个问题。任何帮助表示赞赏。

RuntimeError: DataLoader worker exited unexpectedly

这是代码。

import torch
from torchvision import datasets
from torchvision.transforms import ToTensor
import torch.nn as nn
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader
from torch import optim
from torch.autograd import Variable

train_data = datasets.MNIST(
    root='data',
    train=True,
    transform=ToTensor(),
    download=True,
)
test_data = datasets.MNIST(
    root='data',
    train=False,
    transform=ToTensor()
)
print(train_data)
print(test_data)

print(train_data.data.size())
print(train_data.targets.size())

plt.imshow(train_data.data[0], cmap='gray')
plt.title('%i' % train_data.targets[0])
plt.show()

figure = plt.figure(figsize=(10, 8))
cols, rows = 5, 5
for i in range(1, cols * rows + 1):
    sample_idx = torch.randint(len(train_data), size=(1,)).item()
    img, label = train_data[sample_idx]
    figure.add_subplot(rows, cols, i)
    plt.title(label)
    plt.axis("off")
    plt.imshow(img.squeeze(), cmap="gray")
plt.show()

loaders = {
    'train': DataLoader(train_data,
                        batch_size=100,
                        shuffle=True,
                        num_workers=1),

    'test': DataLoader(test_data,
                       batch_size=100,
                       shuffle=True,
                       num_workers=1),
}


class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(
                in_channels=1,
                out_channels=16,
                kernel_size=5,
                stride=1,
                padding=2,
            ),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2),
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(16, 32, 5, 1, 2),
            nn.ReLU(),
            nn.MaxPool2d(2),
        )
        # fully connected layer, output 10 classes
        self.out = nn.Linear(32 * 7 * 7, 10)

    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        # flatten the output of conv2 to (batch_size, 32 * 7 * 7)
        x = x.view(x.size(0), -1)
        output = self.out(x)
        return output, x  # return x for visualization


cnn = CNN()
print(cnn)

loss_func = nn.CrossEntropyLoss()
print(loss_func)
optimizer = optim.Adam(cnn.parameters(), lr=0.01)
print(optimizer)
num_epochs = 10


def train(num_epochs, cnn, loaders):
    cnn.train()

    # Train the model
    total_step = len(loaders['train'])

    for epoch in range(num_epochs):
        for i, (images, labels) in enumerate(loaders['train']):
            # gives batch data, normalize x when iterate train_loader
            b_x = Variable(images)  # batch x
            b_y = Variable(labels)  # batch y

            output = cnn(b_x)[0]
            loss = loss_func(output, b_y)

            # clear gradients for this training step
            optimizer.zero_grad()

            # backpropagation, compute gradients
            loss.backward()
            # apply gradients
            optimizer.step()

            if (i + 1) % 100 == 0:
                print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
                      .format(epoch + 1, num_epochs, i + 1, total_step, loss.item()))
                pass

        pass

    pass


train(num_epochs, cnn, loaders)


def evalFunc():
    # Test the model
    cnn.eval()
    with torch.no_grad():
        correct = 0
        total = 0
        for images, labels in loaders['test']:
            test_output, last_layer = cnn(images)
            pred_y = torch.max(test_output, 1)[1].data.squeeze()
            accuracy = (pred_y == labels).sum().item() / float(labels.size(0))
            pass

        print('Test Accuracy of the model on the 10000 test images: %.2f' % accuracy)

    pass


evalFunc()

sample = next(iter(loaders['test']))
imgs, lbls = sample

actual_number = lbls[:10].numpy()

test_output, last_layer = cnn(imgs[:10])
pred_y = torch.max(test_output, 1)[1].data.numpy().squeeze()
print(f'Prediction number: {pred_y}')
print(f'Actual number: {actual_number}')

如果您正在使用 jupyter 笔记本。问题更有可能是num_worker。你应该设置num_worker=0。你可以找到here https://stackoverflow.com/a/71193241/16733101一些需要遵循的解决方案。因为不幸的是,jupyter Notebook 在运行多处理时存在一些问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

RuntimeError:DataLoader 工作线程意外退出 的相关文章

随机推荐

  • 删除 int 数组中重复项的程序

    我编写了一些代码来从整数数组中删除重复项 我不想使用任何内置关键字 属性 这是我的逻辑 int iArray 1 2 3 2 3 4 3 int t 0 int arraysize iArray Length for int m 0 m l
  • ModalViewController 加载在另一个 Modal 之上

    可能有更好的方法来做到这一点 如果有请指导我 我正在创建一个UIImagePickerController在 viewDidAppear 中使用 overrideView 来表示 从库中选择 拍照 闪光灯 相机源 等 Set up the
  • Jackson、Retrofit、JodaTime 反序列化

    我正在使用这三个库 retrofit jackson 和 jodatime 并且当对象来自我的 Rest api 时 我正在尝试反序列化我的对象 但我不知道如何解决这个问题 这里是 Rest 返回的 json应用程序编程接口 establi
  • 为 Azure AD B2C 创建测试用户

    有没有办法以编程方式创建用户以使用 Azure AD B2C 进行测试 据我所知 创建用户的唯一方法是通过网站注册 我错过了什么吗 是的 Azure AD B2C Graph API 允许对用户进行 CRUD 操作 您可以通过向 users
  • 软键盘弹出时页面滚动

    我有一个
  • 如何调试 PHP 脚本? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 Locked 这个问题及其答案是locked help locked posts因为这个问题是题外话 但却具有历史意义 目前不接受新的
  • MariaDB - 无法以 root 身份登录

    我正在尝试在 Ubuntu 16 04 02 上设置 MariaDB 10 0 29 在我安装它并启动该过程之后 sudo service mysql start 我无法登录root即使我最初将密码设置为空白 Ie mysql u root
  • android webview崩溃4.3

    自 4 3 版本以来 我在 Android 中的支付 webview 遇到了问题 我猜是由于 SSL 证书重定向造成的 但我无法更改它 我在三星或索尼 08 08 17 22 38 619 E AndroidRuntime 7568 FAT
  • 如何为 Org 模式内联源代码 src_lang{} 进行语法高亮?

    有没有一种方法可以语法突出显示 Org mode 内联源代码 该代码标记为src ruby Array new 组织模式是否有默认选项 或者还有其他方法可以做到这一点吗 更新 这个特定问题的正确答案如下https stackoverflow
  • 如何调试罕见的死锁?

    我正在尝试调试一个自定义线程池实现rarely僵局 所以我不能使用像 gdb 这样的调试器 因为在出 现死锁之前我已经点击了 100 次 启动 调试器 目前 我正在 shell 脚本中的无限循环中运行线程池测试 但这意味着我看不到变量等 我
  • 如何使用 AsyncHttpClient Android 上传多个文件

    我知道我可以从 AsyncHttpClient 上传单个文件 http loopj com android async http http loopj com android async http File myFile new File
  • 多容器docker(AW​​S)链接是单向的吗?

    我通过 AWS 上的多容器 docker 获得了非对称容器可发现性 也就是说 第一个容器可以找到第二个容器 但第二个容器找不到第一个容器 我在 AWS Elastic Beanstalk 上进行了多容器 Docker 部署 两个容器都使用相
  • 在返回“send_file”的烧瓶函数中,代码似乎不会在后续请求上运行,但文件仍然会下载。为什么?

    我正在使用具有以下路线的 Flask 代码 app route download def download file path certificate docx print certificate printed print os getc
  • 从 php stdin 保存大文件

    请告诉我从 php stdin 保存大文件的最佳方法 iOS 开发人员向我发送大型视频内容到服务器 我必须将其存储到文件中 我读取带有视频数据的标准输入线程并将其写入文件 例如 这样 handle fopen php input rb wh
  • JPlayer Circle Player 第一次使用 vox 制作的 wav 文件时不显示圆圈

    我有一个应用程序 它使用 JPlayer Circle Player 播放短音频以进行转录 这些音频均源自 vox 文件 已由 SoX 转换为 wav 按下 播放 按钮时 将播放音频 但不显示绿色圆圈 剪辑播放后 再次按播放确实会显示绿色圆
  • 为什么这个 std::vector 会给出运行时错误?

    vector
  • .NET:关于 AssemblyVersion,什么定义了二进制兼容性?

    对强命名程序集的哪些更改需要更改 AssemblyVersionAttribute 显然 以可能要求客户端必须更改代码的方式更改公共 api 需要增加 AssemblyVersion 但是 如果对公共 API 进行更改而不需要在客户端中更改
  • C 中的类型双关和联合

    我目前正在开发一个项目来构建一个小型编译器 只是为了它 我决定采用构建一个极其简单的虚拟机作为目标的方法 这样我就不必担心学习 elf intel 汇编等的细节 我的问题是关于 C 中使用联合的类型双关 我决定在虚拟机内存中仅支持 32 位
  • MongoDB嵌套对象聚合计数

    我有一个高度嵌套的 mongoDB 对象集 我想计算与给定条件匹配的子文档的数量编辑 在每个文档中 例如 id chr 20 pos 14371 ref A alt G studies study id Study1 samples sam
  • RuntimeError:DataLoader 工作线程意外退出

    我是 PyTorch 和机器学习的新手 所以我尝试按照这里的教程进行操作 https medium com nutanbhogendrasharma pytorch 卷积神经网络 with mnist dataset 4e8a4265e11