为keras添加AUC评估指标

作者:luozhipeng   发表日期:2017-4-25  浏览:4,748次

 

首先建立callbacks脚本,

my_callbacks.py如下:



import keras
from sklearn.metrics import roc_auc_score
import numpy as np

class Histories(keras.callbacks.Callback):
    def on_train_begin(self, logs={}):
        self.aucs = []
        self.losses = []

    def on_train_end(self, logs={}):
        return

    def on_epoch_begin(self, epoch, logs={}):
        return

    def on_epoch_end(self, epoch, logs={}):
        self.losses.append(logs.get('loss'))
        y_pred = self.model.predict(self.validation_data[0:2])

        yp = []
        for i in xrange(0, len(y_pred)):
            yp.append(y_pred[i][0])
        yt = []
        for x in self.validation_data[2]:
            yt.append(x[0])
        
        auc = roc_auc_score(yt, yp)
        self.aucs.append(auc)
        print 'val-loss',logs.get('loss'), ' val-auc: ',auc,
        print '\n'
        
        return

    def on_batch_begin(self, batch, logs={}):
        return

    def on_batch_end(self, batch, logs={}):
        return


 

模型的输入为:


model = Model(inputs=[keyword1, keyword2], outputs=y)

 

在每个epoch结束时计算auc并输出:


histories = my_callbacks.Histories()

model.fit(train_x, train_y, batch_size=1024, epochs=20,shuffle=True, class_weight={1:1.0, 0:0.25}, validation_split=0.2, callbacks=[histories, model_check, lr])

本文固定链接: http://www.luozhipeng.com/?p=1225
转载请注明: luozhipeng 2017-4-25 于 罗志鹏的BLOG 发表

上一篇: :下一篇
返回顶部