Nikhil
Nikhil

Reputation: 143

Keras Weights Saving

I am working with pretrained Keras model MobileNets. I am trying to save the weights of one of the layer in a text file. The dimension of the weight matrix is as follows:

      layerr = model.layers[2].get_weights()
      print(layerr.shape)

      (1, 3, 3, 3, 32)

I am confused as to which is the 3's corresponds to the channel and which of them corresponds to height and width. I know that the 32 corresponds to the number of filters.

Also if you could help me in saving them as a linear matrix, that would be great!

Upvotes: 0

Views: 1649

Answers (1)

Daniel Möller
Daniel Möller

Reputation: 86600

Something is strange, get_weights() should be returning a list, which is not your case in this code. Anyway, assuming you're picking the correct array from the list, and assuming it's a 3D convolution... (otherwise something is not quite right and I'd ask you to share your exact layer definition).

Sounds like a 3D convolution filter with these numbers in sequence:

  • 1 spatial dimension 1
  • 3 spatial dimension 2
  • 3 spatial dimension 3
  • 3 input channels
  • 32 output channels

There are several ways of saving a numpy array. I like numpy.save().

np.save('filename.npy', layerr)

You can also create a text file and save it as text:

with open('filename.txt', 'w') as f:
    f.write(str(layerr))

Not sure about what a "linear matrix" is, but if you want it with only one dimension, you can reshape:

flatWeights = layerr.reshape((-1,))
#then save

But if you're saving for using later, it's better to use model.save() or model.save_weights().

Upvotes: 2

Related Questions