是否可以保存受过训练的图层以在Keras上使用图层? [英] Is it possible to save a trained layer to use layer on Keras?

查看:73
本文介绍了是否可以保存受过训练的图层以在Keras上使用图层?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还没有使用过Keras,我在考虑是否使用它.

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. 我训练一个模型.
  2. 然后,我获得了训练有素的图层t_layer.
  3. 我还有另一个要训练的模型,该模型由layer1layer2layer3组成.
  4. 我想将t_layer用作layer2,而不要更新此层(即t_layer不再学习).
  1. I train a model.
  2. Then, I gain a trained layer t_layer.
  3. I have another model to train which consists of layer1, layer2, layer3 .
  4. I want to use t_layer as layer2 and not to update this layer(i.e. t_layer does not learn any more).

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

This may be an odd attempt, but I want to try this. Is this possible on Keras?

推荐答案

是的.

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

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

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

Keras also allows you to save entire models.

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

Suppose you have a model in the var model:

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

这是一个numpy数组的列表,很可能包含两个数组:weights和bias.您可以简单地使用numpy.save()保存这两个数组,然后再创建一个相似的图层并为其赋予权重:

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    

然后您编译模型:

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.

这篇关于是否可以保存受过训练的图层以在Keras上使用图层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