```
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pymatviz.parity import density_scatter_with_hist
from rdkit import Chem
from rdkit.Chem import AllChem, PyMol
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
import matplotx
'science', 'nature', matplotx.styles.dufte])
plt.style.use([
def gen_conformers(mol, numConfs=10_000, maxAttempts=1000,
=0.2, useExpTorsionAnglePrefs=True,
pruneRmsThresh=True, enforceChirality=True):
useBasicKnowledge"""Use RDkit to generate conformers for a molecule."""
= AllChem.EmbedMultipleConfs(mol, numConfs=numConfs, maxAttempts=maxAttempts, pruneRmsThresh=pruneRmsThresh, useExpTorsionAnglePrefs=useExpTorsionAnglePrefs, useBasicKnowledge=useBasicKnowledge, enforceChirality=enforceChirality, numThreads=0)
ids return list(ids)
def calc_energy(mol, conformer_id, iterations=0):
"""Calculate the energy of a conformer using the Merck Molecular Force Field."""
= AllChem.MMFFGetMoleculeForceField(mol, AllChem.MMFFGetMoleculeProperties(mol), confId=conformer_id)
ff
ff.Initialize()
ff.CalcEnergy()= {}
results if iterations > 0:
"converged"] = ff.Minimize(maxIts=iterations)
results["energy_abs"] = ff.CalcEnergy()
results[return results
# create a molecule
= Chem.AddHs(Chem.MolFromSmiles('CC(CCC)CC(C)(CCCC)O'))
mol
# visualize some conformers using PyMol
= gen_conformers(mol)
conformer_ids = PyMol.MolViewer()
v
v.DeleteAll()for cid in conformer_ids[:50]:
=cid,name='Conf-%d'%cid,showOnly=False)
v.ShowMol(mol,confId'set grid_mode, on')
v.server.do('ray')
v.server.do( v.GetPNG()
```

# Workshop on ML for materials science

*Some notes to accompany the ML workshop.*

## Motivation

To design new materials, we need to know their properties. There are two main routes to get the properties of a material:

- Perform an experiment to measure them
- Perform a simulation to “measure” them in silico

In many cases, performing an experiment is time-consuming and, hence, expensive. Also high-fidelity simulations can be very costly.

Therefore, there is a need for methods that can help us to predict the properties of materials with high fidelity and low cost. In this lecture, we will see that *supervised machine learning* (ML) is a powerful tool to achieve this goal.

Interestingly, this tool can be used in many different ways.

### Where does ML fit in the design process?

Machine learning can be used in multiple ways to make high-fidelity predictions of materials less expensive.

*Replace expensive evaluation of the potential energy surface \(U(\mathbf{X}, \{\mathbf{Z}\})\)*: Quantum chemistry as a field is concerned with the prediction of the potential energy surface \(U(\mathbf{X}, \{\mathbf{Z}\})\) of a system of atoms of types \(\mathbf{Z}\) at positions \(\mathbf{X}\). Quantum chemists have developed different approximations to this problem. However, since they are all kinds of functions that map positions of atoms (and atom types, and in some cases electron densities/coordinates) to energies, we can learn those functions with ML.Note that once we have done that, we generally still need to perform simulations to extract the properties of interest (e.g. as ensemble averages).

There are many good review articles about this. For example, see this one by Unke et al. as well as the ones by Deringer et al. and Behler in the same issue of Chemical Reviews.

*Directly predict the properties of interest*Instead of computing the properties of interest using a molecular simulations, we can build models that learn the \(f(\mathrm{structure}) \to \mathrm{property}\) mapping directly. The basis for this mapping might be experimental data or high-fidelity computational data.Also about this approach, there are many review articles. I also wrote one, focussing on porous materials.

Note that in the context of using ML for molecular simulations, it can also be used to address sampling problems. We will not cover this in detail in this lecture. For a good introduction, see the seminal paper by Noe and a piece about it by Tuckerman.

## Supervised ML workflow

For the main part of this lecture, we will assume that we use models that consume so-called tabular data, i.e. data that is stored in a table (feature matrix \(\mathbf{X}\) and target/label vector/matrix \(\mathbf{Y}\)), where each row corresponds to a material and each of the \(p\) columns corresponds to a so-called feature. We wil later see that this is not the only way to use ML for materials science, but it is the most common one. We will also explore in more detail how we obtain the features.

We will use some data \(\mathcal{D} = \{(\mathbf{x}_i, y_i)\}_{i=1}^N\) to train a model \(f(\mathbf{x}) \to y\) that can predict the target \(y\) for a new structure described with the feature vector \(\mathbf{x}^*\).

