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

标签 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]

有没有办法获取最大值和最小值,在每个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/

相关文章:

tensorflow - 在 keras.sequential 模型中使用 keras.layers.Add()

python - 将卡住的 TensorFlow pb 包装在 tf.keras 模型中

python - 迁移学习失败,因为密集层预计具有形状(无,1)

tensorflow - 使用 Keras model.fit_generator 时 CUDA|RAM 内存不足

python - 具有大数据集的 Keras 模型的超参数优化

keras:在模型中加载保存的模型权重以进行评估

python - 如何在 Keras 中实现具有多个输出的自定义层?

machine-learning - 如何在 Keras 上仅加载特定权重

python - Tensorflow 模型返回疯狂的损失值

tensorflow - 基于过去和 future 值的每个时间序列步骤的二元分类