{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Deep Learning Overview\n",
"\n",
"\n",
"**Deep learning** is a category of **machine learning**. Machine learning is a category of **artificial intelligence**. Deep learning is the use of neural networks to do machine learning, like classify and regress data. This chapter provides an overview and we will dive further into these topics in later chapters.\n",
"\n",
"\n",
"```{admonition} Audience & Objectives\n",
"This chapter builds on {doc}`../ml/regression` and {doc}`../ml/introduction`. After completing this chapter, you should be able to \n",
"\n",
" * Define deep learning\n",
" * Define a neural network\n",
" * Connect the previous regression principles to neural networks\n",
"```\n",
"\n",
"There are many good resources on deep learning to supplement these chapters. The goal of this book is to present a chemistry and materials-first introduction to deep learning. These other resources can help provide better depth in certain topics and cover topics we do not even cover, because I do not find them relevant to deep learning (e.g., image processing). I found the introduction the from [Ian Goodfellow's book](https://www.deeplearningbook.org/contents/intro.html) to be a good intro. If you're more visually oriented, Grant Sanderson has made a [short video series](https://www.youtube.com/watch?v=aircAruvnKk) specifically about neural networks that give an applied introduction to the topic. DeepMind has a high-level video showing what can be accomplished with [deep learning & AI](https://www.youtube.com/watch?v=7R52wiUgxZI). When people write \"deep learning is a powerful tool\" in their research papers, they typically cite [this Nature paper](https://www.nature.com/articles/nature14539) by Yann LeCun, Yoshua Bengio, and Geoffery Hinton. Zhang, Lipton, Li, and Smola have written a practical and example-driven [online book](http://d2l.ai/index.html) that gives each example in Tensorflow, PyTorch, and MXNet. You can find many chemistry-specific examples and information about deep learning in chemistry via the excellent [DeepChem](https://deepchem.io/) project. Finally, some deep learning package provide a short introduction to deep learning via a tutorial of its API: [Keras](https://keras.io/getting_started/), [PyTorch](https://pytorch.org/tutorials/beginner/basics/intro.html).\n",
"\n",
"The main advice I would give to beginners in deep learning are to focus less on the neurological inspired language (i.e., connections between neurons), and instead view deep learning as a series of linear algebra operations where many of the matrices are filled with adjustable parameters. Of course nonlinear functions (activations) are used to join the linear algebra operations, but deep learning is essentially linear algebra operations specified via a \"computation network\" (aka computation graph) that vaguely looks like neurons connected in a brain.\n",
"\n",
"\n",
"```{admonition} nonlinearity\n",
"A function $f(\\vec{x})$ is linear if two conditions hold:\n",
"\n",
"\\begin{equation}\n",
"f(\\vec{x} + \\vec{y}) = f(\\vec{x}) + f(\\vec{y})\n",
"\\end{equation}\n",
"\n",
"for all $\\vec{x}$ and $\\vec{y}$. And\n",
"\n",
"\\begin{equation}\n",
"f(s\\vec{x}) = sf(\\vec{x})\n",
"\\end{equation}\n",
"\n",
"where $s$ is a scalar. A function is **nonlinear** if these conditions do not hold for some $\\vec{x}$.\n",
"```\n",
"\n",
"\n",
"## What is a neural network?\n",
"\n",
"The *deep* in deep learning means we have many layers in our neural networks. What is a neural network? Without loss of generality, we can view neural networks as 2 components: (1) a nonlinear function $g(\\cdot)$ which operates on our input features $\\mathbf{X}$ and outputs a new set of features $\\mathbf{H} = g(\\mathbf{X})$ and (2) a linear model like we saw in our {doc}`../ml/introduction`. Our model equation for deep learning regression is:\n",
"\n",
"\\begin{equation}\n",
" \\hat{y} = \\vec{w}g(\\vec{x}) + b\n",
"\\end{equation}\n",
"\n",
"One of the main discussion points in our ML chapters was how arcane and difficult it is to choose features. Here, we have replaced our features with a set of trainable features $g(\\vec{x})$ and then use the same linear model as before. So how do we design $g(\\vec{x})$? That is the deep learning part. $g(\\vec{x})$ is a differentiable function composed of **layers**, which are themselves differentiable functions each with trainable weights (free variables). Deep learning is a mature field and there is a set of standard layers, each with a different purpose. For example, convolution layers look at a fixed neighborhood around each element of an input tensor. Dropout layers randomly inactivate inputs as a form of regularization. The most commonly used and basic layer is the **dense** or **fully-connected** layer.\n",
"\n",
"```{margin}\n",
"Dense means each input element affects each output element. At one point, sparse layers were popular and had a nice analogy with how a brain is connected. However, dense layers do not require deciding which input/output connections to make and sparse layers are very rare now (except incidentally sparse layers, like convolutions).\n",
"```\n",
"\n",
"A dense layer is defined by two things: the desired output feature shape and the **activation**. The equation is:\n",
"\n",
"\\begin{equation}\n",
" \\vec{h} = \\sigma(\\mathbf{W}\\vec{x} + \\vec{b})\n",
"\\end{equation}\n",
"\n",
"where $\\mathbf{W}$ is a trainable $D \\times F$ matrix, where $D$ is the input vector ($\\vec{x}$) dimension and $F$ is the output vector ($\\vec{h}$) dimension, $\\vec{b}$ is a trainable $F$ dimensional vector, and $\\sigma(\\cdot)$ is the activation function. $F$, the number of output features, is an example of a **hyperparameter**: it is not trainable but is a problem dependent choice. $\\sigma(\\cdot)$ is another hyperparameter. In principle, any differentiable function that has a domain of $(-\\infty, \\infty)$ can be used for activation. However, the function should be nonlinear. If it were linear, then stacking multiple dense layers would be equivalent to one-big matrix multiplication and we'd be back at linear regression. So activations should be nonlinear. Beyond nonlinearity, we typically want activations that can \"turn on\" and \"off\". That is, they have an output value of zero for some domain of input values. Typically, the activation is zero, or close to, for negative inputs. \n",
"\n",
"The most simple activation function that has these two properties is the rectified linear unit (ReLU), which is \n",
"\n",
"$$\n",
"\\sigma(x) = \\left\\{\\begin{array}{lr}\n",
"x & x > 0\\\\\n",
"0 & \\textrm{otherwise}\\\\\n",
"\\end{array}\\right.\n",
"$$\n",
"\n",
"### Universal Approximation Theorem\n",
"\n",
"One of the reasons that neural networks are a good choice at approximating unknown functions ($f(\\vec{x})$) is that a neural network can approximate any function with a large enough network depth (number of layers) or width (size of hidden layers). There are many variations of this theorem -- infinitely wide or infinitely deep neural networks. For example, any 1 dimensional function can be approximated by a depth 5 neural network with ReLU activation functions with infinitely wide layers (infinite hidden dimension) {cite}`lu2017expressive`. The universal approximation theorem shows that neural networks are, in the limit of large depth or width, expressive enough to fit any function.\n",
"\n",
"\n",
"### Frameworks\n",
"\n",
"\n",
"Deep learning has lots of \"gotchas\" -- easy to make mistakes that make it difficult to implement things yourself. This is especially true with numerical stability, which only reveals itself when your model fails to learn. We will move to a bit of a more abstract software framework than JAX for some examples. We'll use [Keras](https://keras.io/), which is one of many possible choices for deep learning frameworks. \n",
"\n",
"### Discussion\n",
"\n",
"When it comes to introducing deep learning, I will be as terse as possible. There are good learning resources out there. You should use some of the reading above and tutorials put out by Keras (or PyTorch) to get familiar with the concepts of neural networks and learning."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Revisiting Solubility Model\n",
"\n",
"We'll see our first example of deep learning by revisiting the solubility dataset with a two layer dense neural network."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Running This Notebook\n",
"\n",
"\n",
"Click the above to launch this page as an interactive Google Colab. See details below on installing packages.\n",
"\n",
"````{tip} My title\n",
":class: dropdown\n",
"To install packages, execute this code in a new cell. \n",
"\n",
"```\n",
"!pip install dmol-book\n",
"```\n",
"\n",
"If you find install problems, you can get the latest working versions of packages used in [this book here](https://github.com/whitead/dmol-book/blob/main/package/setup.py)\n",
"\n",
"````"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"import tensorflow as tf\n",
"import numpy as np\n",
"import dmol"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Load Data\n",
"\n",
"We download the data and load it into a [Pandas](https://pandas.pydata.org/) data frame and then standardize our features as before."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# soldata = pd.read_csv('https://dataverse.harvard.edu/api/access/datafile/3407241?format=original&gbrecs=true')\n",
"# had to rehost because dataverse isn't reliable\n",
"soldata = pd.read_csv(\n",
" \"https://github.com/whitead/dmol-book/raw/main/data/curated-solubility-dataset.csv\"\n",
")\n",
"features_start_at = list(soldata.columns).index(\"MolWt\")\n",
"feature_names = soldata.columns[features_start_at:]\n",
"# standardize the features\n",
"soldata[feature_names] -= soldata[feature_names].mean()\n",
"soldata[feature_names] /= soldata[feature_names].std()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prepare Data for Keras\n",
"\n",
"The deep learning libraries simplify many common tasks, like splitting data and building layers. This code below builds our dataset from numpy arrays. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"full_data = tf.data.Dataset.from_tensor_slices(\n",
" (soldata[feature_names].values, soldata[\"Solubility\"].values)\n",
")\n",
"N = len(soldata)\n",
"test_N = int(0.1 * N)\n",
"test_data = full_data.take(test_N).batch(16)\n",
"train_data = full_data.skip(test_N).batch(16)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notice that we used `skip` and `take` (See {obj}`tf.data.Dataset`) to split our dataset into two pieces and create batches of data.\n",
"\n",
"## Neural Network\n",
"Now we build our neural network model. In this case, our $g(\\vec{x}) = \\sigma\\left(\\mathbf{W^0}\\vec{x} + \\vec{b}\\right)$. We will call the function $g(\\vec{x})$ a *hidden layer*. This is because we do not observe its output. Remember, the solubility will be $y = \\vec{w}g(\\vec{x}) + b$. We'll choose our activation, $\\sigma(\\cdot)$, to be tanh and the output dimension of the hidden-layer to be 32. The choice of tanh is empirical --- there are many choices of nonlinearity and they are typically chosen based on efficiency and empirical accuracy. You can read more about this Keras [API here](https://keras.io/guides/sequential_model/), however you should be able to understand the process from the function names and comments."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# our hidden layer\n",
"# We only need to define the output dimension - 32.\n",
"hidden_layer = tf.keras.layers.Dense(32, activation=\"tanh\")\n",
"# Last layer - which we want to output one number\n",
"# the predicted solubility.\n",
"output_layer = tf.keras.layers.Dense(1)\n",
"\n",
"# Now we put the layers into a sequential model\n",
"model = tf.keras.Sequential()\n",
"model.add(hidden_layer)\n",
"model.add(output_layer)\n",
"\n",
"# our model is complete\n",
"\n",
"# Try out our model on first few datapoints\n",
"model(soldata[feature_names].values[:3])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```{margin} Jax vs Keras\n",
"We could have implemented this in Jax, but it would\n",
"have been a few more lines of code. To keep the focus high level, \n",
"I've used Keras for this chapter.\n",
"```\n",
"\n",
"We can see our model predicting the solubility for 3 molecules above. There may be a warning about how our Pandas data is using float64 (double precision floating point numbers) but our model is using float32 (single precision), which doesn't matter that much. It warns us because we are technically throwing out a little bit of precision, but our solubility has much more variance than the difference between 32 and 64 bit precision floating point numbers. We can remove this warning by modifying the last line to be:\n",
"\n",
"```py\n",
"model(soldata[feature_names].values[:3].astype(float))\n",
"```\n",
"\n",
"At this point, we've defined how our model structure should work and it can be called on data. Now we need to train it! We prepare the model for training by calling {obj}`model.compile`, which is where we define our optimization (typically a flavor of stochastic gradient descent) and loss"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model.compile(optimizer=\"SGD\", loss=\"mean_squared_error\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Look back to the amount of work it took to previously set-up loss and optimization process! Now we can train our model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"remove-output"
]
},
"outputs": [],
"source": [
"model.fit(train_data, epochs=50)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"That was quite simple!\n",
"\n",
"```{margin}\n",
"An epoch is one iteration over the whole dataset, regardless of batch size.\n",
"```\n",
"\n",
"For reference, we got a loss about as low as 3 in our previous work. It was also much faster, thanks to the optimizations. Now let's see how our model did on the test data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"remove-output"
]
},
"outputs": [],
"source": [
"# get model predictions on test data and get labels\n",
"# squeeze to remove extra dimensions\n",
"yhat = np.squeeze(model.predict(test_data))\n",
"test_y = soldata[\"Solubility\"].values[:test_N]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.plot(test_y, yhat, \".\")\n",
"plt.plot(test_y, test_y, \"-\")\n",
"plt.xlabel(\"Measured Solubility $y$\")\n",
"plt.ylabel(\"Predicted Solubility $\\hat{y}$\")\n",
"plt.text(\n",
" min(test_y) + 1,\n",
" max(test_y) - 2,\n",
" f\"correlation = {np.corrcoef(test_y, yhat)[0,1]:.3f}\",\n",
")\n",
"plt.text(\n",
" min(test_y) + 1,\n",
" max(test_y) - 3,\n",
" f\"loss = {np.sqrt(np.mean((test_y - yhat)**2)):.3f}\",\n",
")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This performance is better than our simple linear model."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercises\n",
"\n",
"1. Make a plot of the ReLU function. Prove it is nonlinear.\n",
"2. Try increasing the number of layers in the neural network. Discuss what you see in context of the bias-variance trade off\n",
"3. Show that a neural network would be equivalent to linear regression if $\\sigma(\\cdot)$ was the identity function\n",
"4. What are the advantages and disadvantages of using deep learning instead of nonlinear regression for fitting data? When might you choose nonlinear regression over deep learning?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Chapter Summary\n",
"\n",
"* Deep learning is a category of machine learning that utilizes neural networks for classification and regression of data. \n",
"* Neural networks are a series of operations with matrices of adjustable parameters. \n",
"* A neural network transforms input features into a new set of features that can be subsequently used for regression or classification.\n",
"* The most common layer is the dense layer. Each input element affects each output element. It is defined by the desired output feature shape and the activation function.\n",
"* With enough layers or wide enough hidden layers, neural networks can approximate unknown functions. \n",
"* Hidden layers are called such because we do not observe the output from one. \n",
"* Using libraries such as TensorFlow, it becomes easy to split data into training and testing, but also to build layers in the neural network. \n",
"* Building a neural network allows us to predict various properties of molecules, such as solubility. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Cited References\n",
"\n",
"```{bibliography}\n",
":style: unsrtalpha\n",
":filter: docname in docnames\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"celltoolbar": "Tags",
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}