自定义激活函数
通过定义个操作 Tensor 的函数,然后将其添加到 keras 系统中即可。
from keras.utils.generic_utils import get_custom_objects
def binary(x):
# 注: tf.greater 函数没有 gradient 函数,因此在运行时候会报错
# ValueError: An operation has `None` for gradient. Please make sure that all of your ops have a gradient
# defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.
return K.cast(tf.greater(x, 0), tf.uint8)
# custom activation function
get_custom_objects().update({'binary': Activation(binary)})
自定义层
在 keras 层中除去输入层以外,不能使用没有定义 gradient 函数的函数,否则会报错。
因此如下层只能做 Input 层使用:
class MaskLayer(Layer):
"""
输入与输出维度一致
输出为 0/1
"""
def __init__(self, **kwargs):
self.weight_m = None
super(MaskLayer, self).__init__(**kwa