tensorflow在pyTorch中的时间分布等效项

时间:2020-07-15 09:54:43

标签: tensorflow pytorch

是否存在用于pytorch的tensorflow.keras.layers.Timedistributed的等效实现?

我正在尝试构建类似 时间分配的(Resnet50())。

1 个答案:

答案 0 :(得分:4)

this topic上的miguelvr信用。

您可以使用此代码,该代码是为模仿Timeditributed包装器而开发的PyTorch模块。

import torch.nn as nn

class TimeDistributed(nn.Module):
    def __init__(self, module, batch_first=False):
        super(TimeDistributed, self).__init__()
        self.module = module
        self.batch_first = batch_first

    def forward(self, x):

        if len(x.size()) <= 2:
            return self.module(x)

        # Squash samples and timesteps into a single axis
        x_reshape = x.contiguous().view(-1, x.size(-1))  # (samples * timesteps, input_size)

        y = self.module(x_reshape)

        # We have to reshape Y
        if self.batch_first:
            y = y.contiguous().view(x.size(0), -1, y.size(-1))  # (samples, timesteps, output_size)
        else:
            y = y.view(-1, x.size(1), y.size(-1))  # (timesteps, samples, output_size)

        return y