Passing initial_state to Bidirectional RNN layer in Keras - keras

I'm trying to implement encoder-decoder type network in Keras, with Bidirectional GRUs.
The following code seems to be working
src_input = Input(shape=(5,))
ref_input = Input(shape=(5,))
src_embedding = Embedding(output_dim=300, input_dim=vocab_size)(src_input)
ref_embedding = Embedding(output_dim=300, input_dim=vocab_size)(ref_input)
encoder = Bidirectional(
GRU(2, return_sequences=True, return_state=True)
)(src_embedding)
decoder = GRU(2, return_sequences=True)(ref_embedding, initial_state=encoder[1])
But when I change the decode to use Bidirectional wrapper, it stops showing encoder and src_input layers in the model.summary(). The new decoder looks like:
decoder = Bidirectional(
GRU(2, return_sequences=True)
)(ref_embedding, initial_state=encoder[1:])
The output of model.summary() with the Bidirectional decoder.
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_2 (InputLayer) (None, 5) 0
_________________________________________________________________
embedding_2 (Embedding) (None, 5, 300) 6610500
_________________________________________________________________
bidirectional_2 (Bidirection (None, 5, 4) 3636
=================================================================
Total params: 6,614,136
Trainable params: 6,614,136
Non-trainable params: 0
_________________________________________________________________
Question: Am I missing something when I pass initial_state in Bidirectional decoder? How can I fix this? Is there any other way to make this work?

It's a bug. The RNN layer implements __call__ so that tensors in initial_state can be collected into a model instance. However, the Bidirectional wrapper did not implement it. So topological information about the initial_state tensors is missing and some strange bugs happen.
I wasn't aware of it when I was implementing initial_state for Bidirectional. It should be fixed now, after this PR. You can install the latest master branch on GitHub to fix it.

Related

None Output from MixtureSameFamily Tensorflow

I am trying to learn multi modal distribution using Neural Network and Gaussian Mixture model.
but, in my modal summary the output layer has None output, and it is from using MixtureSameFamily.
Can you help me resolve this?
def zero_inf(out):
loc, scale, probs = tf.split(out, num_or_size_splits=3, axis=-1)
scale = tf.nn.softplus(scale)
probs = tf.nn.softmax(probs)
return tfd.MixtureSameFamily(
mixture_distribution = tfd.Categorical(probs=probs),#D
components_distribution = tfd.Normal(loc=loc, scale=scale))
## Definition of the custom parametrized distribution
inputs = tf.keras.layers.Input(shape=(5,))
out = Dense(6)(inputs)#A
p_y_zi = tfp.layers.DistributionLambda(lambda t: zero_inf(t))(out)
model_zi = Model(inputs=inputs, outputs=p_y_zi)
# def NLL(y_true, y_hat):
# return -y_hat.log_prob(tf.reshape(y_true,(-1,)))
# model_zi.compile(optimizer="adam", loss=NLL)
model_zi.summary()
Below is the model summary.
Model: "model_70"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_30 (InputLayer) [(None, 5)] 0
_________________________________________________________________
dense_130 (Dense) (None, 6) 36
_________________________________________________________________
distribution_lambda_36 (Dist ((None,), (None,)) 0
=================================================================
Total params: 36
Trainable params: 36
Non-trainable params: 0
_________________________________________________________________
Because of this empty/none output, I unable to train the model as I get some shape related errors.
InvalidArgumentError: Cannot update variable with shape [] using a Tensor with shape [32], shapes must be equal.
[[{{node metrics_60/mae/AssignAddVariableOp}}]]
Tensorflow version: 2.6.2
Tensorflow-probability: 0.14.0
Python: 3.6

Why are these LSTM parameter counts different?

I'm building an LSTM, for a report, and would like to summarize things about it. However, I've seen two different ways to build an LSTM in Keras that yield two different values for the number of parameters.
I'd like to understand why the parameters differ in this way.
This question correctly shows why this code
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding
from keras.layers import LSTM
model = Sequential()
model.add(LSTM(256, input_dim=4096, input_length=16))
model.summary()
results in 4457472 parameters.
From what I can tell, the following two LSTMs should be the same
m2 = Sequential()
m2.add(LSTM(1, input_dim=5, input_length=1))
m2.summary()
m3 = Sequential()
m3.add(LSTM((1),batch_input_shape=(None,5,1)))
m3.summary()
However, the m2 results in 28 parameters, but the m3 results in 12 parameters. Why?
How is 12 being calculated for a 1 unit LSTM with a 5-dim input?
Included the warning message. Hope it is helpful.
Output
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
lstm_1 (LSTM) (None, 256) 4457472
=================================================================
Total params: 4,457,472
Trainable params: 4,457,472
Non-trainable params: 0
_________________________________________________________________
Warning (from warnings module):
File "difparam.py", line 11
m2.add(LSTM(1, input_dim=5, input_length=1))
UserWarning: The `input_dim` and `input_length` arguments in recurrent layers are deprecated. Use `input_shape` instead.
Warning (from warnings module):
File "difparam.py", line 11
m2.add(LSTM(1, input_dim=5, input_length=1))
UserWarning: Update your `LSTM` call to the Keras 2 API: `LSTM(1, input_shape=(1, 5))`
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
lstm_2 (LSTM) (None, 1) 28
=================================================================
Total params: 28
Trainable params: 28
Non-trainable params: 0
_________________________________________________________________
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
lstm_3 (LSTM) (None, 1) 12
=================================================================
Total params: 12
Trainable params: 12
Non-trainable params: 0
_________________________________________________________________
m2 was built based on info from the Stack Overflow question, and m3 was built based on this video from YouTube.
Because the correct values are input_dim = 1 and input_length = 5.
It's even written in the warning you received, where the input shape for m2 is different from the one used in m3:
UserWarning: Update your LSTM call to the Keras 2 API: LSTM(1, input_shape=(1, 5))
It's highly recommended that you use the suggestion in the warning.

How to use a GlobalAveragePool layer as the output of a model

I am receiving this error when I am trying to build a model using the output from another model.
Output tensors to a Model must be the output of a Keras `Layer` (thus holding past layer metadata). Found: <keras.layers.pooling.GlobalAveragePooling2D object at 0x7Somthing or another
What I am trying to do is to use a finetuned model as the base model and retain the whole thing using a different method (an SCNN instead of a CNN).
This is how I am declaring the model and where it goes wrong.
pair_base_model = Model(inputs = base_model.input, outputs=base_model.get_layer('glb_avg_pool'))
And this is how I load my previous model
base_model = load_model('../input/base-model-reid/0.ckpt')
print(base_model.summary())
Which gives me this
......... Whole bunch of other stuff
block14_sepconv2_act (Activatio (None, 7, 7, 2048) 0 block14_sepconv2_bn[0][0]
__________________________________________________________________________________________________
glb_avg_pool (GlobalAveragePool (None, 2048) 0 block14_sepconv2_act[0][0]
__________________________________________________________________________________________________
dense_1 (Dense) (None, 1502) 3077598 glb_avg_pool[0][0]
==================================================================================================
Total params: 23,939,078
Trainable params: 10,980,862
Non-trainable params: 12,958,216
__________________________________________________________________________________________________
None
I'm stupoid I was working on this a little too late and found something simple that I messed up.
I needed to use the .output for the layer in order to get the output I cannot just call .get_layer(xxxxxxx) as this won't work
pair_base_model = Model(inputs = base_model.input, outputs=base_model.get_layer('glb_avg_pool').output)
This is the working code.
Thanks for anyone who looked at this.

In Keras, how to get the layer name associated with a "Model" object contained in my model?

I built a Sequential model with the VGG16 network at the initial base, for example:
from keras.applications import VGG16
conv_base = VGG16(weights='imagenet',
# do not include the top, fully-connected Dense layers
include_top=False,
input_shape=(150, 150, 3))
from keras import models
from keras import layers
model = models.Sequential()
model.add(conv_base)
model.add(layers.Flatten())
model.add(layers.Dense(256, activation='relu'))
# the 3 corresponds to the three output classes
model.add(layers.Dense(3, activation='sigmoid'))
My model looks like this:
model.summary()
Layer (type) Output Shape Param #
=================================================================
vgg16 (Model) (None, 4, 4, 512) 14714688
_________________________________________________________________
flatten_1 (Flatten) (None, 8192) 0
_________________________________________________________________
dense_7 (Dense) (None, 256) 2097408
_________________________________________________________________
dense_8 (Dense) (None, 3) 771
=================================================================
Total params: 16,812,867
Trainable params: 16,812,867
Non-trainable params: 0
_________________________________________________________________
Now, I want to get the layer names associated with the vgg16 Model portion of my network. I.e. something like:
layer_name = 'block3_conv1'
filter_index = 0
layer_output = model.get_layer(layer_name).output
loss = K.mean(layer_output[:, :, :, filter_index])
However, since the vgg16 convolutional is shown as a Model and it's layers are not being exposed, I get the error:
ValueError: No such layer: block3_conv1
How do I do this?
The key is to first do .get_layer on the Model object, then do another .get_layer on that specifying the specific vgg16 layer, THEN do .output:
layer_output = model.get_layer('vgg16').get_layer('block3_conv1').output
To get the name of the layer from the VGG16 instance use the following code.
for layer in conv_base.layers:
print(layer.name)
the name should be the same inside your model. to show this you could do the following.
print([layer.name for layer in model.get_layer('vgg16').layers])
like Ryan showed us. to call the vgg16 layer you must call it from the model first using the get_layer method.
One can simply store the name of layers in the list for further usage
layer_names=[layer.name for layer in base_model.layers]
This worked for me :)
for idx in range(len(model.layers)):
print(model.get_layer(index = idx).name)
Use the layer's summary:
model.get_layer('vgg16').summary()

Dimension error building LSTM with keras

I am trying to builda LSTM network using Keras.
My time seriese example is of size 492. And I want to use the 3 previous examples to predict the next example. So, the input is converted to size (num_samples,3*492),and the output size is (num_samples,492).
According to this blog, I firstly convert my data size into of form (num_samples,timesteps,features)
#convert trainning data to 3D LSTM shape
train_origin_x = train_origin_x.reshape((train_origin_x.shape[0],3,492))
test_origin_x = test_origin_x.reshape((test_origin_x.shape[0],3,492))
print(train_origin_x.shape,test_origin_x.shape)
(216, 3, 492) (93, 3, 492)
print(train_origin_y,test_origin_y)
(216, 492) (93, 492)
And below is the my code to build the LSTM network
#building network
model = Sequential()
model.add(LSTM(hidden_units,return_sequences=True,input_shape=(train_origin_x.shape[1],train_origin_x.shape[2])))
model.add(Dense(492))
model.compile(loss='mse',optimizer='adam')
print('model trainning begins...')
history = model.fit(train_origin_x,train_origin_y,epochs = num_epochs,batch_size = num_batchs,
validation_data=(test_origin_x,test_origin_y))
However I got an error in the process, saying
ValueError: Error when checking target: expected dense_1 to have 3 dimensions, but got array with shape (216, 492)
Anyone knows the what's the problem?
Any comments or suggestions is welcome and appreciated!!
Below is the result of model.summary()
model.summary()
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
lstm_1 (LSTM) (None, 3, 50) 108600
_________________________________________________________________
dense_1 (Dense) (None, 3, 492) 25092
=================================================================
add return_sequences to your LSTM code:
model.add(LSTM(hidden_units, return_sequences = False,input_shape=(train_origin_x.shape[1],train_origin_x.shape[2])))

Resources