支持我有一个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)
但是这种写法很难过,代码也很多余。
有更好的写作方式吗?
答案 0 :(得分:3)
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)
答案 1 :(得分:1)
更好地制作一个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)