text_plain_output_1.png
from ipywidgets import interact, widgets

from tensorflow import keras

import math

import matplotlib.pyplot as plt

import numpy as np

fashion_mnist = keras.datasets.fashion_mnist
(in_train, out_train), (in_valid, out_valid) = fashion_mnist.load_data()

(in_train.shape, in_valid.shape, np.unique(out_train))

in_train = in_train / 255.0
in_valid = in_valid / 255.0

class_names = {index: cn for index, cn in enumerate(['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'])}

# row_number = int(input('How many rows of training images would you like to review?'))
row_number = 5
def plot_train(n_rows = 2, predictions=None):
    '''create a grid with 10 columns
    '''
    n_cols = 10
    # n_rows = math.ceil(len(images) / n_cols)
    images = in_train[: n_cols * n_rows]
    labels = out_train[: n_cols * n_rows]
    fig, axes = plt.subplots(n_rows, n_cols, figsize=(n_cols + 3, n_rows + 2))
    if predictions is None:
        predictions = [None] * len(labels)
    for index, (x, y_true, y_pred) in enumerate(zip(images, labels, predictions)):
        ax = axes.flat[index]
        ax.imshow(x, cmap=plt.cm.binary)
        ax.set_title(class_names[y_true])
        if y_pred is not None:
            ax.set_xlabel(class_names[y_pred])
        ax.set_xticks([])
        ax.set_yticks([])

# plot first 20 images
plot_train(row_number)

#input('How many rows of training images would you like to review?')
def plot(images, labels, predictions=None):
    '''create a grid with 10 columns
    '''
    n_cols = min(10, len(images))
    n_rows = math.ceil(len(images) / n_cols)
    fig, axes = plt.subplots(n_rows, n_cols, figsize=(n_cols + 3, n_rows + 2))
    if predictions is None:
        predictions = [None] * len(labels)
    for index, (x, y_true, y_pred) in enumerate(zip(images, labels, predictions)):
        ax = axes.flat[index]
        ax.imshow(x, cmap=plt.cm.binary)
        ax.set_title(class_names[y_true])
        if y_pred is not None:
            ax.set_xlabel(class_names[y_pred])
        ax.set_xticks([])
        ax.set_yticks([])

# plot first 20 images
#plot(in_train[:20], out_train[:20])   

def plot(images, labels, predictions=None):
    # create a grid with 10 columns
    n_cols = min(10, len(images))
    n_rows = math.ceil(len(images) / n_cols)
    fig, axes = plt.subplots(n_rows, n_cols, figsize=(n_cols + 3, n_rows + 2))
    if predictions is None:
        predictions = [None] * len(labels)
    for index, (x, y_true, y_pred) in enumerate(zip(images, labels, predictions)):
        ax = axes.flat[index]
        ax.imshow(x, cmap=plt.cm.binary)
        ax.set_title(class_names[y_true])
        if y_pred is not None:
            ax.set_xlabel(class_names[y_pred])
        ax.set_xticks([])
        ax.set_yticks([])

# plot first 20 images
#plot(in_train[:20], out_train[:20])   

model = keras.Sequential(layers=[keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation='relu'), keras.layers.Dense(10, activation='softmax')])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(in_train, out_train, batch_size=60, epochs=10, validation_split=0.2)

loss, accuracy = model.evaluate(in_valid, out_valid)

probs = model.predict(in_valid)
preds = model.predict(in_valid).argsort()[:, -1]

from ipywidgets import interact, widgets
img_idx_slider = widgets.IntSlider(value=0, min=0, max=len(in_valid) - 1, description='Image index')
@interact(index=img_idx_slider)
def visualize_prediction(index=0):
    fix, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))
    ax1.imshow(in_valid[index], cmap=plt.cm.binary)
    ax1.set_title('label: %s' % class_names[out_valid[index]])
    ax1.set_xlabel('predict: %s' % class_names[preds[index]])
    ax2.bar(x=[class_names[index] for index in range(10)], height=probs[index] * 100)
    plt.xticks(rotation=90)