[0.3] 續(xù)--Tensorflow踩坑記之tf.metrics

【續(xù)】--Tensorflow踩坑記之tf.metrics

欠下的帳總歸還是要還的,之前一直拖著,總是懶得寫tf.metrics這個(gè)API的一些用法,今天總算是克服了懶癌,總結(jié)一下tf.metrics遇到的一些坑。

插一句閑話,這一次的博客基本上用的都是 Jupyter,感覺一級(jí)好用啊。可以一邊寫代碼,一邊記markdown,忍不住上一張效果圖,再次歡迎大噶去我的Github上看一看,而且Github支持 jupyter notebook 顯示,真得效果很好。

jupyter

在這篇偽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ì)算公式

Precision = \frac{truePositive}{truePositive + falsePositive}

讓我們先造點(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ò)展,我們希望使評估指標(biāo)能夠逐步更新,每批新的預(yù)測和標(biāo)簽。 為此,我們需要跟蹤兩個(gè)值。

  • 正確預(yù)測的正樣本數(shù)量
  • 預(yù)測樣本中所有正樣本的數(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ì)算邏輯以及對應(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è)官方的解釋

The precision function creates two local variables,
true_positives and false_positives, that are used to compute the precision. This value is ultimately returned as precision, an idempotent operation that simply divides true_positives by the sum of true_positives and false_positives.
For estimation of the metric over a stream of data, the function creates an update_op operation that updates these variables and returns the precision.

兩個(gè)變量和 tf.metrics.precision()的關(guān)系

官方文檔提及的two local variablestrue_postivesfalse_positives分別對應(yīng)上文定義的兩個(gè)變量。

  • true_postives -- N_TRUE_P
  • false_postives -- N_PRED_P - N_TRUE_P

三個(gè)函數(shù)和頭大的update_op

官方文檔提及的update_opprecision分別對應(yīng)上文定義的兩個(gè)函數(shù)

  • precision--calculate_precision()
  • update_op--update_running_variables()

大家不要被這個(gè)update_op搞暈,其實(shí)從字面來理解就是一個(gè)變量更新的操作,上文的代碼中,就是通過reset_running_variables()的位置來決定何時(shí)對變量進(jìn)行更新,其實(shí)就是對應(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_metrictf_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)該可以滿足日常簡單地使用了。
labels,predictions,k的輸入形式是什么樣的呢?

閑話不說,直接看看上面的栗子。栗子中rel其實(shí)對應(yīng)為labelsrec對應(yīng)為predictions,那k又是什么意思呢?
劃重點(diǎn):這里的k表明你需要對多少個(gè)預(yù)測樣本進(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ù)中,對于predictions會(huì)根據(jù)輸入的k值進(jìn)行top_k操作。
對應(yīng)上面的代碼中,當(dāng)k=10,即對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哇。下面給出栗子和簡單解釋啦。

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))

簡單解釋一下

  • 首先y_true代表標(biāo)簽值(未經(jīng)過one-hot),shape:(batch_size, num_labels) ,y_pred代表預(yù)測值(logit值) ,shape:(batch_size, num_classes)

  • 其次,要注意的是tf.metrics.sparse_average_precision_at_k中會(huì)采用top_k根據(jù)不同的k值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ù)測輸出是和標(biāo)簽匹配的 ,所以最終輸出為:1/6 = 0.166666 ;當(dāng)k=2時(shí),除了第一個(gè)batch的預(yù)測輸出,第三個(gè)batch的預(yù)測輸出也是和標(biāo)簽匹配的,所以最終輸出為:(1+(1/2))/6 = 0.25。

P.S:在以后的tf版本里,將tf.metrics.average_precision_at_k替代tf.metrics.sparse_average_precision_at_k

簡直超累的,目測是最近的最后一篇博客啦,有什么錯(cuò)誤一定告訴我啦。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容