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

支持我有一个具有 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)

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


有没有更好的写作方式?


幕布斯7119047
浏览 247回答 2
2回答

精慕HU

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)

慕雪6442864

更好地 make alambda将创建一个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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python