MSE 413 – Lab 4 – Neural Networks and Deep Learning Simon Fraser University School of Mechatronic Systems Engineering MSE413 - Machine Learning in Mechatronics Lab 4 – Neural Networks and Deep Learning Due Date: March 30th, 11:59pm Background Artificial Neural Networks (ANNs) consist of several artificial neurons (or nodes) that resemble the behaviour of the human brain neurons. These networks allow computer programs to learn and recognize complex patterns in the data. ANNs comprise three main layers, the input layer, a single or multiple hidden layers, and an output layer (Fig.1). The nodes are connected with a specific weight and threshold. The weights for the connections get adjusted after training the ANN. The nodes get activated if the output of an individual node is higher than the threshold. One common application to the ANNs is to solve complex nonlinear regression and classification problems (e.g. Fig.2). Multiple training algorithms are available for ANNs. Other advantages of ANNs including their ability to implicitly detecting complex nonlinear relationships, detecting all possible interactions between predictor variables. ©https://www.ibm.com Fig1. ANNs schematic © https://towardsdatascience.com Fig2. An example for complex classification problem However, there are a number of challenges that exist working with ANNs. These challenges include the “black-box” nature of the ANNs, greater computational cost, and proneness to overfitting. Both advantages and challenges should be taken into account while implementing ANNs to solve real-world mechatronics problems. 1 MSE 413 – Lab 4 – Neural Networks and Deep Learning Recent advances in Computer Vision with Deep Learning revealed the efficiency of one particular algorithm, called Convolutional Neural Network (CNN) for image processing. A CNN is a Deep Learning algorithm that is able to capture the spatial and temporal dependencies in an image by implementing relevant filters. Since CNN reduces the number of parameters involved and reusability of weights, the architecture performs a better fitting to the image dataset. Please review the contents presented in this link to learn more about the details of CNNs. In this Lab we will focus on both ANNs and CNNs to carry out image processing. The dataset provided for this Lab is a brain tumor MRI image dataset. You'll begin this assignment by classifying data using a simple Perceptron. Then, you'll proceed to Artificial Neural Networks (ANNs) and basic Convolutional Neural Networks (CNNs). Afterwards, you'll be tasked with classification using advanced, pre-trained convolutional networks, with the power of transfer learning. You can find these pre-trained networks at the following link. Then you should compare your results with the already developed models. In the final step of this assignement we will use labeling platform of Roboflow to prepare our dataset for object detection task, in which you will not only classify each image, but detect the tumor in that very image. In other words, In the last part of this assignment, we'll utilize the labeling platform provided by roboflow to prepare our dataset for an object detection task. This task involves not only classifying each image but also detecting the tumor present within the image itself. The dataset for tasks 1-4 is uploaded as “Brain_tumor” and the dataset for task 5 is a separate one uploaded as “Brain_tumor_YOLO”. 2 MSE 413 – Lab 4 – Neural Networks and Deep Learning MSE 413- Assignment 4 (Spring 2025) Tumor MRI dataset A brain tumor is a collection, or mass, of abnormal cells in your brain. Your skull, which encloses your brain, is very rigid. Any growth inside such a restricted space can cause problems. Brain tumors can be cancerous (malignant) or noncancerous (benign). When benign or malignant tumors grow, they can cause the pressure inside your skull to increase. This can cause brain damage, and it can be life-threatening. Early detection and classification of brain tumors is an important research domain in the field of medical imaging and accordingly helps in selecting the most convenient treatment method to save patients life therefafter. This dataset contains 3510 images of human brain MRI images which are classified into 4 classes: glioma - meningioma – pituitary and no tumor. The training and test sets for both classification and object detection (task 5) are separately uploaded for you. Note 1) In this assignment, right before fitting any model to your training data use the magic method “%%time” in order to be able to record the time of your training. Note 2) In this assignment, consistency in runtime performance is important. Use the same hardware type for all of your trained models throughout the assignment. For example, if you begin with CPU, continue with CPU for all models. If you begin with GPU, continue with GPU for all models. Note 3) If you are asked to modify a model. Please have both the modified and unmodified models recorded on your notebook. Don’t replace any model while modifying. Note 4) For all classification tasks in this assignment, use the provided reduced dataset only. This reduced dataset has been prepared to keep the computations manageable and consistent across students. 1. Data Exploration [10%] In this step, you'll upload the data into your notebook, familiarize yourself with it, and gather useful information such as the shape of the images, potential inconsistencies, and the type of images (grayscale or RGB).Import all the necessary packages including (numpy, tensorflow, keras) and visualization packages. 1.1) 1.2) Use “keras.preprocessing.image_dataset_from_directory” to upload your images into two separate training and test datasets in your notebook.(2 points) Report the number of images in the training and test datasets, along with the class names and the number of classes.( 1point) 3 MSE 413 – Lab 4 – Neural Networks and Deep Learning 1.3) 1.4) Report the image shape (height, width, channels) by inspecting a representative batch of images. State whether the dataset appears to have consistent image dimensions. (2 points) Display 6 sample images from the training dataset in a 2 × 3 figure layout and show their corresponding class labels ( 5 points) Hint: You may use dataset.take(1) to inspect one batch of images and labels. 2. Simple Perceptron [15%] A perceptron is the simplest form of a neural network with one hidden layer. It takes multiple inputs, each multiplied by a weight, sums them up, and applies an activation function to produce an output. In this task, you will begin with a simple baseline model to assess how well a perceptron performs on this image classification problem. 2.1) 2.2) 2.3) 2.4) For the perceptron task, define a smaller subset of the provided reduced dataset by selecting 25% of the training data and 25% of the test data. These will be your training and testing datasets for the perceptron model. (1point) As each image data is imported in tensor format, you need first to change the format of your data to numpy array and then vectorize it to make it suitable for Perceptron input. Define a function “data_vectorizer” to receive your training and testing data and return x_train, y_train,x_test, and y_test vector arrays as output. (4points) Report the shape of your training and testing data after vectorization. (1point) Normalize your data using MinMaxScaler() and train a perceptron on your training data. Record the time (2points) [Note: you should make perceptron consistent with multi-class classification before training, take advantage of OneVsRestClassifier of sklearn to do it!] 4 MSE 413 – Lab 4 – Neural Networks and Deep Learning 2.5) Evaluate and report the following metrics on your test data: o Accuracy o Precision o Recall o F1 score Based on the reported metrics, briefly discuss whether this model would be reliable enough for real world medical decision support. (4points) 2.6) Calculate and display the confusion matrix of your model on test data. (3points) 3. Artificial Neural Network(ANN) [20%] ***From this point on, your model development will be done by keras and its modules.*** 3.1) Consider the base structure schematically shown in the Figure below and walk through the steps (7points): o Use keras.Sequential() to build a feedforward ANN with two hidden Dense layers and one output Dense layer, as shown in the figure. [ Note: Include a Flatten layer to convert image data into vector form, and apply normalization to scale pixel values before feeding data into the ANN so the image data can be used as input to the ANN.] • • • The number of neurons in the first two hidden layers are 100, 75 respectively and the number of neurons in output layer should be equal to the number of classes. Now take a summary of your model and report the number of trainable parameters. Compile your model with the following parameters: o Optimizer = “sgd” o Loss = “sparse_categorical_crossentropy” o Metric = “accuracy” 5 MSE 413 – Lab 4 – Neural Networks and Deep Learning • • • • • • • Use the pseudocode in the appendix to split your train dataset into training and validation set.[Note: Due to the format of your dataset, keras model will automatically distinguish between x and y in training and validation sets, thus you don’t need to do any further splitting] Use the memory optimizing pseudocode in the appendix for faster training. Now fit your model for 20 epochs and report the final values of the following: Training accuracy Validation accuracy Total training time You should keep your baseline ANN results, since you will compare later models against this baseline. In the next two parts, you will perform controlled architecture changes to study how network depth and hidden layer width affect performance. 3.2) Repeat the model building, compilation, training, and reporting steps above. You do not need to repeat the train validation split or the memory optimization steps. Do this for two more scenarios below and record the performance metrics and time (3points): o Develop a 4 layer model ( 3 – hidden layers, 3rd layer neurons = 50) o Develop a 5 layer model ( 4 - hidden layers, 3rd and 4th layer neurons=50) 3.3) Now, based on the same 2- hidden layer model developed in 3.1 do the followings (3 points): • Develop a new version of the same 2 hidden layer ANN in which the number of neurons in each hidden layer is reduced to 50% of the original values. ( round up the number of neurons if needed) and record performance metrics. • Develop a model with 150% of neurons of each hidden layer and record performance metrics. Use a barchart and plot training and validation accuracy as a function of different models you developed. What is your final conclusion of these observations? (2 points) 3.4) 3.5) Out of the barchart above select the best model, compromising accuracy with the severity of overfitting ( Severity of overfitting as a ballpark is the difference between training and validation accuracy) (1point) 6 MSE 413 – Lab 4 – Neural Networks and Deep Learning 3.6) 3.7) Select your best ANN model from the previous parts by considering both validation accuracy and the severity of overfitting. Then add one Dropout layer before the output layer with dropout rate 0.25 and any fixed seed value. Train this updated model for the same 20 epochs and compare its training and validation accuracy with the original selected model. (3points) Use the method .evaluate() on your test set and report the deployment loss and accuracy of this model. (1point) 4. Convolutional Neural Networks(CNNs)[20%] a) LeNet-5 LeNet-5, developed by Yann LeCun in the 1990s, was one of the earliest convolutional neural network architectures, pioneering the application of deep learning in handwritten digit recognition and significantly advancing the field of computer vision. LeNet-5 is mainly developed for 32×32 handwritten digit recognition. In this section, you will design a modified version to take use of it for the purpose of this assignment. Note that convolutional networks do not require vectorization of images before input, also normalization of input images is not a must in many cases, but can standardize the input data and reduce variations in features caused by differences in image resolutions. The original architecture of LeNet-5 ( 1990) 7 MSE 413 – Lab 4 – Neural Networks and Deep Learning In this section, you will first build a classical CNN architecture, then improve it, and finally compare it with a transfer learning approach. 4.1) As the first step let’s regenerate LeNet – 5 based on the figure above with some modifications to make it consistent with the task at hand (5 points): o Add an input layer before the first convolution layer and set its input shape to match your image dimensions. o Make the complete model based on the figure however replace all sigmoid activation functions with Relu. [Note: number of filters in each layer is equal to the number of channels in the output of that layer]. o For the last Dense layer (output layer) replace the number of neurons (10) with the number of your own classes. o Compile and fit your model with all the adjustments of section 3. o Report the accuracies. Hint: Convolutional models expect image inputs directly. You do not need to flatten the input, but you may apply rescaling (normalization) if needed. 4.2) If you've followed the steps correctly, you might find the results of LeNet-5 to be somewhat disappointing. So, refer to the figure below, make the adjustments on the model accordingly to make a modified version of the previous model. (5 points): o Replace the input layer with a Rescaling layer and impose the input shape. o In 2 to 4 sentences, explain one or two reasons why max pooling is often preferred over average pooling in many CNN applications. o Now replace the Average pooling layers with Maxpooling with the same inputs. o Insert dropout layers with dropout rate of 0.2 in the specified locations in your model. o Compile and fit the model on training data and record the time. o Report the training and validation accuracies. Briefly explain whether the modified model improves over the original LeNet 5 model. o Evaluate the model on your test set and report the deployment loss and accuracy of this model. b) Transfer Learning Transfer learning is a machine learning technique where knowledge gained from solving one task is applied to a related task, enabling the reuse of pre-trained models to improve performance, reduce training time, and address data scarcity issues in various domains such as computer vision, natural language processing, and speech recognition. In this part of task 4 we want to use a powerful pre-trained model as the core of a convolutional neural network for our tumor classification task. 8 MSE 413 – Lab 4 – Neural Networks and Deep Learning MobileNet is a lightweight deep neural network architecture designed for mobile and embedded vision applications. It utilizes depthwise separable convolutions to reduce computational complexity while maintaining high accuracy, making it efficient for deployment on resourceconstrained devices. Here we use this architecture to develop a transfer learning based model. 4.3) Use the pretrained MobileNetV2 model and develop a transfer learning model as shown in the figure below. First of all, import MobileNetV2 with the argument (include_top=False) to take use of it as the core of your own model. After architechting your model do the followings (7 points): o Report trainable and non-trainable parameters of your model. o Report number of layers in the core model. o Use the concept of transfer learning and turn all trainable layers of the core model into non-trainable ones except for the last 12 layers ( i.e. only 12 last layers of the core model will have trainable parameters and for the rest, the same pre-trained parameters will be frozen). Clearly report the number of trainable and non trainable parameters before and after freezing layers. o Compile and fit your model to the training and validation data with the same adjustments of previous sections and for 20 epochs. Record the running time. o Evaluate the model on your test set and report the deployment loss and accuracy of this model. Hint: Use the appropriate preprocessing function for MobileNetV2 (e.g., preprocess_input) before feeding images into the model. 4.4) Using a barchart, plot deployment accuracy vs execution time (minutes) of training of all finalized models so far and label each bar with its corresponding model (from perceptron to your recent MobileNet based model). Report your insights. (3 points) 9 MSE 413 – Lab 4 – Neural Networks and Deep Learning This layer is to standardize the input for MobileNetV2 Schematic of the MobileNetV2 based model 5. Object detection : YOLOV5[15%] YOLO (You Only Look Once) is a popular object detection algorithm known for its speed and accuracy. Unlike traditional approaches that rely on region proposal techniques, YOLO frames object detection as a regression problem to directly predict bounding boxes and class probabilities in a single pass through the neural network, making it extremely efficient for real-time applications. In this final part of the assignment, you will use YOLOv5 for a basic object detection workflow on a separate annotated dataset. The first step is image annotation to create input for your YOLO algorithm. 10 MSE 413 – Lab 4 – Neural Networks and Deep Learning As the number of data in your dataset is huge (more than 5,000 training data) and image annotation is a manual task, another dataset containing 200 training images and 40 testing images is uploaded for you, named “Brain_tumor_YOLO”. **Important: Use only the Brain_tumor_YOLO dataset for Task 5. Do not use the classification dataset for YOLO training. 5.1) 5.2) 5.3) 5.4) As the first step you should import YOLO. In this assignment you will work with a moderate version of YOLO, which is YOLOv5. Use the psedocode in the appendix to upload and clone YOLOv5 in your notebook. (1 points) Watch the video in this link to learn how to annotate an image with bounding box for object detection. Now apply these steps to the provided Brain_tumor_YOLO dataset by following the steps below: (6 points) o Upload and annotate the YOLO images class by class, then combine them into one final object detection dataset in Roboflow before export. o Familiarize yourselves with each tumor and its usual location in the brain. If a tumor is not visually distinguishable in an image, do not force a tumor bounding box annotation. Follow the provided instructions for the no tumor class separately. In the end only annotated images will be exported to final step. o After annotating the images of each class, you will be asked to select the share of training, validation, and test. For each class select 85% training and 15% validation. No test selection is needed. o For annotating No tumor class, select the entire brain in the image and tag it as no tumor. Apply this rule consistently for all no tumor images used in the annotation task. o In the final step of creating your annotated dataset, click on Generate in roboflow and the followings: ✓ For preprocessing Let it be on Auto orient. Change the resize adjustments to the size of your own image. ✓ Add these augmentations to your dataset. Flip horizontal, Flip vertical, 90° rotation, ±15° rotation, ±20% brightness, 2.5 pixel blur , 0.85% noise. ✓ Click on create and go to the versions tab. o Export your dataset: Format YOLOv5 PyTorch, and chose show download code. Copy and paste the code in your notebook and run it! Use the psedocode of yolo training in the appendix to execute the algorithm on your data. Make sure that the correct path to the data.yaml file is used in your YOLOv5 training command. (1 points) In no more than one paragraph, explain what mAP50 means in the context of YOLO object detection. (2 points) 11 MSE 413 – Lab 4 – Neural Networks and Deep Learning 5.5) 5.6) Use the YOLO testing pseudocode in the appendix to run detection separately on each test class folder. You should perform 4 separate detection runs, one for each class folder. (3 points) At the end of test, the path to the annotated images by the trained algorithm will be provided to you( as Results saved to runs/detect/exp ). Choose one result image from each class at your own discretion and include it in your report and show the result of your model’s annotation. (2 points) Sample output Appendix A Data split 12 MSE 413 – Lab 4 – Neural Networks and Deep Learning Memory optimizer Cloning YOLOv5 YOLO training YOLO testing Recommended workflow: Complete the assignment in order. First perform data exploration, then train the perceptron baseline, then the ANN models, then the CNN models, and finally the YOLOv5 object detection task. Keep your notebook clearly sectioned and save important outputs as you progress. 13 MSE 413 – Lab 4 – Neural Networks and Deep Learning Appendix B – Guided Implementation Hints This appendix provides general guidance and code structure. These are not full solutions. You are expected to load the dataset using TensorFlow utilities. Hints: • Make sure your dataset is organized into class folders. • Each subfolder should represent one class. • image_size should be consistent across all tasks. To understand your data, inspect one batch: Hints: • images.shape → gives batch size, height, width, channels • Check if images are RGB (3 channels) or grayscale (1 channel) You may need to extract part of the dataset: • take() selects a portion of batches • Make sure subset sizes are reasonable 14 MSE 413 – Lab 4 – Neural Networks and Deep Learning Converting Dataset to NumPy (for Perceptron) Hints: • Perceptron models require NumPy arrays • TensorFlow datasets must be converted Training a Perceptron Hints: • Use OneVsRestClassifier for multi-class classification • Perceptron alone is binary Evaluating Performance Hints: • Use average='weighted' for multi-class metrics • Report all required metrics 15 MSE 413 – Lab 4 – Neural Networks and Deep Learning Building an ANN Model (General Structure) Hints: • Use Flatten() to convert images to vectors • Hidden layer sizes should match assignment instructions • Output layer size = number of classes Compiling the ANN Hints: • Follow assignment for optimizer and loss • Use sparse categorical crossentropy for multi-class 16 MSE 413 – Lab 4 – Neural Networks and Deep Learning Training the ANN Hints: • Track both training and validation accuracy • Use validation set to detect overfitting Adding Dropout Hints: • Add dropout before output layer • Use value between 0 and 1 • Helps reduce overfitting CNN Model (General Idea) Hints: • CNNs take image inputs directly (no manual flatten at start) • Use Conv → Pool pattern • Number of filters and layers should follow assignment 17 MSE 413 – Lab 4 – Neural Networks and Deep Learning Transfer Learning (MobileNetV2) Hints: • Use pretrained weights • Input shape must match your dataset Freezing Layers Hints: • Freeze most layers • Keep last few layers trainable Building Transfer Learning Model Hints: • Add custom layers on top of base model • Do not modify base architecture YOLOv5 – General Workflow Hints: • Clone YOLOv5 repository then Install required dependencies and Use Roboflow export code YOLO Dataset 18 MSE 413 – Lab 4 – Neural Networks and Deep Learning Hints: • Use ONLY Brain_tumor_YOLO dataset • Do not mix with classification dataset YOLO Training Hints: • Training requires a data.yaml file • Check correct dataset path • Training may take time depending on hardware YOLO Testing Hints: • Results saved automatically • Check runs/detect/exp directory • Use output images for report Final Note This appendix is designed to guide your implementation. You are expected to: • understand each step • adapt the code to your assignment requirements • organize your notebook clearly Avoid copying blindly. Focus on understanding the workflow and applying it correctly. Submitting your Assignment The assignment must be submitted online at Canvas with the following structure: For this assignment you should submit one zipped folder that contains: 1. A report- The assignment report must be in PDF format, called report.pdf. This report must contain all the figures and discussions/explanations for the questions. 2. An .ipynb file that contains all your codes. Submit one notebook file named Assignment4.ipynb. Your notebook should be clearly sectioned by task, contain the code used for all required parts, and include enough output to show your final results. 19
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )