Is it possible to save a trained layer to use layer on Keras?

后端 未结 1 643
广开言路
广开言路 2021-02-09 05:16

I haven\'t used Keras and I\'m thinking whether to use it or not.

I want to save a trained layer to use later. For example:

  1. I train a model.
  2. Then,
1条回答
  •  说谎
    说谎 (楼主)
    2021-02-09 05:59

    Yes, it is.

    You will probably have to save the layer's weights and biases instead of saving the layer itself, but it's possible.

    Keras also allows you to save entire models.

    Suppose you have a model in the var model:

    weightsAndBiases = model.layers[i].get_weights()
    

    This is a list of numpy arrays, very probably with two arrays: weighs and biases. You can simply use numpy.save() to save these two arrays and later you can create a similar layer and give it the weights:

    from keras.layers import *
    from keras.models import Model
    
    inp = Input(....)    
    out1 = SomeKerasLayer(...)(inp)  
    out2 = AnotherKerasLayer(....)(out1)
    .... 
    model = Model(inp,out2)
    #above is the usual process of creating a model    
    
    #supposing layer 2 is the layer you want (you can also use names)    
    
    weights = numpy.load(...path to your saved weights)    
    biases = numpy.load(... path to your saved biases)
    model.layers[2].set_weights([weights,biases])
    

    You can make layers untrainable (must be done before the model compilation):

    model.layers[2].trainable = False    
    

    Then you compile the model:

    model.compile(.....)    
    

    And there you go, a model, whose one layer is untrainable and has weights and biases defined by you, taken from somewhere else.

    0 讨论(0)
提交回复
热议问题