关于Tensorflow是如何定义其线性层的,我有一个快速的(也可能是愚蠢的)问题。在PyTorch中,线性(或稠密)层定义为,y=x^T+b,其中A和b是线性层的权重矩阵和偏置向量(见这里)。
然而,我无法精确地为Tensorflow找到一个等价的方程!它和PyTorch是一样的还是只是y=x+b?
提前谢谢你!
发布于 2021-03-14 16:28:06
tf.keras.layers.Dense
是在tensorflow源代码中定义的:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/keras/layers/core.py#L1081
如果您遵循它的call
函数中的引用,它将引出这里使用的操作的定义,它实际上是输入和权重的矩阵乘法加上预期的偏置向量:
outputs = gen_math_ops.MatMul(a=inputs, b=kernel)
...
outputs = nn_ops.bias_add(outputs, bias)
发布于 2021-03-14 16:43:22
如果我们在None
API中的密集层中设置keras
激活,那么它们在技术上是等价的。
丹索尔·弗洛
tf.keras.layers.Dense(..., activation=None)
激活:要使用的激活功能。如果不指定任何内容,则不应用任何激活(即。“线性”激活: a(x) =x。
在PyTorch的src里。
torch.nn.Linear
现在他们在这一点上是平等的。对传入数据的线性转换: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)
或,
trd = torch.nn.Linear(in_features = 3, out_features = 30)
y = trd(torch.ones(5, 3))
print(y.size())
# torch.Size([5, 30])
它的等效tf
实现应该是
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(30, input_shape=(5,), activation=None))
或,
tfd = tf.keras.layers.Dense(30, input_shape=(3,), activation=None)
x = tfd(tf.ones(shape=(5, 3)))
print(x.shape)
# (5, 30)
https://stackoverflow.com/questions/66626700
复制相似问题