是否可以保存经过训练的层以在 Keras 上使用层?

2024-03-06

我没用过Keras,正在考虑要不要用。

我想保存经过训练的图层以供以后使用。例如:

  1. 我训练一个模型。
  2. 然后,我获得一个经过训练的层t_layer.
  3. 我有另一个模型要训练,其中包括layer1, layer2, layer3 .
  4. 我想用t_layer as layer2并且不更新该层(即t_layer不再学习)。

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


是的。

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

Keras 还允许您保存整个模型 https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model.

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

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

这是一个 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])

您可以使层不可训练(必须在模型编译之前完成):

model.layers[2].trainable = False    

然后编译模型:

model.compile(.....)    

这就是一个模型,其一层是不可训练的,并且具有由您定义的从其他地方获取的权重和偏差。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否可以保存经过训练的层以在 Keras 上使用层? 的相关文章

随机推荐