AssertionError: size of input tensor and input format are different.

想用tensorboard添加图片的时候出现以下错误

Traceback (most recent call last):
  File "/usr/local/pycharm-2020.3.5/plugins/python/helpers/pydev/pydevd.py", line 1477, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/usr/local/pycharm-2020.3.5/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/data/chenrj/paper5/main.py", line 142, in <module>
    acc_test,  epoch_max = train_SemiTime(
  File "/data/chenrj/paper5/optim/pretrain.py", line 95, in train_SemiTime
    test_acc, best_epoch = model.train(tot_epochs=tot_epochs, train_loader=train_loader,
  File "/data/chenrj/paper5/model/semiSOP.py", line 99, in train
    writer.add_images('cor_matrix', cor_matrix, epoch)
  File "/data/chenrj/.local/lib/python3.9/site-packages/torch/utils/tensorboard/writer.py", line 589, in add_images
    image(tag, img_tensor, dataformats=dataformats), global_step, walltime)
  File "/data/chenrj/.local/lib/python3.9/site-packages/torch/utils/tensorboard/summary.py", line 376, in image
    tensor = convert_to_HWC(tensor, dataformats)
  File "/data/chenrj/.local/lib/python3.9/site-packages/torch/utils/tensorboard/_utils.py", line 100, in convert_to_HWC
    assert(len(tensor.shape) == len(input_format)), "size of input tensor and input format are different. \
AssertionError: size of input tensor and input format are different.         tensor shape: (128, 128), input_format: NCHW

原因

这是因为我代码中的数据是一个二维矩阵,而add_images这个函数接受的输入是一个四维的数据,为NCHW,N是数据样本量,C为channel,H和W为图片的长和宽。

解决方法

因为我的项目中是不断生成的特征图想保存下来,因此用add_images()这个函数的话没办法实现(原因解释过了),因此有2种解决方法:

1、将特征图先用一个列表保存下来,然后最后再add_images()。

2、把函数修改为add_image,add_image()函数要求的输入是一个三维的数据,为CHW。

因为我需要查看图片的变化,所以我这里采用第二种方法,将我的二维矩阵添加一维C的维度,然后在

add_image。代码如下

writer.add_image('cor_matrix', cor_matrix.unsqueeze(0), epoch)

打开tensorboard可以通过滑动条查看过往的图像。

 

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值