ckportfolio.com - Image Classification: Python

Image Classification: Python

Importing Fashion MNIST with Colab

# IMPORT NECESSARY LIBRARIES
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

# LOAD FASHION DATASET, ESP TRAINING AND TEST DATA
fashion_dataset = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_dataset.load_data()

# ESTABLISH TEXT LABELS
class_names = ['T-shirt', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

# NORMALIZE IMAGE DATA (0 TO 1)
train_images = train_images / 255
test_images = test_images / 255

# DISPLAY SAMPLE DATASET
plt.figure(figsize=(10,5))
for i in range(15):
  plt.subplot(3,5,i+1)
  plt.xticks([])
  plt.yticks([])
  plt.imshow(train_images[i])
  plt.xlabel(class_names[train_labels[i]])
plt.show()

Exploring Fashion MNIST dataset

# ESTABLISH NEW MODEL
# 1. FLATTEN IMAGE INTO NUMBER SEQUENCE
# 2. SET GRANULARITY OF ANALYSIS
# 3. ESTABLISH 10 SEPARATE OUTCOMES

model = tf.keras.Sequential([
      tf.keras.layers.Flatten(input_shape=(28, 28)),
      tf.keras.layers.Dense(128, activation='relu'),
      tf.keras.layers.Dense(10)
])

# COMPILE MODEL WITH OPTIMIZER WHILE MINIMIZING ERROR

model.compile(
    optimizer='adam',
    metrics=['accuracy'],
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
)

# FEED DATA INTO MODEL

model.fit(train_images, train_labels, epochs=10)

Creating and training a new model with Keras

# EVALUATE MODEL AGAINST TEST DATA

test_loss, test_accuracy = model.evaluate(test_images, test_labels)

print(test_loss)
print(test_accuracy)

Verifying model performance with test images

# ESTABLISH PROBABILITY MODEL BASED ON TRAINED MODEL

prob_model = tf.keras.Sequential([
  model,
  tf.keras.layers.Softmax()                         
])

# CREATE PREDICTION FOR ALL TEST IMAGES

predictions = prob_model.predict(test_images)

# DISPLAY SAMPLE TEST PREDICTIONS

plt.figure(figsize=(10,20))

for i in range(25):
    plt.subplot(5, 5, i+1)
    plt.imshow(test_images[i])

    prediction_label = np.argmax(predictions[i])
    np.max(predictions[i])

    percentage = np.max(predictions[i])
    percentage = percentage*100
    percentage = np.round(percentage)
    percentage = np.str(percentage)

    plt.xlabel(class_names[prediction_label] + ' (' + percentage + '%)')

plt.show()
### Applying completed model to new images```

```python
# ALLOW ONE TO PROVIDE CUSTOM IMAGE URL

image_url = "" #@param {type:"string"}

import random, string

chars = ''.join(random.sample(string.ascii_letters, 15))

image_path = tf.keras.utils.get_file(chars, origin=image_url)

image_obj = tf.keras.utils.load_img(
    image_path, target_size=(28, 28), color_mode=("grayscale")
)

# ANALYZE IMAGE AND CONVERT TO NUMERICAL DATA

image_analysis = np.asarray(image_obj)
image_analysis = image_analysis / 255

plt.figure()
plt.imshow(image_obj)

# INVERT IMAGE INFORMATION AS NEEDED

if (image_analysis[0][0] > 0.8):
    image_obj = np.invert(image_obj)

# PACKAGE IMAGE OBJECT INTO ARRAY AND PUSH TO PROBABILITY MODEL

image_analysis = np.asarray(image_obj)
image_analysis = image_analysis / 255
image_array = np.expand_dims(image_analysis, 0)
result = prob_model.predict(image_array)

# DISPLAY PREDICTION RESULT

plt.figure()
plt.imshow(image_obj)

prediction_label = np.argmax(result)

percentage = np.max(result)
percentage = percentage*100
percentage = np.round(percentage)
percentage = np.str(percentage)

plt.xlabel(class_names[prediction_label] + ' (' + percentage + '%)')
plt.show()
Fin