Hitesh
Hitesh

Reputation: 1325

How to get Conv2D layer filter weights

How do I get the weights of all filters (like 32 ,64, etc.) of a Conv2D layer in Keras after each epoch? I mention that, because initial weights are random but after optimization they will change.

I checked this answer but did not understand. Please help me find a solution of getting the weights of all the filter and after every epoch.

And one more question is that in Keras documentation for the Conv2D layer input shape is (samples, channels, rows, cols). What exactly does samples mean? Is it the total number of inputs we have (like in MNIST data set it is 60.000 training images) or the batch size (like 128 or other)?

Upvotes: 3

Views: 2731

Answers (1)

Daniel Möller
Daniel Möller

Reputation: 86600

Samples = batch size = number of images in a batch

Keras will often use None for this dimension, meaning it can vary and you don't have to set it.

Although this dimension actually exists, when you create a layer, you pass input_shape without it:

Conv2D(64,(3,3), input_shape=(channels,rows,cols))
#the standard it (rows,cols,channels), depending on your data_format

To have actions done after each epoch (or batch), you can use a LambdaCallback, passing the on_epoch_end function:

#the function to call back
def get_weights(epoch,logs):
    wsAndBs = model.layers[indexOfTheConvLayer].get_weights()
    #or model.get_layer("layerName").get_weights()

    weights = wsAndBs[0]
    biases = wsAndBs[1]
    #do what you need to do with them
    #you can see the epoch and the logs too: 
    print("end of epoch: " + str(epoch)) for instance

#the callback
from keras.callbacks import LambdaCallback
myCallback = LambdaCallback(on_epoch_end=get_weights)

Pass this callback to the training function:

model.fit(...,...,... , callbacks=[myCallback])

Upvotes: 4

Related Questions