【问题标题】:How to calculate accuracy in training RNN language model in Tensorflow?如何在 Tensorflow 中计算训练 RNN 语言模型的准确率?
【发布时间】:2019-01-29 12:08:21
【问题描述】:

我在这里使用这个词级 RNN 语言模型:https://github.com/hunkim/word-rnn-tensorflow

如何计算RNN模型在每个epoch的准确率。

以下是训练中的代码,显示每个 epoch 中的训练损失和其他内容:

for e in range(model.epoch_pointer.eval(), args.num_epochs):
        sess.run(tf.assign(model.lr, args.learning_rate * (args.decay_rate ** e)))
        data_loader.reset_batch_pointer()
        state = sess.run(model.initial_state)
        speed = 0
        if args.init_from is None:
            assign_op = model.epoch_pointer.assign(e)
            sess.run(assign_op)
        if args.init_from is not None:
            data_loader.pointer = model.batch_pointer.eval()
            args.init_from = None
        for b in range(data_loader.pointer, data_loader.num_batches):
            start = time.time()
            x, y = data_loader.next_batch()
            feed = {model.input_data: x, model.targets: y, model.initial_state: state,
                    model.batch_time: speed}
            summary, train_loss, state, _, _ = sess.run([merged, model.cost, model.final_state,
                                                         model.train_op, model.inc_batch_pointer_op], feed)
            train_writer.add_summary(summary, e * data_loader.num_batches + b)
            speed = time.time() - start
            if (e * data_loader.num_batches + b) % args.batch_size == 0:
                print("{}/{} (epoch {}), train_loss = {:.3f}, time/batch = {:.3f}" \
                    .format(e * data_loader.num_batches + b,
                            args.num_epochs * data_loader.num_batches,
                            e, train_loss, speed))
            if (e * data_loader.num_batches + b) % args.save_every == 0 \
                    or (e==args.num_epochs-1 and b == data_loader.num_batches-1): # save for the last result
                checkpoint_path = os.path.join(args.save_dir, 'model.ckpt')
                saver.save(sess, checkpoint_path, global_step = e * data_loader.num_batches + b)
                print("model saved to {}".format(checkpoint_path))
train_writer.close()

【问题讨论】:

    标签: python tensorflow lstm


    【解决方案1】:

    因为模型对每个类别都有目标和预测概率。 您可以减少概率张量以保持最高概率的类索引。

    predictions = tf.cast(tf.argmax(model.probs, axis=2), tf.int32)
    

    然后你可以与目标进行比较,以了解它是否成功预测:

    correct_preds = tf.equal(predictions, model.targets)
    

    最后,准确度是正确预测与输入大小之间的比率,也就是这个布尔张量的平均值。

    accuracy = tf.reduce_mean(tf.cast(correct_preds, tf.float32))
    

    【讨论】:

    • 我在 correct_preds = tf.equal(predictions, model.targets) ValueError 中遇到错误:尺寸必须相等,但对于输入的“相等”(操作:“相等”),尺寸必须是 31215 和 25形状:[31215]、[50,25]。找不到任何解决方案
    • Hum 尝试重塑张量,因此第一个维度是获取 argmax 索引之前的批量大小。 tf.reshape(model.probs, [50, -1])
    • 我尝试在预测变量中使用重塑而不是 model.probs,它现在可以工作了。但是当我尝试在每个时期打印精度时,结果是“Tensor("Mean_150:0", shape=(), dtype=float32)"
    • 嗨@Austin,是的,这意味着这是一个包含单个浮点值的张量。这里它代表准确度。要打印张量的内容,请在会话中运行该操作,并打印返回值。显然你也可以使用accuracy = tf.Print(accuracy, accuracy, message="Acc=")
    【解决方案2】:

    你也可以使用 Tensorflow 的tf.metrics.accuracy 函数。

    accuracy, accuracy_update_op  = tf.metrics.accuracy(labels = tf.argmax(y, axis = 2), predictions = tf.argmax(predictions, axis = 2), name = 'accuracy')
    running_vars_accuracy = tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES, scope="LSTM/Accuracy")
    

    accuracy_update_op操作会更新每批的两个局部变量:

    [<tf.Variable 'accuracy/total:0' shape=() dtype=float32_ref>,
     <tf.Variable 'accuracy/count:0' shape=() dtype=float32_ref>]
    

    然后,只需调用 accuracy op 将打印每个 epoch 的整体准确度:

    for epoch in range(num_epochs):
        avg_cost_train = 0.
        total_train_batch = int((len(X_train)/(batch_size)) + 1)
    
        running_vars_initializer_accuracy.run()
        for _ in range(total_train_batch):
            _, miniBatchCost_train, miniBatchAccuracy_train = sess.run([trainer, loss, accuracy_update_op], feed_dict = {X: Xtrain, y: ytrain})
            avg_cost_train += miniBatchCost_train / total_train_batch
        accuracy_train = sess.run(accuracy)
    

    这里需要注意的是,不要在同一个session.run() 函数调用中调用tf_metrictf_metric_update

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-26
      • 2019-04-12
      • 1970-01-01
      • 2018-09-27
      • 1970-01-01
      • 2020-10-17
      • 2023-04-04
      • 1970-01-01
      相关资源
      最近更新 更多