title: TensorFlow classifies all images as same class
body: <h3>Problem</h3>
  <p>I've created an Image Classifier CNN in TensorFlow to classify a graph into one of three classes: Linear, Quadratic, or Cubic. I followed the documentation at <a href="https://www.tensorflow.org/tutorials/images/classification" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/images/classification</a>. I've unit-tested all previous sections of the code, and they work perfectly fine. But when it comes to labeling the images of graphs, every graph is classified as <code>This image most likely belongs to Cubic Sinusoidal with a 88.71 percent confidence.</code> The exact same classification and probability for <em>any image</em>.</p>
  <p><a href="https://i.stack.imgur.com/ngjNG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ngjNG.png" alt="Wrong Classification" /></a></p>
  <h3>Attempted Fixes</h3>
  <p>I've compared my code with the documentation, and there doesn't seem to be anything wrong. If anyone can help, that would be great. I even found a similar Q&amp;A <a href="https://stackoverflow.com/questions/58262303/tensorflow-image-classifier-returns-the-same-label-for-each-image">here</a>.</p>
  <h3>Code</h3>
  <p>My code is below. The Colab Notebook is <a href="https://colab.research.google.com/drive/1c25FpjrmoBglMta5rW-CgYkM6UfZiSss?usp=sharing" rel="nofollow noreferrer"><strong>here</strong></a>. I've included all my code because I'm not sure what the issue is:</p>
  <pre><code>pip install tensorflow
  
  pip install numpy
  
  pip install matplotlib
  
  !git clone https://github.com/Refath/SinusoidalAnalyzer.git
  
  # Import Libraries
  import tensorflow as tf
  from tensorflow import keras
  from keras.models import Sequential
  from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout
  from tensorflow.keras import layers
  from tensorflow.keras.utils import to_categorical
  import numpy as np
  import matplotlib.pyplot as plt
  
  plt.style.use('fivethirtyeight')
  
  # Load the Data
  from keras.datasets import cifar10
  (x_train, y_train), (x_test, y_test) = cifar10.load_data()
  
  import pathlib
  dataset_url = &quot;https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz&quot;
  data_dir = tf.keras.utils.get_file(origin = dataset_url,
                                     fname = &quot;flower_photos&quot;,
                                     untar = True)
  data_dir = pathlib.Path(data_dir)
  
  import pathlib
  dataset_url = &quot;https://barisciencelab.tech/Graphs.tar.gz&quot;
  data_dir = tf.keras.utils.get_file(origin = dataset_url,
                                     fname = &quot;FunctionIdentifier&quot;,
                                     untar = True)
  data_dir = pathlib.Path(data_dir)
  
  print(list(data_dir.glob('*/*.png')))
  image_count = len(list(data_dir.glob('*/*.png')))
  print(image_count)
  
  import numpy as np
  import os
  import PIL
  import PIL.Image
  import tensorflow as tf
  import tensorflow_datasets as tfds
  graphs = list(data_dir.glob('*/*.png'))
  print(graphs)
  PIL.Image.open(str(graphs[6]))
  
  batch_size = 32
  img_height = 36
  img_width = 36
  
  train_ds = tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    validation_split=0.2,
    subset=&quot;training&quot;,
    seed=123,
    image_size=(img_height, img_width),
    batch_size=batch_size)
  
  val_ds = tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    validation_split=0.2,
    subset=&quot;validation&quot;,
    seed=123,
    image_size=(img_height, img_width),
    batch_size=batch_size)
  
  class_names = ['Cubic Sinusoidal', 'Linear Sinusoidal', 'Quadratic Sinusoidal']
  print(class_names)
  
  import matplotlib.pyplot as plt
  
  plt.figure(figsize=(10, 10))
  for images, labels in train_ds.take(1):
    for i in range(9):
      ax = plt.subplot(3, 3, i + 1)
      plt.imshow(images[i].numpy().astype(&quot;uint8&quot;))
      plt.title(class_names[labels[i]])
      plt.axis(&quot;off&quot;)
  
  for image_batch, labels_batch in train_ds:
    print(image_batch.shape)
    print(labels_batch.shape)
    break
  
  normalization_layer = tf.keras.layers.experimental.preprocessing.Rescaling(1./255)
  
  normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
  image_batch, labels_batch = next(iter(normalized_ds))
  first_image = image_batch[0]
  # Notice the pixels values are now in `[0,1]`.
  print(np.min(first_image), np.max(first_image))
  
  AUTOTUNE = tf.data.AUTOTUNE
  
  train_ds = train_ds.cache().prefetch(buffer_size=AUTOTUNE)
  val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
  
  num_classes = 3
  
  model = tf.keras.Sequential([
    tf.keras.layers.experimental.preprocessing.Rescaling(1./255),
    tf.keras.layers.Conv2D(32, 3, activation='relu'),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Conv2D(32, 3, activation='relu'),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Conv2D(32, 3, activation='relu'),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(num_classes)
  ])
  
  model.compile(
    optimizer='adam',
    loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=['accuracy'])
  
  model.summary()
  
  epochs = 3
  history = model.fit(
    train_ds,
    validation_data=val_ds,
    epochs=3
  )
  
  acc = history.history['accuracy']
  val_acc = history.history['val_accuracy']
  
  loss = history.history['loss']
  val_loss = history.history['val_loss']
  
  epochs_range = range(epochs)
  
  plt.figure(figsize=(8, 8))
  plt.subplot(1, 2, 1)
  plt.plot(epochs_range, acc, label='Training Accuracy')
  plt.plot(epochs_range, val_acc, label='Validation Accuracy')
  plt.legend(loc='lower right')
  plt.title('Training and Validation Accuracy')
  
  plt.subplot(1, 2, 2)
  plt.plot(epochs_range, loss, label='Training Loss')
  plt.plot(epochs_range, val_loss, label='Validation Loss')
  plt.legend(loc='upper right')
  plt.title('Training and Validation Loss')
  plt.show()
  
  &quot;&quot;&quot;# 1-Sample *Cubic* Test (Passed; Accuracy: 99.91%)&quot;&quot;&quot;
  
  cubic_url = &quot;https://raw.githubusercontent.com/Refath/SinusoidalAnalyzer/main/CubicSinusoidal_1.png&quot;
  cubic_path = tf.keras.utils.get_file('CubicSinusoidal_1', origin=cubic_url)
  
  img = keras.preprocessing.image.load_img(
      cubic_path, target_size=(img_height, img_width)
  )
  img_array = keras.preprocessing.image.img_to_array(img)
  img_array = tf.expand_dims(img_array, 0) # Create a batch
  
  predictions = model.predict(img_array)
  score = tf.nn.softmax(predictions[0])
  
  print(
      &quot;This image most likely belongs to {} with a {:.2f} percent confidence.&quot;
      .format(class_names[np.argmax(score)], 100 * np.max(score))
  )
  
  &quot;&quot;&quot;# 1-Sample *Quadratic* Test (Failed :( )&quot;&quot;&quot;
  
  quad_url = &quot;https://raw.githubusercontent.com/Refath/SinusoidalAnalyzer/main/QuadSinusoidal_1.png&quot;
  quad_path = tf.keras.utils.get_file('QuadSinusoidal_1', origin=quad_url)
  
  img = keras.preprocessing.image.load_img(
      quad_path, target_size=(img_height, img_width)
  )
  img_array = keras.preprocessing.image.img_to_array(img)
  img_array = tf.expand_dims(img_array, 0) # Create a batch
  
  predictions = model.predict(img_array)
  score = tf.nn.softmax(predictions[0])
  
  print(
      &quot;This image most likely belongs to {} with a {:.2f} percent confidence.&quot;
      .format(class_names[np.argmax(score)], 100 * np.max(score))
  )
  
  lin_url = &quot;https://raw.githubusercontent.com/Refath/SinusoidalAnalyzer/main/LinSinusoidal_1.png&quot;
  lin_path = tf.keras.utils.get_file('QuadSinusoidal_1', origin=lin_url)
  
  img = keras.preprocessing.image.load_img(
      lin_path, target_size=(img_height, img_width)
  )
  img_array = keras.preprocessing.image.img_to_array(img)
  img_array = tf.expand_dims(img_array, 0) # Create a batch
  
  predictions = model.predict(img_array)
  score = tf.nn.softmax(predictions[0])
  
  print(
      &quot;This image most likely belongs to {} with a {:.2f} percent confidence.&quot;
      .format(class_names[np.argmax(score)], 100 * np.max(score))
  )
  </code></pre>