提取Cell State LSTM Keras

问题描述 投票:1回答:2

我想知道在训练模型后是否有可能在Keras中提取LSTM的最后一个单元状态。例如,在这个简单的LSTM模型中:

number_of_dimensions = 128
number_of_examples = 123456

input_ = Input(shape = (10,100,))
lstm, hidden, cell = CuDNNLSTM(units = number_of_dimensions, return_state=True)(input_)

dense = Dense(num_of_classes, activation='softmax')(lstm)

model = Model(inputs = input_, outputs = dense)
parallel_model = multi_gpu_model(model, gpus=2)
parallel_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])

# fit the model
parallel_model.fit(X1, onehot_encoded, epochs=100, verbose=1, batch_size = 128, validation_split = 0.2)

我尝试打印'细胞'但结果是

tf.Tensor 'cu_dnnlstm_2/strided_slice_17:0' shape=(?, 128) dtype=float32 

我想将单元格状态设置为一个numpy形状数组(number_of_examples,number_of_dimensions)或(123456,128)。可以做这个keras吗?

谢谢!

python tensorflow keras lstm rnn
2个回答
2
投票

假设您使用TensorFlow作为后端,您可以在TensorFlow会话中专门运行cell。例如:

from keras.layers import LSTM, Input, Dense
from keras.models import Model
import keras.backend as K
import numpy as np

number_of_dimensions = 128
number_of_examples = 123456

input_ = Input(shape=(10, 100,))
lstm, hidden, cell = LSTM(units=number_of_dimensions, return_state=True)(input_)
dense = Dense(10, activation='softmax')(lstm)
model = Model(inputs=input_, outputs=dense)

with K.get_session() as sess:
    x = np.zeros((number_of_examples, 10, 100))
    cell_state = sess.run(cell, feed_dict={input_: x})
    print(cell_state.shape)

2
投票

您可能感兴趣的选项是将模型权重保存到hdf5文件:

model.save_weights('my_model_weights.h5')

(参考:https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model

然后使用HDF查看器,例如Java HDFView包:https://support.hdfgroup.org/products/java/hdfview/

我相信您可以将数据导出为CSV以导入到Numpy中。

© www.soinside.com 2019 - 2024. All rights reserved.