【问题标题】:PyTorch equivalent of a Tensorflow linear layerPyTorch 等效于 Tensorflow 线性层
【发布时间】:2020-03-28 18:33:58
【问题描述】:

我试图使用 PyTorch 框架重新实现 TensorFlow 代码。下面我包含了 TF 示例代码和我的 PyT 解释。

TensorFlow 实现:

W1 = tf.Variable(xavier_init([135, 128]))
b1 = tf.Variable(tf.zeros(shape=[128]))

def fcn(x):
    z = tf.reshape(x, (-1, 135))
    out1 = leaky_relu( tf.matmul(z, W1) + b1 )

    return out1

PyTorch 实现:

class decoder(nn.Module):
    def __init__(self):
        super(decoder, self).__init__()

        self.layer_10 = nn.Linear(135, 128, bias=True)
        self.leaky = nn.LeakyReLU(0.2, inplace=False)
        init.xavier_uniform(self.layer_10.weight) 

    def forward(self, x):
        z = x.view(-1, 135)
        h30 = self.leaky(self.layer_10(z))

        return h30

我想知道实现 matmul 部分的正确方法是什么,因为 pytorch 中的权重没有像 TF 中那样明确定义(或者如果我错了,请纠正我)。

【问题讨论】:

    标签: tensorflow pytorch


    【解决方案1】:

    你不需要显式地调用torch.matmul:它在nn.Linear层的forward方法的实现中。通过调用self.layer_10(z),您实际上是在(在后台)调用forward 方法,该方法执行矩阵乘法并为您添加偏差。

    如果您希望代码完全相同,您可能希望使用相同的方法显式初始化权重。为此,您拥有实现各种权重初始化的nn.init。具体来说,您可能会发现 nn.init.xavier_uniform_ 相关。

    【讨论】:

    • 谢谢解答,现在权重初始化好看吗?
    • @Blade 为此,您需要查看 xavier_init 在张量流中的作用,并查看它是否与 pytorch 的默认值匹配。我不知道确切的行为。
    • 谢谢。供未来读者参考,这就是programcreek.com/python/example/108253/… 中的第二个示例的方式
    猜你喜欢
    • 2021-08-01
    • 2021-10-11
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 2022-10-12
    • 2019-01-02
    • 2020-09-22
    • 2020-12-28
    相关资源
    最近更新 更多