tensorflow計算各個類別的正確率


import tensorflow as tf

def count_nums(true_labels, num_classes):
    initial_value = 0
    list_length = num_classes
    list_data = [ initial_value for i in range(list_length)]
    for i in range(0, num_classes):
        list_data[i] = true_labels.count(i)
    return list_data

def accuracy(confusion_matrix, true_labels, num_classes):
    # 各個類別的測試樣本的個數
    list_data = count_nums(true_labels, num_classes)

    # 各個類別正確分類的個數
    initial_value = 0
    list_length = num_classes
    true_pred = [ initial_value for i in range(list_length)]
    for i in range(0,5):
        true_pred[i] = confusion_matrix[i][i]

    # 計算各個樣本被正確分類的正確率
    acc = []
    for i in range(0, 5):
        acc.append(0)

    for i in range(0,5):
        acc[i] = true_pred[i] / list_data[i]

    return acc

# 測試數據
y_true = [0, 1, 2, 3, 1, 2, 3, 4, 1] # 真實的標簽
y_pred = [1, 1, 2, 3, 1, 2, 3, 4, 2] # 預測的標簽

# Build graph with tf.confusion_matrix operation
sess = tf.InteractiveSession()
op = tf.confusion_matrix(y_true, y_pred)
# Execute the graph
print ("confusion matrix in tensorflow: ")
confusion_matrix = sess.run(op)
print(confusion_matrix)
sess.close()

# 計算各個類別的正確率
acc = accuracy(confusion_matrix, y_true, num_classes = 5)
print(acc)

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM