I'm using Keras for a regression task and want to restrict my output to a range (say between 1 and 10)
Is there a way to ensure this?
Target of neural network is the goal you want to reach it . The output value of your system should be equal it.
Neural network models can be configured for multi-output regression tasks.
Tanh Activation is an activation function used for neural networks: f ( x ) = e x − e − x e x + e − x. Historically, the tanh function became preferred over the sigmoid function as it gave better performance for multi-layer neural networks.
Write a custom activation function like this
# 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()
And you are expected to see the min
and max
values of b
are very close to 1
and 10
, respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With