简体   繁体   中英

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!

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM