RuntimeError: The size of tensor a (3) must match the size of tensor b (256) at non-singleton dimens

RuntimeError: The size of tensor a (3) must match the size of tensor b (256) at non-singleton dimension 2

1. 问题位置

# visuals_test是有序字典 test_fake_TList是张量列表,有三个张量
test_fake_TList = visuals_test['fake_Ts'] 
save_image(test_fake_TList_cat, os.path.join(output_dir1, f'test_imgs_epoch{i}+{total_test_step}.png'), nrow=4)

2. 报错:

Traceback (most recent call last):
  File "d:/SSIR-Gzm/ssir/inference1.py", line 280, in <module>
    save_image(test_fake_TList,output_dir1,"1.png")
  File "D:\Anaconda\envs\pytorch\lib\site-packages\torch\autograd\grad_mode.py", line 28, in decorate_context
    return func(*args, **kwargs)
  File "D:\Anaconda\envs\pytorch\lib\site-packages\torchvision\utils.py", line 132, in save_image
    grid = make_grid(tensor, **kwargs)
  File "D:\Anaconda\envs\pytorch\lib\site-packages\torch\autograd\grad_mode.py", line 28, in decorate_context
    return func(*args, **kwargs)
  File "D:\Anaconda\envs\pytorch\lib\site-packages\torchvision\utils.py", line 108, in make_grid
    ).copy_(tensor[k])
RuntimeError: The size of tensor a (3) must match the size of tensor b (256) at non-singleton dimension 2

3. 打印出来test_fake_TList

torch.Size([4, 3, 256, 256]), torch.Size([4, 3, 256, 256]), torch.Size([4, 3, 256, 256])]
torch.float32, torch.float32, torch.float32]
[device(type='cuda', index=0), device(type='cuda', index=0), device(type='cuda', index=0)]
[(tensor(0., device='cuda:0'), tensor(1., device='cuda:0')), (tensor(0., device='cuda:0'), tensor(1., device='cuda:0')), (tensor(0., device='cuda:0'), tensor(1., device='cuda:0'))]

4. 疑惑:三个张量的shape都一样,为什么还会报张量不兼容呢?

  1. 报错原因是调用save_image(test_fake_TList,output_dir1,“1.png”)时,test_fake_TList是一个列表,而不是一个单一的Tensor。
  2. torchvision.utils.save_image和make_grid期望输入是一个形状类似于(N, C, H, W)的Tensor,而不是[Tensor, Tensor, …]的列表。

5. 解决方法

你需要将你的test_fake_TList(形如[tensor1, tensor2, tensor3],每个tensor shape为(4, 3, 256, 256))拼接成一个大的tensor。

import torch
from torchvision.utils import save_image

# 假设 test_fake_TList = [tensor1, tensor2, tensor3]

# 1. 拼接为一个 (N, C, H, W) 的tensor,N=4*3=12
test_fake_T = torch.cat(test_fake_TList, dim=0)  # (12, 3, 256, 256)

# 2. 保存图片
save_image(test_fake_T, os.path.join(output_dir1, "1.png"))

6. 吐槽:deepseek信誓旦旦的给我错误分析

在这里插入图片描述
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/d8872bcefb2c4ed88887d63edb1f72ac.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值