How to set a default tensor as a Keras model input? - keras

I have a Keras model with multiple images as inputs, but after trained, I'd like to set some images as default input and let just a single placeholder/input as the Query image.
I tried to use layers.Input(tensor=my_default_tensor) but it doesn't seems to be what I need, the model still seems to need this input to be given during inference time. I'd like it to be hidden from the user, so he just needs to pass the query image as input.

Have you tried tf.keras.layers.Input(tensor=tftensor, shape=())?

I discovered that it is so easy that's why I couldn't find an answer while googling hahaha
It just needed to wrap my "default input images" as a tf.constant(input_image), so I could now use them as normal Keras inputs, but without the need to pass it as a Model input.
Usage example:
from tensorflow.keras import layers
from tensorflow.keras import Model
image_1 = cv2.imread("image/path/1.jpg")
image_2 = cv2.imread("image/path/2.jpg")
normal_input = layers.Input((256, 256, 3))
default_input_1 = tf.constant(image_1)
default_input_2 = tf.constant(image_2)
x_1 = embeddingModule(default_input_1)
x_2 = embeddingModule(default_input_2)
x_3 = embeddingModule(normal_input)
concat_x1_x3 = layers.Concatenate()([x_1, x_3])
concat_x2_x3 = layers.Concatenate()([x_2, x_3])
relation_1 = relationModule(concat_x1_x3)
relation_2 = relationModule(concat_x2_x3)
model = Model(inputs=[normal_input], outputs=[relation_1, relation_2])
Here, embeddingModule and relationModule are two pre-trained Keras models.

Related

Keras. How to concatenate intermediate layers of two different models into a third model

