自定义估算器中的准确性指标

时间:2018-08-15 18:11:23

标签: python python-3.x tensorflow tensorboard

我正在使用自己的估算函数执行多类分类。该代码在我的机器上正常工作。我还将检查点保存到目录中,以便稍后在tensorboard中对其进行可视化

def train_and_evaluate(classifier):
   # Save a reference to the classifier to run predictions later
   all_classifiers[classifier.model_dir] = classifier
   classifier.train(input_fn=train_input_fn, steps=2500)
   eval_results = classifier.evaluate(input_fn=eval_input_fn)
   predictions = np.array([p['logistic'][0] for p in 
   classifier.predict(input_fn=eval_input_fn)])

   # Reset the graph to be able to reuse name scopes
   tf.reset_default_graph()

    # Add a PR summary in addition to the summaries that the classifier writes
    pr = summary_lib.pr_curve('precision_recall', predictions=predictions, labels=y_test.astype(bool),
                          num_thresholds=21)


    with tf.Session() as sess:
       writer = tf.summary.FileWriter(os.path.join(classifier.model_dir, 'eval'), sess.graph)
       writer.add_summary(sess.run(pr), global_step=0)
       writer.close()

head = tf.contrib.estimator.binary_classification_head()


def cnn_model_fn(features, labels, mode, params):
    input_layer = tf.contrib.layers.embed_sequence(
        features['x'], vocab_size, embedding_size,
        initializer=params['embedding_initializer'])

    training = mode == tf.estimator.ModeKeys.TRAIN
    dropout_emb = tf.layers.dropout(inputs=input_layer,
                                    rate=0.2,
                                    training=training)

    conv = tf.layers.conv1d(
        inputs=dropout_emb,
        filters=32,
        kernel_size=3,
        padding="same",
        activation=tf.nn.relu)

    # Global Max Pooling
    pool = tf.reduce_max(input_tensor=conv, axis=1)

    hidden = tf.layers.dense(inputs=pool, units=250, activation=tf.nn.relu)

    dropout_hidden = tf.layers.dropout(inputs=hidden,
                                       rate=0.2,
                                       training=training)

    logits = tf.layers.dense(inputs=dropout_hidden, units=1)

    # This will be None when predicting
    if labels is not None:
        labels = tf.reshape(labels, [-1, 1])

    optimizer = tf.train.AdamOptimizer()



    def _train_op_fn(loss):
        return optimizer.minimize(
            loss=loss,
            global_step=tf.train.get_global_step())

    return head.create_estimator_spec(
        features=features,
        labels=labels,
        mode=mode,
        logits=logits,
        train_op_fn=_train_op_fn)


params = {'embedding_initializer': tf.random_uniform_initializer(-1.0, 1.0)}
classifier = tf.estimator.Estimator(model_fn=cnn_model_fn,
                                        model_dir=os.path.join(model_dir, 'cnn'),
                                        params=params)

train_and_evaluate(classifier)

这是我的张量板的外观enter image description here

在训练中,我正在绘制global_step和损失(不在此图中),如何为训练函数添加准确性指标?

0 个答案:

没有答案