zoukankan      html  css  js  c++  java
  • Pytorch计算loss前的一些工作:one-hot与indexes、nn.CrossEntropyLoss

    indexes转one-hot

    https://stackoverflow.com/questions/65424771/how-to-convert-one-hot-vector-to-label-index-and-back-in-pytorch

    https://pytorch.org/docs/stable/generated/torch.nn.functional.one_hot.html

    可以用pytorch中的自带函数one-hot

    import torch.nn.functional as F
    
    num_classes = 100
    trg = torch.randint(0, num_classes, (2,10)) # [2,10]
    one-hot = F.one_hot(trg, num_classes=num_classes) # [2,10,100]

    one-hot转indexes

    torch.argmax(target, dim=2)

    torch.nn.CrossEntropyLoss

    https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html

    通常在计算loss的时候会用到,看官方的样例,target既可以是index,也可以是probalities(类似于softmax之后)

    # Example of target with class indices
    loss = nn.CrossEntropyLoss()
    input = torch.randn(3, 5, requires_grad=True)
    target = torch.empty(3, dtype=torch.long).random_(5)
    output = loss(input, target)
    output.backward()
    # Example of target with class probabilities
    input = torch.randn(3, 5, requires_grad=True)
    target = torch.randn(3, 5).softmax(dim=1)
    output = loss(input, target)
    output.backward()

    但是它的行为并不完全是我想象的那样,

    需要reshape成(N, size)和(N),再进行计算

    其实也能理解,因为loss计算的结果应该是一个值,而不是matrix

    # output: [batch_size, len, trg_vocab_size]
    # trg: [batch_size, len]
    # 发现并不能直接计算
    # 需要reshape成样例中的形状
    
    output = output.reshape(-1, trg_vocab_size)
    trg = trg.reshape(-1)
    loss = criterion(output, trg)

    个性签名:时间会解决一切
  • 相关阅读:
    HTML5然还在草案阶段
    简单的JS动态加载单体
    步步为营 C# 技术漫谈 五、事件与委托机制
    .NET简谈脚本引擎系列(一:认识脚本引擎)
    微软一站式示例代码库 6月再次更新14个新示例代码
    CLR(公共语言运行时)到底藏在哪?
    .NET简谈构件系统开发模式
    项目管理理论与实践系列文章索引
    .Net调试技巧
    Lucene.Net
  • 原文地址:https://www.cnblogs.com/lfri/p/15480326.html
Copyright © 2011-2022 走看看