keras 上新增 roc auc指標

2022-03-16 06:38:47 字數 2724 閱讀 5737

keras 輸出roc指標,不能每個batch輸出一次,需要全部計算完再一次計算一次。使用sklearn中的metrics roc來計算。幾個帖子類似

class

roc_callback(keras.callbacks.callback):

def__init__

(self,training_data,validation_data):

self.x =training_data[0]

self.y = training_data[1]

self.x_val =validation_data[0]

self.y_val = validation_data[1]

def on_train_begin(self, logs={}):

return

def on_train_end(self, logs={}):

return

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

return

def on_epoch_end(self, epoch, logs={}):

y_pred =self.model.predict(self.x)

roc =roc_auc_score(self.y, y_pred)

y_pred_val =self.model.predict(self.x_val)

roc_val =roc_auc_score(self.y_val, y_pred_val)

print('

\rroc-auc: %s - roc-auc_val: %s

' % (str(round(roc,4)),str(round(roc_val,4))),end=100*'

'+'\n')

return

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

return

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

return

callbacks=[roc_callback(training_data=training_data,validation_data=validation_data)]

首先建立callbacks指令碼,

my_callbacks.py如下:

import

keras

from sklearn.metrics import

roc_auc_score

import

numpy as np

class

histories(keras.callbacks.callback):

6 def on_train_begin(self, logs={}):

7self.aucs =

8self.losses =9

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

11 return12

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

14 return15

16 def on_epoch_end(self, epoch, logs={}):

'loss'))

18y_pred = self.model.predict(self.validation_data[0:2])19

20yp =

21 for i in

xrange(0, len(y_pred)):

23yt =

24 for x in self.validation_data[2]:

26

27auc =roc_auc_score(yt, yp)

29 print

'val-loss

',logs.get('

loss

'), '

val-auc:

',auc,

30 print'\n

'3132 return33

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

35 return36

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

38 return

模型的輸入為:

1

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

在每個epoch結束時計算auc並輸出:

1

histories = my_callbacks.histories()

2

3

model.fit(train_x, train_y, batch_size=1024, epochs=20,shuffle=true, class_weight=, validation_split=0.2, callbacks=[histories, model_check, lr])

keras中新增正則化

正則項在優化過程中層的引數或層的啟用值新增懲罰項,這些懲罰項將與損失函式一起作為網路的最終優化目標 懲罰項基於層進行懲罰,目前懲罰項的介面與層有關,但dense,conv1d,conv2d,conv3d具有共同的介面。這些層有三個關鍵字引數以施加正則項 from keras import regul...

Keras中堆疊新增GRU

from keras.layers import lstm,gru是的,這兩模型可以同時引入。model sequential model.add gru 100,dropout 0.2,recurrent dropout 0.2,return sequences true,input shape ...

Keras上實現AutoEncoder自編碼器

無監督特徵學習 unsupervised feature learning 是一種仿人腦的對特徵逐層抽象提取的過程,學習過程中有兩點 一是無監督學習,即對訓練資料不需要進行標籤化標註,這種學習是對資料內容的組織形式的學習,提取的是頻繁出現的特徵 二是逐層抽象,特徵是需要不斷抽象的。自編碼器 auto...