Reputation: 863
Support i have a network with 5 convolution. I write it by 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)
I want set all convolution's kernel_initializer
to xavier. One of method is:
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)
But this kind of writing is very sad and the code is very redundant.
Is there a better way of writing?
Upvotes: 0
Views: 561
Reputation: 11917
Better make a lambda
that will make a Conv2D
layer and fix the initializer as needed and call it in the model definition part.
I think lambda is more suitable in this situation than a function.
You can do it like this,
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)
Upvotes: 1
Reputation: 56367
Keras provides no way to change the defaults, so you can just make a wrapper function:
def myConv2D(filters, kernel):
return Conv2D(filters, kernel, strides=1, kernel_initializer=tf.glorot_uniform_initializer())
And then use it as:
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)
Upvotes: 3