PyTorch回归神经网络报错RuntimeError:张量无梯度及grad_fn问题求助
解决RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
根据你提供的代码,核心问题和解决步骤如下:
1. 修复模型类定义(最关键)
你的代码中缺失了Model类的定义头,导致它没有继承nn.Module,模型参数无法被PyTorch正确注册,进而使得优化器没有可更新的参数,触发梯度错误。
修正后的模型类代码:
import torch import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): # 补充类定义,明确继承nn.Module def __init__(self, in_features=780, h1=8, h2=6, output=1): super().__init__() self.fc1 = nn.Linear(in_features, h1) self.fc2 = nn.Linear(h1, h2) self.out = nn.Linear(h2, output) def forward(self, x): x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.out(x) return x
2. 补全X_train的张量转换
你提供的数据代码中只处理了X_val和X_test,但训练时用到的X_train没有被转换为PyTorch张量,这会导致输入类型不匹配或梯度传播异常。添加以下代码:
X_train = torch.tensor(X_train_scaled, dtype=torch.float32)
3. 统一标签张量的形状
模型输出的形状是(batch_size, 1),而你的标签张量y_train/y_val是(batch_size,),形状不匹配可能间接影响梯度计算。将标签张量扩展一维:
y_train = torch.tensor(y_train, dtype=torch.float32).unsqueeze(1) y_val = torch.tensor(y_val, dtype=torch.float32).unsqueeze(1) y_test = torch.tensor(y_test, dtype=torch.float32).unsqueeze(1)
验证步骤
在实例化模型后,打印模型参数数量确认参数已被正确注册:
model_nn = Model(in_features=780) print(len(list(model_nn.parameters()))) # 正常应输出6(3层线性层各有weight和bias)
如果输出为0,说明类定义仍有问题,需检查是否正确继承nn.Module。
内容的提问来源于stack exchange,提问作者tommy
相关产品推荐
相关产品推荐

