简体   繁体   English

Keras功能API,手动将权重设置为图层

[英]Keras function api, setting weight manually to a layer

In keras Sequential model, one can set weight directly using set_weights method. 在keras顺序模型中,可以使用set_weights方法直接设置权重。

model.layers[n].set_weights([your_wight])

However I am facing problem if I am trying to set weight to a layer using functional API. 但是,如果我尝试使用功能性API为图层设置权重,则会遇到问题。

Here is the code snippet: 这是代码片段:

emb = Embedding(max_words, embedding_dim, input_length=maxlen)(merge_ip)
         #skipping some lines
         .
         .
emb.set_weights([some_weight_matrix])

This is throwing error that 这引发了错误

AttributeError: 'Tensor' object has no attribute 'set_weights'

which I think becouse emb is a Tensor object. 我认为因为emb是一个Tensor对象。

I am wondering how to set wight properly in my model 我想知道如何在模型中正确设置体重

If you want to set the weights on Embedding layers you might add them to the constructor like this: 如果要在“嵌入”层上设置权重,可以将其添加到构造函数中,如下所示:

from keras.layers import Embedding

embedding_layer = Embedding(len(word_index) + 1,
                            EMBEDDING_DIM,
                            weights=[embedding_matrix],
                            input_length=MAX_SEQUENCE_LENGTH,
                            trainable=False)

https://blog.keras.io/using-pre-trained-word-embeddings-in-a-keras-model.html https://blog.keras.io/using-pre-trained-word-embeddings-in-a-keras-model.html

Later then you can hand over merge_ip : 之后,您可以移交merge_ip

x = embedding_layer(merge_ip)
embed_layer = Embedding(max_words, embedding_dim, input_length=maxlen)
emp = embed_layer(merge_ip)

embed_layer.set_weights("...")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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