如何更改在 PyTorch 中的嵌入层上执行一维卷积的轴?
How to change the axis on which 1 dimensional convolution is performed on embedding layer in PyTorch?
我一直在玩 PyTorch 中的文本分类,但遇到了一维卷积问题。
我设置了维度 (x, y, z) 的嵌入层,其中:
x - 表示批量大小
y - 表示句子的长度(用 padding 固定,所以 40 个单词)
z - 预训练词嵌入的维度(目前为 100)
为简单起见,假设我输入了 (1,40, 100)
的矩阵
然而,据我所知,一旦我执行 torch.nn.conv1d(*args),
生成的矩阵变为(批量大小 = 1,字大小 = 40,特征图大小 = 98),内核大小为 3.
基本上,据我了解,它围绕 y 轴而不是 x 轴进行卷积,并且它不会捕获词嵌入之间的空间关系。
有什么方法可以更改卷积层,使其计算围绕不同轴的特征图吗?
TL,DR:
Torch conv1d 层在嵌入层上的行为方式如下:
enter image description here
但我希望它表现得像这样
enter image description here
如有任何帮助,我们将不胜感激。
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
在卷积之前进行图形评估时转置嵌入:
def forward(self, bacth_text):
x = self.embeddings(batch_text)
x = torch.transpose(x, 1, 2)
x = self.conv1d(x)
我一直在玩 PyTorch 中的文本分类,但遇到了一维卷积问题。
我设置了维度 (x, y, z) 的嵌入层,其中: x - 表示批量大小 y - 表示句子的长度(用 padding 固定,所以 40 个单词) z - 预训练词嵌入的维度(目前为 100)
为简单起见,假设我输入了 (1,40, 100)
的矩阵然而,据我所知,一旦我执行 torch.nn.conv1d(*args), 生成的矩阵变为(批量大小 = 1,字大小 = 40,特征图大小 = 98),内核大小为 3.
基本上,据我了解,它围绕 y 轴而不是 x 轴进行卷积,并且它不会捕获词嵌入之间的空间关系。
有什么方法可以更改卷积层,使其计算围绕不同轴的特征图吗?
TL,DR:
Torch conv1d 层在嵌入层上的行为方式如下: enter image description here
但我希望它表现得像这样
enter image description here
如有任何帮助,我们将不胜感激。
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
在卷积之前进行图形评估时转置嵌入:
def forward(self, bacth_text):
x = self.embeddings(batch_text)
x = torch.transpose(x, 1, 2)
x = self.conv1d(x)