Full text
TREBALL DE FI DE GRAU T´ ITOL DEL TFG: Spectral automated classification in large databases TITULACI ´ O: Doble titulaci´ o de grau en Enginyeria de Sistemes Aeroespacials i Enginyeria de Sistemes de Telecomunicaci´ o AUTOR: Cristian David Echeverry Valencia DIRECTORS: Alberto Rebassa Mansergas Santiago Torres Gil DATA: July 5, 2021
T´ıtol: Classificaci´ o automatitzada d’espectres en grans bases de dades Autor: Cristian David Echeverry Valencia Directors: Alberto Rebassa Mansergas Santiago Torres Gil Data: 5 de juliol de 2021 Resum Degut a la gran quantitat de dades que es recopilen cada dia, hi ha la necessitat de modelar algoritmes d’aprenentatge autom` atic capac¸os de manipular i relacionar la informaci´ o sense processar, amb la menor supervisi´ o humana possible. Un dels m´ es coneguts ´ es el Bosc Aleatori, que pot usar-se per a resoldre una gran varietat de tasques de classificaci´ o. Concretament, en Astronomia milions d’objectes s´ on capturats per sat` el·lits i telescopis, com per exemple en la missi´ o espacial Gaia, i els senyals rebuts es mostren en forma d’un espectre electromagn` etic. Els algoritmes de Bosc Aleatori han resultat ser una eina molt vers` atil i potent a l’hora d’identificar i classificar poblacions estel·lars. En aquest projecte, hem aplicat l’algoritme de Bosc Aleatori basat en un an` alisi espectrosc` opic amb l’objectiu de classificar de forma eficient tres poblacions d’estrelles d’especial inter` es. El nostre objectiu principal ´ es estudiar els par` ametres i variables principals que afecten el rendiment de l’algoritme a l’hora de classificar, i tamb´ e modelar el Bosc Aleatori per categoritzar espectres observats de missions tant actuals com futures. Pretenem obtenir els millors resultats possibles en funci´ o de les caracter´ ıstiques de cada poblaci´ o, mantenint alhora un model eficient i vers` atil. Per aconseguir-ho, fem ´ us tant d’espectres simulats com observats per entrenar i validar l’algoritme, i fem servir m` etriques quantitatives per mesurar el rendiment. All llarg d’aquest projecte, hem assentat les bases d’un classificador de Bosc Aleatori i la preparaci´ o de les dades, analitzant la classificaci´ o te` orica amb espectres simulats. Hem classificat amb el model de Bosc Aleatori una col·lecci´ o real de dades espectrosc` opiques recopilades en el Sloan Digital Sky Survey, revelant una concordanc¸a notable entre la classificaci´ o humana i la de l’Bosc Aleatori, sobretot despr´ es d’aplicar una s` erie de millores a l’algoritme. Finalment, hem generat espectres que simulen als que s’espera que seran publicats per la missi´ o espacial Gaia, i hem constru¨ ıt un model de Bosc Aleatori basat en aquestes dades. Hem implementat diverses millores, i a la fi hem obtingut un model s` olid amb resultats satisfactoris. Amb aix` o, hem estat capac¸os de classificar dues col·leccions d’espectres estel·lars amb diferents caracter´ ıstiques, maximitzant el nombre d’objectes correctament classificats i minimitzant la quantitat de falsos positius.
Title : Spectral automated classification in large databases Author: Cristian David Echeverry Valencia Advisors: Alberto Rebassa Mansergas Santiago Torres Gil Date: July 5, 2021 Overview Due to the vast amount of data collected every day, there exists a need of modelling Machine Learning algorithms that are able to manipulate and link the raw data with as little human supervision as possible. One of the most popular is the Random Forest, which can be used to solve a great variety of categorization tasks. Particularly, in Astronomy millions of objects are captured by satellites and telescopes, for instance by the Gaia space mission, and the receiving signals are displayed in a spectrum. Random Forest algorithms have been proven to be a versatile and powerful tool in identifying and classifying stellar populations. In the present project, we apply a Random Forest algorithm based on spectroscopic analysis with the aim of efficiently classifying three different populations of stars of particular interest. Our main objective is to study the principle parameters and variables that affect the classification performance of the algorithm, and also to model the Random Forest to categorize observed spectra by current and future missions. We aim to obtain the best results according to the characteristics of each population, while maintaining an efficient and versatile model. To achieve that, we rely on both simulated and observed spectra to train and test the algorithm, and on quantitative metrics to measure its performance. Along this project, we have set the basis of the modelled Random Forest classifier and the preparation of the data, analyzing the theoretical classification with simulated data. We have classified with the Random Forest model a real set of spectroscopic data collected by the Sloan Digital Sky Survey, which revealed a notable agreement between the humanmade and the Random Forest classifications, greatly enhanced after the application of different improvements to the algorithm. Finally, we simulated spectra of the expected observed population that will be released by the Gaia space mission, and built a Random Forest model based on it. Several improvements were introduced, but we could eventually achieve a solid model with satisfactory results. With that, we were able to classify two different sets of stellar spectra with different characteristics, maximizing the number of well classified objects while minimizing the amount of false positives.
T´ıtulo: Clasificaci´ on automatizada de espectros en grandes bases de datos Autor: Cristian David Echeverry Valencia Directores: Alberto Rebassa Mansergas Santiago Torres Gil Fecha: 5 de julio de 2021 Resumen Dada la gran cantidad de datos que a diario se recopilan, existe la necesidad de modelar algoritmos de aprendizaje autom´ atico capaces de manipular y relacionar la informaci´ on sin procesar, con la menor supervisi´ on humana posible. Uno de los m´ as conocidos es el Bosque Aleatorio, que puede usarse para resolver una gran variedad de tareas de clasificaci´ on. Concretamente, en Astronom´ ıa millones de objectos son capturados por sat´ elites y telescopios, como por ejemplo en la misi´ on espacial Gaia, siendo las se˜ nales recibidas mostradas en forma de un espectro electromagn´ etico. Los algoritmos de Bosque Aleatorio han resultado ser una herramienta muy vers´ atil y potente a la hora de identificar y clasificar poblaciones estelares. En este proyecto hemos aplicado el algoritmo de Bosque Aleatorio basado en un an´ alisis espectrosc´ opico con el objetivo de clasificar de forma eficiente tres poblaciones estelares de especial inter´ es. Nuestro objetivo principal es estudiar los par´ ametros y variables principales que afectan al rendimiento del algoritmo a la hora de clasificar, y tambi´ en modelar el Bosque Aleatorio para categorizar espectros observados de misiones tanto actuales como futuras. Pretendemos obtener los mejores resultados posibles en funci´ on de las caracter´ ısticas de cada poblaci´ on, manteniendo a la vez un modelo eficiente y vers´ atil. Para conseguirlo, hacemos uso tanto de espectros simulados como observados para entrenar y validar el algoritmo, y utilizamos m´ etricas cuantitativas para medir el rendimiento. A lo largo del proyecto hemos asentado las bases de un clasificador de Bosque Aleatorio y de la preparaci´ on de los datos, analizando la clasificaci´ on te´ orica con espectros simulados. Hemos clasificado con el modelo de Bosque Aleatorio una muestra real de datos espectrosc´ opicos recopilados por el Sloan Digital Sky Survey, revelando una concordancia notable entre la clasificaci´ on humana y la del Bosque Aleatorio, sobre todo tras aplicar una serie de mejoras al algoritmo. Finalmente, hemos generado espectros que simulan a los de la poblaci´ on que se espera ser´ an publicados por la misi´ on espacial Gaia, y hemos construido un modelo de Bosque Aleatorio basado en dichos datos. Hemos implementado varias mejoras, obteniendo al final un modelo s´ olido con resultados satisfactorios. Con ello, hemos sido capaces de clasificar dos colecciones de espectros estelares con diferentes caracter´ ısticas, maximizando el n´ umero de objetos correctamente clasificados y minimizando la cantidad de falsos positivos.
A Tito y Ruby
4.19 Confusion matrix for Case 3. . . . . . . . . . . . . . . . . . . . . . . . . . . 53 4.20 Examples of single objects misclassified in Case 3. MS spectrum (left panel) and WD spectrum (right panel). . . . . . . . . . . . . . . . . . . . . . . . . 54 4.21 Examples of binary objects misclassified in Case 3. . . . . . . . . . . . . . . 55 4.22 ROC curve and AUC score for Case 3. . . . . . . . . . . . . . . . . . . . . 55 4.23 ROC macro-average curves. . . . . . . . . . . . . . . . . . . . . . . . . . . 56 4.24 Metric scores for the three cases. . . . . . . . . . . . . . . . . . . . . . . . 56 4.25 WDMS recall density map as a function of the MS stellar parameters. . . . . 58 4.26 WDMS misclassification as a function of the MS stellar parameters. . . . . . 58 4.27 WDMS recall dependence on the WD stellar parameters. . . . . . . . . . . . 59 4.28 WDMS misclassification according to the WD stellar parameters. . . . . . . . 60 4.29 WDMS recall as a function of flux relation for the three cases under study. . . 61 4.30 ROC curve comparing different thresholds for the different populations. MS population (top left panel), WD population (top right panel), WDMS population (bottom left panel) and legend (bottom right panel). . . . . . . . . . . . . . . 63 5.1 SDSS spectroscopic throughput. . . . . . . . . . . . . . . . . . . . . . . . . 66 5.2 SNR histogram of the SDSS spectra. . . . . . . . . . . . . . . . . . . . . . 67 5.3 Confusion matrix of the SDSS spectra set for the initial Random Forest model. 68 5.4 Misclassified spectra by Random Forest. WDMS spectra (top panels) and MS spectrum (bottom panel). . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 5.5 ROC curves of the SDSS spectra set for the initial Random Forest model. . . 70 5.6 Confusion matrix of the SDSS spectra set when introducing threshold cuts in the Random Forest model. . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 5.7 Confusion matrix of the SDSS spectra set when introducing population limits in the Random Forest model. . . . . . . . . . . . . . . . . . . . . . . . . . 72 5.8 ROC curves of the SDSS spectra set when introducing population limits in the Random Forest model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 5.9 Examples of spectra with low SNR (simulated on the left and real on the right). 73 5.10 Example of spectra with new noise distribution. . . . . . . . . . . . . . . . . 74 5.11 Confusion matrix of the SDSS spectra set when introducing a new noise distribution in the Random Forest model. . . . . . . . . . . . . . . . . . . . . . 74 5.12 ROC curves of the SDSS spectra set when introducing a new noise distribution in the Random Forest model. . . . . . . . . . . . . . . . . . . . . . . . 75 5.13 Confusion matrix of the SDSS spectra set for the final Random Forest model. 76 5.14 ROC curves of the SDSS spectra set for the final Random Forest model. . . . 76 5.15 Different cases ROC curves for the WDMS population. . . . . . . . . . . . . 77 6.1 Nominal resolving power according to the wavelength in Gaia spectra. . . . . 80 6.2 Distribution of stellar parameters of single MS stars (top left), single WDs (top right), MS star components in WDMS (bottom left) and WD components in WDMS (bottom right). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 6.3 SNR distribution of the simulated Gaia spectra. . . . . . . . . . . . . . . . . 82 6.4 Confusion matrix of the synthetic Gaia spectra set for the initial Random Forest model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 6.5 Two examples of misclassified WD (left) and WDMS (right) Gaia spectra. . . 83 6.6 ROC curves of the Gaia spectra set classification for the initial Random Forest model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
6.7 Confusion matrix of the Gaia spectra set classification when introducing threshold cuts in the Random Forest model. . . . . . . . . . . . . . . . . . . 85 6.8 Confusion matrix of the Gaia spectra set classification when introducing population limits in the Random Forest model. . . . . . . . . . . . . . . . . . . . 86 6.9 Confusion matrix of the Gaia spectra set classification when introducing class weights in the Random Forest model. . . . . . . . . . . . . . . . . . . . . . 87 6.10 Confusion matrix of the Gaia spectra set classification for the final Random Forest model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 6.11 Different cases ROC curves for the WDMS population. . . . . . . . . . . . . 90 A.1 Logistic Regression function. . . . . . . . . . . . . . . . . . . . . . . . . . . 2 A.2 Comparison between Decision Tree based methods. . . . . . . . . . . . . . 3 A.3 Support Vector Machine example. . . . . . . . . . . . . . . . . . . . . . . . 3 A.4 Artificial Neural Network scheme. . . . . . . . . . . . . . . . . . . . . . . . 4 C.1 Random Forest confusion matrix. . . . . . . . . . . . . . . . . . . . . . . . 32 C.2 Users confusion matrix. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 C.3 Users accuracy histogram. . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 C.4 Users F1-score histogram. . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 C.5 Random Forest ROC curve. . . . . . . . . . . . . . . . . . . . . . . . . . . 34 C.6 Users ROC curve. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 D.1 WDMS recall density map as a function of the MS stellar parameters for Case 1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 D.2 WDMS misclassification as a function of the MS stellar parameters for Case 1. 35 D.3 WDMS recall density map as a function of the WD stellar parameters for Case 1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 D.4 WDMS misclassification as a function of the WD stellar parameters for Case 1. 36 D.5 WDMS recall density map as a function of the MS stellar parameters for Case 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 D.6 WDMS misclassification as a function of the MS stellar parameters for Case 3. 37 D.7 WDMS recall dependence on the WD stellar parameters for Case 3. . . . . . 38 D.8 WDMS misclassification as a function of the WD stellar parameters for Case 3. 38 E.1 Eclipsing binary 1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 E.2 Eclipsing binary 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 E.3 Eclipsing binary 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
LIST OF TABLES 1.1 ROC terminology. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.1 Simulated spectra summary. . . . . . . . . . . . . . . . . . . . . . . . . . . 33 3.2 Hyperparameters optimal values. Default values are marked with asterisk. . . 40 4.1 Performance metrics comparison. . . . . . . . . . . . . . . . . . . . . . . . 56 5.1 Classification metrics of the SDSS spectra set for the initial Random Forest model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 5.2 SDSS WDMS binary population parameters. . . . . . . . . . . . . . . . . . 72 5.3 Classification metrics of the SDSS spectra set for the final Random Forest model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 6.1 Expected SNR for Gaia spectra and for an apparent magnitude of G=13. . . 80 6.2 Classification metrics of the Gaia spectra set classification for the initial Random Forest model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 6.3 Classification metrics of the Gaia spectra set classification for the final Random Forest model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
LIST OF ACRONYMS Acronym Definition ROC Receiver Operating Characteristic TPR True Positives Rate FPR False Positives Rate AUC Area Under Curve MKK Morgan-Keenan-Kellman system HR Hertzsprung-Rusell diagram MS Main Sequence WD White Dwarf WDMS White Dwarf - Main Sequence RResolving power FWHM Full Width at Half Maximum SNR Signal to Noise ratio AWGN Additive White Gaussian Noise SDSS Sloan Digital Sky Survey 1
2 Spectral automated classification in large databases
ACKNOWLEDGEMENTS En primer lugar, me gustar´ ıa agradecerles a los directores del trabajo, Alberto Rebassa Mansergas y Santiago Torres Gil, toda su dedicaci´ on y tiempo a lo largo de este a˜ no. Desde el primer momento han estado gui´ andome y trabajando en este proyecto, siempre con mucha amabilidad y simpat´ ıa, y me han ayudado acad´ emica y personalmente en todo lo que han podido. Ha sido un verdadero honor haber podido desarrollar este trabajo bajo la supervisi´ on de ambos, de los que he podido aprender much´ ısimo en todo este tiempo. Por otra parte, me gustar´ ıa mencionar a mis padres. Gracias a ellos he podido disfrutar de esta carrera y del proyecto, y han estado pendientes de que pudiera centrarme exclusivamente en ello, lo que conlleva bastante esfuerzo por su parte. Os quiero much´ ısimo, ya queda un poco menos. Por ´ ultimo, quiero agradecerle a mi querida amiga Nad` a la ayuda prestada, y sobre todo, su apoyo personal durante este a˜ no. 3
4 Spectral automated classification in large databases
INTRODUCTION Vast amount of data are collected every day, more than scientists and engineers are able to process. For this reason, there exists a need of modelling artificial intelligence algorithms that are able to manipulate and link these raw data with as little human supervision as possible. In this sense, Machine Learning algorithms have been probed to be feasible tools in tackling these problems. Among these algorithms, one of the most popular is the Random Forest. It can be used to solve a great variety of categorization tasks in different fields, such as image analysis or signal processing. Particularly, in Astronomy millions of objects are captured by satellites and telescopes. The receiving signals are displayed in different ways, one of the most common being a spectrum. In this field, neural networks have been widely used to e.g. classify Galactic populations [1,2]. In particular, the use of neural networks and principal components analysis [3] have been used for automated classification of stellar spectra. However, during the last decade, Random Forest algorithms have been proven to be a more versatile and powerful tool in identifying and classifying stellar populations [4]. On the other hand, Gaia space mission, one of the cornerstones missions of ESA agency, will provide to date the most precise three-dimensional map of our Galaxy. Among the huge amount of information that Gaia will supply in the next few years, it is expected to release spectra of more than a billion objects. As stated, this huge amount of information is out of human reach. Consequently, artificial intelligent algorithms, such as the Random Forest presented here, become optimal methods to address this problem. In the present project we apply a Random Forest algorithm based on spectroscopic analysis with the aim of efficiently classifying three different populations of stars of particular interest: main sequence stars, white dwarfs and white dwarf-main sequence binaries. Our main objective is to study the principle parameters and variables that affect the classification performance of the algorithm, and also to model the Random Forest to categorize observed spectra by current and future missions. We aim to obtain the best results according to the characteristics of each population, while maintaining an efficient and versatile model. To achieve that, we rely on both simulated and observed spectra to train and test the algorithm, and on quantitative metrics to measure its performance. This comparison between different settings will allow to analyse the classification outcomes and even introduce improvements in the classification model. Although the problem addressed here is limited to the field of Astrophysics, it can be easily generalized to any other field of Telecommunications or Aeronautical Engineering in which two or more sources can simultaneously or individually emit a signal and the goal is to disentangle them. The memory is structured in six chapters. In Chapter 1, we introduce the Machine Learning concept and we describe in detail the Random Forest algorithm and its application on different areas of space engineering, telecommunications and astronomy. Chapter 2 is dedicated to introducing the particular problem we want to address and to provide the essential information to understand the nature of the data. In Chapter 3 we explore the parameters of the algorithm, which is configurable and adaptable, focusing on the preprocessing of the data set. In Chapter 4 we generate simulated spectra for the different types of stars we want to analyse. Then we set the basis of the algorithm model and analyze its performance in order to be applied in the following two chapters. Chapter 5 is aimed to evaluate our classification algorithm model when compared with observed 5
12 Spectral automated classification in large databases 1.2.2. Random Forest algorithm With all of the previous information, the operating of the Random Forest can be now explained [12,16,17] following the scheme of Figure 1.5. Figure 1.5: Random Forest algorithm structure. The Random Forest is composed by a number of Decision Trees, that altogether constitute a stronger classifier. To build the Random Forest, firstly the training set is randomly divided in Bootstraps or subsets. Then, the algorithm generates a Decision Tree for each Bootstrap sample: from the Root Node, the data is divided iteratively in subsets using the Gini index. The main difference with the single Decision Tree algorithm is that the Random Forest does not choose the variable that best splits the data in each node, but it selects a random number of features for each Decision Tree and the nodes are split with them – this process is called feature bagging and is very useful in order to avoid correlations between the different Decision Trees. This operation is repeated for each one of the Decision Trees that form the Random Forest, resulting in a group of weakly trained Decision Trees theoretically uncorrelated because of the randomness of the process. Once the forest is built, the algorithm is validated using the testing data set. Each object of this sample will go through each Decision Tree with its own classification rules (i.e., Decision Nodes with thresholds) and the outcome will be a single prediction. This is done for all the tress composing the forest, and although the majority vote (the final class is the one resulting from the majority of single trees) is often used in the Random Forest algorithms, the one in the sci-kit learn library averages the probabilistic prediction of the Decision Trees instead, which means that the final classification is the one with a higher percentage among all the outcomes of the single trees. It has to be noted however that the difference in performance and results between the two approaches is negligible. Having understood the working principles of the algorithm, it is important to remark where the Random Forest name comes from. Its randomness is patent in two process: the first one when the Random Forest randomly divides the training set in smaller subsets for building each Decision Tree, and the second one when the algorithm takes a random
CHAPTER 1. MACHINE LEARNING: THE RANDOM FOREST PARADIGM 13 number of features for each tree in order to make the splits. With those simple but effective techniques, the Random Forest is able to drastically reduce the correlations between its Decision Trees, and therefore, gain in classification power. 1.2.3. Hyperparameters The process of building a Random Forest is quite automatized with the sci-kit learn library, but there are some initial parameters that must be set manually in order to optimize the classification. These are called the hyperparameters, and the performance of the algorithm might depend on their values. By default, sci-kit learn already implements some hyperparameters that are supposed to work reasonably well with a lot of datasets, but it is a good practice to tune them so as to find the optimal configuration. In this section, some of the main important hyperparameters will be explained [14] in order to understand their significance: •Number of estimators: the number of Decision Trees that form the Random Forest. •Criterion: the function that is used in order to calculate the quality of the split. We can select between the Gini index or the entropy index. •Minimum number of samples required to split a node: if there are more samples than this value, the algorithm will continue the splitting process; if not, the current node will be considered a Leaf Node. •Minimum number of samples required to be at a Leaf Node: the current node will be considered to be a Leaf Node if there are at least a number of samples equal to this value in the node. •Maximum depth: the algorithm will finish a Decision Tree when there are no more mixed subsets with different classes, when the number of samples is less than the minimum number of samples required to split a node, or when the tree reaches the maximum number of Decision Nodes set by this hyperparameter. •Maximum number of features to consider when looking for the best split: the number of random features that the algorithm takes into account when doing a split can be controlled with this parameter. •Bootstrap: this hyperparameter enables or disables the using of bootstrap samples when building each Decision Tree. That is, if the whole training set is used to build the tree or just a drawn sample with replacement. The second option will build weaker Decision Trees, but less correlated. •Maximum samples to draw from the training set to train each base estimator: if bootstrap is enabled, this value sets the number of samples used in order to build each estimator. If there is no set value, the algorithm will use all the samples. •Class weights: parameter that allows to set weights to the different classes. This is useful in imbalanced datasets where there are many objects of one population and few of another, as it biases the calculation of the Gini index in favour of the minority class at the cost of allowing some errors in the majority one.
14 Spectral automated classification in large databases Apart from the mentioned hyperparameters, the sci-kit learn library allows to set other values, as a cost function in order to control the complexity of the trees. However, for the purpose of this project we find that their evaluation is not necessary, as they would not improve the performance of the Random Forest and just add more complexity to the system. It must also be taken into account that in order to tune the hyperparameters there is always a trade-off between building time, accuracy and over-fitting. The definition of a hyperparameter may suggest that its minimum or maximum value is the best, but most of the times the classifier will suffer from over-fitting, or the time and resources spent on it will not be worth it in terms of accuracy. In the forthcoming Chapter 3, we will explore how the hyperparameters affect the performance of the Random Forest. 1.2.4. Metrics and scoring Once the classification has been made, there are different techniques in order to study the performance of the Random Forest. Sci-kit learn library [14] already has these methods implemented in the following way. Figure 1.6: Example of a confusion matrix. •Confusion matrix: a matrix, M, that shows how the whole population is classified and how it is truly labelled. The diagonal indicates the number of objects that were actually classified according to its true label, so the higher it is, the better the performance of the algorithm. The off-diagonal elements represent the misclassified objects, being the rows the true labels and the columns the predicted labels. Consequently, an element of the matrix Mi,jcorresponds to all the objects of true class iand labelled as j. In Figure 1.6 we display an example of a confusion matrix. Each cell shows the percentage of samples of the population, that is, the number of objects normalized by each row. In the first cell, we find that 70% of the samples that belong to class A
CHAPTER 1. MACHINE LEARNING: THE RANDOM FOREST PARADIGM 15 were correctly predicted as class A. We have then 20% of objects that were wrongly assigned to class B, and a 10% to class C. From all the populations, the best classified is the class C, with a 90% of its samples correctly identified. Conversely, 30% of elements belonging to class Bare also assigned to class C. A confusion matrix represents an efficient and easy way to immediately know the performance of the algorithm, its flaws and its strengths, where it should be improved and where it works properly, so it is one of the most used metrics. •Accuracy score: it is the fraction of correctly classified elements divided by the whole population, so its maximum value is 1 (meaning that all the elements were correctly classified) and its minimum 0 (all the elements incorrectly classified). The accuracy is computed in the following way: accuracy =tr(M) Ntotal ,(1.2) where Ntotal is the total number of objects, and tr(M) = ∑iMi,i, is the sum of the diagonal elements of the confusion matrix, which are the elements correctly classified. This metric provides a performance of the algorithm with a single number. Nonetheless, it can be a tricky measurement. For example, the confusion matrix of Figure 1.6 has an accuracy of 73%, but elements from class Cwere almost perfectly classified while Bwas much worse processed. Moreover, in an unbalanced dataset the weight of the class with fewer elements will be minimum, and the accuracy will mostly reveal the performance of the class with higher population. That is, it reveals the general performance, but not the accuracy of each label. •Recall score: there are a few metrics to measure the performance of each class individually, as the recall score. In a similar way to the accuracy, it measures the fraction of correctly labelled as class ifrom the whole set of objects that actually belong to that class. That means that it measures the ability of the classifier to find all the objects that belong to a certain class, and it can go from 0 to 1: recalli=Mi,i ∑jMi,j ,(1.3) where the sum term refers to the sum of the elements of the row i. It is also called sensitivity or probability of detection, because it indicates the True Positive samples, that is, the hits of the algorithm for a certain class. In a normalized confusion matrix, the recall scores directly correspond to the diagonal values. •Precision score: another metric for each class is the precision score, which indicates the amount of objects correctly classified as iin comparison with the total amount of objects labelled as i, so it also ranges from 0 to 1. This value quantifies the ability of the classifier to not label as class jan element of class i, which would be: precisioni=Mi,i ∑jMj,i ,(1.4)
16 Spectral automated classification in large databases where the sum term refers to the sum of the elements of the column i. •F1 score: a joint measure of the last two scores would be the F1 score or balanced F-score. It can be defined as a weighted average of both, the precision and recall scores, as sometimes those single metrics do not show the true performance of each class. For instance, all the elements belonging to a certain class ican be perfectly classified, so the recall would be high, but other elements of another class jcould also be classified as class i, corresponding to a low precision. The F1 score would average those metrics and reveal a more realistic and matched value. Its mathematical expression is given by: F1i=precisioni×recalli precisioni+recalli .(1.5) •Cohen’s kappa score: on a classification problem, this metric shows the level of agreement between two classifiers. It is defined as: κ=p0−pe 1−pe ,(1.6) where p0=accuracy and peis the expected agreement probability when both classifiers assign random labels [18], that is: pe=N ∑ i=1 ∑ j Mi,j·∑ j0 Mj0,i. Although this metric is intended only for human annotators, it can actually be used in any situation where two different sets of data need to be compared, in order to show the similarities between them. It can take values from -1 to 1, but scores below 0 mean that the agreement is practically random, and above 0.8 it is considered a good agreement, so we aim to have a higher value of p0while keeping a low value of pe. It is said to be more robust than the accuracy because it takes into account the possibility of agreement by chance. •Geometric mean:G−mean is very similar to the accuracy metric, having the same range from 0 to 1, but it is independent of the ratio between the different populations [18], so it is useful in imbalanced populations. It is defined as: G−mean = ( N ∏ i=1 Pi)1 N,(1.7) where Piis the recall for the ipopulation and Nis the number of different populations. •ROC curve: the last metric that will be considered in this project is the Receiver Operating Characteristic (ROC) curve. Although it is primarily intended for binary classifications, it can be extended to multi-class problems such as the present one. This curve represents the performance of a classifier while varying its discrimination threshold. The resulting points are the True Positive Rate (TPR), also known as recall or probability of detection, versus the False Positive Rate (FPR), also named as probability of false alarm. We could express those three values as: TPR =True Positives Positives =True Positives True Positives +False Negatives (1.8)
CHAPTER 1. MACHINE LEARNING: THE RANDOM FOREST PARADIGM 17 and FPR =False Positives Negatives =False Positives False Positives +True Negatives.(1.9) In a multi-class problem, the Positives would be all those elements that actually belong to a class i, whether they are correctly classified or not, and the True Positives would be those who are correctly classified as a class i. On the other hand, the Negatives would be all the other samples that do not belong to a class i, while the False Positives are the elements that do not belong to a class ibut are classified in it. To sum up: Predicted label Total population = Positive + Negative Predicted class iPredicted not class i True label True class i (Positive) True Positive False Negative True not class i (Negative) False Positive True Negative Table 1.1: ROC terminology. The ROC curve operates with the probability estimates of the positive class, that is, the probability of an element to be classified as a certain class. We can obtain them by averaging several Random Forest predictions, because due to the randomness of the algorithm, there may be some objects that are sometimes classified as a population and sometimes as another. The probability estimates are used as the thresholds for calculating the TPR and the FPR. To do that, the number of Positives above the threshold are counted and divided by the total number of Positives. The same process is done for the FPR, but with the Negatives. The result is a point for the plot, so we obtain as many points as thresholds, and therefore, probability estimates. In this way, when analyzing a ROC curve, we must decide which level of recall we want, and which percentage of False Positives Rate we accept. Linked to this metric, we can find the Area Under the Receiver Operating Characteristic Curve (ROC AUC), which is the area under the curve. This value basically summarizes the information of the curve in a number that goes from 0.5 in the worst case (represented by a dashed diagonal line in Figure 1.7), to 1 if the classifier does not make mistakes. It is important to notice that each class will have its own curve and area, but there are two ways to calculate a general average curve. One of them is computing the macro-average, which will reckon the curve independently for each class and then average it, and the other one is the micro-average, which will aggregate the contributions of each class to compute an average curve. The former one is usually more accurate, for instance in problems where the dataset is not balanced. An example of a multi-class ROC curve provided by the sci-kit website [14] is shown in Figure 1.7. In this case we have curves for three classes and the two micro and macro-average curves. The best performance is the one of the class Apopulation, which is closer to the perfect case (a 90-degree curve). On the other hand, the class Bis incorrectly classified many times, being very close to the worst case (dashed line), where the
18 Spectral automated classification in large databases Figure 1.7: Example of a ROC curve. TPR and the FPR are the same, that is, the algorithm is randomly classifying the population and does not recognize the pattern of said class. We can also notice the micro- and macro-average lines, being both of them very similar probably because the populations are balanced, although the macro curve has a better execution. Besides we can see on the legend the different AUC scores, which correspond to the areas under the curves. The AUC equals to the probability that a random positive sample will be classified higher than a random negative sample. In other words, the probability of an object belonging to class iof being better classified that an object that does not belong to class i. 1.2.5. Advantages and disadvantages 1.2.5.1. Advantages There are several characteristics of the Random Forest that make the algorithm a very suitable candidate, not only for this project but also for tasks that require automatic classification labour. In the first place, Random Forest stands out for its versatility. It can be used for classification tasks, and also for regression problems or even cluster analysis. Besides, it is able to process different types of inputs, either categorical data – e.g. non-numerical features, such as color or occupation – or continuous data – e.g. the weight or the height. In any case it maintains its simplicity being a very easy algorithm to implement, and even most of the times with the default parameters the obtained results can be more than acceptable for the vast majority of problems. One of the most relevant advantages is the fact that the algorithm is able to calculate the importance of each characteristic (features) in the process of building the forest. The Random Forest makes an estimation of the features that were most used, so it can work as a pre-analysis tool in order to perform a dimensional reduction or a feature selection.
CHAPTER 1. MACHINE LEARNING: THE RANDOM FOREST PARADIGM 19 It should also be pointed out that this classifier is very stable and robust, meaning that if new training points are added, the overall performance of the algorithm does not have extreme changes. This is also noticeable when the data has missing points, noisy values or outliers, because the algorithm is able to handle them and maintain an average performance. However, the main reason in favour of using Random Forest is the reduction of over-fitting, thanks to the two random processes that happen when building the algorithm. It still can happen, but it may be fixable adjusting the hyperparameters or checking the data and its preparation. However, the progress in this field from a single Decision Tree is remarkable, producing a more general classifier able to look beyond known data. 1.2.5.2. Disadvantages There are negative aspects of the Random Forest algorithm too. For instance, Random Forest can get very expensive computationally speaking, which also means more time. As it has to train a lot of different Decision Trees with different samples of data, it can consume lots of computer resources, so its efficiency in real-time applications can be restricted. There is always the option of limiting the expansion of the tree with the hyperparameters, which can also be beneficial because not always the best results are the ones with deeper and more abundant trees. One of the main drawbacks of the algorithm is that the user has little control of its building and operation, which also means that the final result is not really interpretable nor descriptive. As Random Forest is such a variable, random and automatic algorithm, the classification process does not reveal patterns or anything useful in order to understand the division of the data. Analysing the final Random Forest is not useful as it is made in a completely random manner. The only clue that we can get from it is the mentioned importance of the features, that reveal how much a feature has been useful in the process of building the Decision Trees. Lastly, it is important to mention that the results of the Random Forest may not be the best ones that can be achievable. Other algorithms, like Gradient Boosted Trees or Artificial Neural Networks (see Appendix A) can overpass Random Forest in classification tasks. However, this has a cost, because these mentioned algorithms are much more complex to implement than Random Forest. A detailed study should be done to compare the algorithm for a specific task, and to decide whether its worth the improvement in classification power at the expense of a larger pre-processing and adjustment time. 1.2.5.3. Why using Random Forest? As disposed above, there are lots of machine learning algorithms capable of performing classifying tasks. Each of them has its own ups and downs, and the fact of choosing one among so many possibilities may be a problem itself. Nevertheless, one must take into account that each algorithm works better for certain applications, and most of the times, there are several algorithms suitable for the same problem. Here the difference consists in choosing the one that gives the best performance, or at least, a performance that is acceptable for the user. That means that there is always a trade-off between training time, training data, algorithm setting and precision achieved in the classification. An important
20 Spectral automated classification in large databases question is then: why using the Random Forest for this project? Because it is a very simple algorithm, easy to implement. The results, even with default parameters, are very satisfactory (although improvable) and it can be easily extrapolated to a lot of general applications. Other algorithms, such as Artificial Neural Network, may have a better performance, but the optimization of its parameters would have taken much more time and it would have been more difficult to achieve many of the different results, in comparison with Random Forest, or even try different setups. 1.2.6. Applications Following the line of creating a generalizable Random Forest algorithm, there are multiple applications already studied that used Random Forest as the main tool in order to solve a problem. It is a versatile algorithm able to solve thousands of scientific problems in different areas, such as medicine, economics, linguistics or engineering. Among the variety of problems solved by Random Forests, some of them related to Aerospace systems and Telecommunication systems will be briefly mentioned (see further details in Appendix B). 1.2.6.1. Aircraft fault diagnosis In the Aerospace and Aeronautical sector, there are a few relevant applications of the Machine Learning algorithm which could improve some tasks or solve different problems, for instance, the application of Random Forest to aircraft engine fault diagnosis. There are lots of researches about this topic, for instance: •Yan [19]: research about airplane common-faults diagnosis, carried out with a thermodynamical model of a engine. The Random Forest results outperformed other classificators, being comparable to an Artificial Neural Network. •Lee et al [20]: study of fault diagnosis on a Unmaned Aircraft Vehicle, with the objective of automatically handle the fault and take a decision by itself. Very high detection rates, above 92% most of the times. •Dong et al [21]: diagnosis centred on the welds of the aircraft, using X-ray images. It required a carefully preparation of the images, but the outcomes were good enough to help reduce the workload of human inspectors. •Shipway et al [22]: in a similar way to the previous research, diagnosis of flat titanium plates to detect damages or pores. Also a thorough image-processing was required, leading to a better performance compared to a human. 1.2.6.2. Aviation performance and safety Continuing on the aeronautical sector, we can point out several projects aimed to the betterment of the aviation performance and its safety: •Williams [23]: turbulence diagnose for aviation research, trained with numerical weather forecast models and data from satellites and radars. A prototype was implemented in the National Center for Atmospheric Research (USA).
CHAPTER 1. MACHINE LEARNING: THE RANDOM FOREST PARADIGM 21 •Kalliguddi [24]: flight delay time prediction using Random Forest, taking into account the different times in airport. In this case, Random Forest was used as a regression estimator and it outperformed the other ones. •Wen et al. [25]: path loss prediction for aircraft cabin environments, with the objective of using wireless communications. Again, Random Forest was used as a regression estimator, leading to successful results very similar to real measures. 1.2.6.3. Space exploration We will move on to another subject that has also been widely explored by different researchers, which is the applications of Machine Learning algorithms, particularly Random Forest, to Space exploration tasks and problems: •Foil et al. [26]: due to the problems in communications for interplanetary missions, as the Mars ones, this research explores the idea of implementing a Random Forest classificator of terrains to a Rover, so it could identify the derivable paths by its own. The results brought around a 80% of accuracy. •Ono et al. [27]: a very similar experiment to the previous one, with the aim of detecting different types of terrain and then introduce the outcomes to a path planner. Very similar results, assessing the functionality of Random Forest for this purpose. •Li et al. [16]: very similar to the aviation fault diagnosis, this one is centred on spacecrafts, motivated by the difficulty of controlling these objects once they are on orbit flight phase. The list of applications can be expanded to a wide variety of field, for instance, wind energy short-term power predicting, important feature genes selection method of tumor, cardiac arrhythmia diagnosis, or even lipreading using Random Forest classification. In any case, the principle of the Random Forest algorithm remains the same, that is, it is applied following a similar process and leading to very interesting and challenging results that open the automation of multiple tasks and problems.
28 Spectral automated classification in large databases To distinguish the spectral properties of both WDs and MS stars in the spectra, we are studying mainly M-type stars, including some K-type at most, since their fluxes are comparable. This is because hotter MS stars outshine the WDs at optical wavelengths and if we have them together in a WDMS binary there is no easy way of determining whether the spectrum is that of a single MS star or that of a binary. Figure 2.4: Example of a WDMS binary spectrum (top panel). The blue is dominated by the WD spectrum (bottom left), while the red has clear M star spectral lines (bottom right). As we have already mentioned, astronomers are interested in finding more and more WDs, because of their importance as Galactic tracers. Also WDMS binaries, in the sense that some characteristics such as effective temperatures, masses, orbital periods or radial velocities can be directly determined from their spectra. The study of WDMS has been fundamental to improve our understanding of several open problems in modern astronomy, such as the evolution of close compact binaries, the age-metallicity relation of the Milky Way, the age-activity-rotation age relation of MS stars among others. 2.2. Statement of the problem Astronomers rely on the identification of WDs and WDMS spectra within large spectroscopic databases. For example, the Sloan Digital Sky Survey [42] has provided the most complete and homogeneous spectroscopic catalogues of WDs, MS stars and WDMS to
CHAPTER 2. AN ASTROPHYSICAL PROBLEM: DISENTANGLING TWO MIXED SOURCES 29 date [43,44]. In total, 3294 WDMS spectra have been found [45] (see more details in Chapter 4). So far, the spectral classification of WDMS binaries has been performed using different techniques, for example a wavelet transform or a χ2-based algorithm that fits the observed spectra with WD, MS or WDMS model spectra [46]. However, this figures are expected to be sooner surpassed by large data base missions, as Gaia. In its data release 3, expected for the first half 2022, nearly 1 billion spectra will be provided. This huge amount of information is out of human reach. Consequently, artificial intelligent algorithms, such as the Random Forest presented here, become optimal methods to address this problem. In this sense, machine learning algorithms have been probed to be feasible tools in tackling these problems. Neural networks, for instance, have been widely used in the classification of Galactic populations [1,2]. In particular, [3] have used neural networks and principal components analysis in tackling a similar problem as ours, that is, on automated classification of stellar spectra. However, during the last decade, Random Forest algorithms have been proved to be a more versatile and powerful tool in identifying and classifying stellar populations [4]. The receiving signals of the sources contain a lot of information revealed in their spectra that can be used to train and test the Random Forest algorithm. Because the current large spectroscopic databases provide spectra in the optical, these sources have flux values for each wavelength between ≃3,800–11,000 ˚ A. However, the signals are captured with a particular spectral resolution, due to the limitations of the instruments. This parameter must be studied in order to see how its variation influences the classification power of the Random Forest. Besides, we must also take into account that the signals are affected by noise, as it is natural in all kinds of signal processing tasks. Its contribution to the deterioration of the signal must also be treated in this project. In addition to the spectral resolution and noise, which depend on the instrument and the environment, there are two more variables intrinsic to each source that make the spectral features to change. These are the effective temperature (Teff) and the surface gravity (log g) of the stars. Although the problem to be treated here arises in a Astrophysical context, it can be easily generalized to a wide variety of telecommunication situations. There are several problems of signal separation and most of them are found in the digital signal processing area, for instance, the cocktail party problem [47]. In this situation, there are different microphones capturing the conversations of multiple people, that is, mixed signals. The aim is to isolate each one of the individual sources, with the additional drawback of the presence of noise. Another example would be the signals collected by a radar used in the aerospace field [48]. It is necessary to extract the unknown independent radar signals from unknown sources. In both cases the Random Forest can classify the different signals and identify the patterns that differentiate them, in order to separate the mixed sources.
CHAPTER 3. PRE-PROCESSING AND DATA PREPARATION This Chapter addresses all the pre-processing tasks that have to be performed previous to obtain a proper estimation. This includes analysing the information related to the data that will be fed to the classifier. 3.1. Population samples In order to train the Random Forest algorithm we built synthetic samples of WDs, MS stars and WDMS binaries. We used the Phoenix MS star library [49] and collected MS star spectra of three different values of the logarithmic surface gravity: 4.5, 5 and 5.5 dex. Their temperatures range from 2,500 to 4,200K in steps of 100K, so in total we obtained 54 MS star model spectra. Regarding the WDs, we used the WD model spectral library of D. Koester [50], containing thirteen different values of the logarithmic surface gravity, from 6.5 to 9.5 dex in 0.25 steps. Their temperatures range from 6,000K to 10,000K in 250K steps, from 10,000K to 30,000K in 1,000K steps, from 30,000K to 70,000K in 5,000K steps, and from 70,000K to 100,000K in 10,000K steps. In total, we had 611 WD model spectra. Given that the MS and WD spectra outlined above are model spectra, their resolution is virtually infinite. The current instruments will never be able to obtain spectra with such a level of resolution, but these ones are useful in this project considering that we can downgrade their resolution in order to study the effects of this parameter on the Random Forest algorithm. It is also important to notice that the spectra are not affected by any noise, which is generally the case in real spectra. The first issue with the data sets is that they are not balanced, meaning that the number of WD and MS model spectra are different. According to Brieman [13], the Random Forest (in general, most of the classification algorithms) does not work very well with unbalanced data sets. If there are more objects of one class than of another, the Random Forest will use statically more objects of that abundant category to build the trees. As a result, the Decision Trees will be trained to know more about this category and the predictions will be good for one class, but not for the others. There are different approaches to solve this problem. For instance, applying weights to the classes or sampling the data, up or down, in order to equalize the set. In this particular case, we are assuming that in a real population the MS spectra will be very similar to the simulated samples, which is a very good assumption. It is not a problem to interpolate between the different temperatures of the model spectra to obtain more samples and balance the data set. This process is called over-sampling and does not add information, as it just replicates the existing data, but it allows to increase the amount of the less-common samples without losing information in return for over-fitting, but this should not be a problem as we expect the new spectra to be similar to the model. After interpolating the temperatures for each surface gravity we obtained 273 temperatures of the MS stars, ranging from 2,500K to 4,200K in 6.25K steps, approximately. In total we thus obtained 819 MS spectra, from the initial 54 available. So as to maintain about the 31
32 Spectral automated classification in large databases same amount of stars of each population, finally from those 819 only 615 were chosen, ranging all the available temperatures and surface gravities. For the WDMS binaries there are not available simulated spectra, so we decided to create them by combining the fluxes from the MS and the WD model spectra introduced before. This was possible because all the spectra have calculated fluxes at a fix distance of 200 pc. This process could lead to having more than half million WDMS spectra, but with the objective of having a balanced data set, only 729 were generated with 27 MS and 27 WD stars from all the range of temperatures and surface gravities. 3.2. Resolving power and SNR As we have already mentioned in the previous section, the WD, MS and WDMS model spectra are virtually at an infinite resolution and are not affected by noise. Given that real spectra are at given limited resolution and are affected by noise, our firts task is to model the simulated data according to the possible resolutions of the spectra and Signal-to-Noise ratios (SNR). The spectral resolution denotes the capacity of certain spectrograph to resolve consecutive peaks in a electromagnetic spectrum. It is represented by ∆λ and it indicates the minimum difference in wavelengths that can be distinguished. Some different definitions of resolution can be found in the literature, depending on where the minimum peak separation is measured, but the two most common ones are the peak width and the valley definition [51]. The former one measures the ∆λ as the width of the peak at a certain flux value, normally at 50% of the peak maximum, called the Full Width at Half Maximum (FMHW). The last definition relies on the valley between two peaks, which is the minimum space between two maximum values, and it is measured at a specified fraction of the peak height [30,52]. When expressing the spectral resolution of an instrument, it is also common to use the concept of resolving power, R, defined as: R=λ ∆λ,(3.1) where λis a considered wavelength, and ∆λ is the difference between peaks that can be distinguished, i.e. resolution. This is for example the measure used by the Sloan Digital Sky Survey spectrographs [53], where the resolution ∆λ is calculated at FMHW. In order to be consistent with the current scientific methodology and terminology, all the resolution units in the present project will be expressed as resolving powers. It is worth mentioning here that the resolving power has a direct consequence on the Random Forest performance. Depending on the resolving power, the number of features used by the Random Forest algorithm will change. That is, a higher resolving power means a higher number of flux values, which in turn means a higher number of spectral lines or wavelengths, that are the input variables of the algorithm. Having more features could be beneficial for the classification or not, depending on whether those features are independent one from each other or they are related. On the other hand, the SNR is the ratio between the signal of a spectrum (which depends
CHAPTER 3. PRE-PROCESSING AND DATA PREPARATION 33 on both the intrinsic brightness of the star and its distance) and the noise. We define noise as the random contributions of different sources that affect the measurement of the signal, and some of the most relevant types are shot noise (associated to the randomness of the photons that arrive to the spectrograph) or read-out noise (associated to image sensor onchip amplifier/s). The SNR measures how well the spectrum of a certain object is obtained by the spectrograph [54], so a SNR below 2 or 3 means that the stellar object is mainly dominated by noise, and from 5 or 10 the spectral features of a given object can generally be discerned. In order to keep the simplicity of this project, we opt for applying a white noise affecting all of the wavelengths and having a constant power spectral density. It will have a Gaussian distribution, with a certain mean µand a certain standard deviation σ. The mean is set to 0 and the standard deviation will depend on the value of the SNR. In conclusion, we are adding an additive white Gaussian noise (AWGN). The calculation of the SNR with a Gaussian noise is straightforward, and we can get an approximation of the SNR for our theoretical model spectra in the following way [55]: SNR =µsignal σnoise (3.2) The advantage of applying this type of noise is that it affects all the wavelengths, so we can consider it a global noise that covers different kinds of noises, but keeping certain simplicity when applying it due to its easiness to program. Taking all of that into account, we have decided to vary the resolving power from 1 to 83,000, and the SNR from 0.25 to 100. The resolution values are set to cover a wide range of resolving powers that could be possibly achieved by real spectrographs. The lower limits on the values of SNR and resolving power are chosen to analyse how the Random Forest performs with poorly resolved and noisy data. This analysis can therefore serve to future studies as an estimation of the possible classification results. MS population WD population WDMS population Initial number of models 54 611 0 Final number of models 819 611 729 Temperature (K) 2,500–4,200 6,000–100,000 2,500–4,200 for MS 6,000–100,000 for WD Surface gravity (log g) 4.5–5.5 6.5–9.5 4.5–5.5 for MS 6.5–9.5 for WD Resolving power 1–83,000 SNR 0.25–100 Table 3.1: Simulated spectra summary. To sum up, Table 3.1 contains the information of the three star populations that will be analyzed and classified by our Random Forest algorithm: the number of individual models, their physical parameters and the parameters that affect the classification that will be studied.
34 Spectral automated classification in large databases 3.3. Performance cross-validation Before building the Random Forest model, we must establish the method of crossvalidation that we will be using. That is, how we will divide the original data set in order to train and test the algorithm. The option of testing the Random Forest with the same sample that it was trained with is not viable, in the sense that it would always have a perfect performance but it would not classify new unknown data in the same way. This is called over-fitting and to avoid it usually a part of the original available data set is saved for the testing section. This process can be done in many ways. One of the most straightforward is using a tool called train test split. It automatically and randomly divides the input data set and its classes in two groups, training set and testing set, each one with a certain number of objects indicated by a user-adjustable percentage. This function allows to keep track of the specific samples that are going to be tested in a very simple and quick method, so after the classification is made the user can easily compute all the metrics. Another approach would be to use the Out-Of-Bag samples. They are a small percentage of the training set that the Random Forest algorithm uses to validate the performance of the classification. The sci-kit library [14] has this technique implemented, but only a score can be retrieved, so it is difficult to interpret it since the samples that are used cannot be known. It could be useful if we wanted to have a vague idea of the classification performance, as a validation set, but not in the present project. The last option is the k-fold Cross-Validation. The whole training data set is divided into ksmaller sets and the estimator is then trained with k−1of the folds, being validated using the remaining fold. After this process is repeated for each one of the kfolds, the general performance is computed by averaging each one of the kresults. This method is very complete and a different variety of metrics can be calculated, but the problems are that it can be very expensive computationally and the objects used for each fold cannot be known. However, it takes advantage of the whole data set and does not damage the training set by taking samples to the validation set. It is commonly used when the user wants to evaluate different settings, as the hyperparameters, because there is the risk of over-fitting on the test set, so it is necessary to have a third set to validate the estimator and check its correct working. In Figure 3.1 we can see a simple scheme of a 5-fold Cross- Validation that is used to find the best setting of parameters. In this case, the training set is divided in 5 folds, 5 times. Each time, 4/5 of the set is used as training (in green) and the remaining part is used as validation set (in blue). After the process, another testing set can be used to finish the evaluation of the classifier. Although this cross-validation method is a solid option, it will only be used for the normalization and hyperparameter adjustment on Sections 3.4. and 3.5., because we just want to obtain a general score to validate the algorithm in both cases. For the rest of the project we have decided to use the train test split function, because we also want to analyze the classification outcome, element by element. This function allows us to do that, but not the k-fold method. It is a very easy tool that does not use a lot of resources, it can be managed to obtain a large amount of information about the training and testing samples and it is useful to get the different metrics with no further complications. The only parameter that must be adjusted is the percentage of training and testing set that we want the function to divide
CHAPTER 3. PRE-PROCESSING AND DATA PREPARATION 35 Figure 3.1: k-fold Cross-Validation scheme. the whole data set. There is not any specific rule and it depends on the type of the data and, mainly, on the objective of the user. It must be taken into account that a high testing percentage entails a low training percentage, meaning that the Random Forest will not be able to classify unknown data because it lacks of classification power. If we set a very high training percentage and the number of objects is low, we could probably fall in over-fitting. As a starting point, we have chosen a training set of 70% and a testing set of 30%. 3.4. Normalization Once the data samples have been prepared, it is important to study if there is need of applying some kind of normalization. Usually, Random Forest will support non-normalized data and even sometimes doing some sort of scaling will affect positively to the classification, but it always depends on the type of data that we are working with. According to Li et al [56], spectral data classification is enhanced if it is beforehand normalized, because stellar objects that belong to a same type can change to a greater or lesser extent due to detector sensitivity, their brightness or their distance from the spectrograph. The main problem is to choose which scaler or normalizer is the best to apply to the dataset, taking into account that the features will be totally changed and consequently, the Random Forest performance. In the sci-kit library [14] that is used in the ongoing project, there are already implemented different pre-processing tools that are used to standardize and normalize the data. Some of them are explained below and their performance will be tested in order to decide which one is the best for the current problem: •Standard scaler: removes the mean of the training samples and scales them to unit variance. It is essential in some estimators that do not perform well if the data
36 Spectral automated classification in large databases is not distributed following a Gaussian with null mean and unit variance, because an outlier with higher variance could dominate the estimation function. It is calculated as: Xscaled =X−µ σ,(3.3) where Xis the actual data, µthe data mean, sigma the data variance and Xscaled the outcome of the scaler. •MinMax scaler: scales each feature individually in a range from the minimum value to the maximum value of that feature from all the objects. It is applied in the following way: Xstd =X−Xmin Xmax −Xmin −→ Xscaled =Xstd ·(max −min)+min (3.4) where Xis the actual data, Xmin,max are the minimum and maximum values, respectively, of the feature, and (min,max)are the extreme values of the range that we want to convert the data to, default is 0 and 1. •MaxAbs scaler: scales each feature between 0 and 1, being 1 the maximum value of that feature. It is very similar to the previous scaler, but this one does not leave the option to choose the range of the final values. •Robust scaler: this scaler uses statistics that are robust to outliers, by removing the median and scaling the data according to the quartile range, that is, between the 1st and 3rd quartile. It is applied to the features individually. •Power transformer: its objective is to transform the data so it is more Gaussianlike, by applying a parametric transformation. There are two types of methods, Yeo- Johnson and Box-Cox, the latter only being useful with strictly positive values. •Quantile transformer: this transformer aims to change the features so they follow a normal or uniform distribution, while reducing the impact of outliers. To do that, a quantile non-linear function is applied. •Normalizer: normalizes elements individually to unit norm, being able to process large arrays or matrices. It can also normalize individual features, and there are three different types: – L1: normalizes by the total sum of the object, which is Xnorm,L1 =X N ∑ i=1 |Xi| .(3.5) – L2: normalizes by the quadratic sum of the object values, Xnorm,L2 =X N ∑ i=1 X2 i .(3.6)
CHAPTER 3. PRE-PROCESSING AND DATA PREPARATION 37 – Max: normalizes by the maximum value of the object, Xnorm,max =X max(X).(3.7) A priori, we would think that the better option is to normalize each object individually, because normalizing each feature could lead to inconsistencies due to the characteristics of the data, which are multiple spectra. However, a quick test was made in order to assure which method threw the best results. Figure 3.2: Accuracy comparison between different scalers. In Figure 3.2, the different explained scalers and normalizers are compared according to the performance of the Random Forest. Only the accuracy metric is used, but it is enough to get an idea of the working of the scalers. The classification has been made using the maximum values for both resolving power and SNR, hence the high accuracy scores, but the results can be generalized to any value. In order to prepare the validation set, a kfold Cross-Validation was applied, as stated in the cross-validation Section (3.3.). We can see that generally, all the scalers have a good performance (i.e., Accuracy >0.99), with the exception of the Power Transformer. It is understandable, because this transformer changes the data to be Gaussian-like, which is not compatible with the spectra data. There is a scaler that stands out, which is the Normalizer, and it makes sense because it affects the objects individually, not the features. Among the different Normalizers, the L1 is the one with the highest accuracy score (red dot), which normalizes the data by the total sum of each element. Consequently, in our calculation we will adopt L1 given that is the simplest and has the highest performance. 3.5. Hyperparameter adjustment Prior to running the Random Forest with the data set, it is also necessary to set the hyperparameters of the algorithm [57,58]. Although there are automatic techniques, such as a
44 Spectral automated classification in large databases Figure 4.2: MS recall density map as a function of Rand SNR. Figure 4.3: WD recall density map as a function of Rand SNR. Figure 4.4: WDMS recall density map as function of Rand SNR.
CHAPTER 4. SIMULATED DATA CLASSIFICATION 45 Figure 4.5: MS precision density map as a function of Rand SNR. Figure 4.6: WD precision density map as a function of Rand SNR. Figure 4.7: WDMS precision density map as a function of Rand SNR.
46 Spectral automated classification in large databases 4.1.4. F1-score maps In the last trio of Figures 4.8,4.9 and 4.10, we represent the F1-score, also known as balanced F-score. This metric is the weighted average of the recall and the precision, so we could consider it as the measurement that includes all the information about the different populations, being the most interesting from a user’s point of view. In general, we see the same behaviour in all of the three populations, with the threshold around R≈300. The MS stars, (Figure 4.8) barely reach the 95% level, only for values of R above 300 and SNR higher than 100, but the score is generally high (more than 80%) and only starts to degrade for really low values of Rand SNR. In this case, for most resolving powers and SNR the algorithm will correctly classify the MS population spectra more than 80% of the times, at least theoretically. It is also a good sign that the contour lines are a bit separated, so that the score does not plummet if any parameter is slightly changed. Attending to the WD spectra map on Figure 4.9, although the general behaviour is similar to the MS population, the results are much better. The maximum score is able to even reach almost 100%, being this population the best classified by the algorithm. We find an extensive white area, meaning a 2σlevel of confidence, in which the WD stars will most probably be correctly categorised. This region covers low values of Rwith high SNR, and overall, Rfrom 30 on and SNR above 30. In a similar way to the MS population, the F1- score does not rapidly descend for most values, only for the worst section of the map (the left lower corner). Finally, Figure 4.10 shows the WDMS F1-score map. The range of the metric is nearly the same as the MS population, but in this case the contour lines are much closer, meaning that this category is deeply affected by the changes of Rand SNR. Apart from that, we could say that the algorithm performs with a correctly classification of the WDMS population 68% of the times (σconfidence) for most values of Rand SNR, specially Rabove 100 and SNR above 5. It may not seem as a very high percentage, but this result must be taken as a preliminary value to bear in mind when applying the RF.
CHAPTER 4. SIMULATED DATA CLASSIFICATION 47 Figure 4.8: MS F1-score density map as a function of Rand SNR. Figure 4.9: WD F1-score density map as a function of Rand SNR. Figure 4.10: WDMS F1-score density map as a function of Rand SNR..
48 Spectral automated classification in large databases 4.2. Performance at specific values of Rand SNR After analysing the overall performance of the Random Forest depending on a wide range of Rand SNR values, we will now focus on three specific pairs: •Case 1 - high resolving power and high SNR: R=80,000 and SNR=100. •Case 2 - intermediate resolving power and medium SNR: R=1,800 and SNR=10. •Case 3 - low resolving power and low SNR: R=40 and SNR=1. Case 1 represents the most ideal scenario in which we not only have high-resolution spectra but also high SNR. This can be achieved for example at the Galileo Telescope located in La Palma using the HARPS spectrograph. The intermediate case (Case 2) is very similar to the spectra provided by the Sloan Digital Sky Survey public data base (which will be analysed in the next Chapter 5). Case 3 covers the worse case scenario of both very low R and SNR. This combination is unlikely in real observations but it is important to consider it because the results obtained should summarise the lowest expectations the user can get from the Random Forest performance. 4.2.1. General classification performance The three cases will be evaluated in this section and in the two following ones. For each case we will analyze several metrics and scores and we will also give examples of different misclassified spectra and the possible causes why the Random Forest was not able to correctly process them. 4.2.1.1. Case 1: high resolving power and SNR The number of features that the Random Forest has to process in this case goes up to 200,000, so the computation time is the highest. After averaging the results of 100 Random Forest realizations, we obtain the confusion matrix illustrated in Figure 4.11. The confusion matrix has been normalized by each population, that is, the numbers shown are the ratios of samples per population. The color bar in the right provides the ratio per population. We can see that the algorithm has a very good performance. The category with the worst percentage is the MS population, with a 93.7% of the samples being correctly classified and only a 6.35% that was wrongly assigned to the WDMS population. Attending to the WD stars, we have an almost perfect classification, being mistaken as WDMS only a 2% of the times. For the WDMS population, the correct ratio is also very high, having only a ≃5% of misclassified samples: 3.5% as MS and 1.17% as WDs. We also check that the MS and WD populations are not confused between them. We expect all the confusion matrices to follow the same trend, otherwise it would be a sign that there is something in the algorithm that is malfunctioning. Predominantly, the most difficult disentangling case would be between the MS and WDMS population, as both of them have the highest wrongly classified ratios.
CHAPTER 4. SIMULATED DATA CLASSIFICATION 49 Figure 4.11: Confusion matrix for Case 1. We can say that the WDMS population case reaches a 2σconfidence level although the MS percentage is lower than 95%, but the difference is very small and may be due to the randomness that characterizes the algorithm. Besides, that remaining 5% could be spectra that is indeed very difficult to differentiate, especially by humans. Some examples of misclassified spectra are shown in Figure 4.12. Figure 4.12: Example of single objects misclassified in Case 1. MS spectrum (left panel) and WD spectrum (right panel). Both single populations are only misclassified as WDMS, as stated before. Looking at the MS spectrum (left panel of Figure 4.12), it could seem unusual that the Random Forest does not classify it as a MS star, but we must recall that WDMS models are built from MS and WD single models. This specific MS star has a very high temperature, not even belonging to the M-class but being a K-class star. This fact means that, on average, the flux magnitude is higher than other MS models and also than most of the WD stars considered. Thus, when creating WDMS models with this MS star, it dominates over the WDs in most of the cases and their spectra are virtually identical to those of single MS stars. As a consequence, a MS star with a very high temperature is mostly considered a WDMS star,
50 Spectral automated classification in large databases but in return, the WDMS spectra that contain a dominant MS star will be correctly classified. In conclusion, there is probably a trade-off between correctly classifying WDMS binaries with a dominant single star but misclassifying the single population, or misclassifying the WDMS but correctly classifying the high-flux MS stars. This issue will be further discussed in Section 4.2.3. Regarding the WD star that has been wrongly categorized (right panel of Figure 4.12), we can guess that it is a similar quandary. This WD has a very high temperature and will dominate over cold MS stars, leading to a training sample with multiple WDMS binaries that contain this dominant WD. Figure 4.13: Example of binary object misclassified in Case 1. We can also find examples of WDMS binaries with dominant WDs or MS stars that have been misclassified by the Random Forest as single WDs (right panel of Figure 4.13) or MS stars (left panel of Figure 4.13). The algorithm finds it very difficult to distinguish between single stars and WDMS binaries in which one of the components dominates the flux emission. Figure 4.14: ROC curve and AUC score for Case 1. Finally, in Figure 4.14 we show the ROC curve for case 1. We recall that the ROC curve represents, for each population, the True Positive and False Positive rates. These rates
CHAPTER 4. SIMULATED DATA CLASSIFICATION 51 are the recall or sensitivity of the algorithm and the probability of false alarm, respectively. The first one exhibits how many True Positive (correctly labelled) samples occur among all Positive (true labelled) objects, while the second defines the number of incorrectly labelled samples among the Negative samples available (objects that do not belong to the class that is being studied). We can see that for all three classes the curve is almost a 90-degree angle, which is the perfect case. The curve that is above the rest and is virtually perfect is the WD, which makes sense since its recall and precision were the best and unaffected by other categories. The worst population would be the WDMS, because there were objects labelled as both single populations and viceversa, which affect both rates negatively. The MS population has also a very good score, comparable to the macro-averaged one. The AUC scores are just a numerical confirmation of the significance of the different curves, and we could generally agree that the Random Forest algorithm performance works very well in this case. 4.2.1.2. Case 2: intermediate resolving power and SNR We continue this analysis with the second case, i.e., an intermediate resolving power of 1,800 and an average SNR of 10. These values are typical of the Sloan Digital Sky Survey public spectroscopic data base. Figure 4.15: Confusion matrix for Case 2. The results on the confusion matrix (Fig. 4.15) reveal an overall worst classification than for Case 1, as expected. The WD population classification is enhanced, reaching a 99.3%, and the MS population has around a 93% of the samples correctly classified. However, we get a very degraded percentage for the WDMS binary population, only a 74% of the objects. The misclassified spectra is almost equally distributed between both single populations, with around 12-13% for each. This deterioration of the results is probably due to the lower SNR, according to the accuracy and F1-score maps of the previous section 4.1., but we will get more details by studying examples of the misclassified spectra. We show examples of a missclaffied MS spectrum and a missclassified WD spectrum in Fig.4.16, where we can appreciate the effect of the higher noise power on both objects,
52 Spectral automated classification in large databases Figure 4.16: Example of single objects misclassified in Case 2. MS spectrum (left panel) and WD spectrum (right panel). Figure 4.17: Example of binary object misclassified in Case 2.
CHAPTER 4. SIMULATED DATA CLASSIFICATION 53 Figure 4.18: ROC curve and AUC score for Case 2. which degrades the classification power of the Random Forest. Missclassied examples of WDMS spectra can be found in Figure 4.17. in these two cases the WD (left panel) and the MS star (right panel) have fluxes that do not overcome the noise level. Regarding the ROC curves and their respective AUC scores for Case 2 (Fig.4.18), we can observe very sharp curves for the single populations and the macro-average, but the AUC scores denounce substantial worse scores than in the first case. This is because even though the populations are very well classified, there is a certain rate of False Positives (WDMS classified as single stars). The WDMS curve is now visibly weaker than the others, due to the worse performance of the Random Forest for this class. 4.2.1.3. Case 3: low resolving power and SNR Figure 4.19: Confusion matrix for Case 3.
60 Spectral automated classification in large databases Figure 4.28: WDMS misclassification according to the WD stellar parameters. tion does not depend on the temperature, only on the surface gravity. But for colder WDs, there is a nearly linear dependency on both of them, unlike the MS parameters. We notice that the colder the WD and the lower its surface gravity, the spectrum is more likely to be classified as a MS star. The white area on the right up corner corresponds to binaries that have not been misclassified anytime, so they do not belong to any of the subgroups. These four figures have contributed in a significant way to help us clarify the performance of the Random Forest algorithm in relation to the binary stars, which were the least accurately detected. We expect that the other two Cases follow a similar trend to the one that we have analyzed, but with their particular characteristics. The Case 1, with a better performance, has bigger areas with higher recall scores, and the darker areas concentrate in colder temperatures for both MS and WD components, as the noise contribution is not a problem. On the other side, the Case 3 has a very degraded performance (overall of the WDMS population), so we obtain figures with darker areas, but with a similar behaviour to the ones that we have displayed. The figures are shown in the Appendix Das a complementary description of the Random Forest for the two cases. 4.2.3. RF performance variation for different flux component ratios in WDMS binaries One issue that has been constant through the different analysis of this Chapter is the misclassification of WDMS binaries with one dominant component as single stars and vice versa. That is the reason why we have opted for delving into this matter. 4.2.3.1. Flux relation definition For the Random Forest to distinguish the WD and the MS components in a WDMS spectrum both of them have to emit enough flux, otherwise the algorithm will confuse the spectrum with that a single star. The obvious question is whether we can set a threshold on the
CHAPTER 4. SIMULATED DATA CLASSIFICATION 61 flux ratio between the two stars for the Random Forest to distinguish the spectrum as that of a WDMS. With this in mind, we define fblue of a given spectrum as the mean of its flux between 4,000 and 4,500 ˚ A. The same would apply to the fred but between 8,000 and 8,500 ˚ A. With these two parameters, we are able to characterize the single star spectra, expecting fblue >fred in the WD stars and fblue <fred for the MS objects. When generating a WDMS spectrum, we directly sum the flux of the WD and MS components, as stated in Section 3.1. By doing this, we are able to compare the flux measurements of the two stars that have been combined, obtaining a ratio of fluxes in the blue and another one in the red. Those values will be the ones defined as flux relations: f lux relationred/blue =f1,red/blue f2,red/blue (4.1) where f1/2,red/blue refers to the defined flux of a star either in the red or in the blue. To standardize this metric, we take the star with higher flux always in the numerator of the quotient (so the resulting flux relation is always over the unity) and we consider the minimum of the two ratios in each spectrum since it is the one that truly indicates how dominant is one star over the other. In other words, we define the flux relation of a WDMS spectrum as the minimum flux ratio in the blue or in the red between the star with higher mean flux and the star with lower mean flux, measured in the ranges stated before (4,000 to 4,500 ˚ A and 8,000 to 8,500 ˚ A). 4.2.3.2. Flux relation effect on classification performance With the previous definition, we are able to compute the flux relation for the different simulated WDMS stars and compare it to a performance metric to see its evolution. As we are dealing with individual objects and how they were classified, we can only compute the recall score. Once more, the references will be each one of the three cases proposed on section 4.2. Figure 4.29: WDMS recall as a function of flux relation for the three cases under study.
62 Spectral automated classification in large databases Figure 4.29 represents for each of the three cases under study the change of the recall as a function of the flux relation of the binary stars. Starting with Case 1, (R=80,000 and SNR=100), we expect a high recall in average. For lower flux relations the recall is higher, and it keeps descending until around 200. We observe an ascension in the last segment, from 200 to 4,000, which may not seem to agree with the tendency. However, the graphs that represented the single star parameters versus the WDMS recall (see Figure 4.25) showed a high recall for hotter MS stars. At first sight, it would be very hard to detect any binary with a flux relation over 10 or 20, in the sense that the minimum difference of magnitude between the two single stars would be a 10% of the dominating star, but the algorithm seems to be doing fine even for higher values. Continuing with Case 2 (R=1,800 and SNR=10), we encounter a similar behaviour but with worse scores. For lower flux relations, the recall is continuously decreasing until around 100, where it slightly increases back to approximately 40%. This score implies that the algorithm is confusing more binary objects as single population stars, so we are not able to trust the outcome of the classification. For the last Case 3 (R=40 and SNR=1), the behaviour of the algorithm is practically random, with an average of 50% of the stars correctly classified in accordance with Section 4.2.1.3. where we commented its metrics. There are parts with higher recall, reaching the 60%, but we could take them as fluctuations of the algorithm. 4.2.3.3. Flux relation threshold It would be intriguing to know how the classification is altered if we impose a threshold in the flux relation of the binaries for the training set. We tried to recreate this experiment, establishing three different thresholds to the binary training population and seeing the results of the classification. To achieve that, we have fixed the Rand SNR values for the whole dataset, and then we have removed from the training set the binaries with a flux relation above said cut. The testing set, however, will remain with all the available binaries. By doing this, we assure that the population that would be unlabelled in a real mission maintains all the possibilities for a binary star, from those with low flux relation to those with high values. As in the previous analysis we only process the Case 2 as the most representative case. We show the ROC curvess for the different populations and for three different thresholds (10, 50 and 100; higher cuts do not reveal significant information given that there are fewer objects with such high flux relations) in Fig. 4.30. All the curves are very close to the perfect case, and apparently the thresholds do not benefit the classification, as the area of the curves get smaller. The effect of adding a threshold cut is that more objects belonging to the single populations are correctly classified, but at the expense of missclassifying more binary objects. Attending to the WDMS population, the thresholds help to raise the precision of the class but with the traded-off of lowering the recall. In general, not setting a threshold is the best initial assumption, obtaining good results in average for the three populations. The threshold cuts at 50 and at 100 behave almost in the same way, and they could help to better classify the single populations. The lower threshold could be used to refine the single populations, but many binary objects would be
CHAPTER 4. SIMULATED DATA CLASSIFICATION 63 Figure 4.30: ROC curve comparing different thresholds for the different populations. MS population (top left panel), WD population (top right panel), WDMS population (bottom left panel) and legend (bottom right panel). wrongly classified. For the subsequent parts of this project we will not adopt a flux relation threshold.
CHAPTER 5. RANDOM FOREST CLASSIFICATION OF SDSS SPECTRA In Chapters 3 and 4 we have prepared the simulated data and obtained a classification model whose performance has been analyzed. The next step should be testing the algorithm with observed data, already labelled, in order to compare the results. This is the main objective of this Chapter, in which we will study spectra from the Sloan Digital Sky Survey (SDSS) belonging to MS, WD and WDMS populations that have been already classified. We will prepare the simulated data to train the Random Forest model and classify the observed samples to obtain the performance metrics. Then, we will propose some improvements to the classification method, in order for the results to be more similar to the SDSS catalogue. 5.1. The Sloan Digital Sky Survey The Sloan Digital Sky Survey (SDSS) [59,60] is one of the most detailed and largest astronomical surveys ever made, carried out with the collaboration of hundreds of international scientists from different institutions. It has obtained spectra of more than three million objects. With this, the SDSS has contributed to the scientific advance in the knowledge and understanding of the structure of the Universe. It started collecting data in 2000 and has advanced through different phases, from the SDSS-I between 2000 and 2005, until the SDSS-IV that finished in 2020. Right now the project is in its fifth phase, which is expected to provide a huge spectroscopic backbone that will help to achieve the full science potential of space missions like Gaia. SDSS spectra are obtained with a 2.5m optical telescope located at the Apache Point Observatory in New Mexico using a pair of fiber-fed double spectrograph covering the wavelengths from 3,800 ˚ A to 9,200 ˚ A with a resolving power (R=λ/δλ)of 1,800. The spectrograph’s throughput along these said wavelengths is available in Figure 5.1. Each one of the two spectrographs gathers information, one in the blue - from 3,800 to 6,150 ˚ A - and the other in the red – from 5,800 to 9,200 ˚ A. The two lines in Figure 5.1 represent each one of the CCDs (image sensors) where the spectrographs collect the data. That is, for the blue wavelengths we have one spectrograph collecting data with the throughputs indicated by Blue-1 and Blue-2, each one corresponding to a CCD, and the same for the red spectrograph, with Red-1 and Red-2. These instruments capture intermediate resolved spectra from millions of stellar objects. Among them, we can find MS, WD and WDMS stars. The SDSS contains the most complete spectroscopic catalogues of these types of stars, which were classified thanks to different techniques that involve human supervision. A group of these already labelled spectra was downloaded and used in order to compare with the automatic classification. 65
66 Spectral automated classification in large databases Figure 5.1: SDSS spectroscopic throughput. 5.2. Data preparation We extracted a practically balanced sample containing 2,340MS, 2,031 WD and 2,552 WDMS - that is, a total of 6,923 spectra from the full catalogues. We think that there are enough objects to validate the Random Forest classification, as they cover all different possible values of stellar parameters. Practically all of them had the same resolving power with the flux values at the same wavelengths, but some started or ended at different values. Introducing a cut from 3,850 to 9,150 ˚ A, we achieved that all of them had exactly the same range. Additionally, the spectra have an estimation of the error for the flux at each wavelength, which can be used to calculate an approximation to the SNR in the following way: SNR = N ∑ i f luxi errori N,(5.1) where irefers to each one of the wavelengths available in the spectra, f luxiis the value of flux for that wavelength and errorithe error estimation at that certain wavelength. The total number of wavelengths is represented by N, where N=3,760. The range of SNR for the chosen SDSS spectra goes from 0.45 in the worst case to 100. In order to better figure out the distribution of the SNR, Figure 5.2 depicts an histogram of the range of values that the SNR can take. Most of the objects have SNRs below 50, with an average around 11. It is worth noting that there is a large fraction of objects with a SNR as low as 5. This fact could be a problem when classifying the spectra, as we have seen in Chapter 4 (4.1.) that with a resolving power higher than 300 the performance of the algorithm only depends on the SNR.
CHAPTER 5. RANDOM FOREST CLASSIFICATION OF SDSS SPECTRA 67 Figure 5.2: SNR histogram of the SDSS spectra. All the objects mentioned above will constitute the testing set of the classification, in the sense that they already have a label and we want to check the class that the Random Forest algorithm assigns to them. Now, we must prepare the training set which will be formed by simulated spectra. We will degrade our spectra with virtually infinite resolution to the same value of the SDSS spectra, 1,800, obtaining the resulting flux values for the same wavelengths. Besides, we must add different SNR in order to train the algorithm with as many values as possible, in coherence with the observed spectra. For now, we will continue adding a white Gaussian noise for the same reasons explained in Section 3.2., with a null mean and a standard deviation in agreement with the SNR. To match the observed spectra as much as possible, we considered the following values of SNR: 1, 3, 5, 7, 10, 15, 20, 40, 60 and 100. Therefore, from the starting 615 MS, 611 WD and 729 WDMS synthetic spectra - 1,955 in total -, we obtained a training set composed by 19,550 simulated spectra, with a resolving power of 1,800 and 10 different values of SNR. By doing this, we assure that the algorithm is fed with all of the possible spectra that we expect to be in the SDSS observed sample. Apart from that, all the sets (training and testing) were normalized, as stated in section 3.4. In relation with the Random Forest setting, we adopted the default parameters and applied not further changes with respect to Chapters 3 and 4. When making the classification, we averaged again 100 Random Forest predictions, obtaining less deviated classifications and also being able to compute the probability estimates needed for the ROC curves. 5.3. Classification results The first metric to be analyzed is the confusion matrix (see Figure 5.3). In the three rows we have the label that was assigned to the SDSS spectra, while in the columns we find the Random Forest predicted label. The MS population is the one that presents the greatest disagreement with the observed case, with almost 15% of the objects assigned to the
68 Spectral automated classification in large databases binary population. The WDMS has a higher recall, almost a 90%, being confused mostly with WD objects. Finally, the WDs show a perfect agreement with the SDSS classification. Figure 5.3: Confusion matrix of the SDSS spectra set for the initial Random Forest model. It is important to remark here that the SDSS spectra classified as WDMS binaries clearly display in most cases the two components and, as a consequence, they are undoubtedly WDMS stars. We can assume that these objects are correctly classified and take them as a reference, hence, we expect that our algorithm can also distinguish the two components. However, there is still around 10% of the objects mistaken mainly with the WD population. As examples, we have the spectra of two SDSS-labelled WDMS that were assigned to the WD population (see top panels of Figure 5.4). The one of the top left panel has a SNR of 2, and the MS companion is hardly detected, so it is understandable that that our algorithm is not able to properly classify this object. However, on the top right panel, the contribution of both stars is clearly visible. These spectra are the most commonly missclassified, and we should do some improvement to our Random Forest algorithm in order to fix these issues. A different issue with our Random Forest algorithm is that a relatively large fraction of MS stars are as classified as WDMS. An example is shown in the bottom panel of Figure 5.4. We believe that they are confused as binaries because in the training set there are WDMS stars with dominant MS objects. In addition, the contribution of noise might also confuse the algorithm and make it detect these type of single stars as binaries. As we have stated before, we must take into account that we are comparing two different classifications of real spectra. This means that there might be a percentage of MS and WD objects that were classified as such but that are not, as the Random Forest suggests. Moving on to Table 5.1, we find the different metrics that measure the classification performance of the Random Forest. The accuracy and G−mean are almost the same because the testing set is balanced, and the Kappa coefficient is above 0.8, indicating a good agreement between both classifications. The best precision is found for the MS population, remarking that most of the stars labelled as MS stars actually belong to that class. However, we find lower scores for the WD and WDMS populations. This supports the main problems of the classification described above. To sum up, the algorithm has agreed with
CHAPTER 5. RANDOM FOREST CLASSIFICATION OF SDSS SPECTRA 69 Figure 5.4: Misclassified spectra by Random Forest. WDMS spectra (top panels) and MS spectrum (bottom panel). the SDSS classification in 9 out of 10 spectra. It is not a bad result, bearing in mind that we have trained the algorithm with simulated data, but we aim to enhance that result to better match the SDSS labels, at least in the binary population. The last metric we discuss is the ROC curve, shown in Figure 5.5. This analysis is crucial, as setting a certain threshold could help us to improve the classification and detect most certainly the true class of a spectrum. Starting with the MS population, we find that with a really low threshold we immediately get a very high recall. This means that the objects that have been classified nearly a 100% of the times as MS, will surely coincide with the SDSS catalogue. The WD population, however, is a bit different. The algorithm is able to identify all the WD samples but with a little penalty, i.e. accepting as WD some of the binary objects. Lastly, the WDMS have the worst performance, and only reach a recall of MS WD WDMS Accuracy 0.904 Cohen’s kappa 0.856 G−mean 0.906 Recall 0.849 0.985 0.891 Precision 0.998 0.879 0.855 F1-score 0.917 0.929 0.873 Table 5.1: Classification metrics of the SDSS spectra set for the initial Random Forest model.
76 Spectral automated classification in large databases Figure 5.13: Confusion matrix of the SDSS spectra set for the final Random Forest model. show excellent results, being the worst one the 95.1% precision of the WDMS population. This percentage remarks that there are still spectra from the single populations mislabelled as WDMS. However, as it has been stated in previous paragraphs, we are comparing two different classifications and the disagreements between them should be carefully analyzed. The last metric is the ROC curve in Figure 5.14. The performance is very similar to the one were we used only the new noise model. The MS population reaches the perfect case, while the others have areas around 0.98 and 0.99 for the WDMS and WDs, respectively. We think that setting a threshold cut would not benefit to a greater extent to the performance, as it is already almost excellent. Figure 5.14: ROC curves of the SDSS spectra set for the final Random Forest model. To sum up the Random Forest classification of the SDSS spectra, we display the ROC
CHAPTER 5. RANDOM FOREST CLASSIFICATION OF SDSS SPECTRA 77 curves (see Figure 5.15) of the WDMS population for each one of the results that we have obtained: initial, limiting population (LP), adding a new noise distribution (ND) and the last two combined for the final model. Figure 5.15: Different cases ROC curves for the WDMS population. With this results, we can effectively witness how the performance of the binary population classification is improved with each method. The initial model has the worst classification, and limiting the population improves the MS single stars. As a consequence, less MS objects are labelled as WDMS, which improves the binary population curve. Adding the new noise leads to a general better agreement of the algorithm, and combining the last two methods helps to slightly rise the Random Forest performance, almost reaching a perfect agreement with human classification.
CHAPTER 6. RANDOM FOREST CLASSIFICATION OF FORTHCOMING GAIA MISSION SPECTRA In this Chapter we make use of the Random Forest algorithm that we have developed and tested to evaluate its potential to identify WDs, MS stars and WDMS within the spectroscopic data base that the satellite Gaia will provide in its Data Release 3, expected next year. We will first generate a synthetic sample of spectra that emulates Gaia performance, and then we will adjust our Random Forest algorithm to achieve the best classification. 6.1. The Gaia mission Gaia, the acronym for Global Astrometric Interferometer for Astrophysics, is a space probe launched in 2014 by the European Space Agency (ESA), whose main objective is to create a three-dimensional map of our Galaxy by obtaining information of more than 1 billion stars. The Gaia satellite, located in the Lagrangian point L2 in a Lissajous orbit, is surveying the sky and observing each one of the sources 70 times, leading to big amounts of data recollected in huge databases. Concretely, the down-link information data rate is around 8.7 Megabits per second, resulting in an amount of compressed science data around 40 Gigabytes per day. In total, we are expected to have more than 73 Terabytes over the full, nominal life of the mission, that can rise up to 1 Petabyte (1 million Gigabytes) for the complete data set, taking into account the additional data products that are created from the basic observations. Gaia mission is the successor of Hipparchus, a satellite launched in 1989 that was in charge of charting the position of the stars, producing a catalogue of more than 12 million stars. However, Gaia was built in order to overcome the previous mission, with a betterquality equipment. All of the information that Gaia is collecting is sent raw to the Earth, where it needs to be processed and calibrated in order to be used by the astronomical community. There have been already two releases of data, in 2016 and in 2018, with multiple information as magnitudes, parallaxes or radial velocities [63,64,65]. The Data Release 3 is expected to arrive in 2022, and it is supposed to contain the optical spectroscopic information of the objects. This huge amount of information requires new software and the use of novelty techniques, such as automatic classification algorithms, in order to analyze all its content. 6.2. Data preparation Our first task is to create a set of synthetic spectra emulating Gaia performance. Consequently, we start by analyzing the Gaia spectrograph characteristics. It consists of two low-resolution prisms, one for the blue wavelengths (Blue Photometer or BP) from 3,300 to 6,800 ˚ A and the other for the red wavelengths (Red Photometer or RP), between 6,400 and 10,000 ˚ A [63]. The expected resolving power is quite low and not constant, changing with the wavelength according to Figure 6.1 [66]. 79
80 Spectral automated classification in large databases Figure 6.1: Nominal resolving power according to the wavelength in Gaia spectra. The mean of the resolving power is around 66 and the expected SNR of the spectra depends on the stellar object and its magnitude1. SNR estimates for the MS and WD stars with a magnitude of 13 are shown in the Table 6.1 [66]. SNR BP SNR RP MS star 278 1036.2 WD star 451.9 487.2 Table 6.1: Expected SNR for Gaia spectra and for an apparent magnitude of G=13. 6.2.1. The synthetic Gaia spectra sample In order to mimic Gaia observations we take advantage of a detailed population synthesis modeling of the Galaxy provided by the Group of Astronomy and Astrophysics of the UPC [18]. The simulator, based on Monte Carlo techniques, generates the expected stellar parameters of the population of single WDs, single MS stars and WDMS binaries in the Galaxy that can be accessible by the Gaia satellite. The results of our simulation for a sample of stars at 100pc around the Sun [67] indicate that the percentages of the different populations are clearly unbalanced, resulting 5992:126:167, i.e. 95.34% of single MS stars, 2% of WDs and 2.66% of binaries. In Figure 6.2 we display the distribution of stellar parameters, namely their effective temperatures and surface gravities, for the different populations under study. Based on this simulation we build the testing sets by applying a bivariate interpolation of the temperatures and surface gravities on the three spectral grids of MS, WDs and WDMS (Section 3.1.), thus obtaining the corresponding synthetic spectra for each simulated star of the sample. 1The magnitude of a star is a measure of its brightness applied in a logarithmic scale; the fainter the star, the larger value of the magnitude.
CHAPTER 6. RANDOM FOREST CLASSIFICATION OF FORTHCOMING GAIA MISSION SPECTRA 81 Figure 6.2: Distribution of stellar parameters of single MS stars (top left), single WDs (top right), MS star components in WDMS (bottom left) and WD components in WDMS (bottom right). After generating the spectra for each star we computed a function which downgraded the resolving power to the expected Gaia resolution according to Figure 6.1. Then we adopted a SNR for each of the stars as follows. First, we assume that the SNR is proportional to the f lux, SNR ∝f lux. Then, by using the relation between magnitude (in our case the Gaia magnitude G) and flux, G=−2.5·log(f lux) +C,(6.1) where Cis a constant of calibration, we can easily derive the relation between SNR and magnitude: SNR2=SNR1·10 G1−G2 2.5.(6.2) We know from Table 6.1 the values of the SNR for G=13. Thus, by adopting G1=13 and the corresponding SNR1depending on the type of star and the range of wavelengths (BP or RP), we can estimate the SNR2for each one of the objects of magnitudes G2. For the binary stars we only have approximations of SNR for their MS and WD components individually, so we take the average of both of them in the blue and in the red. Once the SNR were obtained, the corresponding noise levels were added to the spectra following a white noise Gaussian distribution. It is also worth saying that in the case of binary systems the fluxes of both components are
82 Spectral automated classification in large databases just added, leading to the following expression for the final resulting magnitude, Gf, of the binary system: Gf=−2.5·log10−0.4·G1+10−0.4·G2,(6.3) where G1and G2are the magnitudes of the individual stars. Figure 6.3: SNR distribution of the simulated Gaia spectra. The left panel of Figure 6.3 shows that the expected SNRs are distributed over a wide range of values, but most of the spectra have a SNR below 300. In the right panel of the figure we zoom in to the 0-300 range, where we see that the BP values are peaking at around 20, while the RP ones have a constant distribution. 6.2.2. The training set With respect to the training set, we maintained the same dataset of simulated spectra explained in Chapter 2 (3.1.), the only difference being that we adopted the same resolving power and SNR estimations as we did for the testing sample in the previous section. The values of SNR we chose were: 1, 3, 5, 7, 10, 15, 20, 30, 40, 60, 80, 100, 500 and 1000, covering the whole range of the synthetic spectra. Finally, the training set was also normalised before running the Random Forest, which was applied 100 times in order to average the results, as we have done in the other classifications. 6.3. Classification results After applying the Random Forest to the synthetic Gaia sample, we can obtain the performance metrics because we know the true labels. It is important to remember that in an observed unknown set we would not be able to do it, as we would only have the predicted label. Consequently, our analysis can be understood as a preliminary test for the forthcoming Gaia spectra in order to optimize the algorithm. Therefore, we first make a classification with the default settings and then we propose some improvements to the final Random Forest model.
CHAPTER 6. RANDOM FOREST CLASSIFICATION OF FORTHCOMING GAIA MISSION SPECTRA 83 In Figure 6.4 we show the confusion matrix of the classification. The MS population is the best classified, with a very good recall of 94%. This is the class with more samples out of the three of them, so the high percentage also indicates a high number of objects. Figure 6.4: Confusion matrix of the synthetic Gaia spectra set for the initial Random Forest model. On the other side, the WDs are much worse classified, only identifying a 73% of the samples. The majority of mislabelled objects are assigned to the WDMS population, although we also find a tiny percentage in the MS population. The binary population has the worst performance, with only a 54% of recall. This means that the Random Forest randomly classifies binary objects as MS or WDMS. Figure 6.5: Two examples of misclassified WD (left) and WDMS (right) Gaia spectra. A closer look to the spectra that has been misclassified may reveal more information about the issues of the performance. Two examples are shown in Figure 6.5. In the left panel we show a WD spectrum with a SNR on BP of 4 and on RP of 4.2. As clearly seen, the poor resolution and the high noise of the WD spectra is the main problem, given that most of the objects incorrectly classified have a SNR in the blue or in the red below 5. With respect to the right panel, we display the spectrum of a WDMS that was mistaken by a MS star. It has
84 Spectral automated classification in large databases SNR in the blue of 4.2 and in the red of 9. Although the noise is low enough to distinguish the MS component, the low resolving power deeply affects the spectrum. MS WD WDMS Accuracy 0.929 Cohen’s kappa 0.445 G−mean 0.719 Recall 0.944 0.732 0.537 Precision 0.986 1 0.197 F1-score 0.965 0.845 0.288 Table 6.2: Classification metrics of the Gaia spectra set classification for the initial Random Forest model. In Table 6.2 we show the metrics of the classification. We see how this time, unlike the SDSS classification, the accuracy, Cohen’s kappa and G-mean do not have the same value. This is because the dataset is not balanced, so we must be careful with the interpretation of these values. The accuracy, with a 93%, shows the amount of correctly classified elements. It seems to be a very high value, but it is mostly referring to the MS population, which has a lot of objects and therefore a higher weight when calculating the metric. Moving to the Kappa coefficient, the value is much lower. It evidences that the agreement between the true classes and the predicted classes is not good enough, under 0.8. With respect to the G-mean, however, we obtain a more realistic approach to the classification. It shows a 71.9%, i.e. the geometric (weighted) average of the three populations is around that value. Figure 6.6: ROC curves of the Gaia spectra set classification for the initial Random Forest model. With respect to the precision, we obtain very good values for the single populations, meaning that most of the samples identified as MS or WD truly belong to that class, but the WDMS has a worrying value of 20%. This suggests that most of the labelled WDMS are
CHAPTER 6. RANDOM FOREST CLASSIFICATION OF FORTHCOMING GAIA MISSION SPECTRA 85 not really WDMS, but belong to the single populations. This poor result is due to the percentage of MS stars labelled as WDMS, and the solution for this problem must be studied. Lastly, the F1-score averages the results of recall and precision, giving values that are closer to the true nature of the classification. Attending to the ROC curves (see Figure 6.6), the poor performance of the algorithm becomes evident. The curve with greater area belongs to the WD classification, since for low values of FPR it is able to detect 90% of the samples. The MS stars can be highly detected, with the cost of admitting a high percentage of False Positives – around a 40% of WDMS stars. The curve of the WDMS population is non-optimal, for low values of FPR it only detects the 50% of the binaries, reaching a maximum of 70% with the trade-off of mislabelling a 15% of the single stars. 6.4. Classification improvements To enhance the Random Forest classification we will apply three different methods and analyze their outcome as compared to the previous initial classification. 6.4.1. Probability estimates threshold Here we apply some threshold cuts to the probabilities of prediction of the Random Forest. With that, we are leaving out of the classification the spectra that the Random Forest is not sure about, and only take into account the objects above that threshold. Figure 6.7: Confusion matrix of the Gaia spectra set classification when introducing threshold cuts in the Random Forest model. Our main goal is to improve the binary population classification, mainly the precision score but also the recall. In order to do this, our first approach is to set the WDMS threshold very high. With that, we aim to lower the number of single objects misclassified, as we think
92 Spectral automated classification in large databases data, could only be correctly classified 63% of the times, but on the positive side, it seems to be guaranteed that more than 95% of the labels imposed for that population are actually correct. All in all, we have been able to classify two different sets of stellar spectra with different characteristics, maximizing the number of well classified objects while minimizing the amount of false positives. This fact validates the Random Forest algorithm that we have configured as a powerful tool which can be used not only in the field of astronomy but also in diverse fields and applications, such as aerospace engineering or space technologies. In what follows we point out some future work lines that we have not been able to explore in the present project. To begin with, it would be of interest to study the effects of performing a feature selection. In all the classifications made along this project we have used the whole set of variables available for each sample, but some improvements are expected to be achieved if some of the features are removed. For instance, using the importance calculated by the Random Forest we could choose those variables above a certain threshold. This would help to increase the efficiency and reduce the computational time of the algorithm, since the amount of information to process would be less but more meaningful. Another issue that should be analyzed is the noise distribution of the database. We established a white Gaussian noise, affecting all frequencies with a null mean and certain standard deviation. However, we realised that the Random Forest applied to the Sloan Digital Sky Survey data had a deficient performance mainly due to this fact. We changed the noise distribution to fit the observed spectra, resulting in a much better prediction, but it was an initial analysis that can be dealt in greater depth in future works. Finally, there exists the possibility of modifying the training set. We have used a constant training set formed by simulated spectra that is adapted to the nature of the testing database. It would be intriguing to know how the algorithm responds to adding observed spectra to the training set. In this way, the Random Forest would have more information and could become more accurate when classifying other data. Along the same lines, we have only dealt with three stellar populations. Adding objects that do not belong to any of the known classes should be explored widening the possibilities of the Random Forest algorithm.
BIBLIOGRAPHY [1] M. Hern´ andez-Pajares and J. Floris. Classification of the Hipparcos input catalogue using the Kohonen network. Monthly Notices of the Royal Astronomical Society, 268(2):444–450, 05 1994. 5,29 [2] Santiago Torres, Enrique Garc´ ıa-Berro, and Jordi Isern. Neural Network Identification of Halo White Dwarfs. ApJ, 508(1):L71–L74, November 1998. 5,29 [3] Coryn A. L. Bailer-Jones, Mike Irwin, and Ted von Hippel. Automated classification of stellar spectra - II. Two-dimensional classification with neural networks and principal components analysis. MNRAS, 298(2):361–377, August 1998. 5,29 [4] S. Torres, C. Cantero, A. Rebassa-Mansergas, G. Skorobogatov, F. M. Jim´ enez- Esteban, and E. Solano. Random Forest identification of the thin disc, thick disc, and halo Gaia-DR2 white dwarf population. MNRAS, 485(4):5573–5589, June 2019. 5,29 [5] European Space Agency. Gaia data release scenario. https://www.cosmos.esa. int/web/gaia/release, 2021. Online; accessed 10-January-2021. 7 [6] Warren S McCulloch and Walter Pitts. A logical calculus of the ideas immanent in nervous activity. The bulletin of mathematical biophysics, 5(4):115–133, 1943. 7 [7] M. Mohammed, M.B. Khan, and E.B.M. Bashier. Machine Learning: Algorithms and Applications. CRC Press, 2016. 7,1 [8] J. Gama, R. Camacho, P. Brazdil, A. Jorge, and L. Torgo. Machine Learning: ECML 2005: 16th European Conference on Machine Learning, Porto, Portugal, October 3-7, 2005, Proceedings. Lecture Notes in Artificial Intelligence. Springer, 2005. 7 [9] Roohollah Amiri, Hani Mehrpouyan, Lex Fridman, Ranjan K Mallik, Arumugam Nallanathan, and David Matolak. A machine learning approach for power allocation in hetnets considering qos. In 2018 IEEE International Conference on Communications (ICC), pages 1–7. IEEE, 2018. 9 [10] Tin Kam Ho. Random decision forests. In Proceedings of 3rd international conference on document analysis and recognition, volume 1, pages 278–282. IEEE, 1995. 10 [11] Tin Kam Ho. The random subspace method for constructing decision forests. IEEE transactions on pattern analysis and machine intelligence, 20(8):832–844, 1998. 10 [12] Khaled Fawagreh, Mohamed Medhat Gaber, and Eyad Elyan. Random forests: from early developments to recent advancements. Systems Science & Control Engineering, 2(1):602–609, 2014. 10,12 [13] Leo Breiman. Random forests. Machine learning, 45(1):5–32, 2001. 10,31 [14] F. Pedregosa, G. Varoquaux, A. Gramfort, V. Michel, B. Thirion, O. Grisel, M. Blondel, P. Prettenhofer, R. Weiss, V. Dubourg, J. Vanderplas, A. Passos, D. Cournapeau, M. Brucher, M. Perrot, and E. Duchesnay. Scikit-learn: Machine learning in Python. Journal of Machine Learning Research, 12:2825–2830, 2011. 10,13,14,17,34,35 93
94 Spectral automated classification in large databases [15] Laura Elena Raileanu and Kilian Stoffel. Theoretical comparison between the gini index and information gain criteria. Annals of Mathematics and Artificial Intelligence, 41(1):77–93, 2004. 10 [16] Ke Li, Nan Yu, Pengfei Li, Shimin Song, wu Lei, Yang Li, and Meng Liu. Multi-label spacecraft electrical signal classification method based on dbn and random forest. PLoS ONE, 12, 05 2017. 12,21,8 [17] L. Breiman and A. Cutler. Random forests. https://www.stat.berkeley.edu/ ˜breiman/RandomForests/cc_home.htm, 2004. Online; accessed 11-November- 2020. 12 [18] S Torres, C Cantero, Alberto Rebassa-Mansergas, G Skorobogatov, FM Jim´ enez- Esteban, and E Solano. Random forest identification of the thin disc, thick disc, and halo gaia-dr2 white dwarf population. Monthly Notices of the Royal Astronomical Society, 485(4):5573–5589, 2019. 16,80 [19] Weizhong Yan. Application of random forest to aircraft engine fault diagnosis. In The Proceedings of the Multiconference on” Computational Engineering in Systems Applications”, volume 1, pages 468–475. IEEE, 2006. 20,5 [20] Sanghyuk Lee, Wookje Park, and Sikhang Jung. Fault detection of aircraft system with random forest algorithm and similarity measure. The Scientific World Journal, 2014, 2014. 20,5 [21] Xinghui Dong, Chris J Taylor, and Tim F Cootes. Automatic inspection of aerospace welds using x-ray images. In 2018 24th International Conference on Pattern Recognition (ICPR), pages 2002–2007. IEEE, 2018. 20,6 [22] NJ Shipway, TJ Barden, P Huthwaite, and MJS Lowe. Automated defect detection for fluorescent penetrant inspection using random forest. NDT & E International, 101:113–123, 2019. 20,6 [23] John K Williams. Using random forests to diagnose aviation turbulence. Machine learning, 95(1):51–70, 2014. 20,6 [24] Anish M Kalliguddi and Aera K Leboulluec. Predictive modeling of aircraft flight delay. Universal Journal of Management, 5(10):485–491, 2017. 21,7 [25] Jinxiao Wen, Yan Zhang, Guanshu Yang, Zunwen He, and Wancheng Zhang. Path loss prediction based on machine learning methods for aircraft cabin environments. IEEE Access, 7:159251–159261, 2019. 21,7 [26] Greydon Foil, David R Thompson, William Abbey, and David S Wettergreen. Probabilistic surface classification for rover instrument targeting. In 2013 IEEE/RSJ International Conference on Intelligent Robots and Systems, pages 775–782. IEEE, 2013. 21,7 [27] Masahiro Ono, Thoams J Fuchs, Amanda Steffy, Mark Maimone, and Jeng Yen. Riskaware planetary rover operation: Autonomous terrain classification and path planning. In 2015 IEEE aerospace conference, pages 1–10. IEEE, 2015. 21,8
BIBLIOGRAPHY 95 [28] J. Tennyson. Astronomical Spectroscopy: An Introduction to the Atomic and Molecular Physics of Astronomical Spectra. Astronomical Spectroscopy: An Introduction to the Atomic and Molecular Physics of Astronomical Spectra. Imperial College Press, 2005. 23 [29] I. Appenzeller. Introduction to Astronomical Spectroscopy. Cambridge Observing Handbooks for Research Astronomers. Cambridge University Press, 2013. 23 [30] Richard Walker. Analysis and interpretation of astronomical spectra analysis and interpretation of astronomical spectra: Theoretical background and practical applications for amateur astronomers, 2012. 24,32 [31] Leandro G. Althaus, Alejandro H. C´ orsico, Jordi Isern, and Enrique Garc´ ıa-Berro. Evolutionary and pulsational properties of white dwarf stars. The Astronomy and Astrophysics Review, 18(4):471–566, Aug 2010. 25 [32] Enrique Garc´ ıa–Berro and Terry D. Oswalt. The white dwarf luminosity function. New Astronomy Reviews, 72-74:1–22, 2016. 25 [33] European Southern Observatory. Spectrum of white dwarf stars in ngc 6397. https: //www.eso.org/public/images/eso9953b/, 1999. Online; accessed 4-March- 2021. 25 [34] NASA Hubble Space Telescope. Signature of a white dwarf. https://hubblesite. org/image/3052/news/115-spectra, 2012. Online; accessed 3-March-2021. 25 [35] Bruce MacEvoy. Spectral classification of stars. https://www.handprint.com/ ASTRO/specclass.html, 2013. Online; accessed 4-March-2021. 26 [36] NASA. Stars. https://science.nasa.gov/astrophysics/focus-areas/ how-do-stars-form-and-evolve, 2021. Online; accessed 4-March-2021. 26 [37] Australia Telescope National Facility. Main sequence stars. https: //www.atnf.csiro.au/outreach/education/senior/astrophysics/ stellarevolution_mainsequence.html, 2021. Online; accessed 3-March- 2021. 26 [38] Hannu Karttunen, Pekka Kr¨ oger, Heikki Oja, Markku Poutanen, and Karl Johan Donner. Binary Stars and Stellar Masses, pages 247–255. Springer Berlin Heidelberg, Berlin, Heidelberg, 1994. 27 [39] Australia Telescope National Facility. Types of binary stars. https: //www.atnf.csiro.au/outreach//education/senior/astrophysics/ binary_types.html, 2021. Online; accessed 3-March-2021. 27 [40] A Rebassa-Mansergas, B T G¨ ansicke, and D Koester. The physical properties of white dwarf-main sequence binaries from SDSS. Journal of Physics: Conference Series, 172:012025, jun 2009. 27 [41] Detlev Koester. White Dwarf Stars, pages 559–612. Springer Netherlands, Dordrecht, 2013. 27
96 Spectral automated classification in large databases [42] Donald G. et al. York and SDSS Collaboration. The Sloan Digital Sky Survey: Technical Summary. AJ, 120(3):1579–1587, September 2000. 28 [43] A Rebassa-Mansergas, A Nebot G´ omez-Mor´ an, MR Schreiber, BT G¨ ansicke, A Schwope, J Gallardo, and D Koester. Post-common envelope binaries from sdss– xiv. the dr7 white dwarf–main-sequence binary catalogue. Monthly Notices of the Royal Astronomical Society, 419(1):806–816, 2012. 29 [44] S. O. Kepler, Ingrid Pelisoli, Detlev Koester, Nicole Reindl, Stephan Geier, Alejandra D. Romero, Gustavo Ourique, Cristiane de Paula Oliveira, and Larissa A. Amaral. White dwarf and subdwarf stars in the Sloan Digital Sky Survey Data Release 14. MNRAS, 486(2):2169–2183, June 2019. 29 [45] A. Rebassa-Mansergas, J. J. Ren, S. G. Parsons, B. T. G¨ ansicke, M. R. Schreiber, E. Garc´ ıa-Berro, X. W. Liu, and D. Koester. The SDSS spectroscopic catalogue of white dwarf-main-sequence binaries: new identifications from DR 9-12. MNRAS, 458(4):3808–3819, June 2016. 29 [46] A. Rebassa-Mansergas, B. T. G¨ ansicke, M. R. Schreiber, D. Koester, and P. Rodr´ ıguez-Gil. Post-common envelope binaries from SDSS - VII. A catalogue of white dwarf-main sequence binaries. MNRAS, 402(1):620–640, February 2010. 29, 71 [47] Simon Haykin and Zhe Chen. The cocktail party problem. Neural computation, 17(9):1875–1902, 2005. 29 [48] Feng Youqian, Zhang Shanwen, and Li Zhengchao. A method of radar signal separation. In 2007 International Conference on Computational Intelligence and Security Workshops (CISW 2007), pages 846–849, 2007. 29 [49] T. O. Husser, S. Wende-von Berg, S. Dreizler, D. Homeier, A. Reiners, T. Barman, and P. H. Hauschildt. A new extensive library of PHOENIX stellar atmospheres and synthetic spectra. A&A, 553:A6, May 2013. 31 [50] D. Koester. White dwarf spectra and atmosphere models. Mem. Societa Astronomica Italiana, 81:921–931, January 2010. 31 [51] I. Mills, International Union of Pure, Applied Chemistry, International Union of Pure, Terminology Applied Chemistry Commission on Physicochemical Symbols, and Units. Quantities, Units, and Symbols in Physical Chemistry. IUPAC Chemical Data Series. Blackwell Scientific Publications, 1993. 32 [52] Victor Gold, editor. The IUPAC Compendium of Chemical Terminology. International Union of Pure and Applied Chemistry (IUPAC), 2019. 32 [53] Donald G. York, J. Adelman, John E. Anderson, Jr., Scott F. Anderson, James Annis, Neta A. Bahcall, J. A. Bakken, Robert Barkhouser, Steven Bastian, Eileen Berman, and et al. The sloan digital sky survey: Technical summary. The Astronomical Journal, 120(3):1579–1587, Sep 2000. 32 [54] Olivier Hainaut. Signal, noise and detection. https://www.eso.org/˜ohainaut/ ccd/sn.html, 2005. Online; accessed 21-April-2021. 33
BIBLIOGRAPHY 97 [55] National Institute of Standards and Technology. Signal to noise ratio. https://www. itl.nist.gov/div898/software/dataplot/refman2/auxillar/snr.htm, 2017. Online; accessed 5-May-2021. 33 [56] Xiang-Ru Li, Yang-Tao Lin, and Kai-Bin Qiu. Stellar spectral classification and feature evaluation based on a random forest. Research in Astronomy and Astrophysics, 19(8):111, aug 2019. 35 [57] James Bergstra and Yoshua Bengio. Random search for hyper-parameter optimization. Journal of machine learning research, 13(2), 2012. 37 [58] Philipp Probst, Marvin N. Wright, and Anne-Laure Boulesteix. Hyperparameters and tuning strategies for random forest. Wiley Interdisciplinary Reviews: Data Mining and Knowledge Discovery, 9(3), Jan 2019. 37 [59] James E. et al. Gunn. The 2.5 m Telescope of the Sloan Digital Sky Survey. AJ, 131(4):2332–2359, April 2006. 65 [60] J. C. et al. Wilson. The Apache Point Observatory Galactic Evolution Experiment (APOGEE) Spectrographs. PASP, 131(999):055001, May 2019. 65 [61] A. Rebassa-Mansergas, B. T. G¨ ansicke, P. Rodr´ ıguez-Gil, M. R. Schreiber, and D. Koester. Post-common-envelope binaries from SDSS - I. 101 white dwarf mainsequence binaries with multiple Sloan Digital Sky Survey spectroscopy. MNRAS, 382(4):1377–1393, December 2007. 71 [62] R. Cojocaru, A. Rebassa-Mansergas, S. Torres, and E. Garc´ ıa-Berro. The population of white dwarf–main sequence binaries in the sdss dr 12. Monthly Notices of the Royal Astronomical Society, 470(2):1442–1452, May 2017. 71 [63] Gaia Collaboration et al. Gaia data release 1. summary of the astrometric, photometric, and survey properties. Astronomy and Astrophysics, 595:A2, 2016. 79 [64] Collaboration Gaia, AGA Brown, A Vallenari, T Prusti, JHJ De Bruijne, C Babusiaux, ´ AL Juh´ asz, G Marschalk´ o, G Marton, L Moln´ ar, et al. Gaia data release 2 summary of the contents and survey properties. Astronomy & Astrophysics, 616(1), 2018. 79 [65] D. W. Evans, M. Riello, F. De Angeli, G. Busso, F. van Leeuwen, C. Jordi, C. Fabricius, A. G. A. Brown, J. M. Carrasco, H. Voss, and et al. Gaiadata release 1. Astronomy & Astrophysics, 600:A51, Mar 2017. 79 [66] J. M. Carrasco, M. Weiler, C. Jordi, C. Fabricius, F. De Angeli, D. W. Evans, F. van Leeuwen, M. Riello, and P. Montegriffo. Internal calibration of gaia bp/rp lowresolution spectra, 2021. 79,80 [67] Aina Ferrer i Burjachs. Population synthesis study of the binary Gaia white dwarf population, Bachelor’s Thesis, (UPC), 2021. 80 [68] G. Bonaccorso. Machine Learning Algorithms. Packt Publishing, 2017. 1 [69] Christopher M Bishop. Pattern recognition and machine learning. springer, 2006. 1
[70] S Pyrzas, BT G¨ ansicke, A Rebassa-Mansergas, M Schreiber, P Rodr´ ıguez-Gil, TR Marsh, A Nebot Gomez-Moran, and D Koester. Hunting for eclipsing post common envelope binaries from sdss. In AIP Conference Proceedings, volume 1273, pages 372–377. American Institute of Physics, 2010. 39
AP ` ENDIXS T´ ITOL DEL TFG: Spectral automated classification in large databases TITULACI ´ O: Doble titulaci´ o de grau en Enginyeria de Sistemes Aeroespacials i Enginyeria de Sistemes de Telecomunicaci´ o AUTOR: Cristian David Echeverry Valencia DIRECTORS: Alberto Rebassa Mansergas Santiago Torres Gil DATA: July 5, 2021
APPENDIX A. CLASSIFICATION ALGORITHMS A.1. Classification algorithms As the purpose of this project is centred on a classification problem, some of the most known classification algorithms will be explained here [7,68,69]. Generally, these algorithms can classify between only two classes – binary algorithms – or between more than two classes – multi-class algorithms. A.1.1. Na¨ıve-Bayes It is a simple probabilistic classifier based on the Bayes theorem, whose mathematical expression is the following one: P(A|B) = P(A)·P(B|A) P(B)(A.1) Where Aand Bare the events, P(A)and P(B)the independent probabilities of each event, and P(A|B)and P(B|A)the probability of the first event happening if the other event is also happening. The algorithm works by calculating the probability of certain element belonging to a certain class, that is P(classj|elementi), and the element will be classified to the class with the highest probability among all the classes. Its implementation is very straightforward, as the calculations are fast and simple, but it relies too much on the independence of the elements, so if there is some kind of relation between the data its performance will not be optimal. A.1.2. Logistic Regression In this case, the probability of an element belonging to a certain class is modelled following a logistic function that works as a threshold, so it is only used in binary classifications. That function has the following expression: y=1 1+e−x(see Figure A.1), where xis the term to evaluate. In classification problems, that term is the previously explain Bayesian theorem, in particular the sum of logarithms of the Bayesian probabilities of belonging to a class 0 or a class 1. A similar algorithm is the linear regression, in which the function is a line y=m·x+b, or a polynomial regression, with as many coefficients as needed. However, a persistent problem in all of them is that many times the data are not linearly separable and although a linear estimator could be applied (for simplicity or speed) assuming some error, it may be necessary to opt for a non-linear method. These linear algorithms are easy to implement and could be extendable to multiple classes classification, but they assume again the nondependency between the data. 1
data that was not classified. The input data for the Random Forest were images in which each pixel belonged to a certain class, so the algorithm could identify the different patterns that describe different physical surfaces. The used dataset belongs to a volcanic field, and then the Rover imaging was simulated, giving 23 images for the training. The resulting performance was able to correctly assign the different classes to the images most of the times. Different settings were used, being the worst classification around 80% of accuracy, and the best almost 100%. The combination with the semi-supervised algorithm led to very good automatic instrument targeting, validating the performance of both the Random Forest and the novelty detection. B.3.2. Terrain classification for Rover - Ono et al A similar experiment was conducted by Ono et al [27] based on a risk-aware planetary Rover operation, and aiming to elaborate an autonomous terrain classification and path planner for the Mars mission. The idea comes up from the need of examining the different hazards that could be in a terrain and evaluate the possible risks, so the Rover can automatically decide which path to take. The data was obtained from human experts that already labelled 5 types of terrains common in the surface of the red planet: sand, bedrock, loose rock, embedded pointy rock and embedded round rock. All of them have several drawbacks, taking into account past missions where the Rover missions could not continue because they got stuck in these types of ground, but the first three ones were considered as drivable. The training data is composed by images with labelled pixels, according if the information showed on them belong to one type or to another, making a total of 66 images. The Random Forest was evaluated using 10-fold cross-validation, and the outcome was a 76.2% of accuracy for the drivable terrains and a 89.2% for the pointy rocks. The results of the classification were then used in order to plan the path to follow, but the Random Forest was considered as a great and powerful tool, able to classify even in a multi-label case. B.3.3. Spacecraft fault diagnosis - Li et al In the last place, we comment an application very similar to the aviation fault diagnosis, but for a spacecraft. It was explored by Li et al [16]. They tried to implement a multi-label spacecraft electrical signal classification method based on Deep Belief Networks (DBN) (a type or Artificial Neural Network) and Random Forest. The purpose of the project relies on the several difficulties that exist in diagnosing and maintaining a spacecraft once it has stepped into the orbit flight phase. They centred their research on the complex electrical signals that the spacecraft produces, which are a huge amount of data. Firstly the data would be acquired using a method called wavelet denoising, in order to separate the signal from the noise. After that, the DBN would be useful in order to reduce the dimensionality of the data, while the Random Forest would be in charge of the detection of the faults. In total, there were 22,800 samples available with 1,000 features each, covering 19 different types of signals and labels from 13 modes in the spacecraft flying data. Some of the data, for instance, was the pitch altitude angle, roll angle, various posture quaternions or gyro angular velocity in the three axis. The dataset was divided in training and testing, 56% and 44% of the total, respectively. The performance of the Random Forest was very superior
to other classifiers that were evaluated on the paper, as KNN or SVM. Besides, different methods apart from DBN are used in order to dimensionalize the data, but the Random Forest had the greatest performance every time, reaching very good accuracy results for the different setups and very low training and testing times. Finally, a combination of Random Forest and other dimension reduction method is proposed to completely assess the algorithm results.
APPENDIX C. WEB APPLICATION This Appendix contains information related to the web application designed. After having analyzed and gone deeper on the classification of simulated spectra, we decided to compare the algorithm with a human classification. For this purpose, we made a web application where the users - both experts and novices in the matter - could easily categorize one by one a subsample of simulated spectra and obtain the metrics of their classification. We go more into detail in the web structure, briefly explaining its front-end and back-end, and finally display the results achieved. C.1. Web structure C.1.1. Web back-end The application was coded in Python, using the PyCharm IDE. The libraries used were the following ones: [ ]: from flask import Flask, render_template, request, session, ,→redirect, url_for from sklearn.metrics import confusion_matrix, accuracy_score, ,→recall_score, precision_score, cohen_kappa_score import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import pandas as pd import sqlite3 import itertools import numpy as np The Flask framework provides the necessary tools to start a server. Besides, in order to manage the database with the information of the user we made use of SQLite, a relational database management system (RDBMS) which is embedded into the end program. Its simplicity and efficiency were ideal for the present project, achieving the objectives for the web application development. The database was organized in the following way: •Predictions table: contains the name of the user, the number of the spectrum and the users prediction. •Parameters table: contains the name of the user and the computed metrics of the users classification. When the user introduces its name and classifies a spectrum, the prediction is stored in the first table. When all of the spectra have been classified, the metrics of the user are collected in the second table, establishing a One-to-Many relationship between both databases. The rest of the code for the web application server is displayed next. 11
[ ]: # Function to change the class numbers to string labels def replacer(y_int): y_str =[] for iin range(len(y_int)): if y_int[i] == 0: y_str.append('MS') if y_int[i] == 1: y_str.append('WD') if y_int[i] == 2: y_str.append('WDMS') return y_str # Function to plot the confusion matrix def plot_confusion_matrix(cm, classes, normalize=False, ,→title='Confusion matrix', cmap=plt.cm.Blues): plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks =np.arange(len(classes)) plt.xticks(tick_marks, classes) plt.yticks(tick_marks, classes) if normalize: cm =cm.astype('float')/cm.sum(axis=1)[:, np.newaxis] thresh =cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm. ,→shape[1])): plt.text(j, i, cm[i, j], horizontalalignment="center", color="white" if cm[i, j] >thresh else "black") #plt.tight_layout() plt.clim(0,11) plt.ylabel('True label') plt.xlabel('Predicted label') # Function to convert the images path to html ,→understandable items, in order to display the images def path_to_image_html(path): return '<img src="static/figs/'+path +'" width="200" >' # Starti the Flask application, hosted in the directory ,→'static'
app =Flask(__name__, static_url_path='/static') app.secret_key ='wdms' # Load database with the spectra information: label, ,→class and image BBDDstars =pd.read_hdf('/home/cdev/mysite/BBDDstars.hdf') # Compute the metrics of the RF classification at the ,→begginng of the app acc_rf =round(accuracy_score(BBDDstars['class']. ,→values,BBDDstars['rf'].values), 4) ck_rf =round(cohen_kappa_score(BBDDstars['class']. ,→values,BBDDstars['rf'].values), 4) recall_rf =recall_score(BBDDstars['class'].values,BBDDstars['rf']. ,→values,average=None) recall_rf[0]=round(recall_rf[0], 4) recall_rf[1]=round(recall_rf[1], 4) recall_rf[2]=round(recall_rf[2], 4) prec_rf =precision_score(BBDDstars['class']. ,→values,BBDDstars['rf'].values, average=None) prec_rf[0]=round(prec_rf[0], 4) prec_rf[1]=round(prec_rf[1], 4) prec_rf[2]=round(prec_rf[2], 4) # Save the RF classification confusion matrix cm_rf =confusion_matrix(BBDDstars['class'], BBDDstars['rf']) title_rf ='RF classification' plot_confusion_matrix(cm_rf, ['MS','WD','WDMS'], title=title_rf, ,→cmap=plt.cm.Blues) plt.savefig('/home/cdev/mysite/static/images/cmatrix_rf.jpg', ,→dpi=250, bbox_inches='tight')# CAMBIAR! image_cm_rf ='cmatrix_rf.jpg' plt.clf() # Retrive the spectra images yimages =[] for iin range(len(BBDDstars)): yimages.append(str(BBDDstars.num.values[i]) +'.jpg') # Convert the numbered classes to strings (MS,WD,WDMS) ytest_str =replacer(BBDDstars['class'].values) yrf_str =replacer(BBDDstars['rf'].values) # If main app is opened if __name__ == "__main__": # Open connection to the database
conn =sqlite3.connect('/home/cdev/mysite/database.db') print("Opened database successfully") cur =conn.cursor() # If database tables do not exist, create it try: cur.execute('CREATE TABLE predictions (user TEXT, spectrum ,→INT, pred INT)') cur.execute('CREATE TABLE parameters (user TEXT, acc FLOAT, ,→ck FLOAT, recM FLOAT, recWD FLOAT, recWDMS FLOAT, ' 'prM FLOAT, prWD FLOAT, prWDMS FLOAT, cmatrix ,→CHAR)') print("Tables created successfully") # If databaes tables exist, notify except: conn.commit() print("Tables already exists") # Close connection to database conn.close() # Start app app.run() # If web app url is accesed @app.route("/", methods=["GET","POST"]) def main(): # When user introduces name, check if user has already ,→accessed the app before if request.method == 'POST': # Retrieve username username =request.form['username'] # Open connection to the database conn =sqlite3.connect('/home/cdev/mysite/database.db') cur =conn.cursor() # Enquiry the predictions already made by the user cur.execute("SELECT * FROM 'predictions'WHERE user == (? ,→)", (username,)) rows =cur.fetchall() conn.close() # If user has not made any predictions yet if len(rows) == 0: # Counter to 0 session['counter']= 0
# Username is stored in session variable session['uname']=username # Redirect to index url return redirect(url_for('index')) # If user has made predictions else: # If all the spectra has been classified if len(rows) == len(BBDDstars): session['uname']=username # Redirect to the results url return redirect(url_for('results')) else: # Retrieve the last spectrum classified session['counter']=len(rows) session['uname']=username # Redirect to index url return redirect(url_for('index')) # Render the main url template return render_template('main.html') # If index url is accesed @app.route("/index", methods=["GET","POST"]) def index(): # Open connection to database conn =sqlite3.connect('/home/cdev/mysite/database.db') # When user introduces class of spectrum if request.method == 'POST': # Retrieve prediction pred =request.form['class'] # Retrieve spectrum label spectrum =request.form['num'] # Retrieve username name =session['uname'] # Query to intoduce in the thable 'prediction' the ,→users input cur =conn.cursor() cur.execute("INSERT INTO predictions (user,spectrum,pred) ,→VALUES (?,?,?)", (name,spectrum,pred)) conn.commit() # If user has not classified all spectra if session['counter']<len(BBDDstars) - 1: # Add 1 to the users spectra count
session['counter']+= 1 else: # Redirect to results urls return redirect(url_for('results')) conn.close() # Load next spectrum and its image sample =BBDDstars.iloc[session['counter']] sample_image =str(sample.num) +'.jpg' # Return index url with next spectrum, its image, ,→number and username return render_template('index.html', image_path=sample_image, ,→num_spectrum=sample.num, counter=session['counter'], ,→uname=session['uname']) # If results url is accessed @app.route("/results", methods=["GET"]) def results(): # Open connection to database conn =sqlite3.connect('/home/cdev/mysite/database.db') cur =conn.cursor() # Enquiry to retrieve all the predictions made by the ,→user cur.execute("SELECT * FROM 'predictions'WHERE user == (?)", ,→(session['uname'],)) rows =cur.fetchall() # Close connection to database conn.close() ypred =[] # Loop to retrieve the predictions and store them in a ,→new list for row in rows: ypred.append(row[2]) # Open connection to database conn =sqlite3.connect('/home/cdev/mysite/database.db') cur =conn.cursor() # Enquiry to retrieve the metrics of the user cur.execute("SELECT * FROM 'parameters'WHERE user == (?)", ,→(session['uname'],)) rows =cur.fetchall() # Close connection to database conn.close()
# If metrics of the user have not been compute yet if len(rows) == 0: # Compute user confusion matrix and save it cm_user =confusion_matrix(BBDDstars['class'], ypred) np.save('/home/cdev/mysite/static/cmatrix/cm_'+ ,→session['uname']+'.npy', cm_user) title_user =session['uname']+'classification' ,→plot_confusion_matrix(cm_user,['M','WD','WDMS'],title=title_user,cmap=plt. ,→cm.Blues) plt.savefig('/home/cdev/mysite/static/images/cmatrix_'+ ,→session['uname']+'.jpg', dpi=250, bbox_inches='tight') ,→#CAMBIAR! image_cm_user ='cmatrix_'+session['uname']+'.jpg' plt.clf() # Compute classification metrics for user acc_user =round(accuracy_score(BBDDstars['class'],ypred), ,→4) ck_user =round(cohen_kappa_score(BBDDstars['class'], ,→ypred), 4) recall_user = ,→recall_score(BBDDstars['class'],ypred,average=None) recall_user[0]=round(recall_user[0],4) recall_user[1]=round(recall_user[1],4) recall_user[2]=round(recall_user[2],4) prec_user = ,→precision_score(BBDDstars['class'],ypred,average=None) prec_user[0]=round(prec_user[0], 4) prec_user[1]=round(prec_user[1], 4) prec_user[2]=round(prec_user[2], 4) # Open connection to database conn =sqlite3.connect('/home/cdev/mysite/database.db') cur =conn.cursor() # Insert new row with user metrics in 'parameters' ,→table cur.execute("INSERT INTO parameters ,→(user,acc,ck,recM,recWD,recWDMS,prM,prWD,prWDMS,cmatrix) VALUES ,→(?,?,?,?,?,?,?,?,?,?)", (session['uname'], str(acc_user), str(ck_user), ,→str(recall_user[0]), str(recall_user[1]), str(recall_user[2]), str(prec_user[0]), ,→str(prec_user[1]), str(prec_user[2]), image_cm_user))
Spectrum Class Prediction Random Forest SNR 12 WD WD WD 5 13 M M M 5 14 WDMS WDMS WDMS 10 15 M M M 10 16 WDMS M M 1 17 M WD M 20
Spectrum Class Prediction Random Forest SNR 18 M WD M 20 19 WDMS WD WDMS 100 20 M M WDMS 10 21 WD WDMS WD 1 22 WD WD WDMS 100 23 WDMS WD WDMS 100
Spectrum Class Prediction Random Forest SNR 24 M M M 100 25 WDMS WD WD 10 26 WDMS WD WDMS 5 27 WDMS WD WDMS 50 28 WD WDMS WD 20 29 WD WDMS WD 10
Spectrum Class Prediction Random Forest SNR 30 WDMS M WDMS 10 31 WD WD WD 20 32 M M M 1 33 WD WD WD 100 34 WDMS M WDMS 50 35 WDMS M WDMS 10
Anónimo Random Forest M WD WDMS M WD WDMS Accuracy 0.4857 0.8857 Cohen's kappa 0.2373 0.828 Recall 0.6364 0.6364 0.2308 0.9091 0.9091 0.8462 Precision 0.5833 0.4375 0.4286 0.9091 0.9091 0.8462 Accuracy (from 0 to 1): fraction of correct predictions, which is the number of elements correctly classfied divided by the total number of elements. Cohen's kappa (from -1 to 1): expresses the level of agreement between two classifications, in this case, between the real classes and the predicted clases. A score below 0 means practically random labels, while a score above 0.8 is considered good agreement. Recall (from 0 to 1): ratio between the number of elements belonging to a certain class that were correctly classified and the total number of elements belonging to such class. Precision (from 0 to 1): ratio between the number of elements belonging to a certain class that were correctly classified and the total number of elements classified as such class.
C.2. Classification results After several users made the classification, we retrieved the database and obtained the results. With them, we were able to compute different histograms to see how the human classifiers performed, while comparing to the RF classification. The subsample of spectra was taken from the simulated objects. We made a group of stars that covered different temperatures and surfaces gravities of the MS and WD, and different combinations of WDMS. We tried to make a balanced dataset, with 11 objects of the single populations and 13 objects of the binary population, as it is the one more affected by misclassification. All of them had the resolving power of the spectra from the Sloan Digital Sky Survey, 1,800. Moreover, we decided to test different SNR, ranging from 1 to 100. We generated 35 spectra that the users had to classified. In total, 24 astronomers on different backgrounds accessed and completed the classification successfully. The following figures were computed with the different classifications, and we always compare with the Random Forest outcome of the same spectra. We begin with the confusion matrix, to obtain the general picture of both results. Figure C.1 depicts the classification of the Random Forest. We can see that those particular spectra were correctly classified most of the times, being the binary population the worst labelled - a 15% of the WDMS are not well classified. This is probably due to the different noises that we have added, so in average the recall of the binaries is worse. Attending to Figure C.2, we are able to observe the classification made by the users, in average. We find similar percentages for the single populations, but the binaries are very badly classified. A third of the WDMS samples is assigned to each one of the single populations, so we could state that their classification is completely random. After the first approach, we can see how each metric changes with the different users. This is shown in Figure C.3 in form of a histogram representing the number of users for different values of accuracy. The red dashed line depicts the accuracy of the Random Forest, so we are able to visualize if any of the users overcome its classification, or not. From all the metrics related to the global performance we compute only the accuracy, but as the data set is balanced we can assure that the Cohen’s kappa and the G-mean will have similar values. The accuracy of the users is generally low, with a mean around 70%. There are two users that were able to reach between a 80-82.5%, but none of them could overpass the Random Forest, with a 88.5% of accuracy. This is coherent with the confusion matrix, but it gives more information about each one of the users. We now take a look at the metrics for each population. Among the recall, the precision and the F1-score, we opt for displaying the last one, as it gives the average information of the other two, and we can complete the results then with the ROC curve. Figure C.4 shows the histogram of the F1-score. Here we encounter that the score for the MS population is in color red, for the WD stars is in blue, and for the binaries in green. We also see the values of the Random Forest, as dashed lines, and with the color of each population. As expected, the scores for the WDMS population are quite low, with the mean around 50% and a various range of values, from almost 30% to 70%. The MS and WD populations have been classified better than the binaries, reaching a 80% in average. Nevertheless, none of the users is able to classify the singles nor binaries better than the RF, with a F1 score
of 90.9% and 84.6%, respectively. We now move on to the ROC curve for both the Random Forest and the users. Firstly, the Random Rorest curves in Figure C.5 have a very great AUC score, and are close to the perfect classification. The WD is the best classified population, obtaining the maximum TPR for a very low FPR, that means that the algorithm is able to detect all the WD at the cost of confusing only a few WDMS. Regarding the MS and WDMS populations, we find that their curves and areas are very similar. At first this could be contradicting the previous results (the confusion matrix and F1 histogram), but the ROC curves are using the probability estimates instead of the actual predictions. That is, although at the end the MS stars are detected when averaging the 100 RF classifications, the algorithm has doubts about certain objects belonging to that class. For the WDMS we have the same issue, and reaching the maximum values of recall has a higher cost of mislabelling objects from other populations. Attending to the users ROC curve, Figure C.6, the MS and WD populations are able to achieve a 100% of recall, but misclassifying a great part of the WDMS, around a 20%. The binary population has very low scores, but setting a different threshold for the probability estimates could improve the users classification. Again, it seems like the WDMS are classified in a much better way than we saw in the confusion matrix, but this is due to the use of probability estimates. In general, the purpose of the experiment was to see if the Random Forest was truly a useful tool for astronomers in order to ease the task of classification, which can be sometimes hard and time-consuming. We are able to check the validity of the algorithm, with results that are generally better than the ones obtained by humans. It is worth mentioning that not all of the users that made the classification were experts on the matter of WDMS, but even the ones with the best results were just below the RF performance. We conclude stating that the Random Forest algorithm’s performance is at least, comparable to a human classification, being totally valid and helpful.
Figure C.1: Random Forest confusion matrix. Figure C.2: Users confusion matrix.
Figure C.3: Users accuracy histogram. Figure C.4: Users F1-score histogram.