提取细胞状态 LSTM Keras

Extract Cell State LSTM Keras

我想知道在训练模型后是否可以在 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)

我尝试打印 'cell' 但结果是

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

我想将单元格状态作为形状为 (number_of_examples, number_of_dimensions) 或 (123456, 128) 的 numpy 数组。有可能做这个keras吗?

谢谢!

假设您使用 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)

您可能感兴趣的一个选项是将模型权重保存到 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 中。