{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceType":"competition","sourceId":3004,"databundleVersionId":861823},{"sourceType":"competition","sourceId":16017,"databundleVersionId":708189},{"sourceType":"datasetVersion","sourceId":9243,"datasetId":2243,"databundleVersionId":9243},{"sourceType":"datasetVersion","sourceId":34877,"datasetId":27352,"databundleVersionId":35935}],"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# STEP #1: PROBLEM STATEMENT AND BUSINESS CASE","metadata":{}},{"cell_type":"markdown","source":"Fashion training set consists of 70,000 images divided into 60,000 training and 10,000 testing samples. Dataset sample consists of 28x28 grayscale image, associated with a label from 10 classes. \n\nThe 10 classes are as follows:  \n0 => T-shirt/top\n1 => Trouser\n2 => Pullover\n3 => Dress\n4 => Coat\n5 => Sandal\n6 => Shirt\n7 => Sneaker\n8 => Bag\n9 => Ankle boot\n\nEach image is 28 pixels in height and 28 pixels in width, for a total of 784 pixels in total. Each pixel has a single pixel-value associated with it, indicating the lightness or darkness of that pixel, with higher numbers meaning darker. This pixel-value is an integer between 0 and 255. ","metadata":{}},{"cell_type":"markdown","source":"# STEP #2: IMPORTING DATA","metadata":{}},{"cell_type":"code","source":"# import libraries \nimport pandas as pd # Import Pandas for data manipulation using dataframes\nimport numpy as np # Import Numpy for data statistical analysis \nimport matplotlib.pyplot as plt # Import matplotlib for data visualisation\nimport seaborn as sns\nimport random\n\n%matplotlib inline\nsns.set_style(\"whitegrid\")","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:26.583163Z","iopub.execute_input":"2026-04-05T23:14:26.583448Z","iopub.status.idle":"2026-04-05T23:14:30.839827Z","shell.execute_reply.started":"2026-04-05T23:14:26.583410Z","shell.execute_reply":"2026-04-05T23:14:30.839064Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# dataframes creation for both training and testing datasets \nfashion_train_df = pd.read_csv('/kaggle/input/fashionmnist/fashion-mnist_train.csv',sep=',')\nfashion_test_df = pd.read_csv('/kaggle/input/fashionmnist/fashion-mnist_test.csv', sep = ',')","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:30.840739Z","iopub.execute_input":"2026-04-05T23:14:30.841192Z","iopub.status.idle":"2026-04-05T23:14:36.145631Z","shell.execute_reply.started":"2026-04-05T23:14:30.841146Z","shell.execute_reply":"2026-04-05T23:14:36.144967Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# STEP #3: VISUALIZATION OF THE DATASET  ","metadata":{}},{"cell_type":"code","source":"# Let's view the head of the training dataset\n# 784 indicates 28x28 pixels and 1 coloumn for the label\n# After you check the tail, 60,000 training dataset are present\nfashion_train_df.head()","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:36.147145Z","iopub.execute_input":"2026-04-05T23:14:36.147409Z","iopub.status.idle":"2026-04-05T23:14:36.180396Z","shell.execute_reply.started":"2026-04-05T23:14:36.147358Z","shell.execute_reply":"2026-04-05T23:14:36.179848Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Let's view the last elements in the training dataset\nfashion_train_df.tail()","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:36.181168Z","iopub.execute_input":"2026-04-05T23:14:36.181472Z","iopub.status.idle":"2026-04-05T23:14:36.192997Z","shell.execute_reply.started":"2026-04-05T23:14:36.181449Z","shell.execute_reply":"2026-04-05T23:14:36.192307Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Let's view the head of the testing dataset\nfashion_test_df.head()","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:36.193979Z","iopub.execute_input":"2026-04-05T23:14:36.194606Z","iopub.status.idle":"2026-04-05T23:14:36.209963Z","shell.execute_reply.started":"2026-04-05T23:14:36.194580Z","shell.execute_reply":"2026-04-05T23:14:36.209358Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Let's view the last elements in the testing dataset\nfashion_test_df.tail()","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:36.210732Z","iopub.execute_input":"2026-04-05T23:14:36.211016Z","iopub.status.idle":"2026-04-05T23:14:36.227816Z","shell.execute_reply.started":"2026-04-05T23:14:36.210993Z","shell.execute_reply":"2026-04-05T23:14:36.227169Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"fashion_train_df.shape","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:36.228691Z","iopub.execute_input":"2026-04-05T23:14:36.228985Z","iopub.status.idle":"2026-04-05T23:14:36.239755Z","shell.execute_reply.started":"2026-04-05T23:14:36.228954Z","shell.execute_reply":"2026-04-05T23:14:36.239143Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Create training and testing arrays\ntrain = np.array(fashion_train_df, dtype='float32')\ntest = np.array(fashion_test_df, dtype='float32')","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:36.240590Z","iopub.execute_input":"2026-04-05T23:14:36.240846Z","iopub.status.idle":"2026-04-05T23:14:36.420675Z","shell.execute_reply.started":"2026-04-05T23:14:36.240825Z","shell.execute_reply":"2026-04-05T23:14:36.420084Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train.shape","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:36.423034Z","iopub.execute_input":"2026-04-05T23:14:36.423505Z","iopub.status.idle":"2026-04-05T23:14:36.427869Z","shell.execute_reply.started":"2026-04-05T23:14:36.423480Z","shell.execute_reply":"2026-04-05T23:14:36.427257Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:36.428727Z","iopub.execute_input":"2026-04-05T23:14:36.428951Z","iopub.status.idle":"2026-04-05T23:14:36.443220Z","shell.execute_reply.started":"2026-04-05T23:14:36.428930Z","shell.execute_reply":"2026-04-05T23:14:36.442630Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:36.444056Z","iopub.execute_input":"2026-04-05T23:14:36.444340Z","iopub.status.idle":"2026-04-05T23:14:36.458589Z","shell.execute_reply.started":"2026-04-05T23:14:36.444311Z","shell.execute_reply":"2026-04-05T23:14:36.457870Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class_names = ['T_shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', \n               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\n\n# Let's view some images!\ni = random.randint(1,60000) # select any random index from 1 to 60,000\nplt.imshow(train[i,1:].reshape((28,28))) # reshape and plot the image\n\nplt.imshow(train[i,1:].reshape((28,28)) , cmap = 'gray') # reshape and plot the image\nlabel_index = fashion_train_df[\"label\"][i]\nplt.title(f\"{class_names[label_index]}\")\n\n\n# Remember the 10 classes decoding is as follows:\n# 0 => T-shirt/top\n# 1 => Trouser\n# 2 => Pullover\n# 3 => Dress\n# 4 => Coat\n# 5 => Sandal\n# 6 => Shirt\n# 7 => Sneaker\n# 8 => Bag\n# 9 => Ankle boot","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:36.459529Z","iopub.execute_input":"2026-04-05T23:14:36.459929Z","iopub.status.idle":"2026-04-05T23:14:36.686181Z","shell.execute_reply.started":"2026-04-05T23:14:36.459890Z","shell.execute_reply":"2026-04-05T23:14:36.685589Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"label = train[i,0]\nlabel","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:36.687036Z","iopub.execute_input":"2026-04-05T23:14:36.687319Z","iopub.status.idle":"2026-04-05T23:14:36.692113Z","shell.execute_reply.started":"2026-04-05T23:14:36.687288Z","shell.execute_reply":"2026-04-05T23:14:36.691521Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Let's view more images in a grid format\n# Define the dimensions of the plot grid \nW_grid = 15\nL_grid = 15\n\n# fig, axes = plt.subplots(L_grid, W_grid)\n# subplot return the figure object and axes object\n# we can use the axes object to plot specific figures at various locations\n\nfig, axes = plt.subplots(L_grid, W_grid, figsize=(17,17))\n\naxes = axes.ravel() # flaten the 15 x 15 matrix into 225 array\n\nn_train = len(train) # get the length of the train dataset\n\n# Select a random number from 0 to n_train\nfor i in np.arange(0, W_grid * L_grid): # create evenly spaces variables \n\n    # Select a random number\n    index = np.random.randint(0, n_train)\n    # read and display an image with the selected index    \n    axes[i].imshow( train[index,1:].reshape((28,28)) )\n    label_index = int(train[index,0])\n    axes[i].set_title(class_names[label_index], fontsize=8)\n    axes[i].axis('off')\n\nplt.subplots_adjust(hspace=0.4)\n\n# Remember the 10 classes decoding is as follows:\n# 0 => T-shirt/top\n# 1 => Trouser\n# 2 => Pullover\n# 3 => Dress\n# 4 => Coat\n# 5 => Sandal\n# 6 => Shirt\n# 7 => Sneaker\n# 8 => Bag\n# 9 => Ankle boot","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:36.693035Z","iopub.execute_input":"2026-04-05T23:14:36.693323Z","iopub.status.idle":"2026-04-05T23:14:43.514814Z","shell.execute_reply.started":"2026-04-05T23:14:36.693289Z","shell.execute_reply":"2026-04-05T23:14:43.514024Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Scale these values to a range of 0 to 1 before feeding them to the neural network model. To do so, divide the values by 255. It's important that the training set and the testing set be preprocessed in the same way:","metadata":{}},{"cell_type":"code","source":"# Prepare the training and testing dataset \nX_train = train[:, 1:] / 255\ny_train = train[:, 0]\n\nX_test = test[:, 1:] / 255\ny_test = test[:,0]","metadata":{"scrolled":true,"execution":{"iopub.status.busy":"2026-04-05T23:14:43.515784Z","iopub.execute_input":"2026-04-05T23:14:43.516025Z","iopub.status.idle":"2026-04-05T23:14:43.581034Z","shell.execute_reply.started":"2026-04-05T23:14:43.516002Z","shell.execute_reply":"2026-04-05T23:14:43.580443Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"To verify that the data is in the correct format and that you're ready to build and train the network, let's display the first 25 images from the training set and display the class name below each image.","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(10, 10))\nfor i in range(25):\n    plt.subplot(5, 5, i + 1)\n    plt.xticks([])\n    plt.yticks([])\n    plt.grid(False)\n    plt.imshow(X_train[i].reshape((28,28)), cmap=plt.cm.binary)\n    label_index = int(y_train[i])\n    plt.title(class_names[label_index])\nplt.show()\nplt.tight_layout()","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:43.581968Z","iopub.execute_input":"2026-04-05T23:14:43.582371Z","iopub.status.idle":"2026-04-05T23:14:44.298173Z","shell.execute_reply.started":"2026-04-05T23:14:43.582335Z","shell.execute_reply":"2026-04-05T23:14:44.297588Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(12, 8))\n\nplt.subplot(2, 2, 1)\nclasses, counts = np.unique(y_train, return_counts=True)\nplt.barh(class_names, counts)\nplt.title('Class distribution in training set')\n\nplt.subplot(2, 2, 2)\nclasses, counts = np.unique(y_test, return_counts=True)\nplt.barh(class_names, counts)\nplt.title('Class distribution in testing set')","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:44.299186Z","iopub.execute_input":"2026-04-05T23:14:44.299472Z","iopub.status.idle":"2026-04-05T23:14:44.560246Z","shell.execute_reply.started":"2026-04-05T23:14:44.299435Z","shell.execute_reply":"2026-04-05T23:14:44.559515Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# STEP #4: TRAINING THE MODEL","metadata":{}},{"cell_type":"markdown","source":"We split our training data into train and validate datasets, in order to train our model and validate it using the validation data set to avoid overfitting before testing the model on the test datasets which is as real-world data for our model.","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nX_train, X_validate, y_train, y_validate = train_test_split(X_train, y_train, test_size=0.2, random_state=42)","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:44.561264Z","iopub.execute_input":"2026-04-05T23:14:44.561586Z","iopub.status.idle":"2026-04-05T23:14:45.370054Z","shell.execute_reply.started":"2026-04-05T23:14:44.561553Z","shell.execute_reply":"2026-04-05T23:14:45.369239Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(X_train.shape)\nprint(y_train.shape)","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:45.371130Z","iopub.execute_input":"2026-04-05T23:14:45.371640Z","iopub.status.idle":"2026-04-05T23:14:45.376424Z","shell.execute_reply.started":"2026-04-05T23:14:45.371599Z","shell.execute_reply":"2026-04-05T23:14:45.375750Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# * unpack the tuple\nX_train = X_train.reshape(X_train.shape[0], * (28, 28, 1))\nX_test = X_test.reshape(X_test.shape[0], * (28, 28, 1))\nX_validate = X_validate.reshape(X_validate.shape[0], * (28, 28, 1))\n","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:45.377359Z","iopub.execute_input":"2026-04-05T23:14:45.377635Z","iopub.status.idle":"2026-04-05T23:14:45.389259Z","shell.execute_reply.started":"2026-04-05T23:14:45.377612Z","shell.execute_reply":"2026-04-05T23:14:45.388775Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(X_train.shape)\nprint(y_train.shape)\nprint(X_validate.shape)\nprint(y_validate.shape)","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:45.390226Z","iopub.execute_input":"2026-04-05T23:14:45.390614Z","iopub.status.idle":"2026-04-05T23:14:45.401718Z","shell.execute_reply.started":"2026-04-05T23:14:45.390579Z","shell.execute_reply":"2026-04-05T23:14:45.401049Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Build the model\nBuilding the neural network requires configuring the layers of the model, then compiling the model.\n\n### Set up the layers\nThe basic building block of a neural network is the *layer*. Layers extract representations from the data fed into them. Hopefully, these representations are meaningful for the problem at hand.\n\nMost of deep learning consists of chaining together simple layers. Most layers, such as `tf.keras.layers.Dense`, have parameters that are learned during training.","metadata":{}},{"cell_type":"code","source":"import keras\nimport tensorflow as tf","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:14:45.402608Z","iopub.execute_input":"2026-04-05T23:14:45.402905Z","iopub.status.idle":"2026-04-05T23:15:17.646416Z","shell.execute_reply.started":"2026-04-05T23:14:45.402869Z","shell.execute_reply":"2026-04-05T23:15:17.645803Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout, BatchNormalization\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import TensorBoard","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:15:17.647265Z","iopub.execute_input":"2026-04-05T23:15:17.647782Z","iopub.status.idle":"2026-04-05T23:15:17.671106Z","shell.execute_reply.started":"2026-04-05T23:15:17.647757Z","shell.execute_reply":"2026-04-05T23:15:17.670394Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"cnn_model = Sequential()\n\n# Try 32 fliters first then 64\ncnn_model.add(Conv2D(filters=32, kernel_size=(3, 3), input_shape=(28,28,1), activation='relu', padding='same'))\ncnn_model.add(BatchNormalization())\ncnn_model.add(Conv2D(filters=32, kernel_size=(3, 3), input_shape=(28,28,1), activation='relu', padding='same'))\ncnn_model.add(BatchNormalization())\ncnn_model.add(MaxPooling2D(pool_size=(2, 2)))\ncnn_model.add(Dropout(0.2))\n\ncnn_model.add(Conv2D(filters=64, kernel_size=(3, 3), input_shape=(28,28,1), activation='relu', padding='same'))\ncnn_model.add(BatchNormalization())\ncnn_model.add(Conv2D(filters=64, kernel_size=(3, 3), input_shape=(28,28,1), activation='relu', padding='same'))\ncnn_model.add(BatchNormalization())\ncnn_model.add(MaxPooling2D(pool_size=(2, 2)))\ncnn_model.add(Dropout(0.2))\n\n# cnn_model.add(Conv2D(filters=128, kernel_size=(3, 3), input_shape=(28,28,1), activation='relu'))\n# cnn_model.add(BatchNormalization())\n# cnn_model.add(Conv2D(filters=128, kernel_size=(3, 3), input_shape=(28,28,1), activation='relu'))\n# cnn_model.add(BatchNormalization())\n# cnn_model.add(MaxPooling2D(pool_size=(2, 2)))\n# cnn_model.add(Dropout(0.25))\n\n# cnn_model.add(Conv2D(32,3, 3, activation='relu'))\n# cnn_model.add(MaxPooling2D(pool_size = (2, 2)))\n\ncnn_model.add(Flatten())\ncnn_model.add(Dense(units=128, activation='relu'))\ncnn_model.add(Dropout(0.2))\ncnn_model.add(Dense(units=10, activation='softmax'))","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:15:17.672072Z","iopub.execute_input":"2026-04-05T23:15:17.672479Z","iopub.status.idle":"2026-04-05T23:15:21.073313Z","shell.execute_reply.started":"2026-04-05T23:15:17.672444Z","shell.execute_reply":"2026-04-05T23:15:21.072545Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"The first layer in this network, `keras.layers.Flatten`, transforms the format of the images from a two-dimensional array (of 28 by 28 pixels) to a one-dimensional array (of 28 * 28 = 784 pixels). Think of this layer as unstacking rows of pixels in the image and lining them up. This layer has no parameters to learn; it only reformats the data.\n\nAfter the pixels are flattened, the network consists of a sequence of two `keras.layers.Dense` layers. These are densely connected, or fully connected, neural layers. The first Dense layer has 128 nodes (or neurons). The second (and last) layer is a 10-node softmax layer that returns an array of 10 probability scores that sum to 1. Each node contains a score that indicates the probability that the current image belongs to one of the 10 classes.","metadata":{}},{"cell_type":"markdown","source":"### Compile the model\nBefore the model is ready for training, it needs a few more settings. These are added during the model's compile step:\n\n- *Loss function* —This measures how accurate the model is during training. You want to minimize this function to \"steer\" the model in the right direction.\n- *Optimizer* —This is how the model is updated based on the data it sees and its loss function.\n- *Metrics* —Used to monitor the training and testing steps. The following example uses *accuracy*, the fraction of the images that are correctly classified.","metadata":{}},{"cell_type":"code","source":"METRICS = [\n    'accuracy',\n    tf.keras.metrics.Precision(name='precision'),\n    tf.keras.metrics.Recall(name='recall')\n]\n\ncnn_model.compile(loss ='sparse_categorical_crossentropy', optimizer='adam' ,metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:15:21.074423Z","iopub.execute_input":"2026-04-05T23:15:21.074708Z","iopub.status.idle":"2026-04-05T23:15:21.092955Z","shell.execute_reply.started":"2026-04-05T23:15:21.074685Z","shell.execute_reply":"2026-04-05T23:15:21.092426Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Train the model\n\nTraining the neural network model requires the following steps:\n\n1. Feed the training data to the model. In this example, the training data is in the `X_train` and `y_train` arrays.\n2. The model learns to associate images and labels.\n3. You ask the model to make predictions about a test set—in this example, the `X_test` array. Verify that the predictions match the labels from the `y_test` array.\n\nTo start training, call the `model.fit` method—so called because it \"fits\" the model to the training data:","metadata":{}},{"cell_type":"code","source":"epochs = 50\nbatch_size = 512\n\nhistory = cnn_model.fit(\n    X_train, y_train, \n    batch_size=batch_size, \n    epochs=epochs,\n    verbose=1, \n    validation_data=(X_validate, y_validate)\n)","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2026-04-05T23:15:21.093771Z","iopub.execute_input":"2026-04-05T23:15:21.094040Z","iopub.status.idle":"2026-04-05T23:17:04.659331Z","shell.execute_reply.started":"2026-04-05T23:15:21.094019Z","shell.execute_reply":"2026-04-05T23:17:04.658690Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(12, 8))\n\nplt.subplot(2, 2, 1)\nplt.plot(history.history['loss'], label='Loss')\nplt.plot(history.history['val_loss'], label='val_Loss')\nplt.legend()\nplt.title('Loss evolution')\n\nplt.subplot(2, 2, 2)\nplt.plot(history.history['accuracy'], label='accuracy')\nplt.plot(history.history['val_accuracy'], label='val_accuracy')\nplt.legend()\nplt.title('Accuracy evolution')","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:17:04.663245Z","iopub.execute_input":"2026-04-05T23:17:04.663558Z","iopub.status.idle":"2026-04-05T23:17:04.931357Z","shell.execute_reply.started":"2026-04-05T23:17:04.663533Z","shell.execute_reply":"2026-04-05T23:17:04.930732Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# STEP #5: EVALUATING THE MODEL","metadata":{}},{"cell_type":"code","source":"evaluation = cnn_model.evaluate(X_test, y_test)\nprint(f'Test Accuracy : {evaluation[1]:.3f}')","metadata":{"scrolled":true,"execution":{"iopub.status.busy":"2026-04-05T23:17:04.932326Z","iopub.execute_input":"2026-04-05T23:17:04.932661Z","iopub.status.idle":"2026-04-05T23:17:07.021023Z","shell.execute_reply.started":"2026-04-05T23:17:04.932628Z","shell.execute_reply":"2026-04-05T23:17:07.020286Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"It turns out that the accuracy on the test dataset is a little less than the accuracy on the training dataset. This gap between training accuracy and test accuracy represents overfitting. Overfitting is when a machine learning model performs worse on new, previously unseen inputs than on the training data.","metadata":{}},{"cell_type":"markdown","source":"## Makes predictions\n\nWith the model trained, you can use it to make predictions about some images.","metadata":{}},{"cell_type":"code","source":"# get the predictions for the test data\npredicted_classes = cnn_model.predict(X_test)\npredicted_classes = np.argmax(predicted_classes, axis=1)","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:17:07.022060Z","iopub.execute_input":"2026-04-05T23:17:07.022305Z","iopub.status.idle":"2026-04-05T23:17:08.703118Z","shell.execute_reply.started":"2026-04-05T23:17:07.022281Z","shell.execute_reply":"2026-04-05T23:17:08.702489Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Here, the model has predicted the label for each image in the testing set. Let's take a look at the first prediction:","metadata":{}},{"cell_type":"code","source":"test_img = X_test[0]\nprediction = cnn_model.predict(X_test)\nprediction[0]","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:17:08.704158Z","iopub.execute_input":"2026-04-05T23:17:08.704810Z","iopub.status.idle":"2026-04-05T23:17:09.380043Z","shell.execute_reply.started":"2026-04-05T23:17:08.704780Z","shell.execute_reply":"2026-04-05T23:17:09.379407Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"A prediction is an array of 10 numbers. They represent the model's \"confidence\" that the image corresponds to each of the 10 different articles of clothing. You can see which label has the highest confidence value:","metadata":{}},{"cell_type":"code","source":"np.argmax(prediction[0])","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:17:09.380945Z","iopub.execute_input":"2026-04-05T23:17:09.381198Z","iopub.status.idle":"2026-04-05T23:17:09.386949Z","shell.execute_reply.started":"2026-04-05T23:17:09.381175Z","shell.execute_reply":"2026-04-05T23:17:09.386190Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"So, the model is most confident that this image is an `T-shirt/top`, or `class_names[0]`. Examining the test label shows that this classification is correct:","metadata":{}},{"cell_type":"code","source":"L = 5\nW = 5\nfig, axes = plt.subplots(L, W, figsize = (12,12))\naxes = axes.ravel()\n\nfor i in np.arange(0, L * W):  \n    axes[i].imshow(X_test[i].reshape(28,28))\n    axes[i].set_title(f\"Prediction Class = {(predicted_classes[i]):0.1f}\\n True Class = {y_test[i]:0.1f}\")\n    axes[i].axis('off')\n\nplt.subplots_adjust(wspace=0.5)","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:17:09.387968Z","iopub.execute_input":"2026-04-05T23:17:09.388519Z","iopub.status.idle":"2026-04-05T23:17:10.678750Z","shell.execute_reply.started":"2026-04-05T23:17:09.388485Z","shell.execute_reply":"2026-04-05T23:17:10.678097Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, predicted_classes)\nplt.figure(figsize = (14,10))\nsns.heatmap(cm, annot=True)\n# Sum the diagonal element to get the total true correct values","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:17:10.679691Z","iopub.execute_input":"2026-04-05T23:17:10.680063Z","iopub.status.idle":"2026-04-05T23:17:11.063300Z","shell.execute_reply.started":"2026-04-05T23:17:10.680038Z","shell.execute_reply":"2026-04-05T23:17:11.062561Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import classification_report\n\nnum_classes = 10\ntarget_names = [f\"Class {i}\" for i in range(num_classes)]\n\nprint(classification_report(y_test, predicted_classes, target_names = target_names))","metadata":{"execution":{"iopub.status.busy":"2026-04-05T23:17:11.064375Z","iopub.execute_input":"2026-04-05T23:17:11.064799Z","iopub.status.idle":"2026-04-05T23:17:11.081952Z","shell.execute_reply.started":"2026-04-05T23:17:11.064772Z","shell.execute_reply":"2026-04-05T23:17:11.081144Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Resources:\n\n1. [Machine Learning Practical 6 Real-World Applications Course - Udemy](https://www.udemy.com/course/machine-learning-practical/)\n2. [Tensorflow documentation](https://www.tensorflow.org/tutorials/keras/classification)","metadata":{}}]}