## Feeding structures into models

### Incorporating symmetries/invariances/equivariances

#### Learning a very simple force field

To understand what it takes to feed structures into ML models, let us try to build a very simple force field. To make things simple and fast, we will just attempt to predict the energies of different conformers of the same molecule.

We will create some data using RDkit and then use scikit-learn to train a model.

##### Generating data

For those conformers, we can now retrieve the positions and energies and save them in a pandas dataframe.

```
# make column names
= sum([[f'x_{n}',f'y_{n}', f'z_{n}'] for n in range(mol.GetNumAtoms())], [])
coordinate_names
# make a dataframe
= []
data for conformer_id in conformer_ids:
= calc_energy(mol, conformer_id)['energy_abs']
energy = mol.GetConformer(conformer_id).GetPositions().flatten()
positions = dict(zip(coordinate_names, positions))
position_dict 'energy'] = energy
position_dict[
data.append(position_dict)= pd.DataFrame(data).sample(len(data))
data data
```

x_0 | y_0 | z_0 | x_1 | y_1 | z_1 | x_2 | y_2 | z_2 | x_3 | ... | x_36 | y_36 | z_36 | x_37 | y_37 | z_37 | x_38 | y_38 | z_38 | energy | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|

2956 | -1.888411 | 0.980716 | 0.795268 | -1.384598 | -0.376714 | 0.551406 | -2.443785 | -1.429192 | 0.595362 | -3.546461 | ... | 4.471521 | -1.316545 | -0.316297 | 5.440541 | -1.261157 | 1.173016 | 0.535373 | -0.312004 | -2.765652 | 56.666092 |

347 | -0.638619 | 0.948293 | -1.162322 | -1.284374 | -0.289195 | -0.678756 | -2.740119 | -0.058294 | -0.274108 | -2.856352 | ... | 2.032264 | 2.642428 | -0.156436 | 3.804315 | 2.783507 | -0.437701 | 0.659132 | -2.160081 | -2.018395 | 50.196823 |

2164 | 2.247132 | -2.182808 | -0.484047 | 1.919532 | -0.950373 | 0.367501 | 3.140370 | -0.101372 | 0.293503 | 3.212722 | ... | -5.207289 | 1.462214 | 0.024671 | -4.255456 | -0.039155 | 0.095625 | -1.110165 | -2.844829 | -0.807478 | 54.755549 |

228 | -2.162932 | -1.793674 | -0.603346 | -1.833500 | -0.702714 | 0.383394 | -2.354875 | 0.633275 | -0.124539 | -3.874322 | ... | 5.494222 | 0.925957 | 0.053361 | 5.149128 | 2.068757 | -1.258956 | 0.619818 | 1.489050 | -0.056103 | 51.775634 |

85 | -2.019104 | -1.627692 | -0.533789 | -1.667962 | -0.212083 | -0.774601 | -2.469322 | 0.636404 | 0.212608 | -3.945823 | ... | 4.744605 | 1.123609 | 0.803188 | 4.698638 | -0.701746 | 0.570503 | 0.806263 | 0.529371 | 2.184220 | 48.362424 |

... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |

1937 | 1.345999 | -1.402712 | -0.358375 | 1.695800 | -0.184273 | 0.443783 | 2.449441 | 0.839638 | -0.381257 | 3.730152 | ... | -3.939779 | -1.101125 | 1.004064 | -3.674175 | -2.446992 | -0.229017 | -0.431422 | 1.589681 | -1.088693 | 64.963128 |

1739 | 1.336938 | -0.355992 | 1.565392 | 1.178714 | 0.042012 | 0.139400 | 2.603596 | 0.092437 | -0.458330 | 3.501323 | ... | -4.593405 | 0.740102 | 0.458868 | -5.425128 | 1.679390 | -0.818177 | -0.328068 | -2.994603 | -1.177913 | 60.512864 |

916 | 2.263933 | 0.297272 | -2.011137 | 1.617864 | -0.300167 | -0.773578 | 2.317359 | 0.238740 | 0.416252 | 3.778697 | ... | -5.081354 | -0.473016 | 0.461398 | -4.062779 | 0.531913 | 1.523067 | -0.914121 | -0.573692 | 2.153439 | 47.607815 |

1331 | -0.987950 | -1.249019 | -1.666076 | -1.577749 | -0.690378 | -0.400411 | -3.052775 | -0.534001 | -0.590542 | -3.783669 | ... | 5.254249 | 0.493001 | 0.847023 | 6.133113 | -0.046544 | -0.688083 | 0.701830 | -1.359424 | 1.297942 | 53.542013 |

