Full text
Facultade de Química Grao en Química Traballo de Fin de Grao Mellora de métodos computacionais semiempíricos para a predición de reactividade química mediante técnicas de “machine learning” Autor: Xabier García Andrade Titor: Emilio Martínez Nuñez Departamento de Química Física Cotitor: Pablo García Tahoces Departamento de Electrónica e Computación Xullo de 2021. Curso 2020/2021
Traballo de Fin de Grao •Rama do coñecemento: Química Física •Departamento, centro, institución ou empresa: Facultade de Química (USC) •Titor: Dr. Emilio Martínez Nuñez •Cotitor: Dr. Pablo García Tahoces Autorización dos titores: Dr. Emilio Martínez Nuñez, Profesor Titular do Departamento de Química Física da Universidade de Santiago de Compostela. Dr. Pablo García Tahoces, Profesor Titular do Departamento de Electrónica e Computación da Universidade de Santiago de Compostela. Certifican: que a presente memoria adxunta, titulada "Mellora de métodos computacionais semiempíricos para a predición de reactividade química mediante técnicas de ’machine learning’", que presenta Xabier García Andrade, foi realizada baixo a súa dirección na Facultade de Química da Universidade de Santiago de Compostela. Considerando que a nomeada memoria constitúe o seu traballo de fin de grao, autorizan a súa presentación na Universidade de Santiago de Compostela. Para que así conste, asinan o presente informe en Santiago de Compostela a día 3 de Xullo de 2021. MARTINEZ NUÑEZ EMILIO - 33306236M Firmado digitalmente por MARTINEZ NUÑEZ EMILIO - 33306236M Nombre de reconocimiento (DN): c=ES, serialNumber=IDCES-333062 36M, givenName=EMILIO, sn=MARTINEZ NUÑEZ, cn=MARTINEZ NUÑEZ EMILIO - 33306236M Fecha: 2021.07.02 16:47:00 +02'00' GARCIA TAHOCES PABLO - 10066395P Firmado digitalmente por GARCIA TAHOCES PABLO - 10066395P Nombre de reconocimiento (DN): c=ES, serialNumber=IDCES-100663 95P, givenName=PABLO, sn=GARCIA TAHOCES, cn=GARCIA TAHOCES PABLO - 10066395P Fecha: 2021.07.05 10:14:33 +02'00'
Abstract O machine learning e a intelixencia artificial estanse convertindo en técnicas cada vez máis presentes na investigación en química computacional. A medida que temos acceso a unha maior cantidade datos de química cuántica, aumentan as posibilidades de uso de algoritmos intelixentes para a exploración do espazo químico. Por outra parte, aínda non dispoñemos de métodos eficientes para a predición de propiedades de reacción cuantitativas. Entre estas propiedades atópase a enerxía de activación, cuxa predición de forma precisa proporcionaría un método para o descubrimento de novos mecanismos de reacción e forneceríanos control sobre a cinética das reaccións. O presente traballo intenta buscar un algoritmo baseado en machine learning para a predición de enerxías de activación. O noso modelo depende dun cálculo a nivel semiempírico (PM7) e proporciona unha predición a nivel DFT mediante machine learning. Con este procedemento, conseguimos precisión química cun custo computacional reducido. Ademais de obter un rendemento equiparable ao estado da arte, esta alternativa contribúe con descritores personalizados, que poden ser incorporados en novos procedementos de minaría de datos na química. Por último, tamén proporciona unha interpretación do modelo dende a perspectiva da intuición química. Resumen El machine learning y la inteligencia artificial se están convirtiendo en técnicas cada vez más presentes en la investigación en química computacional. A medida que tenemos acceso a una mayor cantidad de datos de química cuántica, aumentan las posiblidades de uso de algoritmos inteligentes para la exploración del espacio químico. Por otra parte, todavía no disponemos de métodos eficientes para la predicción de propiedades de reacción cuantitativas. Entre estas propiedades se 1
encuentra la energía de activación, cuya predicción de forma precisa proporcionaría un método para el descubrimiento de nuevos mecanismos de reacción y nos facilitaría el control sobre la cinética de las reacciones. El presente trabajo intenta buscar un algoritmo basado en machine learning para la predicción de energías de activación. Nuestro modelo depende de un cálculo a nivel semiempírico (PM7) y proporciona una predicción a nivel DFT mediante machine learning. Con este procedimiento, conseguimos precisión química con un coste computacional reducido. Además de obtener un rendimiento equiparable al estado del arte, esta alternativa contribuye con descriptores personalizados, que pueden ser incorporados en procedimientos de minería de datos en la química. Por último, también proporciona una interpretación del modelo desde una perspectiva de la intuición química. Abstract Machine learning and artificial intelligence are becoming ubiquitous techniques in computational chemistry research. With quantum-chemical data becoming increasingly available, intelligent algorithms are taking the upper hand in the exploration of the chemical space. On the other hand, we still lack efficient algorithms when it comes to predicting quantitative reaction properties. Within this properties, accurately predicting activation energies would enable rapid discovery of new reaction mechanisms and would grant control over chemical kinetics. The present work intends to seek for a machine learning-based algorithm to predict activation energies. Our model relies on a semiempirical calculation (PM7 level of theory) and resorts to machine learning to DFT accuracy. With this procedure, we can obtain chemical accuracy while limiting the computational expenditure. In addition to achieving state of the art performance, this approach contribute with innovative custom descriptors that can be harnessed in data mining techniques in the chemical domain and allow interpretability from the perspective of chemical intuition. 2
CONTENTS Contents 1 Introduction 4 2 Objectives and Work Plan 7 3 Theoretical Framework 9 3.1 Artificial Intelligence and Machine Learning . . . . . . . . . . . . . . 9 3.1.1 Artificial Neural Networks . . . . . . . . . . . . . . . . . . . . 14 3.1.2 Experimentation in ML . . . . . . . . . . . . . . . . . . . . . 17 3.2 QuantumChemistry ........................... 18 3.2.1 Semiempirical Methods . . . . . . . . . . . . . . . . . . . . . . 18 4 Experimental Procedure 22 4.1 DatabaseCuration ............................ 22 4.2 DatasetDescription............................ 26 4.3 Descriptor Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . 28 4.4 ModelSelection.............................. 30 4.5 Alternatives................................ 40 5 Conclusions 43 5.1 Conclusiones................................ 44 5.2 Conclusións ................................ 45 3
1 Introduction Accurately predicting reactivity is certainly one of the most fundamental problems that can be faced in chemistry. Unravelling how any chemical system evolves and transforms with time opens many possibilities to develop new synthetic routes or enhancing current ones. A sufficiently trained chemist can definitely tell how reactants behave and what product they would yield. Nevertheless, sometimes the system is not tractable by human thinking. This limitation has lead to the development of new computational methodologies and algorithms that can emulate human-like performance, whose success is not only limited by computational power, but also by intrinsic algorithmic design flaws. From a computational perspective, in order to predict reactivity, the most crucial parameter that must be determined in a chemical reaction is the activation energy. Calculating reaction parameters for simple enough systems has been possible since the development of Hartree Fock (HF) methods [1]. Despite HF scheme success, it fails to produce useful calculations as the system becomes larger. In this situation, semi-empirical methods emerged as a tool to handle large molecules by means of integrating empirical parameters and approximations together with the HF formalism. Semi-empirical methods [2] enabled large systems calculations, but their results differed from experimental data if the system did not resemble those used for the parametrization. In order to achieve higher accuracy, computational chemists had to resort to density functional theory (DFT), which is another ab initio method [3]. DFT saw unprecedented success, attaining quantum chemical accuracy in many different sets of molecules. Then again, the limitation of DFT calculations is the size of the system. There are other methods that provide even more accurate calculations, CCSD(T) (coupled cluster calculations), considered by many quantum chemists as the gold standard [4]. Coupled cluster methods are only restricted to very small systems becoming extremely expensive as the system becomes larger. For the purpose of the present work, the discussion will remain at the DFT level. 4
At this point, we can agree that our main target would be to find a way to surpass DFT limitations while still obtaining the same rigorous results. There have been many attempts to formulate a new theoretical framework that can utterly substitute DFT, but they stumble in the same pitfall which is not being scalable. This situation lead to stagnation within the theoretical chemistry field, until the rise of machine learning in the physical sciences. Machine learning has been shifting the scientific paradigm for the last decade, from purely theoretical modelling towards data-driven discoveries. The applications in chemistry cover a broad range, from complex problems in retrosynthesis or reaction optimization to drug design [5] in the context of organic chemistry. Analytical chemistry is probably the subfield in chemistry where machine learning was first used, since the problems in analytical chemistry are typically of statistical nature, such as evaluating food quality [6]. In inorganic chemistry, recent developments of deep learning frameworks allow highly accurate prediction for inorganic materials [7]. Regarding predictions of reaction parameters, such as activation energy, machine learning based methodologies have seen significant growth as well. In particular, deep learning algorithms (a subfield within machine learning) dominate this area. Marquetand et al. [8] work was pioneering in the use of machine learning. They proposed a high-dimensional neural network to fit electronic structure data and construct potential energy surfaces for organic reactions. Allison et al. [9] described the application of an artificial neural network to the prediction of reaction rate constants for reactions involving OH radicals. Closer related to the scope of our work, Green et al.(2020) [10] proposed a deep learning approach to calculate activation energies and other quantitative data from reaction data. They used a novel approach that relies on a directed message passing neural network that encodes molecules as graphs and predicts the activation energy. Nevertheless, this model does not utilize information available from the transition 5
states and only relies on information from the atomic connectivity from reactants and products. After a thorough revision of the state of the art, it is clear that ML has taken over the computational chemistry space when it comes to quantitative prediction of reaction parameters. With the present work, we intend to expand on th type of methods, overcoming the shortcomings and flaws on common ML approaches by combining domain expertise as chemists and the most sophisticated machine learning algorithms. 6
2 Objectives and Work Plan The present work seeks to expand current methods on reaction parameters prediction. In particular, our goal is to develop a deep learning-based model that can accurately predict activation energies while remaining computationally affordable. In the previous chapter we mentioned how most approaches sought to surpass electronic structure calculations or molecular dynamics and provide a machine learning model that can directly predict the desired activation energy. Nevertheless, our approach is focused on leveraging a cheap calculation provided by semiempirical methods into higher accuracy (DFT level of theory). More precisely, the semiempirical level employed will be PM7 provided by MOPAC and the DFT functional with the desired precision is ωB97X-D3. This work can also be understood as a correction for the semiempirical level of theory or even as a reparametrization. In summary, we want to achieve higher accuracies without jeopardizing computational efficiency. In addition to providing this correction, the interpretation of the model output from a chemical perspective will grant unique insights into how semiempirical and DFT calculation differ, which can provide clues on how to offset parametrizations for theoreticians working on these semiempirical methods. With respect to the work plan, in order to train a model first it is necessary to obtain a curated dataset containing enough samples. For this work, the database produced by Grambow et al. (2020) [10] was used. They generated quantitative data for almost 12000 organic reactions at the ωB97X-D3/def2-TZVP quantum chemistry level. After scraping the data, sempiempirical calculations must be performed using geometries for the different chemical species specified in the database. Since there is the possibility that a fraction of the calculations cannot be achieved at the semiempirical level of theory, it was necessary to discard some of the data entries. Having obtained data at the semiempirical level, it was then possible to obtain 7
3.1 Artificial Intelligence and Machine Learning every iteration. If the learning rate is too large, global minimum might be skipped and the optimization might land in a local minimum. If is too small, the learning optimization process can be too slow. 3.1.1 Artificial Neural Networks Armed with the global vision on how machine learning problems work, now we should specify how parameters are updated and how predictions are made for the particular case of neural networks, even though that the same process is used for different models. An artificial neural network is a computing system which learns patterns from data and whose functioning rationale is inspired by how biological systems process and share information. Figure 5: Artificial Neural Network representation Every layer in a neural network is comprised of neurons, which can be understood as its building blocks. A collection of neurons comprise each of the layers shown in Figure 5. There are different types of layers, named input layer, hidden layers and output layer. Hidden layers are optional, and so are the number of hidden layers in a neural network. The purpose of each type of layer will become clear in the following paragraphs. At this point, we must focus on the building blocks. Each 14
3.1 Artificial Intelligence and Machine Learning neuron contains two sets of parameters: weights (θi) and biases (bi). When data is fed from the input layer, every neuron computes a linear function by using its weights and biases: Z=θ·X+b(3) Note that if neural networks only performed linear calculations, they would be equivalent to linear regression. In order to be able to compute non linear patterns, it is necessary to introduce another function. In ML terminology, this (presumably) non linear function is often referred to as activation function. In general, it can be expressed as: A=g(Z) = g(θ·X+b)(4) There are several activation functions, among those the most popular options are sigmoid or ReLu (Rectified Linear unit) functions, defined as: 3210123 x 0.0 0.5 1.0 1.5 2.0 2.5 3.0 g ( x ) ReLu Activation Function ReLu Function a) ReLu Activation Function 3210123 x 0.2 0.4 0.6 0.8 g ( x ) Sigmoid Activation Function Sigmoid Function b) Sigmoid Activation Function Figure 6: Activation Functions g(x) = 1 1 + e−x(5) 15
3.1 Artificial Intelligence and Machine Learning g(x) = max(0, x)(6) Where equations 6 and 5 refer to ReLu and sigmoid functions respectively. Figure 6 a) displays ReLu and b) Sigmoid activations functions. These two steps are performed sequentially, using the output from one layer as input for the next layer until output layer is reached. The output layer already produces our predictions, which will be used to calculate the loss function. Steps up to this point comprise what is usually known as feedforward step. Next steps, which will be called backwards steps, are the reason why neural networks are so widely used. The underlying algorithm which explains how NN learn is backpropagation [15]. Backpropagation is a method to calculate partial derivatives of the cost function with respect to the weights (parameters) of the model. Keeping in mind that each neuron computes a complex function depending on the output from previous layers, it is clear that in order to calculate partial derivatives, this relationship must be considered by means of the chain rule. Thus, backpropagation becomes an efficient implementation which enables a rapid computation of gradients in parameter space. ∂J ∂θ[L]=1 N ∂J ∂Z[L]g(Z)T=1 N ∂J ∂Z[L]A[L−1]TT(7) ∂J ∂b[L]=1 N N X i ∂J ∂Z[L](i)(8) ∂J ∂A[L−1] =θ[l]T∂J ∂Z[L](9) Equations 7 to 9 show how backpropagation is performed, where the Lindex refers to the layer and the other quantities were already defined previously. This is the most general version, it must be noticed that the exact implementation will 16
3.1 Artificial Intelligence and Machine Learning depend on which activation functions and loss function are chosen. Nevertheless, we will not elaborate more on this topic, since the most relevant bit of information to retain and which must be emphasized is that backpropagation is just a method to compute gradients. Eventually the computation of these gradients are needed for gradient descent algorithm to perform optimization with respect to the loss function as explained in the previous section. After revising the details and intricacies in neural networks, we will summarize how information flows within this model. First, predictor variables Xare fed to the input layer, which initiates the feedforward step until it reaches the output layer, producing a prediction ˆy. Cost function is used by the neural network to learn the optimal parameters to optimize the prediction by means of backpropagation and gradient descent. The process is repeated for a number of epochs until convergence of the loss function. Equipped with the knowledge on how to train models, now we will move on to discuss how to perform machine learning experiments. 3.1.2 Experimentation in ML Experiments in machine learning usually follow the same approach. First, the dataset is partitioned typically into train, validation and test sets by randomly selecting data entries and assigning a percentage of the dataset to each one. The train set, as the name suggests, is the one used to optimize the model parameters such that it learns how to perform the task. The validation set is used to measure how the model behaves with respect to a given metric and evaluates how the model works with unseen data. In the context of regression, the most common metric is arguably the mean absolute error (MAE , equation 10). Test set serves as an assessment on how the model is able to extrapolate to data which was not used during training nor as validation of the model performance. The difference between validation and test might seem subtle, but after performing an experiment it becomes 17
3.2 Quantum Chemistry clearer. MAE =PN i|Yi−ˆyi| N(10) Another concern regarding the experimentation process can be raised with respect to the partition into train and validation sets. Since we have agreed that it must be done randomly, the final distribution might result in a pathological division which leads to particularly poor results or, conversely, to a division which places examples in the validation set which are remarkably easy to predict. In order to solve this issue, cross-validation can be used, which consists of randomly splitting the dataset into train and validation several times and then taking the average values. With this technique, extreme values are smoothed and results are more likely to be able to generalize to new samples. 3.2 Quantum Chemistry In addition to the theoretical foundations on ML, a thorough review on quantum chemical calculations must be considered to understand what type of assumptions and limitations are needed in each case. For the scope of the present work, only semiempirical level of theory will be covered. Since DFT is only used as a reference method and due to the limited nature of this report, we will avoid expanding on the intricacies behind the method. Due to its increasing popularity, the essentials can be found in most introductory physical chemistry textbooks like Atkins [16]. 3.2.1 Semiempirical Methods Semiempirical methods are considered ab initio electronic structure methods which emerged as an efficient implementation of Hartree-Fock schemes. Nevertheless, Hartree-Fock methods require solving large matrices and integrals beyond 18
3.2 Quantum Chemistry numerical feasibility. Assuming that the wavefunction can be approximated in the form of a Slater determinant containing the molecular orbitals as N one-electron wave functions, the next step would be to find the Slater determinant that minimizes the energy by means of the variational principle. That is, finding the wavefunction that minimizes the integral: E= min ΘS→NhΘS|ˆ H|ΘSi(11) Where ˆ His the electronic Hamiltonian and ΘSis the Slater determinant. In the LCAO MO approximation, an electron can be described by means of a molecular orbital (OM), written as a linear combination of atomic orbitals (LCAO): ϕ(ri) = 1 √NiX l ci lφi(ri)(12) Where φi(~x)represents individual atomic orbitals and each cl iis a coefficient that must be determined by means of a variational method. The normalization constant is determined by: Ni=X lX k ci kci lSkl (13) Skl is the overlap integral between kand latomic orbitals. At this point it is useful to define three integrals which are central to the Hartree-Fock framework. The overlap integral is calculated as: Skl =Zϕk(r2)ϕl(r2)d3r2(14) Then, the Coulomb integral which accounts for the electronic repulsion is defined 19
3.2 Quantum Chemistry as: Ckl =Zϕk(r1)21 Rkl +1 r12 −1 rk1−1 rl2ϕl(r2)2d3r1d3r2(15) Finally, the exchange interaction integral which does not have a classical analogue with no clear physical explanation. It accounts for quantum mechanical phenomena: Jkl =Zϕ∗ k(r1)ϕ∗ l(r2)1 Rkl +1 r12 −1 rk1−1 rl2ϕl(r1)ϕk(r2)d3r1d3r2(16) A thorough explanation on how to expand this calculation can be found in a regular quantum chemistry textbook as it is out of the scope of this work. We will only present results, where we can skip to the following formula: FCk=kSCk(17) Which is known as the Fock secular equation, where Ckis the matrix containing the coefficients. F matrix is the Fock matrix, where the ith element is computed as: Fi=hi+ N/2 X j (2Cj−Jj)(18) Where hiis the corresponding one-electron hamiltonian. Then, the problem is reduced to a diagonalization exercise, which requires computationally expensive integral evaluations in order to obtain both F and S matrices. It is important to emphasize the final objective of this method. We want to find a diagonal matrix Ckwhich contains the coefficients that grant a functional form for the wavefunction. Calculating the energy by means of equation 11 leads to the ground state energy. 20
3.2 Quantum Chemistry Since evaluating the integrals needed for the variational method are extremely expensive from the computational perspective, there were several attempts to elude them. The prevalent version of these approximations is the so called NDDO type of semiempirical methods. NDDO stands for neglect of diatomic differential overlap and its purpose is to equate a certain type of integral to zero. In summary, it neglects the overlap over two basis functions ϕiϕjdrwhere the functions ϕi(r−RM) and ϕn(r−RN)are centered on different nuclei. The consequence is that the number of repulsion integrals that must be computed is drastically reduced [17]. In summary, semiempirical methods are Hartree-Fock based schemes where an additional approximation is considered in order to elude the calculation of an enormous number of integrals. This is where semiempirical methods attract more attention compared to DFT. DFT scaling law follows cubic complexity O(n3)while semiempirical NDDO methods as those incorporated in MOPAC lead to linear complexity O(n). While there is a wide variety of semiempirical methods currently available, PM7 [18], included in MOPAC, is corroborated as the best performing method. PM7 was parametrized to achieve greater performances with molecules outside of the subset of molecules employed for the parametrization. With respect to the approximations and assumptions made for PM7, two major modifications were reviewed. First, it enhanced the description of non-covalent interactions by means of including dispersion and hydrogen bonds. Then, errors under the NDDO formalism were corrected. Discussions regarding quantum chemical methods open the opportunity to clarify a term widely used in this work. When we refer to activation energies, we are actually referring to barrier heights. Nevertheless, after an extensive literature research, the term coined for barrier heights in the context of machine learning is activation energies. True activation energies are dependent on the temperature and would pose a much more intricate problem. 21
4 Experimental Procedure 4.1 Database Curation As mentioned previously, the first task we need to carry out after downloading the database contents is to perform the calculations at the semiempirical level. Our target data is Y=EDF T a−EPM7 a, which makes necessary the calculation of barrier heights at both the DFT and PM7 levels of theory. The database contains 11960 folders including output files produced after the optimizations for reactant, transition state and product. These output files were generated from Q-Chem software, at the ωB97X-D3 level of DFT theory using def2-TZVP basis expansion. Barrier heights are directly obtained by subtracting the TS final energy minus the reactant energy, considering ZPE. On the other hand, obtaining barrier heights at the semiempirical level entailed a much more complex process, as several sanity checks are required. Figure 7 presents a flow chart diagram explaining how the calculations are performed step by step. Further explanations are needed and the following paragraphs are allocated to understanding the diagram. First step, labeled as TS optimization in Figure 7 consists on parsing transition state coordinates from the database and performing an optimization step using MOPAC at semiempirical level of theory starting from the database geometry. After this step, it is crucial to check whether this TS connects reactants and products present in the database. That is, we must inspect if the optimized TS with MOPAC corresponds to the same reaction as per the database. In order to verify which reactants each TS leads to, the Intrinsic Reaction Coordinate (IRC) must be followed. The reaction path IRC method consists on finding the reaction path corresponding to the steepest descent curve from the first-order saddle point. That is, the path which maximizes the gradient starting from the TS 22
4.1 Database Curation Figure 7: Dataset generation flow diagram coordinates within the potential energy surface and eventually arriving at a minimum. This steepest descent reaction path in mass weighted coordinates is usually what is referred to by IRC [19]. This calculation can be performed in different directions starting at the TS geometry. Each direction is represented in the flow diagram by means of the keyword IRC = 1 or IRC = -1. Ideally, after performing this step, the minima obtained for each TS should correspond to the reactants and products present in the reaction involving that specific TS. Thus, the next step boils down to comparing different geometries and resolving whether they represent the same molecule. This step can be automated by resorting to spectral graph theory. A graph is the natural mathematical representation of a molecule, encoding how atoms are connected (bonds) in matrix form. The most relevant matrix is the 23
4.4 Model Selection Apart from how atoms are connected in a molecule, it is also important to know what type of bonds are involved. In order to encode this information, we parsed the bond order matrix from MOPAC output files and calculated its eigenvalues. The eigenvalues of this bond order matrix served as new descriptors. There was still room for capitalizing on the information provided by MOPAC calculations. By providing special keywords, it is possible to compute electrophilic and nucleophilic delocalizabilities, as well as charge densities [26]. These quantities provide an estimation on the energy stabilization upon the attack from an electrophilic or nucleophilic agent respectively. In general, they provide a picture of how the charge is distributed within a molecule. 4.4 Model Selection After obtaining the complete set of descriptors, it is important to investigate if there are highly correlated variables. Correlated features would only add statistical noise to the model and the usual procedure is to remove descriptors that exceed a correlation threshold. The correlation measure employed was Pearson correlation coefficient: r=Pi(xi−¯x)(yi−¯y) pPi(xi−¯x)2Pi(yi−¯y)2(22) Where xiare the values for descriptor xand yifor descriptor y. Considering every possible descriptor, a correlation matrix can be built where each entry represents the pairwise Pearson correlation coefficient between every pair of descriptors. A correlation threshold was established such that if a pair of descriptors exceed this value, one of them had to be dropped from the dataset. This threshold was optimized by cross-validation and the final value was set to ρ= 0.9. The next step, as outlined in the previous chapter regarding experimentation in 30
4.4 Model Selection ML, involves partitioning the dataset into training, validation and test sets. Following common practices in ML literature as well as considering the size of our dataset, we decided to use 85 % of the data for training purposes, 5 % for validation and 10 % for the test set. After separating the test set, it is time to select the optimum model which provides the best performance in the validation set. Following the procedure outlined in the previous chapters, in order to obtain the best performing model we need to optimize its hyperparameters. In the context of deep learning, there are several hyperparameters that can be fine-tuned. Since searching for the optima for every combination of hyperparameters simultaneously would be extremely computationally expensive, a sequential approach was carried out. First, it was necessary to elucidate the number of hidden layers and the number of neurons per layer. The minimum was obtained by resorting to a grid search. This method entails trying every possible combination and examining the one that minimizes a given metric. For our experiment, we decided to use MAE as the optimizing metric. It is important to emphasize that this metric is validated on the samples not used for training, meaning that this metric is computed for the validation set. With the aim of obtaining more general results, we used cross-validation. Crossvalidation involves testing the model performance with different train/validation set partitions with the purpose of preventing pathological cases. Table 1 shows MAE for the different combinations that assemble various forms of model architecture. 31
4.4 Model Selection Number of Hidden Layers Number of Neurons per hidden layer MAE (kcal/mol) 4128 ×256 ×64 ×32 5.04 ±0.34 4128 ×128 ×64 ×32 5.14 ±0.33 4128 ×64 ×64 ×32 5.21 ±0.33 5128 ×256 ×128 ×64 ×32 8.1±4.3 5128 ×128 ×64 ×64 ×32 5.13 ±0.40 5128 ×64 ×32 ×64 ×32 5.19 ±0.36 6128 ×256 ×128 ×64 ×64 ×32 8.1±4.5 6128 ×128 ×64 ×32 ×64 ×32 5.14 ±0.28 6128 ×64 ×32 ×16 ×64 ×32 5.21 ±0.23 Table 1: Neural Network Architecture hyperparameter tuning Uncertainties were assigned by means of the standard deviations obtained because of the cross-validation procedure. More precisely, 3-fold cross-validation was employed, meaning that per every combination of hyperparameters, 3 different dataset partitions were used and the presented values refer to the mean value. After selecting 4 hidden layers as the optimum value with the corresponding number of neurons, we could fix what is usually referred to as the network architecture. Apart from obtaining the minimum MAE from this architecture, there is another reason to choose the model with the lowest possible number of hidden layers and neurons. In the situation where two different models perform equally on the same dataset, it is always preferable to choose the simplest model. In this case, that would be the model with the least number of parameters, which depends on the number of neurons. The simpler the model is, the better it will extrapolate to data entries outside of the training and validation sets. Occam’s razor is commonly mentioned as the argument to avoid high complexity models on deep learning approaches [27]. 32
4.4 Model Selection Reducing model complexity serves as a hedge against another undesirable phenomenon which can happen in machine learning settings. This issue is overfitting, which consists of training a model which learns to predict data on the training set to an extremely high accuracy but achieving poor performance on the test set. The main evidence that a model is overfitting is that it performs drastically better on the training set than on the test set and the more iterations, the worse result is obtained in the test set. There are several approaches to avoid overfitting apart from increasing model simplicity. The most widely used resource is introducing dropout [28] within the model architecture. Dropout involves ignoring some connections between hidden layers with a given probability, such that statistical noise is introduced in the model in order to prevent the model from learning to excessively adapt to the training data. Dropout probability can be included as a hyperparameter as well which must be fine-tuned in a similar approach as network architechture. Dropout probability was optimized together with another pair of hyperparameters: learning rate and batch size. Batch size in interpreted as the number of data entries that are passed down to the input layer per iteration and learning rate is a measure on the magnitude of parameter update in every gradient descent iteration. Table 2 shows the results from validation set performances for different combinations of the hyperparameters using 3-fold cross-validation again. Since parameter space is still tractable , we decided to perform discretized grid search again, pursuing every possible set of parameters. 33
4.4 Model Selection Batch Size Learning Rate Dropout Rate 128 256 512 0.01 0.15 14.26 ±0.19 14.24 ±0.15 14.23 ±0.17 MAE kcal/mol 0.001 0.15 4.61 ±0.44 4.41 ±0.40 4.38 ±0.39 0.0001 0.15 4.34 ±0.35 4.30 ±0.36 4.34 ±0.36 0.01 0.25 14.23 ±0.16 14.24 ±0.16 14.25 ±0.15 0.001 0.25 4.75 ±0.31 4.57 ±0.37 4.59 ±0.32 0.0001 0.25 4.52 ±0.45 4.50 ±0.37 4.60 ±0.40 0.01 0.35 14.24 ±0.16 14.25 ±0.14 14.23 ±0.16 0.001 0.35 4.99 ±0.44 4.81 ±0.30 5.01 ±0.30 0.0001 0.35 4.65 ±0.34 4.78 ±0.49 4.85 ±0.35 Table 2: Hyperparameter Optimization From this experiment we can conclude that the optimum model is obtained by using 0.15 as dropout rate, 0.0001 as learning rate and a batch size of 128 samples. At this moment, it was interesting to include the data augmentation technique mentioned earlier. That is, including reverse barrier heights to increase the training data. Using twice the training data lead to results that were within the confidence interval spanned by the optimized model: (4.34 ±0.35) kcal/mol . We concluded that data augmentation in this case does not lead to better performances while penalizing computational expenditure. A sensible explanation is that our descriptors are heavily dependent on the transition state and reverse reactions share transition states with direct ones, introducing noise during training. This approach was abandoned and only direct reactions were finally used. 34
4.4 Model Selection 0 1000 2000 3000 4000 Epochs 0 500 1000 1500 2000 2500 3000 3500 MSE ( kcal / mol )2 MSE Train set MSE Dev set 0 1000 2000 3000 4000 Epochs 10 20 30 40 MAE kcal / mol MAE Train set MAE Dev set Learning Curves for DL model Figure 11: Learning Curves Figure 11 represents how MSE and MAE evolve on the training and validation (dev) sets. This procedure serves to identify and troubleshoot potential problems during training process. Since both metrics evolve similarly for every iteration, with the validation loss function only diverging in the end, we can state that the model effectively learns to predict samples from the training set and it is able to extrapolate to the validation set successfully. In other words, from evaluating this plot we can explore whether underfitting or overfitting is involved in this learning problem. In order to visualize the final model architecture and dimensions, Figure 12 displays a representation containing all the information needed to reproduce this model. 35
4.4 Model Selection Figure 12: Final model architecture Apart from the number of neurons per layer, the activation function used is also included, as well as how dropout was implemented. Dense layers refer to hidden layers where every neuron is fully connected. Note that the input layer requires 36
4.4 Model Selection entries to have 222 dimensions, which corresponds to the number of descriptors needed. On the other hand, the output layer produces two dimensions, due to the fact that we are simultaneously predicting both activation energies and productreactants energy differences. Upon obtaining a model with the optimum hyperparameters, it is time to compare its performance with respect to simply using PM7 calculations. Figure 13 shows on the left activation energies calculated at DFT level vs activation energies at PM7 level for the test set. Using MAE as a metric, the value obtained is 11.24 kcal/mol, with semiempirical calculations inducing systematic errors, as PM7 underestimates high activation energies (for higher values of activation energies, the majority of the points lie above the y=xblack line). 50 100 150 200 EPM 7 a ( kcal / mol ) 40 60 80 100 120 140 160 EDFT a ( kcal / mol ) MAE= 11.24 ( kcal / mol ) 50 100 150 EPM 7 + DL a ( kcal / mol ) 40 60 80 100 120 140 160 MAE= 3.69 ( kcal / mol ) DFT vs PM7 comparison + DL correction Figure 13: DL corrected activation energies On the right, activation energies at DFT level vs DL-corrected activation energies. 37
4.4 Model Selection The model performs equivalently well in every energy range, with no systematic bias, obtaining a MAE on the test set of 3.69 kcal/mol. The previous plot does not provide an accurate picture on how the model performs for the test set, because most of the samples from the test set are around 100 kcal/mol. Figure 14 shows how the correction works with a color code representing the number of data points lying in the same pixel. With this type of graph, it is clear that there is a compact density of points whose activation energies are accurately corrected. 40 60 80 100 120 140 EPM 7 + DL a ( kcal / mol ) 40 60 80 100 120 140 EDFT a ( kcal / mol ) 0.0 0.5 1.0 1.5 2.0 2.5 3.0 Count Figure 14: Density of corrected activation energies values. Apart from harnessing the power of this model with respect to its predictive power, it is equally important to asses how interpertable the model is (as opposed to black-box models). In order to extract more information from this model, we will employ Shap values [29]. Shap values is an approach that helps understanding how 38
4.4 Model Selection a machine learning model output is produced. Its foundation lays in the domain of game theory, but we will not provide a detailed explanation since it is out of the scope of this work. In order to comprehend the intuition behind this, it tries to make a prediction without employing a certain descriptor and validating how the model performs without this descriptor. Thus, we can obtain a measure of the most important descriptors and how they affect the prediction. Figure 15: Shap values sorted by descriptor importance Figure 15 represents the most relevant descriptors sorted by importance. It is interesting to notice how the activation energy computed at low level (MOPAC) as well as the exponential of this value represent the most important descriptors. Then, another point that emphasizes the interest behind our approach is how the most important features were novel descriptors proposed in this work rather than descriptors obtained from RDKit library. The model weights descriptors related to charge distribution as high priority descriptors, such as Parr and Pople absolute hardness (Par_n_Pople) and Mulliken electronegativity (Mul), which are both HOMO and LUMO linear combinations. 39
5.2 Conclusións barato computacionalmente serve como base para obter modelos máis precisos. En canto aos descritores empregados, é importante enfatizar o interese en empregar a información encapsulada nos estados de transición, un detalle omitido xeralmente na literatura. Ademais disto, os nosotros descritores adaptados, baseados en aspectos da teoría de grafos e a densidade electrónica (entre outros), poden ser adoptados polos usuarios para expandir as técnicas de minaría de datos usadas habitualmente na química. Por outra parte, introducimos o interese de empregar modelos de machine learning explicables ou interpretables no contexto da química. Esta forma de abordar o problema non só proporciona os descritores máis importantes, ademáis infórmanos da influenza de cada descritor sobre a predición. Esta liña de traballo pode beneficiar próximas parametrizacións de métodos semiempíricos. Cómpre salientar como ao analizar os descritores que o modelo considera máis importantes, atopamos que os descritores propostos no noso traballo son os priorizados polo modelo en vez dos extraídos da literatura. Futuro traballo neste tema pode extenderse a partir deste proxecto, xa que aínda quedan alternativas por explorar. A solución máis directa para mellorar a precisión do método e a súa habilidade para extrapolar a sistemas diferentes é expandir a base de datos mediante máis cálculos a alto nivel para aumentar o número de reaccións contidas. En particular, sería interesante incluir moléculas suficientemente diferentes para que a distribución estatística subxacente tivese en conta unha maior variedade de moléculas e fose menos homoxénea. A medida que se incrementa o tamaño do conxunto de datos, é posible recorrer a modelos máis sofisticados que requiren menos información (menos descritores) para acadar precisión química, como as CNN probadas neste traballo. Como nota concluínte, podemos afirmar que aínda que as solucións baseadas en machine learning xa están incorporadas na investigación en química computacional, podemos explotar máis a inxente cantidade de datos da que dispoñemos neste campo. 46
REFERENCES References [1] A.J. Duke and R.F.W. Bader. “A Hartree-Fock SCF calculation of the activation energies for two SN2 reactions”. Chemical Physics Letters (1971). [2] James J. P. Stewart. “Optimization of parameters for semiempirical methods I. Method”. Journal of Computational Chemistry (1989). [3] W. Kohn and L. J. Sham. “Self-Consistent Equations Including Exchange and Correlation Effects”. Phys. Rev. (1965). [4] Luke W. Bertels, Joonho Lee, and Martin Head-Gordon. “Polishing the Gold Standard: The Role of Orbital Choice in CCSD(T) Vibrational Frequency Prediction”. Journal of Chemical Theory and Computation (2021). [5] Adam C. Mater and Michelle L. Coote. “Deep Learning in Chemistry”. Journal of Chemical Information and Modeling (2019). [6] Ana M. Jiménez-Carvelo, Antonio González-Casado, M. Gracia Bagur-González, and Luis Cuadros-Rodríguez. “Alternative data mining/machine learning methods for the analytical evaluation of food quality and authenticity – A review”. Food Research International (2019). [7] Logan Ward, Ankit Agrawal, Alok Choudhary, and Christopher Wolverton. “A general-purpose machine learning framework for predicting properties of inorganic materials”. npj Computational Materials (2016). [8] Michael Gastegger and Philipp Marquetand. “High-Dimensional Neural Network Potentials for Organic Reactions and an Improved Training Algorithm”. Journal of Chemical Theory and Computation (2015). [9] Thomas C. Allison. “Application of an Artificial Neural Network to the Prediction of OH Radical Reaction Rate Constants for Evaluating Global Warming Potential”. The Journal of Physical Chemistry B (2016). 47
REFERENCES [10] Colin A. Grambow, Lagnajit Pattanaik, and William H. Green. “Reactants, products, and transition states of elementary chemical reactions based on quantum chemistry”. Scientific Data (2020). [11] Alfred North Whitehead and Bertrand Russell. Principia Mathematica. Cambridge University Press, 1925–1927. [12] F. Rosenblatt. The Perceptron, a Perceiving and Recognizing Automaton Project Para. Report: Cornell Aeronautical Laboratory. Cornell Aeronautical Laboratory, 1957. [13] Fabian Pedregosa, Gael Varoquaux, Alexandre Gramfort, Vincent Michel, Bertrand Thirion, Olivier Grisel, Mathieu Blondel, Peter Prettenhofer, Ron Weiss, Vincent Dubourg, Jake Vanderplas, Alexandre Passos, David Cournapeau, Matthieu Brucher, Matthieu Perrot, Edouard Duchesnay, and Gilles Louppe. “Scikit-learn: Machine Learning in Python”. Journal of Machine Learning Research (2012). [14] Sebastian Ruder. “An overview of gradient descent optimization algorithms”. arXiv preprint arXiv:1609.04747 (2016). [15] Henry J Kelley. “Gradient theory of optimal flight paths”. Ars Journal (1960). [16] Peter Atkins and Julio Paula. Atkins’ Physical chemistry. Oxford University press, 2008. [17] Wolfhard Koch. “Neglect of Diatomic Differential Overlap (NDDO) in Non- Empirical Quantum Chemical Orbital Theories”. Zeitschrift für Naturforschung A(1993). [18] James J. P. Stewart. “Optimization of parameters for semiempirical methods VI: more modifications to the NDDO approximations and re-optimization of parameters”. Journal of Molecular Modeling (2013). [19] Ramon Crehuet and Josep Maria Bofill. “The reaction path intrinsic reaction coordinate method and the Hamilton–Jacobi theory”. The Journal of Chemical Physics (2005). 48
REFERENCES [20] Rich Caruana. “Multitask Learning”. Machine Learning (1997). [21] Lars Ruddigkeit, Ruud van Deursen, Lorenz C. Blum, and Jean-Louis Reymond. “Enumeration of 166 Billion Organic Small Molecules in the Chemical Universe Database GDB-17”. Journal of Chemical Information and Modeling (2012). [22] Luke Taylor and Geoff Nitschke. “Improving Deep Learning with Generic Data Augmentation”. 2018. [23] Greg Landrum. “RDKit: Open-Source Cheminformatics Software” (2016), Visited 1/07/2021. url:https://github.com/rdkit/rdkit/releases/tag/ Release_2016_09_4. [24] Peter Ertl, Bernhard Rohde, and Paul Selzer. “Fast Calculation of Molecular Polar Surface Area as a Sum of Fragment-Based Contributions and Its Application to the Prediction of Drug Transport Properties”. Journal of Medicinal Chemistry (Sept. 2000). [25] Milan Randic. “Characterization of molecular branching”. Journal of the American Chemical Society (1975). [26] Gerrit Schüürmann. “QSAR analysis of the acute fish toxicity of organic phosphorothionates using theoretically derived molecular descriptors”. Environmental Toxicology and Chemistry (1990). [27] Ke Sun and Frank Nielsen. “Lightlike Neuromanifolds, Occam’s Razor and Deep Learning”. arXiv:1905.11027 (2021). [28] Nitish Srivastava, Geoffrey Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdinov. “Dropout: A Simple Way to Prevent Neural Networks from Overfitting”. Journal of Machine Learning Research (2014). [29] Scott M Lundberg and Su-In Lee. “A Unified Approach to Interpreting Model Predictions”. Advances in Neural Information Processing Systems. Ed. by I. Guyon, U. V. Luxburg, S. Bengio, H. Wallach, R. Fergus, S. Vishwanathan, and R. Garnett. Curran Associates, Inc., 2017. 49
REFERENCES [30] Waseem Rawat and Zenghui Wang. “Deep Convolutional Neural Networks for Image Classification: A Comprehensive Review”. Neural Computation (2017). [31] Kunal Ghosh, Annika Stuke, Milica Todorović, Peter Bjørn Jørgensen, Mikkel N. Schmidt, Aki Vehtari, and Patrick Rinke. “Deep Learning Spectroscopy: Neural Networks for Molecular Excitation Spectra”. Advanced Science (2019). [32] Christian Szegedy, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott Reed, Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, and Andrew Rabinovich. “Going Deeper with Convolutions”. arXiv:1409.4842 (2014). [33] Karen Simonyan and Andrew Zisserman. “Very Deep Convolutional Networks for Large-Scale Image Recognition”. 3rd International Conference on Learning Representations. 2015. 50