Tensorflow的tf.keras.layers.Dense和PyTorch的torch.nn.Linear之间的区别?

Alp*_*a96 22 tensorflow pytorch

我有一个关于 Tensorflow 如何定义其线性层的快速(可能是愚蠢的)问题。在 PyTorch 中,线性(或密集)层定义为 y = x A^T + b,其中 A 和 b 是线性层的权重矩阵和偏差向量(请参阅此处)。

但是,我无法精确找到 Tensorflow 的等效方程!它与 PyTorch 相同还是只是 y = x A + b ?

先感谢您!

M.I*_*nat 23

如果我们在 API 中将激活设置为None密集层keras,那么它们在技术上是等效的。

张量流的

tf.keras.layers.Dense(..., activation=None) 
Run Code Online (Sandbox Code Playgroud)

根据医生的说法,在这里进行更多研究。

激活:要使用的激活函数。如果您未指定任何内容,则不会应用任何激活(即“线性”激活:a(x) = x)。

在 PyTorch 的src中。

torch.nn.Linear
Run Code Online (Sandbox Code Playgroud)

此时他们是平等的。对输入数据的线性变换:y = x*W^T + b. 请参阅下面这两个更具体的等效实现。在 中PyTorch,我们做

class Network(torch.nn.Module):
    def __init__(self):
        super(Network, self).__init__()
        self.fc1 = torch.nn.Linear(5, 30)
    def forward(self, state):
        return self.fc1(state)
Run Code Online (Sandbox Code Playgroud)

或者,

trd = torch.nn.Linear(in_features = 3, out_features = 30)
y = trd(torch.ones(5, 3))
print(y.size())
# torch.Size([5, 30])
Run Code Online (Sandbox Code Playgroud)

它的等效tf实现是

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(30, input_shape=(5,), activation=None)) 
Run Code Online (Sandbox Code Playgroud)

或者,

tfd = tf.keras.layers.Dense(30, input_shape=(3,), activation=None)
x = tfd(tf.ones(shape=(5, 3)))
print(x.shape)
# (5, 30)
Run Code Online (Sandbox Code Playgroud)


Ale*_*lex 6

tf.keras.layers.Dense在tensorflow源代码中定义:

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/keras/layers/core.py#L1081

如果您遵循其函数中的引用call,它将引导您找到此处使用的运算的定义,这实际上是输入和权重的矩阵乘法加上预期的偏差向量:

https://github.com/tensorflow/tensorflow/blob/a68c6117a1a53431e739752bd2ab8654dbe2534a/tensorflow/python/keras/layers/ops/core.py#L74

outputs = gen_math_ops.MatMul(a=inputs, b=kernel)
...
outputs = nn_ops.bias_add(outputs, bias)

Run Code Online (Sandbox Code Playgroud)

  • 在上面 TF 源代码的第一个链接的第 1192 行(https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/keras/layers/core.py#L1192)中,权重用 `shape=[last_dim, self.units]` (N_feats, N_out) 和 PyTorch [(源代码链接)](https://github.com/pytorch/pytorch/blob/master/torch/nn/ module/linear.py#L79),权重用“Parameter(torch.Tensor(out_features, in_features))” (N_out, N_feats) 初始化 (2认同)