Keras multiply layer output with scalar
Not sure if it is useful to answer an old question, but maybe someone else has run into the same problem.
The issue is indeed the shape of your scalar versus the shape of your input (or x). You should reshape your scalar to have as many dimensions as the matrix you're multiplying with, using np.reshape
, e.g.:
from keras import *
from keras.layers import *
import numpy as np
# inputs
X = np.ones((32,32,128,128))
s = np.arange(32).reshape(-1,1,1,1) # 1 different scalar per batch example, reshaped
print(X.shape, s.shape)
# model
input_X = Input(shape=(32,128,128))
input_scalar = Input(shape = (1,1,1))
sc_mult = Lambda(lambda x: x * input_scalar)(input_X)
model = Model(inputs=[input_X, input_scalar], outputs=sc_mult)
out = model.predict([X,s])
out
Now out[0,:,:,:]
is all zeros, out[1,:,:,:]
is all ones, out[31,:,:,:]
is all 31
s, et cetera.