简体   繁体   English

如何为Tensorflow优化器创建自定义指标?

[英]How create custom metric for Tensorflow optimizer?

I want minimize/maximize such metrics as F1-score, Precision, Recall and my custom metric. 我想要最小化/最大化F1得分,精度,召回率和自定义指标之类的指标。 There is my metric and optimizer code: 有我的指标和优化程序代码:

def my_metric(logits, labels):
    predicted = tf.argmax(logits, 1)
    actual = tf.argmax(labels, 1)

    NS = tf.count_nonzero(actual)
    NR = tf.reduce_sum(tf.cast(tf.equal(actual, 0), tf.float32))
    TP = tf.reduce_sum(tf.cast(tf.equal(actual+predicted, 0), tf.float32))
    FP = tf.reduce_sum(tf.cast(tf.equal(actual*(1-predicted), 1), tf.float32))
    TN = tf.reduce_sum(tf.cast(tf.equal(actual+predicted, 2), tf.float32))
    FN = tf.reduce_sum(tf.cast(tf.equal(actual+(1-predicted), 0), tf.float32))
    '''
    Precision = TP / TP + FP
    Recall = TP / TP + FN
    b = 0.5
    denom = (1.0 + b**2) * TP + FN*b**2 + FP
    Fb = (1.0 + b**2) * TP / denom
    '''
    Metric = (TP / NR) - (FP / NS)

    return Metric


def training(metric, learning_rate):
    optimizer = tf.train.AdamOptimizer(learning_rate)
    train_op = optimizer.minimize(metric)
    return train_op

When i try to minimize any metric, i get such error: 当我尝试最小化任何指标时,出现以下错误:

ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables [...] and loss Tensor("Training/Sub_3:0", shape=(), dtype=float32). ValueError:没有为任何变量提供渐变,请在图形中检查变量和损耗Tensor(“ Training / Sub_3:0”,shape =(),dtype = float32)之间不支持渐变的运算。

What should i do to train my neural network using some custom metric instead loss function? 我应该怎么做才能使用一些自定义指标而不是损失函数来训练我的神经网络? Maybe add some gradient definition? 也许添加一些渐变定义? How to do it for metrics above? 如何针对上述指标进行操作?

The metric has to be differentiable to your parameters. 指标必须与您的参数不同。 The tensorflow method tf.equal is not differentiable. 张量流方法tf.equal是不可微的。

If you are not sure whether an operation is differentiable wrt your parameters, you can find out using tf.gradients method. 如果不确定参数是否可以区分操作,则可以使用tf.gradients方法进行查找

import tensorflow as tf

w = tf.Variable(1, name="w", dtype=tf.float32 ) # parameter to optimize for
x = tf.placeholder(shape=(), dtype=tf.float32, name="x") # input
op = tf.multiply(w,x)

grads_op_wrt_w = tf.gradients(op, w)
print(grads_op_wrt_w)

I have create a small gist for a method which checks the gradient flow of an operation here . 我为方法创建了一个小要点,该方法可以在此处检查操作的梯度流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM