深度学习网络中的num_hiddens代表什么,此处为什么是4*num_hiddens?


class BiRNN(nn.Module):
    def __init__(self, vocab_size, embed_size, num_hiddens, num_layers, **kwargs):
        super(BiRNN, self).__init__(**kwargs)
        self.embedding = nn.Embedding(vocab_size, embed_size)
        # 将bidirectional设置为True获得双向循环神经网络
        self.encoder = nn.LSTM(embed_size, num_hiddens, num_layers, num_layers=num_layers, bidirectional=True)
        self.decoder = nn.Linear(4 * num_hiddens, 2)
     def forward(self, inputs):
       # inputs的形状是(批量大小,时间步数)
       # 因为长短期记忆网络要求其输入的第一个维度是时间维,
       # 所以在获得词元表示之前,输入会被转置。
       # 输出形状为(时间步数,批量大小,词向量维度)
       embeddings = self.embedding(inputs.T)
       self.encoder.flatten_parameters()
       # 返回上一个隐藏层在不同时间步的隐状态,
       # outputs的形状是(时间步数,批量大小,2*隐藏单元数)
       outputs, _ = self.encoder(embeddings)
       # 连结初始和最终时间步的隐状态,作为全连接层的输入,
       # 其形状为(批量大小,4*隐藏单元数)
       encoding = torch.cat((outputs[0], outputs[-1]), dim=1)
       outs = self.decoder(encoding)
       return outs

self.decoder = nn.Linear(4 * num_hiddens, 2),这个全连接层的input为什么是4*num_hiddens

https://pytorch.org/docs/stable/generated/torch.nn.LSTM.html#torch.nn.LSTM

img


先看下LSTM输出的通道数[seq_length, batch_size, num_directions * hidden_size],你的双向num_directions =2,所以在18行的时候你的output=[seq_length, batch_size, 2*hidden_size],第21行中使用toch.cat()进行了一次横向拼接,两个2*hidden_size横向拼接不就是4*hidden_size了?

一个应用案例,你就知道为什么了

Fashion-MNIST数据集中图像形状为28 × 28 28 \times 2828×28,类别数为10。使用长度为28 × 28 = 784 28 \times 28 = 78428×28=784的向量表示每一张图像。因此,输入个数为784,输出个数为10。我们设超参数隐藏单元个数为256。

#设置输入28*28=784 输出设置为10(类别) 隐藏单元个数设置为256 两层的神经网络
num_inputs, num_outputs, num_hiddens = 784, 10, 256

W1 = torch.tensor(np.random.normal(0, 0.01, (num_inputs, num_hiddens)), dtype=torch.float)
b1 = torch.zeros(num_hiddens, dtype=torch.float)
W2 = torch.tensor(np.random.normal(0, 0.01, (num_hiddens, num_outputs)), dtype=torch.float)
b2 = torch.zeros(num_outputs, dtype=torch.float)

params = [W1, b1, W2, b2]
for param in params:
    param.requires_grad_(requires_grad=True)