Full text
MASTER THESIS TITLE: Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs MASTER DEGREE: Master's degree in Applied Telecommunications and Engineering Management (MASTEAM) AUTHOR: Alexis Nevot Ezpeleta ADVISOR: Francesc Tarrés Ruiz DATE: July, 6th 2020
Title: Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs Author: Alexis Nevot Ezpeleta Advisor: Francesc Tarrés Ruiz Date: July 06, 2020 Abstract This project has studied an unusual topic on image recognition and classification that can have numerous utilities on multimedia content. The approach studied on this project has been scenes recognition on TV news programs, which is a good starting point to distinguish scenes on visual content displayed on TV. The work in this project can be the first steps to segment scenes on movies, series, documentaries, etc… The methodology used to build a program capable to recognise and classify images is Deep Learning, a subset of Machine Learning based on artificial neural networks that learn from representations of data obtained after performing some operations on the input images. As in Machine Learning, a training process with multiple example outputs is necessary to make the system capable to figure out the rules to obtain those outputs (categories) from the given inputs (frames). To build an image recognition system, the most suitable framework (previous comparison has been made between some of them) has been installed to code the operations that lead to the image classification and the results to evaluate its performance. Another important part to complete this project is the data collection and management, the data volume has to be large and diverse in order to increase the number and type of patterns or features learnt from the representations, and therefore, to increase the system’s capability to generalize. It also has to be managed properly, in order to not difficult the learning process with additional, human errors. The last part of this project consists on training the classifier in the different architectures, check which input parameters lead to the best performance and compare the results to decide which of them is the most appropriate to classify TV news program images. After the training is finished, the system must be tested with never-seen data in order to check its real performance and obtain a proper evaluation.
CONTENTS INTRODUCTION ................................................................................................ 1 CHAPTER 1. CONVOLUTIONAL NEURAL NETWORKS ................................ 3 1.1. Deep Learning and architecture overview ...................................................................... 3 1.1.1. Convolution operation layer .................................................................................... 4 1.1.2. Max Pooling operation layer ................................................................................... 5 1.1.4. Flatten layer ............................................................................................................ 6 1.1.4. Loss function and optimizer .................................................................................... 7 1.1.5. Activation functions in neurons ............................................................................... 8 1.2. Convolutional Neural Networks background ................................................................. 9 1.2.1. GPU (Graphical Processing Unit) ......................................................................... 10 1.2.2. ImageNet database .............................................................................................. 11 CHAPTER 2. KERAS – DEVELOPMENT TOOLS .................................................................... 13 2.1 Keras, TensorFlow, PyTorch and Caffe comparison ................................................... 13 2.2 Building the CNN ............................................................................................................. 14 2.1.2. Loading pre-trained architectures ......................................................................... 15 2.2.2 Adding classifier on top of architectures ............................................................... 15 2.2.3. Generating data to CNN from original input images............................................. 16 2.2.4. Compiling and training the model ......................................................................... 16 2.2.5. Generating predictions ......................................................................................... 17 2.1. Loss function and learning algorithms ......................................................................... 17 2.3.1. Loss Function ....................................................................................................... 18 2.3.2. Learning algorithm (SGD) ..................................................................................... 18 2.4. Optimizers ........................................................................................................................ 19 2.4.1. SGD with Momentum ........................................................................................... 19 2.4.2. RMSprop ............................................................................................................... 19 2.4.3. ADAM (Adaptive Moment estimation) .................................................................. 20 2.5. Used CNN architectures ................................................................................................. 21 2.5.1. VGG Net ............................................................................................................... 21 2.5.2. GoogLeNet Inception module ............................................................................... 22 2.5.3. XCEPTION ........................................................................................................... 23 CHAPTER 3. BUILDING THE DATASET ........................................................ 25 3.1. Obtaining videos.............................................................................................................. 25 3.1.1. From deferred programs: Video on Demand ........................................................ 25 3.1.2. Live streaming: Personal Video Recorder (PVR) ................................................. 26 3.1.3. Videos’ properties ................................................................................................. 27 3.2. From videos to frames – FFMPEG ................................................................................. 28 3.2.1 FFMPEG syntax ................................................................................................... 29 3.2.2. Naming frames ..................................................................................................... 29 3.3. Frames’ classification ..................................................................................................... 30 3.3.1. Data management ................................................................................................ 31
CHAPTER 4. TRAINING AND RESULTS ....................................................... 34 4.1. Results for architecture VGG16 ..................................................................................... 34 4.2. Results for architecture VGG19 ..................................................................................... 34 4.3. Results for Inception V3 ................................................................................................. 35 4.4. Results for Xception ........................................................................................................ 35 CONCLUSIONS ............................................................................................... 38 REFERENCES ................................................................................................. 41 Annexes ...................................................................................................................................... 43
Introduction 1 INTRODUCTION This project’s objective is to classify images, in particular, frames belonging to TV news programs. The approach performed in this project could be the first step in multimedia applications, to provide the capability to search specific scenes in multimedia content. The methodology used for that purpose is Deep Learning, which is a subset of Machine Learning and AI. DL has similarities with ML in terms of learning rules, a new programming paradigm that suits perfect to automate known tasks, but the difference is that DL is a methodology capable to learn the features coming from the representations obtained in the Convolutional Neural Networks, a very effective tool to recognise and classify images. Its current hype is increasing its popularity, attracting the interest of more people that introduce new topics susceptible to use image classification thanks to the possibility of transferring the learning obtained with high-performance equipment capable to compete on image recognition challenges. The first step is to obtain the necessary number of frames to train (learning process) the system that performs the classifications. With the collection of a data set, the next step is to build a system that, after the training process, is capable to classify the frames corresponding to the provided categories. To use the functionalities of the Convolutional Neural Networks, a DL framework must be installed in order to load all the images, do the training process and obtain the classification results. The choice of the framework is subjective and normally it depends on which is the most suitable for the user, and for that reason a comparison of different frameworks has been made on the second chapter of this project. Apart from the frameworks, a common element in frameworks has been compared: the optimizer, which is important to minimize errors during the classification task. The architectures used to do the classifications are also explained in Chapter 2. After collecting enough videos of the newscasts with the methods explained on chapter 3, these videos have been sliced into frames to build the dataset. Once the dataset is built, and, in order to maximize the system’s accuracy, the frames have been properly tagged with their corresponding categories, ensuring not additional, human errors worsen the classification results. Usually, not all frames will be correctly classified, reason for which is necessary to prepare properly the data and add some functions to maximize the effectiveness of the training process. To improve the system’s performance, some techniques in Convolutional Neural Networks that have proved to be effective will be used to overcome the problem of using a small dataset, which is the case of this project. With the data collected, the system can begin the training and display the results: In the first place, the validation results with known data will give an idea of how accurate is the system and the overall error during the classification, and the last evaluation, which consists on classification of never-seen data will reveal how efficient is the classifier. The validation results allow to tune some input
2 Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs parameters with the objective of improving the results in classifications (validation and test). The results obtained in this work are the best that the dataset and the training parameters allow. The results obtained with the tested architectures show that the results, and therefore, the generalization ability is better with shallow architectures, as stated by the Occam’s razor principle[1]. The structure of this work is described here: Chapter 1 explains the corresponding field that contains the methods to analyse the images and get the representations from which it can perform the classifications. Chapter 2 is focused on the environments from which image recognition and classification can be performed, explains which functions have been used, some of the available optimizers and the description of the architectures used to do the classifications. Chapter 3 explains how the videos of the TV news programs are obtained, and from these videos, the frames to build the dataset to train the system, along with the proper management that sorts the data to ensure we obtain the expected results from the classification task. Chapter 4 shows and explains the results obtained after using the different architectures coming from the ILSVRC contest.
Convolutional Neural Networks 3 CHAPTER 1. CONVOLUTIONAL NEURAL NETWORKS This chapter explains the general architecture of a Convolutional Neural Network (CNN), its functions and the background that compose the full system that takes as input the images of the dataset and performs the classification. First of all, we explain the methodology used to build the system: Deep Learning (DL) and how this methodology has been used in this project to reach its main goal. The next section explains the set of operations that compose the core of DL because this part comprises some concepts of Artificial Intelligence (AI) and the way the system learns. The last section explains the DL background in terms of hardware and programming, the evolution of programming paradigm and some recent history of DL, topic used to introduce the architectures used in this project that will be explained extensively in Chapter 2. 1.1. Deep Learning and architecture overview The goal of this project is to build a system capable to classify different types of scenes in TV News Programs, those taken at the TV studio and those taken from video reports. We will call these frames simply as studio and non-studio frames. One of the most popular methodologies to classify and recognise images is Deep Learning (DL). Today, most Deep Learning architectures for image recognition are based on Convolutional Neural Networks (CNN) to learn representations of data at different levels of abstraction. Actually, the depth in a neural network is related to the number of layers used to represent the information of the image at different levels of detail. In general, first layers represent a low-level abstraction of the original image such as lines, corners, edges, etc.; higher layers usually represent higher-level interactions between images’ objects. NN name comes as reference to neurobiology despite there is no evidence that the human brain has a similar learning method [2]. Despite DL has achieved more breakthroughs apart from image recognition and classification, these will not be commented here because they are not in focus within this project. Before going into details about CNNs, an architecture overview is shown to provide a bird’s eye-view [3]. In general, CNNs stack these layers to conform the next structure: Input: The incoming information that handles this layer are pixel values of the image with the three colour channels RGB. Convolution: These layers compute the output of neurons connected to local regions in the input or other layers. MaxPooling: Necessary to downsample extracted images after convolutions for computational reasons. Fully Connected (FC): Required layer to perform the classification, with a neuron per class.
4 Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs Another layer is necessary first to convert the convolution format to the FC in order to get the classifications, the flatten layer, explained in section 1.1.4. The elements to describe in neural networks are listed here: The layers and the combination of these to create the network. The input data: Original input images to classify. The Loss function: Feedback about predicted and real categories. Optimizer: Determines the algorithm for adapting the parameters in the learning procedure. 1.1.1. Convolution operation layer In order to recognise features in images, each layer extracts many representations (also called feature maps, from now on, the word feature map can mean either the original input image or a feature map) from a single input image by sliding convolutional filters (also called kernels) across its width and height. From a single input image, a feature map per filter is obtained, and to bring some clarity, a main parameter in convolution layers is the number of filters to apply, in the case, using 64 filters will output 64 feature maps, different with each other, from a single convolution layer. Filters are small matrixes with values (weights) designed to detect objects, features, shapes[4]… that are used in Image processing to sharpen, detect edges, blur images, estimate vertical contours… The size of these filters is usually 3x3, 5x5 pixels, this feature allows learning patterns in any position of the image, thanks to the values of the filters’ weights, and depending on the image dimension, the filter size may cause a dimension reduction on feature maps during successive convolutions due to border effects [2]. This way of learning reduces the number of total weights, which means as well a reduction of the number of parameters to process, and therefore, the number of necessary images to learn. Fig 1.1 Example of convolution operation on number 4 (MNIST database)
Convolutional Neural Networks 5 In the previous example about convolution, there are filters sliding throughout the image with their pre-set values and indications about which features of the image are being learnt. To provide information about filters and their use, an example is shown: Fig 1.2 Example of filtered grey image Computationally speaking, an image is a grid of pixels, which values ranges from 0 to 255 in three channels corresponding to the RGB model, but before managing values on that range, these will be first normalized between 0 and 1 for convenience during the processes yet to come. The filters slide over the image carrying out an element-wise product and sum of the filter matrix with the part of the input it is currently on (see [4]). Each layer applies multiple filters with initial small random values of their weights [5], so the output will be far from expected, but with every example processed the weights are adjusted a little in the right direction, reducing loss score, a term that will be explained in section 1.1.3. These weights are adjusted gradually depending on a feedback signal in order to minimize the Loss function, which is the main objective of the learning process, also called training, a mechanism that makes Machine Learning and Deep Learning systems capable to distinguish and classify information. 1.1.2. Max Pooling operation layer This operation has the main objective of downsampling the feature maps. To avoid that downsampling may introduce a loss in significant information, it is convenient to slide windows over the images and output the maximum value of each channel. This concept is similar to convolution because a window slides throughout all the images to perform the Max Pooling operation (see [6]), but instead of transforming patches via element-wise product, the transformation is carried out by extracting the maximum value of the pixels contained in the Max Pooling window with size 2x2 pixels. The reasons to downsample the images are simple: To reduce the number of coefficients per sample and so, the computational load of the network. Too many coefficients suppose overfitting[7], no ability to generalize when recognising learnt features if these appear with slight differences. To eliminate spatial hierarchy when learning features, this means recognising patterns or features regardless their position and orientation.
12 Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs Fig 1.9 Small overview of ImageNet architectures (Fig. 1.9) shows the winning architectures of all ImageNet challenges over the years as introduction, because most of them will appear in this document as tested architectures to perform the classification task. The equipment used for this project is described in Annex A1 (Hardware specifications).
Keras - Development Tools 13 CHAPTER 2. KERAS – DEVELOPMENT TOOLS This chapter describes the environment used to build the different CNNs in this project, the description explains the code that has made possible obtaining the results of the image classification, but before explaining the environment, the first section here under compares different DL frameworks available to create neural networks. The code to build the network in Python will be detailed, beginning with the load of architectures and ending with the classifications [2]. This comprises creating the models with layers, transforming the original input images into data that can be fed to the CNN, compiling the model, training and finally displaying the results. Despite being in a new programming paradigm, problems that move us further from our objective may arise, but some strategies to cope with them will be explained as well. Different loss functions and optimizers will be explained in detail to analyse which is the most suitable to perform the image classification of this project. Also the different network architectures will be explained and detailed in this chapter, the comparison about the results will be shown and explained in Chapter 4. 2.1 Keras, TensorFlow, PyTorch and Caffe comparison More businesses and companies are moving to the use of AI in order to automate tasks and improve their performance, bringing intelligence to machines thanks to the use of ML and/or DL systems. Depending on the technology they work with and the desired purpose, the choice of the framework to develop the system is crucial. Normally the perfect framework for each case is chosen in function of results, fast business and ease to deploy. In the case of image recognition and classification, the necessary technology has been explained, remaining only the environment in which to build the program that loads images and returns their classification. Four DL frameworks are compared in a table to see in a clear, quick way which are the important features to take into account before beginning to program a full CNN such as API level, ease to code, architecture, debugging, support[13]… Since the four frameworks can perfectly lead to the same objective, it is normal that some functionalities are shared amongst them, as the case of Keras, which has an user friendly API, but doesn’t handle low-level functions, therefore, frameworks with low level API (specifically TensorFlow) have to be installed to provide Keras with these functionalities (the name of this concept is backend). With low-level functions we mean mathematical operations such as generalized Matrix-Matrix multiplication and NN basics such as the element-wise operation in convolutions.
14 Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs Table 2.1. Framework comparison Keras TensorFlow PyTorch Caffee API level High level High & low level Low level Low level Speed Slow For high performance For high performance Fast (1ms / image) Architecture Simple Complex Complex Complex (big networks) Coding Single line code Reduced size of model with high acc. Complex Complicated but extensible Debugging Not frequently needed Difficult Better debugging capabilities Not complicated Support Small community support Backed by community tech companies Stronger community support No commercial support Datasets Small High performance models Large datasets Small and large Popularity High due to its simplicity Highest popularity High Low The main features of these frameworks are exposed in the table and after considering them all, here is the explanation of why the choice for this project has been Keras. The main reason is that it is the perfect framework to begin working with CNNs due to its simple architecture and high level API. This way, pre-trained architectures can be easily loaded to obtain results in short time to check them. Another important feature about Keras is the dataset size: Since it uses TensorFlow as backend, it results to be slow for big sizes, and the dataset of this project has been built from scratch, reason for which is quite difficult to reach sizes of tens of thousands (see ImageNet or OpenImage datasets). Each category trains, validates and tests with 1000 frames per category, but small datasets can be augmented with a technique called Data Augmentation to achieve similar results to big sizes, explained in section 2.2.3. 2.2 Building the CNN This section shows and explains the code used to build the CNNs. The operations explained in Chapter 1 will appear here with the proper parameters to reach the objective, the part of code explained here is the basic code that allows to perform the necessary operations to perform the classification: Load the different architectures Add our own classifier with our categories Load and convert the frames to the proper format Train and validate the model Test the model with predictions of never-seen data
Keras - Development Tools 15 2.1.2. Loading pre-trained architectures Fig 2.1 Convolutional base load This is the part in which the different architectures are loaded in Keras, conv_base will play the role of all architectures tested in this project: VGG16/19, Inception V3 and Xception, it is a common approach for computer vision problems in which datasets are small. By setting weights to ‘imageNet’, we indicate we want to use the networks’ values obtained from the training with multiple GPUs for a long time, using ImageNet dataset. It is also important not to train the whole network, for that, the classifier is removed (include_top=False) and it is necessary to freeze all layers from the pre-trained CNN (layer.trainable = False) as shown on (Fig 2.1). The reason to not use the original classifier from the architecture is to make sure that the representations learnt are specific to our classes and data, which are not as specific as in the pre-trained classifier [2]. All the input images are resized to square shape with height and width values = (224, 224) for all architectures. 2.2.2 Adding classifier on top of architectures Fig 2.2 Classifier added to convolutional base We add this classifier on top of the architectures, which converts the format coming from convolution layers into the proper format to perform the classification. The Dropout layer is to randomly select and deactivate a number of neurons (0.5 factor is to deactivate half of the neurons), leaving the rest of neurons solving the problem. This is one the measures to cope with overfitting, which means a network lacks capability to generalize. [5]. Note that the last layer has one neuron per class, with softmax activation for multiple classes, which will output the probability distribution, selecting the class with the highest probability.
16 Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs 2.2.3. Generating data to CNN from original input images From this point, it is necessary to convert the dataset images, stored in their corresponding folders, into a format that can be fed as input to CNNs. The functionality in Keras able to do that is the ImageDataGenerator class, which requires some arguments depending on the use of the data. Note that the validation and test data will only be converted to the proper format and their pixels value will be rescaled from the interval [0 - 255] to [0-1]. The training data on the other hand, will be augmented with extra arguments on the ImageDataGenerator class to generate additional training data to increase the model’s accuracy with small quantity of data. Data is augmented according to the parameters provided to the generator with ranges of zoom, rotations, flips, displacement (see [14])… This concept is called Data augmentation, which is the second measure to cope with overfitting, by introducing modified frames that seem different from the original frames. Fig 2.3 Converting frames to CNN format 2.2.4. Compiling and training the model With all this preparation, it is the moment to configure an optimizer, a Loss function to minimize and the metrics to measure. Different optimizers have been used in this project are explained in section 2.3. Once the optimizer and the loss function have been compiled, the training and validation process (model.fit) can begin. The duration of this process depends on the number of epochs, it must be high enough to monitor accuracy after convergence.
Keras - Development Tools 17 All models have been trained for a long enough period where the models converge and, thus, a bird view of the global behaviour can be taken. Fig 2.4 Configure optimizer and train the model 2.2.5. Generating predictions After obtaining the results from the training and validation process, the next step is to evaluate the model with never-seen data. Using a validation set allows to tune the model by changing input arguments, number of layers, number of epochs, etc… for the cases in which the results are not good enough, but to have a complete evaluation of the model it is important to distinguish if it performs well both in seen as in never-seen data. The best way to show the evaluation of the system is placing each prediction in a confusion matrix [15]. These matrixes will be shown in Chapter 4, but basically, each column represents a category, and the rows represent the predicted categories. This tool allows knowing which categories confuse the system because it shows the number of mismatches and in which category is classified. The ideal confusion matrix is diagonal with the number of elements of each category, because it means that the predicted categories coincide with true categories. (In this case, a diagonal matrix with the value 1000). Fig 2.5 Evaluating the model with never-seen data 2.1. Loss function and learning algorithms As mentioned in Chapter 1, to perform automatic classification the system must learn to classify correctly through the training process, reducing the Loss score provided by the Loss function, which basically compares the network’s prediction with the true value and outputs a Loss score. This function has to be minimized in order to achieve maximum accuracy, which is the Optimizer’s task.
18 Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs To accomplish this task, the Optimizer manages the Loss score and the filters’ weights, which are updated depending on that score, the lower the score, the softer the updates in the weights. The Optimizer looks for the values for which the gradient of the Loss function is zero (as close as possible), but on the basis that all Optimizers have the same goal, there are different types of Optimizers with different ways to find the values that minimize the Loss Function. An important parameter for the Optimizers is the Learning Rate (LR), which is decisive to reach convergence: If LR is too low, reaching convergence can take forever, if it is too high, the algorithm will never converge, for that reason it is important to adapt the LR while searching the minima. The most basic optimizer is Gradient Descent (GD), but achieving the proper values is not feasible when handling millions of parameters, so a faster version, Stochastic Gradient Descent (SGD) is introduced as basis of the Optimizers used in this project: 2.3.1. Loss Function First of all, we need to check the problem to face, in this case it is a multiclass classification problem, so the corresponding Loss Function is [5]: 𝐽(𝑦) =∑𝑦𝑑·𝑙𝑛𝑦′+(1 − 𝑦𝑑)·𝑙𝑛 (1 − 𝑦′) 𝑀 𝑖=1 , (𝑦𝑑 is the true target) (2,1) 𝑦′= 𝑆(𝑊𝑇· 𝑋) (𝑦′ Is the predicted value) (2,2) 𝐖𝒌+𝟏 = 𝐖𝒌− µ∇𝐰𝐽(𝑦) Is the expression for weight learning (2,3) As can be observed on these equations, the changes that can lead the Loss Function J(𝑦) to its minimum value, will depend on how good or bad are the predictions obtained (𝑦′), and the predictions’ quality depend at the same time on the weights learnt through the Backpropagation mechanism, that will be constantly updated during the training process. To sum up, the Loss Function values depend exclusively on the weights. 2.3.2. Learning algorithm (SGD) Similar to GD, the only input value for this optimizer is the LR, taking big steps when the predicted value is far from the true target (high LR) and small steps when the predictions are close to the true target (low LR), the difference is that redundant samples form clusters (minibatches) to implement the mathematical calculations with the gradients (see [16]). This feature allows the Optimizer to work in just that subset of data, instead of all the information, which results faster because the number of steps are reduced in a factor corresponding to the number of minibatches or clusters (faster than GD). SGD does not compute the exact derivative of the Loss Function, it is an estimation for each batch, therefore, the gradients ‘oscillate’ instead of moving uniformly, causing that not all steps to the minima are in the right direction. Moreover, working on minibatches provide more stable estimates of the parameters in fewer steps.
Keras - Development Tools 19 2.4. Optimizers The optimizers perform mathematical operations to reach the minima as fast as possible, despite they use different ways to find the minima, the objective is the same. The different optimizers [17] used in this project are described below: 2.4.1. SGD with Momentum Instead of taking the direction on the maximum gradient, the strategy of this method, with momentum, is moving average of the gradients and the value from previous gradients. With this technique, the optimizer tends to oscillate, and the way it deals with these oscillations is averaging the estimated gradients (weighed averages), that would be closer to the original function, accelerating them in the right direction. The way to the minima is described by the formula: 𝑚𝑡= 𝛽𝑚𝑡−1 +(1 − 𝛽) 𝑔𝑡 (2,4) Fig 2.6 SGD with Momentum 2.4.2. RMSprop Similar to SGD, the main parameter is the LR, but RMSprop looks for a fast way to the minima, dumping oscillations not routed in the right direction. The method is to penalize the updates of those parameters that cause the Loss function to suffer wide oscillations, with the objective not to adapt quickly to such changes for the weights’ values. The advantage of the updates that are correctly routed to the minima is that they do not suffer any penalty and therefore, there will not be big oscillations in the way to the local minima. 𝑣𝑡= 𝜌𝑣𝑡−1 +(1 − 𝜌) 𝑔𝑡2 (2,4) This formula indicates how the gradient are treated: The square of the average gradient is computed, multiplied by (1 − 𝜌) and added the previous exponential average (𝑣𝑡−1) of the gradients to obtain the result. The reason to do it in this way, is to weigh the more recent gradients respect the previous.
20 Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs RMSprop can also deal with large datasets thanks to the use of minibatches, averaging the gradients for each weight, and taking all the steps with the same magnitude. The magnitude of the steps can be regularized dividing the gradient by the square root of the mean gradient, reason for which the Optimizer’s name is RMSprop, the LR is also divided for a weight that is the average of the magnitudes of the recent gradients that had that weight. 2.4.3. ADAM (Adaptive Moment estimation) ADAM is an adaptive LR optimization algorithm, computing each LR for different parameters, like RMSprop, it uses squared gradients to scale the LR and computes them individually for each parameter and similar to SGD with momentum, it moves average over the gradients. ADAM uses estimations of the first and second moment (expectations of the gradients’ values, 𝑔𝑡): 𝑚𝑡= 𝛽1𝑚𝑡−1 + (1 − 𝛽1)𝑔𝑡 (2,5) 𝑣𝑡= 𝛽2𝑣𝑡−1 + (1 − 𝛽2)𝑔𝑡 2 (2,6) However, developing some iterations in these formulas and assuming that the expectations of the gradients come from the same distribution, it can be checked easily that there is an inherent bias that must be corrected according to the expression below: 𝑚𝑡= 𝑚𝑡 1−𝛽1 (2,7) 𝑣𝑡= 𝑣𝑡 1−𝛽2 (2,8) As these equations show, this optimizer has more hyperparameters than the previous ones, the recommended values are: 𝛽1= 0.9 𝛽2 = 0.999 𝛽1 and 𝛽2 are used to average the first and the second moment to scale the LR for each parameter, being 𝜂 the initial LR. There is also an additional parameter (ϵ) to ensure no division by zero in the weight update: 𝑤𝑡= 𝑤𝑡−1 − 𝜂 𝑚 𝑡 √𝑣 𝑡+ϵ (2,9) With recommended value ϵ = 10-8 .
Keras - Development Tools 21 2.5. Used CNN architectures Different CNN architectures have been tested to check which of them provides the maximum accuracy to perform the classification of the newscast frames. These architectures belong to networks that have competed in ILSVRC, obtaining very good results in terms of classification. At the beginning, their first approach was achieving maximum depth in these architectures, but experience revealed that insistence on deep networks didn’t always lead to better results. For this reason, approaches with changes on convolution operation and feed-forwarding outputs were successful as explained below. 2.5.1. VGG Net Presented in ILSVRC 2014, this architecture can optionally use 16 or 19 convolutional layers with 3x3 filters. It becomes progressively simplified in terms of width, using 2x2 MaxPooling filters with stride 2, increasing the total number of filters in the upper layers. Concatenating 3x3 convolution layers, the reception field is increased, and the 3x3 size reduces the total number of parameters. Another important feature of this architecture is the use of ReLU activation on each convolution layer, it makes the decision function more discriminatory, achieving a more accurate classification[5]. VGG Net has become a reference architecture and has contributed to a better understanding on the NNs. As 3x3 convolutional layers are added, each feature depends on a 3x3 region from the original image, in the second 3x3 layer, each output element will depend on a 5x5 region from the original image, on a 7x7 region on the third layer and so on… This way, after each MaxPooling operation, each output will depend on a 14x14 region. VGG16 number of parameters is 138 million, a large number for a configuration of 16 layers, however, its conceptual simplicity makes this network widely used on multiple applications since it is implemented in the majority of frameworks as pre-trained network on ImageNet. The architecture is shown in (Fig 2.7). Fig 2.7 VGG Net architecture
Building the Dataset 29 This support is possible thanks to its libavformat and the libavcodec libraries for media formats that contain muxers and demuxers for audio/video containers. The libavfilter library is also useful for management matters. The elements compatible with FFMPEG needed to build the data set with frames extracted from videos are: CODEC H.264/AVC/MPEG-4 AVC/MPEG-4 part 10 (encoders: libx264, libx264rgb, compatible for de/coding and pixel format). CODEC MPEG-2 Video (compatible for de/coding and pixel format). CODEC PNG format support to save frames. The most important feature of FFMPEG for this project is its capability to recognise a vast number of CODECs and formats to recognise the input (MPEG- 2/4 videos) and to get the desired output (PNG frames). 3.2.1 FFMPEG syntax The FFMPEG program reads the content of the specified input with –i option, the options used in FFMPEG for this project have been these: The resulting command that converts a video into frames has this structure: > ffmpeg -i [video_name.extension] [frame_name.extension] As example: > ffmpeg -i RTVE-i1.mp4 RTVE-i1-%d.png (%d is to have numbered frames) This command slices a video into frames one by one, and according to the standard frame rate in European countries, each second contains 25 frames, but it results in many redundant frames, so the solution proposed is obtaining 1 frame per second instead of 25 per second: > ffmpeg -i [video_name.extension] –vf fps=1 [frame_name.extension] -vf is an option to indicate the use of a video filter, the option of the video filter selected for this project is to set frames per second from 25 (default frame rate on MPEG-2/4) to 1. As example: > ffmpeg -i RTVE-i1.mp4 –vf fps=1 RTVE-i1-%d.png This way, FFMPEG will extract less frames from videos, no extra-storage will be required to keep redundant frames and the manual classification will be easier. 3.2.2. Naming frames Naming downloaded videos is necessary to identify channel and program, when a video is downloaded, the convention to identify channel and program is:
30 Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs Channel_name-i[number of video].extension An example to see it clearly can be: TV3-i6.avi The number next to i keeps no relation with the days of the month, it is just an index to enumerate the videos. In the same day, two or three TV news program can be emitted in the same channel (at morning, evening, night). To have more variety in frames, for a given channel, a good option is to download and separate morning, evening, night and weekend newscast from different days. The choice in this project has been this: Download all morning newscasts from a fixed month. Download all evening newscasts from the next month. Download all the night newscasts from the next month after evening newscast. Download the equivalent number of newscasts of the weekend edition. A way to separate them in this project has been to distribute the newscasts between training folder, and the validation folder as indicated further in this document. This criterion is to ensure that Intro_New category does not contain almost identical frames: the presenters will be different this way. The convention to name the frames is: Channel_name-i[number of video]-[frame_index].extension Again, an example is provided: A3-i4-148.png 3.3. Frames’ classification After obtaining all the frames from a video, the next step is to classify them; the method to classify the frames has been this: Check all the frames In case a frame belongs to one of the categories, move it to the folder corresponding to that category. Continue checking frames until the last one. The main goal of this project is to distinguish studio frames from non-studio frames, and to achieve that, the proposed categories to classify are these:
Building the Dataset 31 ● Graph_Intro: Corresponds to graphic frames, digitally created by computer, not from any camera. This category belongs to studio because the displayed info comes from data obtained by the TV program. For this reason, it is a studio category. ● Intro_New: This category refers to presenters’ explanation before a reporter explains the new; it can introduce as well a set of graphics. This is clearly a studio category. ● Reporter: Frame where a reporter gathers all possible info about the event and provides a status-report about the place. It can be the beginning of the non-studio category, or can, as well can indicate the end of non-studio. ● Rep_Interview: This kind of frame shows a reporter interviewing a person about the event that made the journalists come to that place. This category cannot be studio. ● Rep_New: Reporter explaining new with camera support. This category normally comes next after Reporter category to provide additional info with cameras to television viewers. This is a non-studio category. ● Video_New: New development, the core of the non-studio category, the raw image of the camera showing the mentioned event happening. It normally contains vehicles, buildings, monuments, distant crowd, landscapes… The reason to choose these categories is to make the network identify which features belong to studio and which features do not. Examples of these frames can be found on Annex A3. 3.3.1. Data management To make our network capable to identify each frame it is necessary first to collect enough samples of each category. The network must do the training part first; it means to make the model classify the training samples with no prior knowledge. At the beginning, the model will classify frames incorrectly, but it will keep learning though errors, until it learns patterns and detect elements that guide it during the convolution process. Once the training has been completed, it is necessary then to measure the model’s accuracy and loss (this stage is called validation, a way to see the training’s results). The data from validation is a fragment of the training data, which means that the data is similar but not identical to the model and it is not data from which it has learnt. Validation data is important in order to tune our network’s configuration (selecting the number of layers, the number of epochs, the batch size, and it is a way to see at first sight if the network suffers underfitting or overfitting. Another interesting validation technique is the K-fold cross validation, which consists on splitting the training set into k groups use one of them as a validation set. Do the training process for the rest of the groups and
32 Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs validate with the extracted group, then repeat this operation for all groups and the resulting loss accuracy is the average of the resulting k trainings. After having obtained system’s accuracy and loss, the next step is to make the model classify never-seen data to have an objective result, this is the Test part. 3.3.1.1. Data proportions All models in ML/DL must satisfy a proportion [5] of data in order to obtain the desired results (accuracy as close as possible to 100% and almost null loss). The proportion of data that has provided the best results until now has been this: Fig 3.3 Data proportions for Training, Validation and Test In previous Deep Learning problems, the order of magnitude of the training samples is tens of thousands (40.000-60.000 frames) having validation and test the proportional part as shown on the figure (Fig 3.3). In the case of this project, the number of frames for each category has been 1000 for training, 1000 for validation and 1000 for test. Previously the proportion has not been accomplished, but Keras has functionalities that can boost accuracy with small data sets, the functionality applied in this project is Data Augmentation, achieving accuracy around [85-90]% depending on the network architecture used. This functionality is an approach that creates more training data from existing samples by generating random transformations such as rotation, zoom, horizontal flip… With these transformations, the trick is that the frame is similar but not identical. Therefore, the network will not consider it as a redundant element during the training part, feature that allows the model to cope with overfitting and helps increasing its generalization ability. 3.3.1.2. Dataset and channels’ structure The way to load data in Keras is to place the frames in their corresponding category, the data set for this project consists in a folder named ‘Data set’ which contains three folders, ‘1-Training’, ‘2-Validation’, ‘3-Test’. Each of these folders contains one folder per category, which in this case, if we take as example the folder ‘1-Training’, it contains 6 folders with the names of the categories of this project, as shown in (Fig 3.4)
Building the Dataset 33 Fig 3.4 Folders’ structure in Dataset A folder with the channel’s name that contains as many folders as downloaded videos, following the previous convention commented in FFMPEG naming, the folder with the name of the channel contains various folders: ‘i1’, ‘i2’…’iN’. Not all the channels have the same number of TV news programs because there are channels that provide more useful frames than others do with the same amount of frames. After obtaining some folders with frames from FFMPEG, the next recommended task is to analyse these folders immediately and not generate new folders until the appropriate frames are on their corresponding folders. 3.3.1.3. Distribution of TV channels in Training, Validation and Test The distribution of the frames in the Traning, Validation and Test folders has been done according to this convention: To train the network with national newscasts and check its performance by testing frames from international TV channels like BBC, CNN, CNBC… Table 3.2. National newscast edition for training and validation TRAINING VALIDATION Morning, evening, night Weekend Table 3.3. International newscast edition for training and validation TRAINING VALIDATION Morning Evening The reason for this distribution is to provide as maximum variety as possible in national channels, with a limited number of presenters, studios and reporters, and for the case of international TV channels, which are endless, the diversity will reach its maximum with just a sample of one studio, one presenter, one reporter… per channel. Since the international channels are outnumbered, the list of all channels is on the Annex A2.
34 Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs CHAPTER 4. TRAINING AND RESULTS This chapter shows the results after having fed the dataset to each architecture, the results shown are the training loss and accuracy along with validation loss and accuracy of all the trainings, and finally, the prediction accuracy. Training loss is the error on the training set of data. Validation loss refers to errors in the validation data classification. Training accuracy is the ratio between successful classifications and total number of frames during the training process. Validation accuracy is the ratio between successful classifications and total number of frames during the validation process. Prediction accuracy is the ratio between successful classifications and total number of frames during the prediction process. The measure that determines if a result is good or bad after the classifications is the prediction accuracy, which is considered an objective and unbiased measure, the validation accuracy, in the other hand, is a small part that comes from the training set, reason for which that measure cannot be absolutely considered as never-seen data. The numerical results are displayed in these tables (30th epoch), obtained after finishing the training for 30 epochs, saving the model and begin training again with a lower LR to obtain better, but stationary results. The accuracy graphs and the confusion matrixes of all architectures can be found on Annex A4. 4.1. Results for architecture VGG16 Table 4.1. Results for VGG16 Train Loss Train Acc Val. Loss Val. Acc Pred. Acc SGD with M 0.1795 0.9400 0.2703 0.9070 0.86 RMSprop 0.0264 0.9920 0.3624 0.9190 0.87 ADAM 0.0085 0.9995 0.5621 0.9210 0.87 VGG16 is the architecture that leads to the best results obtained in this project, reaching the maximum prediction accuracy. Despite SGD prediction accuracy is slightly lower, the validation graph shows a small overfitting affection (validation curve is not distant from training curve, which is not the case of RMSprop and ADAM, where overfitting in both cases begins in epoch 6), and thus, has a better generalization capability. This result is accord with the Occam’s razor principle. 4.2. Results for architecture VGG19 Table 4.2. Results for VGG19 Train Loss Train Acc Val. Loss Val. Acc Pred. Acc SGD with M 0.1504 0.9605 0.2735 0.9010 0.86 RMSprop 0.0232 0.9925 0.5029 0.9110 0.86 ADAM 0.0045 0.9980 0.4003 0.9150 0.86
Training and Resulta 35 The VGG19 results do not differ much from VGG16 architecture. Again, SGD optimizer is slower reaching overfitting, and in the case of in RMSprop, the training and validation curve don’t split until epoch 10 and with ADAM, the validation accuracy curve (stationary in 0.99) is not far off the training accuracy curve (stationary in 0.91). RMS prop and ADAM converge fast, but not to the best solution. 4.3. Results for Inception V3 Table 4.3. Results for Inception V3 Train Loss Train Acc Val. Loss Val. Acc Pred. Acc SGD with M 0.4001 0.8585 1.6072 0.6210 0.56 RMSprop 0.5319 0.8150 1.7329 0.5940 0.53 ADAM 0.1697 0.9400 2.0595 0.6600 0.59 The results with Inception architecture begin to worsen, prediction accuracy decreases from 0.90 to values lower than 0.60 and the validation accuracy suffers a similar decrease. Despite many LRs have been tested to improve the results of the table, the validation accuracy remains stationary regardless the number of epochs in all architectures. A reason for this behaviour is the convergence on solutions that are good for training, but for this architecture, the validation results are poor and far from solution if compared to VGGs. 4.4. Results for Xception Table 4.4. Results for Xception Train Loss Train Acc Val. Loss Val. Acc Pred. Acc SGD with M 0.1904 0.9460 0.9841 0.7060 0.62 RMSprop 0.2743 0.9045 1.1564 0.7070 0.61 ADAM 0.2260 0.9260 1.3683 0.7500 0.65 The results obtained in Xception, however, are numerically a bit better than the Inception results, but the graphs show a clear overfitting in which is impossible to obtain better validation results with the small quantity of frames obtained. For this architecture, validation curve never reaches the training curve, providing poor results for the predictions. The reason that concludes this behaviour in all the architectures is the small quantity of frames in the dataset. Due to this small quantity, all the architectures suffer overfitting, in the case of RMSprop and ADAM convergence is reached fast, but the solutions obtained are very good for training and bad for validation, keeping this trend during all epochs. SGD, in the other hand, reaches convergence slower than RMSprop and ADAM, reason for which obtains better results: overfitting arrives later for this optimizer.
36 Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs Some of the best results are shown here as example: Fig 4.1 VGG16 SGD Fig 4.2 VGG19 SGD
Training and Resulta 37 Some bad results examples: Fig 4.3 Xception RMSprop Fig 4.4 Inception V3 ADAM
38 Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs CONCLUSIONS The work in this project has studied and documented the basics in Deep Learning, a subset of Machine Learning popular in the field of image classification. The steps followed to obtain the classifications that distinguish the frames between the studio and non-studio categories have been these: Document the basic operations in CNNs. Compare the different DL frameworks and install the most suitable. Implement the CNNs with the necessary operations shown in Chapter 1. Build the dataset, by obtaining videos and extracting the frames. Load the architectures, train the networks with different optimizers and techniques to obtain the results and compare them. With the obtained results and after all the research to do this project, the reached conclusions are these: The interest and research in DL is increasing, with the appearance of new classification datasets, to solve different problems such as clothes, sports, supermarket product classification… Thanks to the loaded architectures it is possible achieve very good results in shallow architectures. The deepest networks result non-effective in small datasets. The generalization capability is higher with shallow architectures, according to Occam’s razor principle, which states that the simplest explanation is normally the right one. Data augmentation parameters in the training frames must generate frames that have no additional features respect the validation set and the test, for example, the validation set will rarely contain a rotated frame in a newscast. Depending on the problem, Data Augmentation can boost accuracy to 95% with small datasets, not here due to small quantity and restricted augmentation. The Future lines of development are these: The first improvement has an easy but long implementation, consists on installing as many DL frameworks as possible and check the performance with image classification, taking into account DL is not exclusively associated to computer vision. Along with this implementation, building a bigger dataset with more frames would be interesting to compare performances obtained in this project for further research. The results would be better in the deepest architectures with a bigger dataset. The work in this project classifies the different type of scenes that appear on the newscasts. In subsequent versions of the created system in this project, it would be interesting to identify the presence of the sign language that appears on some newscasts. A first approach can be done by creating
Annexes 45 A2.2 Test Channels Table A2.2 Channels to build the test set TeleMadrid IB3 CNN BBC RT CBS 2DF ARAGON TV ARIRANG BDMADRID BLOOMBERG CANAL SUR CNBC CUBAVISION FOX NEWS NEWSROOM TVN NHK TV10 SKYNEWS TV5 MONDE TV RECORD SD
46 Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs A3. Example frames for each category Fig A3.1 Graph_Intro frame Fig A3.2 Intro_New frame I Fig A3.3 Rep_Interview frame
Annexes 47 Fig A3.4 Reporter frame Fig A3.5 Rep_New frame Fig A3.6 Video_New frame
48 Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs A4. Results from all architectures Fig A4.1 VGG16 results – SGD Fig A4.2 VGG16 results – RMSprop
Annexes 49 Fig A4.3 VGG16 results – ADAM Fig A4.4 VGG19 results – SGD
50 Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs Fig A4.5 VGG19 results – RMSprop Fig A4.6 VGG19 results – ADAM
Annexes 51 Fig A4.7 Inception V3 results – SGD Fig A4.8 Inception V3 results – RMSprop
52 Convolutional Neural Networks for classifying studio/non-studio frames in TV news programs Fig A4.9 Inception V3 results – ADAM Fig A4.10 Xception results – SGD
Annexes 53 Fig A4.11 Xception results – RMSprop Fig A4.12 Xception results – ADAM