2717 | -1.663847 | -2.033645 | 0.718789 | -1.221512 | -0.669793 | 0.115075 | -2.374927 | -0.243201 | -0.730142 | -3.604649 | ... | 3.946810 | 0.881520 | 2.302628 | 5.232277 | -0.061103 | 1.516130 | 1.634280 | -1.232796 | -2.276993 | 55.428224 |

3211 rows × 118 columns

Given this data, we can build a model. We will use a gradient boosting regressor from scikit-learn. We will also split the data into a training and a test set. In later sections, we will see why this is important. But for now, let us us just appreciate that a test set—conformers we did not train on—will give us a measure of how well our model will perform on new, unseen, conformers.

```
= data[coordinate_names] # X
positions = data['energy'] # y
energies
# split into training and test set
= 3000
train_points = positions[:train_points]
train_positions = positions[train_points:]
test_positions = energies[:train_points]
train_energies = energies[train_points:]
test_energies
# train a model
from sklearn.ensemble import HistGradientBoostingRegressor
= HistGradientBoostingRegressor()
model model.fit(train_positions, train_energies)
```

HistGradientBoostingRegressor()

**In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.**

On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

HistGradientBoostingRegressor()

Once we have trained a model, we can use it to predict the energies of new conformers. Let’s first see how well it does on the data it was trained on.

```
= model.predict(train_positions)
train_predictions
='True energy', ylabel='Predicted energy') density_scatter_with_hist(train_energies.values, train_predictions, xlabel
```

`<AxesSubplot:xlabel='True energy', ylabel='Predicted energy'>`

This looks pretty good. But how well does it do on new conformers? Let’s see.

```
= model.predict(test_positions)
test_predictions
='True energy', ylabel='Predicted energy') density_scatter_with_hist(test_energies.values, test_predictions, xlabel
```

`<AxesSubplot:xlabel='True energy', ylabel='Predicted energy'>`

From physics we know that (without external field) the energy of a molecule does not depend on where in space it is. That is, if we translate a molecule along \([1, 1, 1]\), the energy should not change.

```
# translate the molecule along [1, 1, 1]
= train_positions + 1
translated_positions = model.predict(translated_positions)
translated_predictions density_scatter_with_hist(train_energies.values, translated_predictions)
```

`<AxesSubplot:xlabel='Actual', ylabel='Predicted'>`

This is not what we expect. Our model shows completly unphysical behavior and predicts a different energy for the same conformers in different positions in space.

To fix this, and related problems, we need to use a more elaborate approach to building a model.

#### Mmaking predictions invariant/equivariant to transformations

##### What are symmetries we would like to respect?

Before we can talk about how to build a model that respects symmetries, we need to know what symmetries we would like to respect.

In the case of molecules, we would like to respect the following symmetries:

- translation: that is, if we move a molecule along a vector, the energy should not change (see above)
- rotation: that is, if we rotate a molecule, the energy should not change
- permutation of atoms: that is the order with which we put the atoms in the model does not matter

For crystals, we additionally need to respect periodicity. That is, for intensive properties, there should be no difference between using a unit cell or a super cell of that unit cell as input for a model.

Broadly speaking, there are three different ways to build models that respect symmetries.

*Data augmentation*: This is the most straightforward approach. We can generate new data points by applying the symmetries to the existing data points. For example, we can generate new conformers by rotating the existing conformers. This approach is very simple to implement, but it can be very expensive. For example, if we want to generate new conformers by rotating the existing conformers, we need to generate a new conformer for every rotation. This approach is often used for computer vision pipelines in which you might want to detect a cat in an image independent of the orientation. In this case, you can generate new images by rotating the existing images.*Features that are invariant/equivariant*: This approach is more sophisticated. We can build features that are invariant/equivariant to the symmetries we want to respect. For example, we can build features that are invariant to rotation. In the case of force field such features are bond lengths and angles. This is approach is widely used in ML for chemistry and materials science.*Models that are invariant/equivariant*: Alternatively, one can build special models that can consume point clouds as inputs and are equivariant to the symmetries we want to respect. We will not discuss this in detail, but you can find starting points in this perspective by Tess Smidt.

##### Invariant/equivariant features

###### Symmetry functions

###### Fingerprints

###### Correlation functions

###### Symmetry functions

###### Cheaper computations

## Training a model

### How to know if a model is good?

Before we can proceed to building models, we need to estabilsh a way to measure how good a model is.

Interestingly, this is not as trivial as it may sound. To realize this, it is useful to formally write down what we mean by a good model.

