sklearn的precision_score, recall_score, f1_score使用

来源:互联网 发布:北京华贸广场caffe 编辑:程序博客网 时间:2024/06/08 03:16

1 使用numpy计算true positives等

import numpy as npy_true = np.array([0, 1, 1, 0, 1, 0])y_pred = np.array([1, 1, 1, 0, 0, 1])# true positiveTP = np.sum(np.multiply(y_true, y_pred))print(TP)# false positiveFP = np.sum(np.logical_and(np.equal(y_true, 0), np.equal(y_pred, 1)))print(FP)# false negativeFN = np.sum(np.logical_and(np.equal(y_true, 1), np.equal(y_pred, 0)))print(FN)# true negativeTN = np.sum(np.logical_and(np.equal(y_true, 0), np.equal(y_pred, 0)))print(TN)
输出结果:

2211

2 使用tensorflow计算true positives等

import tensorflow as tfsess = tf.Session()y_true = tf.constant([0, 1, 1, 0, 1, 0])y_pred = tf.constant([1, 1, 1, 0, 0, 1])# true positiveTP = tf.reduce_sum(tf.multiply(y_true, y_pred))print(sess.run(TP))# false positiveFP = tf.reduce_sum(tf.cast(tf.logical_and(tf.equal(y_true, 0), tf.equal(y_pred, 1)), tf.int32))print(sess.run(FP))# false negativeFN = tf.reduce_sum(tf.cast(tf.logical_and(tf.equal(y_true, 1), tf.equal(y_pred, 0)), tf.int32))print(sess.run(FN))# true negativeTN = tf.reduce_sum(tf.cast(tf.logical_and(tf.equal(y_true, 0), tf.equal(y_pred, 0)), tf.int32))print(sess.run(TN))
输出结果:

2211

3 使用sklearn的metrics模块计算precision,recall和f1-score

3.1 数据是list类型

from sklearn.metrics import precision_score, recall_score, f1_scorey_true = [0, 1, 1, 0, 1, 0]y_pred = [1, 1, 1, 0, 0, 1]p = precision_score(y_true, y_pred, average='binary')r = recall_score(y_true, y_pred, average='binary')f1score = f1_score(y_true, y_pred, average='binary')print(p)print(r)print(f1score)
输出结果:

0.50.6666666666670.571428571429

3.2 数据是ndarray类型

from sklearn.metrics import precision_score, recall_score, f1_scoreimport numpy as npy_true = np.array([[0, 1, 1],                    [0, 1, 0]])y_pred = np.array([[1, 1, 1],                    [0, 0, 1]])y_true = np.reshape(y_true, [-1])y_pred = np.reshape(y_pred, [-1])p = precision_score(y_true, y_pred, average='binary')r = recall_score(y_true, y_pred, average='binary')f1score = f1_score(y_true, y_pred, average='binary')print(p)print(r)print(f1score)
输出结果:

0.50.6666666666670.571428571429

阅读全文
0 2