Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 提取细胞状态LSTM Keras_Python_Tensorflow_Keras_Lstm_Rnn - Fatal编程技术网

Python 提取细胞状态LSTM Keras

Python 提取细胞状态LSTM Keras,python,tensorflow,keras,lstm,rnn,Python,Tensorflow,Keras,Lstm,Rnn,我想知道是否有可能在训练模型后提取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_

我想知道是否有可能在训练模型后提取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数组(示例的数量,维度的数量)或(123456128)。有可能这样做吗


谢谢大家!

假设您使用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')
(参考号:)

然后使用HDF查看器,如Java HDFView包:


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

我相信OP要求的是LSTM层的状态,而不是权重。公平地说,我没有回答原始问题的确切措辞。根据优化器状态,也将使用此方法保存,那么这是否使我的答案至少有50%的准确性?!不,LSTM隐藏状态和单元格状态不会与模型一起保存,只保存优化器状态。这不是一回事。