# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/asange/mit-deep-learning/blob/master/tf_basic_class_example.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + id="HyVCYktQidB4" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="9e0b6e61-0153-4a85-9a1f-7960eb3bb942"
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt

print(tf.__version__)

# + id="K8HMaTY8i38d" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 153} outputId="451becba-9b50-41fb-f3b6-d5ed150b904f"
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

# + id="Qzmq0NVPjRxO" colab_type="code" colab={}
class_names =  ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

# + id="WE-RXGW_jZrP" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 347} outputId="da8b2003-b06c-428b-a8c8-461b90dacfb0"
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)

# + id="KzXZmRGtkPVm" colab_type="code" colab={}
train_images = train_images / 255.0
test_images = test_images /255.0

# + id="S2Ip5Sr4kgtB" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 609} outputId="af3ef02b-5ea5-4b3c-b94c-0f6a5f795ff0"
plt.figure(figsize = (10, 10))
for i in range(25):
  plt.subplot(5, 5, i+1)
  plt.xticks([])
  plt.yticks([])
  plt.grid(False)
  plt.imshow(train_images[i], cmap = plt.cm.binary)
  plt.xlabel(class_names[train_labels[i]])
  

# + id="ZLuGjbIAlXt5" colab_type="code" colab={}
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28,28)),
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(10, activation=tf.nn.softmax)
])

# + id="sQj4ymt2mSOe" colab_type="code" colab={}
model.compile(optimizer=tf.train.AdamOptimizer(),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# + id="9J4tq4L-nPNH" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 224} outputId="7510adde-c5bb-4df9-c383-7ed9ecf8e3b4"
model.fit(train_images, train_labels, epochs = 5)

# + id="xaVOYtEznfsn" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 54} outputId="e7444e16-e603-4323-d79d-914adf777278"
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)

# + id="vmyljkdBoARO" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 72} outputId="4d93e8c2-a012-4986-ffec-66c14ef66491"
predictions = model.predict(test_images)
predictions[0]

# + id="v2cygy9PoYbq" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="061eeefb-d63a-4e6e-e0d6-2f1c2b066989"
np.argmax(predictions[1123]), test_labels[1123]


# + id="kf6fnCtso0dv" colab_type="code" colab={}
def plot_image(i, predictions_array, true_label, img):
  predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]
  plt.grid(False)
  plt.xticks([])
  plt.yticks([])
  
  plt.imshow(img, cmap=plt.cm.binary)
  
  predicted_label = np.argmax(predictions_array)
  if predicted_label == true_label:
    color = 'blue'
  else:
    color = 'red'
  
  plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label], 
                                      100*np.max(predictions_array),
                                      class_names[true_label]),
                                      color = color)

def plot_value_array(i, predictions_array, true_label):
  predictions_array, true_label = predictions_array[i], true_label[i]
  plt.grid(False)
  plt.xticks([])
  plt.yticks([])
  
  thisplot = plt.bar(range(10), predictions_array, color = '#777777')
  plt.ylim([0,1])
  predicted_label = np.argmax(predictions_array)
  
  thisplot[predicted_label].set_color('red')
  thisplot[true_label].set_color('blue')
  
  

# + id="rqTeCo75rjny" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 204} outputId="95bcbed0-b5d1-4227-8799-583667749f84"
i = 1123
plt.figure(figsize=(6, 3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1, 2,2)
plot_value_array(i, predictions, test_labels)

# + id="jOr7kqqutkOu" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 609} outputId="1a83bf60-f747-4845-b2ff-6db3b93a0d89"
num_rows = 5
num_cols = 3
num_images = num_rows * num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
  plt.subplot(num_rows, 2*num_cols, 2*i+1)
  plot_image(i, predictions, test_labels, test_images)
  plt.subplot(num_rows, 2*num_cols, 2*i+2)
  plot_value_array(i, predictions, test_labels)

# + id="HmqfEJcwur3u" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="73639ab5-e239-4358-b1a5-7cc1e2373b63"
img = test_images[0]
print(img.shape)

# + id="Y9L4feYXu4S1" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="72cb79d9-546f-4e47-fe4e-1940e95e386c"
img = (np.expand_dims(img, 0))
print(img.shape)

# + id="bjnCVYVOvDZH" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 54} outputId="99b5d12e-a928-441a-e97d-aedaf23e0f70"
predictions_single = model.predict(img)
print(predictions_single)

# + id="RVwjl6NNvMv5" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 377} outputId="0f3aeae3-0c30-4e03-c0a6-7865b8abb129"
plot_value_array(0, predictions_single, test_labels) 
_ = plt.xticks(range(10), class_names, rotation=45)

# + id="1UESRgTtvwg4" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="0ce99794-984f-430a-bf91-e2eb4aa22b36"
np.argmax(predictions_single[0])

StarcoderdataJupyterScriptsDedupFiltered