LSTM类中的默认非线性激活函数为tanh。我希望在我的项目中使用ReLU。浏览文档和其他资源时,我无法找到一种简单的方式来做到这一点。我能找到的唯一方法是定义自己的自定义LSTMCell,但是在这里作者说自定义LSTMCell不支持GPU加速功能(或者自文章发表以来是否有所改变?)。我需要使用CUDA来加快培训速度。任何帮助,将不胜感激。
自定义LSTMCell不支持GPU加速功能 -此语句可能意味着如果您使用LSTMCell,则GPU加速功能将受到限制。当然,您可以编写自己的LSTM实现,但需要牺牲运行时。
例如,一旦我按如下方式实现LSTM(基于线性层),当用作深度神经模型的一部分时,所用时间比LSTM(PyTorch中提供)要多2到3倍。
class LSTMCell(nn.Module):
def __init__(self, input_size, hidden_size, nlayers, dropout):
""""Constructor of the class"""
super(LSTMCell, self).__init__()
self.nlayers = nlayers
self.dropout = nn.Dropout(p=dropout)
ih, hh = [], []
for i in range(nlayers):
ih.append(nn.Linear(input_size, 4 * hidden_size))
hh.append(nn.Linear(hidden_size, 4 * hidden_size))
self.w_ih = nn.ModuleList(ih)
self.w_hh = nn.ModuleList(hh)
def forward(self, input, hidden):
""""Defines the forward computation of the LSTMCell"""
hy, cy = [], []
for i in range(self.nlayers):
hx, cx = hidden[0][i], hidden[1][i]
gates = self.w_ih[i](input) + self.w_hh[i](hx)
i_gate, f_gate, c_gate, o_gate = gates.chunk(4, 1)
i_gate = F.sigmoid(i_gate)
f_gate = F.sigmoid(f_gate)
c_gate = F.tanh(c_gate)
o_gate = F.sigmoid(o_gate)
ncx = (f_gate * cx) + (i_gate * c_gate)
nhx = o_gate * F.tanh(ncx)
cy.append(ncx)
hy.append(nhx)
input = self.dropout(nhx)
hy, cy = torch.stack(hy, 0), torch.stack(cy, 0)
return hy, cy
Run Code Online (Sandbox Code Playgroud)
我很高兴知道LSTM的自定义实现的运行时间是否可以改善!
| 归档时间: |
|
| 查看次数: |
3475 次 |
| 最近记录: |