Full text
Degree Project in Computer Science First cycle 15 credits Designing Convolutional Neural Networks for Classification of Metastatic Tissue in the Lymph Nodes Evaluation of the Effect of Feature Map Distributions Across Convolutional Layers on Network Performance PERE GINEBRA SOLANELLAS Stockholm, Sweden 2022
Degree Project in Computer Science Author: Pere Ginebra Solanellas Supervisor: Kevin Smith Examiner: Pawel Herman Date: June 2022 KTH - School of Electrical Engineering and Computer Science
1 Abstract Cancer is one of the leading causes of mortality in the world. It is estimated that about 20% of males and 17% of females will suffer it at some point in their lives, while 13% of males and 9% of females will die from it [1]. Cancer is caused by abnormal cell growth which can spread through the body in a process called metastasis. One of the ways to diagnose and evaluate the severity of cancer is to analyse the lymph nodes for presence of metastatic tissue. Recently, Artificial Neural Networks (ANNs) have been used to aid the detection of such tissue in images, but there are many design decisions to consider in making a network for this task. One of the most important design decisions when developing an ANN is the choice of the network, as this will define how the model will evaluate patterns from the input. Convolutional Neural Networks are the main ANN architecture used for image analysis, as these use filters to evaluate how prevalent different shapes or patterns are in an image. My research has studied how different ways of using these filters affects lymph node image classification results. From the worst to best performing models tested, there is a 0.0739 accuracy gap (from 0.8494 to 0.9234), representing an 8.709% increase in performance. Within models of the same size in terms of number of patterns analysed, there are gaps of up to 0.035 accuracy. My research has found network size to be closely related to training time, although different designs have different training complexities, so a case can be made for models of a same size that perform worse but also train faster. The main conclusion of this project is that the way features are extracted from lymph node images in a Neural Network clearly affect its performance, but also its training complexity. With this knowledge, one can test different approaches and designs according to their requirements and resources.
2 Sammanfattning Cancer är en av de främsta dödsorsakerna i världen. Man uppskattar att cirka 20% av männen och 17% av kvinnorna kommer att drabbas någon gång under sitt liv, medan 13% av männen och 9% av kvinnorna kommer att dö av cancer [1]. Cancer orsakas av onormal celltillväxt som kan spridas i kroppen i en process som kallas metastasering. Ett av sätten att diagnostisera och bedöma cancerens svårighetsgrad är att analysera lymfkörtlarna för att se om det finns metastaserande vävnad. På senare tid har artificiella neurala nätverk (ANN) använts för att underlätta upptäckten av sådan vävnad i bilder, men det finns många konstruktionsbeslut att ta hänsyn till när man gör ett nätverk för denna uppgift. Ett av de viktigaste besluten när man utvecklar ett ANN är valet av nätverk, eftersom detta kommer att definiera hur modellen kommer att utvärdera mönster från inmatningen. Konvolutionella neurala nätverk är den vanligaste ANN-arkitekturen som används för bildanalys, eftersom dessa använder filter för att utvärdera hur vanligt förekommande olika former eller mönster är i en bild. I min forskning har jag studerat hur olika sätt att använda dessa filter påverkar resultaten av klassificeringen av lymfkörtelbilder. Från de sämsta till de bäst presterande modellerna som testats finns det en skillnad i noggrannhet på 0,0739 (från 0,8494 till 0,9234), vilket motsvarar en ökning av prestanda med 8,709 %. Inom modeller av samma storlek när det gäller antalet analyserade mönster finns det skillnader på upp till 0,035 noggrannhet. Min forskning har visat att nätverksstorlek är nära relaterad till träningstid, även om olika konstruktioner har olika träningskomplexitet, så det går att argumentera för att modeller av samma storlek presterar sämre men också tränas snabbare. Den viktigaste slutsatsen av det här projektet är att det sätt på vilket funktionerna extraheras från bilder av lymfkörtlar i ett neuralt nätverk tydligt påverkar dess prestanda, men också dess träningskomplexitet. Med denna kunskap kan man testa olika tillvägagångssätt och konstruktioner utifrån sina krav och resurser.
3 Contents 1. Introduction ........................................................................................................................ 4 1.1. Research Question ....................................................................................................... 4 1.2. Approach ..................................................................................................................... 5 1.3. Scope ........................................................................................................................... 5 2. Background ........................................................................................................................ 6 2.1. Artificial Neural Networks and architectures.............................................................. 6 2.2. Convolutional Neural Networks.................................................................................. 7 3. Method ................................................................................................................................ 9 3.1. Dataset ......................................................................................................................... 9 3.2. Approach ..................................................................................................................... 9 3.3. The architecture ......................................................................................................... 10 3.4. Experiment design ..................................................................................................... 13 3.5. Model training ........................................................................................................... 14 3.6. Metrics ....................................................................................................................... 14 4. Results ............................................................................................................................... 16 4.1. Classification accuracy .............................................................................................. 16 4.2. AUC score ................................................................................................................. 18 4.3. Training progression ................................................................................................. 19 4.4. Training time ............................................................................................................. 21 5. Discussion .......................................................................................................................... 23 5.1. Number of features .................................................................................................... 23 5.2. Number of layers ....................................................................................................... 23 5.3. Distribution of features.............................................................................................. 24 5.4. Limitations ................................................................................................................ 25 6. Conclusion ........................................................................................................................ 26 6.1. Conclusion ................................................................................................................. 26 6.2. Future work ............................................................................................................... 26 7. Appendix ........................................................................................................................... 28 8. Bibliography ..................................................................................................................... 29
4 Chapter 1 Introduction Artificial Neural Networks (ANNs) are machine learning algorithms based on the biological neural networks in our brain. The amount of research that has gone into these has increased during the last decade due to their capacity to recognize patterns in many types of data, but the field still has a lot of developments to be made [2]. One of the multiple problems that ANNs have been used for is computer vision, with various models being developed to detect and classify elements in an image. For this, data scientists design networks of neurons that will each learn a small pattern of the data to analyze, but there are no set rules that define the best design for a task. Therefore, scientists must test different designs in order to find the one that gives the best results for the specific problem [3][4]. Convolutional Neural Networks (CNNs) are a subset of ANNs used for multi-dimensional data types with spatially related data points [5][6]. The most common example of this is images [6][7], as they are represented by matrices of pixels, which store position in 2 or 3 dimensions that would be destroyed by flattening. CNNs recognize images by detecting patterns within them known as features. This project analyzes the classification performance of CNNs in relation to the number of patterns they evaluate and their complexity. For this purpose, the Patch Camelyon (PCam) dataset [8][9] is used, which consists of segments of images from histopathological scans of lymph node sections. Each image is labeled according to the presence of metastatic tissue in the center of the image. Detecting this tissue in the lymph node is key to diagnosing and determining the severity of cancer. 1.1. Research Question This thesis studies the effect of some architecture design decisions on the results of ANNs. More specifically, the number of feature maps and their distribution across convolutional layers in a Convolutional Neural Network (CNN) is analyzed. With this I aim to answer the question: How does the distribution of feature maps in a convolutional neural network’s architecture affect its image classification results?
5 My main hypothesis is that deeper and larger networks generally perform better, as has been found in the past; this observation has given way to the term Deep Learning which is commonly used to refer to ANNs with multiple layers [5]. Apart from this, the little existing research on the effect of using different distributions of feature maps did not allow me to make more claims on the outcome of the study. 1.2. Approach This project analyzes the results of architectures with different shapes and sizes in respect to the number of features extracted in each layer. This has been done by first designing a base architecture and framework using PyTorch and Jupyter notebooks allowing for easy iteration, modification and training of each specific architecture design. The results of all these architectures are compared by recording the validation accuracy, precision, recall and f1 scores of each epoch during training, and the same metrics as well as the ROC AUC score over a test dataset with the fully trained model after a set number of epochs. 1.3. Scope The scope of this project is defined by the number of different architectures tested and their maximum sizes. These are limited by the available computing power and time to complete the project. With unlimited resources one could test a broader number of designs of bigger potential sizes and even test them with different hyperparameters and multiple datasets to obtain observations that are easier to extrapolate. Since this is not the case, experimentation has been restrained to 5 different types of architecture with 9 different size variations in hopes of exploring a wide enough range of designs to provide meaningful insight to the topic. Following this, each of these 45 unique architectures has been trained 5 times, resulting in 225 total models and over 150 hours of total training time on a mobile GPU in a laptop (RTX 2060 Max-Q). The same hyperparameters are used for all tests and only the Patch Camelyon image dataset is used, as previously mentioned.
6 Chapter 2 Background 2.1. Artificial Neural Networks and architectures The field of Machine Learning studies algorithms that can improve or “learn” over time. One subset of these algorithms is Artificial Neural Networks (ANNs), which are inspired by neurons in the brain, as they also consist of interconnected groups of nodes. Feedforward Neural Networks (FNNs) are a very popular and simplified version of ANNs. These networks are made up of layers of neurons, the first being the input layer, the last being the output, and the rest the hidden layers. Each layer takes the previous one as input, so every neuron takes the output of a set of neurons in the previous layer and computes a weighted sum with them, and sometimes also applies a function (activation function) before passing the result as output. These weights represent a pattern of the input, and by adjusting them a set of patterns that best describes the data being analyzed can be found. So, each layer of N neurons learns to identify the contents of the previous one using N different characteristics/patterns observed from it. When layers are chained one after the other, the resulting models can identify the original inputs by evaluating if they follow the patterns that they have learned to recognize by optimizing their weights. The term ‘architecture’ in ANNs refers to the design of the network. This design takes into account: how many layers it has in total, or the size/depth of the network; how many neurons make up each layer, or the size/width of the layer; and the type of neurons/layers used. Architecture design plays a big role in defining a model that delivers the desired results. It has been commonly observed that deeper architectures, that is, with more layers, tend to find better patterns to recognize their input datasets [5]. However, given too many layers, these patterns adjust too well to the input and therefore do not recognize new occurrences as well (a problem known as overfitting) [2]. Deep architectures also take a longer time to train, especially when working with big datasets and inputs such as images. For this reason, finding an architecture that suits the user’s needs and resources is a lengthy and often tedious process that requires a lot of testing and analysis of results. For now, all we have are general guidelines for finding a good network [10], such as starting small and building up while
7 carefully analyzing and keeping track of results to avoid common problems such as overfitting. 2.2. Convolutional Neural Networks Convolutional Neural Networks (CNNs) are a subset of ANNs, and more specifically FNNs, used for data types where data points are spatially related, especially when this space they are located in is not one dimensional [5][6]. The reason for this is that they work with groups of neighboring data points to evaluate patterns instead of using them individually. This process takes place in the convolutional layers of the CNN architecture. In the case of standard CNNs for image classification, convolutional layers apply a set of 2 dimensional filters to their input in a sliding window style to generate an output feature map. Each filter represents a pattern, and the convolutional layer calculates how present that pattern is in each window of the input image/feature map it receives. This is done by multiplying the values of the filter with those of the window of pixels being analysed and then adding all the values of the resulting matrix into one, which represents the resemblance between that window and the feature on the filter. In this case, the weights being optimized by training the model are the values in each filter’s matrix, which define what pattern they evaluate. An illustration of this kind of architecture can be seen in Figure 1. Figure 1. Basic CNN architecture. Source: MathWorks Multiple patterns can be evaluated within one single convolutional layer by simply applying multiple filters individually to the input. Each filter results in a new feature map that stores how present a pattern is in each position of the map, so the dimension of the output of a convolutional layer depends on the number of features it finds (number of filters x size of feature maps). The number of filters applied in a layer can be considered the number of
14 Feature maps after each convolutional layer Shape Flat Up Down Hill Valley Layer 1 57 11 102 21 88 2 57 23 91 41 71 3 57 34 80 61 53 4 57 46 68 82 35 5 57 57 57 102 18 6 57 68 46 82 35 7 57 80 34 61 53 8 57 91 23 41 71 9 57 102 11 21 88 Total Features Extracted: 513 512 512 512 512 Table 1. Example distribution of 512 features across 9 layers in each architecture design. Each cell represents the number of feature maps generated by each convolutional layer in a specific design. 3.5. Model training To compare the results of all these architectures, each is trained and tested 5 times to reduce variability, and as mentioned earlier, metrics are stored during the training and after testing. The parameters used for training all the models - batch size of 64, learning rate of 0.0005, 30 epochs and the Adam optimizer [11] – have been selected after manually experimenting with different combinations and architectures to ensure the best possible results for all models while also making sure that most architectures can train in a reasonable amount of time. A lower batch size usually results in better generalization but also makes it computationally harder to train [9]; when using a 32 image batch results are slightly better (up to ~1% increase in accuracy) but 64 is significantly faster (upwards of 10%). A lower learning rate tends to be able to reach better accuracy but also takes more epochs to do so [2]; a rate of 0.001 is a good place to start testing, but in this case it often fails to train on some models, so 0.0005 is the chosen rate to get faster results than 0.0001. Finally, with this combination of parameters, 30 epochs are where most the tested models reach a peak in accuracy. 3.6. Metrics The metrics used to compare models in this project are: - Accuracy: the percentage of correct predictions. Calculated as: 𝑎𝑐𝑐𝑢𝑟𝑎𝑐𝑦 = 𝑐𝑜𝑟𝑟𝑒𝑐𝑡𝑝𝑟𝑒𝑑𝑖𝑐𝑡𝑖𝑜𝑛𝑠 𝑡𝑜𝑡𝑎𝑙𝑝𝑟𝑒𝑑𝑖𝑐𝑡𝑖𝑜𝑛𝑠
15 - AUC ROC: the Receiver Operator Characteristic (ROC) curve is a plot that represents the performance of a binary classifier in relation to its discrimination threshold. It is defined by plotting the true positive rate against the false positive rate of multiple discrimination thresholds. The area under said curve (AUC) can be used as a classification score, an AUC of 1 represents a perfect classifier which predicts 100% correctly with every threshold, while an AUC of 0.5 represents a random classifier. It gives a more insightful classification score by evaluating how well the model discriminates between classes, as predicting something to be of class A with a certainty of 0.55 is not the same as doing it with 0.9 certainty. Other basic metrics like average total accuracy, average accuracy per epoch, average accuracy per second of training, total training time, etc., are used.
16 Chapter 4 Results 4.1. Classification accuracy The classification accuracy of each model over the test dataset has been used to evaluate the effect of each design decision on a network’s performance. As seen in Figure 6, some models have an accuracy of exactly 0.5928. This value is the ratio of class imbalance in the dataset, which means that these models predict the same class (negative) for every input. This happens due to the complexity of some of the architectures, especially the ones with the most feature maps, which sometimes fail to train. Figure 6. Test accuracy of each trained model. Each graph contains models with the same architecture width and groups them by their architecture depth. Looking at the average accuracy per architecture type and size in Figure 7, the models that are affected by this can be seen more clearly, as they have averages around or under 0.85. All distribution designs have problems when training on 512 feature maps, especially with 9 layers, where all of them except flat fail to train at least once.
17 Figure 7. Average test accuracy of each unique architecture design’s 5 tested models. Each graph contains models with the same architecture width and groups them by their architecture depth. Removing the untrained models in Figure 8, the trained models’ results become more clear. The first observation we can make is that in this case having 6 layers is the best option, 3 layer networks perform the worst and lose accuracy when increasing the number of feature maps, and 9 layers underperforms 3 in networks with 128 feature maps but is closer to 6 with 256 and 512. Increasing the number of features generally brings better results in the networks with more than 3 convolutional layers. Focusing on the performance of each individual distribution shape, a clear best performer cannot be identified. However, some observations can be made. For instance, up and valley are all around the worst performers, flat generally gets slightly higher accuracies and tends to be more consistent in the models with more features, and down can get the best results but is more inconsistent and fails to train more often. For more detailed information on the distribution of scores for each unique architecture, refer to Table 2 in the appendix.
18 Figure 8. Test accuracy of each tested model, excluding those with accuracies under 0.6 (untrained). Each graph contains models with the same architecture width and groups them by their architecture depth. 4.2. AUC score As mentioned earlier, the area under the ROC curve gives more insight into how well a model performs classification by including prediction confidence into the score by using discrimination thresholds. This can be observed in Figure 9, as not all the models that did not train correctly have the same score. This is probably because even though they predict the same label for all images, each model’s certainty of the chosen label might be different due to weight variations from the training process. Figure 9. Test ROC AUC score of all trained models. Each graph contains models with the same architecture width and groups them by their architecture depth.
19 By not including the models with scores under 0.8 out of the plot in Figure 10, some new observations can be made about the trained models. The down architectures show worse results with the parameters they were performing the best in terms of accuracy. Other models like valley, which got some of the worst accuracies, seem to do slightly better when comparing AUC scores, which might indicate that they are more confident on their correct classifications and less on their incorrect ones. Focusing on number of layers, the disparity in this score is smaller between the 3 groups compared to when using accuracy. More specifically, some models with 3 layers and 128 features sometimes match or even outperform their higher layer count versions, when they underperformed in terms of accuracy. Figure 10. Test ROC AUC scores, excluding models with a score under 0.8. Each graph contains models with the same architecture width and groups them by their architecture depth. For more detailed information on the distribution of scores for each unique architecture, refer to Table 2 in the appendix. 4.3. Training progression Figure 11 represents the average validation accuracy of each architecture after every epoch of training. This gives us an indication of how fast each model converges to its maximum accuracy: models with 3 layers approach their peak at around 15 epochs, models with 6 layers start slowing down at around 20-25 epochs and the 9-layer models continue improving in accuracy even past 25.
20 There is not much difference in epoch training progression between different architecture designs within a set of size parameters. Only slight offsets and models that reach their plateau earlier than others can be observed. For example, the up model, which seems to be the worst performing in terms of accuracy is slightly behind with every epoch of training and even reaches its peak a bit earlier on some models but does not show many other differences in terms of progression. Figure 11. Average validation accuracy per epoch of each unique architecture design. Each graph represents architectures of the same size.
21 4.4. Training time The total training time of models is more constant for each unique architecture than other metrics and offers easier to interpret results. There is a clear relationship between the total feature maps extracted in an architecture and the time it takes to train. Moreover, the number of layers on an architecture affects each design differently, some increase in training time when more layers are added to the network while others train the longest at 6 layers. Focusing on individual designs, up is the design that trains the fastest in most cases, especially on bigger models. Furthermore, flat is the next to train faster all around, except in some models with 512 feature maps. Finally, down tends to be the hardest to train, made clear in larger models, where it can take more than twice as long to train compared to other designs with the same number of features. Figure 12. Training time of every model. Each graph contains models with the same architecture width and groups them by their architecture depth. This can be put into context by comparing the average validation accuracy per second of training of every model in Figure 13. Firstly, given the same amount of time for training, some models outperform others that they do not with a set number of epochs. Specifically, the up models outperform a lot of other models by the time they complete 30 epochs, as they do so in a shorter amount of time; the flat models follow a similar trend but sometimes also perform better than other fully trained models that train for a longer time.
22 Figure 13. Average validation accuracy per second of each unique architecture design, excluding models with an accuracy score under 0.6. Each graph represents architectures of the same size. These differences could be due to the fact that the resolution of feature maps gets lowered with each pooling layer; so, feature maps in the last layers are easier to extract than feature maps in the earlier ones.
23 Chapter 5 Discussion This project does not seek to find the best architecture to solve the lymph node image classification problem, as well-known architectures like AlexNet [13], VGG [14], GoogleNet [15] or ResNet [16] have already been applied to this task [17][18][19]. Instead, the goal was to see how specific design decisions affect image classification in this dataset. Nevertheless, for the sake of comparison, the best architectures designed for this project approach or even match the 92-98% accuracy range of the well-known solutions, as seen in Table 2 in the Appendix. From this we can say that even though they were developed to be simple to easily reflect changes in their design, these architectures still perform well relative to architectures considered state-of-the-art until recently (all developed between 2012 and 2015) and can therefore offer meaningful insight on design decisions. 5.1. Number of features From the results obtained in this study, it appears that extracting more features translates into higher accuracy, as long as the architecture has enough layers to support them. The only models that do not perform better when increasing total number of feature maps are the ones with 3 layers, and even then, the difference in performance is not very significant (up to -2% variation between the same model with 128 and 512 features). However, increasing the number of features also increases the training complexity of a model significantly, so it takes longer to achieve said results. 5.2. Number of layers There is a limit to how many layers you can use with a certain number of features before you start losing accuracy, contrary to my original hypothesis that more layers would result in higher accuracy. It seems that extracting a small number of features per convolutional layer may hinder performance, or there might be a limit to the usefulness of stacking convolutions, an idea that has been explored in the development of newer architectures like ResNet [16]. The cause of this could be explored by testing architectures with more than 512 total feature
30 [17] Y. Sun, F. A. Binti Hamzah and B. Mochizuki, "Optimized Light-Weight Convolutional Neural Networks for Histopathologic Cancer Detection," 2020 IEEE 2nd Global Conference on Life Sciences and Technologies (LifeTech), 2020, pp. 11-14, doi: 10.1109/LifeTech48969.2020.1570619224. [18] C. Vo-Le, N. H. Son, P. Van Muoi and N. H. Phuong, "Breast Cancer Detection from Histopathological Biopsy Images Using Transfer Learning," 2020 IEEE Eighth International Conference on Communications and Electronics (ICCE), 2021, pp. 408-412, doi: 10.1109/ICCE48956.2021.9352069. [19] Wang, Dayong, Aditya Khosla, Rishab Gargeya, Humayun Irshad, and Andrew H. Beck. "Deep learning for identifying metastatic breast cancer." arXiv:1606.05718
TRITA – XXX-XXX 20XX:XX www.kth.se