【问题标题】:How to change the axis on which 1 dimensional convolution is performed on embedding layer in PyTorch?如何更改在 PyTorch 的嵌入层上执行一维卷积的轴?
【发布时间】:2019-08-09 03:42:39
【问题描述】:

我一直在使用 PyTorch 中的文本分类,但遇到了一维卷积的问题。

我设置了一个维度 (x, y, z) 的嵌入层,其中: x - 表示批量大小 y - 表示句子的长度(用填充固定,所以 40 个单词) z - 预训练词嵌入的维度(目前为 100)

为简单起见,假设我放入了一个 (1,40, 100) 的矩阵

但是,据我所知,一旦我执行了 torch.nn.conv1d(*args), 生成的矩阵变为 (batch size = 1, word size = 40, feature map size = 98),内核大小为 3。

基本上,据我了解,它围绕 y 轴而不是 x 轴进行卷积,并且它不会捕捉词嵌入之间的空间关系。

有什么办法可以改变卷积层,让它围绕不同的轴计算特征图?

TL、DR:

Torch conv1d 层在嵌入层上的行为方式如下: enter image description here

但我希望它表现得像这样

enter image description here

任何帮助将不胜感激。

【问题讨论】:

    标签: python conv-neural-network pytorch embedding


    【解决方案1】:

    在卷积之前进行图评估时转置嵌入:

        def forward(self, bacth_text):
            x = self.embeddings(batch_text)
            x = torch.transpose(x, 1, 2)
            x = self.conv1d(x)
    

    【讨论】:

      【解决方案2】:

      conv1d 期望输入的大小为 (batch_size, num_channels, length) 并且无法更改它,因此您有两种可能的方法,您可以permute 嵌入的输出,也可以使用一个 conv1d 而不是嵌入层(in_channels = num_words、out_channels=word_embedding_size 和 kernel_size=1),它比嵌入慢,不是一个好主意!

      input = torch.randint(0, 10, (batch_size, sentence_length))
      embeddings = word_embedding(input) #(batch_size, sentence_length, embedding_size)
      embeddings_permuted = embeddings.permute(0, 2, 1) #(batch_size, embedding_size, sentence_length)
      conv_out = convolution(embeddings_permuted) #(batch_size, conv_out_channels, changed_sentence_length)
      #now you can either use the output as it is or permute it back (based on your upper layers)
      #also note that I wrote changed_sentence_length because it is a fucntion of your padding and stride 
      

      【讨论】:

      • 非常感谢,我想我会尝试对嵌入矩阵进行排列,看看效果如何,因为我已经在 keras 中获得了种子训练模型。我会投票给你,但由于这是我的第一篇文章,由于积分系统或其他原因,我无法这样做:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 2019-01-16
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 2022-01-10
      • 2018-07-26
      相关资源
      最近更新 更多