[英]How to set custom initial weights to biLSTM layer Keras?
我目前正在構建帶有注意力的 BiLSTM,並使用 Antlion 算法優化 BiLSTM 層權重。 Antlion 算法在 MATLAB 代碼中,我能夠集成 Python 和 MATLAB 以獲得優化的權重,如下所示:
#LSTM hidden nodes
hidden_nodes=11
import matlab.engine
eng = matlab.engine.start_matlab()
#call optimised_weights.m
[forward_kernel, backward_kernel,forward_recurrent, backward_recurrent]=eng.optimised_weights(int(hidden_nodes),nargout=4)
eng.quit()
## convert to nparray
forward_kernel=np.array(forward_kernel)
backward_kernel=np.array(backward_kernel)
forward_recurrent=np.array(forward_recurrent)
backward_recurrent=np.array(backward_recurrent)
我目前在將權重和偏差設置為 BiLSTM 層時遇到問題,如下面的 model 中創建的(未設置自定義初始權重):
class attention(Layer):
def __init__(self, return_sequences=True,**kwargs):
self.return_sequences = return_sequences
super(attention,self).__init__()
def build(self, input_shape):
self.W=self.add_weight(name="att_weight", shape=(input_shape[-1],1),
initializer="normal")
self.b=self.add_weight(name="att_bias", shape=(input_shape[1],1),
initializer="zeros")
super(attention,self).build(input_shape)
def call(self, x):
e = K.tanh(K.dot(x,self.W)+self.b)
a = K.softmax(e, axis=1)
output = x*a
if self.return_sequences:
return output
return K.sum(output, axis=1)
def get_config(self):
# For serialization with 'custom_objects'
config = super().get_config()
config['return_sequences'] = self.return_sequences
return config
model = Sequential()
model.add(Input(shape=(5,1)))
model.add(Bidirectional(LSTM(hidden_nodes, return_sequences=True)))
model.add(attention(return_sequences=False)) #this is a custom layer...
model.add(Dense(104, activation="sigmoid"))
model.add(Dropout(0.2))
model.add(Dense(1, activation="sigmoid"))
model.compile(optimizer=tf.keras.optimizers.Adam(epsilon=1e-08,learning_rate=0.01),loss='mse')
es = EarlyStopping(monitor='val_loss', mode='min', verbose=2, patience=50)
mc = ModelCheckpoint('model.h5', monitor='val_loss',
mode='min', verbose=2, save_best_only=True)
我嘗試了以下方法:
model.add(Bidirectional(LSTM(hidden_nodes, return_sequences=True,
weights=[forward_kernel,forward_recurrent,np.zeros(20,),backward_kernel,backward_recurrent,np.zeros(20,)])))
但是一旦 model 被編譯,權重和偏差就會改變......即使 kernel,循環和偏置初始化器設置為無......
我已經參考了這個鏈接: https://keras.io/api/layers/initializers/但無法將它與我的問題聯系起來......
如果你們能提供解決此問題的見解,以及我遺漏的任何基本部分,我將不勝感激。 如果需要,我很樂意分享更多細節。
謝謝!
使用tf.constant_initializer
將您的自定義權重提供為np.array
。 此外,當您使用Bidirectional
層時,您需要使用自定義權重明確指定后向層。
layer = Bidirectional(
LSTM(
hidden_nodes,
return_sequences=True,
kernel_initializer=tf.constant_initializer(forward_kernel),
recurrent_initializer=tf.constant_initializer(forward_recurrent),
),
backward_layer=LSTM(
hidden_nodes,
return_sequences=True,
kernel_initializer=tf.constant_initializer(backward_kernel),
recurrent_initializer=tf.constant_initializer(backward_recurrent),
go_backwards=True,
),
)
注意重量的預期形狀。 由於圖層的輸入是(batch, timesteps, features)
,您的權重應該具有以下形狀(以考慮 LSTM 單元中的 4 個門):
(features, 4*hidden_nodes)
(hidden_nodes, 4*hidden_nodes)
(4*hidden_nodes)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.