Keras中的动态激活功能

时间:2019-04-20 07:06:24

标签: tensorflow keras keras-layer

我正在做一个研究项目,涉及用多项式激活替换某些ReLu激活。我继承的代码是将Keras与TensorFlow后端结合使用-我对此经验很少。

基本上,我正在构建普通的ResNet图,并且需要逐步用自定义函数替换掉一些ReLu。换句话说,我的自定义激活需要执行以下操作:

def activation(x)
    approx = .1992 + .5002*x + .1997*x**2
    relu = tf.nn.relu(x)
    diff = (TOTAL_EPOCHS - CURRENT_EPOCH) / TOTAL_EPOCHS
    return (1-diff)*approx + diff*relu

我遇到的问题是弄清楚如何使用keras和model.fit通过当前时代使函数动态化。我尝试了一些事情,例如定义自定义层,传递计数器变量以及尝试使用tensorflow的全局step变量,但是每次尝试都会遇到烦人的错误。我想知道是否有一种我忽略的简单方法?看来这应该是微不足道的,但我只是缺乏框架方面的经验。

1 个答案:

答案 0 :(得分:2)

您可以使用keras.callbacks.Callback使用keras和model.fit通过当前时代使函数动态化。这是使激活函数的返回值等于当前纪元的示例。从MSE值,您可以快速看到当前纪元参与了激活函数的计算。

from keras.models import Model
from keras.layers import Activation,Input
from keras.utils.generic_utils import get_custom_objects
import keras.backend as K
from keras.callbacks import Callback

class MonitorCallback(Callback):
    def __init__(self, CURRENT_EPOCH):
        self.parm = CURRENT_EPOCH
    def on_epoch_begin(self, epoch, logs=None):
        K.set_value(self.parm, epoch)

CURRENT_EPOCH = K.variable(0)
TOTAL_EPOCHS = 8
def custom_activation(x):
    return CURRENT_EPOCH

num_input = Input(shape=(1,))
get_custom_objects().update({'custom_activation': Activation(custom_activation)})
output = Activation(custom_activation)(num_input)
model = Model(num_input,output)
model.compile(optimizer='rmsprop',loss='mse',metrics=['mse'])

model.fit(x=[1],y=[2],epochs=TOTAL_EPOCHS,callbacks=[MonitorCallback(CURRENT_EPOCH)])

# print
Using TensorFlow backend.
Epoch 1/8
1/1 [==============================] - 2s 2s/step - loss: 4.0000 - mean_squared_error: 4.0000
Epoch 2/8
1/1 [==============================] - 0s 2ms/step - loss: 1.0000 - mean_squared_error: 1.0000
Epoch 3/8
1/1 [==============================] - 0s 2ms/step - loss: 0.0000e+00 - mean_squared_error: 0.0000e+00
Epoch 4/8
1/1 [==============================] - 0s 2ms/step - loss: 1.0000 - mean_squared_error: 1.0000
Epoch 5/8
1/1 [==============================] - 0s 3ms/step - loss: 4.0000 - mean_squared_error: 4.0000
Epoch 6/8
1/1 [==============================] - 0s 3ms/step - loss: 9.0000 - mean_squared_error: 9.0000
Epoch 7/8
1/1 [==============================] - 0s 3ms/step - loss: 16.0000 - mean_squared_error: 16.0000
Epoch 8/8
1/1 [==============================] - 0s 3ms/step - loss: 25.0000 - mean_squared_error: 25.0000

请注意,keras.callbacks.Callback中的纪元从零开始计数。您可以尝试用激活功能替换custom_activation