【问题标题】:How to restrict output of a neural net to a specific range?如何将神经网络的输出限制在特定范围内?
【发布时间】:2018-09-29 08:59:18
【问题描述】:

我正在使用 Keras 执行回归任务,并希望将我的输出限制在一个范围内(比如 1 到 10 之间)

有没有办法确保这一点?

【问题讨论】:

  • ...minmax 是你的朋友吗?这是你想要的吗?
  • 是的,我将如何使用它?
  • 例如。 model.add(Dense(1)) 是我的最后一层。如何添加最小、最大约束?

标签: python neural-network keras regression


【解决方案1】:

像这样写一个自定义激活函数

# a simple custom activation
from keras import backend as BK
def mapping_to_target_range( x, target_min=1, target_max=10 ) :
    x02 = BK.tanh(x) + 1 # x in range(0,2)
    scale = ( target_max-target_min )/2.
    return  x02 * scale + target_min

# create a simple model
from keras.layers import Input, Dense
from keras.models import Model
x = Input(shape=(1000,))
y = Dense(4, activation=mapping_to_target_range )(x)
model = Model(inputs=x, outputs=y)

# testing
import numpy as np 
a = np.random.randn(10,1000)
b = model.predict(a)
print b.min(), b.max()

您应该会看到bminmax 值分别非常接近110

【讨论】:

    【解决方案2】:

    标准化您的输出,使其在 0、1 范围内。确保您的标准化函数允许您稍后将它们转换回来。

    sigmoid 激活函数的输出始终在 0 和 1 之间。只需确保您的最后一层具有 sigmoid 激活功能,以将您的输出限制在该范围内。现在您可以获取输出并将它们转换回您想要的范围。

    您还可以考虑编写自己的激活函数来转换数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-23
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多