• RuntimeError: multi-target not supported at


    1. 出错代码行
    计算交叉熵是出现异常提示:RuntimeError: multi-target not supported at /opt/conda/conda-bld/pytorch_1549635019666/work/aten/src/THNN/generic/ClassNLLCriterion.c:21
    
    loss = criterion(prediction, target)
    2 原因:
    CrossEntropyLoss does not expect a one-hot encoded vector as the target, but class indices
    pytorch 中计计算交叉熵损失函数时, 输入的正确 label 不能是 one-hot 格式。函数内部会自己处理成 one hot 格式。所以不需要输入 [ 0 0 0 0 1],只需要输入 4 就行。
    
    print(prediction.size())
    print(target.size())
    print("target = ", target)
    loss = criterion(prediction, target)
    # 输出给过如下
    torch.Size([2, 145]) # 输入两个数据,每个数据的有145个值
    torch.Size([2]) # target(ground true) 是两个值,每个数据一个值
    target = tensor([4, 4]) # 两个数据具体的 target 值,都是4
    
    3. 解决方法:
    更改 dataloader 中 dataset 中 def __getitem__(self, index) 返回的 target 的内容(将 one hot 格式改成 数字格式 就行)。
    如果 target 的size 不是一维的话,需要添加一行代码,如下:
    target = target.squeeze() # 添加这一行,用于降维度(从 torch.Size([2, 1]) 降成torch.Size([2]) ) ,即 target 从[ [4], [4]] 降成 [ 4, 4 ]
    loss = criterion(prediction, target)
    
    4. 总结
    pytorch 中使用神经网络进行多分类时,网路的输出 prediction 是 one hot 格式,但计算 交叉熵损失函数时,loss = criterion(prediction, target) 的输入 target 不能是 one hot 格式,直接用数字来表示就行(4 表示 one hot 中的 0 0 0 0 1)。
    所以,自己构建数据集,返回的 target 不需要是 one hot 格式。
    

      

  • 相关阅读:
    自动化运维工具Ansible
    svn服务
    关于nagios系统下使用shell脚本自定义监控插件的编写以及没有实时监控图的问题
    企业级监控nagios实践
    centos6 下FastDFS 在storage节点上nginx的fastdfs-nginx-module 模块编译出现的问题
    分布式文件系统FastDFS
    运维的各个阶段
    用php做一个简单的注册用户功能
    ttttttttttt
    exclude和include当中/**和/*区别
  • 原文地址:https://www.cnblogs.com/blogwangwang/p/12018897.html
Copyright © 2020-2023  润新知