Nayeem
Nayeem

Reputation: 91

How to run any Keras layer as a single layer to understand its behaviour?

In order to understand the implementation of any Keras layer (e.g. Conv2DTranspose), is there a way of running the layer as a standalone layer (with Tensorflow backend)?

Upvotes: 3

Views: 2063

Answers (3)

Nayeem
Nayeem

Reputation: 91

I found a way to develop a simple single layer model.

keras_model = Sequential()
keras_model.add(Conv2DTranspose(32, (2, 2), strides=(2, 2), input_shape=(32, 32, 3), name='trans'))
keras_model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.SGD())
keras_model.summary()
keras_model.save('model.h5')

Upvotes: 1

Dmytro Prylipko
Dmytro Prylipko

Reputation: 5064

I did it this way:

image_t = ds.make_one_shot_iterator().get_next() 
inputs = Input(shape=(224, 224, 3))
conv = Conv2D(16, (3, 3), padding='same')(inputs)
m = Model(inputs=inputs, outputs=conv)
m.compile(loss='mse', optimizer='rmsprop')  # loss and optimizer do not matter really
m.summary()

with tf.Session() as sess:                                                                                                                                                                                                                                        
   image = sess.run([image_t])                                                                                                                                                                                                                                         
   out = m.predict(image)[0]  

Upvotes: 0

Novak
Novak

Reputation: 2171

You can extract the weights of each layer in keras and use it to initialize the weights of the new layer of the same type. Then use this new layer as a model and just do predict. If the layer is not the first, you have to recreate model with all the layers up until the wanted layer, initialize their weights with weights from the trained model and the rest is the same.

Upvotes: 0

Related Questions