如何使用pyTorch暗示LSTM神经网络的装袋方法?



像标题一样,我的问题是如何使用 PyTorch 库将 Bagging 方法应用于 LSTM?我已经在python上使用TensorFlow构建了一个。但是现在要使用 C 和 C++ 暗示到系统中,要求我需要使用 PyTorch?

是否有任何建议不需要使用 PyTorch 并直接将基于张量流构建的模型应用于系统中的真实预测?

请帮忙!

如果你想在 PyTorch 中创建一个融合,你可以单独训练多个模型,然后定义一个类来一起使用它们:

class MyEnsemble(nn.Module):
def __init__(self, firstModel, secondModel):
super(MyEnsemble, self).__init__()
self.firstModel = modelA
self.secondModel = modelB
self.classifier = nn.Linear(in_features, n_classes) #define accordingly
self.relu = nn.ReLU()
def forward(self, x1, x2):
x1 = self.firstModel(x1)
x2 = self.secondModel(x2)
x = torch.cat((x1, x2), dim=1)
x = self.classifier(self.relu(x))
return x

如果你想使用你的TensorFlow模型,有多种方法可以做到这一点。可以将其导出到C++ Tensorflow -> C++

当你在 PyTorch中创建融合时,最好使用 PyTorch 中的nn.ModuleList()类。该nn.ModuleList()具有与普通 Python 列表相同的功能,如append()。当你创建这样的集成模型时,你可以直接调用backward运算,梯度下降将通过模型发生。

下面是一个集成神经网络(EnsembleNet(,它使用NeuralNet作为融合的单个NN实例。

NeuralNet(nn.Module):
def __init__(self):
super(NeuralNet, self).__init__()
self.fc1 = nn.Linear(in_dim, out_dim)
self.fc2 = nn.Linear(out_dim, 1)

def forward(self, X):
""" X must be of shape [-1, in_dim]"""
X = self.fc1(X)
return torch.sigmoid(self.fc2(X))

EnsembleNet(nn.Module):
def __init__(self, net = NeuralNet, num_ensemble=5, seed_val=SEED):
super(EnsembleNet, self).__init__()
self.ensembles = nn.ModuleList()
for i in range(num_ensemble):
torch.manual_seed(seed_val*i+1)
if torch.cuda.is_available(): # To randomize init of NNs for Ensembles
torch.cuda.manual_seed(seed_val*i+1)
self.ensembles.append(net)
self.final = nn.Linear(num_ensemble, 1)
def forward(self, X_in_list):
pred = torch.cat([net(X_in_list[i]) for i,net in enumerate(self.ensembles)])
pred = pred.reshape(-1, len(self.ensembles))
return torch.sigmoid(self.final(pred))

要使用装袋,只需创建一个X_input_list,其中列表中的不同元素是张量,这些张量已从训练数据中替换采样。(您的X_input_list和num_ensemble必须具有相同的大小(

您可以修改EnsembleNet初始化代码以获取不同神经网络的列表。

最新更新