Keras:连接输入和输出的约束

时间:2017-12-16 18:10:21

标签: python tensorflow constraints keras

有没有办法可以对序列预测强制执行约束?

说,如果我的建模如下:

model = Sequential()
model.add(LSTM(150, input_shape=(n_timesteps_in, n_features)))
model.add(RepeatVector(n_timesteps_in))
model.add(LSTM(150, return_sequences=True))
model.add(TimeDistributed(Dense(n_features, activation='linear')))
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['acc'])

我可以以某种方式捕获model.pred(x) <= x

的约束

docs表明我们可以为网络权重添加约束。但是,他们没有提到如何映射输入和输出之间的关系或约束。

2 个答案:

答案 0 :(得分:4)

从未听说过它....但是有很多方法可以使用功能API模型和自定义函数来实现它。

下面,有一个可能的答案,但首先,这真的是最好的吗?

如果您正在尝试创建自动编码器,则不应该关心限制输出。否则,你的模型将不会真正学到很多东西。

也许最好的办法就是首先将输入标准化(在-1和+1之间),然后在最后使用app.module.ts激活。

保留输入的功能API模型:

tanh

自定义限制选项

有无限的方法可以做到这一点,这里有一些可能或可能不是你需要的例子。但是你可以自由地开发类似的东西。

以下选项将各个输出限制为各自的输入。但您可能更愿意使用限制在最大输入范围内的所有输出。

如果是,请使用以下内容:inputTensor = Input(n_timesteps_in, n_features) out = LSTM(150, input_shape=)(inputTensor) out = RepeatVector(n_timesteps_in)(out) #this line sounds funny in your model... out = LSTM(150, return_sequences=True)(out) out = TimeDistributed(Dense(n_features))(out) out = Activation(chooseOneActivation)(out) out = Lambda(chooseACustomFunction)([out,inputTensor]) model = Model(inputTensor,out) model.compile(...)

1 - 一个简单的拉伸'tanh':

您可以使用maxInput = max(originalInput, axis=1, keepdims=True)(范围从-1到+1)并将其乘以输入来简单地定义上限和下限。

使用tanh图层以及Activation('tanh')图层中的以下自定义函数:

Lambda

我不完全确定这将是一个健康的选择。如果想要创建一个自动编码器,这个模型很容易找到一个输出尽可能接近1的所有import keras.backend as K def stretchedTanh(x): originalOutput = x[0] originalInput = x[1] return K.abs(originalInput) * originalOutput 激活的解决方案,而不是真正查看输入。

2 - 修改'relu'

首先,您可以根据输入简单地tanh输出,更改 relu 激活。使用上面模型中的clip以及Activation('relu')(out)图层中的以下自定义函数:

Lambda

当一切都超过极限并且反向传播无法返回时,这可能有一个缺点。 ('relu'可能会出现问题)。

3 - 半线性,半修改tanh

在这种情况下,您不需要def modifiedRelu(x): negativeOutput = (-1) * x[0] #ranging from -infinite to 0 originalInput = x[1] #ranging from -infinite to originalInput return negativeOutput + originalInput #needs the same shape between input and output 图层,也可以将其用作Activation

'linear'

答案 1 :(得分:2)

Keras提供了一种处理此类微不足道约束的简便方法。我们可以写virtual

完整示例

out = Minimum()([out, input_tensor])

这是模型的网络结构。它显示了输入和输出如何用于计算钳位输出。

enter image description here

相关问题