ECL中Python嵌入调用PyTorch类遇未定义错误的解决咨询
在ECL嵌入Python环境中创建PyTorch nn.Module类对象的解决方案
问题根源分析
第一个错误
name 'model_1' is not defined:
核心原因是类的构造函数写法错误——Python类的构造函数必须是双下划线的__init__,你写成了单下划线的_init_,导致Python无法识别这是类的初始化方法,类实例化时会出现未定义的错误。第二个错误
name 'torch' is not defined:
大概率是ECL的PYEMBED环境未正确安装PyTorch,或者嵌入代码的作用域/缩进存在问题,导致导入的模块未被正确识别。
修复后的完整代码
f() := EMBED(PY) import torch import torch.nn as nn import torch.optim as optim class model_1(nn.Module): # 修正:使用双下划线的__init__作为构造函数 def __init__(self): # 同步修正父类构造方法的调用 super(model_1, self).__init__() input_size = torch.randint(10, 100, (1,)).item() hidden_size = torch.randint(10, 100, (1,)).item() output_size = torch.randint(2, 10, (1,)).item() self.layer1 = nn.Linear(input_size, hidden_size) self.activation = nn.ReLU() self.layer2 = nn.Linear(hidden_size, output_size) self.softmax = nn.Softmax(dim=1) def forward(self, x): x = self.layer1(x) x = self.activation(x) x = self.layer2(x) x = self.softmax(x) return x # 实例化模型 model = model_1() batch_size = 32 input_size = model.layer1.in_features input_data = torch.randn(batch_size, input_size) target = torch.randint(0, model.layer2.out_features, (batch_size,)) criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.01) num_epochs = 10 for epoch in range(num_epochs): output = model(input_data) loss = criterion(output, target) print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}') optimizer.zero_grad() loss.backward() optimizer.step() ENDEMBED; f();
额外注意事项
- 环境验证:确保ECL所使用的Python环境已安装PyTorch,可在对应环境中执行
pip install torch torchvision torchaudio完成安装。 - 缩进规范:
PYEMBED块内的Python代码严格遵循缩进规则,错误的缩进会导致作用域异常。 - 参数调试:如果需要稳定调试,建议将
input_size等动态生成的参数改为固定值,避免每次运行模型结构不一致。
内容的提问来源于stack exchange,提问作者decoded051
相关产品推荐
相关产品推荐

