我正在使用Keras(TensorFlow)来构建深度神经网络模型 . 在模型中,我需要定义自己的精度函数 .
假设模型预测完成工作所需的时间(以分钟为单位,介于0到20之间) . 如果预测输出在/ - 2之内,我希望模型打印出精度 . 如果预测输出是x分钟,而预期输出是x 1,我想要考虑这是一个正确的预测,如果预期输出是x 3,我想考虑这是一个错误的预测 .
这与 top_k_categorical_accuracy 略有不同
top_k_categorical_accuracy
您可以使用Keras后端apis轻松实现逻辑..这也将确保您的度量标准在tensorflow和theano上工作 .
这里有测试:
import numpy as np import keras from keras import backend as K shift = 2 def custom_metric(y_true,y_pred): diff = K.abs(K.argmax(y_true, axis=-1) - K.argmax(y_pred, axis=-1)) return K.mean(K.lesser_equal(diff, shift)) t1 = np.asarray([ [0,0,0,0,0,0,1,0,0,], [0,0,0,0,0,0,1,0,0,], [0,0,0,0,0,0,1,0,0,], [0,0,0,0,0,0,1,0,0,], [0,0,0,0,0,0,1,0,0,], [0,0,0,0,0,0,1,0,0,], ]) p1 = np.asarray([ [0,0,0,0,0,1,0,0,0,], [0,0,0,0,1,0,0,0,0,], [0,0,0,0,0,0,0,1,0,], [0,0,0,0,0,0,0,0,1,], [1,0,0,0,0,0,0,0,0,], [0,0,0,0,0,0,1,0,0,], ]) print K.eval(keras.metrics.categorical_accuracy(K.variable(t1),K.variable(p1))) print K.eval(custom_metric(K.variable(t1),K.variable(p1)))
现在在 compile 语句中使用它: metrics=custom_metric
compile
metrics=custom_metric
1 回答
您可以使用Keras后端apis轻松实现逻辑..这也将确保您的度量标准在tensorflow和theano上工作 .
这里有测试:
现在在
compile
语句中使用它:metrics=custom_metric