运行扩散概率模型代码遇TypeError:torch.cat期望张量却得到列表
解决反向扩散模型图片保存时的TypeError问题
问题原因
报错TypeError: expected Tensor as element 0 in argument 0, but got list出现在torch.cat(all_images_list, dim=0)行,核心原因是all_images_list中的元素不是PyTorch张量,而是列表——这说明你的sample函数返回的是列表而非预期的张量,或者num_to_groups生成的分组导致sample输出异常。
修复步骤
1. 检查并修正sample函数
确保你的sample函数返回的是PyTorch张量(形状应为(batch_size, channels, img_height, img_width))。可参考标准实现对齐:
def sample(model, batch_size=16, channels=3, img_size=64, timesteps=1000, device=device): x = torch.randn((batch_size, channels, img_size, img_size), device=device) for t in reversed(range(0, timesteps)): t_tensor = torch.full((batch_size,), t, device=device, dtype=torch.long) predicted_noise = model(x, t_tensor) beta_t = beta[t] alpha_t = alpha[t] alpha_bar_t = alpha_bar[t] noise = torch.randn_like(x) if t > 0 else torch.zeros_like(x) x = 1 / torch.sqrt(alpha_t) * (x - ((1 - alpha_t) / torch.sqrt(1 - alpha_bar_t)) * predicted_noise) + torch.sqrt(beta_t) * noise return x
如果你的sample函数里有将张量转成列表的操作(比如.tolist()),请移除,确保直接返回张量。
2. 验证num_to_groups函数
确保num_to_groups生成的是正整数分组,不会出现0值。标准实现如下:
def num_to_groups(num, divisor): groups = num // divisor remainder = num % divisor return [divisor] * groups + ([remainder] if remainder > 0 else [])
避免因传入batch_size=0导致sample函数输出异常。
3. 调试拼接逻辑
可以添加打印语句,逐个验证sample的输出类型:
# 替换原all_images_list生成代码 all_images_list = [] for n in batches: img_tensor = sample(model, batch_size=n, channels=channels) print(f"Sample output shape: {img_tensor.shape}, type: {type(img_tensor)}") all_images_list.append(img_tensor) all_images = torch.cat(all_images_list, dim=0)
如果输出显示type是list而非torch.Tensor,回到步骤1修正sample函数。
4. 调整save_image参数(可选)
如果最终生成的图片总数和nrow不匹配,比如生成了4张图,可将nrow改为2,让布局更合理:
save_image(all_images, str(results_folder / f'sample-{milestone}.png'), nrow=2)
内容的提问来源于stack exchange,提问作者Rishi Suman
相关产品推荐
相关产品推荐

