我正在尝试为Keras实现AUC指标,以便在运行期间model.fit()运行验证集后进行AUC测量.
我将指标定义为:
def auc(y_true, y_pred):
keras.backend.get_session().run(tf.global_variables_initializer())
keras.backend.get_session().run(tf.initialize_all_variables())
keras.backend.get_session().run(tf.initialize_local_variables())
#return K.variable(value=tf.contrib.metrics.streaming_auc(
# y_pred, y_true)[0], dtype='float32')
return tf.contrib.metrics.streaming_auc(y_pred, y_true)[0]
Run Code Online (Sandbox Code Playgroud)
这导致以下错误,我不明白.
tensorflow.python.framework.errors_impl.FailedPreconditionError:
Attempting to use uninitialized value auc/true_positives...
Run Code Online (Sandbox Code Playgroud)
从在线阅读来看,似乎问题是2倍,张量流/ keras中的错误和部分问题,而tensorflow无法从推理初始化局部变量.鉴于这两个问题,我不明白为什么我会收到此错误或如何克服它.有什么建议?
我写了另外两个可以正常工作的指标:
# PFA, prob false alert for binary classifier
def binary_PFA(y_true, y_pred, threshold=K.variable(value=0.5)):
y_pred = K.cast(y_pred >= threshold, 'float32')
# N = total number of negative labels
N = K.sum(1 - y_true)
# FP = total number of false alerts, alerts from the negative class labels
FP = K.sum(y_pred - y_pred * y_true)
return FP/N
# P_TA prob true alerts for binary classifier
def binary_PTA(y_true, y_pred, threshold=K.variable(value=0.5)):
y_pred = K.cast(y_pred >= threshold, 'float32')
# P = total number of positive labels
P = K.sum(y_true)
# TP = total number of correct alerts, alerts from the positive class labels
TP = K.sum(y_pred * y_true)
return TP/P
Run Code Online (Sandbox Code Playgroud)
以下是我经常使用的技巧。基本上,这允许您使用任何现有的指标sklearn
from sklearn.metrics import roc_auc_score
import tensorflow as tf
def auc( y_true, y_pred ) :
score = tf.py_func( lambda y_true, y_pred : roc_auc_score( y_true, y_pred, average='macro', sample_weight=None).astype('float32'),
[y_true, y_pred],
'float32',
stateful=False,
name='sklearnAUC' )
return score
Run Code Online (Sandbox Code Playgroud)
现在我们可以创建一个简单的模型来验证这个指标。
from keras.layers import Input
from keras.models import Model
x = Input(shape=(100,))
y = Dense(10, activation='sigmoid')(x)
model = Model(inputs=x, outputs=y)
model.compile( 'sgd', loss='binary_crossentropy', metrics=[auc] )
print model.summary()
a = np.random.randn(1000,100)
b = np.random.randint(low=0,high=2,size=(1000,10))
model.fit( a, b )
Run Code Online (Sandbox Code Playgroud)
小智 4
您需要在返回 auc 张量之前运行 tf.initialize_local_variables()
def auc(y_true, y_pred):
auc = tf.metrics.auc(y_true, y_pred)[1]
K.get_session().run(tf.local_variables_initializer())
return auc
Run Code Online (Sandbox Code Playgroud)
这会将 TP、FP、TN、FN 初始化为零。请注意,这只会在第一次计算时给出正确的 auc 分数,因为 TP、FP、TN、FN 变量必须在每次运行后初始化为零。
| 归档时间: |
|
| 查看次数: |
1895 次 |
| 最近记录: |