如何将神经网络的输出限制在特定范围内?

meg*_*ams 3 python regression neural-network keras

我将Keras用于回归任务,并希望将输出限制在一定范围内(例如1到10)

有没有办法确保这一点?

pit*_*all 6

编写这样的自定义激活功能

# 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()
Run Code Online (Sandbox Code Playgroud)

并且您应该看到的minmaxb分别非常接近110


Pri*_*usa 5

对输出进行归一化,使其在0,1范围内。请确保使用归一化功能稍后再将其转换回去。

乙状结肠激活功能始终在0、1之间输出。只需确保您的最后一层具有乙状结肠激活,以将您的输出限制在该范围内。现在,您可以获取输出并将其转换回所需的范围。

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