{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "Wou8xF81D_ke" }, "source": [ "## FashionMNIST Computer Vision Object Classification Project\n", "\n", "In this notebook, we're going to be doing a classification project to classify a clothing dataset (FashionMNSIT) based on a total of 10 different clothing classes. The link to the dataset can be found here: https://www.tensorflow.org/datasets/catalog/fashion_mnist\n", "\n", "For the paper reference, you can open the following link: https://arxiv.org/abs/1708.07747\n" ] }, { "cell_type": "markdown", "metadata": { "id": "RvgLMt7oD_kf" }, "source": [ "### Check for a GPU" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "PMZpOUW3D_kf" }, "outputs": [], "source": [ "# Make sure we have access to a GPU\n", "!nvidia-smi" ] }, { "cell_type": "markdown", "metadata": { "id": "pPV4yN3MD_kg" }, "source": [ "### Downloading helper functions script for our modelling experiments" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "9cx66BFBD_kg" }, "outputs": [], "source": [ "# Download script\n", "!wget https://raw.githubusercontent.com/mrdbourke/tensorflow-deep-learning/refs/heads/main/extras/helper_functions.py" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "-Yhie97ED_kg" }, "outputs": [], "source": [ "# Import the necessary functions from script\n", "from helper_functions import create_tensorboard_callback, plot_loss_curves, compare_historys, make_confusion_matrix" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Z981PCk4D_kg" }, "outputs": [], "source": [ "import tensorflow_datasets as tfds\n", "import tensorflow as tf\n", "\n", "# Check if our target dataset is within TensorFlow datasets\n", "all_datasets = tfds.list_builders()\n", "print(f'fashion_mnist' in all_datasets)" ] }, { "cell_type": "markdown", "metadata": { "id": "k9XlAH2TD_kg" }, "source": [ "> 🔑 **Note:** Most TensorFlow datasets (TFDS) have already been split into training and test sets, so there's no need to create a splitting function or to split the dataset manually." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ytdoru3lD_kg" }, "outputs": [], "source": [ "# Download the target dataset\n", "(train_ds, test_ds), ds_info = tfds.load(name = 'fashion_mnist', split = ['train', 'test'], as_supervised = True, with_info = True)" ] }, { "cell_type": "markdown", "metadata": { "id": "fvhNeV20D_kh" }, "source": [ "### Visualising one or more random samples from our dataset\n", "\n", "It's important that before building or picking a pretrained computer vision model, we visualise **random** samples from our training data so we can have an idea of how our training dataset of clothing images is going to look like. This can give us an inkling on where the model can potentially get confused when trying to predict the target class, due to similarity between two or more classes.\n", "\n", "The data explorer's motto: visualise, visualise, visualise!\n", "\n", "To visualise one or more random samples from the training dataset, there are two options:\n", "* The short way: we can use the method `tfds.show_examples()` method from TensorFlow datasets: https://www.tensorflow.org/datasets/api_docs/python/tfds/visualization/show_examples\n", "* Or we can create a visualisation function to plot one or more random samples if we want" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "wyfGD62FD_kh" }, "outputs": [], "source": [ "# Visualise a sample of clothing from the train dataset (using the tfds.show_examples() function)\n", "tfds.show_examples(train_ds, ds_info)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "uQQnmyapD_kh" }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "\n", "def view_random_image(train_data, ds_info):\n", " class_names = ds_info.features['label'].names\n", "\n", " for image, label in train_data.take(5):\n", " plt.figure(figsize = (7, 7))\n", "\n", " # Handle grayscale vs RGB\n", " img = tf.squeeze(image).numpy()\n", " if img.ndim == 2:\n", " plt.imshow(img, cmap = 'gray')\n", " else:\n", " plt.imshow(img.astype('uint8'))\n", "\n", " plt.title(class_names[label])\n", " plt.axis(False)\n", " plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "gBMLvEYvD_kh" }, "outputs": [], "source": [ "# Test function\n", "view_random_image(train_data = train_ds, ds_info = ds_info)" ] }, { "cell_type": "markdown", "metadata": { "id": "B34XB0YAD_kh" }, "source": [ "### Creating preprocessing functions and data pipelines for our data for faster execution time\n", "\n", "Now that we've seen what our training dataset looks like, it's time to start creating efficient data pieplines and preprocessing functions for our GPU to run as fast as possible." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "x9x6_WWXD_kh" }, "outputs": [], "source": [ "# Create data augmentation layer (for diversity)\n", "from tensorflow.keras import layers\n", "\n", "data_augmentation = tf.keras.Sequential([\n", " layers.RandomFlip('horizontal'),\n", " layers.RandomRotation(0.1),\n", " layers.RandomZoom(0.1),\n", "], name = 'data_augmentation')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "wynciXlCD_kh" }, "outputs": [], "source": [ "# Define a simplified preprocessing function\n", "def preprocess_simple(image, label, image_size = 224):\n", " image = tf.image.resize(image, [image_size, image_size])\n", " image = tf.cast(image, dtype = tf.float32)\n", " if image.shape[-1] == 1:\n", " image = tf.image.grayscale_to_rgb(image)\n", " return image, label" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "j0Gd8MTnD_ki" }, "outputs": [], "source": [ "batch_size = 32\n", "\n", "# Map preprocessing function, shuffle and parallelise it to training data\n", "train_ds = train_ds.map(map_func = preprocess_simple, num_parallel_calls = tf.data.AUTOTUNE)\n", "train_ds = train_ds.shuffle(1000).batch(batch_size).prefetch(tf.data.AUTOTUNE)\n", "\n", "# Validation/test pipeline\n", "test_ds = test_ds.map(map_func = preprocess_simple, num_parallel_calls = tf.data.AUTOTUNE)\n", "test_ds = test_ds.batch(batch_size).prefetch(tf.data.AUTOTUNE)\n", "\n", "train_ds, test_ds" ] }, { "cell_type": "markdown", "metadata": { "id": "yXdhIVHaD_ki" }, "source": [ "### Creating ModelCheckPoint callback" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "aQ3TCoG_D_ki" }, "outputs": [], "source": [ "# Import tensorboard callback from script\n", "from helper_functions import create_tensorboard_callback\n", "\n", "# Setup model checkpoint path to save all of models' progress during training\n", "checkpoint_path = 'model_checkpoint.weights.h5'\n", "model_checkpoint = tf.keras.callbacks.ModelCheckpoint(filepath = checkpoint_path, save_weights_only = True, monitor = 'val_accuracy', save_best_only = True)" ] }, { "cell_type": "markdown", "metadata": { "id": "wDHpy9V7D_ki" }, "source": [ "### Mixed precision training" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "vYM92QFmD_ki" }, "outputs": [], "source": [ "from tensorflow.keras import mixed_precision\n", "\n", "mixed_precision.set_global_policy('mixed_float16')\n", "mixed_precision.global_policy()" ] }, { "cell_type": "markdown", "metadata": { "id": "HZIqYPAaD_ki" }, "source": [ "## Model 0 (baseline): Pretrained ResNet101V2:\n", "\n", "Our first modelling experiment will start off will a simple ResNet18 architecture (baseline), we will proceed further will complex ImageNet model architectures as we will have plenty of modelling experiments to cover." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "_W0mE-LrD_ki" }, "outputs": [], "source": [ "from tensorflow.keras import layers\n", "\n", "# Setup input shape for base model\n", "input_shape = (224, 224, 3)\n", "\n", "# Get number of classes\n", "num_classes = ds_info.features['label'].num_classes\n", "\n", "# Create model using functional API\n", "base_model = tf.keras.applications.ResNet101V2(include_top = False, weights = 'imagenet', input_shape = input_shape)\n", "base_model.trainable = False\n", "\n", "inputs = layers.Input(shape = input_shape, name = 'input_layer')\n", "x = data_augmentation(inputs)\n", "x = base_model(inputs)\n", "x = layers.GlobalAveragePooling2D(name = 'global_average_pooling_layer')(x)\n", "x = layers.BatchNormalization()(x)\n", "x = layers.Dense(256, activation = 'relu')(x)\n", "x = layers.Dropout(0.5)(x)\n", "outputs = layers.Dense(num_classes, activation = 'softmax', name = 'output_layer')(x)\n", "model_0 = tf.keras.Model(inputs, outputs)\n", "\n", "# Compile baseline model\n", "model_0.compile(loss = tf.keras.losses.SparseCategoricalCrossentropy(),\n", " optimizer = tf.keras.optimizers.Adam(),\n", " metrics = ['accuracy'])\n", "\n", "# Get model summary\n", "model_0.summary()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "BftCyAMqD_ki" }, "outputs": [], "source": [ "# Fit feature extractor model to data\n", "history_model_0 = model_0.fit(train_ds, epochs = 5, steps_per_epoch = len(train_ds), validation_data = test_ds, validation_steps = int(0.15 * len(test_ds)), callbacks = [create_tensorboard_callback(dir_name = 'tensorboard_logs', experiment_name = 'resnet18_feature_extraction'), model_checkpoint])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "9Uu4T31aD_ki" }, "outputs": [], "source": [ "# Evaluate model\n", "model_0.evaluate(test_ds)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "3iDKK7ZTD_kj" }, "outputs": [], "source": [ "# Make predictions with model\n", "model_0_preds = model_0.predict(test_ds, verbose = 1)\n", "model_0_preds, model_0_preds.shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "HotoK4P4D_kj" }, "outputs": [], "source": [ "# Convert model preds to tensor -> label\n", "model_0_preds_tensor = tf.convert_to_tensor(model_0_preds)\n", "labels = tf.argmax(model_0_preds_tensor, axis = 1)\n", "labels" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "9ydyclx1D_kj" }, "outputs": [], "source": [ "# Plot model loss curves\n", "plot_loss_curves(history = history_model_0)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "J9P-BlzvD_kj" }, "outputs": [], "source": [ "import numpy as np\n", "\n", "# Get true labels from the test dataset\n", "true_labels = []\n", "for images, labels_batch in test_ds.unbatch():\n", " true_labels.append(labels_batch.numpy())\n", "\n", "true_labels = np.array(true_labels)\n", "\n", "# Plot model 0's confusion matrix\n", "make_confusion_matrix(y_true = true_labels, y_pred = labels)" ] }, { "cell_type": "markdown", "metadata": { "id": "5EukTAWVD_kj" }, "source": [ "From all of `model_0`'s experiment tracking and results, everything turned out to be very impressive (i.e. ROC curves for loss and accuracy, as well as when fitting the model to the training data).\n", "\n", "From the confusion matrix above, we can see which classes (labels) is the model getting confused on and where it is getting confused the **most**." ] }, { "cell_type": "markdown", "metadata": { "id": "KWVfQuWVD_kj" }, "source": [ "## Model 1: Pretrained ResNet152V2\n", "\n", "Let's see if our pretrained ResNet1252V2 feature extractor can beat the ResNet152 pretrained model." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "eQDz-i4cD_kj" }, "outputs": [], "source": [ "#input_shape = (224, 224, 3)\n", "\n", "num_classes = ds_info.features['label'].num_classes\n", "\n", "base_model = tf.keras.applications.ResNet152V2(include_top = False, weights = 'imagenet', input_shape = input_shape)\n", "base_model.trainable = False\n", "\n", "inputs = layers.Input(shape = input_shape, name = 'input_layer')\n", "x = data_augmentation(inputs)\n", "x = base_model(inputs)\n", "x = layers.GlobalAveragePooling2D(name = 'global_average_pooling_layer')(x)\n", "x = layers.BatchNormalization()(x)\n", "x = layers.Dense(256, activation = 'relu')(x)\n", "x = layers.Dropout(0.5)(x)\n", "outputs = layers.Dense(num_classes, activation = 'softmax', name = 'output_layer')(x)\n", "model_1 = tf.keras.Model(inputs, outputs)\n", "\n", "# Compile\n", "model_1.compile(loss = tf.keras.losses.SparseCategoricalCrossentropy(),\n", " optimizer = tf.keras.optimizers.Adam(),\n", " metrics = ['accuracy'])\n", "\n", "model_1.summary()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "u1LItMggD_kj" }, "outputs": [], "source": [ "# Fit\n", "history_model_1 = model_1.fit(train_ds, epochs = 5, steps_per_epoch = len(train_ds), validation_data = test_ds, validation_steps = int(0.15 * len(test_ds)), callbacks = [create_tensorboard_callback(dir_name = 'tensorboard_logs', experiment_name = 'resnet152_feature_extraction'), model_checkpoint])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "6cdmGS5dD_kj" }, "outputs": [], "source": [ "# Evaluate model\n", "model_1.evaluate(test_ds)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "d5l0kBl1D_kj" }, "outputs": [], "source": [ "# Make predictions with model\n", "model_1_preds = model_1.predict(test_ds, verbose = 1)\n", "model_1_preds" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "tKa6tGQ8D_kk" }, "outputs": [], "source": [ "# Convert preds to pred labels\n", "model_1_preds_tensor = tf.convert_to_tensor(model_1_preds)\n", "labels = tf.argmax(model_1_preds_tensor, axis = 1)\n", "labels" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "XhCF7RuLD_kk" }, "outputs": [], "source": [ "# Plot loss curves\n", "plot_loss_curves(history = history_model_1)" ] }, { "cell_type": "markdown", "metadata": { "id": "uAKWMgRQD_kk" }, "source": [ "The loss curves on `model_1` look much the same and aligned with each other like `model_0`'s. However, `model_0` still outperforms `model_1`'s val_accuracy score very slightly." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Z1djqeNDD_kk" }, "outputs": [], "source": [ "# Plot model_1's confusion matrix\n", "make_confusion_matrix(y_true = true_labels, y_pred = labels)" ] }, { "cell_type": "markdown", "metadata": { "id": "kJXRfbDZD_kl" }, "source": [ "### Comparing `model_1` and `model_2` histories\n", "\n", "We're now going to compare the histories of both `model_1` and `model_2`.\n", "\n", "> 🔑 **Note:** We haven't fine-tuned both models since they're already performing very well, so the curve/graph for fine-tuning won't be displayed." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "n1HnbtK1D_kl" }, "outputs": [], "source": [ "# Comapre model_0 and model_1 histories\n", "compare_historys(original_history = history_model_0, new_history = history_model_1)" ] }, { "cell_type": "markdown", "metadata": { "id": "hQNnm7jhD_kl" }, "source": [ "## Model 2: Pretrained ResNet50V2" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "FYwtxIGdD_kl" }, "outputs": [], "source": [ "input_shape = (224, 224, 3)\n", "\n", "num_classes = ds_info.features['label'].num_classes\n", "\n", "base_model = tf.keras.applications.ResNet50V2(include_top = False, weights = 'imagenet', input_shape = input_shape)\n", "base_model.trainable = False\n", "\n", "inputs = layers.Input(shape = input_shape, name = 'input_layer')\n", "x = data_augmentation(inputs)\n", "x = base_model(inputs)\n", "x = layers.GlobalAveragePooling2D(name = 'global_average_pooling_layer')(x)\n", "x = layers.BatchNormalization()(x)\n", "x = layers.Dense(256, activation = 'relu')(x)\n", "x = layers.Dropout(0.5)(x)\n", "outputs = layers.Dense(num_classes, activation = 'softmax', name = 'output_layer')(x)\n", "model_2 = tf.keras.Model(inputs, outputs)\n", "\n", "# Compile\n", "model_2.compile(loss = tf.keras.losses.SparseCategoricalCrossentropy(),\n", " optimizer = tf.keras.optimizers.Adam(),\n", " metrics = ['accuracy'])\n", "\n", "model_2.summary()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "jy2O8RDED_kl" }, "outputs": [], "source": [ "# Fit\n", "history_model_2 = model_2.fit(train_ds, epochs = 5, steps_per_epoch = len(train_ds), validation_data = test_ds, validation_steps = int(0.15 * len(test_ds)), callbacks = [create_tensorboard_callback(dir_name = 'tensorboard_logs', experiment_name = 'resnet50_feature_extraction'), model_checkpoint])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "a_hTntFND_km" }, "outputs": [], "source": [ "# Evaluate model\n", "model_2.evaluate(test_ds)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "MjkXAdl8D_km" }, "outputs": [], "source": [ "# Make predictions with model\n", "model_2_preds = model_2.predict(test_ds, verbose = 1)\n", "model_2_preds" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "YQAAj5DSD_km" }, "outputs": [], "source": [ "# Convert preds to labels\n", "model_2_preds_tensor = tf.convert_to_tensor(model_2_preds)\n", "labels = tf.argmax(model_2_preds_tensor, axis = 1)\n", "labels" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "z_fcHSecD_km" }, "outputs": [], "source": [ "# Plot loss curves\n", "plot_loss_curves(history = history_model_2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "HVMVfbSwD_km" }, "outputs": [], "source": [ "# Plot model's confusion matrix\n", "make_confusion_matrix(y_true = true_labels, y_pred = labels)" ] }, { "cell_type": "markdown", "metadata": { "id": "hED2NGzKD_km" }, "source": [ "## Model 3: Pretrained EfficientNetV2B0" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "wBMm_7LuD_km" }, "outputs": [], "source": [ "input_shape = (224, 224, 3)\n", "\n", "num_classes = ds_info.features['label'].num_classes\n", "\n", "base_model = tf.keras.applications.EfficientNetV2B0(include_top = False, weights = 'imagenet', input_shape = input_shape)\n", "base_model.trainable = False\n", "\n", "inputs = layers.Input(shape = input_shape, name = 'input_layer')\n", "x = data_augmentation(inputs)\n", "x = base_model(inputs)\n", "x = layers.GlobalAveragePooling2D(name = 'global_average_pooling_layer')(x)\n", "x = layers.BatchNormalization()(x)\n", "x = layers.Dense(256, activation = 'relu')(x)\n", "x = layers.Dropout(0.5)(x)\n", "outputs = layers.Dense(num_classes, activation = 'softmax', name = 'output_layer')(x)\n", "model_3 = tf.keras.Model(inputs, outputs)\n", "\n", "# Compile\n", "model_3.compile(loss = tf.keras.losses.SparseCategoricalCrossentropy(),\n", " optimizer = tf.keras.optimizers.Adam(),\n", " metrics = ['accuracy'])\n", "\n", "model_3.summary()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "-ofjZbdxD_km" }, "outputs": [], "source": [ "# Fit\n", "history_model_3 = model_3.fit(train_ds, epochs = 5, steps_per_epoch = len(train_ds), validation_data = test_ds, validation_steps = int(0.15 * len(test_ds)), callbacks = [create_tensorboard_callback(dir_name = 'tensorboard_logs', experiment_name = 'efficientnetv2b0_feature_extraction'), model_checkpoint])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "H3xGy6BED_km" }, "outputs": [], "source": [ "# Evaluate model\n", "model_3.evaluate(test_ds)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "vkqiz7VoD_kn" }, "outputs": [], "source": [ "# Make predictions with model\n", "model_3_preds = model_3.predict(test_ds, verbose = 1)\n", "model_3_preds" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "j7E1vp6TD_kn" }, "outputs": [], "source": [ "# Convert preds to labels\n", "model_3_preds_tensor = tf.convert_to_tensor(model_3_preds)\n", "labels = tf.argmax(model_3_preds_tensor, axis = 1)\n", "labels" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "nQ2zNBogD_kn" }, "outputs": [], "source": [ "# Plot loss curves\n", "plot_loss_curves(history = history_model_3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "r49isxXzD_kn" }, "outputs": [], "source": [ "# Plot model's confusion matrix\n", "make_confusion_matrix(y_true = true_labels, y_pred = labels)" ] }, { "cell_type": "markdown", "metadata": { "id": "VQtF2QzHD_kn" }, "source": [ "## Model 4: Pretrained EfficientNetV2M (M = medium sized)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "_RcLQebPD_kn" }, "outputs": [], "source": [ "input_shape = (224, 224, 3)\n", "\n", "num_classes = ds_info.features['label'].num_classes\n", "\n", "# Create an instance of the EfficientNetV2M model\n", "base_model = tf.keras.applications.EfficientNetV2M(include_top = False, weights = 'imagenet', input_shape = input_shape)\n", "base_model.trainable = False\n", "\n", "inputs = layers.Input(shape = input_shape, name = 'input_layer')\n", "x = data_augmentation(inputs)\n", "x = base_model(inputs)\n", "x = layers.GlobalAveragePooling2D(name = 'global_average_pooling_layer')(x)\n", "x = layers.BatchNormalization()(x)\n", "x = layers.Dense(256, activation = 'relu')(x)\n", "x = layers.Dropout(0.5)(x)\n", "outputs = layers.Dense(num_classes, activation = 'softmax', name = 'output_layer')(x)\n", "model_4 = tf.keras.Model(inputs, outputs)\n", "\n", "model_4.compile(loss = tf.keras.losses.SparseCategoricalCrossentropy(),\n", " optimizer = tf.keras.optimizers.Adam(),\n", " metrics = ['accuracy'])\n", "\n", "model_4.summary()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "HfaLKAHvD_kn" }, "outputs": [], "source": [ "# Fit model 4\n", "history_model_4 = model_4.fit(train_ds, epochs = 5, steps_per_epoch = len(train_ds), validation_data = test_ds, validation_steps = int(0.15 * len(test_ds)), callbacks = [create_tensorboard_callback(dir_name = 'tensorboard_logs', experiment_name = 'efficientnetv2m_feature_extraction'), model_checkpoint])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "GggjG3tlD_kn" }, "outputs": [], "source": [ "# Evaluate model\n", "model_4.evaluate(test_ds)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "E11M-zCDD_kn" }, "outputs": [], "source": [ "# Make predictions with model\n", "model_4_preds = model_4.predict(test_ds, verbose = 1)\n", "model_4_preds" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "yySq4tBjD_ko" }, "outputs": [], "source": [ "# Convert preds to labels\n", "model_4_preds_tensor = tf.convert_to_tensor(model_4_preds)\n", "labels = tf.argmax(model_4_preds_tensor, axis = 1)\n", "labels" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "DZ2dMSyMD_ko" }, "outputs": [], "source": [ "# Plot loss curves\n", "plot_loss_curves(history = history_model_4)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "_pXQNf_-D_ko" }, "outputs": [], "source": [ "# Plot model's confusion matrix\n", "make_confusion_matrix(y_true = true_labels, y_pred = labels)" ] }, { "cell_type": "markdown", "metadata": { "id": "a4_GbofTD_ko" }, "source": [ "## Uploading our modelling experiments to TensorBoard\n", "\n", "We're now done with our modelling exeperiments with this notebook, let's now upload our results to TensorBoard to view all of our models' training logs." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "hRwzWu1OD_ko" }, "outputs": [], "source": [ "# Upload models' results to TensorBoard\n", "!pip install -q tensorboard\n", "%load_ext tensorboard\n", "%tensorboard --logdir=/content/tensorboard_logs\n", "%reload_ext tensorboard" ] } ], "metadata": { "colab": { "provenance": [] } }, "nbformat": 4, "nbformat_minor": 0 }