precision_score, recall_score, f1_score的计算

1 使用numpy计算true positives等

[python]  view plain  copy
  1. import numpy as np  
  2.   
  3. y_true = np.array([011010])  
  4. y_pred = np.array([111001])  
  5.   
  6. # true positive  
  7. TP = np.sum(np.multiply(y_true, y_pred))  
  8. print(TP)  
  9.   
  10. # false positive  
  11. FP = np.sum(np.logical_and(np.equal(y_true, 0), np.equal(y_pred, 1)))  
  12. print(FP)  
  13.   
  14. # false negative  
  15. FN = np.sum(np.logical_and(np.equal(y_true, 1), np.equal(y_pred, 0)))  
  16. print(FN)  
  17.   
  18. # true negative  
  19. TN = np.sum(np.logical_and(np.equal(y_true, 0), np.equal(y_pred, 0)))  
  20. print(TN)  
输出结果:

2
2
1
1

2 使用tensorflow计算true positives等

[python]  view plain  copy
  1. import tensorflow as tf  
  2.   
  3. sess = tf.Session()  
  4.   
  5. y_true = tf.constant([011010])  
  6. y_pred = tf.constant([111001])  
  7.   
  8. # true positive  
  9. TP = tf.reduce_sum(tf.multiply(y_true, y_pred))  
  10. print(sess.run(TP))  
  11.   
  12. # false positive  
  13. FP = tf.reduce_sum(tf.cast(tf.logical_and(tf.equal(y_true, 0), tf.equal(y_pred, 1)), tf.int32))  
  14. print(sess.run(FP))  
  15.   
  16. # false negative  
  17. FN = tf.reduce_sum(tf.cast(tf.logical_and(tf.equal(y_true, 1), tf.equal(y_pred, 0)), tf.int32))  
  18. print(sess.run(FN))  
  19.   
  20. # true negative  
  21. TN = tf.reduce_sum(tf.cast(tf.logical_and(tf.equal(y_true, 0), tf.equal(y_pred, 0)), tf.int32))  
  22. print(sess.run(TN))  
输出结果:

2
2
1
1

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

3.1 数据是list类型

[python]  view plain  copy
  1. from sklearn.metrics import precision_score, recall_score, f1_score  
  2.   
  3. y_true = [011010]  
  4. y_pred = [111001]  
  5.   
  6. p = precision_score(y_true, y_pred, average='binary')  
  7. r = recall_score(y_true, y_pred, average='binary')  
  8. f1score = f1_score(y_true, y_pred, average='binary')  
  9.   
  10. print(p)  
  11. print(r)  
  12. print(f1score)  
输出结果:

0.5
0.666666666667
0.571428571429

3.2 数据是ndarray类型

扫描二维码关注公众号,回复: 2662420 查看本文章
[python]  view plain  copy
  1. from sklearn.metrics import precision_score, recall_score, f1_score  
  2. import numpy as np  
  3.   
  4. y_true = np.array([[011],   
  5.                    [010]])  
  6. y_pred = np.array([[111],   
  7.                    [001]])  
  8.   
  9. y_true = np.reshape(y_true, [-1])  
  10. y_pred = np.reshape(y_pred, [-1])  
  11.   
  12. p = precision_score(y_true, y_pred, average='binary')  
  13. r = recall_score(y_true, y_pred, average='binary')  
  14. f1score = f1_score(y_true, y_pred, average='binary')  
  15.   
  16. print(p)  
  17. print(r)  
  18. print(f1score)  
输出结果:

0.5
0.666666666667
0.571428571429
转自:http://blog.csdn.net/blythe0107/article/details/75003890

猜你喜欢

转载自blog.csdn.net/u010859498/article/details/79022704