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都一样,为什么还会报张量不兼容呢?
- 报错原因是调用save_image(test_fake_TList,output_dir1,“1.png”)时,test_fake_TList是一个列表,而不是一个单一的Tensor。
- 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