【问题标题】:How to save and restore a lstm trained model in Tensorflow using Saver?如何使用 Saver 在 Tensorflow 中保存和恢复经过 lstm 训练的模型?
【发布时间】:2017-09-26 11:34:27
【问题描述】:

我保存了一个经过训练的 LSTM 模型,我想恢复预测以在测试中使用它。我试图关注this post。但是我遇到了错误。这是我尝试过的:

x = tf.placeholder('tf.float32', [None, input_vec_size, 1])
y = tf.placeholder('tf.float32')


def recurrent_neural_network(x):
    layer = {'weights': tf.Variable(tf.random_normal([n_hidden, n_classes])),
             'biases': tf.Variable(tf.random_normal([n_classes]))}     
    x = tf.transpose(x, [1, 0, 2])
    x = tf.reshape(x, [-1, 1])
    x = tf.split(x, input_vec_size, 0)

    lstm_cell = rnn.BasicLSTMCell(n_hidden, state_is_tuple=True)
    outputs, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32)
    output = tf.add(tf.matmul(outputs[-1], layer['weights']), layer['biases'])

    return output

def train_neural_network(x):
    prediction = recurrent_neural_network(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
    optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)
    saver = tf.train.Saver()

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        Training ...
        saver.save(sess, os.path.join(os.getcwd(), 'my_test_model'))

在那之后,在训练阶段我正在尝试

def test_neural_network(input_data):
    with tf.Session() as sess:
        #sess.run(tf.global_variables_initializer())
        new_saver = tf.train.import_meta_graph('my_test_model.meta')
        new_saver.restore(sess, tf.train.latest_checkpoint('./'))
        prediction = tf.get_default_graph().get_tensor_by_name("prediction:0")

        Calculate features from input_data ...
        result = sess.run(tf.argmax(prediction.eval(feed_dict={x: features}), 1))

但这会引发以下错误:

KeyError: “名称‘prediction:0’指的是一个不存在的张量。操作‘prediction’在图中不存在。”

然后我尝试添加: 保存前tf.add_to_collection('prediction', prediction),恢复后用prediction = tf.get_collection('prediction')[0]替换。但这给了我以下错误:

InvalidArgumentError(参见上面的回溯):您必须为占位符张量“Placeholder_2”提供一个值,其 dtype 为 float 和 shape [?,34,1] [[节点:Placeholder_2 = Placeholderdtype=DT_FLOAT, shape=[?,34,1], _device="/job:localhost/replica:0/task:0/cpu:0"]]

我知道第一个错误,我应该指定一个名称以便恢复,但 prediction 不是 tensorflow 变量。我浏览了几篇以前的帖子和文章,但无法提出一个可行的解决方案。所以,我的问题是:

  1. 我在做一些概念上的错误吗?如果有,是什么?
  2. 如果没有,是否存在实施错误?我该如何解决?

谢谢。

【问题讨论】:

    标签: python tensorflow lstm recurrent-neural-network


    【解决方案1】:

    我终于可以保存我训练有素的模型,并发布一个答案,以防有人遇到这个问题。我没有得到确切问题的解决方案,但我可以使用tflearn 构建和保存我的模型。为了训练和存储:

    model = tflearn.DNN(lstm_model(n_classes, input_vec_size))
    model.fit(train_x, train_y, validation_set=(test_x, test_y), n_epoch=20,
              show_metric=True, snapshot_epoch=True, run_id='lstm_model')
    model.save("../Models/lstm_model")
    

    然后,恢复:

    model.load(filepath+"lstm_model")
    

    这似乎是一种更容易使用模型的方法,并提供了一种紧凑而新颖的方法来完成我在问题中发布的相同任务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-25
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 2016-02-18
      • 1970-01-01
      • 2019-10-08
      相关资源
      最近更新 更多