我使用我的测试集作为验证集。我使用类似的方法作为How to compute Receiving Operating Characteristic (ROC) and AUC in keras?
问题是我在训练期间的val_auc大约是0.85,当我使用时
fpr, tpr, _ = roc_curve(test_label, test_prediction)
roc_auc = auc(fpr, tpr)
我得到了0.60的金额。我知道他们使用不同的配方,并且流式传输可能与sklearn计算的不同。但差异非常大,我无法弄清楚造成这种差异的原因。
# define roc_callback, inspired by https://github.com/keras-team/keras/issues/6050#issuecomment-329996505
def auc_roc(y_true, y_pred):
# any tensorflow metric
value, update_op = tf.contrib.metrics.streaming_auc(y_pred, y_true)
# find all variables created for this metric
metric_vars = [i for i in tf.local_variables() if 'auc_roc' in i.name.split('/')[1]]
# Add metric variables to GLOBAL_VARIABLES collection.
# They will be initialized for new session.
for v in metric_vars:
tf.add_to_collection(tf.GraphKeys.GLOBAL_VARIABLES, v)
# force to update metric values
with tf.control_dependencies([update_op]):
value = tf.identity(value)
return value
clf = Sequential()
clf.add(LSTM(units = 128, input_shape = (windowlength, trainX.shape[2]), return_sequences = True))#, kernel_regularizer=regularizers.l2(0.01)))
clf.add(Dropout(0.2))
clf.add(LSTM(units = 64, return_sequences = False))#, kernel_regularizer=regularizers.l2(0.01)))
clf.add(Dropout(0.2))
clf.add(Dense(units = 128, activation = 'relu'))
clf.add(Dropout(0.2))
clf.add(Dense(units = 128, activation = 'relu'))
clf.add(Dense(units = 1, activation = 'sigmoid'))
clf.compile(loss='binary_crossentropy', optimizer = 'adam', metrics = ['acc', auc_roc])
my_callbacks = [EarlyStopping(monitor='auc_roc', patience=50, verbose=1, mode='max')]
clf.fit(trainX, trainY, batch_size = 1000, epochs = 80, class_weight = class_weights, validation_data = (testX, testY),
verbose = 2, callbacks=my_callbacks)
y_pred_pro = model.predict_proba(testX)
print (roc_auc_score(y_test, y_pred_pro))
如果有人能引导我走向正确的方向,我真的很感激。
首先,tf.contrib.metrics.streaming_auc
已弃用,请改用tf.metrics.auc
。
正如您所提到的,TF使用不同的方法来计算AUC而不是Scikit-learn。 TF使用近似方法。引用其文档:
为了离散AUC曲线,使用线性间隔的阈值集来计算召回和精确值对。
这几乎总是会给出比实际得分更高的AUC分数。此外,thresholds
参数默认为200,如果数据集很大,则该参数为低。增加它应该使分数更准确,但无论你设置多高,它总会有一些错误。
另一方面,Scikit-learn使用不同的方法计算“真实的”AUC分数。
我不知道为什么TF使用近似方法,但我想因为它的内存效率更高,速度更快。此外,虽然它高估了分数,但它很可能会保留模型的相对顺序:如果一个模型具有比另一个模型更接近的AUC,那么它的真正AUC将 - 也可能 - 也更好。