我正在研究一个具有线性层的神经网络架构,如果它高于某个阈值,我需要该层的输出与输入相同,即
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]
有没有办法获取最大值和最小值,在每个epoch和batch update之后计算阈值,从而得到阈值输出
最佳答案
你可以定义一个 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))
关于keras - 基于输出值的最大值和最小值的阈值线性层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48050900/