Search code examples
keraskeras-layertf.keras

Multiply output of Keras layer with a scalar


Pardon me if this is a poorly framed question. This happens to be my first question here.

Say I have an output layer in Keras, and I want to multiply the last value (result of sigmoid activation) with a scalar (say 5).

(I have attached a code snippet here. Assume all necessary libraries / dependencies included)

def create_model():
    inp = Input(shape=(561,))
    x = Dense(units=1024,input_dim=561)(inp)
    x = LeakyReLU(0.2)(x)
    x = Dropout(0.3)(x)
    x = Dense(units=512)(x)
    x = LeakyReLU(0.2)(x)
    x = Dropout(0.3)(x)
    x = Dense(units=256)(x)
    x = LeakyReLU(0.2)(x)

    x = Dense(units=1, activation='sigmoid')(x)
    
    m = tf.convert_to_tensor(5) #creating a tensor of value = 5
    
    o = Multiply()([x, m]) #trying to multiply x with o. Doesn't work though!

    model = Model(inputs=[inp], outputs=[o])
    
    model.compile(loss='binary_crossentropy', optimizer = Adam(lr=0.0002, beta_1=0.5))
    
    return model

model = create_model()
model.summary()

I tried this, and I am getting "tuple index out of range" error. I would be glad if someone could help me (i.e in multiplication of last layer's output with a scalar)


Solution

  • Check the dimensions.The dimensions of x and m are not matching. Use Lambda layer instead of Multiply. This will definitely solve your problem.