2017-01-12 14 views
9

मैं टेंसरबोर्ड में भ्रम मैट्रिक्स का दृश्य देखना चाहता हूं। ऐसा करने के लिए, मैं टेन्सफोर्लो स्लिम का मूल्यांकन उदाहरण संशोधित कर रहा हूं: https://github.com/tensorflow/models/blob/master/slim/eval_image_classifier.pyटेन्सफोर्लो में टेंसफोर्लो भ्रम मैट्रिक्स

इस उदाहरण कोड में, सटीकता पहले ही प्रदान की गई है, लेकिन स्ट्रीमिंग नहीं होने पर सीधे "भ्रम मैट्रिक्स" मीट्रिक जोड़ना संभव नहीं है।

स्ट्रीमिंग मेट्रिक्स और गैर स्ट्रीमिंग वाले लोगों के बीच क्या अंतर है?

इसलिए, मैं इस तरह यह जोड़ने की कोशिश की:

c_matrix = slim.metrics.confusion_matrix(predictions, labels) 

#These operations needed for image summary 
c_matrix = tf.cast(c_matrix, uint8) 
c_matrix = tf.expand_dims(c_matrix, 2) 
c_matrix = tf.expand_dims(c_matrix, 0) 

op = tf.image_summary("confusion matrix", c_matrix, collections=[]) 
tf.add_to_collection(tf.GraphKeys.SUMMARIES, op) 

यह tensorboard में एक छवि बनाता है, लेकिन शायद वहाँ एक स्वरूपण समस्या है। मैट्रिक्स को 0-1 के बीच सामान्यीकृत किया जाना चाहिए ताकि यह सार्थक छवि उत्पन्न कर सके।

मैं एक सार्थक भ्रम मैट्रिक्स कैसे बना सकता हूं? मैं बहु बैच मूल्यांकन प्रक्रिया से कैसे निपट सकता हूं?

उत्तर

0

पुन: आपकी छवि सार्थक नहीं है - tf.summary.image के दस्तावेज़ों के अनुसार, uint8 मान अपरिवर्तित (सामान्यीकृत नहीं किया जाएगा) के लिए, और श्रेणी [0, 255] में व्याख्या की जाती है। क्या आपने अपनी छवि को [0,25] के बजाय [0,255] पर फिर से सामान्य करने की कोशिश की है?

+0

हां। यह बेहतर दिखता है।हालांकि, मैं अभी भी कई बैचों से परिणाम एकत्र करने में सक्षम नहीं हूं और इसे एक भ्रम मैट्रिक्स में डाल सकता हूं .. – user2616232

13

यहां बताया गया है कि मैंने टेस्ट कोड के लिए "स्ट्रीमिंग" भ्रम मैट्रिक्स का उत्पादन और प्रदर्शन कैसे किया है (प्रत्येक बैच के परीक्षण के लिए test_op का मूल्यांकन किया गया है)।

def _get_streaming_metrics(prediction,label,num_classes): 

    with tf.name_scope("test"): 
     # the streaming accuracy (lookup and update tensors) 
     accuracy,accuracy_update = tf.metrics.accuracy(label, prediction, 
               name='accuracy') 
     # Compute a per-batch confusion 
     batch_confusion = tf.confusion_matrix(label, prediction, 
              num_classes=num_classes, 
              name='batch_confusion') 
     # Create an accumulator variable to hold the counts 
     confusion = tf.Variable(tf.zeros([num_classes,num_classes], 
              dtype=tf.int32), 
           name='confusion') 
     # Create the update op for doing a "+=" accumulation on the batch 
     confusion_update = confusion.assign(confusion + batch_confusion) 
     # Cast counts to float so tf.summary.image renormalizes to [0,255] 
     confusion_image = tf.reshape(tf.cast(confusion, tf.float32), 
            [1, num_classes, num_classes, 1]) 
     # Combine streaming accuracy and confusion matrix updates in one op 
     test_op = tf.group(accuracy_update, confusion_update) 

     tf.summary.image('confusion',confusion_image) 
     tf.summary.scalar('accuracy',accuracy) 

    return test_op,accuracy,confusion 

आप test_op चलाकर सभी डेटा बैचों की प्रक्रिया के बाद, आप बस अंतिम भ्रम मैट्रिक्स (अपने सत्र के भीतर) confusion.eval() या sess.eval(confusion) से यदि आप पसंद करते देख सकते हैं।

+1

यह बहुत अच्छा लगता है! इसे एएसएआईसी +1 –

+0

आज़माएगा जब मैं इसे आज़माता हूं, तो मुझे प्राप्त सारांश छवि चर (जेरोस) के प्रारंभिकरण के अनुरूप होती है। अगर मैं 'confusion_update' का उपयोग करता हूं तो ऐसा लगता है कि यह काम कर रहा है। कोई विचार क्यों? – Tristan

5

यहां कुछ ऐसा है जो tf.contrib.metrics.MetricSpec (जब आप अनुमानक का उपयोग करते हैं) के साथ काम करता है। यह जेरोद के उत्तर और metric_op.py स्रोत फ़ाइल से प्रेरित है।

from tensorflow.python.framework import ops,dtypes 
from tensorflow.python.ops import array_ops,variables 

def _createLocalVariable(name, shape, collections=None, 
validate_shape=True, 
       dtype=dtypes.float32): 
    """Creates a new local variable. 
    """ 
    # Make sure local variables are added to 
    # tf.GraphKeys.LOCAL_VARIABLES 
    collections = list(collections or []) 
    collections += [ops.GraphKeys.LOCAL_VARIABLES] 
    return variables.Variable(
    initial_value=array_ops.zeros(shape, dtype=dtype), 
    name=name, 
    trainable=False, 
    collections=collections, 
    validate_shape=validate_shape) 

def streamingConfusionMatrix(label, prediction, 
weights=None,num_classes=None): 
    """ 
    Compute a streaming confusion matrix 
    :param label: True labels 
    :param prediction: Predicted labels 
    :param weights: (Optional) weights (unused) 
    :param num_classes: Number of labels for the confusion matrix 
    :return: (percentConfusionMatrix,updateOp) 
    """ 
    # Compute a per-batch confusion 

    batch_confusion = tf.confusion_matrix(label, prediction, 
            num_classes=num_classes, 
            name='batch_confusion') 

    count = _createLocalVariable(None,(),dtype=tf.int32) 
    confusion = _createLocalVariable('streamConfusion',[num_classes, 
    num_classes],dtype=tf.int32) 

    # Create the update op for doing a "+=" accumulation on the batch 
    countUpdate = count.assign(count + tf.reduce_sum(batch_confusion)) 
    confusionUpdate = confusion.assign(confusion + batch_confusion) 

    updateOp = tf.group(confusionUpdate,countUpdate) 

    percentConfusion = 100 * tf.truediv(confusion,count) 

    return percentConfusion,updateOp 

फिर आप निम्नलिखित तरीके से मूल्यांकन मीट्रिक के रूप में उपयोग कर सकते हैं:: आप प्रतिशत के साथ एक स्ट्रीम भ्रम मैट्रिक्स मिल

from tensorflow.contrib import learn,metrics 
#[...] 

evalMetrics = {'accuracy': 
learn.MetricSpec(metric_fn=metrics.streaming_accuracy), 
       'confusionMatrix':learn.MetricSpec(metric_fn= 
                lambda 
label,prediction,weights=None:       
streamingConfusionMatrix(             
label,prediction,weights,num_classes=nLabels))} 

मैं तुम्हें numpy.set_printoptions (का उपयोग करने का सुझाव परिशुद्धता = 2, को दबाने = सच है) इसे प्रिंट करने के लिए।

8

यहां कुछ ऐसा है जो मैंने एक साथ रखा है जो उचित रूप से अच्छी तरह से काम करता है। फिर भी टिक प्लेसमेंट आदि

Confusion Matrix as Image in Tensorflow

की तरह कुछ बातें समायोजित करने की आवश्यकता यहाँ समारोह है कि काफी आप के लिए सब कुछ करना होगा।

from textwrap import wrap 
import re 
import itertools 
import tfplot 
import matplotlib 
import numpy as np 
from sklearn.metrics import confusion_matrix 



def plot_confusion_matrix(correct_labels, predict_labels, labels, title='Confusion matrix', tensor_name = 'MyFigure/image', normalize=False): 
''' 
Parameters: 
    correct_labels     : These are your true classification categories. 
    predict_labels     : These are you predicted classification categories 
    labels       : This is a lit of labels which will be used to display the axix labels 
    title='Confusion matrix'  : Title for your matrix 
    tensor_name = 'MyFigure/image' : Name for the output summay tensor 

Returns: 
    summary: TensorFlow summary 

Other itema to note: 
    - Depending on the number of category and the data , you may have to modify the figzie, font sizes etc. 
    - Currently, some of the ticks dont line up due to rotations. 
''' 
cm = confusion_matrix(correct_labels, predict_labels, labels=labels) 
if normalize: 
    cm = cm.astype('float')*10/cm.sum(axis=1)[:, np.newaxis] 
    cm = np.nan_to_num(cm, copy=True) 
    cm = cm.astype('int') 

np.set_printoptions(precision=2) 
###fig, ax = matplotlib.figure.Figure() 

fig = matplotlib.figure.Figure(figsize=(7, 7), dpi=320, facecolor='w', edgecolor='k') 
ax = fig.add_subplot(1, 1, 1) 
im = ax.imshow(cm, cmap='Oranges') 

classes = [re.sub(r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\1 ', x) for x in labels] 
classes = ['\n'.join(wrap(l, 40)) for l in classes] 

tick_marks = np.arange(len(classes)) 

ax.set_xlabel('Predicted', fontsize=7) 
ax.set_xticks(tick_marks) 
c = ax.set_xticklabels(classes, fontsize=4, rotation=-90, ha='center') 
ax.xaxis.set_label_position('bottom') 
ax.xaxis.tick_bottom() 

ax.set_ylabel('True Label', fontsize=7) 
ax.set_yticks(tick_marks) 
ax.set_yticklabels(classes, fontsize=4, va ='center') 
ax.yaxis.set_label_position('left') 
ax.yaxis.tick_left() 

for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): 
    ax.text(j, i, format(cm[i, j], 'd') if cm[i,j]!=0 else '.', horizontalalignment="center", fontsize=6, verticalalignment='center', color= "black") 
fig.set_tight_layout(True) 
summary = tfplot.figure.to_summary(fig, tag=tensor_name) 
return summary 
#

और यहाँ कोड है कि आप इस कार्यों को कॉल करना होगा के बाकी है।

''' confusion matrix summaries ''' 
img_d_summary_dir = os.path.join(checkpoint_dir, "summaries", "img") 
img_d_summary_writer = tf.summary.FileWriter(img_d_summary_dir, sess.graph) 
img_d_summary = plot_confusion_matrix(correct_labels, predict_labels, labels, tensor_name='dev/cm') 
img_d_summary_writer.add_summary(img_d_summary, current_step) 

उलझन में !!!

संबंधित मुद्दे