您的位置:首页 > 其它

sklearn的precision_score, recall_score, f1_score使用

2017-07-12 09:23 495 查看

1 使用numpy计算true positives等

import numpy as np

y_true = np.array([0, 1, 1, 0, 1, 0])
y_pred = np.array([1, 1, 1, 0, 0, 1])

# true positive
TP = np.sum(np.multiply(y_true, y_pred))
print(TP)

# false positive
FP = np.sum(np.logical_and(np.equal(y_true, 0), np.equal(y_pred, 1)))
print(FP)

# false negative
FN = np.sum(np.logical_and(np.equal(y_true, 1), np.equal(y_pred, 0)))
print(FN)

# true negative
TN = np.sum(np.logical_and(np.equal(y_true, 0), np.equal(y_pred, 0)))
print(TN)
输出结果:

2
2
1
1


2 使用tensorflow计算true positives等

import tensorflow as tf

sess = tf.Session()

y_true = tf.constant([0, 1, 1, 0, 1, 0])
y_pred = tf.constant([1, 1, 1, 0, 0, 1])

# true positive
TP = tf.reduce_sum(tf.multiply(y_true, y_pred))
print(sess.run(TP))

# false positive
FP = 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 negative
FN = 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 negative
TN = tf.reduce_sum(tf.cast(tf.logical_and(tf.equal(y_true, 0), tf.equal(y_pred, 0)), tf.int32))
print(sess.run(TN))输出结果:
2
2
1
1


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

3.1 数据是list类型

from sklearn.metrics import precision_score, recall_score, f1_score

y_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.5
0.666666666667
0.571428571429


3.2 数据是ndarray类型

from sklearn.metrics import precision_score, recall_score, f1_score
import numpy as np

y_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.5
0.666666666667
0.571428571429
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: