如何修正PyTorch中MyModel神经网络模型以匹配指定架构?
问题排查与代码修正
错误原因
你的代码通过inp和out参数动态生成内层线性层,导致内层的张量尺寸完全依赖于网络的输入输出参数。这违背了任务提示中**"内层的输入输出张量尺寸不依赖网络入口和出口张量尺寸"**的要求。任务要求的模型结构是固定的:输入维度为20,后续每个线性层的输出维度比前一层少1,直到输出维度为10。
修正后的代码
方案1:固定模型输入输出尺寸(最符合任务要求)
import torch import torch.nn as nn class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() layers = [] current_dim = 20 # 生成9个带ReLU激活的线性层,维度从20递减到11 for _ in range(9): layers.append(nn.Linear(current_dim, current_dim - 1)) layers.append(nn.ReLU()) current_dim -= 1 # 最后一层线性层,从11维度映射到10维度(输出层) layers.append(nn.Linear(current_dim, 10)) self.layers = nn.ModuleList(layers) def forward(self, x): for layer in self.layers: x = layer(x) return x # 创建符合要求的模型 model = MyModel()
方案2:保留参数接口并添加校验
如果需要保留inp和out参数接口,可添加参数校验确保输入输出符合任务要求,同时固定内层结构:
import torch import torch.nn as nn class MyModel(nn.Module): def __init__(self, inp, out): super(MyModel, self).__init__() # 强制输入为20、输出为10,不符合则抛出错误 assert inp == 20 and out == 10, "This model only supports input size 20 and output size 10" layers = [] current_dim = 20 for _ in range(9): layers.append(nn.Linear(current_dim, current_dim - 1)) layers.append(nn.ReLU()) current_dim -= 1 layers.append(nn.Linear(current_dim, out)) self.layers = nn.ModuleList(layers) def forward(self, x): for layer in self.layers: x = layer(x) return x model = MyModel(inp=20, out=10)
修正说明
- 内层结构不再依赖输入输出参数动态生成,而是固定按照20→19→18→…→11→10的维度递减,满足"每个后续线性层神经元数量比前一层少1"的要求。
- 严格遵循任务提示,确保内层张量尺寸与网络入口、出口尺寸解耦,符合图示模型的结构要求。
内容的提问来源于stack exchange,提问作者Мария Найденко
相关产品推荐
相关产品推荐