#### Empirical risk minimization

Let’s assume we have some input space \(\mathcal{X}\) and some output space \(\mathcal{Y}\). We can think of \(\mathcal{X}\) as the space of all possible inputs and \(\mathcal{Y}\) as the space of all possible outputs. For example, \(\mathcal{X}\) could be the space of all possible molecules and \(\mathcal{Y}\) could be the space of all possible energies. We want to learn a function \(f: \mathcal{X} \rightarrow \mathcal{Y}\) that maps inputs to outputs. We can think of \(f\) as a model that we want to train.

To build this models we have samples of the joint distribution \(p(x, y)\), where \(x\) is an input and \(y\) is the corresponding output. We can think of this as a set of data points \(\{(x_1, y_1), (x_2, y_2), \dots, (x_n, y_n)\}\).

If we now define a loss function \(L\) we can compute the risk, which is the expected value of the loss function:

\[ R(h)={\mathbf {E}}[L(f(x),y)]=\int L(f(x),y)\,dP(x,y). \]

our goal is to find a model \(f\) that minimizes the risk:

\[ {\displaystyle h^{*}={\underset {h\in {\mathcal {H}}}{\operatorname {arg\,min} }}\,{R(h)}.} \]

In practice we cannot compute this. The reason is that we do not have access to the joint distribution \(p(x, y)\), but only to a finite set of samples \(\{(x_1, y_1), (x_2, y_2), \dots, (x_n, y_n)\}\).

### Linear regression

```
import jax.numpy as jnp
def linear_regression(x, w, b):
return jnp.dot(x, w) + b
```

```
def loss(w, b):
= linear_regression(x, w, b)
prediction return jnp.mean((prediction - y) ** 2)
```

```
def init_params(num_feat):
return np.random.normal(size=(num_feat,)), 0.0
```

`= jax.grad(loss, argnums=(0, 1)) loss_grad `

```
= 1e-6
learning_rate = 1000 num_epochs
```

## Bias-variance trade-off

## Hyperparameters

## Kernel trick

## Feature importance

### Permutation feature importance

## Feature selection

### Curse of dimensionality

For understanding the curse of dimensionality, it is useful to consider a very simple ML model, the \(k\)-nearest neighbors model. In this model, we have a set of training points \(\{(x_1, y_1), (x_2, y_2), \dots, (x_n, y_n)\}\), where \(x_i\) is a vector of features and \(y_i\) is the corresponding label. To make a prediction, we compute the distance between the input and all training points and return the mode of the labels of the \(k\) closest training points.

Clearly, in this algorithm it is important to find the nearest neighbor. In general, this is important in many algorithms, for instance also in kernel-based learning.

Let’s now ask ourself what part of the space we need to find the nearest neighbors.

For this, let’s start considering a unit cube \([0,1]^d\) and \(n\) data points \(x_i\) sampled uniformly from this cube.

The smallest hypercube that contains \(k\) out of the \(n\) points has the following edge length

\[ l^d = \frac{k}{n} \quad \Rightarrow \quad l = \left(\frac{k}{n}\right)^{1/d} \]

If we plot this for different values of \(d\) we get the following plot:

```
import matplotlib.pyplot as plt
import numpy as np
def length(d, k=5, n=10_000):
return (k/n)**(1/d)
= np.arange(1, 1000)
d
plt.plot(d, length(d))'numbr of dimensions')
plt.xlabel('length of hypercube that contains k neighbors') plt.ylabel(
```

`Text(0, 0.5, 'length of hypercube that contains k neighbors')`

Clearly, for large \(d\) the length approaches 1—which means that all points are now almost equally far apart and comparing distances no longer makes much sense.

We can also check this by performing a simulation: Generating random \(d\) dimensional points and computing the distance between them. We can then plot the distribution of distances.

```
from scipy.spatial import distance_matrix
= [2, 5, 10, 100, 10_000]
dimensions = 1000
num_points
= plt.subplots(1, len(dimensions), sharey='all')
fig, axes
def get_distances(d, num_points):
= np.random.uniform(size=(num_points, d))
points = distance_matrix(points, points)
distances return np.array(distances).flatten()
for d, ax in zip(dimensions, axes):
= get_distances(d, num_points)
distances =20)
ax.hist(distances, binsf'd={d} \n cv={distances.std()/distances.mean():.2f}') ax.set_title(
```

Clearly, for large \(d\) the distances are almost the same (the histograms are much more peaked). We can also see this in terms of the coefficient of variation (cv), which is the standard deviation divided by the mean. For large \(d\) the cv is very small, which means that the distances are very similar.