TypeError: unsupported format string passed to Tensor.__format__

minister_79: <p>Good fellow friends,</p>
<p>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:</p>
<pre><code class="lang-auto">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
</code></pre>
<p>Below is the error it returns, please help me. Thank you</p>
<pre><code class="lang-auto">Traceback (most recent call last):
  File "/Users/mac/Desktop/OAMP_NET/tpg.py", line 243, in &lt;module&gt;
    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__
</code></pre>

albanD: <p>I guess you are trying to pass a tensor to your <code>.format()</code> call. Which is not supported.<br>
In particular, <code>BER</code> looks like it is a Tensor of size 1, len(snr_t) so that might not be possible to print with format.<br>
If you just want the one for this sample, I guess you want:</p>
<pre><code class="lang-auto">        BER = 1 - accuracy[0][k]
        print('({0}) BER:{1:6.6f}'.format(t + 1, BER.item()))
</code></pre>

minister_79: <p>@ 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.</p>

albanD: <p>At the moment we don’t support format. Maybe we want to add that? <a class="mention" href="/u/smth">@smth</a></p>
<p>If you want to print the whole Tensor, you can <code>print(foo)</code>.</p>

Mona_Jalal: <p>Hello <a class="mention" href="/u/alband">@albanD</a> <a class="mention" href="/u/smth">@smth</a></p>
<p>I have the same error when trying to convert a code written for old PyTorch to 1.9<br>
Do you have a solution?</p>
<pre><code class="lang-auto">(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
&lt;class 'torch.utils.data.dataloader.DataLoader'&gt;
/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 &lt;module&gt;
    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__
</code></pre>
<p>Here’s the problematic part of the code:</p>
<pre><code class="lang-auto">
        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))
</code></pre>

Mona_Jalal: <p>This (adding .item() to each tensor) worked for me:</p>
<pre><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.item(), losses.avg.item(), 
            100. * accs.val.item(), 100. * accs.avg.item(), emb_norms.val.item(), emb_norms.avg.item()))</code></pre>