I have two sequential models that both do a pretty good job of classifying audio. One uses mfccs and the other wave forms. I am now trying to combine them into a third functional API model using one of the later Dense layers from each of the mfcc and wave form models. The example about how to get the intermediate layers in the Keras FAQ is not working for me (https://keras.io/getting-started/faq/#how-can-i-obtain-the-output-of-an-intermediate-layer).
Here is my code:
mfcc_model = load_model(S01_model_local_loc)
waveform_model = load_model(T01_model_local_loc)
mfcc_input = Input(shape=(79,30,1))
mfcc_model_as_layer = Model(inputs=mfcc_model.input,
outputs=mfcc_model.get_layer(name = 'dense_9').output)
waveform_input = Input(shape=(40000,1))
waveform_model_as_layer = Model(inputs=waveform_model.input,
outputs=waveform_model.get_layer(name = 'dense_2').output)
concatenated_1024 = concatenate([mfcc_model_as_layer, waveform_model_as_layer])
model_pred = layers.Dense(2, activation='sigmoid')(concatenated_1024)
uber_model = Model(inputs=[mfcc_input,waveform_input], outputs=model_pred)
This throws the error:
AttributeError: Layer sequential_5 has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use get_input_at(node_index) instead.
Changing the inputs to the first two Model statements to inputs=mfcc_model.get_input_at(1) and inputs=waveform_model.get_input_at(1) solves that error message, but I then get this error message:
ValueError: Graph disconnected: cannot obtain value for tensor Tensor("dropout_21_input:0", shape=(?, 79, 30, 1), dtype=float32) at layer "dropout_21_input". The following previous layers were accessed without issue: []
If I remove the .get_layer statements and just take the final output of the model the graph connects nicely.
What do I need to do to just get the output of the Dense layers that I want?
Update: I found a really hacky way of getting what I want. I pop'ed off the layers of the mfcc and wave form models until the output layers were what I wanted. Then the code below seems to work. I'd love to know the right way to do this!
mfcc_input = Input(shape=(79,30,1))
waveform_input = Input(shape=(40000,1))
mfcc_model_as_layer = mfcc_model(mfcc_input)
waveform_model_as_layer = waveform_model(waveform_input)
concatenated_1024 = concatenate([mfcc_model_as_layer, waveform_model_as_layer])
model_pred = layers.Dense(2, activation='sigmoid')(concatenated_1024)
test_model = Model(inputs=[mfcc_input,waveform_input], outputs=model_pred)

Keras - using embedding with multiple categorical variables

If I understand the concept of embedding matrices correctly, they exist to provide a more efficient way to encode categorical variables than by using one hot encoding. It seems that if you have multiple categorical variables as inputs to a Keras model, you need to use a separate embedding matrix for each categorical variable. However, I can't find a way to use embedding with multiple categorical variables using the Embedding class provided by Keras. The example in the documentation shows only how to use embedding when the input to the model is a single categorical variable. Can somebody please provide a working example of how to use embedding with Keras when the input consists of multiple categorical variables, and possibly other variables for which embedding is not used (for example, continuous variables)?
For each categorical variable, you can have separate embedding. Hope the below code helps.
inputss = []
embeddings = []
for c in self.categorical_vars:
inputs = Input(shape=(1,),name='input_sparse_'+c)
#no_of_unique_cat = data_lr[categorical_var].nunique()
embedding_size = min(np.ceil((no_of_unique_cat)/2), 50 )
embedding_size = int(embedding_size)
embedding = Embedding(no_of_unique_cat+1, embedding_size, input_length = 1)(inputs)
embedding = Reshape(target_shape=(embedding_size,))(embedding)
inputss.append(inputs)
embeddings.append(embedding)
input_numeric = Input(shape=(1,),name='input_constinuous')
embedding_numeric = Dense(16)(input_numeric)
inputss.append(input_numeric)
embeddings.append(embedding_numeric)
x = Concatenate()(embeddings)
x = Dense(10, activation = 'relu')(x)
x = Dropout(.15)(x)
out_control = Dense(output_shape)(x)

Using Keras like TensorFlow for gpu computing

I would like to know if Keras can be used as an interface to TensoFlow for only doing computation on my GPU.
I tested TF directly on my GPU. But for ML purposes, I started using Keras, including the backend. I would find it 'comfortable' to do all my stuff in Keras instead of Using two tools.
This is also a matter of curiosity.
I found some examples like this one:
http://christopher5106.github.io/deep/learning/2018/10/28/understand-batch-matrix-multiplication.html
However this example does not actually do the calculation.
It also does not get input data.
I duplicate the snippet here:
'''
from keras import backend as K
a = K.ones((3,4))
b = K.ones((4,5))
c = K.dot(a, b)
print(c.shape)
'''
I would simply like to know if I can get the result numbers from this snippet above, and how?
Thanks,
Michel
Keras doesn't have an eager mode like Tensorflow, and it depends on models or functions with "placeholders" to receive and output data.
So, it's a little more complicated than Tensorflow to do basic calculations like this.
So, the most user friendly solution would be creating a dummy model with one Lambda layer. (And be careful with the first dimension that Keras will insist to understand as a batch dimension and require that input and output have the same batch size)
def your_function_here(inputs):
#if you have more than one tensor for the inputs, it's a list:
input1, input2, input3 = inputs
#if you don't have a batch, you should probably have a first dimension = 1 and get
input1 = input1[0]
#do your calculations here
#if you used the batch_size=1 workaround as above, add this dimension again:
output = K.expand_dims(output,0)
return output
Create your model:
inputs = Input(input_shape)
#maybe inputs2 ....
outputs = Lambda(your_function_here)(list_of_inputs)
#maybe outputs2
model = Model(inputs, outputs)
And use it to predict the result:
print(model.predict(input_data))

How to make the enabling of a given layer, in a keras model, trainable?

I have the following siamese model:
I would like to make the enabling/disabling of layers a-L1 and b-L1 trainable. ie: a-L1 and/or b-L1 should be transparent (not used or disabled) for the current input if necessary. So, the model after training, will learn when it should enable/disable one or both of the layers a-L1 and b-L1.
I managed to train this model with 4 cases, so I got 4 different models accordingly:
model-1: without a-L1 and b-L1
model-2: without a-L1
model-3: without b-L1
model-4: with both a-L1 and b-L1
the performances of these models complement each other and I would like to combine them. Do you have some suggestions, please?
Let's consider you have trained four models and them let's call them m1, m2, m3 and m4
first define the input layer which is common for all of them.
inputs = Input(shape=your_inputs_shape)
model_1_output = m1(inputs)
model_2_output = m2(inputs)
model_3_output = m3(inputs)
model_4_output = m4(inputs)
merged_layer = Concatenate(axis=your_concatanation_axis)([model_1_output, model_2_output, model_3_output,model_4_output)
new_model = Model(inputs=inputs, outputs=merged_layer)
I hope this will solve your problem.
EDIT:
To answer your question on comment, It is possible to combine only the layers before L2. But you have to decide which model's layers starting from L2, you are going to use(Since you are not combining layers starting from L2). Let's assume you want to use m1 model's layers after L2. In addition I want to add the weighting mechanism I've specified above in comments of the answer.
First let's define new models with common new inputs
new_inputs = Input(shape=(inputs_shape))
new_m1 = keras.models.Model(inputs = new_inputs, outputs = m1(new_inputs))
new_m2 = keras.models.Model(inputs = new_inputs, outputs = m2(new_inputs))
new_m3 = keras.models.Model(inputs = new_inputs, outputs = m3(new_inputs))
new_m4 = keras.models.Model(inputs = new_inputs, outputs = m4(new_inputs))
Now get the L2 layer for all models
model1_l2 = new_m1.layers[1].get_layer("L2").output
model2_l2 = new_m2.layers[1].get_layer("L2").output
model3_l2 = new_m3.layers[1].get_layer("L2").output
model4_l2 = new_m4.layers[1].get_layer("L2").output
weighted merge
merged = Concatenate(axis=your_concatanation_axis)([model1_l2, model2_l2, model3_l2,model4_l2])
merged_layer_shape = merged.get_shape().as_list()
# specify number of channels you want the output to have after merging
desired_output_channels = 32
new_trainable_weights = keras.backend.random_normal_variable(shape=(merged_layer_shape[-1], desired_output_channels),mean=0,scale=1)
weighted_output = keras.backend.dot(merged,new_trainable_weights)
now connect the layer of model1(m1) next to L2 with this new weighted_output
# I'm using some protected properties of layer. But it is not recommended way to do it.
# get the index of l2 layer in new_m1
for i in range(len(new_m1.layers[1].layers)):
if new_m1.layers[1].layers[i].name=="L2":
index = i
x = weighted_output
for i in range(index+1, len(new_m1.layers[1].layers)):
x = new_m1.layers[1].layers[i](x)
new_model = keras.models.Model(inputs=new_inputs, outputs=x)

How to use hidden layer activations to construct loss function and provide y_true during fitting in Keras?

Assume I have a model like this. M1 and M2 are two layers linking left and right sides of the model.
The example model: Red lines indicate backprop directions
During training, I hope M1 can learn a mapping from L2_left activation to L2_right activation. Similarly, M2 can learn a mapping from L3_right activation to L3_left activation.
The model also needs to learn the relationship between two inputs and the output.
Therefore, I should have three loss functions for M1, M2, and L3_left respectively.
I probably can use:
model.compile(optimizer='rmsprop',
loss={'M1': 'mean_squared_error',
'M2': 'mean_squared_error',
'L3_left': mean_squared_error'})
But during training, we need to provide y_true, for example:
model.fit([input_1,input_2], y_true)
In this case, the y_true is the hidden layer activations and not from a dataset.
Is it possible to build this model and train it using it's hidden layer activations?
If you have only one output, you must have only one loss function.
If you want three loss functions, you must have three outputs, and, of course, three Y vectors for training.
If you want loss functions in the middle of the model, you must take outputs from those layers.
Creating the graph of your model: (if the model is already defined, see the end of this answer)
#Here, all "SomeLayer(blabla)" could be replaced by a "SomeModel" if necessary
#Example of using a layer or a model:
#M1 = SomeLayer(blablabla)(L12)
#M1 = SomeModel(L12)
from keras.models import Model
from keras.layers import *
inLef = Input((shape1))
inRig = Input((shape2))
L1Lef = SomeLayer(blabla)(inLef)
L2Lef = SomeLayer(blabla)(L1Lef)
M1 = SomeLayer(blablaa)(L2Lef) #this is an output
L1Rig = SomeLayer(balbla)(inRig)
conc2Rig = Concatenate(axis=?)([L1Rig,M1]) #Or Add, or Multiply, however you're joining the models
L2Rig = SomeLayer(nlanlab)(conc2Rig)
L3Rig = SomeLayer(najaljd)(L2Rig)
M2 = SomeLayer(babkaa)(L3Rig) #this is an output
conc3Lef = Concatenate(axis=?)([L2Lef,M2])
L3Lef = SomeLayer(blabla)(conc3Lef) #this is an output
Creating your model with three outputs:
Now you've got your graph ready and you know what the outputs are, you create the model:
model = Model([inLef,inRig], [M1,M2,L3Lef])
model.compile(loss='mse', optimizer='rmsprop')
If you want different losses for each output, then you create a list:
#example of custom loss function, if necessary
def lossM1(yTrue,yPred):
return keras.backend.sum(keras.backend.abs(yTrue-yPred))
#compiling with three different loss functions
model.compile(loss = [lossM1, 'mse','binary_crossentropy'], optimizer =??)
But you've got to have three different yTraining too, for training with:
model.fit([input_1,input_2], [yTrainM1,yTrainM2,y_true], ....)
If your model is already defined and you don't create it's graph like I did:
Then, you have to find in yourModel.layers[i] which ones are M1 and M2, so you create a new model like this:
M1 = yourModel.layers[indexForM1].output
M2 = yourModel.layers[indexForM2].output
newModel = Model([inLef,inRig], [M1,M2,yourModel.output])
If you want that two outputs be equal:
In this case, just subtract the two outputs in a lambda layer, and make that lambda layer be an output of your model, with expected values = 0.
Using the exact same vars as before, we'll just create two addictional layers to subtract outputs:
diffM1L1Rig = Lambda(lambda x: x[0] - x[1])([L1Rig,M1])
diffM2L2Lef = Lambda(lambda x: x[0] - x[1])([L2Lef,M2])
Now your model should be:
newModel = Model([inLef,inRig],[diffM1L1Rig,diffM2L2lef,L3Lef])
And training will expect those two differences to be zero:
yM1 = np.zeros((shapeOfM1Output))
yM2 = np.zeros((shapeOfM2Output))
newModel.fit([input_1,input_2], [yM1,yM2,t_true], ...)
Trying to answer to the last part: how to make gradients only affect one side of the model.
...well.... at first that sounds unfeasible to me. But, if that is similar to "train only a part of the model", then it's totally ok by defining models that only go to a certain point and making part of the layers untrainable.
By doing that, nothing will affect those layers. If that's what you want, then you can do it:
#using the previous vars to define other models
modelM1 = Model([inLef,inRig],diffM1L1Rig)
This model above ends in diffM1L1Rig. Before compiling, you must set L2Right untrainable:
modelM1.layers[??].trainable = False
#to find which layer is the right one, you may define then using the "name" parameter, or see in the modelM1.summary() the shapes, types etc.
modelM1.compile(.....)
modelM1.fit([input_1, input_2], yM1)
This suggestion makes you train only a single part of the model. You can repeat the procedure for M2, locking the layers you need before compiling.
You can also define a full model taking all layers, and lock only the ones you want. But you won't be able (I think) to make half gradients pass by one side and half the gradients pass by the other side.
So I suggest you keep three models, the fullModel, the modelM1, and the modelM2, and you cycle them in training. One epoch each, maybe....
That should be tested....

Resources