如何在 PyTorch 上编写这一行? tf.keras.layers.PReLU(shared_axes=[1,2])(x)
shared_axes=[1,2]很重要
我在某处找到了这个解决方案,但我不确定它是否正确: nn.PReLU(num_parameters=1)
先谢谢大家了!
PyTorch 似乎默认执行
shared_axis
操作。我们可以用下面的代码来检查:
TensorFlow:
import tensorflow as tf
x = tf.keras.layers.PReLU(shared_axes=(1,2))
x.build((None, 10, 10, 3)) # initialize the weights to an image-like input shape
print(x.weights[0].shape) # will print 'TensorShape([1, 1, 3])'
# if we omit the shared_axes parameter we get:
x = tf.keras.layers.PReLU()
x.build((None, 10, 10, 3)) # initialize the weights to an image-like input shape
print(x.weights[0].shape) # will print 'TensorShape([10, 10, 3])'
PyTorch:
from torch import nn
x = nn.modules.activation.PReLU()
print(x.weight.shape) # will print 'torch.Size([1])'
# to get one parameter per filter we have to set it
x = nn.modules.activation.PReLU(3)
print(x.weight.shape) # will print 'torch.Size([3])'
希望有助于理解差异。您还可以通过列表初始化torch版本来获取第二个版本的TF代码。
另一个区别是 TensorFlow 使用
0.0
进行初始化,而 PyTorch 使用 0.25
进行初始化。要获得与 TensorFlow 完全相同的初始化,请执行以下操作:
f = #number of filters of the previous layer
x = nn.modules.activation.PReLU(f, init=0.0)