基于输出值的最大值和最小值的阈值线性层

时间:2018-01-01 15:31:57

标签: keras

我正在开发一个具有线性层的神经网络架构,如果它高于某个阈值,我需要层的输出与输入相同,即

a(x) = x if x >= threshold      else a(x) = 0 if x < threshold

线性层如下:

t = Dense(100)

因此,我在keras中的Dense层之后使用了ThresholdedReLU层。阈值是这样的,它取决于Dense层输出值的最大值和最小值:

threshold = delta*min{s} + (1-delta)*max{s}
where min{s} is the minimum of the 100 output values of the Dense layer
and   max{s} is the maximum of the 100 output values of the Dense layer
and   delta is a value between [0,1]

有没有办法可以获得最大值和最小值,在每个纪元和批量更新后计算阈值,从而获得阈值输出

1 个答案:

答案 0 :(得分:2)

您可以定义Lambda layer并在其中使用后端功能。我就是这样做的:

from keras.layers import Dense, Lambda
from keras.models import Sequential
import keras.backend as K
import numpy as np


def thresholded_relu(x, delta):
    threshold = delta * K.min(x, axis=-1) + (1 - delta) * K.max(x, axis=-1)
    return K.cast((x > threshold[:, None]), dtype=K.dtype(x)) * x


delta = 0.5
model = Sequential()
# model.add(Dense(100, input_shape=(100,)))
model.add(Lambda(lambda x: thresholded_relu(x, delta), input_shape=(100,)))
model.compile('sgd', 'mse')

x = np.arange(0, 100, 1)[None, :]
pred = model.predict(x)
for y, p in zip(x[0], pred[0]):
    print('Input: {}. Pred: {}'.format(y, p))
相关问题