如何将二维Tensor转换为一维Tensor?排查MSELoss运行时错误
张量变形与MSELoss错误解决
一、将二维张量转为一维张量
你可以用以下几种方法实现形状转换:
- 使用
squeeze()方法:移除张量中所有大小为1的维度,正好适配你的场景:import torch t = torch.tensor([[4.],[1.]], device='cuda:0') t_1d = t.squeeze() # 输出结果:tensor([4., 1.], device='cuda:0') - 使用
flatten()方法:直接将张量展平为一维:t_1d = t.flatten() - 使用
view()方法:手动指定目标形状(需保证元素总数一致):t_1d = t.view(-1) # -1表示自动计算该维度的大小
二、RuntimeError错误分析与解决
你遇到的RuntimeError: Boolean value of Tensor with more than one value is ambiguous错误和张量形状无关,问题出在MSELoss的调用方式上:
错误写法:
loss = nn.MSELoss(y_tilde,y)
nn.MSELoss是一个类,需要先实例化再传入参数计算损失;或者使用函数式接口F.mse_loss直接调用。正确写法有两种:
- 实例化损失类后调用:
import torch.nn as nn criterion = nn.MSELoss() loss = criterion(y_tilde, y)
- 使用函数式接口:
import torch.nn.functional as F loss = F.mse_loss(y_tilde, y)
内容的提问来源于stack exchange,提问作者S.EB
相关产品推荐
相关产品推荐

