gpt4 book ai didi

python - PyTorch 置换在 RCNN 中的使用

转载 作者:行者123 更新时间:2023-12-04 15:08:53 32 4
gpt4 key购买 nike

我正在研究使用 PyTorch 进行文本分类的 RCNN 实现。 Full Code .有两点使用 permute 函数置换张量的维度。第一个是在 LSTM 层之后和 tanh 之前。第二个是在线性层之后和最大池化层之前。

您能否解释一下为什么排列是必要的或有用的?

相关代码

    def forward(self, x):
# x.shape = (seq_len, batch_size)
embedded_sent = self.embeddings(x)
# embedded_sent.shape = (seq_len, batch_size, embed_size)

lstm_out, (h_n,c_n) = self.lstm(embedded_sent)
# lstm_out.shape = (seq_len, batch_size, 2 * hidden_size)

input_features = torch.cat([lstm_out,embedded_sent], 2).permute(1,0,2)
# final_features.shape = (batch_size, seq_len, embed_size + 2*hidden_size)

linear_output = self.tanh(
self.W(input_features)
)
# linear_output.shape = (batch_size, seq_len, hidden_size_linear)

linear_output = linear_output.permute(0,2,1) # Reshaping fot max_pool

max_out_features = F.max_pool1d(linear_output, linear_output.shape[2]).squeeze(2)
# max_out_features.shape = (batch_size, hidden_size_linear)

max_out_features = self.dropout(max_out_features)
final_out = self.fc(max_out_features)
return self.softmax(final_out)

其他存储库中的类似代码

RCNN 的类似实现使用permutetranspose。以下是示例:

最佳答案

permute 函数所做的是根据所需的顺序重新排列原始张量,注意 permute 不同于 reshape 函数,因为当应用 permute 时,张量中的元素遵循您提供的索引,而在 reshape 中则不是。

示例代码:

import torch 
var = torch.randn(2, 4)
pe_var = var.permute(1, 0)
re_var = torch.reshape(var, (4, 2))
print("Original size:\n{}\nOriginal var:\n{}\n".format(var.size(), var) +
"Permute size:\n{}\nPermute var:\n{}\n".format(pe_var.size(), pe_var) +
"Reshape size:\n{}\nReshape var:\n{}\n".format(re_var.size(), re_var))

输出:

Original size:
torch.Size([2, 4])
Original var:
tensor([[ 0.8250, -0.1984, 0.5567, -0.7123],
[-1.0503, 0.0470, -1.9473, 0.9925]])
Permute size:
torch.Size([4, 2])
Permute var:
tensor([[ 0.8250, -1.0503],
[-0.1984, 0.0470],
[ 0.5567, -1.9473],
[-0.7123, 0.9925]])
Reshape size:
torch.Size([4, 2])
Reshape var:
tensor([[ 0.8250, -0.1984],
[ 0.5567, -0.7123],
[-1.0503, 0.0470],
[-1.9473, 0.9925]])

考虑到 permute 的作用,我们可以看到第一个 permute 所做的是重新排序连接张量,以适应​​ self.W 的输入格式,即以批处理为第一维;第二个 permute 做类似的事情,因为我们想要沿着序列最大池化 linear_output 并且 F.max_pool1d 将沿着最后一个维度池化。

关于python - PyTorch 置换在 RCNN 中的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65571264/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com