tf.keras如何设置Conv2D的默认参数?

How to set the default parameters of Conv2D in tf.keras?

支持我有一个有 5 个卷积的网络。我用Keras写的。

x = Input(shape=(None, None, 3))
y = Conv2D(10, 3, strides=1)(x)
y = Conv2D(16, 3, strides=1)(y)
y = Conv2D(32, 3, strides=1)(y)
y = Conv2D(48, 3, strides=1)(y)
y = Conv2D(64, 3, strides=1)(y)

我想将所有卷积 kernel_initializer 设置为 xavier。方法之一是:

x = Input(shape=(None, None, 3))
y = Conv2D(10, 3, strides=1, kernel_initializer=tf.glorot_uniform_initializer())(x)
y = Conv2D(16, 3, strides=1, kernel_initializer=tf.glorot_uniform_initializer())(y)
y = Conv2D(32, 3, strides=1, kernel_initializer=tf.glorot_uniform_initializer())(y)
y = Conv2D(48, 3, strides=1, kernel_initializer=tf.glorot_uniform_initializer())(y)
y = Conv2D(64, 3, strides=1, kernel_initializer=tf.glorot_uniform_initializer())(y)

但是这种写法很伤感,代码也很冗余。

有没有更好的写法?

Keras 没有提供更改默认值的方法,所以您可以只做一个包装函数:

def myConv2D(filters, kernel):
    return Conv2D(filters, kernel, strides=1, kernel_initializer=tf.glorot_uniform_initializer())

然后将其用作:

x = Input(shape=(None, None, 3))
y = myConv2D(10, 3)(x)
y = myConv2D(16, 3)(y)
y = myConv2D(32, 3)(y)
y = myConv2D(48, 3)(y)
y = myConv2D(64, 3)(y)

最好制作一个 lambda,它将制作一个 Conv2D 层,并根据需要修复初始化程序,并在模型定义部分调用它。

我认为 lambda 比函数更适合这种情况。

你可以这样做,

customConv = lambda filters, kernel : Conv2D(filters, kernel, strides=1, kernel_initializer=tf.glorot_uniform_initializer())

x = Input(shape=(None, None, 3))

y = customConv(10, 3)(x)
y = customConv(16, 3)(y)
y = customConv(32, 3)(y)
y = customConv(48, 3)(y)
y = customConv(64, 3)(y)