TypeError: unsupported format string passed to Tensor.__format__

Good fellow friends,

I have built a deep unfolding network for signal detection, the model trains well but during inference over different signal-to-noise ration, I’m getting the following error:

def eval(network,t): #calculate BER
    snr_t = torch.linspace(0.0, 15.0, 6)
    sigma2_t = (N/torch.pow(10,snr_t/10.0))/2.0
    sigma_std_t = torch.sqrt(sigma2_t) 
    s_zero = torch.zeros(batch_size, N) #.cuda()  # initial value
    accuracy = torch.zeros(1, len(snr_t))
    num_err = torch.zeros(1, test_itr)
    H_change()
    for k in range(len(snr_t)):
        for i in range(test_itr):
            x = generate_batch() #.cuda()
            x_hat = network(x, s_zero, t+1, sigma_std_t[k]) #.cuda()
            if isnan(x_hat).any():
                print("Nan")
                continue

            err = x * torch.sign(x_hat)
            num_err[0][i] += torch.nonzero(F.relu(err)).size(0)

        accuracy[0][k] = torch.mean(num_err/(test_itr*batch_size*N))
        BER = 1 - accuracy
        print('({0}) BER:{1:6.6f}'.format(t + 1, BER))

    return BER

Below is the error it returns, please help me. Thank you

Traceback (most recent call last):
  File "/Users/mac/Desktop/OAMP_NET/tpg.py", line 243, in <module>
    main()
  File "/Users/mac/Desktop/OAMP_NET/tpg.py", line 193, in main
    BER = eval(network,t)
  File "/Users/mac/Desktop/OAMP_NET/tpg.py", line 149, in eval
    print('({0}) BER:{1:6.6f}'.format(t + 1, BER))
  File "/Users/mac/miniconda3/lib/python3.6/site-packages/torch/tensor.py", line 379, in __format__
    return object.__format__(self, format_spec)
TypeError: unsupported format string passed to Tensor.__format__
1 Like

I guess you are trying to pass a tensor to your .format() call. Which is not supported.
In particular, BER looks like it is a Tensor of size 1, len(snr_t) so that might not be possible to print with format.
If you just want the one for this sample, I guess you want:

        BER = 1 - accuracy[0][k]
        print('({0}) BER:{1:6.6f}'.format(t + 1, BER.item()))
1 Like

@ albanD thank you for your kind reply. Going by your answer, I can only print one value of the BER tensor, and my goal is to print the entrie BER tensor. How can I do that please? Thanks.

At the moment we don’t support format. Maybe we want to add that? @smth

If you want to print the whole Tensor, you can print(foo).

Hello @albanD @smth

I have the same error when trying to convert a code written for old PyTorch to 1.9
Do you have a solution?

(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__

Here’s the problematic part of the code:


        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 (adding .item() to each tensor) worked for me:

    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.item(), losses.avg.item(), 
            100. * accs.val.item(), 100. * accs.avg.item(), emb_norms.val.item(), emb_norms.avg.item()))