Keras 利用sklearn的ROC-AUC建立評(píng)價(jià)函數(shù)詳解
我就廢話不多說(shuō)了,大家還是直接看代碼吧!
# 利用sklearn自建評(píng)價(jià)函數(shù) from sklearn.model_selection import train_test_split from sklearn.metrics import roc_auc_score from keras.callbacks import Callback class RocAucEvaluation(Callback): def __init__(self, validation_data=(), interval=1): super(Callback, self).__init__() self.interval = interval self.x_val,self.y_val = validation_data def on_epoch_end(self, epoch, log={}): if epoch % self.interval == 0: y_pred = self.model.predict(self.x_val, verbose=0) score = roc_auc_score(self.y_val, y_pred) print('\n ROC_AUC - epoch:%d - score:%.6f \n' % (epoch+1, score)) x_train,y_train,x_label,y_label = train_test_split(train_feature, train_label, train_size=0.95, random_state=233) RocAuc = RocAucEvaluation(validation_data=(y_train,y_label), interval=1) hist = model.fit(x_train, x_label, batch_size=batch_size, epochs=epochs, validation_data=(y_train, y_label), callbacks=[RocAuc], verbose=2)
補(bǔ)充知識(shí):keras用auc做metrics以及早停
我就廢話不多說(shuō)了,大家還是直接看代碼吧!
import tensorflow as tf from sklearn.metrics import roc_auc_score def auroc(y_true, y_pred): return tf.py_func(roc_auc_score, (y_true, y_pred), tf.double) # Build Model... model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy', auroc])
完整例子:
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 def create_model_nn(in_dim,layer_size=200): model = Sequential() model.add(Dense(layer_size,input_dim=in_dim, kernel_initializer='normal')) model.add(BatchNormalization()) model.add(Activation('relu')) model.add(Dropout(0.3)) for i in range(2): model.add(Dense(layer_size)) model.add(BatchNormalization()) model.add(Activation('relu')) model.add(Dropout(0.3)) model.add(Dense(1, activation='sigmoid')) adam = optimizers.Adam(lr=0.01) model.compile(optimizer=adam,loss='binary_crossentropy',metrics = [auc]) return model ####cv train folds = StratifiedKFold(n_splits=5, shuffle=False, random_state=15) oof = np.zeros(len(df_train)) predictions = np.zeros(len(df_test)) for fold_, (trn_idx, val_idx) in enumerate(folds.split(df_train.values, target2.values)): print("fold n°{}".format(fold_)) X_train = df_train.iloc[trn_idx][features] y_train = target2.iloc[trn_idx] X_valid = df_train.iloc[val_idx][features] y_valid = target2.iloc[val_idx] model_nn = create_model_nn(X_train.shape[1]) callback = EarlyStopping(monitor="val_auc", patience=50, verbose=0, mode='max') history = model_nn.fit(X_train, y_train, validation_data = (X_valid ,y_valid),epochs=1000,batch_size=64,verbose=0,callbacks=[callback]) print('\n Validation Max score : {}'.format(np.max(history.history['val_auc']))) predictions += model_nn.predict(df_test[features]).ravel()/folds.n_splits
以上這篇Keras 利用sklearn的ROC-AUC建立評(píng)價(jià)函數(shù)詳解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python selenium 實(shí)例之通過(guò) selenium 查詢禪道是否有任務(wù)或者BUG
這篇文章主要介紹了Python selenium 實(shí)例之通過(guò) selenium 查詢禪道是否有任務(wù)或者BUG的相關(guān)資料,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09pytorch創(chuàng)建tensor函數(shù)詳情
這篇文章主要介紹了pytorch創(chuàng)建tensor函數(shù)詳情,文章圍繞tensor函數(shù)的相關(guān)自來(lái)哦展開(kāi)詳細(xì)內(nèi)容的介紹,需要的小伙伴可以參考一下,希望對(duì)你有所幫助2022-03-032021年的Python 時(shí)間軸和即將推出的功能詳解
這篇文章主要介紹了2021年的Python 時(shí)間軸和即將推出的功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07Python調(diào)用edge-tts實(shí)現(xiàn)在線文字轉(zhuǎn)語(yǔ)音效果
edge-tts是一個(gè) Python 模塊,允許通過(guò)Python代碼或命令的方式使用 Microsoft Edge 的在線文本轉(zhuǎn)語(yǔ)音服務(wù),這篇文章主要介紹了Python調(diào)用edge-tts實(shí)現(xiàn)在線文字轉(zhuǎn)語(yǔ)音效果,需要的朋友可以參考下2024-03-03Python實(shí)現(xiàn)變量數(shù)值交換及判斷數(shù)組是否含有某個(gè)元素的方法
這篇文章主要介紹了Python實(shí)現(xiàn)變量數(shù)值交換及判斷數(shù)組是否含有某個(gè)元素的方法,涉及Python字符串與數(shù)組的相關(guān)賦值、判斷操作技巧,需要的朋友可以參考下2017-09-09