【續(xù)】--Tensorflow踩坑記之tf.metrics
欠下的帳總歸還是要還的醋界,之前一直拖著服鹅,總是懶得寫tf.metrics
這個(gè)API的一些用法混蔼,今天總算是克服了懶癌涧尿,總結(jié)一下tf.metrics
遇到的一些坑系奉。
- 博客中涉及到的所有代碼都已經(jīng)傳到瀾子的Github上啦~歡迎互粉哇圈盔。
- 本篇博客也傳到了瀾子的個(gè)人博客匪蝙,歡迎大噶多多關(guān)注哇炊汹。
插一句閑話头谜,這一次的博客基本上用的都是 Jupyter,感覺一級(jí)好用啊脂新⊙崞可以一邊寫代碼槽地,一邊記markdown号阿,忍不住上一張效果圖并鸵,再次歡迎大噶去我的Github上看一看,而且Github支持 jupyter notebook 顯示扔涧,真得效果很好园担。
在這篇偽Tensorflow-tf-metrics中届谈,瀾子介紹了tf.metrics
中涉及的一些指標(biāo)和概念,包括:精確率(precision)弯汰,召回率(recall)艰山,準(zhǔn)確率(accuracy),AUC咏闪,混淆矩陣(confusion matrix)曙搬。下面先給出官方的API文檔,看看這個(gè)模塊中都有哪些隱藏秘笈鸽嫂。
看了官方文檔之后纵装,大噶可能會(huì)發(fā)現(xiàn)其中有好多可以調(diào)用的函數(shù),不僅有precision
/ accuracy
/ auc
/ recall
溪胶,還有precision_at_k
/ recall_at_k
搂擦,更有precision_at_thresholds
/ precision_at_top_k
/ sparse_precision_at_k
...天啦嚕稳诚,這都是什么呀哗脖,瀾子已經(jīng)徹底暈了,到底要怎么用鞍饣埂(眼冒金星中)才避。別急,讓我一個(gè)坑一個(gè)坑地告訴你氨距。
劃重點(diǎn)
首先桑逝,這篇文章是受到Ronny Restrepo的啟發(fā),
這是一篇很好的文章俏让,將tf.metrics.accuracy()
講解滴很清楚楞遏,本文就模仿他的思路,驗(yàn)證一下precision
的計(jì)算首昔。
精確率的計(jì)算公式
讓我們先造點(diǎn)數(shù)據(jù)寡喝,傳統(tǒng)算算看
import tensorflow as tf
import numpy as np
labels = np.array([[1,1,1,0],
[1,1,1,0],
[1,1,1,0],
[1,1,1,0]], dtype=np.uint8)
predictions = np.array([[1,0,0,0],
[1,1,0,0],
[1,1,1,0],
[0,1,1,1]], dtype=np.uint8)
n_batches = len(labels)
# First,calculate precision over entire set of batches
# using formula mentioned above
pred_p = (predictions > 0).sum()
# print(pred_p)
true_p = (labels*predictions > 0).sum()
# print(true_p)
precision = true_p / pred_p
print("Precision :%1.4f" %(precision))
上述方法的問題
由于硬件方面的一些限制,導(dǎo)致此方法不能擴(kuò)展到大型數(shù)據(jù)集勒奇,比如當(dāng)數(shù)據(jù)集很大時(shí)预鬓,就無法一次性適應(yīng)內(nèi)存。
因而赊颠,為了使其可擴(kuò)展格二,我們希望使評(píng)估指標(biāo)能夠逐步更新,每批新的預(yù)測(cè)和標(biāo)簽竣蹦。 為此顶猜,我們需要跟蹤兩個(gè)值。
- 正確預(yù)測(cè)的正樣本數(shù)量
- 預(yù)測(cè)樣本中所有正樣本的數(shù)量
所以我們要這么做
# Initialize running variables
N_TRUE_P = 0
N_PRED_P = 0
# Specific steps
# Create running variables
N_TRUE_P = 0
N_PRED_P = 0
def reset_running_variables():
""" Resets the previous values of running variables to zero """
global N_TRUE_P, N_PRED_P
N_TRUE_P = 0
c = 0
def update_running_variables(labs, preds):
global N_TRUE_P, N_PRED_P
N_TRUE_P += ((labs * preds) > 0).sum()
N_PRED_P += (preds > 0).sum()
def calculate_precision():
global N_TRUE_P, N_PRED_P
return float (N_TRUE_P) / N_PRED_P
怎么用上面的函數(shù)呢痘括?
接下來的兩個(gè)例子长窄,給出了運(yùn)用的具體代碼,并且可以更好滴幫助我們理解tf.metrics.precision()
的計(jì)算邏輯以及對(duì)應(yīng)輸出所代表的含義
樣本整體準(zhǔn)確率(直接計(jì)算)
# Overall precision
reset_running_variables()
for i in range(n_batches):
update_running_variables(labs=labels[i], preds=predictions[i])
precision = calculate_precision()
print("[NP] SCORE: %1.4f" %precision)
批次準(zhǔn)確率(直接計(jì)算)
# Batch precision
for i in range(n_batches):
reset_running_variables()
update_running_variables(labs=labels[i], preds=predictions[i])
prec = calculate_precision()
print("- [NP] batch %d score: %1.4f" %(i, prec))
[NP] batch 0 score: 1.0000
[NP] batch 1 score: 1.0000
[NP] batch 2 score: 1.0000
[NP] batch 3 score: 0.6667
不要小瞧這兩個(gè)變量和三個(gè)函數(shù)
上面說了這么多,感覺沒有tensorflow的什么事哇抄淑,別急屠凶,先看一個(gè)tensorflow的官方文檔
放一個(gè)官方的解釋
Github代碼中precision的注釋部分
The
precision
function creates two local variables,
true_positives
andfalse_positives
, that are used to compute the precision. This value is ultimately returned asprecision
, an idempotent operation that simply dividestrue_positives
by the sum oftrue_positives
andfalse_positives
.
For estimation of the metric over a stream of data, the function creates anupdate_op
operation that updates these variables and returns theprecision
.
兩個(gè)變量和 tf.metrics.precision()
的關(guān)系
官方文檔提及的two local variables :true_postives
和 false_positives
分別對(duì)應(yīng)上文定義的兩個(gè)變量。
- true_postives -- N_TRUE_P
- false_postives -- N_PRED_P - N_TRUE_P
三個(gè)函數(shù)和頭大的update_op
官方文檔提及的update_op
和precision
分別對(duì)應(yīng)上文定義的兩個(gè)函數(shù)
- precision--calculate_precision()
- update_op--update_running_variables()
大家不要被這個(gè)update_op
搞暈肆资,其實(shí)從字面來理解就是一個(gè)變量更新的操作矗愧,上文的代碼中,就是通過reset_running_variables()
的位置來決定何時(shí)對(duì)變量進(jìn)行更新郑原,其實(shí)就是對(duì)應(yīng)于tf.variables_initializer()
唉韭。我之所以一直用錯(cuò)這個(gè)API,是因?yàn)槲覍?code>tf.variables_initializer()放在了錯(cuò)誤的位置犯犁,導(dǎo)致變量沒有按照我的預(yù)期正常更新属愤,進(jìn)而結(jié)果一直不正確。具體看看tensorflow是怎么實(shí)現(xiàn)的吧酸役。
Overall precision using tensorflow
# Overall precision using tensorflow
import tensorflow as tf
graph = tf.Graph()
with graph.as_default():
# Placeholders to take in batches onf data
tf_label = tf.placeholder(dtype=tf.int32, shape=[None])
tf_prediction = tf.placeholder(dtype=tf.int32, shape=[None])
# Define the metric and update operations
tf_metric, tf_metric_update = tf.metrics.precision(tf_label,
tf_prediction,
name="my_metric")
# Isolate the variables stored behind the scenes by the metric operation
running_vars = tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES, scope="my_metric")
# Define initializer to initialize/reset running variables
running_vars_initializer = tf.variables_initializer(var_list=running_vars)
with tf.Session(graph=graph) as session:
session.run(tf.global_variables_initializer())
# initialize/reset the running variables
session.run(running_vars_initializer)
for i in range(n_batches):
# Update the running variables on new batch of samples
feed_dict={tf_label: labels[i], tf_prediction: predictions[i]}
session.run(tf_metric_update, feed_dict=feed_dict)
# Calculate the score
score = session.run(tf_metric)
print("[TF] SCORE: %1.4f" %score)
[TF] SCORE: 0.8889
Batch precision using tensorflow
# Batch precision using tensorflow
with tf.Session(graph=graph) as session:
session.run(tf.global_variables_initializer())
for i in range(n_batches):
# Reset the running variables
session.run(running_vars_initializer)
# Update the running variables on new batch of samples
feed_dict={tf_label: labels[i], tf_prediction: predictions[i]}
session.run(tf_metric_update, feed_dict=feed_dict)
# Calculate the score on this batch
score = session.run(tf_metric)
print("[TF] batch %d score: %1.4f" %(i, score))
[TF] batch 0 score: 1.0000
[TF] batch 1 score: 1.0000
[TF] batch 2 score: 1.0000
[TF] batch 3 score: 0.6667
再次劃重點(diǎn)
大噶一定要注意
session.run(running_vars_initializer)
score = session.run(tf_metric)
這兩行代碼在計(jì)算整體樣本精確度以及批次精確度所在位置的不同住诸。
瀾子第一次的時(shí)候由于粗心,并沒有注意兩段代碼的不同涣澡,才會(huì)導(dǎo)致tf計(jì)算結(jié)果和普通計(jì)算結(jié)果不一致
還需要注意的點(diǎn)
不要在一個(gè)sess.run()
里面同時(shí)調(diào)用tf_metric
和tf_metric_update
贱呐,下面的代碼是錯(cuò)誤的示范
_ , score = session.run([tf_metric_update,tf_metric],\
feed_dict=feed_dict)
update_op究竟返回了什么捏
此處參考了
stackoverflow的一個(gè)回答
具體代碼如下
rel = tf.placeholder(tf.int64, [1,3])
rec = tf.constant([[7, 5, 10, 6, 3, 1, 8, 12, 31, 88]], tf.int64)
precision, update_op = tf.metrics.precision_at_k(rel, rec, 10)
sess = tf.Session()
sess.run(tf.local_variables_initializer())
stream_vars = [i for i in tf.local_variables()]
#Get the local variables true_positive and false_positive
print("[PRECSION_1]: ",sess.run(precision, {rel:[[1,5,10]]})) # nan
#tf.metrics.precision maintains two variables true_positives
#and false_positives, each starts at zero.
#so the output at this step is 'nan'
print("[UPDATE_OP_1]:",sess.run(update_op, {rel:[[1,5,10]]})) #0.2
#when the update_op is called, it updates true_positives
#and false_positives using labels and predictions.
print("[STREAM_VARS_1]:",sess.run(stream_vars)) #[2.0, 8.0]
# Get true positive rate and false positive rate
print("[PRECISION_1]:",sess.run(precision,{rel:[[1,10,15]]})) # 0.2
#So calling precision will use true_positives and false_positives and outputs 0.2
print("[UPDATE_OP_2]:",sess.run(update_op,{rel:[[1,10,15]]})) #0.15
#the update_op updates the values to the new calculated value 0.15.
print("[STREAM_VARS_2]:",sess.run(stream_vars)) #[3.0, 17.0]
[STREAM_VARS_1]: [0.0, 0.0, 0.0, 0.0, 2.0, 8.0]
[PRECISION_1]: 0.2
[UPDATE_OP_2]: 0.15
[STREAM_VARS_2]: [0.0, 0.0, 0.0, 0.0, 3.0, 17.0]
tf.metrics.precision_at_k
上面的代碼中,我們看到運(yùn)用的是tf.metrics.precision_at_k()
這個(gè)API入桂,這里的k
是什么呢奄薇?
首先,我們要理解一個(gè)概念抗愁,究竟什么是Precision at k
馁蒂,這里有兩份資料,應(yīng)該能很好地幫助你理解這個(gè)概念蜘腌。
瀾子就是看了這兩份資料之后沫屡,理解了Precision at k
的概念的。
然后我們來看看這個(gè)函數(shù)是怎么用的逢捺,第一步當(dāng)然要先看看輸入啦谁鳍。
tf.metrics.precision_at_k(
labels,
predictions,
k,
class_id=None,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
我們重點(diǎn)關(guān)注labels,predictions,k這三個(gè)參數(shù),應(yīng)該可以滿足日常簡(jiǎn)單地使用了劫瞳。
那labels,predictions,k的輸入形式是什么樣的呢倘潜?
閑話不說,直接看看上面的栗子志于。栗子中rel
其實(shí)對(duì)應(yīng)為labels
涮因,rec
對(duì)應(yīng)為predictions
,那k
又是什么意思呢伺绽?
劃重點(diǎn):這里的k
表明你需要對(duì)多少個(gè)預(yù)測(cè)樣本進(jìn)行排序养泡。這樣說可能有一點(diǎn)抽象嗜湃,給一個(gè)解釋。
Precision@k = (Recommended items @k that are relevant) / (# Recommended items @k)
可以先去看一下Github澜掩,發(fā)現(xiàn)其實(shí)在tf.metrics.precision_at_k
這個(gè)函數(shù)中购披,對(duì)于predictions
會(huì)根據(jù)輸入的k值
進(jìn)行top_k
操作。
對(duì)應(yīng)上面的代碼中肩榕,當(dāng)k=10
刚陡,即對(duì)rec = tf.constant([[7, 5, 10, 6, 3, 1, 8, 12, 31, 88]], tf.int64)
所有的樣本進(jìn)行排序,進(jìn)而在函數(shù)中實(shí)際運(yùn)用的是rec
中樣本數(shù)值從大到小排列的索引值株汉。這樣解釋應(yīng)該就能看懂上面代碼的意思了筐乳。
后來,瀾子又在
看到有人問怎么用tf.metrics.sparse_average_precision_at_k
乔妈,就又去求是了一波蝙云,
還完成了知乎的技術(shù)首答以及stackoverflow上第一個(gè)贊,
歡迎互粉知乎和stackoverflow哇路召。下面給出栗子和簡(jiǎn)單解釋啦勃刨。
import tensorflow as tf
import numpy as np
y_true = np.array([[2], [1], [0], [3], [0]]).astype(np.int64)
y_true = tf.identity(y_true)
y_pred = np.array([[0.1, 0.2, 0.6, 0.1],
[0.8, 0.05, 0.1, 0.05],
[0.3, 0.4, 0.1, 0.2],
[0.6, 0.25, 0.1, 0.05],
[0.1, 0.2, 0.6, 0.1]
]).astype(np.float32)
y_pred = tf.identity(y_pred)
_, m_ap = tf.metrics.sparse_average_precision_at_k(y_true, y_pred, 3)
sess = tf.Session()
sess.run(tf.local_variables_initializer())
stream_vars = [i for i in tf.local_variables()]
tf_map = sess.run(m_ap)
print("TF_MAP",tf_map)
print("STREAM_VARS",(sess.run(stream_vars)))
tmp_rank = tf.nn.top_k(y_pred,3)
print("TMP_RANK",sess.run(tmp_rank))
簡(jiǎn)單解釋一下
首先
y_true
代表標(biāo)簽值(未經(jīng)過one-hot),shape:(batch_size, num_labels)
,y_pred
代表預(yù)測(cè)值(logit值) 优训,shape:(batch_size, num_classes)
其次朵你,要注意的是
tf.metrics.sparse_average_precision_at_k
中會(huì)采用top_k
根據(jù)不同的k值
對(duì)y_pred
進(jìn)行排序操作 ,所以tmp_rank
是為了幫助大噶理解究竟y_pred在函數(shù)中進(jìn)行了怎樣的轉(zhuǎn)換揣非。然后,
stream_vars = [i for i in tf.local_variables()]
這一行是為了幫助大噶理解tf.metrics.sparse_average_precision_at_k
創(chuàng)建的tf.local_varibles
實(shí)際輸出值躲因,進(jìn)而可以更好地理解這個(gè)函數(shù)的用法早敬。具體看這個(gè)例子,當(dāng)
k=1
時(shí)大脉,只有第一個(gè)batch的預(yù)測(cè)輸出是和標(biāo)簽匹配的 搞监,所以最終輸出為:1/6 = 0.166666
;當(dāng)k=2
時(shí)镰矿,除了第一個(gè)batch的預(yù)測(cè)輸出琐驴,第三個(gè)batch的預(yù)測(cè)輸出也是和標(biāo)簽匹配的,所以最終輸出為:(1+(1/2))/6 = 0.25秤标。
P.S:在以后的tf版本里绝淡,將tf.metrics.average_precision_at_k
替代tf.metrics.sparse_average_precision_at_k
。
簡(jiǎn)直超累的苍姜,目測(cè)是最近的最后一篇博客啦牢酵,有什么錯(cuò)誤一定告訴我啦。