我想知道训练模型后是否有可能在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
我想将单元格状态作为numpy数组的形状(number_of_examples,number_of_dimensions)或(123456,128)。可以做这个keras吗?
谢谢!
答案 0 :(得分: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)
答案 1 :(得分: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。