是否可以保存训练有素的图层以在Keras上使用图层?

sat*_*ibi 4 machine-learning neural-network python-3.x deep-learning keras

我没有使用过Keras而我正在考虑是否使用它.

我想保存一个训练好的图层以便以后使用.例如:

  1. 我训练模特.
  2. 然后,我获得了一个训练有素的层t_layer.
  3. 我有另一种模式来训练它由layer1,layer2,layer3.
  4. 我想使用t_layeras layer2而不是更新这一层(即t_layer不再学习).

这可能是一个奇怪的尝试,但我想尝试这个.在Keras这可能吗?

Dan*_*ler 10

是的.

您可能必须保存图层的权重和偏差,而不是保存图层本身,但这是可能的.

Keras还允许您保存整个模型.

假设你在var中有一个模型model:

weightsAndBiases = model.layers[i].get_weights()
Run Code Online (Sandbox Code Playgroud)

这是numpy数组的列表,很可能有两个数组:权重和偏差.您可以简单地使用numpy.save()保存这两个数组,稍后您可以创建一个类似的图层并为其赋予权重:

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])
Run Code Online (Sandbox Code Playgroud)

您可以使图层无法处理(必须在模型编译之前完成):

model.layers[2].trainable = False    
Run Code Online (Sandbox Code Playgroud)

然后编译模型:

model.compile(.....)    
Run Code Online (Sandbox Code Playgroud)

在那里,你去了一个模型,它的一层是无法处理的,并且具有由你定义的权重和偏差,取自其他地方.