简体   繁体   中英

pytorch+tensorboard error “ AttributeError: 'Tensor' object has no attribute 'items' ”

Good afternoon. I want to log the loss of the train using the tensorboard in pytorch. I got an error there.

AttributeError: 'Tensor' object has no attribute 'items'

I want to solve this error and check the log using tensorboard. Here I show my code.

l_mse = mseloss(img,decoder_out)
writer.add_scalars("MSE",l_mse,n_iter)

img is real image in GAN and decoder_out is Generator output. then I have error blow.

Traceback (most recent call last):
  File "main.py", line 39, in <module>
    main()
  File "main.py", line 22, in main
    solover.train(dataloader)
  File "path to my file", line 239, in train
    writer.add_scalars("MSE",l_mse,n_iter)
  File "/~~/anaconda3/lib/python3.7/site-packages/torch/utils/tensorboard/writer.py", line 378, in add_scalars
    for tag, scalar_value in tag_scalar_dict.items():
AttributeError: 'Tensor' object has no attribute 'items'

I tried

writer.add_scalars("MSE",l_mse,n_iter).eval()
writer.add_scalars("MSE",l_mse.item(),n_iter)
writer.add_scalars("MSE",l_mse.detach().cpu().numpy(),n_iter)

but still not work well.

You are calling for writer.add_scalars with a s . From Pytorch Tensorboardx documentation you can see that this function expects a dictionary as input.

 add_scalars(main_tag, tag_scalar_dict, global_step=None, walltime=None)
  • tag_scalar_dict (dict) – Key-value pair storing the tag and corresponding values
writer = SummaryWriter()
r = 5
for i in range(100):
    writer.add_scalars('run_14h', {'xsinx':i*np.sin(i/r),
                                    'xcosx':i*np.cos(i/r),
                                    'tanx': np.tan(i/r)}, i)
writer.close()

Use writer.add_scalar instead

To log a scalar value, use writer.add_scalar('myscalar', value, iteration) . Note that the program complains if you feed a PyTorch tensor. Remember to extract the scalar value by x.item() if x is a torch scalar tensor.

writer.add_scalar("MSE", l_mse.item(), n_iter)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM