title: Find confusion matrix of image classification in Tensorflow
body: <p>I am training a model to classify images into 2 classes following this tutorial: <a href="https://www.tensorflow.org/tutorials/images/classification" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/images/classification</a></p>
  <p>After <code>model.fit()</code>, I want to evaluate the accuracy of the model's prediction using a test set which contains images that weren't included in the training or validation sets. The test set contains 2 folders which contain the images of the corresponding class.</p>
  <pre><code>├── test_data/
  │   ├── class1/
  │   ├── class2/
  </code></pre>
  <p>And I want to find the recall, precision and accuracy of each class using confusion matrix.
  However, I am new to deep learning and Tensorflow. I have no idea how to get the confusion matrix for each class. I am also not sure whether the way I pass images to the model is correct.</p>
  <p>The following is my current implementation on using the model to predict on new data.</p>
  <pre class="lang-py prettyprint-override"><code># get the list of class names in the training set
  train_class_names = train_ds.class_names
  
  # load the test data
  test_data_dir = pathlib.Path('test_data/')
  test_data_list = list(test_data_dir.glob('*/*.jpg'))
  
  test_ds = tf.keras.utils.image_dataset_from_directory(
    test_data_dir,
    image_size=(img_height, img_width),
    batch_size=batch_size)
  
  predicted_img = []
  
  # for every image in the test_data folder, pass it to the model to predict its class
  for path in test_data_list:
      img = tf.keras.utils.load_img(
          path, target_size=(img_height, img_width)
      )
      img_array = tf.keras.utils.img_to_array(img)
      img_array = tf.expand_dims(img_array, 0)
      
      test_class_name = path.parent.name
  
      predictions = model.predict(img_array)
      score = tf.nn.softmax(predictions[0])
      
      # append the image, predicted class and actual class to a list 
      # so that I can print them out to see if the prediction is correct
      predicted_img.append([img, train_class_names[np.argmax(score)], test_class_name])
  </code></pre>