【问题标题】:TypeError: unsupported format string passed to Tensor.__format__TypeError:不支持的格式字符串传递给 Tensor.__format__
【发布时间】:2021-10-31 09:40:16
【问题描述】:

当尝试将为旧 PyTorch 编写的代码转换为 1.9 时,我收到此错误:

(fashcomp) [jalal@goku fashion-compatibility]$ python main.py --name test_baseline --learned --l2_embed --datadir ../../../data/fashion/
/scratch3/venv/fashcomp/lib/python3.8/site-packages/torchvision/transforms/transforms.py:310: UserWarning: The use of the transforms.Scale transform is deprecated, please use transforms.Resize instead.
  warnings.warn("The use of the transforms.Scale transform is deprecated, " +
  + Number of params: 3191808
<class 'torch.utils.data.dataloader.DataLoader'>
/scratch3/venv/fashcomp/lib/python3.8/site-packages/torch/nn/functional.py:718: UserWarning: Named tensors and all their associated APIs are an experimental feature and subject to change. Please do not use them for anything important until they are released as stable. (Triggered internally at  /pytorch/c10/core/TensorImpl.h:1156.)
  return torch.max_pool2d(input, kernel_size, stride, padding, dilation, ceil_mode)
Traceback (most recent call last):
  File "main.py", line 329, in <module>
    main()    
  File "main.py", line 167, in main
    train(train_loader, tnet, criterion, optimizer, epoch)
  File "main.py", line 240, in train
    print('Train Epoch: {} [{}/{}]\t'
  File "/scratch3/venv/fashcomp/lib/python3.8/site-packages/torch/_tensor.py", line 561, in __format__
    return object.__format__(self, format_spec)
TypeError: unsupported format string passed to Tensor.__format__

这是代码中存在问题的部分:

if batch_idx % args.log_interval == 0:
    print('Train Epoch: {} [{}/{}]\t'
          'Loss: {:.4f} ({:.4f}) \t'
          'Acc: {:.2f}% ({:.2f}%) \t'
          'Emb_Norm: {:.2f} ({:.2f})'.format(
        epoch, batch_idx * num_items, len(train_loader.dataset),
        losses.val, losses.avg, 
        100. * accs.val, 100. * accs.avg, emb_norms.val, emb_norms.avg))

我从this bug report 看到,截至两年前,还没有针对此问题提供解决方案。您对如何解决此问题或任何替代方案有任何建议吗?

代码来自here

【问题讨论】:

  • 我没有看到明确的张量。 accs.val 仍然是张量吗?如果是这样,它们应该是单个项目,在这种情况下尝试 accs.val.item() 并对其他 .avg.val 执行相同操作

标签: python deep-learning pytorch computer-vision tensor


【解决方案1】:

如果您尝试以特定方式格式化 torch.Tensor,则此错误会重现:

>>> print('{:.2f}'.format(torch.rand(1)))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-ece663be5b5c> in <module>()
----> 1 print('{:.2f}'.format(torch.tensor([1])))

/usr/local/lib/python3.7/dist-packages/torch/_tensor.py in __format__(self, format_spec)
    559         if self.dim() == 0:
    560             return self.item().__format__(format_spec)
--> 561         return object.__format__(self, format_spec)
    562 
    563     def __ipow__(self, other):  # type: ignore[misc]

TypeError: unsupported format string passed to Tensor.__format__

在没有任何格式规则的情况下执行'{}'.format(torch.tensor(1)) - - 会起作用。

这是因为torch.Tensor 没有实现那些特定的格式操作。


一个简单的解决方法是使用itemtorch.Tensor 转换为适当的-对应的-类型

>>> print('{:.2f}'.format(torch.rand(1).item()))
0.02

您应该将此修改应用于您的print 字符串表达式中涉及的所有torch.Tensorlosses.vallosses.avgaccs.valaccs.avgemb_norms.valemb_norms.avg

【讨论】:

  • 问你一个快速的问题,你知道为什么在 vscode 中当我输入 .item() 时它没有自动完成吗? loss.val.item()
  • 我想你是这个意思?格式(时代,batch_idx * num_items,len(train_loader.dataset),loss.val.item(),loss.avg.item(),100。* accs.val.item(),100。* accs.avg.item (), emb_norms.val.item(), emb_norms.avg.item())
  • 它是否将变量检测为torch.Tensor,我的意思是它是否提出了其他张量方法?还是只是缺少item
  • 我注意到当我输入 torch.nn.functional 时它并没有提示或自动完成(基本上功能在 vscode 中根本没有显示,但可以工作)
  • 是的,你应该应用它 per 张量。我的回答中的torch.rand(1).item() 仅用于演示目的。
猜你喜欢
  • 2017-12-30
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多