<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Maxim Ziatdinov on Medium]]></title>
        <description><![CDATA[Stories by Maxim Ziatdinov on Medium]]></description>
        <link>https://medium.com/@ziatdinovmax?source=rss-eb4c5879edd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GcZq1QlG-q0iZV-cGQyiqw.jpeg</url>
            <title>Stories by Maxim Ziatdinov on Medium</title>
            <link>https://medium.com/@ziatdinovmax?source=rss-eb4c5879edd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:35:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ziatdinovmax/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Making the “Automated scientist”: Co-navigating the hypothesis and experimental space using…]]></title>
            <link>https://medium.com/data-science/making-the-automated-scientist-co-navigating-the-hypothesis-and-experimental-space-using-9c9e14de74c8?source=rss-eb4c5879edd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c9e14de74c8</guid>
            <category><![CDATA[gaussian-process]]></category>
            <category><![CDATA[bayesian-inference]]></category>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[thoughts-and-theory]]></category>
            <category><![CDATA[physics]]></category>
            <dc:creator><![CDATA[Maxim Ziatdinov]]></dc:creator>
            <pubDate>Tue, 14 Dec 2021 03:32:21 GMT</pubDate>
            <atom:updated>2021-12-15T18:59:46.649Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/thoughts-and-theory">Thoughts and Theory</a></h4><h3><strong>Making the “Automated scientist”: Co-navigating the hypothesis and experimental space using structured Gaussian Processes</strong></h3><p><em>Maxim Ziatdinov¹ ² &amp; Sergei V. Kalinin¹</em></p><p><em>¹ Center for Nanophase Materials Sciences and ² Computational Sciences and Engineering Division, Oak Ridge National Laboratory, Oak Ridge, TN 37831, United States</em></p><p>Experimental scientific research is one of the most fascinating activities known to mankind (at least, in the highly subjective opinion of the authors). Both of us started our scientific careers because of relatively simple backyard experimentation. For the second author in his teen years, it was applied exothermic chemical reactions, aka homemade fireworks. Here, it was relatively straightforward to follow the textbook recipes to produce the remarkable and colorful light effects. We doubt that the process can be described any better than done by J. R. R. Tolkien in the opening chapters of the Lord of the Rings describing Bilbo’s farewell party, so we will stop at this. However, it was even more fun to understand the redox chemical equations behind the fireworks and use this knowledge to tune the component fractions to enhance the spark generation or duration or to add alkali salts to tune the light emissions. In other words, understanding the magic behind the fireworks, and trying to use this understanding to make them more interesting.</p><p>As a second example, in his Ph.D. the first author was using a combination of ultra-high vacuum scanning tunneling microscopy and density functional theory to explore how chemical modifications of edges and vacancies in graphene affect its electronic properties [1, 2]. Again, the observations of beautiful atomic-scale images were but a first step towards understanding the intricate physical mechanisms giving rise to the functionality of graphene. Elucidating them allows us to address the interventional and counterfactual questions, meaning the what-if questions. For example, what happens if we substitute a specific atom in a material by its neighbor in the periodic table? Can we find the substitution that will yield the desired functionality? These and many other questions make science so much fun.</p><p>These are examples of a continuous cycle of scientific exploration that constitutes much of the scientist&#39;s work. We plan the experiments to enhance understanding of the theoretical mechanisms, thus refining and developing a theoretical model. In many cases, the experiments will yield new results that cannot be explained within the existing framework. This in turn sparks the development of new theories explaining the observations (or questioning and checking the experimental methodology). From a theoretical perspective, the theory can be built from the sets of postulates or known laws and relationships, ranging from highly abstract constructs of modern algebraic theory to the computational exploration of novel materials and compounds. Again, the new and non-trivial theoretical predictions are often of interest in the context of experimental realization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aECbPLkcjkQtle0u-UVTzA.jpeg" /><figcaption><strong>Figure 1.</strong> (Left) Exothermic decomposition of mysterious orange powder that turns green in the process. (Right) Atomically resolved image of Graphene containing defects visualized via Scanning Tunneling Microscopy. Figure by the authors.</figcaption></figure><p>Enter machine learning (ML). There are multiple overviews and perspectives on machine learning, delineating the general vision and underpinning of the field [3, 4]. However, the vast majority of the ML methods are currently based on purely correlative models — optimizing finding of correlative relationships between the features and targets in classical supervised learning, or disentangling the data representations in (variational) autoencoders. More importantly, many of these methods are often based on static data sets such as MNIST, CIFAR, or large medical and biological imaging data sets. Note that transition from static data sets to dynamic ones incorporating new data on the fly is highly non-trivial — and often is affected by the out of distribution effects. These limitations of classical ML are well known, and over the last several years multiple opinions on how to address them were posed [5], including those by the authors [6].</p><p>Partially in response to these limitations, over the last several years the ML and physics communities have been actively exploring the combination of ML and physics. For example, one of the central premises of science is a deep belief that correct physical laws will have elegant mathematical representation. Perhaps best this concept is represented by the famous <a href="https://en.wikipedia.org/wiki/The_Unreasonable_Effectiveness_of_Mathematics_in_the_Natural_Sciences">piece</a> by Winer on “Unreasonable Effectiveness of Mathematics in Natural Sciences”. Correspondingly, combining machine learning with reduced symbolic representations opens one way to combine machine learning and physics, with the recent works by Cranmer, Ho, and Battaglia and Brunton and Kutz being among the early examples.</p><p>The second limitation of classical machine learning methods is their reliance on well-established static data sets. In a sense, the ML part starts once the data is already available in full. Thus, the trained networks can be applied to new data — but only if it is generated by the same process, i.e., it comes from the same distribution. For many ML problems, this is achieved by having an extensive training data set covering all possible potentialities. However, this is often difficult or impossible, stimulating the development of active learning methods where the ML algorithm dynamically interacts with a data generation process. This can range from the simple choice of candidates for manual labeling to playing Atari games to running the bespoke scientific tools or automated cars.</p><p>Classical examples of active learning frameworks are Bayesian Optimization (BO) and Reinforcement Learning (RL). However, most of the algorithms within these frameworks are still data-driven, relying on the correlations between action, states, and rewards. Correspondingly, these algorithms typically require relatively large volumes of data (so far, more so for RL than BO) to establish correlative relationships between policies and outcomes. Note that much of the recent progress in Bayesian Optimization and Reinforcement Learning methods as applied to experiment or theory has been based on purely correlative methods [7–9, 10, 11]. Recently, a number of groups started to explore approaches combining physical models and active learning, either in the context of classical Bayesian inference on parametric models [12] or more flexible structured <a href="https://towardsdatascience.com/unknown-knowns-bayesian-inference-and-structured-gaussian-processes-why-domain-scientists-know-4659b7e924a4">Gaussian Processes</a>. However, in most of these cases, a physical model was relatively rigid.</p><p>This brief overview addresses a natural question of whether physical discovery and active learning can be integrated into a single framework. In this hypothesis-driven active learning, or <strong>hypothesis learning</strong> for short, the algorithm queries both the hypothesis space and the experimental space, with the dual goal of selecting and refining theories and driving the experimental protocol. Here we pose that it is possible, and introduce a <em>hypoAL</em> algorithm that allows accomplishing that.</p><p>We consider the simplest form of discovery when we have a list of possible models as alternative hypotheses. We assume that only one model is correct. Each model is characterized by several parameters. We assume that we can define priors on parameter values representing some of our knowledge about the system of interest. The idea here is that a correct model of a system’s behavior leads to a faster decrease of the overall Bayesian uncertainty about the system. However, running a full Bayesian inference (BI) on every model and selecting the one with the lowest uncertainty is computationally expensive and very time-consuming (the cost and time quickly rise as new measurements are added). Hence, our algorithm has only a short “warm-up” phase where we conduct BI for each model, select a model with the lowest total or median uncertainty over all the unmeasured points, and reward this model according to a pre-defined reward function. After this, we utilize a standard <em>ϵ</em>-greedy policy to sample only one model at each step. The total/median uncertainty computed from the Bayesian posterior of a sampled model is compared to the total/median uncertainty recorded in the previous step. If the uncertainty decreases, the sampled model is given a positive reward — otherwise, it gets penalized (negative reward). Then the next measurement point is derived as <em>x</em>ₙₑₓₜ= <em>argmax</em>(<em>U</em>) where <em>U</em> is the uncertainty ‘map’ produced by the sampled model. The entire <em>hypoAL</em> algorithm is summarized below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wo44lGgqnrx_BG3NRib3A.jpeg" /><figcaption><em>HypoAL</em> algorithm co-navigating experimental and hypothesis spaces</figcaption></figure><p>Let us illustrate the <em>hypoAL</em> algorithm on a concrete example relevant to phase transitions in physics that manifest in a discontinuity of a measurable system’s property (e.g., heat capacity). The corresponding (synthetic) data is shown in Figure 2 where the <em>x</em>-axis is a tunable parameter (temperature, concentration, etc.) and the <em>y</em>-axis is a system’s property that is measured experimentally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*rmtu4JOsfQRK6qJ1Q02rCw.jpeg" /><figcaption><strong>Figure 2. </strong>Synthetic data describing a 1D system with a discontinuous “phase transition”. Figure by authors.</figcaption></figure><p>Note that the full data (“noisy observations”) in Figure 2 is never seen by the algorithm. Instead, we start with a small number (3, in this case) of ‘seed’ measurement to initialize the <em>hypoAL</em> algorithm. The algorithm contains three possible models of the system’s behavior:</p><p>· Model 1 has a power-law behavior before transition point and linear behavior after transition point,</p><p>· Model 2 has a linear behavior before and after transition point,</p><p>· Model 3 has a power-law behavior before and after transition point.</p><p>We can use them as standalone probabilistic models or wrap them into the structured Gaussian processes. We chose the latter as it provides more flexibility and deals better with situations when none of the models is correct (see our previous <a href="https://towardsdatascience.com/unknown-knowns-bayesian-inference-and-structured-gaussian-processes-why-domain-scientists-know-4659b7e924a4">post</a>).</p><p>In all three models, we place a uniform prior over the possible position of transition point (meaning we don’t assume to have any knowledge of where exactly it may occur) and normal priors over the rest of the parameters.</p><p>The <em>hypoAL</em> learning is shown below in a form of animation. It shows the reconstruction performed by a model sampled at each step, the associated uncertainty, the acquisition function (here equivalent to median uncertainty), and the running sample-averaged reward for each model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*mthkzU-_91zrfw-HsDCVZw.gif" /><figcaption><strong>Figure 3. </strong>Application of <em>hypoAL</em> to the 1D system with a discontinuous ‘phase transition’. Figure by authors.</figcaption></figure><p>It is instructive to consider the behavior of the reconstructed function and the acquisition function during the process. The hypothesis functions we have chosen differ in their functional behavior in the continuous region, and positing and magnitude of the jump. The acquisition function (here it corresponds to the <em>s</em>GP uncertainty over the unmeasured points) by convention defines the “degree of interest” of the algorithm to the different regions of the parameter space, with the <em>argmax</em> of the acquisition function defining the point for taking the next measurements. It is clear that the choice of the model and behavior of the acquisition function are closely coupled, with the function seeking the location of the discontinuity. Also, note that the location containing the discontinuity was first discovered incorrectly — but upon accumulation of new observations, the algorithm has converged on the ground truth value.</p><p>The evolution of the Bayesian uncertainty during active learning is shown in Figure 4. The algorithm favored the third model where the system’s behavior before and after the transition point is described by the power-law functions (and, since we used synthetic data with known ground truth, we know that this is the correct model).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YY5bXsICJozFnEtA-az1Qw.jpeg" /><figcaption><strong>Figure 4.</strong> Evolution of median uncertainty (Uₘ in the <em>hypoAL</em> algorithm) during the active learning. The final sample-averaged rewards for each model are shown in the plot legend. Figure by authors.</figcaption></figure><p>Figure 5 also shows the result of the Bayesian fit over the entire parameter space for the three models using the points discovered by <em>hypoAL</em>. The model that received the highest reward clearly provided the best fit. Hence, we were able to learn a correct data distribution produced by a discontinuous function using only a small number of measurements, and also identify a correct model describing the system’s behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mdqf4m7hI7CIT5FIUEbXqw.jpeg" /><figcaption><strong>Figure 5. </strong>The Bayesian fits with three different models using the points discovered by <em>hypoAL</em>. The final sample-averaged reward for each model is also shown in subplot titles. Figure by authors.</figcaption></figure><p>The reproducibility and robustness of the algorithm were <a href="https://arxiv.org/abs/2112.06649">confirmed</a> by running it for different initializations of the seed points as well as other discontinuous functions.</p><p>So far, we were mainly focused on the ability of our algorithm to discover a correct model of the system’s behavior, but it also provides practical advantages in terms of overall execution time and reconstruction accuracy over the active learning strategies with a single probabilistic model (as described in the previous <a href="https://towardsdatascience.com/unknown-knowns-bayesian-inference-and-structured-gaussian-processes-why-domain-scientists-know-4659b7e924a4">post</a>, the active learning with a standard GP is not well suited for discontinuous functions and therefore is not considered here at all). We note that the ideal case scenario is to use <em>s</em>GP with the known/correct model of the system’s behavior (Model 3, in this case). In practice, however, this is rarely possible. In Figure 6 we compared the reconstruction error and execution time between active learning with partially correct standalone probabilistic models (AL-Model 1 and AL-Model 2) and <em>hypoAL</em>. The <em>hypoAL</em> clearly outperformed both models. Its execution time is also comparable to the active learning with the correct model (AL-Model 3) and, interestingly enough, it consistently produced a slightly better reconstruction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmVhbLCjUxItm6Y7nuZDoA.jpeg" /><figcaption><strong>Figure 6.</strong> The efficiency of active learning with standalone probabilistic models (AL-Model 1, AL-Model 2, AL-Model 3) and hypoAL for the same Bayesian inference setting. Note that Model 3 is the fully correct model and Model 2 and Model 1 are partially correct models. The y-axis corresponds to the mean absolute error. Figure by authors.</figcaption></figure><p>To summarize, the hypothesis learning approach realized via the h<em>ypoAL</em> algorithm developed here offers multiple parallels with the scientist&#39;s work. The algorithm sequentially queries the black box data generation process, effectively performing an experiment. Based on measurement results and some partial knowledge of the system of interest, as encoded in the list of possible models and prior distributions over their parameters, the algorithm explores which model explains the observation better and tries to reward the correct model based on how well it explains the data– much like a scientist will do. Again, much like the case for human-based research, prior knowledge matters. It will greatly accelerate the convergence of the algorithm if the priors are correct and narrow (i.e., we know a lot about the system), will converge to the correct model if priors are broad (we do not know much, but have an open mind), and may result in very slow progress if the priors are narrow and incorrect (we have wrong preconceived notions).</p><p>While the current example is very simple and relies on the analytical functions for models and ground truth, it is fairly straightforward to extend to more complex models, higher dimensional spaces, etc. The questions that will become open in this case include, how do we treat the high-dimensional behaviors, and to which extent low dimensional embeddings can be combined with simplistic functional forms. Similarly, for large dimensional theory spaces, we need pathways to effectively enumerate theories via graphs or NLP encodings, avoiding prohibitive enumeration search in the functional spaces. This also links to the exploration policy choices, with standard <em>ϵ</em>-greedy being sufficient only in low-dimensional spaces (in which there are not that many ways to do things wrong). But this is exactly what makes this direction exciting!</p><p>Following the original <a href="https://towardsdatascience.com/unknown-knowns-bayesian-inference-and-structured-gaussian-processes-why-domain-scientists-know-4659b7e924a4">posting</a> on the unknown knowns, one of our readers have shared another masterpiece of Persian poetry by Ibn Yamin (<a href="https://onejourney.net/ibn-yamin-quotes/">https://onejourney.net/ibn-yamin-quotes/</a>), who said</p><p>H<em>e who knows not,</em></p><p><em>And knows not that he knows not,</em></p><p><em>Is a fool — shun him.</em></p><p><em>He who knows not,</em></p><p><em>And knows that he knows not,</em></p><p><em>Is a child — teach him.</em></p><p><em>He who knows,</em></p><p><em>And knows not that he knows,</em></p><p><em>Is asleep — wake him.</em></p><p><em>He who knows,</em></p><p><em>And knows that he knows,</em></p><p><em>Is wise — follow him.</em></p><p>We hope that the combination of Bayesian methods co-navigating the hypothesis and automated experiment spaces can be one of the directions to grow in the coming years. Finally, in the scientific world, we acknowledge our research sponsor. This effort was performed and supported at Oak Ridge National Laboratory’s Center for Nanophase Materials Sciences (CNMS), a U.S. Department of Energy, Office of Science User Facility. You can take a virtual walk through it by using <a href="https://my.matterport.com/show/?m=MT819FqAwbT">this link</a>, and please let us know if you want to know more.</p><p>For more details/results, check out our <a href="https://arxiv.org/abs/2112.06649">preprint</a> on arxiv and the corresponding <a href="https://github.com/ziatdinovmax/hypoAL">code</a> on GitHub.</p><p><strong>References</strong></p><p>1. Ziatdinov, M.; Fujii, S.; Kusakabe, K.; Kiguchi, M.; Mori, T.; Enoki, T., Direct imaging of monovacancy-hydrogen complexes in a single graphitic layer.<em> Physical Review B </em><strong>2014,</strong> <em>89</em> (15), 155405.</p><p>2. Ziatdinov, M.; Lim, H.; Fujii, S.; Kusakabe, K.; Kiguchi, M.; Enoki, T.; Kim, Y., Chemically induced topological zero mode at graphene armchair edges. <em>Phys. Chem. Chem. Phys. </em><strong>2017,</strong> <em>19</em> (7), 5145–5154.</p><p>3. LeCun, Y.; Bengio, Y.; Hinton, G., Deep learning. <em>Nature </em><strong>2015,</strong> <em>521</em> (7553), 436–444.</p><p>4. Schmidhuber, J., Deep learning in neural networks: An overview. <em>Neural Netw. </em><strong>2015,</strong> <em>61</em>, 85–117.</p><p>5. Schölkopf, B.; Locatello, F.; Bauer, S.; Ke, N. R.; Kalchbrenner, N.; Goyal, A.; Bengio, Y., Toward causal representation learning. <em>Proceedings of the IEEE </em><strong>2021,</strong> <em>109</em> (5), 612–634.</p><p>6. Vasudevan, R. K.; Ziatdinov, M.; Vlcek, L.; Kalinin, S. V., Off-the-shelf deep learning is not enough, and requires parsimony, Bayesianity, and causality. <em>npj Comput. Mater. </em><strong>2021,</strong> <em>7</em> (1), 6.</p><p>7. Vasudevan, R. K.; Kelley, K. P.; Hinkle, J.; Funakubo, H.; Jesse, S.; Kalinin, S. V.; Ziatdinov, M., Autonomous Experiments in Scanning Probe Microscopy and Spectroscopy: Choosing Where to Explore Polarization Dynamics in Ferroelectrics. <em>ACS Nano </em><strong>2021,</strong> <em>15</em> (7), 11253–11262.</p><p>8. Kalinin, S. V.; Valleti, M.; Vasudevan, R. K.; Ziatdinov, M., Exploration of lattice Hamiltonians for functional and structural discovery via Gaussian process-based exploration–exploitation. <em>J. Appl. Phys </em><strong>2020,</strong> <em>128</em> (16), 164304.</p><p>9. Krull, A.; Hirsch, P.; Rother, C.; Schiffrin, A.; Krull, C., Artificial-intelligence-driven scanning probe microscopy. <em>Communications Physics </em><strong>2020,</strong> <em>3</em> (1), 54.</p><p>10. Silver, D.; Huang, A.; Maddison, C. J.; Guez, A.; Sifre, L.; van den Driessche, G.; Schrittwieser, J.; Antonoglou, I.; Panneershelvam, V.; Lanctot, M.; Dieleman, S.; Grewe, D.; Nham, J.; Kalchbrenner, N.; Sutskever, I.; Lillicrap, T.; Leach, M.; Kavukcuoglu, K.; Graepel, T.; Hassabis, D., Mastering the game of Go with deep neural networks and tree search. <em>Nature </em><strong>2016,</strong> <em>529</em> (7587), 484-+.</p><p>11. Mnih, V.; Kavukcuoglu, K.; Silver, D.; Rusu, A. A.; Veness, J.; Bellemare, M. G.; Graves, A.; Riedmiller, M.; Fidjeland, A. K.; Ostrovski, G.; Petersen, S.; Beattie, C.; Sadik, A.; Antonoglou, I.; King, H.; Kumaran, D.; Wierstra, D.; Legg, S.; Hassabis, D., Human-level control through deep reinforcement learning. <em>Nature </em><strong>2015,</strong> <em>518</em> (7540), 529–533.</p><p>12. McDannald, A.; Frontzek, M.; Savici, A. T.; Doucet, M.; Rodriguez, E. E.; Meuse, K.; Opsahl-Ong, J.; Samarov, D.; Takeuchi, I.; Kusne, A. G., On-the-fly Autonomous Control of Neutron Diffraction via Physics-Informed Bayesian Active Learning. <em>arXiv preprint arXiv:2108.08918 </em><strong>2021</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c9e14de74c8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/making-the-automated-scientist-co-navigating-the-hypothesis-and-experimental-space-using-9c9e14de74c8">Making the “Automated scientist”: Co-navigating the hypothesis and experimental space using…</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unknown Knowns, Bayesian Inference, and structured Gaussian Processes]]></title>
            <link>https://medium.com/data-science/unknown-knowns-bayesian-inference-and-structured-gaussian-processes-why-domain-scientists-know-4659b7e924a4?source=rss-eb4c5879edd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4659b7e924a4</guid>
            <category><![CDATA[bayesian-inference]]></category>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[thoughts-and-theory]]></category>
            <category><![CDATA[active-learning]]></category>
            <category><![CDATA[automation-tools]]></category>
            <dc:creator><![CDATA[Maxim Ziatdinov]]></dc:creator>
            <pubDate>Thu, 18 Nov 2021 18:57:06 GMT</pubDate>
            <atom:updated>2021-11-19T19:29:13.838Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/thoughts-and-theory">Thoughts and Theory</a></h4><h4>Why domain scientists know more ML than they think</h4><p><em>Maxim Ziatdinov¹ ² &amp; Sergei V. Kalinin¹</em></p><p><em>¹ Center for Nanophase Materials Sciences and ² Computational Sciences and Engineering Division, Oak Ridge National Laboratory, Oak Ridge, TN 37831, United States</em></p><p>About 20 years ago, Donald Rumsfeld, the erstwhile minister of defense, <a href="https://en.wikipedia.org/wiki/There_are_known_knowns">famously said</a> referring to the intelligence situation, “<em>…there are known knowns; there are things we know we know. We also know there are known unknowns; that is to say we know there are some things we do not know. But there are also unknown unknowns — the ones we don’t know we don’t know</em>.”. Despite coming from a different context, this statement profoundly describes the work of scientists. We establish our worldview and build fundamental exploration based on what we know, can read in the textbooks, or have learned throughout our professional career from experience, discussions with colleagues, or spending countless hours in the labs. These are the known knowns. We also often know what we do not know — and typically, these known unknowns are the immediate target of our research. That said, for each scientific experiment, the unknown unknowns are critical — the factors outside of our sphere of attention that can drastically affect our measurements, analyses, and conclusions.</p><p>Obviously, the very succinct statement by Rumsfeld is not the first time the division of the world into types of knowns and unknowns was noticed. To the authors’ knowledge, the first documented statement to this effect can be traced to <a href="https://en.wikipedia.org/wiki/Nasir_al-Din_al-Tusi">Naser od-Din Tusi</a> (1201–1274), who said</p><p><em>Har kas ke bedanad va bedanad ke bedanad</em></p><p><em>Asb-e kherad az gombad-e gardun bejahanad</em></p><p><em>Har kas ke nadanad va bedanad ke nadanad</em></p><p><em>Langan kharak-e khish be manzel beresanad</em></p><p><em>Har kas ke nadanad va nadanad ke nadanad</em></p><p><em>Dar jahl-e morakkab’abad od-dar bemanad</em></p><p>or, in translation from Farsi:</p><p><em>Anyone who knows, and knows that he knows</em></p><p><em>Makes the steed of intelligence leap over the vault of heaven</em></p><p><em>Anyone who does not know, but knows that he does not know</em></p><p><em>Can bring his lame little donkey to the destination nonetheless</em></p><p><em>Anyone who does not know, and does not know that he does not know</em></p><p><em>Is stuck forever in the double ignorance</em></p><p>It is highly possible that the historical references can go even earlier, but we were unable to find them. That said, despite the significant progress of the instruments of scientific inquiry from the Abbasid and Umayyad eras, the role of the known and unknown factors in scientific discovery remains.</p><p>For example, in his scientific career the second author worked extensively with Electrochemical Strain Microscopy (ESM), the technique that allows probing electrochemical reactions on the nanometer level via measuring minute (smaller than the radius of the hydrogen atom) expansion and contraction of material induced by ionic motion [1, 2]. The measured signal in the ESM is a local hysteresis loop, representing the electrochemical response of a material to bias. For a classical material such as ceria CeO₂, these hysteresis loops will be very reproducible between distinct locations on the sample surface. This suggests that they are descriptive of the reactions at the scanning probe microscopy tip-surface junction and are not affected by the possible variations of materials composition (we did not expect much) or surface roughness (which is always a problem in SPM). However, the shape of the hysteresis loops changed completely when the measurements were performed in a controlled gas atmosphere and, yet again, vacuum. And this, in turn, signified that the atmospheric environment is a significant factor in the measured responses. If we had not done the measurements in several atmospheres (that required non-standard modifications to the microscope) and tried to describe the mechanisms without considering the role of atmospheric water, this would have been a typical example of an unknown unknown. As it were, it became a known unknown — which stimulated another decade of theoretical and experimental studies and led to the discovery of unusual coupling between ferroelectricity and surface electrochemistry [3], among other developments.</p><p>That said, are the three categories of knowns/unknows all there is to it? We pose that when actively incorporating machine learning methods into the domain science, we often discover <em>unknown knowns</em> — meaning the full spectrum of prior knowledge ranging from generalizations (physical laws) and domain-specific data, all the way to the difficult-to-quantify intuition. Hence, the question now becomes, how can we incorporate the prior knowledge, the unknown knowns, into the scientific discovery process and do so in a principled and quantifiable manner.</p><p>The general framework for this is laid by the Bayes formula. There are multiple excellent books describing the Bayesian approach, as well as Medium posts. For the second author, the preferred point of entry into all things Bayesian were the books by Martin [4] and Lambert [5], with the systematic comparison between Bayesian and frequentist methods given by Kruschke [6] The first author believes that the best (for the domain scientist) book on the Bayesian analysis is Richard McElreath’s <a href="https://xcelab.net/rm/statistical-rethinking/">“Statistical Rethinking”</a>.</p><p>Below, we give the classical Bayes formula from the domain scientist perspective. Here, the purpose of the scientific experiment is to derive new knowledge, aka probability of theory, from the newly acquired experimental data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*OlTjNJ0bDxz8QPQNX6YAvA.jpeg" /><figcaption><strong>Figure 1. </strong>Bayes formula from the domain scientist perspective. Figure by the authors.</figcaption></figure><p>Here, the probability of data given the theory, or likelihood in Bayesian language, is directly accessed using the forward modeling. The probability of data, or evidence, is directly assessed using computational methods, whether it is Markov Chain Monte Carlo or Variational Inference. But it is the third part — the probability of theory, or a prior — that typically raises most issues. Indeed, the critique often leveled at Bayesian models is that they require priors, and these are difficult to be established consistently. And in fact, they are — if one stays fully in the statistics field. For a domain expert, prior knowledge is absolutely essential and actually defines domain expertise. However, it is the unknown known, and very often this knowledge is not easy to quantify or establish in the form of prior distributions in the traceable algorithmic form. Perhaps even more importantly, it is not immediately clear how to incorporate the prior knowledge in the active learning workflows for experimental discovery. Let’s consider them one by one.</p><p>Once the experimental data is available, the Bayesian Inference methods allow straightforward analytics to be performed. For example, recently, we have explored the structure of ferroelectric domain walls using high-resolution electron microscopy [7]. Here, the domain wall structure is determined by the specific functional form of the free energy that gives rise to analytical solutions describing the domain wall profile. The simple functional fits, as done earlier [8, 9], give numerical estimates of the parameters, but do not allow to go beyond these. Comparatively, Bayesian methods allow incorporating the prior knowledge of materials’ physics in the form of prior distributions of relative constants, which in turn can be obtained from the preponderance of published data, macroscopic measurements, etc. For example, one of the values of large materials informatics projects such as <a href="https://materialsproject.org/">Materials Project</a> is that it integrates the data from multiple separated sources into easy-to-access form.</p><p>Similarly, the Bayesian framework allows answering non-trivial questions such as whether prior knowledge of materials physics affects what we learn from the experiment (quite surprisingly — the more we know, the more we learn), whether the specific models of materials behaviors can be differentiated based on the observed data (not in this case), and what microscope resolution or information limit is necessary to distinguish different models. Similarly, Bayesian methods allow defining many “absolute” quantities in a probabilistic fashion — for example, descriptors such as symmetry or structural units [10].</p><p>However, the next question becomes whether we can use the Bayesian approach for active learning and property optimization? In principle, it is possible to use the classical Bayesian approach as detailed above. Here, we define the prior hypothesis as a structured probabilistic model. Given the experimental data, we refine the parameters of our model and then explore the posterior predictive probabilities over the parameter space. Much like classical Bayesian Optimization/active learning (BO/AL) described in our previous <a href="https://towardsdatascience.com/gaussian-process-first-step-towards-active-learning-in-physics-239a8b260579">post</a>, the expected value and/or associated uncertainty can be used to guide the measurements (i.e., select the next measurement point).</p><p>However, practically, the BO/AL based on the structured probabilistic model of the expected system’s behavior does not work well when the model is only partially correct. At the same time, this is exactly what we usually have to deal with in experiments where even the most sophisticated theory describes reality only to a certain approximation, and several competing models are possible, not to mention all the measurements-related non-idealities. Of course, the alternative is to substitute a rigid structured probabilistic model with a highly flexible Gaussian process (GP). The latter, however, does not usually allow for the incorporation of prior domain knowledge and can be biased toward a trivial interpolative solution.</p><p>Hence, we introduce a structured Gaussian Process (sGP), where a classical GP is augmented by a structured probabilistic model of the expected system’s behavior [11]. This approach allows us to balance the flexibility of the non-parametric GP approach with a rigid structure of prior (physical) knowledge encoded into the parametric model. The Bayesian treatment of the latter provides additional control over the BO/AL via the selection of priors for the model parameters, i.e., incorporation of the past knowledge.</p><p>More formally, given the input parameters <em>x</em> and target property <em>y</em>, the classical GP is defined as <em>y</em> ~ <em>MultivariateNormal</em>(<em>m</em>(<em>x</em>), <em>K</em>(<em>x</em>, <em>x</em>`)), where <em>m</em> is a mean function usually set to 0 and <em>K</em> is a kernel function with weakly-informative priors (usually chosen as LogNormal) over its parameters. The latter can be inferred using the Hamiltonian Monte Carlo (HMC) sampling technique. Then, the prediction on the new/unmeasured set of inputs is given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*24hSMcONrjx3ZB6_DP9Xfg.png" /></figure><p>where <em>θⁱ </em>is a single HMC posterior sample with kernel hyperparameters. Note that the commonly assumed observation noise is absorbed into the computation of the kernel function. (We denoted the new inputs and associated prediction by a * subscript — unfortunately, at the moment of writing, the Medium does not have the in-line support for this and other subscripts).</p><p>In our <em>s</em>GP approach, we substitute a constant mean function <em>m</em> in the equations above with a structured probabilistic model whose parameters are inferred together with the kernel parameters via the HMC. Then, the Eq (1b) becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*TAhI9nL7VS76ONOvab2eHw.png" /></figure><p>where <em>ϕⁱ </em>is a single HMC posterior sample with the learned model parameters. This probabilistic model reflects our prior knowledge about the system, but it does not have to be precise, that is, the model can have a different functional form, as long as it captures general or partial trends in the data.</p><p><strong>Bayesian Optimization with structured GP</strong></p><p>We will illustrate the advantage of the <em>s</em>GP approach with specific examples. First, we are going to use a slightly modified <a href="https://doi.org/10.1016/j.paerosci.2008.11.001">Forrester function</a>, <em>f</em>(<em>x</em>) = (5<em>x-</em>2)²sin(12<em>x</em>-4), which is commonly used to evaluate the optimization algorithms. It has two local minima in addition to the global minimum. Our goal is to converge on the global minimum using only a small number of steps (measurements). First, we use BO with vanilla GP. We start with a ‘good’ initialization of the seed points (the ‘warmup’ measurements performed before running the BO) and use the <a href="https://towardsdatascience.com/gaussian-process-first-step-towards-active-learning-in-physics-239a8b260579">upper confidence bound</a> (UCB) acquisition function with <em>k</em> = -0.5,<em> </em>for selecting the next measurement point at each step. As expected, the GP-BO quickly converged on the true minimum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FrWaSWUBqeCwKZGsSHxKww.jpeg" /><figcaption><strong>Figure 2.</strong> Black-box function optimization with vanilla GP-BO: the case of ‘good’ initialization. Figure by the authors.</figcaption></figure><p>Now, let’s start with a ‘bad’ initialization where the initialized points fall into the region around one of the local minima. Due to this bad initialization, the GP-BO gets stuck in a local minimum and is unable to converge on the true minimum. We note that in the real experiments, one does not usually have the luxury of restarting measurements using different initializations, and therefore must be equipped to deal with bad initializations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2gEzfODXkKVWnfE7EUPBw.jpeg" /><figcaption><strong>Figure 3.</strong> Black-box function optimization with vanilla GP-BO: the case of ‘bad’ initialization.</figcaption></figure><p>One way to look at the example above is that we got stuck in a local minimum because our algorithm did not “know” about the potential existence of a different minimum. But if we do know that there may be more minima (one of which could be the true/global one), then this prior knowledge can be incorporated into the <em>s</em>GP model.</p><p>Specifically, let’s define a structured probabilistic model as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*91r9LzeBDQKH6aXpXLjFFQ.png" /></figure><p>where <em>y</em>₀ ~ <em>Uniform</em>(-10, 10), <em>A</em>ₙ ~ <em>LogNormal</em>(0, 1), <em>w</em>ₙ ~ <em>HalfNormal</em>(0.1), and <em>x</em>ₙ⁰ ~ <em>Uniform</em>(0, 1) are the priors over the model parameters. This model simply tells us that there are two minima in our data but does not assume to have any knowledge about their relative depth and width, nor does it contain information about how far apart they are. We then substitute the constant prior mean function <em>m</em> in GP with the probabilistic model defined in Eq (3) and run the BO for the ‘bad’ initialization the same way as before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ozBVmzKI5BjdkjfNseAwdg.jpeg" /><figcaption><strong>Figure 4.</strong> Optimization with <em>s</em>GP-BO in the case of ‘bad’ initialization. Thanks to the partial prior knowledge about the system (that it has more than one minimum), the optimization algorithm is able to pull itself away from a local minimum and converge on the true/global minimum. Figure by the authors.</figcaption></figure><p>We can see that the optimization algorithm equipped with some knowledge of the expected system’s behavior was able to pull itself away from a local minimum and converge onto the global one. We have performed a systematic comparison between GP-BO and <em>s</em>GP-BO for several dozens of different random initializations of the seed points and in the presence of noise and found a superior performance of the <em>s</em>GP-BO in nearly all cases [11].</p><p>To understand the superior performance of the sGP-BO, we can compare the acquisition functions for GP-BO and <em>s</em>GP-BO at different steps of the optimization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNdQ0gRgnTt-vgaq6_wI3g.jpeg" /><figcaption><strong>Figure 5. </strong>Acquisition function of the vanilla GP-BO (top row) and <em>s</em>GP-BO (bottom row) at the 1, 3, 5, 7, and 9th steps. Figure by the authors.</figcaption></figure><p>Clearly, the vanilla GP-BO gets quickly locked in a local minimum with its acquisition function remaining largely unchanged (top row in Figure 5) as the algorithm ‘assumes’ it already found the true/global minimum. On the other hand, the acquisition function in the <em>s</em>GP-BO (bottom row in figure 5) displays a structure with multiple minima early on, which helps the algorithm to climb out of the local minimum and to converge on the true minimum at the later steps of the process even despite a very bad initialization. The evolution of the acquisition function in the bottom row of Figure 5 is truly remarkable in the sense that the algorithm is looking for a second minimum as if driven by intuition. And in some sense, it is— the prior knowledge we incorporated in the form of GP’s mean function in Eq (3) postulates that there is a second minimum somewhere — and the acquisition function highlights where this second minimum is most likely to be.</p><p>But what if this “prior knowledge” is only partially correct? As noted earlier, the advantage of <em>s</em>GP-BO compared to standalone probabilistic models is that the flexibility of the GP kernel allows us to use imprecise and sometimes even ‘incorrect’ functional forms of the models. We illustrate this using a structured probabilistic model of the form <em>m</em> = <em>A</em>e<em>ᵃˣ</em>sin(<em>bx</em>), with (log)normal priors on its parameters, for BO as a standalone model and as a part of <em>s</em>GP. We note that while this is clearly not the right model for describing the Forrester function, it does nevertheless capture some trends in data such as the presence of a global minimum and multiple local minima.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YF-azJdsWfvAxR37wC2t9A.jpeg" /><figcaption><strong>Figure 6. </strong>Results of BO with a standalone probabilistic model (left) and results of sGP-BO augmented with the exact same model (right). Figure by the authors.</figcaption></figure><p>The BO with a standalone probabilistic model (Figure 6, left) was not able to converge on the global minimum. The inference per se is too rigid and fails if the reality does not fit into the chosen model framework. It also could not produce a satisfactory reconstruction of the objective function even around the measured points and its uncertainty estimates do not appear to be particularly meaningful. On the other hand, the <em>s</em>GP-BO with the same probabilistic model as a part of the GP, easily identified the true minimum (Fig. 6, right). It also performed a good reconstruction of the underlying function around the measured regions and provided meaningful uncertainty estimates outside those regions, which could be used to select the next measurement points for a full recovery of the objective function (if necessary).</p><p><strong>Structured GP for actively learning discontinuous functions</strong></p><p>As our second example, we show how <em>s</em>GP can be used to reconstruct a discontinuous function from sparse and noisy observations. We note that the presence of discontinuities is common in the physics of phase transitions where one typically wants to reconstruct the behavior of the property of interest close to the transition point as well as in two phases before and after the transition. At the same time, the standard GP is not equipped to work with such discontinuities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6lCHBRc-iKM9lDHplUoFgA.jpeg" /><figcaption><strong>Figure 7.</strong> (a) Noisy observations of a discontinuous function, (b) Vanilla GP-based reconstruction of the underlying piecewise function, (c) <em>s</em>GP-based reconstruction with a ‘correct’ model of system’s behavior, (d) sGP-based reconstruction with a partially correct model. The uncertainty in reconstruction is defined by the dispersion in sampled predictions. Figure by the authors.</figcaption></figure><p>Figure 7a shows observations generated by the piecewise function of the form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*kzk7hs40uNto8yii7aBAbg.png" /></figure><p>Our goal is to reconstruct the underlying function from these noisy data points. First, we try vanilla GP (Figure 7b). It doesn’t perform well, which should not be very surprising since the standard GP is not equipped to deal with discontinuities. Intuitively, it can be understood by the contradictory requirements the discontinuity brings to the kernel function — the kernel with a large length scale cannot describe discontinuity, whereas small length scales necessitate multiple measurements to discover function behavior everywhere. Note that simple GP also extrapolates poorly outside the measurement interval (albeit in this case multiple strategies to address this issue are available).</p><p>Next, we try the <em>s</em>GP augmented by two different probabilistic models. The first <em>s</em>GP is augmented by a piecewise probabilistic function that has a general power-law form of <em>axᵇ</em> for <em>x</em> &lt; <em>xₜ</em> and <em>cxᵈ </em>for <em>x</em> ≥ <em>xₜ</em>, with a uniform prior on <em>xₜ</em> and log-normal priors on the other parameters. It shows a good overall reconstruction (Figure 7c) except for the transition region where we do not have enough observations. However, this region is also characterized by very large uncertainty (variation in the sampled predictions), suggesting that one may want to perform extra measurements in that area. It is also remarkable to examine the behavior of sampled predictions in this case — essentially, they differ in estimation on where the switch point is located. Again, this comports to the scientist&#39;s decision-making logic— if we expect the phase transition and are confident in the functional behavior of measured response before and after the transition, the only remaining uncertainty is the transition point!</p><p>The second <em>s</em>GP is augmented by a piecewise probabilistic function equal to <em>ax</em> for <em>x</em> &lt; <em>xₜ</em> and <em>bx</em> for <em>x</em> ≥ <em>xₜ</em>, with a uniform prior on <em>xₜ</em> and log-normal priors on the <em>a</em> and <em>b</em>. Note that this model is only partially correct: it has a transition point but assumes linear (instead of power-law) behavior before and after the transition. As a result, the reconstruction quality (Figure 7d) is lower, even though it is still somewhat better than for vanilla GP. Note that in this case the maximal uncertainty is associated with behavior before the transition (we do not expect the power-law behavior).</p><p>The uncertainties in the model predictions can be used to guide measurements to obtain a more accurate reconstruction of the underlying function. The procedure is the same as in the Bayesian optimization, except that we use the model’s uncertainty instead of the acquisition function to predict the next measurement point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GaWrrZC9U8kNAdftQhmizw.jpeg" /><figcaption><strong>Figure 8.</strong> The results of active learning with (a) vanilla GP, (b) <em>s</em>GP augmented by a ‘correct’ model of expected system’s behavior, (c) <em>s</em>GP augmented by a partially correct model of expected system’s behavior. Figure by the authors.</figcaption></figure><p>We can see that both <em>s</em>GP models quickly focused on the transition region before exploring other parts of the parameter ‘space’ (Figure 8b, c). As a result, we were able to improve dramatically the quality of the reconstruction. On the other hand, the uncertainty-guided exploration with vanilla GP still failed to reconstruct the transition region (Figure 8a). Hence, we see again that even <em>s</em>GP with a partially correct model of the expected system’s behavior can outperform the standard GP approach.</p><p>In summary, the augmentation of the Gaussian process with a (fully Bayesian) probabilistic model of the expected system’s behavior allows for more efficient optimization and active learning of a system’s properties. Note that even for incorrect or partially correct models the active learning algorithm will eventually arrive at the right answer — but at the cost of a larger number of experimental steps. Check our preprint for more details, including the application of this concept to physical models [11]. Please also check out our <a href="https://github.com/ziatdinovmax/gpax">gpax</a> software package for applying this and other GP tools to scientific data analysis. If you want to learn more about the Scanning Probe Microscopy, you are welcome to the channel M*N: Microscopy, Machine Learning, Materials.</p><p>Finally, in the scientific world, we acknowledge our research sponsor. This effort was performed and supported at Oak Ridge National Laboratory’s Center for Nanophase Materials Sciences (CNMS), a U.S. Department of Energy, Office of Science User Facility. You can take a virtual walk through it using <a href="https://my.matterport.com/show/?m=MT819FqAwbT">this link</a> and please let us know if you want to know more.</p><p>The executable Google Colab notebook is available <a href="https://colab.research.google.com/github/ziatdinovmax/notebooks_for_medium/blob/main/sGP_for_medium.ipynb">here</a>.</p><p><strong>References:</strong></p><p>1. Balke, N.; Jesse, S.; Morozovska, A. N.; Eliseev, E.; Chung, D. W.; Kim, Y.; Adamczyk, L.; Garcia, R. E.; Dudney, N.; Kalinin, S. V., Nanoscale mapping of ion diffusion in a lithium-ion battery cathode. <em>Nat. Nanotechnol. </em><strong>2010,</strong> <em>5</em> (10), 749–754.</p><p>2. Kumar, A.; Ciucci, F.; Morozovska, A. N.; Kalinin, S. V.; Jesse, S., Measuring oxygen reduction/evolution reactions on the nanoscale. <em>Nat. Chem. </em><strong>2011,</strong> <em>3</em> (9), 707–713.</p><p>3. Yang, S. M.; Morozovska, A. N.; Kumar, R.; Eliseev, E. A.; Cao, Y.; Mazet, L.; Balke, N.; Jesse, S.; Vasudevan, R. K.; Dubourdieu, C.; Kalinin, S. V., Mixed electrochemical-ferroelectric states in nanoscale ferroelectrics. <em>Nature Physics </em><strong>2017,</strong> <em>13</em> (8), 812–818.</p><p>4. Martin, O., <em>Bayesian Analysis with Python: Introduction to statistical modeling and probabilistic programming using PyMC3 and ArviZ, 2nd Edition</em>. Packt Publishing: 2018.</p><p>5. Lambert, B., <em>A Student’s Guide to Bayesian Statistics</em>. SAGE Publications Ltd; 1 edition: 2018.</p><p>6. Kruschke, J., <em>Doing Bayesian Data Analysis: A Tutorial with R, JAGS, and Stan</em>. Academic Press; 2 edition: 2014.</p><p>7. Nelson, C. T.; Vasudevan, R. K.; Zhang, X. H.; Ziatdinov, M.; Eliseev, E. A.; Takeuchi, I.; Morozovska, A. N.; Kalinin, S. V., Exploring physics of ferroelectric domain walls via Bayesian analysis of atomically resolved STEM data. <em>Nat. Commun. </em><strong>2020,</strong> <em>11</em> (1), 12.</p><p>8. Borisevich, A. Y.; Morozovska, A. N.; Kim, Y. M.; Leonard, D.; Oxley, M. P.; Biegalski, M. D.; Eliseev, E. A.; Kalinin, S. V., Exploring Mesoscopic Physics of Vacancy-Ordered Systems through Atomic Scale Observations of Topological Defects. <em>Phys. Rev. Lett. </em><strong>2012,</strong> <em>109</em> (6).</p><p>9. Li, Q.; Nelson, C. T.; Hsu, S. L.; Damodaran, A. R.; Li, L. L.; Yadav, A. K.; McCarter, M.; Martin, L. W.; Ramesh, R.; Kalinin, S. V., Quantification of flexoelectricity in PbTiO3/SrTiO3 superlattice polar vortices using machine learning and phase-field modeling. <em>Nat. Commun. </em><strong>2017,</strong> <em>8</em>.</p><p>10. Kalinin, S. V.; Oxley, M. P.; Valleti, M.; Zhang, J.; Hermann, R. P.; Zheng, H.; Zhang, W.; Eres, G.; Vasudevan, R. K.; Ziatdinov, M., Deep Bayesian local crystallography. <em>npj Computational Materials </em><strong>2021,</strong> <em>7</em> (1), 181.</p><p>11. Ziatdinov, M. A.; Ghosh, A.; Kalinin, S. V., Physics makes the difference: Bayesian optimization and active learning via augmented Gaussian process. <em>arXiv:2108.10280 </em><strong>2021</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4659b7e924a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/unknown-knowns-bayesian-inference-and-structured-gaussian-processes-why-domain-scientists-know-4659b7e924a4">Unknown Knowns, Bayesian Inference, and structured Gaussian Processes</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning Meets Gaussian Process: How Deep Kernel Learning Enables Autonomous Microscopy]]></title>
            <link>https://medium.com/data-science/deep-learning-meets-gaussian-process-how-deep-kernel-learning-enables-autonomous-microscopy-58106574cfeb?source=rss-eb4c5879edd------2</link>
            <guid isPermaLink="false">https://medium.com/p/58106574cfeb</guid>
            <category><![CDATA[bayesian-optimization]]></category>
            <category><![CDATA[gaussian-process]]></category>
            <category><![CDATA[active-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Maxim Ziatdinov]]></dc:creator>
            <pubDate>Tue, 02 Nov 2021 14:02:31 GMT</pubDate>
            <atom:updated>2021-11-03T13:46:50.948Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Maxim Ziatdinov¹ ² &amp; Sergei V. Kalinin¹</em></p><p><em>¹ Center for Nanophase Materials Sciences and ² Computational Sciences and Engineering Division, Oak Ridge National Laboratory, Oak Ridge, TN 37831, United States</em></p><p>For many scientists and engineers, the road towards their profession started from microscopy. Under a simple optical microscope or a magnifying glass, the sand from the nearby beach starts to look like a mountain country containing skeletons of diatoms and snails and pieces of colorful minerals. The droplet of water from the puddle reveals curious (and sometimes disturbing) microscopic denizens. With modern phones, the Google Lens can help identify their class and genus. The dried salt solution will show rainbow-colored crystals. In a more professional setting, the bespoke (and much more expensive) electron and scanning probe microscopes reveal micron and nanometer-scale structures of the material, going all the way to visualize atomic patterns forming the materials and molecules laying on their surfaces. The figure below shows the golden orb spider imaged by the second author and the “buckyball” molecules on the surface imaged by the first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wV7P-Yif4YSs8PNPgllr3w.jpeg" /><figcaption>Figure 1. (Left) Golden orb spider. (Right) Sumanene (‘buckyball’) molecules on gold surface. Figures by the authors.</figcaption></figure><p>Yet the modern microscopes allow not only to image materials and their surfaces but also to perform much more detailed studies of their properties. In scanning tunneling microscopy (STM), the operator can choose potentially interesting regions and perform tunneling spectroscopy, i.e., measure the current-voltage curves. Controlled by quantum tunneling, this curve will contain information about the local density of states, superconductivity, charge density waves, and other exciting phenomena on the surface [1–2]. In electron microscopy, the technique of choice is electron energy loss spectroscopy [3]. Here, measuring the energy loss of electrons passing through the solid reveals the chemical structure of individual atoms and, with recent advances in monochromated instruments, allowed probing quasiparticles such as electrons and plasmons in solids [4–5]. The particularly broad gamut of the possible spectroscopic modes emerged in the scanning probe microscopies, allowing researchers to probe local mechanical properties, conductivity, and ferroelectric polarization switching [6–7].</p><p>Unfortunately, the local functional measurements take a lot of time compared to imaging. For example, getting a simple STM image often takes about 5–10 minutes. Getting the dense array of spectroscopic curves over a dense spatial grid of points takes days, necessitating building ultrastable microscopes that will not drift appreciably over these times. The same considerations apply to electron microscopes, for which additional consideration is sample damage by the electron beam. Finally, many measurements are destructive and cannot be taken over the dense grid, for example, nanoindentation. These considerations severely limit the capabilities of these measurements and the insight they provide into the material’s structure and functionality. Much like proverbial Jon Snow, if we do not know where to measure, we measure everywhere hoping to capture the behaviors of interest during the <em>ex-situ</em> data analysis, hoping to identify the regions of interest. Can we do better with machine learning? (hint: we can, otherwise this blog post would not be written).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rK4B_xYD_dSUCxoN2EPVbA.jpeg" /><figcaption>Figure 2: The modern microscopes, such as the ultra-high vacuum scanning tunneling microscope shown on the left, allow exploring materials structure and functionalities on the nanoscale and atomic-scale levels. Shown on the right are the 2D topographic image for which we can perform spectroscopic measurements on the m x <em>n</em> grid (not shown) and differential tunneling conductance spectra recorded in two grid points. Figure by the authors.</figcaption></figure><p>In order to understand what it takes to make this work, we first consider the paradigmatic approach for active learning in experiments based on Gaussian Process (GP). In most general form, GP refers to the class of algorithms that attempt to reconstruct the function over certain (low dimensional) parameter space from a set of sparse measurements. In other words, given a set of observed data points (<em>x</em>ᵢ, <em>y</em>ᵢ) and assuming normally distributed observation noise <em>ϵ, </em>the GP aims to reconstruct the function <em>f</em>(<em>x</em>) such as <em>y</em>ᵢ= <em>f</em>(<em>x</em>ᵢ) + <em>ϵ</em>ᵢ, with <em>f</em> ~ <em>MultivariateNormal</em>(0; <em>K</em>(<em>x</em>ᵢ, <em>x</em>ⱼ)). The functional form of the kernel <em>K </em>is chosen prior to the experiment, and its hyperparameters are inferred from the observations using either Markov chain Monte Carlo methods or stochastic variational inference. You can read about the more rigorous definition of GP <a href="http://www.gaussianprocess.org/gpml/chapters/">here</a>. Please see also <a href="https://ziatdinovmax.medium.com/gaussian-process-first-step-towards-active-learning-in-physics-239a8b260579">our previous Medium post on GPs</a>. Our group has applied GP to a number of imaging problems including <a href="https://doi.org/10.1038/s41524-020-0289-6">reconstruction of sparse hyperspectral data</a>, <a href="https://aip.scitation.org/doi/10.1063/5.0011917">hysteresis loop engineering in ferroelectrics</a>, and efficient <a href="https://aip.scitation.org/doi/10.1063/5.0021762">exploration of the parameter space for lattice Hamiltonians</a>, and the full codes are available through the <a href="https://github.com/ziatdinovmax/GPim">GPim package</a>.</p><p>The unique aspect of GP is that the function is reconstructed along with the associated uncertainty Σ(<em>x</em>). This aspect allows extending GP towards the active learning methods. Suppose we want to learn the value of the function over parameter space in the most effective way by sequentially selecting points to perform the measurements. In that case, the region with the maximal uncertainty represents the optimum point for a query. In this manner, a GP-driven automated experiment seeks to reduce the uncertainty about function in the most expeditious manner.</p><p>It should be noted the GP can be further extended to target specific behavior. In this case, if we have prior knowledge of what values of the function we are looking for, we can combine the expectation and uncertainty in a single acquisition function. The maximum (or minimum) of the acquisition function is then used for the navigation of the parameter space. This approach combining the exploration and exploitation of the parameter space is generally referred to as Bayesian Optimization (BO).</p><p>Then the question becomes whether GP/BO can be utilized to enable automated experiments in microscopy. It turns out that it is possible in <a href="https://doi.org/10.1021/acsnano.0c10239">the case of simple imaging or spectroscopy</a>, but the total gain is relatively small. Indeed, images typically contain multiple features at many different length scales — from large to small. A priori, we do not know what these features are. Correspondingly, GP-based algorithms that try to navigate image space based on single point measurement and discover the associated kernel function get stumbled. Indeed, for known images, the kernel function is roughly equivalent to the correlation function, and this is not a very effective way to represent the image. In principle, one can work with reduced representation of the image achieved through applying either standard multivariate decomposition (PCA, NMF) or autoencoder techniques to image patches. However, there is no guarantee that these reduced representations will be physically meaningful, and they can be frequently dominated by instrumental factors such as drift (in many cases, a domain expert has to separate physical variables from the unphysical ones, which defies the whole point of the automated experiment). Furthermore, decomposition requires the patches to be available in advance — belying the concept of discovery.</p><p>The GP-produced gain is further reduced as the microscope’s electronics and mechanics can start to fail if forced to move the probe along the very complex paths. On top of that, the GP usually does not work well to predict complex patterns. All in all, it looks like the GP it is insufficient for automated experiments in microscopy.</p><p>Enter the deep kernel learning. To understand how it works, let’s recap what a human operator would do if they looked at the image. Human eyes immediately register the objects of interest. For example, in the STM image of the superconductor in Figure 2, we can instantly notice the regions with bright spots. A qualified human operator would immediately identify these regions as potentially hosting a localized electronic state(s) although its properties will probably depend on the surrounding. Similarly, one can notice multiple regions with stripy contrast which could be indicative of surface reconstruction. There are many of them and it is intuitively obvious that they should have somewhat similar behaviors. So perhaps it is sufficient to perform a spectroscopic measurement in several of them and assume that the observed behaviors are representative. However, there are also regions where a small depression and/or protrusions are embedded into the stripy domains and those regions may contain some additional interesting insights about the physics of this system. The question then becomes whether we can utilize the information contained in the structural images to guide the spectroscopic measurements in an autonomous fashion.</p><p>Deep kernel learning (DKL), originally <a href="https://arxiv.org/abs/1511.02222">introduced</a> by Andrew Gordon Wilson, can be understood as a hybrid of classical deep neural network (DNN) and GP, as shown in Figure 3. Here, the DNN part serves as a feature extractor that allows reducing the complex high-dimensional features to low-dimensional descriptors on which a standard GP kernel operates. The parameters of DNN and of GP kernel are optimized jointly by performing a gradient ascent on marginal log-likelihood. The DKL output on the new inputs is the expected value and associated uncertainty for the property (or properties, if we are interested in vector-valued functions) of interest. Let’s see how we can harness DKL to run experiments on the electron or scanning probe microscopes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zs-1c1o2AyGHUPoWNJ6IaQ.jpeg" /><figcaption>Figure 3. Deep kernel learning: training and prediction steps. The training inputs are (structural) image patches and targets are scalar values of the physical functionality of interest (usually derived from spectroscopic curves measured in those patches). At the prediction step, the trained DKL model is used to obtain the expected value of the functionality of interest and corresponding uncertainty for the new set of structural image patches (for which the functionality has not yet been measured experimentally). Figure by the authors.</figcaption></figure><p>We are going to show two basic examples where DKL is used to map parts of a material’s structure that maximize a particular physical functionality. To achieve this, the DKL must learn the correlative structure-property relationship(s) in the system. Implementation-wise, the DKL training inputs are small patches of a structural image, and training targets are scalar values associated with some physical functionality derived from spectra measured in the centers of patches (the DKL can also work with vector-valued targets and can even predict the entire spectra, but these will be discussed in a separate post). The goal is to use easy-to-acquire structural data to guide spectroscopic measurements that are typically much more tedious. Hence, the DKL-based automated experiment begins with collecting a structural image, which is split into a set of small patches (one patch per image pixel), followed by the acquisition of several spectroscopic curves in random locations of the image. These sparse observations are used to train a DKL model. Then, a trained DKL model is used to predict a property of interest in every coordinate of the structural image (or, more specifically, for every image patch centered at that coordinate) for which there is no measured spectrum. The predicted mean property value and associated uncertainty are used to derive an acquisition function to sample the next measurement point(s). Once a new measurement is performed, the training data is updated, and the whole process is repeated.</p><p>First, let’s use the publicly available <a href="https://zenodo.org/record/4433093#.YYDHPZ7MKuU">dataset</a> obtained on plasmonic nanocubes. Here our structural data come from a scanning transmission electron microscopy image. The functionality of interest is derived from the electron energy loss spectra measured over the same area and, in this particular example, is simply the intensity of the edge plasmon peak. We run DKL for 100 iterations which are about 3% of the total grid points. At each iteration, we select the next measurement point using a simple Thompson sampler. Since we already know the ground truth, we can overlay the sampled points with the ground truth map. One can see that we were able to identify regions within the structural image where the functionality of interest is maximized by measuring only a small fraction of a grid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_PvE-eNSZG0HWDLjCLSqA.jpeg" /><figcaption>Figure 4. DKL-based search for regions of the nano-plasmonic array that host edge plasmons. Figure by the authors.</figcaption></figure><p>Now, let’s see how this approach works for identifying sample regions that maximize hysteresis loop area in piezoresponse force microscopy. Our DKL setup is almost the same as in the previous experiment, except that now, at each step we sample a batch of 4 points instead of just a single point. Again, as one can see from Figure 5 below, we were able to quickly localize the behavior of interest with a very small number of measurements (~5% of the entire grid).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gc-7Y0IHbEpCH6J8OIXJBg.jpeg" /><figcaption>Figure 5. DKL-based search for regions that maximize hysteresis loop area. Figure by the authors.</figcaption></figure><p>Overall, this approach uses structural information to guide spectroscopic (functional) measurements by actively learning the structure-property relationships in the system. Importantly, we can use almost any physical search criteria from the simple ones used in this blog post to much more complicated ones. In this manner, we combine the power of correlative machine learning to establish relationships in the multidimensional data set and derive corresponding uncertainties, and domain expertise encoded in the choice of the search criteria.</p><p>Please check out our <a href="https://github.com/pycroscopy/atomai">AtomAI</a> software package for applying this and other deep/machine learning tools to scientific imaging. If you want to learn more about the Scanning Probe Microscopy, welcome to channel M*N: Microscopy, Machine Learning, Materials. Finally, in the scientific world, we acknowledge the sponsor that funded this research. This effort was performed and supported at Oak Ridge National Laboratory’s Center for Nanophase Materials Sciences (CNMS), a U.S. Department of Energy, Office of Science User Facility. You can take a virtual walk through it using <a href="https://my.matterport.com/show/?m=MT819FqAwbT">this link</a> and tell us if you want to know more.</p><p>The executable Google Colab notebook for one of the examples is available <a href="https://colab.research.google.com/github/ziatdinovmax/notebooks_for_medium/blob/main/DKL_for_medium.ipynb">here</a>.</p><h4><strong>References:</strong></h4><p>1. Roushan, P.; Seo, J.; Parker, C. V.; Hor, Y. S.; Hsieh, D.; Qian, D.; Richardella, A.; Hasan, M. Z.; Cava, R. J.; Yazdani, A., Topological surface states protected from backscattering by chiral spin texture. <em>Nature </em><strong>2009,</strong> <em>460</em> (7259), 1106-U64.</p><p>2. Pan, S. H.; Hudson, E. W.; Lang, K. M.; Eisaki, H.; Uchida, S.; Davis, J. C., Imaging the effects of individual zinc impurity atoms on superconductivity in Bi2Sr2CaCu2O8+delta. <em>Nature </em><strong>2000,</strong> <em>403</em> (6771), 746–750.</p><p>3. Pennycook, S. J.; Varela, M.; Lupini, A. R.; Oxley, M. P.; Chisholm, M. F., Atomic-resolution spectroscopic imaging: past, present and future. <em>J. Electron Microsc. </em><strong>2009,</strong> <em>58</em> (3), 87–97.</p><p>4. Kapetanakis, M. D.; Zhou, W.; Oxley, M. P.; Lee, J.; Prange, M. P.; Pennycook, S. J.; Idrobo, J. C.; Pantelides, S. T., Low-loss electron energy loss spectroscopy: An atomic-resolution complement to optical spectroscopies and application to graphene. <em>Phys. Rev. B </em><strong>2015,</strong> <em>92</em> (12).</p><p>5. Hage, F. S.; Nicholls, R. J.; Yates, J. R.; McCulloch, D. G.; Lovejoy, T. C.; Dellby, N.; Krivanek, O. L.; Refson, K.; Ramasse, Q. M., Nanoscale momentum-resolved vibrational spectroscopy. <em>Sci. Adv. </em><strong>2018,</strong> <em>4</em> (6), 6.</p><p>6. Kalinin, S. V.; Strelcov, E.; Belianinov, A.; Somnath, S.; Vasudevan, R. K.; Lingerfelt, E. J.; Archibald, R. K.; Chen, C. M.; Proksch, R.; Laanait, N.; Jesse, S., Big, Deep, and Smart Data in Scanning Probe Microscopy. <em>ACS Nano </em><strong>2016,</strong> <em>10</em> (10), 9068–9086.</p><p>7. Vasudevan, R. K.; Jesse, S.; Kim, Y.; Kumar, A.; Kalinin, S. V., Spectroscopic imaging in piezoresponse force microscopy: New opportunities for studying polarization dynamics in ferroelectrics and multiferroics. <em>MRS Commun. </em><strong>2012,</strong> <em>2</em> (3), 61–73.</p><p>8. Kalinin, S. V.; Valleti, M.; Vasudevan, R. K.; Ziatdinov, M., Exploration of lattice Hamiltonians for functional and structural discovery via Gaussian process-based exploration-exploitation. <em>J. Appl. Phys. </em><strong>2020,</strong> <em>128</em> (16), 11.</p><p>9. Kalinin, S. V.; Ziatdinov, M.; Vasudevan, R. K., Guided search for desired functional responses via Bayesian optimization of generative model: Hysteresis loop shape engineering in ferroelectrics. <em>J. Appl. Phys. </em><strong>2020,</strong> <em>128</em> (2), 8.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58106574cfeb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deep-learning-meets-gaussian-process-how-deep-kernel-learning-enables-autonomous-microscopy-58106574cfeb">Deep Learning Meets Gaussian Process: How Deep Kernel Learning Enables Autonomous Microscopy</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gaussian Process: First Step Towards Active Learning in Physics]]></title>
            <link>https://medium.com/data-science/gaussian-process-first-step-towards-active-learning-in-physics-239a8b260579?source=rss-eb4c5879edd------2</link>
            <guid isPermaLink="false">https://medium.com/p/239a8b260579</guid>
            <category><![CDATA[bayesian-inference]]></category>
            <category><![CDATA[bayesian-optimization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gaussian-process]]></category>
            <dc:creator><![CDATA[Maxim Ziatdinov]]></dc:creator>
            <pubDate>Mon, 01 Nov 2021 22:02:47 GMT</pubDate>
            <atom:updated>2022-04-24T17:16:49.326Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Maxim Ziatdinov¹ ² &amp; Sergei V. Kalinin¹</em></p><p><em>¹ Center for Nanophase Materials Sciences and ² Computational Sciences and Engineering Division, Oak Ridge National Laboratory, Oak Ridge, TN 37831, United States</em></p><p>Despite the extreme disparity in terms of objects and study methods, some tasks are common across multiple scientific fields. One of such tasks is an interpolation. Imagine having the measurements of some property of interest, such as temperature (if you are a meteorologist) or soil composition, or presence of useful ores (if you are a geologist) over some area. It would be extremely useful to interpolate these numbers between the (usually small) number of measurement points to obtain 2D maps amenable to the human eye. This can be approached using multiple methods including splines, kernel density approximations, neural network fits, and many others. However, when doing so, the second natural question is the uncertainty of these interpolated values, or to which extent they are trustable. The uncertainties are clearly minimal at the locations where the measurements were taken but will grow when moving away from the measurement points. Finally, the third and perhaps most interesting question is whether we can use the knowledge of the interpolated function and its uncertainty to guide our search strategy. In other words, given the measurements of property of interest in several locations, can we choose the next point for measurements — based on anticipated reward or probability to get one. All these problems can be addressed in a principled manner using Gaussian Process (GP) and GP-based Bayesian Optimization.</p><p>Similar problems, albeit defined over different parameter spaces, emerge in multiple other scientific domains. Search for materials with interesting and useful properties often implies the exploration of binary-, ternary-, and quaternary phase diagrams, i.e., 1D, 2D, and 3D compositional spaces. Tuning the microscope for optimal resolution implies tuning of several control parameters such as tip bias and tunneling current (for Scanning Tunneling Microscopy) or driving bias and setpoint (for Piezoresponse Force Microscopy). Even in theory/simulations, we often want to explore the phase diagram of a particular Hamiltonian by tuning a small number of exchange parameters. Clearly, all these problems can be solved via a grid search, that is, evaluating our system or running a microscope, or synthesizing a material sample for each combination of parameters. Equally obvious, this is extremely impractical. For example, for materials synthesis, if we want to explore compositions every 1% of the concentration, we will need 100 samples for a binary system, 10⁴ samples for a ternary system, and 10⁶ samples for a quaternary one. That will take a while!</p><p>In physical sciences, these problems are typically addressed using the combination of intuition, approximate methods, and experiments/simulations. For example, to define the phase diagram of Ising Hamiltonian as a function of temperature, the approximate methods can be used to get the system behaviors for very large and very low temperatures. Similarly, the universality class of the system and its behavior in the vicinity of the phase transition can be analyzed. The remaining task is then finding relevant transition temperature and critical exponents describing the system’s behavior in its vicinity. In experimental sciences (e.g., tuning a microscope), there are usually well-understood expectations of how the system behaves when a parameter changes. Finally, materials scientists use the combination of thermodynamic theory and measurements to explore the phase diagram within a small number of iterations. However, these approaches are very heterogeneous and domain-specific. How would a data scientist do it?</p><p>An approach to address these problems is a Gaussian Process. The formal definition and discussion of this approach are available in a number of excellent open publications and textbooks, particularly by <a href="http://www.gaussianprocess.org/gpml/">Rasmussen and Williams</a>. Here, we would like to offer a slightly unusual approach to describe the GP, centered on how the experiments improve our understanding of the world and how this knowledge is encoded in formal mathematical structure.</p><p>Imagine having a scalar function (or property of interest) defined over low-dimensional parameter space. This can be temperature over globe, materials hardness or magnetism over ternary phase diagram, or contrast over microscope image. Prior to any measurement (or calculation), we have no information on the possible values of the function — i.e., everything is possible. Upon measuring the values of the function at several locations, we, strictly speaking, know only the values in these locations and nothing else. However, it is not unreasonable to postulate that the values of the function we are interested in are somehow correlated across the parameter space. In physics, we often look for some specific functional form, either phenomenological or stipulated by fundamental physical laws. However, from the data science perspective, we postulate that the relationship between function values at the adjacent location is defined by a kernel function such as exp(-(<em>xᵢ</em>-<em>xⱼ</em>)²/2<em>l</em>²). The latter is known as Radial Basis Function and is one of the most common kernel functions in GP. The parameter <em>l</em> defines the characteristic lengthscale of the process and is usually inferred from data.</p><p>More formally, given the dataset <em>D</em>={<em>xᵢ</em>, <em>yᵢ</em>}, <em>i</em>=1, …, <em>N, </em>where <em>x</em> and <em>y</em> are input features and output targets, the Gaussian Process can be defined by the following probabilistic model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*KlfsUSx6x-KH1VGoeUwBZw.png" /></figure><p>where <em>MVN</em> is a multivariate normal distribution, <strong>m</strong> is a prior mean function (usually chosen to be some constant), <strong>K </strong>is our kernel function with (hyper)parameters <em>σ</em> and <em>l</em> for which we chose weakly-informative log-normal priors. We also assume there is normally distributed observation noise, <strong>ϵ</strong>~<em>Normal</em>(0, <em>s</em>²<strong>I</strong>), such that <strong>y</strong>ₙₒᵢₛᵧ<strong>=y + ϵ. </strong>Practically, we absorb it into the computation of kernel function.</p><p>Having set up the model and prior distributions, the next step is to obtain the predictive posterior for new/unseen data. Here, we get posterior samples for the GP model parameters using a Hamiltonian Monte Carlo (HMC) algorithm from NumPyro’s probabilistic programming library. We then sample from the multivariate normal posterior over the model outputs at the provided new input points Xₙₑᵥᵥ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M6GBFMgpacRmIxNudtPAWg.png" /></figure><p>where <strong><em>θ</em></strong><em>ⁱ</em> is a single HMC posterior sample containing kernel hyperparameters and model noise.</p><p>Let’s see how it works for a simple 1D function for which we get some sparse noisy observations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*DIBG3N10MfEmPAFiwa2LQQ.png" /><figcaption>Figure 1. Noisy observations of periodic function sin(10<em>x</em>). Figure by the authors.</figcaption></figure><p>We run the HMC for the model defined in Eq (1) given data observed in Figure 1 to obtain posterior samples for the model parameters. Then we compute posterior predictive distribution according to Eq (2) over the dense uniform grid of points between -1 and 1. The results are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*QqEINe1Ln_aVjRAurLgC4g.png" /><figcaption>Figure 2. The GP predictions sampled from multivariate normal posterior in Eq 2a. The center of the mass of the sampled means (Eq 2b) is also shown. Figure by the authors.</figcaption></figure><p>Note that a unique aspect of the GP compared to many other interpolation methods is that it provides information both on the expected function values, and the uncertainty for each predicted point. The latter is simply a variance (or standard deviation) in the sampled predictions. For the data in Figure 2, we will get a large uncertainty between -0.75 and -0.25 since there are no observations in that area. Note that the GP model still performed a pretty good job of predicting the mean function value over that region.</p><p>Before proceeding to how the uncertainty can be used to navigate a parameter space, let us quickly see what will happen if we change a kernel function. Specifically, we will replace our RBF kernel with a periodic kernel of the form exp(-2sin²(<em>π</em>(<em>xᵢ</em>-<em>xⱼ</em>)/<em>p</em>)/<em>l</em>²) with a uniform prior over the period <em>p </em>~ <em>Uniform</em>(0.1, 1.0). We then re-run the HMC and re-compute our posterior predictive distribution. The results for the periodic kernel are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*QaA3O1WKWdqTHjAByTb2tQ.png" /><figcaption>Figure 3. The GP prediction with the periodic kernel. Figure by the authors.</figcaption></figure><p>Clearly, the predictions are much better now (and the model is much more certain about them!). This suggests that the selection of the appropriate GP kernel can be guided by the physics of the problem.</p><p>The GP-predicted mean function value and the associated uncertainty can be used to derive the so-called acquisition function for the selection of the next measurement point in the parameter space. One of the commonly used acquisition functions is called upper confidence bound (UCB) and is essentially a linear combination of the predicted mean and uncertainty,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*uZoRSohQOWVIxj4o22w58w.png" /></figure><p>where <em>k</em> &lt; 0 for the minimization problems and <em>k</em> &gt; 0 for the maximization problems.</p><p>Below we show a simple 1D example of how the acquisition function works. Suppose we want to minimize some black-box function for which we have about one and half dozen of noisy observations (Figure 4). Without taking the uncertainty into account, our next measurement point would be at ~0.15, which appears to be the function’s minimum based on the available observations and GP reconstruction. However, there is a relatively high uncertainty between 0.4 and 0.6, as well as above ~0.65, so maybe there’s another, deeper minimum hiding there. The UCB acquisition function takes this uncertainty into account and outputs the next point to measure at ~0.5. We then perform measurements at that point, update our observations, and (if necessary) “re-train” our GP model to derive another acquisition function for getting the next measurement point. This balance (or trade-off) between exploiting the regions close to the already measured points and exploring the “unknown” is at the heart of Bayesian optimization. There are, of course, many other, more sophisticated, acquisition functions and we refer the interested readers to the <a href="https://www.cs.ox.ac.uk/people/nando.defreitas/publications/BayesOptLoop.pdf">review on Bayesian optimization by Nando de Freitas</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9igJ2r7jmiT7uMCrWO35hA.jpeg" /><figcaption>Figure 4. The GP prediction of the unknown objective function (left) and the derived UCB acquisition function (see Eq 3) for <em>k</em> = -2 (right). Figure by the authors.</figcaption></figure><p>To illustrate the Bayesian optimization process for a real physical system, we explore the phase diagram for the Ising model, as described in detail in our <a href="https://doi.org/10.1063/5.0021762">recent paper</a>. Here, we used GP-based Bayesian optimization with the UCB acquisition function for the effective exploration of the parameter space of the lattice Hamiltonian and mapping the regions where specific macroscopic functionalities are maximized. In Figure 5 below, we show, via individual snapshots, an example of discovering regions of the parameter space in the next-nearest-neighbor Ising model where the heat capacity is maximized. One can see that the algorithm quickly zeros-down on the regions of interest allowing discovery of areas with the highest heat capacity in an effective (compared to a regular grid search) manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FwG-cE5ABw_KMUrkJ_o2vQ.jpeg" /><figcaption>Figure 5. GP-based Bayesian optimization of heat capacity in the Ising model. Shown are all the points discovered by GP at steps 100, 200, 300, 400, and 600, as well as a full grid simulation (‘ground truth’). Figure by the authors.</figcaption></figure><p>To summarize, here we introduce the Gaussian Process and Bayesian Optimization methods and illustrate their implementation and application for a real physics problem. In addition to the analysis of the Ising model, the GP has been used to study the <a href="https://doi.org/10.1063/5.0011917">hysteresis loops in ferroelectrics</a>, <a href="https://doi.org/10.1021/acsenergylett.0c01749">explore the compositional spaces</a> of hybrid perovskites in automated synthesis, <a href="https://doi.org/10.1063/5.0013847">achieve super-resolution</a> in scanning probe and electron microscopy and spectroscopy, and even <a href="https://pubs.acs.org/doi/abs/10.1021/acsnano.0c10239">control operational microscope</a> exploring polarization dynamics in ferroelectric thin films.</p><p>Yet despite the power of GP, a simple implementation discussed here has a number of significant limitations. The first and obvious one is that the parameter space in which GP operates tends to be fairly low-dimensional, with optimal performance usually limited to &lt;6 D spaces. The second limitation is that the structure of correlations is defined by the kernel function and while a large number of kernel functions including anisotropic and periodic have been proposed, most of these are phenomenological in nature. Finally, it tends to be computationally intensive.</p><p>However, as in many cases, the basic GP approaches can be readily extended in other directions. For example, the combination of the deep neural networks and Gaussian process yields the family of <a href="https://arxiv.org/abs/1511.02222">deep kernel learning</a> methods that combine the expressivity of the deep learning and flexibility of GP. It is also possible to directly inject prior physical knowledge by substituting GP’s constant mean function with a probabilistic model of the expected system’s behavior. Stand by for future blog posts about DKL and sGP application in physical sciences!</p><p>Please also check out our <a href="https://github.com/ziatdinovmax/GPim">GPim</a> and <a href="https://github.com/ziatdinovmax/gpax">gpax</a> software packages for applying GPs to scientific data, with a focus on imaging and spectroscopy. Finally, in the scientific world, we acknowledge the sponsor that funded this research. This effort was performed and supported at Oak Ridge National Laboratory’s Center for Nanophase Materials Sciences (CNMS), a U.S. Department of Energy, Office of Science User Facility. You can take a virtual walk through it using <a href="https://my.matterport.com/show/?m=MT819FqAwbT">this link</a> and tell us if you want to know more.</p><p>The executable Google Colab notebook with basic GP examples discussed in the text is available <a href="https://colab.research.google.com/github/ziatdinovmax/notebooks_for_medium/blob/main/GP_for_medium.ipynb">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=239a8b260579" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/gaussian-process-first-step-towards-active-learning-in-physics-239a8b260579">Gaussian Process: First Step Towards Active Learning in Physics</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering the shifts with variational autoencoders]]></title>
            <link>https://medium.com/data-science/mastering-the-shifts-with-variational-autoencoders-ca609ec84f1?source=rss-eb4c5879edd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca609ec84f1</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[signal-processing]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[thoughts-and-theory]]></category>
            <dc:creator><![CDATA[Maxim Ziatdinov]]></dc:creator>
            <pubDate>Tue, 13 Apr 2021 00:25:10 GMT</pubDate>
            <atom:updated>2021-04-14T22:48:36.803Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/thoughts-and-theory">Thoughts and Theory</a></h4><h4>How variational autoencoders can be used to analyze one-dimensional signals</h4><p><em>Maxim Ziatdinov¹ ² &amp; Sergei V. Kalinin¹</em></p><p><em>¹ Center for Nanophase Materials Sciences and ² Computational Sciences and Engineering Division, Oak Ridge National Laboratory, Oak Ridge, TN 37831, United States</em></p><p>Data often comes in the form of one-dimensional signals. These can be the time series recording from a sensor or detector measuring the temperature, humidity, and wind velocity in meteorology, heart rate in an individual fitness tracker, or more sophisticated detection systems that are now becoming widespread due to the proliferation of the Internet of Things (IoT) devices and light edge computing such as Arduino, Raspberry Pi, and NVIDIA Jetson. Even without any specialized electronics, recent apps such as Arduino Science Journal give access to the pressure, magnetic field, and acceleration sensors on a cell phone, allowing for a multitude of home experimentation (“<em>How much does the pressure change if I walk up the stairs</em>?”, “<em>What is the acceleration pattern when I run or walk</em>?”).</p><p>In many of these applications, the signal has some characteristic aspects, whether it is heartbeat rhythm, walking gate, vibration pattern that contains information on fitness, health, and other characteristics that we may want to discover. If the time reference points for the signals are well known or the data is periodic, the analysis of such data is straightforward. However, the precise positioning of events and characteristic features is often unavailable and can be something we aim to discover jointly with their characteristic patterns.</p><p>Similar problems abound in scientific domains. A simple example can be the X-ray scattering data, where the peaks corresponding to the specific indices can shift with the molar volume of material in solid solutions. Another example can be mass-spectrometry data, where peaks can shift due to surface charging during data acquisitions, Raman spectra where peak shifts indicate strains in materials, and so on. In many cases, such data can be available over a large parameter space, e.g. position in hyperspectral imaging, concentration in combinatorial libraries assessment, or voltage in the active device characterization. The question is — can machine learning help us to process and understand these types of data in an unsupervised manner?</p><p>For one of the coauthors (S.V.K.) the interest in this area started with the introduction of the band excitation (BE) method in scanning probe microscopy (<a href="https://en.wikipedia.org/wiki/Scanning_probe_microscopy">SPM</a>). The variety of existing SPM methods are generally based on the interaction between the sharp (sometimes atomically-sharp) probe and the surface. The probe is positioned at the end of the cantilever with a laser beam bouncing off the backside. The small displacements of the probe result in the large shifts of a laser beam on the detector, allowing for the detection of the minute displacements. Practically, displacements as small as fractions of the nanometer can be detected. In terms of relevant forces, for spring constants of the order of ~1 N/m, the corresponding force will be on the order of interatomic forces. Hence the name Atomic Force Microscopy.</p><p>The late 90ies have seen a broad introduction of the dynamic SPM methods [1, 2]. In these, the cantilever is excited by an oscillatory signal applied either to the piezo element driving cantilever (intermittent contact topographic imaging, magnetic force microscopy), or cantilever directly (Kelvin Probe Force Microscopy and Electrostatic Force Microscopy). The microscope electronics detects either amplitude and phase of a signal at a single frequency (lock-in detection, LIA), or by tracing the changes of resonance frequency due to tip-surface interactions (phase-locked-loop, PLL). However, both LIA and PLL detect signals at a single frequency only, leaving the system physically underdetermined (i.e., simple harmonic oscillator has three parameters — amplitude, resonance frequency, and quality factor). The assumption of the constant driving force is only approximately correct in many SPM methods leading to spurious signal changes and lack of quantitative information and does not apply to many others.</p><p>The band excitation (BE) scanning probe microscopy has been developed to address this problem [3, 4]. In this method, the atomic force microscope detects the segment of the amplitude/phase-frequency resonance curve within a chosen frequency band in parallel (hence the name). The 2D SPM image hence becomes 3D, where each spatial pixel now contains the full frequency-dependent response curve. The fit by a simple harmonic oscillator equation then allows reconstructing the amplitude, resonance frequency, and quality factor maps from which materials properties can be extracted. However, the peak shape can (and more often than not does) differ from the SHO shape. This peak shape information is ignored in the analysis. As one possible strategy, we can utilize prior physical knowledge in the form of the functional form of responses, etc., in least-square fits or Bayesian inference [5]. However, this strategy is often time-consuming, and in many cases, analytical solutions are unavailable.</p><p>Unsupervised machine learning to the rescue! The applications of the principal component analysis (PCA) to the BE data in 2007–2008 [6] have started the foray into ML methods for our group that still continues. However, ironically, the first application of the PCA to the band excitation data has shown that meaningful results can be obtained only in a small number of cases where peak shifts within the image are small and the noise level is relatively high. Then a small number of PCA components is sufficient to represent the data, and they can even be identified with specific physical mechanisms. For data sets where the resonance frequency changes a lot, or noise levels are low, PCA yields a large number of components [7] the physical meaning (or even usefulness for exploratory data analysis) is unclear. The same fate befalls other linear decomposition methods such as non-negative matrix factorization, Bayesian Linear Unmixing [8], and others [9].</p><p>However, now we can clearly formulate our expectations for the “ideal” unsupervised ML method for such data sets. It should be able to find the descriptors or disentangle the representations of the 1D data sets, ignoring (or separating) relative positions of the peaks. And this is exactly what shift variational autoencoders (shift-VAE) are designed to accomplish.</p><p>In shift-VAE, we designate one of the latent variables to capture the information about the relative position of spectra, whereas the rest of the latent variables “look” for other (than position) factors of variation, such as height, width, inter-peak distance (if more than one peak), etc. Let’s call this special latent variable an “offset latent variable”. We start by creating a 1D <em>x</em>-coordinate grid whose length is equal to the number of points in the spectra. Our encoder maps the inputs (spectra) into the offset latent variable and two (or more) conventional latent variables. Assuming that shifts in position are normally distributed, the offset latent vector is sampled from a unit Gaussian distribution. The sampled values are used to shift our coordinate grid, which is then concatenated with the conventional latent variables and passed to the VAE’s decoder to enforce a geometric consistency between the shifted spectra.</p><p>Now, let’s experiment with the shift VAE and compare it to the PCA/NMF and conventional VAE. As a first step, we can generate a synthetic data set formed by Gaussians (or linear combinations of Gaussians and Lorentzians with the same center).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QVSB7qXkmXx6N61I" /></figure><p>Here, the centers and width of the Gaussians are stored as the ground truth data, whereas the curves themselves form the feature set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/0*Mn_hBnmKpEkL_AgM" /><figcaption><em>64 typical curves from the synthetic data set. The x-range changes from (-12, 12), the centers of the Gaussians are uniformly distributed over (-3, 3), and width is uniformly distributed over (0.5, 5). The amplitude value of the (additive) noise is sampled uniformly between 0 and 0.1. Image by the authors.</em></figcaption></figure><p>Simple PCA analysis implemented in the accompanying notebook (see link at the end of the article) indeed illustrates that the number of components required to represent such data set is large, and the readers are welcome to play with the behavior of the components as a function of the data spread in the parameter space and noise level.</p><p>Now let’s apply the simple VAE. To do this, we are going to use our <a href="https://github.com/ziatdinovmax/pyroVED">pyroVED</a> package which is built on top of the Pyro probabilistic programming language. Using the pyroVED (as <em>pv </em>), the VAEs can be trained with just a few lines of code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K_j8ReFU48d8m8Ak" /></figure><p>In this case, the VAE encodes the dataset via the two latent variables, and the distribution of the data points in the latent space of the trained VAE model is shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/0*9pwTOVdObD1pw-KP" /><figcaption><em>The data points in the latent space of a conventional VAE. Image by the authors.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/0*EWbfwkHxuEQh8kEB" /><figcaption><em>The latent manifold learned by a conventional VAE projected to spectral space.</em></figcaption></figure><p>The results are not so bad! Our data points clearly show the structure resembling the joint uniform distribution. To check this guess, we can color each point using the ground truth label and see that labels corresponding to width are changing (mostly) from top to bottom of the image, whereas the ones corresponding to the center position are changing (mostly) from left to right. We can also reconstruct the curves from the grid of points in the latent space and observe that indeed the width changes from top to bottom and position changes from left to right. Hence, our variational autoencoder has (mostly) disentangled the representations of the data, and in this case one of the disentangled factors of variation is the width and another is the position.</p><p>However, once we plot our latent variables versus the ground truth, we see that while there is a definite relationship between the ground truth variables and latent variables, they are not equal. Furthermore, the offsets are encoded in arbitrary units, which is not of great practical use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/0*K3A0MlWWNwfBek6T" /><figcaption><em>VAE’s latent variables versus the ground truth. Image by the authors.</em></figcaption></figure><p>Now, let’s repeat this analysis with the shift VAE. Here, the relative shift is separated as a special (offset) latent variable, and the remaining variability is encoded as two conventional latent variables. To do this in pyroVED, we just need to change <em>coord=0</em> to <em>coord=1</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*jbB4LHFLiTAnAA16" /></figure><p>The corresponding latent space representation is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/0*X8aefJzWt69SEy6t" /><figcaption><em>The data points in the latent space of shift-VAE. Image by the authors.</em></figcaption></figure><p>Note that the latent space is quasi-collapsed, with the data points forming a 1D manifold (although there is a tiny “leakage” from the offset latent variable to the first (“collapsed”) latent variable). Classically in VAEs, this collapse of latent space is perceived as a problem calling for the adjustment of the “loss” function. However, here we know that our ground truth data set has only two factors of variability, one of which is position. Hence, the dimensionality of our latent space hints at the true physical dimensionality of the data!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/0*g2Qv6Cem-ViR9Z5p" /><figcaption><em>The latent manifold learned by shift-VAE projected to spectral space. Image by the authors.</em></figcaption></figure><p>Note that the reconstructed spectra from the latent space of the system are all centered at zero, suggesting that the shift VAE was able to separate the shift and other variability factors. Finally, the offset derived from shift-VAE is numerically very close to the ground truth values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/0*anmGzFPlSkuUk3D_" /><figcaption><em>Shift-VAE’s latent variables versus the ground truth. Note that here we do not plot a “collapsed” latent variable. Image by the authors.</em></figcaption></figure><p>This summarizes the introduction of the shift-VAE. Feel free to play with the notebook and apply it to your data sets. Please check out our <a href="https://github.com/ziatdinovmax/pyroVED">pyroVED</a> software package for applying this and other VAEs to scientific image and spectral data (it is in the alpha stage and the contributions/suggestions are more than welcome!). If you are interested to learn more about different SPM modes as applied to the electrical and electromechanical characterization, you are welcome to sign to our YouTube channel <a href="https://www.youtube.com/channel/UCyh-7XlL-BuymJD7vdoNOvw">M*N: Microscopy, Machine Learning, Materials</a>.</p><p>Finally, in the scientific world, we acknowledge the sponsor that funded this research. This effort was performed and supported at Oak Ridge National Laboratory’s Center for Nanophase Materials Sciences (CNMS), a U.S. Department of Energy Office of Science User Facility. You can take a virtual walk through it using <a href="https://my.matterport.com/show/?m=MT819FqAwbT">this link</a> and tell us if you want to know more.</p><p>The executable Google Colab notebook is available <a href="https://colab.research.google.com/github/ziatdinovmax/notebooks_for_medium/blob/main/shiftVAE_medium.ipynb">here</a>.</p><p><strong>References</strong></p><p>1. Butt, H. J.; Cappella, B.; Kappl, M., Force measurements with the atomic force microscope: Technique, interpretation and applications. <em>Surf. Sci. Rep. </em><strong>2005,</strong> <em>59</em> (1–6), 1–152.</p><p>2. Garcia, R.; Perez, R., Dynamic atomic force microscopy methods. <em>Surf. Sci. Rep. </em><strong>2002,</strong> <em>47</em> (6–8), 197–301.</p><p>3. Jesse, S.; Kalinin, S. V.; Proksch, R.; Baddorf, A. P.; Rodriguez, B. J., The band excitation method in scanning probe microscopy for rapid mapping of energy dissipation on the nanoscale. <em>Nanotechnology </em><strong>2007,</strong> <em>18</em> (43), 435503.</p><p>4. Jesse, S.; Kalinin, S. V., Band excitation in scanning probe microscopy: sines of change. <em>J. Phys. D-Appl. Phys. </em><strong>2011,</strong> <em>44</em> (46), 464006.</p><p>5. Vasudevan, R. K.; Kelley, K. P.; Eliseev, E.; Jesse, S.; Funakubo, H.; Morozovska, A.; Kalinin, S. V., Bayesian inference in band excitation scanning probe microscopy for optimal dynamic model selection in imaging. <em>J. Appl. Phys. </em><strong>2020,</strong> <em>128</em> (5), 10.</p><p>6. Jesse, S.; Kalinin, S. V., Principal component and spatial correlation analysis of spectroscopic-imaging data in scanning probe microscopy. <em>Nanotechnology </em><strong>2009,</strong> <em>20</em> (8), 085714.</p><p>7. Belianinov, A.; Kalinin, S. V.; Jesse, S., Complete information acquisition in dynamic force microscopy. <em>Nat. Commun. </em><strong>2015,</strong> <em>6</em>.</p><p>8. Dobigeon, N.; Brun, N., Spectral mixture analysis of EELS spectrum-images. <em>Ultramicroscopy </em><strong>2012,</strong> <em>120</em>, 25–34.</p><p>9. Kannan, R.; Ievlev, A. V.; Laanait, N.; Ziatdinov, M. A.; Vasudevan, R. K.; Jesse, S.; Kalinin, S. V., Deep data analysis via physically constrained linear unmixing: universal framework, domain examples, and a community-wide platform. <em>Adv. Struct. Chem. Imag. </em><strong>2018,</strong> <em>4</em>, 20.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca609ec84f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/mastering-the-shifts-with-variational-autoencoders-ca609ec84f1">Mastering the shifts with variational autoencoders</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enter the j(r)VAE: divide, (rotate), and order… the cards]]></title>
            <link>https://medium.com/data-science/enter-the-j-r-vae-divide-rotate-and-order-the-cards-9d10c6633726?source=rss-eb4c5879edd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d10c6633726</guid>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[explore]]></category>
            <category><![CDATA[disentanglement]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[thoughts-and-theory]]></category>
            <dc:creator><![CDATA[Maxim Ziatdinov]]></dc:creator>
            <pubDate>Thu, 11 Mar 2021 20:42:10 GMT</pubDate>
            <atom:updated>2021-03-25T19:16:05.408Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/thoughts-and-theory">Thoughts and Theory</a></h4><h4>Introduction to joint (rotationally-invariant) VAEs that can perform unsupervised classification and disentangle relevant (continuous) factors of variation at the same time.</h4><p><em>Maxim Ziatdinov¹ ² &amp; Sergei V. Kalinin¹</em></p><p><em>¹ Center for Nanophase Materials Sciences and ² Computational Sciences and Engineering Division, Oak Ridge National Laboratory, Oak Ridge, TN 37831, United States</em></p><p>What are joint (rotationally-invariant) variational autoencoders, and why would we need them? The short answer to the first question is that <em>j</em>(<em>r</em>)VAE is a version of a variational autoencoder where one of the latent variables is discrete and the rest are continuous. Hence, <em>j</em>VAE seeks both to cluster the data by associating it with a specific discrete class and disentangle data representations within the class via latent variables. The answer to the second question is that in the experimental world, we often do not know what we are dealing with, but very much want to find out.</p><p>In their careers, both authors of this note focus on nanometer- and atomically-resolved imaging and spectroscopy. M.Z. started his career doing Scanning Tunneling Microscopy and first-principles calculations at the Tokyo Institute of Technology, Japan, exploring the electronic properties of graphene decorated with hydrogen and oxygen atoms. After moving to Oak Ridge, he gradually transitioned to the field of data analysis and applied deep/machine learning (ML/DL), with his first DL papers focusing on the analysis of electron microscopy datasets. <a href="https://en.wikipedia.org/wiki/Sergei_V._Kalinin">S.V.K.</a> has started his familiarity with Scanning Probe Microscopy as a visiting student in PosTech, South Korea in 1996, and has made microscopy a career since 1998 as a graduate student at U. Penn working with Dawn Bonnell. In 25 years, he has amassed expertise working with variants of scanning probe microscopy, electron microscopy, and chemical imaging. The commonality for all these techniques is their capability to yield massive amounts of data, from polarization distributions in grains of polycrystalline thin films to the electronic structure of high-temperature superconductors to structural distortions underpinning the physics of the class of Kitaev materials for quantum computing.</p><p>As microscopists by training and inclination, we seek to understand the physics and chemistry of materials from these data, either looking for qualitative understanding of the materials’ structure and functionalities (<em>“Are there dislocations? Do we see evidence of point defects?”</em>), or by refining quantitative physical models (“<em>How does polarization behave at interfaces? What is the value of flexoelectric tensor?”</em>), or by discovering novel phenomena (“<em>Hmmm…. This is weird…</em>”). However, for many years such analysis was based on human analytics and comprehension — spending innumerable hours with the visualization software of the time looking for specific objects while varying contrast, filtering, color schemes, in the analysis software. Clearly, this is not the best strategy even for the 2D images (even though it used to be even worse in the times of Polaroid cameras connected to the microscopes). For the multidimensional spectroscopic data sets now common in electron and scanning probe microscopy, or stacks of images such as movies of atomic evolution in electron microscopy, this is just impossible.</p><p>Hence, the question is whether machine learning can help us discover “interesting“ objects in data. If we know exactly what we are looking for, i.e. have labels, this becomes a classical supervised learning problem. The authors have pioneered the use of the deep convolutional neural networks (DCNN) for the atom finding in electron microscopy images in 2017, enabling analysis of massive data sets containing hundreds of images and creating libraries of atomic defects, exploring point defect reactions, etc [1–3]. In this case, ML effectively performs a human-level task, only faster.</p><p>However, in many cases, we aim to look for new and unusual objects and behaviors in our data. For example, we may want to find what are the constituent building blocks forming the structure of amorphous solids. Alternatively, we seek to understand how the electronic density patterns on the surface of high-temperature superconductors are organized, and if there is any underlying order. As a third example, we aim to discover ferroelectric domain structures from images of the atomic lattice. How should we go about it?</p><p>One possible strategy for such analysis is descriptor engineering with subsequent unsupervised learning. We subdivide the image into multiple sub-images and explore the latter. In the absence of any prior knowledge about the system, the sub-images can be picked on a rectangular grid, much like it is done in the input convolutional layer of DCNN. Alternatively, they can be centered on the objects of interest, providing inferential bias into the analysis. For atomically resolved data, it is natural to center the descriptors on atomic columns, whereas for ferroelectric domains we can position them on domain walls. Parenthetically, the choice of the position encodings can be a very interesting area going further.</p><p>With the descriptors in hand, we may seek to find disparate categories of atomic structures (e.g. discover “molecules”) or find the strain states of individual structural units. The first task is done by clustering. Using a suitable algorithm, whether <em>k</em>-means, Gaussian Mixture Model, or UMAP, we try to separate our descriptors into dissimilar groups. The second can be realized by physics-based analysis if we know exactly what we are looking for. Sometimes we do — however, there is always a risk to find exactly what you are looking for whether it is there or not, and miss novel discoveries. Hence, we would like to use unsupervised ML to find relevant traits within the data, and that’s exactly where variational autoencoders with their capability to disentangle data representations and find <em>a priori</em> unknown factors of variability within the data can come in handy.</p><p>However, often we need to do both at the same time! For example, in the observations of atomic motion in STEM, we can observe both structural units like 5-, 6-, and 7- member rings of ideal graphene and defects, but also their deformations under strain. Similarly, we can see beautiful domain structures in ferroelectric materials, and the human brain will naturally classify them into different types, and elucidate deformations within each type. Can VAEs do it?</p><p>Of course, one approach to this is to encode the full data set in one latent space. In this case, each encoded object corresponds to a single latent vector, and we can simply cluster the points in the latent space. However, in this case, the representation of the data (understood as a smooth variation of relevant traits within the data set) will not be disentangled well. In some sense, class to class variation dominates the process. Compare the disentangled data for the simple (<em>r</em>)VAE and conditional (<em>r</em>)VAE from our <a href="https://ziatdinovmax.medium.com/how-we-learnt-to-love-the-rotationally-invariant-variational-autoencoders-rvae-and-almost-562aa164c59f">previous post</a> — clearly, when classes are known, we can dig into the data structure much deeper and the traits become uniform across full latent space (rather than piecewise).</p><p>So, how can we proceed? A way to do it is to make one of the latent directions discrete, an approach we refer to as <em>j</em>VAE (‘<em>j</em>’ for joint). In this case during training, the autoencoder both assigns the discrete class to the variables and finds the optimal continuous latent code, i.e. performs classification and disentangles relevant variables at the same time.</p><p>However, this is not simple, because discrete (categorical) latent variables cannot be backpropagated through samples. One solution is to substitute a non-differentiable sample from a categorical distribution with a differentiable sample from a Gumbel-Softmax distribution [4, 5]. Another solution is to marginalize out discrete latent variables via a full enumeration. This approach is generally associated with high computational costs, although the recently available probabilistic programming libraries such as Pyro make this task easier by enabling <a href="https://pyro.ai/examples/enumeration.html">parallel enumeration</a>. We have experimented with both approaches and found that they generally produce similar results on our datasets. For this article, we utilized the approach based on the Gumbel-Softmax trick.</p><p>Now, let’s look at examples. Rather than working with the standard MNIST data set, we are going to make our own data set of playing card suits, with monochrome clubs, spades, diamonds, and hearts. We speculate that galaxy images from GalaxyZoo, some biological objects (bacteria, diatoms, viruses) can all be a great subject to explore — both from aesthetic and scientific perspectives. However, cards offer an ideal toy model. Here, diamonds have a shape that is very distinct from the other three hands. Their rotation by 90 degrees is equivalent to uniaxial compression and resizing, bringing interesting degeneracy into outcomes of possible affine transforms. Similarly, hearts and spades differ by fairly small detail, whereas spades and clubs (without tail) have three-fold and mirror symmetry respectively. So, despite simplicity card suits form an interesting collection of symbols.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4RDn71AEAODK1LWpG5YdQ.png" /><figcaption><em>Typical objects of the cards set with different affine transforms. On the left (a = 12, t = 0.1, s = 10), on the right (a = 120, t = 0.1, s = 10). Images by the authors.</em></figcaption></figure><p>First, we create a generator of card symbols with different parameters. We start from the digitized symbols from Word as a starting point, transform them into images, and then use a set of affine transforms including rotation, shear, and translation to prepare our data set. Here, the angles have a uniform distribution from -<em>a</em> to <em>a</em>, translation has a uniform distribution from -<em>t</em> to <em>t</em>, and shear has a uniform distribution from -<em>s</em> to <em>s</em>. The examples from two realizations of this data set are shown above. In other words, here we have multiple well-defined classes of objects with several continuous traits (sizes and positions). Now, let’s assume that we, much like John Snow, do not know anything about these objects, and see if machine learning can help to sort out what goes on here!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FXDyyuSkU6LeimcIMHCozw.png" /><figcaption><em>Principal component analysis on the cards dataset. Images by the authors.</em></figcaption></figure><p>As we pointed in the <a href="https://ziatdinovmax.medium.com/how-we-learnt-to-love-the-rotationally-invariant-variational-autoencoders-rvae-and-almost-562aa164c59f">previous blogpost</a>, recently we almost stopped doing principal component analysis. Running quick PCA on this data set illustrates why — the PCA components are very complex, and there is a lot of them. For sufficiently large data sets there will be as many significant components as the number of pixels in the image. So, not very useful.</p><p>We can run the code from the previous post and quickly look at the VAE analysis on this data set. Shown below are corresponding latent spaces and latent representations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zq-_rQGogAVxnzyavyfxAA.png" /><figcaption><em>VAE analysis on the cards data set for t = 0.1 and varying orientation and shear strength. From left to right (a = 12, s = 1), (a = 12, s = 10), (a = 120, s = 1), and (a = 120, s = 10). The color scheme is chosen to represent the hand. Images by the authors.</em></figcaption></figure><p>For small rotational disorder (<em>a</em> = 12), the latent space clearly forms well-separated clusters corresponding to each hand, with the rotation angles and shear components changing smoothly within the corresponding part of the latent space. At the same time, for large <em>a</em> = 120, the distribution in the latent space becomes very complex. We ascribe this behavior to the fact that the latent space representation should contain the “cowlick” defect containing unphysical shapes of objects, due to the fact that the unit circle (SO(2) Lie group) cannot be well represented on a surface. Given that we have several structures, the VAE is trying to orient the objects by angle and separate them by shape and size, giving rise to a very complex structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*shQCuF7zFEVxB3vZdPZo3g.png" /><figcaption><em>rVAE analysis on the cards data set for t = 0.1 and varying orientation and shear strength. From left to right (a = 12, s = 1), (a = 12, s = 10), (a = 120, s = 1), and (a = 120, s = 10). The color scheme is chosen to represent the hand. Images by the authors.</em></figcaption></figure><p>In comparison, shown above is the <em>r</em>VAE analysis of the same data. In this case, the rotational angle is separated as an independent variable by the construction of the latent vector. The emergent behaviors are truly remarkable. For small angle and shear disorder, <em>a</em> = 12, <em>s</em> = 1, the hands form four very distinct groups in the latent space of the system. If the shear disorder is increased, <em>a</em> = 12, <em>s</em> = 10, these clusters elongate and form clearly visible 1D manifolds in the latent space. When we increase the orientation disorder, <em>a</em> = 120, we start to see more than one cluster for each hand, e.g. there is a cluster corresponding to two orientations of clubs and spades rotated by 120 degrees. In other words, <em>r</em>VAE with the chosen priors can compensate for a small deviation of rotational angle but tends to discover the degenerate minima. As a simple exercise to understand this behavior, consider the structural similarity (or correlation) between club images as they are rotated around the central axis. The correlation will have pronounced minima for 120 and 240 degrees, where the main leaves overlap and only positions of the small tail differ. Here for small shear distortion, <em>s</em> = 1, we have well-defined clusters corresponding to the rotational variants of the hands, and for large shear distortion, <em>s</em> = 10, they again become elongated manifolds. Note that in some sense we have disentangled the representation of the data, which in this case is shear. Furthermore, it is curious to compare the shape of the manifold for diamonds and not diamonds — the former are more elongated and diffuse exactly due to the presence of affine transform that is equivalent to 90-degree rotation!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCIwCqJERTUYI66pu7xyQw.png" /><figcaption><em>jVAE analysis for a = 12, t = 0.1, s = 10. Images by the authors.</em></figcaption></figure><p>Now, enter the <em>j</em>VAE. You are welcome to play with the different model parameters in the accompanying notebook, and here we are only going to show values for two examples. For small disorder, <em>a</em> = 12 and <em>s</em> = 10, the simple <em>j</em>VAE (without rotational latent variable) does an excellent job separating the objects in an unsupervised manner. Notice how the first latent manifold traversal captures information about the orientational disorder (+ shear deformation), whereas the second latent manifold traversal captures off-the-center displacements (+ shear deformation).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l7_7Jx3uSrIKUtda8l2a9g.png" /><figcaption><em>jVAE analysis for a = 120, t = 0.1, s = 10. Images by the authors.</em></figcaption></figure><p>For the large disorder, the simple <em>j</em>VAE fails to separate classes. As one can see from the figure above, each inferred “class” contains a mixture of diamonds, spades, clubs, and hearts. We note that unlike (<em>r</em>)VAE, <em>j</em>(<em>r</em>)VAE tends to be quite sensitive to the initialization of model parameters (i.e., initialization of weights in decoder and encoder neural networks and shuffling of the training set), although on the qualitative level the results remain largely unchanged. Feel free to experiment with different seeds in the notebook and see how they affect the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Un0B_P7xa7nxo0IXFpq7Iw.png" /><figcaption><em>jrVAE analysis for a = 120, t = 0.1, s = 10. Images by the authors.</em></figcaption></figure><p>In comparison, <em>jr</em>VAE that has three “special” continuous latent variables designated to absorb rotational and translational disorder shows much better separation for the same disorder parameters. Here, both clubs and diamonds got their own latent space, whereas hearts and spades share another (here we would like to add that simply adding three (or more) more standard continuous latent variables to <em>j</em>VAE won’t resolve its inability to separate classes for the large disorder).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CB7UK8Jhq3r6CFQyyIC_DQ.png" /><figcaption><em>Encoded latent space for the jVAE (left) and jrVAE (right) for a = 120, t = 0.1, s = 10. Images by the authors.</em></figcaption></figure><p>Finally, let’s see how well our <em>jr</em>VAE classes correspond to the original classes. Note that the order of inferred classes is random (depends on the initialization) and doesn’t correspond to the order of the ground truth labels. We can see that overall, it did quite a remarkable job separating different classes without any supervision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*nG8lNmmclf-sk5ZHmSWf9g.png" /><figcaption><em>Correlation matrix (inferred vs. ground truth) for jrVAE for a = 120, t = 0.1, s = 10. Image by the authors.</em></figcaption></figure><p>Note that the performance can be fine-tuned further; however, in this case, we would be tuning it towards the “known” answer for this particular system, whereas unknown systems are, well, unknown.</p><p>This summarizes the introduction of the <em>j</em>VAE and <em>jr</em>VAE. Feel free to play with the notebooks and apply them to your data sets. The authors use VAE and its extensions in their research on atomically resolved and mesoscopic imaging in scanning probe and electron microscopies, but these methods can be applied to a much broader variety of optical, chemical, and other imaging, as well as across other computer science domains. Please also check out our <a href="https://github.com/pycroscopy/atomai">AtomAI</a> software package for applying this and other deep/machine learning tools to scientific imaging.</p><p>Finally, in the scientific world, we acknowledge the sponsor that funded this research. This effort was performed and supported at Oak Ridge National Laboratory’s Center for Nanophase Materials Sciences (CNMS), a U.S. Department of Energy, Office of Science User Facility. You can take a virtual walk through it using <a href="https://my.matterport.com/show/?m=MT819FqAwbT">this link</a> and tell us if you want to know more.</p><p>The executable Google Colab notebook is available <a href="https://colab.research.google.com/github/ziatdinovmax/atomai/blob/master/examples/notebooks/Cards_jrVAE_v2a.ipynb">here</a></p><p><strong>References</strong></p><p>1. Ziatdinov, M.; Dyck, O.; Maksov, A.; Li, X. F.; San, X. H.; Xiao, K.; Unocic, R. R.; Vasudevan, R.; Jesse, S.; Kalinin, S. V., Deep Learning of Atomically Resolved Scanning Transmission Electron Microscopy Images: Chemical Identification and Tracking Local Transformations. ACS Nano 2017, 11 (12), 12742–12752.</p><p>2. Maksov, A.; Dyck, O.; Wang, K.; Xiao, K.; Geohegan, D. B.; Sumpter, B. G.; Vasudevan, R. K.; Jesse, S.; Kalinin, S. V.; Ziatdinov, M., Deep learning analysis of defect and phase evolution during electron beam-induced transformations in WS2. npj Comput. Mater. 2019, 5, 12.</p><p>3. Ziatdinov, M.; Dyck, O.; Li, X.; Sumpter, B. G.; Jesse, S.; Vasudevan, R. K.; Kalinin, S. V., Building and exploring libraries of atomic defects in graphene: Scanning transmission electron and scanning tunneling microscopy study. Sci. Adv. 2019, 5 (9), eaaw8989.</p><p>4. Jang, E.; Gu, S.; Poole, B., Categorical reparameterization with Gumbel-Softmax. arXiv preprint arXiv:1611.01144 2016.</p><p>5. Dupont, E., Learning Disentangled Continuous and Discrete Representations. arXiv preprint arXiv:1804.00104.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d10c6633726" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/enter-the-j-r-vae-divide-rotate-and-order-the-cards-9d10c6633726">Enter the j(r)VAE: divide, (rotate), and order… the cards</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we learnt to love the rotationally invariant variational autoencoders (rVAE), and (almost)…]]></title>
            <link>https://medium.com/data-science/how-we-learnt-to-love-the-rotationally-invariant-variational-autoencoders-rvae-and-almost-562aa164c59f?source=rss-eb4c5879edd------2</link>
            <guid isPermaLink="false">https://medium.com/p/562aa164c59f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pyro]]></category>
            <category><![CDATA[thoughts-and-theory]]></category>
            <category><![CDATA[explore]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <dc:creator><![CDATA[Maxim Ziatdinov]]></dc:creator>
            <pubDate>Sat, 27 Feb 2021 01:29:57 GMT</pubDate>
            <atom:updated>2021-03-25T21:33:54.715Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/thoughts-and-theory">Thoughts and Theory</a></h4><h3><strong>How we learnt to love the rotationally invariant variational autoencoders (rVAE), and (almost) stopped doing PCA</strong></h3><h4>Introduction to unsupervised and class-conditioned variational autoencoders (VAEs) with rotational invariance and their application to image analysis</h4><p><em>Maxim Ziatdinov¹ ² &amp; Sergei V. Kalinin¹</em></p><p><em>¹ Center for Nanophase Materials Sciences and ² Computational Sciences and Engineering Division, Oak Ridge National Laboratory, Oak Ridge, TN 37831, United States</em></p><p>Scientific research often yields enormous volumes of data. The examples range from fields such as astronomy with its exquisite optical and radio telescopes, satellite geospatial imagery, medical and biological imaging, neutron- and X-Ray scattering, and scanning probe and electron microscopies. Very often the imaging information is available at multiple bands or spectra at each spatial location, giving rise to complex multidimensional data sets. The typical example will be hyperspectral satellite imaging, where a full optical spectrum is measured at each spatial location. However, even more imaging modalities emerge in the context of domain science applications such as scanning probe or electron microscopy. In all these cases, the first step to the researcher is to visualize and subsequently interpret the imaging data in terms of objects of interest, were it new types of stars or exoplanets in astronomy, plant growth patterns or hidden installations in geospatial imaging, or electronic properties of a single atom in scanning tunneling microscopy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnHOk_gSuX9s083AE5AMmA.png" /><figcaption><em>Atomic-scale surface topography of iron-based superconductor (just above a superconducting transition) and tunneling conductance proportional to the local density of electronic states at several selected locations. Image by M.Z. (from the time before he learnt to love VAE)</em></figcaption></figure><p>The human eyes are extremely well suited to the analysis of the imaging data, the capability that emerged as the result of the millennia of evolution in the savannah where noticing the predator or prey in time was a condition for survival. At the same time, human perception and comprehension (with few exceptions) are generally not well suited for comprehension and object recognition of 3, 4, or higher-dimensional data. Hence, the natural question is whether machine learning can help in this matter.</p><p>The scientific field is abounding of the examples of visionaries whose foresight has significantly preempted the field. A well-known example is <a href="https://en.wikipedia.org/wiki/Ada_Lovelace">Ada Lovelace</a>, who had explored the context of computer programming long before computers has become available. Another is <a href="https://en.wikipedia.org/wiki/J._C._R._Licklider">Joe Licklider</a>, one of the founders of DARPA, whose book “The Libraries of the Future” written in the 50ies have predicted much of the modern internet-based knowledge infrastructure including electronic books and journals, data bases, etc. In microscopy, one of the first visionary perspectives was given by Noel Bonnett in his publications, delineating applications of machine learning and multivariate statistics to hyperspectral data [1, 2]. The first practical applications of multivariate statistical methods in microscopy appeared several years later, when personal computers have become powerful enough to handle the “huge” 50x50x1000 hyperspectral data sets in electron [3] and scanning probe [4] microscopy that gave rise to acceptable images.</p><p>The ML method of choice (or availability) at that time was principal component analysis (PCA), a technique converting the hyperspectral data set <em>R</em>(<em>x</em>, <em>y</em>, <em>E</em>) in the linear combination of loading maps <em>aᵢ</em>(<em>x</em>, <em>y</em>) and components <em>Aᵢ</em>(<em>E</em>).In the most general sense, the components define the specific behaviors of the system and the loading maps contain the information on where this behavior manifests. It was often argued that PCA analysis does not assign physical meaning to the components (which is correct — they are defined only in the information-theory sense), and consequently, multiple versions of linear and non-linear dimensionality reduction methods allowing for specific physical constraints emerged over the last decade [5]. Currently, many of these methods are available as a part of basic Python libraries such as scikit-learn, and even more are available as stand-alone libraries. However, the key aspect of these methods as applied to hyperspectral data is that they explore common features in the spectral domain only, and the exchange of pixels in the spatial domains does not affect the components and only leads to the exchange of pixels in loading maps.</p><p>However, in many cases, the scientists analyzing imaging data are interested in specific shapes. In the ancient human world, we sought to detect the predator before the opposite happens. In astronomy, we aim to identify the shape of the galaxies or weak variations of the intensity of stars indicative of the presence of exoplanets. In scanning probe or electron microscopy, we aim to discover the ordering patterns signifying symmetry breaking and emergence of the novel electronic or structural orders. Sometimes, PCA and related methods allow such discoveries via examination of the loading maps. However, in many cases, the relevant spatially resolved information is spread over the tens of loading maps. Hence, the question is whether there are machine learning algorithms that can explore shapes?</p><p>One of the main difficulties here is that in images the shapes can <em>a priory</em> have any orientation. While modern deep convolutional neural networks (DCNNs) are equivariant, i.e. allow for the detection of a specific object anywhere within the image, they are typically limited when it comes to the discovery of multiple rotational classes of a single object. For example, in classical cases such as Image Net or supervised learning of cats in images, cats generally are oriented in the vertical direction. While the data sets with cats in any orientation can be made, that will likely cause serious questions on the ethical treatment of animals. Consequently, even supervised networks are not particularly good in recognizing a rotational version of the same object (see, for example, the famous <a href="https://hub.packtpub.com/researchers-input-rabbit-duck-illusion-to-google-cloud-vision-api-and-conclude-it-shows-orientation-bias/">duck vs. rabbit illusion</a>). This is even a bigger problem for unsupervised learning when we do not know what specific objects we are trying to find.</p><p>Here comes the rotationally invariant variational autoencoders (that we have learnt to love over the last year since they have allowed us to resolve several physical problems that stymied us for a decade). Let’s explore this concept step by step. The autoencoder generally refers to a special class of neural networks where the original data set is compressed to a small number of continuous latent variables and is then expanded back to the original data set. The network is trained to improve (in a sense of a chosen loss function) the data reconstruction, which sounds like a somewhat limited objective (e.g. we could have just left it alone). The key trick here is that in the process the network learns how to optimally describe the data in terms of the latent variables. This allows the autoencoder to discover the optimal representation(s), while also rejecting the noise present in the data. Hence applications in denoising, image reconstruction, etc.</p><p>The variational autoencoder (VAE) builds upon this concept by making the reconstruction process probabilistic. In this case, the latent variables are drawn from certain (typically Gaussian) distribution, and the training seeks to optimize both the reconstruction loss and the Kullback-Leibler divergence between the distribution of the encoded images and latent variables corresponding to decoded images in the latent space. One of the most attractive features of VAEs is their capability to disentangle the representations of the data, i.e. discovering the specific trait such as handwriting styles in MNIST data, emotions in human faces, or complex manifolds defining the degrees of freedom in robotic systems. There are multiple excellent sources explaining VAEs both on Medium and on arXiv [6].</p><p>Here, we extend the VAE to the analysis of rotationally invariant features. In the rotationally-invariant VAE (rVAE), there is one “neuron” in the latent layer designated to absorb arbitrary rotations of structures in images whereas all other neurons are used for disentangling the remaining factors of variation. The trick here is to write the VAE’s decoder as a function of image (spatial) coordinates, which can be realized either via the spatial generator net [7](for a fully-connected decoder) or via a slightly modified version of the spatial broadcast generator [8](for a convolutional decoder). Here, we realized the rVAE via the <a href="https://pyro.ai/">Pyro</a> probabilistic programming language. For completeness, we introduce and discuss both the simple rVAE and class-conditioned rVAE. More complex versions of (r)VAE including joint (r)VAE, semi-supervised (r)VAE, and (r)VAE augmented with normalizing flows allowing for the unknown and partially known classes will be discussed later.</p><p>Let’s play with the rVAE and its variants using the classical MNIST data set (note that instead of digits it could be different atomic or molecular structures). First, we create the rotated MNIST data set that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*PCdKvq5NrIKeDgzvrxlRjQ.png" /><figcaption><em>Sample from the MNIST dataset rotated randomly in the range between -60° and +60°. Image by the authors.</em></figcaption></figure><p>We further proceed to use the rotated digits as features, and keep the labels and rotation angles as ground truth data to compare with the results of rVAE and class-conditioned rVAE analysis.</p><p>First, we explore the simple VAE. Here, we derive the latent space and distribution of points in the latent space colored by angle and digit. As a reminder, the convenient way to illustrate VAE operation is via the distribution of the (encoded) points in the latent space, and via the latent space representation projected to image space. In the former, all features in the data set are encoded and visualized in the latent plane. If some attributes of the data set are known (e.g. classes or rotation angles), they can be used to set the color scale to examine the trends in the latent space. Alternatively, the latent space can be sampled by a rectangular grid of points and the corresponding images can be decoded and plotted as a latent space representation. This analysis is particularly convenient when latent space is 2D and the features are 2D as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BWEL_G3a1_zR1JagUH-8GQ.png" /><figcaption><em>VAE analysis of the rotated MNIST data. Image by the authors.</em></figcaption></figure><p>Shown above are the latent space representations for the rotated MNIST data for the simple VAE. Here, we can clearly see that latent space contains digits in all orientations. It may be fun to experiment with the number of reconstructed sub-images via the function <em>vae.manifold2d(d=some_positive_integer)</em> in the accompanying notebook. Particularly for very large <em>d</em> = 100 the individual digits cannot be recognized, but the latent space representation starts to exhibit patterns corresponding to the areas occupied by individual digits.</p><p>The examination of latent space shows that the angle changes along the first latent direction, whereas the digit changes along the second latent dimension forming well-separated clusters. The notable exception is the cluster corresponding to ‘9’ and’6’ which cannot be distinguished after 180 rotation (same for VAE, same for human). Overall, this clearly illustrates the disentanglement of the data representation concept, where the rotational angle and class emerge as the two most prominent factors of variation within the data.</p><p>Now, we repeat the same analysis with the conditional VAE (cVAE). In this case, our decoded object during the training and prediction is the concatenated image and the class, and hence we have a separate latent space for each of the classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wLJXLogkeSefDdPXbBa8CA.png" /><figcaption><em>cVAE analysis of the rotated MNIST data. Image by the authors.</em></figcaption></figure><p>Shown above are the latent spaces for digits ‘0’, ‘1’, and ‘2’. Note a very intriguing pattern — in this case, the “unphysical shapes” form a cluster (e.g., around the central region in the image with “1”-s) surrounded by “physically realizable” digits. This behavior is linked to a rather fundamental aspect of physics, namely the topological structure of the latent space and data space. Some of the excellent sources on this are Ref. [9, 10]. The encoded data is also shown in the figure above. Here, the latent angle forms a well-defined circle (going from negative to positive rotation angles in the counter-clockwise direction), whereas the digits classes are now distributed as a single blob (as expected, given that each forms its own latent space). The take-home message is that now both disentangled factors are the angle variation, and that VAE and cVAE do not deal with angles well.</p><p>Now let’s add rotation invariance, as incorporated in the rVAE. The latent space representations are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLvJBB1SQNdy4w9yjRFtqw.png" /><figcaption><em>rVAE analysis of the rotated MNIST data. Image by the authors.</em></figcaption></figure><p>In this case, the digits in the latent space are oriented in one direction. The latent space shows that the angles are now random, whereas the digits form well-defined clusters (rather remarkable given that we encode the data set using only two latent variables). We also get the angle as one of the latent variables, and the latent angle and ground truth angle are compared in the figure above. Note that they are linearly related, but at the same time latent angles have broad distribution. This is unsurprising since an angle is one of the characteristics of handwriting style and varies from person to person! The latent representation we discovered hence compensated by this fact via introducing it as an additional augmentation variable, and then separating it from other factors of variation.</p><p>Finally, we illustrate the class-conditioned rVAE (crVAE) applied to this data set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-T3_SRu5wW8l1nnBFH7DDA.png" /><figcaption><em>crVAE analysis of the rotated MNIST data. Image by the authors.</em></figcaption></figure><p>In this case, our latent reconstructions clearly show that within each latent space, the digits are oriented in the same direction, and latent variables now encode very subtle details of the handwriting styles. Have a look at the ‘0’, ’1’, and ‘2’ above, and play with the other digits in the accompanying notebook.</p><p>This summarizes the introduction of the rVAE and crVAE. Feel free to play with the notebook and apply it to your data sets. The authors use VAE and its extensions in their research on atomically resolved and mesoscopic imaging in scanning probe and electron microscopies, but these methods can be applied to a much broader variety of optical, chemical, and other imaging, as well as across other computer science domains. Please also check out our <a href="https://github.com/pycroscopy/atomai">AtomAI</a> software package for applying this and other deep/machine learning tools to scientific imaging.</p><p>Finally, in the scientific world, we acknowledge the sponsor that funded this research. This effort was performed and supported at Oak Ridge National Laboratory’s Center for Nanophase Materials Sciences (CNMS), a U.S. Department of Energy, Office of Science User Facility. You can take a virtual walk through it using <a href="https://my.matterport.com/show/?m=MT819FqAwbT">this link</a> and tell us if you want to know more.</p><p>The executable Google Colab notebook is available <a href="https://colab.research.google.com/github/ziatdinovmax/notebooks_for_medium/blob/main/pyroVAE_MNIST_medium.ipynb">via GitHub</a>.</p><p>1. Bonnet, N., Multivariate statistical methods for the analysis of microscope image series: applications in materials science. <em>J. Microsc.-Oxf. </em><strong>1998,</strong> <em>190</em>, 2–18.</p><p>2. Bonnet, N., Artificial intelligence and pattern recognition techniques in microscope image processing and analysis. In <em>Advances in Imaging and Electron Physics, Vol 114</em>, Hawkes, P. W., Ed. Elsevier Academic Press Inc: San Diego, 2000; Vol. 114, pp 1–77.</p><p>3. Bosman, M.; Watanabe, M.; Alexander, D. T. L.; Keast, V. J., Mapping chemical and bonding information using multivariate analysis of electron energy-loss spectrum images. <em>Ultramicroscopy </em><strong>2006,</strong> <em>106</em> (11–12), 1024–1032.</p><p>4. Jesse, S.; Kalinin, S. V., Principal component and spatial correlation analysis of spectroscopic-imaging data in scanning probe microscopy. <em>Nanotechnology </em><strong>2009,</strong> <em>20</em> (8), 085714.</p><p>5. Kannan, R.; Ievlev, A. V.; Laanait, N.; Ziatdinov, M. A.; Vasudevan, R. K.; Jesse, S.; Kalinin, S. V., Deep data analysis via physically constrained linear unmixing: universal framework, domain examples, and a community-wide platform. <em>Adv. Struct. Chem. Imag. </em><strong>2018,</strong> <em>4</em>, 20.</p><p>6. Kingma, D. P.; Welling, M., An introduction to variational autoencoders. <em>arXiv preprint arXiv:1906.02691 </em><strong>2019</strong>.</p><p>7. Bepler, T.; Zhong, E.; Kelley, K.; Brignole, E.; Berger, B., Explicitly disentangling image content from translation and rotation with spatial-VAE. <em>Advances in Neural Information Processing Systems </em><strong>2019</strong>, 15409–15419.</p><p>8. Watters, N.; Matthey, L.; Burgess, C. P.; Lerchner, A., Spatial broadcast decoder: A simple architecture for learning disentangled representations in VAEs. <em>arXiv preprint arXiv:1901.07017 </em><strong>2019</strong>.</p><p>9. Batson, J.; Haaf, C. G.; Kahn, Y.; Roberts, D. A., Topological Obstructions to Autoencoding. <em>arXiv preprint arXiv:2102.08380 </em><strong>2021</strong>.</p><p>10. Falorsi, L.; de Haan, P.; Davidson, T. R.; De Cao, N.; Weiler, M.; Forré, P.; Cohen, T. S., Explorations in homeomorphic variational auto-encoding. <em>arXiv preprint arXiv:1807.04689 </em><strong>2018</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=562aa164c59f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-we-learnt-to-love-the-rotationally-invariant-variational-autoencoders-rvae-and-almost-562aa164c59f">How we learnt to love the rotationally invariant variational autoencoders (rVAE), and (almost)…</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>