keras計算precision、recall、F1值
阿新 • • 發佈:2021-01-26
技術標籤:自然語言處理深度學習tensorflow
近期寫課程作業,需要用Keras搭建網路層,跑實驗時需要計算precision,recall和F1值,在前幾年,Keras沒有更新時,我用的程式碼是直接取訓練期間的預測標籤,然後和真實標籤之間計算求解,程式碼是
from keras.callbacks import Callback from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score class Metrics(Callback): def on_train_begin(self, logs={}): self.val_f1s = [] self.val_recalls = [] self.val_precisions = [] def on_epoch_end(self, epoch, logs={}): val_predict = (np.asarray(self.model.predict(self.validation_data[0]))).round()##.model val_targ = self.validation_data[1]###.model _val_f1 = f1_score(val_targ, val_predict,average='micro') _val_recall = recall_score(val_targ, val_predict,average=None)### _val_precision = precision_score(val_targ, val_predict,average=None)### self.val_f1s.append(_val_f1) self.val_recalls.append(_val_recall) self.val_precisions.append(_val_precision) #print("— val_f1: %f — val_precision: %f — val_recall: %f" %(_val_f1, _val_precision, _val_recall)) print("— val_f1: %f "%_val_f1) return f1=Metrics() hist=cnn_net.fit(x_train,y_train,batch_size=batch_size,epochs=35,verbose=1,validation_data=(x_train,y_train),callbacks=[f1])
需要使用時,將Metrics檔案匯入,呼叫函式,放置到model.fit( callbacks=[ f1 ] )中就可以計算了。
現在TensorFlow更新到2.2.0以上,Keras版本為2.4.3以上,上面那個函式就不太管用了,後來查資料找到了一個包,keras-metrics.
安裝後,匯入包 keras_metrics,將設定好的引數放置model.compile( metrics=[ km.f1score()] )
import keras import keras_metrics as km model = models.Sequential() model.add(keras.layers.Dense(1, activation="sigmoid", input_dim=2)) model.add(keras.layers.Dense(1, activation="softmax")) model.compile(optimizer="sgd", loss="binary_crossentropy", metrics=[km.f1score(), km.binary_precision(), km.binary_recall()])
新增上之後,就可以計算評價值了。