<?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 Joris C. on Medium]]></title>
        <description><![CDATA[Stories by Joris C. on Medium]]></description>
        <link>https://medium.com/@joris.c?source=rss-ac351149cd48------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*p0wHGFHAbUlmfaM5hW7utQ.jpeg</url>
            <title>Stories by Joris C. on Medium</title>
            <link>https://medium.com/@joris.c?source=rss-ac351149cd48------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:08:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joris.c/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[Physics-Informed Machine Learning — PIML]]></title>
            <link>https://medium.com/@joris.c/physics-informed-machine-learning-piml-debe8f856c10?source=rss-ac351149cd48------2</link>
            <guid isPermaLink="false">https://medium.com/p/debe8f856c10</guid>
            <category><![CDATA[piml]]></category>
            <category><![CDATA[physics-informed-learning]]></category>
            <category><![CDATA[scientific-computing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Joris C.]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 17:55:55 GMT</pubDate>
            <atom:updated>2026-05-21T04:49:48.009Z</atom:updated>
            <content:encoded><![CDATA[<h3>Physics-Informed Machine Learning — PIML</h3><p>A Primer on How to Combine Machine Learning and Physics</p><p>Physics-informed Machine Learning (PIML) is a form of machine learning (ML) where machine learning algorithms are designed to incorporate or discover <strong>laws of physics</strong>. The aim is to either improve their predictive accuracy and generalization beyond what is possible with data alone, or learn new physics from data in the form of equations. It’s an exciting set of machine learning techniques on the <strong>intersection of machine learning and science/engineering</strong>.</p><h4><strong>Contents:</strong></h4><ul><li>Introduction</li><li><a href="https://medium.com/@joris.c/physics-informed-machine-learning-piml-debe8f856c10#e8cd">Physics</a></li><li><a href="https://medium.com/@joris.c/physics-informed-machine-learning-piml-debe8f856c10#c79a">Creating Models with Known Physics</a></li><li><a href="https://medium.com/@joris.c/physics-informed-machine-learning-piml-debe8f856c10#cb5a">Creating Models with Partially Known Physics</a></li><li><a href="https://medium.com/@joris.c/physics-informed-machine-learning-piml-debe8f856c10#77b0">Learning Physics Explicitly</a></li><li><a href="https://medium.com/@joris.c/physics-informed-machine-learning-piml-debe8f856c10#bd6b">Learning Physics Implicitly</a></li><li><a href="https://medium.com/@joris.c/physics-informed-machine-learning-piml-debe8f856c10#0cf1">Any Level of Physics Knowledge — Neural Operators</a></li><li><a href="https://medium.com/@joris.c/physics-informed-machine-learning-piml-debe8f856c10#a1b6">Differentiability &amp;<strong> </strong>Tooling</a></li></ul><h3>Introduction</h3><h4>PIML in short</h4><p>PIML is often presented as lying on the two axes of data-driven and theory-driven methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JvgbcCFdfRDF5wuwb6-KxQ.png" /><figcaption>Fig.: Physics-informed machine learning as a middle ground between pure theory-driven and pure data-driven methods. Inspired by (<a href="https://link.springer.com/chapter/10.1007/978-3-031-60950-3_12">Braga-Neto, 2024</a>).</figcaption></figure><p>Where one end represents traditional Scientific Computing, the other end traditional Machine Learning and PIML being the intermediate.</p><p>Scientific Machine Learning or <a href="https://sciml.ai/roadmap/">SciML</a> is the most used synonym after PIML. It’s aptly named:</p><p><strong>Scientific Machine Learning = Scientific Computing + Machine Learning</strong></p><p>and it’s also the name of the <a href="https://docs.sciml.ai/Overview/stable/">organization</a> responsible for the tools in the <strong>Julia </strong>programming language with this form of machine learning in mind. Their effort is notable because of their built-in compatibility with automatic differentiation (more on that later). Alternative names that are used for PIML are Process-Guided Machine Learning (PGML, <a href="https://www.sciencedirect.com/science/article/abs/pii/S0034425722004928">Wang et al., 2023</a>), Knowledge-Guided ML (KGML, <a href="https://www.routledge.com/Knowledge-Guided-Machine-Learning-Accelerating-Discovery-using-Scientific-Knowledge-and-Data/Karpatne-Kannan-Kumar/p/book/9780367693411">Karpatne et al., 2022</a>) or simply Informed ML (<a href="https://journals.sagepub.com/doi/full/10.1177/09544062231164575">MacKay et al., 2023</a>).</p><p>There are various <strong>reasons</strong> to go for a PIML model (cfr. <a href="https://youtu.be/ARMk955pGbg?list=PLMrJAkhIeNNQ0BaKuBKY43k4xMo6NSbBa&amp;t=662">Brunton</a>):</p><ul><li>Learning new physics</li><li>Capture expensive physics: build surrogate models that strike a better balance of speed and accuracy.</li><li>Capture multi-physics interactions, e.g. through the application of discrepancy modeling</li><li>Update a model with new data</li></ul><p>Additionally, through the accurate modeling of processes and the integration of multi-fidelity models, the application of PIML has the potential to advance the development of <strong>virtual twins</strong>, creating synergistic digital counterparts that closely mirror their real-world counterparts.</p><p>Some <strong>example applications</strong> include:</p><ul><li>Satisfying the Navier-Stokes (NS) equations in fluid dynamics</li><li>Turbulence closure of Reynolds-Average Navier-Stokes (RANS) models (<a href="https://www.osti.gov/servlets/purl/1333570">Ling et al., 2016</a>)</li><li>Weather and climate modeling, e.g. <a href="https://www.axios.com/2024/07/22/google-ai-weather-climate-forecast-model">general circulation models</a> (GCMs)</li><li>Incorporate a radiative transfer model in the domain of remote sensing (<a href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=4664465">Zérah et al., 2023</a>)</li><li>Adhering to chemical processes, such as biogeochemical processes of carbon dynamics (<a href="https://www.nature.com/articles/s41467-023-43860-5#Sec12">Liu et al., 2024</a>)</li><li>Control of HVAC systems in buildings (<a href="https://www.sciencedirect.com/science/article/abs/pii/S0378778823003183">Wang and Dong, 2023</a>)</li></ul><h4>Modeling</h4><p>Machine Learning, Scientific Computing/Physics Simulation and PIML can be further distinguished by the <strong>typical steps</strong> involved in their set-up, input and output. To clarify this, let’s visualize the processes of applying each of these techniques:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*LuUtZy2gyW2X9QvGR-7ohw.png" /><figcaption>Fig.: Traditional Machine Learning &amp; Physics Simulation vs. two types of Physics-Informed ML, each with a different outcome. Note that enforcing already known physics is not necessary for learning physics. Inspired by (<a href="https://www.mdpi.com/2076-3417/13/12/6892">Pateras et al., 2023</a>).</figcaption></figure><p><strong>Machine learning</strong> is applied to training data to get to a predictive model, resulting in inference data, which is relatively easy to get for different inputs. Compare this to <strong>Physics Simulation</strong>, where one must first clearly define the problem (applicable physics, geometry, properties, boundary conditions, …) and apply a solver. This results in simulation data, which is typically more granular than one needs, needing the extraction of performance data. For example, you can think of a CFD simulation where the whole pressure field of a fluid is calculated, but only the pressure drop from inlet to outlet is needed. Moreover, in a standard simulation setup, each new case requires going back to step one, as the inputs might change the physics or a new geometry requiring a new mesh. To get to what I would call a <strong>physics model</strong>, these steps would need to be automated (including a a parametrization of the geometry if relevant). As a result, changes in the input problem can be captured by the model, the available data being only limited to the available computational resources.</p><p><strong>PIML </strong>uses known physics and data as an input. The goal of the ML algorithm is to get either to a <strong><em>better </em>model or learning <em>new</em> physics from data</strong>. What constitutes a better model can vary depending on the application/needs and reference model, but can be higher accuracy, being more generalizable, needing less data, or being computationally less expensive. For the other scenario — learning new physics — enforcing known physics is typically not necessary, but it is certainly an option. The core of both types of algorithms is <strong>synergizing data and physics</strong>. While the first type of algorithms enhances the performance of machine learning models, the second type contributes to a deeper understanding of the underlying physical processes. This opens new avenues for innovation in both AI/ML and science/engineering fields.</p><p>It’s important to <strong>distinguish </strong>more <strong>performant models from neural solvers</strong>. The idea of the former is to enable e.g. surrogate models or reduced order models (ROMs), data assimilation, improved parameter estimation or inverse modeling (infer intrinsic physical parameters or unknown static inputs). The idea of the latter is to employ neural-network-based methods to forward solve e.g. partial differential equations, aiming to <em>replace</em> “traditional” simulation solvers. Apart from (also) needing simulation software for data generation, it’s hard to get right for a broad spectrum of geometries and conditions (e.g. flow regimes) (<a href="https://arxiv.org/pdf/2003.04919.pdf">Willard et al., 2022 </a>). This primer will focus on modeling, though methods like PINNs and neural operators can act both as model and as neural solver. For a broader overview of applications, I recommend (<a href="https://arxiv.org/pdf/2003.04919.pdf">Willard et al., 2022 — Table 1</a>).</p><h4>Forms of PIML</h4><p>This primer will next delve into what physics is considered to bring to ML (which is more broad than just equations) and then further distinguish various forms of PIML. There are three aspects for discerning these methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4yjsb-h1co-cmPKPZQfx_g.png" /><figcaption>Fig.: How to distinguish forms of PIML. Inspired by (<a href="https://arxiv.org/abs/2403.15989">Karpatne et al., 2024</a>).</figcaption></figure><p>This primer will distinguish methods based on the first aspect which is their <strong>type of scientific knowledge</strong>:</p><ol><li>Creating models with known physics</li><li>Creating models with partially known/unknown physics</li><li>Learning Physics: learn physics from data</li></ol><p>On a deeper level, the type of physical system is mostly known and can steer method selection. The physical system can be static vs. dynamic, with more detailed qualifications for dynamical systems like conservative vs. dissipative, chaotic, possibly Hamiltonian or Lagrangian.</p><p>The second aspect is the form of physics-ML integration, which is typically performed with a specific type of final model in mind. This can be an ML model incorporating physics or a physics model leveraging an ML model for specific parts. The last aspect is the method for incorporating physics, also explained in the section below on Physics.</p><p>This primer is heavily inspired by Steve Brunton’s <a href="https://www.youtube.com/playlist?list=PLMrJAkhIeNNQ0BaKuBKY43k4xMo6NSbBa">video lectures</a> on PIML, which got me into the topic myself. His first lectures are organized by their method for incorporating physics. As such, the primer here has a different structure of introducing the topic, providing an opportunity to showcase different takes &amp; examples.</p><h3>Physics</h3><p>Physics encompasses a broad range of principles that govern the natural world, from the subatomic to the cosmic scale. When we talk about incorporating physics into ML, we’re looking at a variety of fundamental concepts, not just equations:</p><ul><li>Conservation: conservation laws reflect the constancy of certain quantities in isolated systems. This includes the conservation of energy, mass, momentum, and charge.</li><li>Symmetry: refers to a system’s property that remains unchanged under certain transformations, such as rotation, reflection, or translation.</li><li>Invariances and equivariances: they are properties of a system that describe how its output changes (or does not change, in the case of equivariances) in response to transformations in its input. An invariant system produces the same output regardless of certain transformations. Examples include time invariance, shift invariance or Galilean invariance.</li></ul><p>This is summarized by the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*_sgr397WFzuCLkAsmJgggA.png" /><figcaption>Principles of Physics-Informed Learning. Inspired by (<a href="https://www.researchgate.net/publication/351814752_Physics-informed_machine_learning">Karniadakis et al., 2021</a>, Fig. 2).</figcaption></figure><p>Predictive models are constructed with assumptions. Specific to physics- informed learning, there are roughly three <strong>pathways </strong>that can be followed separately or in tandem to create these models:</p><ul><li>Observational bias: observational data ought to reflect the underlying physical principles, and can be used as a weak mechanism for embedding these principles into an ML model during its training phase.</li><li>Inductive bias: efforts focused on designing specialized NN architectures that implicitly embed any prior knowledge associated with a given predictive task. It refers to the set of assumptions a machine learning model makes to generalize beyond the observed data.</li><li>Learning bias: related to the preference a learning algorithm has for certain solutions over others. This type of bias can be introduced by the selection of model parameters, loss function (e.g. regularization techniques), or even the algorithm’s structure.</li></ul><p>These 3 types of bias represent the method(s) through which physics is incorporated in ML, and correspond with Brunton’s organization on the topic: data — architecture — loss function — optimization algorithm (note that the learning bias category is split).</p><p>Incorporating the physics above, can bring the following <strong>advantages </strong>to the ML model (<a href="https://arxiv.org/abs/2305.18035">Banerjee et al., 2024</a>):</p><ol><li>Making the ML model both physically and scientifically consistent.</li><li>Model training becomes highly data-efficient, i.e. trainable with fewer data.</li><li>Acceleration of the model training process, such that the models converge faster to an optimal solution.</li><li>Generalization capabilities of the model, such that models can make better prediction for scenarios unseen during the training phase.</li><li>Improvement of transparency and interpretability of models.</li></ol><p>So now that we know what’s encompassed by physics in PIML and what these models can bring, let’s delve into the various models that can be created.</p><h3>Creating Models with Known Physics</h3><p>This section is on models adhering to known physics explicitly and only. The primary method presented here are Physics-Informed Neural Network, also a very popular method. Actually, it is often confused with PIML as a whole. Some other methods such as Hamiltonian Neural Networks (<a href="https://www.youtube.com/watch?v=AEOcss20nDA">HNNs</a>) and Lagrangian Neural Networks (<a href="https://www.youtube.com/watch?v=HLUIx6FqAvg">LNNs</a>) will not be expanded on in this primer.</p><h4>Physics Informed Neural Networks (PINNs)</h4><p>Physics-Informed Neural Networks (PINNs) are an extension of traditional neural networks. They are specifically designed to solve problems governed by differential equations such as partial differential equations (PDEs) or ordinary differential equations (ODEs). This is achieved by adding the residuals of these equations to the <strong>loss function</strong>, ensuring that the learned solution satisfies the governing equations at a set of chosen points. The terms in de differential equation are calculated through backpropagation of the variables of the differential equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MB5m9Hq9r3VNLjYq9WvZFQ.png" /><figcaption>Fig.: schematic of PINNs.</figcaption></figure><p>One of the key advantages of PINNs is their ability to <strong>generalize well even with limited data</strong>, thanks to the incorporation of physical laws which act as strong regularizers. This is nicely shown in this <a href="https://benmoseley.blog/blog/">blog</a>. At the same time, PINNs are known to exhibit several optimization-related failure modes for more complex PDEs, where the PDE-based soft constraints can make the loss landscape highly ill-conditioned and difficult to optimize (cfr. <a href="https://youtu.be/-zrY7P2dVC4?t=1561">Brunton on PINNs</a>). These difficulties become particularly apparent for transport and reaction-diffusion systems, as well as stiff, multiscale, or highly oscillatory problems. Therefore, <strong>optimizer choice</strong> is particularly important for PINNs. Recent work increasingly emphasizes curvature-aware optimizers, such as natural-gradient and quasi-Newton methods, as a key ingredient for stable convergence and accurate PINN solutions (<a href="https://arxiv.org/abs/2604.05230">Jnini et al., 2026</a>).</p><p>There are multiple extension of PINNs. One of the most interesting extensions are <strong>Extended PINNs (XPINNs). </strong>XPINNs are designed to handle <strong>multi-domain</strong> and <strong>multi-scale problems</strong>. In XPINNs, the computational domain is divided into subdomains, and a separate PINN is trained on each subdomain. Information is transferred across XPINN components. This extension allows for parallelization, improved scalability, and increased flexibility in handling problems with different physics or varying levels of complexity across subdomains. An overview even broader than PINNs is given by (<a href="https://arxiv.org/abs/2211.07377">Faroughi et al., 2023</a>).</p><h4>Physics-Encoded Neural Networks</h4><p>Physics-encoded neural networks incorporate prior physical knowledge directly into the <strong>architecture</strong> of the model, rather than adding physics as a penalty term in the loss function. The idea is to restrict the model’s hypothesis space so that certain physical properties are satisfied by construction. These properties can include conservation laws, symmetries, invariances or equivariances (cfr. “fundamental concepts” in <a href="https://medium.com/@joris.c/physics-informed-machine-learning-piml-debe8f856c10#e8cd">Physics</a>). The model’s structure is biased toward functions that are physically admissible.</p><p>A prime example is the <strong>Tensor Basis Neural Network (TBNN)</strong> introduced by (<a href="https://www.cambridge.org/core/journals/journal-of-fluid-mechanics/article/abs/reynolds-averaged-turbulence-modelling-using-deep-neural-networks-with-embedded-invariance/0B280EEE89C74A7BF651C422F8FBD1EB">Ling et al., 2026</a>) for Reynolds-averaged Navier–Stokes turbulence closure. Their model learns the Reynolds stress anisotropy tensor from high-fidelity simulation data, but encodes frame invariance directly into the prediction architecture. Their architecture is depicted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1zSMAmRuXpZkmPyTH0_4Sg.png" /><figcaption>Figure: Tensor Basis Neural Network architecture. Adapted from (<a href="https://www.cambridge.org/core/journals/journal-of-fluid-mechanics/article/abs/reynolds-averaged-turbulence-modelling-using-deep-neural-networks-with-embedded-invariance/0B280EEE89C74A7BF651C422F8FBD1EB">Ling et al., 2016</a>).</figcaption></figure><p>The key idea is to let the neural network learn from scalar quantities that are independent of the coordinate frame, while constructing the tensor output from building blocks that are guaranteed to transform correctly under rotations. In the TBNN, this is implemented with a multiplicative merge layer that combines the learned scalar weights with the tensor basis terms, so the predicted Reynolds stress anisotropy remains physically consistent under coordinate transformations. This paper became influential in fluid mechanics because it showed that deep learning for turbulence closure should not merely fit data, but should respect the geometric and tensorial structure of the governing physics; it helped popularize invariant and equivariant architectures as a serious design principle for machine-learning-based closure models.</p><h3>Creating Models with Partially Known Physics</h3><p>The set of techniques presented here are used when the physics of a system are only partially known or too complex to model entirely from first principles. This is the domain of <strong>hybrid models</strong> and exemplified on the graph below. Hybrid models combine principles from both physics-based (white-box) modeling and data-driven (black-box) approaches. The goal is to leverage the strengths of both methodologies to create a model that is more accurate and generalizable than either approach alone. This kind of models can bridge the gap between theoretical knowledge and empirical observations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*2CmbC0qwuB6BEfElAj1faQ.png" /><figcaption>Hybrid models vs. ML and first principles. Fig. inspired by Steve Brunton’s talk on <a href="https://www.youtube.com/watch?v=7n7xaviepKM&amp;list=PLMrJAkhIeNNQ0BaKuBKY43k4xMo6NSbBa&amp;index=15&amp;ab_channel=SteveBrunton">discrepancy models</a>.</figcaption></figure><h4>Discrepancy modeling</h4><p>Discrepancy modeling involves creating a model that combines theoretical physics-based models with data-driven components to account for unknowns or inaccuracies in the theoretical model. The physics-based part captures what is known, while the data-driven part models the discrepancy between this and observed data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eE1c-8oMLWgO4SN3_t47RA.png" /><figcaption>The discrepancy model is trained based on to correct the difference between physical model estimation and measurement, represented by the green area. This results in in better forecasts, represented by the yellow area. Fig. adapted from (<a href="https://steelelab.me.uw.edu/2023/12/mr-ebers-km-steele-jn-kutz-2024-discrepancy-modeling-framework/">Ebers et al., 2024</a>)</figcaption></figure><p>A practical application of discrepancy modeling is e.g. the work of (<a href="https://arxiv.org/abs/2403.02922">She et al., 2024</a>). It aims to predict biophysical variables such as leaf area index by employing a radiative transfer model (RTM), but applies a so-called bias correction network to account for the systematic bias inherent in the radiative transfer model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9aHsk9ChL01d_s_REwe7g.png" /><figcaption>Fig.: Architecture for estimation of biophysical variables.</figcaption></figure><p>By creating a version of the radiative transfer model that is automatically differentiable — a key feature that underpins backpropagation by enabling the efficient calculation of gradients — and coupling this to a NN that also exhibits this property, allows to compute gradients efficiently and accurately. On its turn, this enables the solution of the inverse problem for determining the biophysical variables.</p><h4>Universal Differential Equations (UDEs)</h4><p>Universal Differential Equations (UDEs) integrate neural networks into classical differential equations. While the structure of the differential equations represents the known physics, the neural networks can approximate the unknown parts. This hybrid approach is flexible, enabling the model to learn from data where the physics are not fully understood.</p><p>An application of UDEs is in modeling glacier ice flow (<a href="https://gmd.copernicus.org/articles/16/6671/2023/gmd-16-6671-2023.pdf">Bolibar et al., 2023</a>), showcasing how they can be utilized in environmental science. A glacier can be modeled using a diffusion equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*6BtXyuIXOFJAPOL7SPB6ZQ.png" /></figure><p>with H the glacier height, b the surface mass balance, D the diffusion coefficient and S the glacier surface. Without going into details, the interesting features of this equation is that S originates from remote sensing data, while the diffusion coefficient is represented by a neural network. The neural network is trained with glacier data as well as climate data. This enables the diffusion equation to better reflect the glacier dynamics.</p><p>The capability for UDEs is well developed in Julia, also being used int the work on glacier dynamics. It offers an opportunity for a.o. a new generation of geophysical models leveraging remote sensing data.</p><h4>Gray-Box Learning of Equations</h4><p>Whereas the focus of previous two models types was on creating models representing unknown physics only, there are approaches to learn equations of missing physics as well. This kind of approach forms the middle ground between other hybrid models and learning physics (cfr. next section). An example work is from (<a href="https://arxiv.org/abs/2305.10706">Kiyani et al., 2023</a>), with its approach depicted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*9iROTrikWuhrhsD6_YGx1Q.png" /><figcaption>Fig.: Simplified figure from (<a href="https://arxiv.org/abs/2305.10706">Kiyani et al., 2023</a>).</figcaption></figure><p>Without going in depth, the goal is to predict F(U):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*iAkRzvXVTU2a4A_5sTMGuw.png" /></figure><p>First, two PINNs are trained to predict Û and F(Û) from the input. Next, a symbolic regression is applied to U and F(Û) to determine F(U). The study leverages the strengths of neural networks to learn from data while keeping the resulting models grounded in the physical reality.</p><h3>Learning Physics Explicitly</h3><p>Learning physics through machine learning involves techniques that can discern underlying physical laws from data. <strong>Symbolic regression</strong> is a prime method in this domain. Unlike traditional regression that fits predefined equations to data, symbolic regression searches the space of mathematical expressions to find the equation that best describes the data, guided by concept of parsimony. A <a href="https://www.statisticshowto.com/parsimonious-model/">parsimonious model</a>, as described in statistical modeling, is one that accomplishes the desired level of explanation or prediction with as few predictor variables as possible, avoiding overfitting and promoting generalizability.</p><p>The concept of <strong>parsimony </strong>is crucial in symbolic regression within Physics-Informed Machine Learning (PIML) because it aligns with the scientific principle of Occam’s Razor: the simplest explanation, or the one with the fewest assumptions, is often preferred. This approach not only aids in discovering the most efficient representation of the physical laws governing the data, but also helps in ensuring the interpretability and transferability of the learned models.</p><h4>Symbolic Regression</h4><p>Symbolic expressions can be represented by so-called binary expression trees:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*cY_XmY7J8Z7dn8Hvdk2Kng.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Expression_tree">Expression tree</a> as it can be used in symbolic regression to represent a function.</figcaption></figure><p>Which makes them amenable to optimization with genetic algorithms e.g. (<a href="https://www.computer.org/csdl/journal/tb/2018/01/07707365/13rRUwhHcPr">Vyas et al., 2018</a>). An alternative representation would be through neural networks, so-called parsimonious neural networks (<a href="https://www.nature.com/articles/s41598-021-92278-w">Desai &amp; Strachan, 2021</a>), the work in question being able to recover a a melting law. As symbolic regression is a <strong>combinatorial problem</strong> (it’s actually NP hard), there’s a scientific quest to innovate beyond these approaches.</p><p>Apart from SINDy, which is excellently <a href="https://www.youtube.com/watch?v=NxAn0oglMVw&amp;list=PLMrJAkhIeNNQ0BaKuBKY43k4xMo6NSbBa&amp;index=10">explained</a> by its creator Steve Brunton, an interesting recent approach is Φ-SO from (<a href="https://iopscience.iop.org/article/10.3847/1538-4357/ad014c">Tenachi et al., 2023</a>). They constrain the search space to include equations which are balanced in terms of their <strong>physical units</strong> only. Otherwise, the equation is simply nonsensical, irrespective of whether it gives a good fit to the numerical values of the data. The authors benchmark their algorithm Φ-SO vs. other symbolic regression frameworks, and apply theirs to astrophysical case studies. One of the nice features is that it can recover the expression of the relativistic energy of a particle as well as its classical approximation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*TNab3wgqaJqFEk4wMdpI9w.jpeg" /><figcaption>Pareto front encoding accuracy-complexity trade-off of recovered physical formulae by Φ-SO. Φ-SO recovers the relativistic expression as well as the classical approximation. Figure from (<a href="https://iopscience.iop.org/article/10.3847/1538-4357/ad014c">Tenachi et al., 2023</a>)</figcaption></figure><p>Thereby illustrating the balance of expression error vs. complexity, cfr. the discussion of parsimony above.</p><h4>Distilling a Symbolic Representation from Neural Networks</h4><p>As an alternative to symbolic regression, a compelling approach involves the distillation of symbolic representations from neural networks (<a href="https://arxiv.org/abs/2006.11287">Cranmer et al., 2020</a>). This method is adept at interpreting specific datasets, such as the trajectories of simple particles shown in the figure, by employing Graph Neural Networks (GNNs).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*u4ZoC1NYDf5jBkPEiFvz2A.png" /><figcaption>Learning a symbolic equation through a GNN. Excerpt of a figure by (<a href="https://arxiv.org/abs/2006.11287">Cranmer et al., 2020</a>)</figcaption></figure><p>These networks excel in predicting dynamics by considering the interactions between particles as a graph, where nodes represent particles and edges encapsulate their interactions. By encoding physics-informed constraints, such as encouraging low-dimensionality representations, GNNs can learn the underlying dynamics efficiently. Subsequently, the learned representations can be translated into symbolic equations, like the known spring law depicted. This approach can be applied to systems where the <strong>interactions can be modeled in a graph-like structure</strong>, such as celestial objects or even the distribution of matter in the universe.</p><h4>Frameworks</h4><p>Frameworks for learning physics, such as <a href="https://www.youtube.com/watch?v=df43V4OjMVs&amp;list=PLMrJAkhIeNNQ0BaKuBKY43k4xMo6NSbBa&amp;index=20">PySR</a>, are still developing. Major discoveries like the recent <a href="https://www.linkedin.com/posts/johnwsanders_a-canonical-hamiltonian-formulation-of-the-activity-7180610249106579458-t3io/">Hamiltonian form</a> of Navier-Stokes were still performed analytically. Nevertheless it would be awesome to recover this from data only.</p><h3>Learning Physics Implicitly</h3><p>The goal of this type of model is to learn the physics implicitly rather than explicitly. The model learns to represent the system’s dynamics or underlying physical behavior through its architecture and data-driven training. The physical laws are encoded within the model’s weights, latent spaces, or outputs, but they are not explicitly represented as equations or formulae. This makes them not directly interpretable. Actually, strictly seen, they aren’t part of PIML as they do not incorporate physics. Nevertheless, the model can make accurate predictions and generalizations based on learned dynamics.</p><p>This section discuss Variational autoencoders and neural implicit flow (NIF), while skipping neural ODEs (<a href="https://www.youtube.com/watch?v=nJphsM4obOk">NODEs</a>), which are a type of neural solver.</p><h4>VAE</h4><p>Variational Autoencoders (VAEs) are a type of generative model particularly useful for modeling dynamical physical systems. A VAE consists of encoder and decoder networks with a latent space in between (<a href="https://lilianweng.github.io/posts/2018-08-12-vae/">Weng, 2018</a>). They map high-dimensional data, such as spatiotemporal phenomena (e.g. fluid flows), to a lower-dimensional latent space. This latent space acts as a Reduced Order Model (ROM), capturing the essential dynamics of the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPf9j_w3WI_VItjsqVGiUQ.png" /><figcaption>VAE for preduction of dynamical systems such as a Von-Karman Vortex Street. The solver can be a neural network itself, such as an LSTM or Transformer. Fluid flow image from <a href="https://en.wikipedia.org/wiki/Fluid_dynamics#/media/File:T%C3%BAnel_de_viento,_v%C3%B3rtice_de_Von_Karman.gif">Wikipedia</a>.</figcaption></figure><p>The decoder in a VAE can generate new instances of physical states by sampling from the latent space. These samples are generated based on the initial state through neural network architectures suitable for temporal predictions, such as long short-term memory (LSTM) networks, resulting in a fast surrogate model for e.g. fluid-flow predictions (<a href="https://www.nature.com/articles/s41467-024-45578-4">Solera-Rico et al., 2024</a>).</p><h4>Neural Implicit Flow (NIF)</h4><p>Neural Implicit Flow (NIF) is a neural network-based technique designed to handle high-dimensional spatio-temporal data by learning a low-rank, mesh-agnostic representation. This approach is designed to deal with variable geometries and sparse or non-uniform data. As shown below, it consists of two parts:</p><ul><li>A ShapeNet which is responsible for capturing and representing the spatial complexity of the data</li><li>A ParameterNet which handles additional complexities beyond just the spatial structure. It accounts for parametric dependencies, temporal evolution, and any other external inputs or conditions that influence the system.</li></ul><p>An illustrative application of NIF is in the reconstruction of sea surface temperatures (SSTs) from sparse sensor measurements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*xxrEDSq_DlGDz6rthnZBgw.png" /><figcaption>Fig.: Neural Implicit Flow framework. Figure inspired by (<a href="https://arxiv.org/abs/2204.03216">Pan et al., 2023</a>)</figcaption></figure><h3>Any Level of Physics Knowledge — Neural Operators</h3><p>Neural Operators (NO) are a class of neural networks designed to learn mappings between function spaces, i.e. to approximate operators that act on functions. Unlike traditional neural networks, which map finite-dimensional vectors to vectors, neural operators take entire functions (or fields) as input and produce functions as output. This makes them particularly well suited for tasks such as solving partial differential equations (PDEs).</p><p>Neural operators are implemented through specific architectures, often referred to as operator networks. The most prominent examples include DeepONet (the original formulation), Fourier Neural Operators (FNOs), and Graph Neural Operators (GNOs). A key advantage of these models is that they are typically designed to be resolution-invariant or at least resolution-flexible, allowing them to generalize across different discretizations. This is an important benefit compared to approaches such as PINNs.</p><h4>Fourier Neural Operators</h4><p>Let’s take a closer look at the Fourier Neural Operator (FNO), illustrated below. The architecture consists of multiple Fourier layers stacked sequentially. As shown in the figure, each Fourier layer combines a global spectral operation with a local linear transformation. The input is first transformed to the frequency domain using a Fourier transform (𝓕), where a learned spectral filter (R) is applied to a subset of Fourier modes. The result is then transformed back to physical space using the inverse transform (𝓕⁻¹). In parallel, a pointwise linear transformation (W) is applied in physical space. Then, both contributions are combined, followed by a nonlinear activation function (σ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGxFl8qDDdAl8FcEA4m0cQ.png" /><figcaption>Fig.: FNO with a) Architecture of the FNO. b) Fourier Layer. Source: (<a href="https://arxiv.org/pdf/2010.08895">Li et al., 2021</a>).</figcaption></figure><p>This combination of global spectral convolution and local transformations is what allows FNOs to efficiently model complex, multi-scale physical systems. An example application is machine learning-based weather prediction (<a href="https://developer.nvidia.com/blog/modeling-earths-atmosphere-with-spherical-fourier-neural-operators/">Bonev et al., 2023</a>), where Spherical Fourier Neural Operators have been applied.</p><p>In environmental science applications, particularly in weather and ocean modeling, neural operator-based models often exhibit instability during <strong>autoregressive long rollouts</strong>, i.e. when predictions are iteratively fed back as inputs over extended time horizons (e.g. beyond ~2 weeks). This behavior is commonly linked to difficulties in accurately capturing and preserving high-frequency, small-scale dynamics that are essential in <strong>turbulent systems</strong>. Traditionally, this has been attributed to <strong><em>spectral bias</em></strong>: the tendency of neural networks to learn low-frequency components more readily than high-frequency ones. However, these instabilities can be mitigated, as illustrated for example in OceanNet (<a href="https://www.nature.com/articles/s41598-024-72145-0">Chattopadhyay et al., 2024</a>) and recent work by (<a href="https://arxiv.org/abs/2602.19265">Khodakarami et al., 2026</a>).</p><h4>Graph Neural Operators</h4><p>While Fourier Neural Operators are highly effective on structured grids, many real-world scientific simulations are defined on <strong>irregular meshes or unstructured geometries</strong>. In CFD and finite-element simulations, the physical domain is typically discretized into a computational mesh consisting of connected cells or nodes. Different simulations of the same physical system may use different mesh resolutions or connectivity patterns. Graph Neural Operators (GNOs) extend neural operator learning to such settings by representing the computational domain as a graph, allowing information to propagate along mesh connectivity rather than through regular grid operations such as Fourier transforms. This makes GNOs particularly relevant for engineering and scientific applications involving complex geometries.</p><p>Recent graph neural operator architectures have explored combining local graph interactions with global spectral representations to improve PDE learning on irregular domains and unstructured meshes. An example is the Spatio-Spectral Graph Neural Operator (Sp²GNO) proposed by (<a href="https://arxiv.org/abs/2409.00604">Sarkar and Chakraborty, 2024</a>), which combines spatial and spectral graph neural networks to capture both short- and long-range dependencies in large-scale simulations. More recently, the Gauge-Invariant Spectral Transformer (GIST) was proposed by (<a href="https://arxiv.org/abs/2603.16849">Rigotti et al., 2026</a>) as a scalable graph neural operator designed to remain robust across different mesh discretizations. By reducing sensitivity to numerical variations in spectral graph representations, GIST improves the transfer of learned operators between coarse and fine meshes while maintaining scalable performance on very large graphs. Although still recent, GIST represents a promising direction toward discretization-invariant neural operators for large-scale mesh-based simulations.</p><h3>Differentiability &amp; Tooling</h3><p>Differentiability is a critical property in Physics-Informed Machine Learning (PIML). The ability to efficiently compute gradients enables the training of models that not only fit data but also respect physical laws, such as through physics-driven loss functions in Physics-Informed Neural Networks (PINNs). This property also facilitates optimization tasks, such as finding the best set of model parameters, or performing model inversion to estimate unknown variables.</p><p>While neural networks are inherently differentiable, many scientific computing tools and models are not, which is where <strong>automatic differentiation (AD)</strong> plays a vital role. AD is a computational technique that calculates exact derivatives (gradients) automatically, ensuring both accuracy and efficiency in gradient computations, even for complex functions.</p><p>Several tools facilitate differentiability by supporting automatic differentiation:</p><ul><li>Julia: Julia is a high-performance programming language well-suited for scientific computing. It provides native support for automatic differentiation through libraries like Zygote.</li><li>PyTorch (PT): PyTorch is as a deep learning framework includes strong support for automatic differentiation through its autograd module.</li><li>JAX: JAX is a Python library designed for high-performance numerical computing, specializing in differentiable programming. It offers automatic differentiation and is highly optimized for complex simulations, such as <a href="https://medium.com/@hghcomphys/why-you-should-learn-jax-a-molecular-dynamics-showcase-f7e79b58be01">molecular dynamics</a>.</li></ul><h3>Conclusion</h3><p>Having introduced Physics-Informed Machine Learning (PIML) in this primer, I encourage you as a reader to look around for how it can be applied in your field. Whether it is for the creation of better models (most likely) or learning physics from data (hard but not impossible), the scientist within you will find inner peace for knowing that your model will not spew out unphysical nonsense, but actually satisfying fundamental principles and laws that govern our universe. Your models can thus be trusted to yield (more) realistic, reliable predictions that can stand up to rigorous scientific validation.</p><p>While neural solvers were not discussed in depth in the primer, they are one of the most exciting research directions. Perhaps we will be able to have a foundation model for physics (<a href="https://arxiv.org/html/2402.12652v1">Ye et al., 2024</a>) or learn latent physics at scale (<a href="https://arxiv.org/abs/2403.17728">Zhou and Farimani, 2024</a>). Imagine resolving <a href="https://www.tiktok.com/@openai/video/7339740660116835627">Sora’s falling glass</a> with Physics Informed Generative Networks.</p><h3>Additional Resources</h3><p>This section contains some additional resources not cited in the primer.</p><h4>General</h4><ul><li>Book: <a href="https://x.com/eigensteve/status/1718004606901666063?lang=en">Data-Driven Science and Engineering</a> by Brunton &amp; Kutz (free download)</li><li>Book: Machine Learning in Modeling and Simulation (<a href="https://link.springer.com/book/10.1007/978-3-031-36644-4">Rabczuk &amp; Bathe, 2023</a>)</li><li>Informed machine learning methods for application in engineering: A review (<a href="https://journals.sagepub.com/doi/full/10.1177/09544062231164575">MacKay et al., 2023</a>)</li><li>Papers: <a href="https://www.linkedin.com/feed/update/urn:li:activity:7129518136218800128/">list</a> of Holger Marshall with several important works</li></ul><h4>Software</h4><ul><li>Optimizers for PINNs: <a href="https://github.com/CrunchOptimizer/PINNs">https://github.com/CrunchOptimizer/PINNs</a></li><li><a href="https://github.com/SMTorg/SMT">Surrogate Modeling Toolbox</a></li><li>Surrogate Modelling: <a href="https://developer.nvidia.com/physicsnemo">NVIDIA PhysicsNeMo</a></li><li>Uncertainty Quantification: <a href="https://github.com/Crunch-UQ4MI/neuraluq">NeuralUQ</a></li><li><a href="https://www.linkedin.com/posts/holger-marschall_datadriven-machinelearning-engineering-activity-7253363024982339584-faOF?utm_source=share&amp;utm_medium=member_desktop">List</a> of Holger Marshall with several important works</li></ul><h4>Environmental Science</h4><ul><li>Differentiable modeling to unify machine learning and physical models and advance Geosciences (<a href="https://arxiv.org/abs/2301.04027">Shen et al., 2023</a>)</li></ul><h4>Fluid Dynamics</h4><ul><li>Book: <a href="https://www.google.be/books/edition/Data_Driven_Fluid_Mechanics/9d2iEAAAQBAJ">Data-Driven Fluid Mechanics</a></li><li>Machine Learning for Fluid Dynamics (<a href="https://www.annualreviews.org/content/journals/10.1146/annurev-fluid-010719-060214">Brunton et al., 2020</a>).</li><li>Emerging Trends in Machine Learning for Computational Fluid Dynamics (<a href="https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&amp;arnumber=10124114">Vinuesa and Brunton, 2022</a>)</li><li>Enhancing computational fluid dynamics with machine learning (<a href="https://www.nature.com/articles/s43588-022-00264-7">Vinuesa and Brunton, 2022</a>); also on <a href="https://arxiv.org/abs/2110.02085">arXiv</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=debe8f856c10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Python for Data Science: Strategies for Reducing Memory Footprint]]></title>
            <link>https://python.plainenglish.io/optimizing-python-for-data-science-strategies-for-reducing-memory-footprint-e55dcc4aa2f8?source=rss-ac351149cd48------2</link>
            <guid isPermaLink="false">https://medium.com/p/e55dcc4aa2f8</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Joris C.]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 05:45:31 GMT</pubDate>
            <atom:updated>2026-02-23T11:10:22.069Z</atom:updated>
            <content:encoded><![CDATA[<p>Unlocking Efficiency: Techniques and Best Practices for Memory Management in Python Projects</p><p><strong>Updated</strong> in 2026 for the use of Memray as memory profiler.</p><h3>Introduction</h3><p>In the world of data science, the efficiency of your Python code is not just about speed but also about how much memory your program uses. This is crucial because every machine has a finite amount of memory, and exceeding this limit can lead to problems such as crashing Jupyter kernels, necessitating a restart, or Apache Spark jobs failing due to memory errors. Understanding the memory footprint of your operations is essential to prevent these issues and ensure your data processing tasks run smoothly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*kWQQqU3Hi7y0kvQ_DJ6pzw.png" /><figcaption>Fig.: memory (represented by green bars) is being efficiently filled with data (depicted in red). Memory is often a constraining resource in the light of large data sets.</figcaption></figure><p>The focus on this article is mainly on processing <strong>numeric </strong>data, which means NumPy will be mentioned a lot, but also Xarray. Xarray extends NumPy’s capabilities to labeled, multi-dimensional arrays. Nevertheless the principles outlined are more broadly applicable and where relevant, frameworks like e.g. pandas will also pop up in the examples given.</p><h4>Space-time trade-off</h4><p>The space-time trade-off or the trade-off between computational efficiency and memory footprint is a well-recognized concept in computer science. This trade-off implies that in many algorithms and data processing tasks, improving the speed (time complexity) of an operation can require more memory (space complexity), and vice versa: reducing memory usage can lead to slower performance. Some examples of space-time trade-offs include caching (vs. on-the-fly generation), data compression and hash tables vs. search trees.</p><p>Some of the strategies outlined below will trade computational efficiency for lower memory requirements, while others are a gain without giving in on efficiency. A prime example of the former is chunking, while an example of the latter is in-place operations in NumPy.</p><h3>Strategies</h3><h4>Data Types and Their Memory Needs</h4><p>Different data types have different memory requirements, and understanding these can help you make better choices in your code. Below is a table for the memory usage of common <strong><em>numeric </em>data types</strong> available in Python’s NumPy. These are various integer and floating point data types with a different number of bits used to represent them. Practically, this means you can save up till a factor 8 through the representation of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DFWtwXN9_PJASBLU-CQl9g.png" /><figcaption>Table 1: Memory usage for different numeric data types; 8 bits = 1 byte. A <a href="https://numpy.org/doc/stable/reference/arrays.scalars.html#sized-aliases">full list</a> is in NumPy’s docs.</figcaption></figure><p>Apart from integers and floats, NumPy also has data types unsigned integers (positive numbers) with the same number of bits as integers (e.g. uint8). The advantage is an extended range (2^nb_bits-1) vs. the inability to represent negative values.</p><p>Note that float16 also exists, but is not listed above, as hardware support for its operations is limited (primarily GPU’s) and not typically used for data science projects.</p><p>The data type for an array can be set at three stages:</p><ol><li><strong>Initialization </strong>of the variable: upon initialization of an array, for example with zeros, it is possible to specify the data type with an optional argument (dtype).</li><li><strong>Calling a function</strong> on a variable: several functions allow specifying the data type (dtype) as an optional argument, for example in NumPy’s sum or mean functions.</li><li><strong>Explicit casting</strong> after an operation: several NumPy functions perform <em>hidden upcasting</em> during computation. A prominent example is np.median, which returns at least float64, regardless of the input dtype, including when overwrite_input=True is specified. Although you may deliberately choose compact data types, NumPy may internally promote data to larger types for numerical stability or correctness. This can temporarily or permanently increase memory usage beyond what is strictly necessary for your application.<br>If the additional precision or range is not required, the result can be cast back to a smaller dtype using .astype(...). Note, however, that intermediate computations will still use the larger dtype, meaning peak memory usage is unaffected by post hoc casting.<br>Another example is np.bincount, which typically operates using int64, even when the input array has a smaller integer dtype (e.g. uint8). If avoiding this upcasting is critical for memory reasons, the only reliable solution is to implement a custom equivalent tailored to a specific dtype (ask a chatbot or coding agent).</li></ol><p>Additionally, to reduce intermediate memory usage, you might want to <strong>cast <em>before</em> an operation</strong> instead of after. So for example when dividing a uint array by 10000 — which will result in an intermediate array of dtype np.float64 — and casting it at the end:</p><p>float32_array = (uint16_array/10000).astype(np.float32)</p><p>Casting it before the operation will result in a float32 array:</p><p>float32_array = (uint16_array.astype(np.float32)/10000)</p><p>At the expense of a slightly less accurate result. The choice of float64 (double precision) vs. float32 (single precision) represents the typical trade-off of accuracy vs. memory consumption (and speed, though this is often less important).</p><p>So <strong>representing data as integers</strong> can potentially reduce memory requirements vs. floats. However, there are 2 caveats:</p><ol><li><strong>Overflow</strong>: if numbers are added or subtracted beyond the range of the data representation, the numbers will <a href="https://numpy.org/doc/stable/user/basics.types.html#overflow-errors">overflow</a> into another value without explicitly giving an error. This can be tricky especially with uints. Note that the default behavior of NumPy is not giving an error, but it is much easier to recognize with floats because they also accommodate -inf and inf.</li><li><strong>NaN values</strong>: floats can accommodate NaN values, making them suitable for certain types of data science operations. Packages like NumPy and Xarray have built-in methods (like np.nansum) or arguments (Xarray’s skipna).</li></ol><p>While overflow generally requires care during programming (and validation/testing), it’s possible to work around NaN values in integer data types by NumPy’s <a href="https://numpy.org/doc/stable/reference/maskedarray.html">masked array</a> module. The masked array can be incredibly efficient as it holds your data separate from a boolean mask, so it not need to copy data upon creation. Note that Xarray does not have similar functionality.</p><p>In Python, it’s very much possible to <strong>inadvertently change data types</strong>: Python’s dynamic typing makes it an easy language to program in, but this flexibility can change the data representation without you knowing. For example, using xarray.where can change data types when the input values are incompatible. Specifically, replacing parts of an array of integer values by NaN will convert its type to float, or replacing values in a boolean array (e.g. a mask) by 0 will convert it to int. It&#39;s essential to be aware of these dynamics to write memory-efficient code — it’s a good idea to check the data type of resulting variables if you set it somewhere in the code.</p><h4>Broadcasting, In-Place Operations and Views</h4><p>Numpy, a cornerstone library in the Python data science ecosystem, offers features like broadcasting and in-place operations that can significantly reduce memory usage.</p><p><a href="https://numpy.org/doc/stable/user/basics.broadcasting.html"><strong>Broadcasting</strong></a><strong> </strong>is a mechanism that allows NumPy to perform operations on arrays of different shapes as if they were compatible shapes, without actually copying data. While some broadcasting operations are handled under the hood — like multiplying a single number by an array, others need to be explicitly handled:</p><p>broadcasted_array = np.broadcast_to(array, shape)</p><p>Which makes the broadcasted_array compatible with the input shape, provided the number of dimensions of <em>array</em> is compatible with <em>shape — </em>if not, use np.newaxis or np.expand_dims to overcome this.</p><p>Broadcasting is closely tied to <strong>vectorization</strong>, as both optimize and simplify operations on arrays or matrices. However, it should be emphasized that it can be smarter to have your data vectorized, but execute some steps in (a) <strong>loop</strong>(s) if these steps are memory-intensive. A good example here is the pairwise distance calculation between multidimensional vectors, as the necessary memory for a vectorized implementation scales O(nb_vectors²).</p><p><strong>In-place operations</strong>, using Numpy’s out argument, allow you to perform operations and store the results in an existing array, rather than creating a new one:</p><pre>import numpy as np<br><br>first_array = np.ones0,0, dtype=&#39;uint8&#39;)<br>second_array = 2*np.ones(0,0, dtype=&#39;uint8&#39;)<br><br>np.subtract(first_array, second_array, out=first_array)</pre><p>The last line is equivalent to:</p><p>first_array -= second_array</p><p>In-place operations introduce a new balance: (intermediate) memory usage vs. readability. Take for example this code:</p><p>array_norm = (array_norm/10000 — mean)/standard_dev</p><p>Writing this with in-place operations leads to the following code:</p><pre>array_norm /= 10000<br>array_norm -= mean<br>array_norm /= standard_dev</pre><p>Which is harder to read than the original, single line of code. A solution to this is moving this to a separate function normalize_array_in_place. Using the in-place sequence of operations avoids storing both the old and new versions of array_norm intermediately in memory. This directly modifies array_norm without creating intermediate copies for each operation.</p><p>However, it&#39;s worth noting that not all operations support the out parameter; for example np.where does not. Moreover, confusingly, where’s <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html">documentation</a> does specify ‘out’ as the parameter that is returned. An alternative to where is to use np.place for in-place modifications, at least if the values to be placed are maximum 1-D (the most common use case):</p><pre>arr = np.arange(6).reshape(2, 3)<br><br>np.place(arr, arr&gt;2, [44, 55])<br><br>print(arr)<br><br># Result:<br>array([[ 0,  1,  2],<br>       [44, 55, 44]])</pre><p>Additionally, some functions support an <strong><em>overwite_input</em></strong> parameter, using the memory of the input array for intermediate operations, at the expense of not preserving the contents of the input array. Example functions include the median and several other statistics functions in NumPy.</p><p>Lastly, a nuanced understanding of how NumPy handles data <strong>subsets </strong>vs. other libraries helps deciding how to operate on data. NumPy often creates ‘views’ rather than copies when slicing arrays (e.g., subset = array[:, 0:3, :, :]). This behavior is a boon for memory efficiency, as views operate on the same data buffer as the original array, avoiding the need for additional memory allocation.</p><p>Conversely, Xarray tends to return copies of the data when performing similar slicing operations using methods like .sel(). So while Xarray&#39;s approach enhances flexibility and convenience—by allowing for more complex data selections and maintaining rich metadata—it can also lead to increased memory usage. This is another manifestation of the trade-off between memory efficiency and readability, or alternatively the usability features provided by higher-level libraries.</p><h4>Deleting Variables</h4><p>A way to explicitly control memory usage is by deleting variables that are no longer needed, freeing up the memory space they occupy. This is done using the del statement. For instance, after using a large data structure in part of your code, you can explicitly delete it once it’s no longer required, by using:</p><p>del large_data_structure</p><p>However, it’s important to note that Python automatically cleans up local variables when exiting a function. This means that intermediate variables, which are used temporarily within a function to store data or computation results, are automatically deleted once the function execution is completed, and the function’s scope is exited. This makes that explicit deletion with del is not usually necessary for these local variables.</p><h4>Efficient Data Structures</h4><p>Choosing the right data structure can greatly impact your program’s memory efficiency. This includes sets vs. lists, sparse matrices and data storage formats, for example .csv vs. .parquet.</p><p><strong>Sets</strong> can be more memory-efficient than lists when storing a collection of unique items. They are designed for fast membership testing, as sets in Python are implemented as hash tables. Lists are ordered collections and can contain duplicate elements. Their memory consumption increases linearly with the number of elements, and looking up items by value has a time complexity of O(n).</p><p><strong>Sparse matrices</strong> can dramatically reduce memory usage when working with data that contains a lot of zeros. They can significantly lower the memory footprint compared to dense matrices. However, sparse matrices are not supported by NumPy, but by scipy and <a href="https://sparse.pydata.org/en/stable/">Sparse</a>. In order to save memory you need at least 33% sparsity, and for computational efficiency the threshold is roughly 1% sparsity (at least for <a href="https://stackoverflow.com/a/36971131">scipy</a>).</p><p>Relatedly, considering the <strong>format in which data is stored</strong> and accessed is crucial, exemplified by the comparison between CSV and Parquet:</p><ul><li>CSV files are simple, text-based formats for storing tabular data. Each line in a CSV file corresponds to a row in the table, with commas separating individual cells. The entire dataset is often loaded into memory, which can be inefficient for large datasets.</li><li>Parquet is a columnar storage file format optimized for use with big data processing frameworks. Parquet files can be read into memory more efficiently than CSV files. They support efficient compression and encoding schemes, which significantly reduce the memory footprint of large datasets. Moreover, because Parquet is columnar, it allows for more efficient querying and loading of specific columns into memory, rather than the entire dataset.</li></ul><h4>Generator Expressions</h4><p>Generator expressions provide a way to perform lazy evaluation, meaning they compute values on the fly and don’t store the entire dataset in memory. They are related to <a href="https://wiki.python.org/moin/Generators">generator functions</a>; instead of the yield keyword, you use parentheses:</p><p>x_squared = (x*x for x in range(10))</p><p>Allowing for efficient iteration over large datasets without a significant memory footprint.</p><p>Unlike generator expressions, most Numpy operations are eagerly evaluated and can consume substantial memory for large arrays. For managing memory more efficiently with Numpy-like operations, libraries such as Dask offer lazy evaluation, deferring computation until necessary, thereby reducing the memory usage. Dask will be discussed further in the next section.</p><h4>Chunking</h4><p>For handling very large datasets that cannot fit into memory, chunking is a powerful technique. Libraries like <strong>Dask </strong>offer built-in support for chunking, processing datasets in smaller, manageable chunks. Dask arrays can be created from NumPy arrays, but Xarray supports automatic chunking of data into Dask arrays under the hood:</p><pre>import xarray as xr<br><br># Open a dataset and automatically chunk it<br>#    into pieces of size 100x100 for each dimension<br>ds = xr.open_dataset(&#39;example.nc&#39;,<br>        chunks={&#39;time&#39;: 100, &#39;latitude&#39;: 100, &#39;longitude&#39;: 100})<br><br># Perform a computation<br># This is done lazily using dask, with calculations performed on chunks<br>mean_temp = ds[&#39;temperature&#39;].mean(dim=&#39;time&#39;)<br><br># To trigger computation and get the result<br>result = mean_temp.compute()</pre><p>Dask can process these chunks in parallel across available CPU cores or even distributed across multiple machines in a cluster. Dask achieves these parallel computing capabilities through constructing and executing a task graph, leveraging lazy evaluation in the process. The task graph represents the sequence of operations to be applied to the data. Hence, optimizing expressions such as the normalize_array_in_place presented above is considered useless.</p><p>Pandas also supports chunking through its chunksize parameter when reading large files, enabling more memory-efficient data processing:</p><pre>import pandas as pd<br><br># Read a large CSV file in chunks of 10000 rows at a time<br>chunksize = 10000<br>for chunk in pd.read_csv(&#39;large_file.csv&#39;, chunksize=chunksize):<br>    # Process each chunk<br>    process(chunk)</pre><h4>Pre-allocation</h4><p>Pre-allocation of variables is a technique that primarily impacts performance, rather than directly reducing the memory footprint of a Python program. However, it can indirectly influence memory efficiency and overall program optimization in several ways. Pre-allocation involves defining size and data type:</p><p>x = np.zeros((3, 20, 30), dtype=np.float32)</p><p>Pre-allocation facilitates predictable memory usage, ensuring that the memory required for data structures, is allocated at once, rather than incrementally. This can reduce memory fragmentation and potentially make more efficient use of memory over time, as the program doesn’t need to repeatedly ask the operating system for more memory as the data structure grows. As such, pre-allocation can also significantly improve the performance of your code.</p><p>That said, pre-allocating simple lists:</p><p>l = [None]*100</p><p>is <a href="https://www.reddit.com/r/learnpython/comments/hxf1nd/is_it_really_best_practice_to_preallocate_lists/">probably a bad idea</a>.</p><h4>Memory Profiling</h4><p>Understanding where your program uses memory is the first step toward optimizing it. Tools for memory profiling in Python can help you identify memory-intensive parts of your code, guiding your optimization efforts. By regularly profiling your code, you can make informed decisions about where to focus your efforts to reduce memory usage.</p><p><a href="https://github.com/bloomberg/memray">Memray</a> is a high-performance memory profiler for Python that traces native memory allocations, including those originating from C extensions. It provides detailed analytical outputs such as flamegraphs, summaries, and allocation tables, enabling precise inspection and optimization of memory-heavy code paths.</p><p>You can profile a script with Memray as follows:</p><pre>python -m memray run -o memray.bin your_script.py<br><br># Generate flamegraph<br>python -m memray flamegraph memray.bin<br><br># Generate summary<br>python -m memray summary memray.bin</pre><p>This workflow produces a memray.bin trace file, along with a flamegraph report and a summary of allocation statistics. These reports provide clear insight into where memory is allocated and how it accumulates during execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h40yurjYpZwxRST-ZxKhjA.png" /><figcaption>Example of a Memray flamegraph. Source: <a href="https://raw.githubusercontent.com/bloomberg/memray/refs/heads/main/docs/_static/images/flamegraph_example.png">Memray</a>.</figcaption></figure><h3>Conclusion</h3><p>Writing memory-efficient Python code for data science is crucial for handling large datasets and preventing program failures due to memory errors. By understanding and applying <strong>techniques </strong>like:</p><ul><li>Careful selection of data types</li><li>Leveraging NumPy’s broadcasting, in-place operations and views</li><li>Deleting intermediate variables</li><li>Employing generator expressions</li><li>Utilizing efficient data structures</li><li>Chunking large datasets</li><li>Pre-allocation</li><li>Regular memory profiling</li></ul><p>You can significantly reduce the memory footprint of your data science applications.</p><p><strong>Package</strong>-wise, for processing numeric data, pure NumPy can be made very efficient. Dask can further enhance this, being able to chunk data for parallel processing. It will also create a task graph representing the sequence of operations (making in-place operations obsolete) and thus enabling lazy evaluation. Xarray offers increased usability, also in combination with Dask, at the expense of memory-efficiency.</p><p>Often, optimizing memory footprint means there is a price to pay in other terms; 3 <strong>balances </strong>were introduced:</p><ul><li>Space-time trade-off</li><li>Memory footprint vs. accuracy</li><li>Memory footprint vs. readability/usability</li></ul><p>The last price to pay is your development time, so don’t go all-in and write <em>del </em>statements everywhere in your code, but focus on the most effective method on reducing the memory peak. Remember, the goal is not just to make your code run faster, but to make it run smarter, using the resources available in the most efficient way possible.</p><p>Or get your boss to pay for more computational resources.</p><h4>Additional Resources</h4><p>For those interested in a broader perspective, especially regarding object-oriented programming in Python and memory management, you can explore additional resources such as this <a href="https://medium.com/@sumana.dotnettricks/delete-variable-in-python-a-comprehensive-guide-f7ea35c34636">article on deleting variables</a> and <a href="https://nitesh-yadav.medium.com/optimize-coding-techniques-in-python-memory-management-8e470111d79a">this article</a>, which also covers garbage collection and context managers. This article did not zoom in on using context managers for file operations (with statement) as this is assumed standard practice.</p><p>For more background information, also on computational efficiency, you can check <a href="https://www.manning.com/books/software-engineering-for-data-scientists">MEAP’s</a> <strong>book </strong>“Software Engineering for Data Scientists” by Andrew Threadway, specifically chapters 6–8:</p><ul><li>Chapter 6 is on computational efficiency. Note that pandas can also represent data through <a href="https://pandas.pydata.org/docs/user_guide/pyarrow.html">PyArrow</a> instead of NumPy. For parallelization, you can also consider <a href="https://superfastpython.com/threadpoolexecutor-vs-processpoolexecutor/">ThreadPool or ProcessPool</a>.</li><li>Chapter 7 is on memory usage and efficiency, the topic of this article. The focus is more on pandas than on NumPy.</li><li>Chapter 8 is on parallel &amp; distributed processing. Note that the use of Dask and PySpark are not mutually exclusive — i.e. you can use Dask in a PySpark cluster.</li></ul><h4>Bonus: Advanced Indexing</h4><p>If you reached this point, it must mean that you are in for a bonus item :)<br>Numpy’s <a href="https://numpy.org/doc/stable/user/basics.indexing.html#advanced-indexing">advanced indexing</a> or <a href="https://jakevdp.github.io/PythonDataScienceHandbook/02.07-fancy-indexing.html">fancy indexing</a> can be a way to vectorize your code, for example when performing a <a href="https://stackoverflow.com/questions/18702746/reduce-a-dimension-of-numpy-array-by-selecting">dimensional reduction</a>, like selecting variables across one axis of multidimensional data:</p><pre># Arrays with random data<br>array = np.randn(10, 100, 200)<br>indices = np.randint(0, high=10, size=(100,200))<br><br># Get the coordinates of the 2D array<br>x, y = np.meshgrid(np.arange(indices.shape[0]), np.arange(<br>    indices.shape[1]), indexing=&#39;ij&#39;)<br><br># Apply advanced indexing<br>result = array.values[indices, x, y]</pre><p>So the result has a shape of 100x200, with data being selected from the input array according to indices. Note that this feature is not available in Xarray; you will have to access the underlying data using .data or .values and create an Xarray out of the result.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e55dcc4aa2f8" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/optimizing-python-for-data-science-strategies-for-reducing-memory-footprint-e55dcc4aa2f8">Optimizing Python for Data Science: Strategies for Reducing Memory Footprint</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Foundation Models in Computer Vision: A Kaleidoscope of Possibilities]]></title>
            <link>https://medium.com/@joris.c/foundation-models-in-computer-vision-a-kaleidoscope-of-possibilities-64ac85f6ff90?source=rss-ac351149cd48------2</link>
            <guid isPermaLink="false">https://medium.com/p/64ac85f6ff90</guid>
            <category><![CDATA[foundation-models]]></category>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[vlm]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[multimodal]]></category>
            <dc:creator><![CDATA[Joris C.]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 19:15:19 GMT</pubDate>
            <atom:updated>2023-11-28T13:31:59.295Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog post will delve into foundation models in the area of computer vision, though in a broad sense, looking at models that have an image as one of the inputs next to e.g. text. Foundation models are trained on a large-scale broad data, and once trained, they operate as a basis and can be adapted (e.g., fine-tuned) to a wide range of downstream tasks related to the original trained model (<a href="https://crfm.stanford.edu/report.html">Bommasami et al., 2021</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUKAV0mfWM2hkevaur96BA.png" /></figure><p>The contribution of this blog is three-fold:</p><ol><li>Present current models in the framework of (<a href="https://arxiv.org/pdf/2307.13721.pdf">Awais et al., 2023</a>)</li><li>For each model, clarify which task(s) it solves, and explain those tasks.</li><li>Point to the latest research, organized by the type of model.</li></ol><p>The framework is shown below and separates models in 4 categories:</p><ul><li>Traditional models, or models with image input only</li><li>Textually prompted models, or Vision Language Models (VLMs)</li><li><a href="#fad6">Visually prompted models</a>, of which Meta’s Segment Anything Model (SAM) is the most prominent example</li><li>Heterogeneous models, or models of which images are one of the possible input modalities.</li></ul><p>The figure also presents some milestone models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-tyYRp5bjLz2wR6a0hesSw.png" /><figcaption>Fig. 1: Evolution of FMs in CV (<a href="https://arxiv.org/pdf/2307.13721.pdf">Awais et al., 2023</a>)</figcaption></figure><p>Let’s go through each type of model.</p><h3>Traditional Models</h3><p>Traditional methods have an <strong>image-only input</strong> and are employed for classification, object detection and segmentation. The state of the art typically consists of a transformer architecture trained with a self-supervised learning (SSL) method. <strong>Transformers </strong>enable the modeling of global spatial dependencies across the entire image (<a href="https://arxiv.org/abs/2010.11929">Dosovitskiy et al., 2021</a>), and e.g. improve generalizability to different resolution imagery in remote sensing (<a href="https://www.mdpi.com/2504-446X/7/2/93">Gilbert et al., 2023</a>). The dominant architecture is the vision transformer or ViT architecture; a broader range of designs and task-specific designs is surveyed by (<a href="https://arxiv.org/abs/2111.06091">Liu et al., 2022</a>).</p><p>On top of the transformer architecture, <strong>SSL methods</strong> allow leveraging unlabeled data to improve generalization capabilities. A good overview of image-based SSL was written by (<a href="https://openreview.net/pdf?id=Ma25S4ludQ">Ozbulak et al., 2023</a>). Additionally, the recently released <a href="https://arxiv.org/pdf/2304.12210.pdf">Cookbook of SSL</a> gives a more general overview of SSL; note that the families it distinguishes are named differently w.r.t. the image-focused paper. Nevertheless, it’s clear Yann LeCun was already brewing more improved methods when writing the cookbook — he was involved in both the recently release <a href="https://ai.meta.com/blog/yann-lecun-ai-model-i-jepa/">I-JEPA</a> method as well as <a href="https://arxiv.org/abs/2308.00566">stochastic locations</a> for masked image modelling (MIM).</p><p>Nevertheless, high-performance <strong>convolutional networks</strong> such as <a href="https://magazine.sebastianraschka.com/p/ahead-of-ai-4-a-big-year-for-ai">ConvNeXt</a> pretrained via supervised learning outperform transformers-based architectures and self-supervised learning on multiple tasks. This is the conclusion of the recent “Battle of the Backbones” study by (<a href="https://arxiv.org/pdf/2310.19909.pdf">Goldblum et al., 2023</a>). The observed superiority of supervised pretraining occurs because such models are often trained on larger datasets. In apples-to-apples comparisons on the same dataset scale, SSL models outperform their supervised counterparts. Additionally, ViTs are more sensitive to the amount of pretraining data and the number of parameters than CNNs.</p><p>An overview on <strong>segmentation </strong>is written by (<a href="https://arxiv.org/abs/2301.07499">Wang et al., 2023</a>); a more specific survey on transformers for segmentation is by (<a href="https://arxiv.org/pdf/2304.09854.pdf">Li et al., 2023</a> — cfr. 3.3 and 4.3 of previous work). They start from a DETR-like meta-architecture and review the key techniques and distinguish models according to their method and associated possible tasks (cfr. Table 3). An interesting highlight is <a href="https://magazine.sebastianraschka.com/p/ahead-of-ai-10-state-of-computer#%C2%A7mask-dino-towards-a-unified-transformer-based-framework-for-object-detection-and-segmentation">Mask DINO</a>, which is a <strong>unified framework</strong> for both object detection and segmentation.</p><p>An exciting recent work on segmentation is the GOSS model (<a href="https://link.springer.com/article/10.1007/s00371-023-02925-8">Hong et al., 2023</a>), which introduces and performs “<strong>generalized open-set semantic segmentation</strong>”, cfr. image below. It is basically the combination of open set segmentation and generalized segmentation (cfr. SAM). The goal is to recognize both known and unknown objects and provide segmentation masks for all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Nss2Hpg7_HPdpFTR.png" /><figcaption>Fig. 2: Different tasks of image segmentation. For a given input image <strong>a</strong> that contains both known (“person”, “dog” and “vegetation”) and unknown objects (“sheep”, “rail” and “grass”), are shown: <strong>b</strong> open-set semantic segmentation (OSS) by pixel identification, <strong>c</strong> generic segmentation (GS) by pixel clustering, and <strong>d</strong> generalized open-set semantic segmentation (GOSS). Image from (<a href="https://link.springer.com/article/10.1007/s00371-023-02925-8">Hong et al., 2023</a>)</figcaption></figure><h3>VLMs</h3><p>Vision Language Models (VLMs) or textually prompted models as on Fig. 1, take in an image and a text, but are prompted by the text input. Two milestones here are OpenAI’s CLIP model and the Flamingo model. Whereas the CLIP-type model lacks the ability to generate language (e.g. for visual question answering, cfr. (<a href="https://arxiv.org/abs/2204.14198">Alayrac et al., 2022</a>)), it ended up to be a much-used component in CV models. On its turn, the Flamingo model set the stage for models including an LLM, hereafter called generative VLMs.</p><h4>CLIP and CLIP-like models</h4><p>CLIP stands for Contrastive Language-Image Pre-training. CLIP’s key contribution is its ability to map data of different modalities, i.e. text and images, into a shared embedding space. This shared multimodal embedding space enables tasks such as zero-shot classification, (simple) captioning and image search/retrieval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ey0BnF06oNlDSFmq-JzwlA.png" /><figcaption>Fig. 3: CLIP’s contrastive pretraining stage resulting in a shared embedding space (<a href="https://openai.com/research/clip">OpenAI</a>).</figcaption></figure><p>One of the most recent model leveraging CLIP is <strong>RAM or Recognize Anything Model</strong>. Its goal is image tagging, i.e. predicting multiple image labels for one image. It surpasses older models in recognition, but does not perform localization within the image. However, it can perfectly <strong>pair with SAM</strong>, which we will revisit later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3sBdvLT7zkp2KI-zICNv9w.png" /><figcaption>Fig. 4: Model capabilities in terms of localization vs recognition, further divided by accuracy and scope. (<a href="https://arxiv.org/pdf/2306.03514.pdf">Zhang et al., 2023</a>)</figcaption></figure><p><strong>Referring Expression Object Detection/Segmentation</strong></p><p>Although not based on CLIP, <strong>Grounding DINO</strong> (<a href="https://arxiv.org/abs/2303.05499">Liu et al., 2023</a>) was inspired by it and performs various objects detection tasks. It was built for open-set detection (i.e. tested on objects not seen during training), but outperformed GLIP and other competitors for closed-set, open-set, and referring object detection by significant margins. Closed-set OD is the reverse of open-set OD, where the categories are known during training and testing. Referring object detection is a task where the model is given a natural language description or a referring expression, and it has to detect the object based on it. Just like RAM, it <strong>pairs well with SAM</strong>, which we will come back to in the section on SAM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*O0PzJyTG-6nvOnvAd0Knrg.png" /><figcaption>Fig. 5: Overview of Grouding-DINO’s capabilities (<a href="https://arxiv.org/abs/2303.05499">Liu et al., 2023</a>)</figcaption></figure><p>The state of the art model for the equivalent segmentation task or Referring Expression Segmentation task is <a href="https://openaccess.thecvf.com/content/CVPR2023/papers/Liu_GRES_Generalized_Referring_Expression_Segmentation_CVPR_2023_paper.pdf">GRES</a>. At the same time, they introduce a new Generalized Referring Expression Segmentation task, which supports expressions indicating an arbitrary number of target objects. This can include multi-target and no-target expressions.</p><p><strong>Open Vocabulary Object Detection/Segmentation</strong></p><p>In open vocabulary detection/segmentation, the model is designed to detect objects across a wide and potentially open-ended range of categories, even those not seen during training. OVOD/OVS combines the challenges of both zero-shot learning and the open-set task. The term “open vocabulary” implies that the set of object categories can be expanded or is not strictly defined. Note that it does not mean that text is an input; the integration of natural language descriptions or user-defined categories is a potential option. This makes OVOD a comprehensive framework that addresses the broader challenge of detecting a wide variety of objects in an open-world scenario.</p><p>The reference for <strong>OD </strong>is <strong>OWL-ViT </strong>(<a href="https://arxiv.org/abs/2205.06230">Minderer et al., 2022</a>), employing a CLIP-based training recipe. For <strong>segmentation</strong>, the current state of the art is <strong>OVSeg </strong>(<a href="https://openaccess.thecvf.com/content/CVPR2023/papers/Liang_Open-Vocabulary_Semantic_Segmentation_With_Mask-Adapted_CLIP_CVPR_2023_paper.pdf">Liang et al., 2023</a>), being based on a Mask-adapted CLIP, a version trained with masked inputs (Cfr. Fig. 4 of (Awais et al., 2023) for an overview of CLIP and its variants). Lastly, there’s <a href="https://www.marktechpost.com/2023/09/26/revolutionizing-panoptic-segmentation-with-fc-clip-a-unified-single-stage-artificial-intelligence-ai-framework/?utm_source=pocket_reader"><strong>FC-CLIP</strong></a>, a model for OV <strong>panoptic segmentation</strong> — a form of segmentation that combines both instance and semantic segmentation. An overview of models for OVOD and OVSS is given by (<a href="https://arxiv.org/pdf/2306.15880.pdf">Wu et al., 2023</a>).</p><h4>Generative VLMs</h4><p>After CLIP, a significant step was taken by Flamingo, created by Google. It coupled a frozen (i.e. unmodified) vision encoder and frozen large language model (LLM) in a way similar to the architecture below, though the structures bridging the modalities (image and language) were more complex. Most commonly in this type of models, the modality or vision encoder is CLIP. The use of the LLM gave VLMs true generative capabilities. This improved captioning performance and enabled so-called Visual Question Answering (<strong>VQA</strong>), basically chatting about images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*kBQat9e9kLVYpZ5Qc7N2MQ.png" /><figcaption>Fig. 6: architecture of a VLM, using a projection layer to bridge the modality gap. Image drawn by author, inspired by (<a href="https://arxiv.org/pdf/2309.16058.pdf">Moon et al., 2023</a>)</figcaption></figure><p>Of course, the most accessible model is OpenAI’s GPT-4V, though it being closed source, we have no idea about its actual architecture. Nevertheless, the report by Microsoft (<a href="https://arxiv.org/pdf/2309.17421.pdf">Yang et al., 2023</a>) is an interesting read. One of the most <a href="https://github.com/BradyFU/Awesome-Multimodal-Large-Language-Models/tree/Evaluation#evaluation-results">capable</a> open source models is the new version of <a href="https://llava-rlhf.github.io/"><strong>LLAVA</strong></a>, which actually has the architecture displayed above. It is also one of the few models trained with reinforcement with human feedback (RLHF), the type of training that improves performance, and reduces hallucinations and toxicity.</p><p>The above conversational VLMs are generally not adept at visual grounding tasks and their standout capability is to reason about holistic images (<a href="https://arxiv.org/pdf/2307.13721.pdf">Awais et al., 2023</a>). A unique work in this regard is <strong>LISA</strong>, as presented below, which is a VLM extended with a vision backbone (actually SAM) to perform segmentation when prompted to do so. It outperforms <a href="https://github.com/microsoft/X-Decoder">X-Decoder</a> (of this category) and SEEM (of the next category) on the referring segmentation task. Additionally, it proposed the <strong>reasoning segmentation</strong> task, which is to output a mask given a complex and implicit query text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GQ1XAsghS4NfVvqQ3uZ4-Q.png" /><figcaption>Fig. 7: Architecture of LISA (<a href="https://arxiv.org/pdf/2308.00692.pdf">Lai et al., 2023</a>)</figcaption></figure><h3>Visually Prompted Models</h3><p>This type of models expects an image and (preferably) a visual prompt (bounding box or points), or a textual prompt; most models allow for multiple prompt types. The output varies depending on the model, with masks ranging from semantic or instance masks to general masks (SAM). There are 4 important models in this category: ClipSeg, SegGPT, SAM and SEEM. The other models are mostly a derivative of SAM. We will go through the first 3, and then take a look at SEEM and other architectures building on SAM. The models presented here are especially interesting for <strong>assisted labeling</strong> applications. Several of the <a href="https://docs.autodistill.com/base_models/groundedsam/">models</a> presented here are available on Roboflow’s python package <a href="https://blog.roboflow.com/autodistill/">autodistill</a>.</p><h4>Zero- &amp; Few-shot Segmentation</h4><p><a href="https://www.width.ai/post/what-is-clipseg">CLIPSeg</a> is a model for semantic segmentation that segments images using the text prompts or prototype images you provide. It is built for <strong>referring segmentation</strong>, which is to segment an image based on text prompts or a reference image. The former is called referring expression segmentation; the latter referring image segmentation. It performs zero-shot segmentation when provided with a text prompt, and one-shot by showing it a prototype image. While novel, CLIP is not designed for learning pixel-level information as it is focused on global features (<a href="https://arxiv.org/pdf/2307.13721.pdf">Awais et al., 2023</a>).</p><p>Next up is <a href="https://arxiv.org/pdf/2304.03284.pdf">SegGPT</a>, a model that unifies solving diverse segmentation tasks such as semantic segmentation, instance segmentation, part segmentation, even for special scenarios like aerial images. It can perform few-shot segmentation or uses in-context examples to provide masks, which is basically equivalent to one-shot segmentation. A practical example of using it is also on <a href="https://blog.roboflow.com/package-detector/">Roboflow</a>.</p><p><a href="https://arxiv.org/abs/2304.02643v1">Segment Anything Model</a> or <a href="https://www.width.ai/post/text-guided-open-vocabulary-segmentation">SAM</a> outputs a mask based on a (set of) point(s), bounding box(es), mask(s) or text input. SAM actually performs interactive segmentation, returning general segmentation masks; though choosing your input well means you can so semantic and/or instance segmentation in practice. Interactive Segmentation involves a user to guide the segmentation process based on bounding boxes, points, scribbles, or other cues. SAM’s performance with text prompts is weaker though as compared to the visual prompts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*HbkHL5H-dKII1iA-NMA2hg.png" /><figcaption><em>Fig. 8: SAM promptable segmentation (Source: </em><a href="https://arxiv.org/abs/2304.02643v1"><em>Kirillov et al.</em></a><em>)</em></figcaption></figure><p>There are a few things to know about its operation. First, it actually output 3 masks at different granularity, but most implementations show only 1. Second, it can also operate in a automatic mode by providing it a grid of points for the image, though you obviously have little control over the result. This is what’s used under the hood if you do not provide it any input. Last, in this automatic mode, it will generally add a significant part of the image to a background mask, which might not always be that interesting fir your application.</p><h4>Universal Segmentation</h4><p>Universal segmentation refers to the process of accommodating various<br>types of human prompts and tackling different segmentation tasks. There are 2 capable models in this area: SEEM and Semantic SAM.</p><p><a href="https://github.com/UX-Decoder/Segment-Everything-Everywhere-All-At-Once">SEEM</a> or Segment Everything Everywhere All at Once offers an interface for generic segmentation tasks as well as referring and interactive segmentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ovLtxIx0agZWX-DInmn2Iw.jpeg" /><figcaption>Fig. 9: SEEM’s input (bottom) vs. output (top) possibilities (<a href="https://github.com/UX-Decoder/Segment-Everything-Everywhere-All-At-Once">Source</a>).</figcaption></figure><p>The other model is <a href="https://github.com/UX-Decoder/Semantic-SAM">Semantic-SAM</a>, which aims to segment and recognize anything a any scale. It offers similar capabilities as SEEM, on top of being able to output up to 6 granularity masks. It was created by first reproducing SAM as a subtask, as well as going going beyond it in terms of granularity abundance, semantic awareness and quality, in order to arrive at universal segmentation.</p><h4>Grounding SAM</h4><p>It did not take long after SAM was released to combine it with other new, capable models in order to provide it visual grounding. This was done by IDEA Research, and they called it <a href="https://github.com/IDEA-Research/Grounded-Segment-Anything">Grounded-Segment Anything</a>. The first version of their model connects Grounding Dino with SAM, such that users prompt it with text, and segment everything based on it the generated bounding boxes of Grounding Dino. An example is presented below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kq5oUuFvs1RHafZ5.png" /><figcaption>Fig. 10: Grounding SAM with Grounding-DINO (<a href="https://github.com/IDEA-Research/Grounded-Segment-Anything">Source</a>)</figcaption></figure><p>The variant with <a href="https://github.com/SysCV/sam-hq">HQ-SAM</a> is currently actually at the top of the Segmentation in the Wild <a href="https://eval.ai/web/challenges/challenge-page/1931/leaderboard/4567">Leaderboard</a> (at least for zero-shot).</p><p>The second version they released is RAM-Grounded-SAM, which actually does not need any inputs by prepending RAM to the chain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q9uHaIE5EsOb99a-.png" /><figcaption>Fig. 11: Grounding SAM with RAM (<a href="https://github.com/IDEA-Research/Grounded-Segment-Anything">Source</a>).</figcaption></figure><h3>Heterogeneous Models</h3><p>This category contains models that an take in multiple types of input and have multiple types of output. It consists of 3 subcategories, namely generalist models, Multimodal Large Language Models (MLLMs, cfr. Image Bind) and embodied models. The last type will not be discussed here; instead it will be handled in a future post on agents.</p><h4>Generalist Models</h4><p>This set of models is aimed at solving a diverse range of vision tasks, broader than e.g. segmentation. They differ in how the task is defined, and what the output is. The first, <a href="https://arxiv.org/abs/2212.02499">Painter</a>, perform tasks ranging from segmentation to denoising or image enhancement, whereby its input is an image along with a set of another image and the “solution” for that image, effectively enabling in-context visual learning — similar to SegGPT, which is actually based on Painter.</p><p>Next is <a href="https://github.com/NVlabs/prismer">Prismer</a>, a model that employs a Mixture of Exports (MoE, basically a specific foundation model for each task) to perform segmentations, OCR, edge detection etc. as the input to a cross-modal module of an LLM. This way, users can generate captions or start a conversation on the input image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1TkpHg8B1mlsNTQD.png" /><figcaption>Fig.: Prismer’s architecture (<a href="https://github.com/NVlabs/prismer">Source</a>)</figcaption></figure><p>Last are the models that employ an LLM to do task orchestration, i.e. letting the LLM distribute the task to the correct vision model. Examples are <a href="https://arxiv.org/abs/2305.11175">VisionLLM</a> and Microsoft’s <a href="https://github.com/microsoft/TaskMatrix">TaskMatrix</a>/VisualGPT. While the tasks it can handle are more broad than a VLM, its performance on vision-language tasks worse as information is lost when crossing modalities.</p><h4>MLLM</h4><p>The term Multi-modal Large Language Model (MLLM) has been reserved in this text to distinguish models that take at least 3 different modalities as an input — text, image and at least one other. Sometimes, VLMs are also referred to as MLLMs. In this regard, an important model is Meta’s <a href="https://ai.meta.com/blog/imagebind-six-modalities-binding-ai/">ImageBind</a> and its recent successor <a href="https://arxiv.org/pdf/2309.16058.pdf">AnyMAL</a>. While ImageBind used images as the central modality, AnyMAL switches this to text and has an architecture such as LLAVA’s as show above in Fig. 6. This AnyMAL’s output is text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YTXhfo5O3itcUUBFUYTsJw.gif" /><figcaption>Fig. : ImageBind binds 7 modalities taking images as the central modality (<a href="https://ai.meta.com/blog/imagebind-six-modalities-binding-ai/">Source</a>).</figcaption></figure><p>The multimodal capabilities were taken one step further by <a href="https://github.com/NExT-GPT/NExT-GPT">NexT-GPT</a>, a model described as a Any-to-Any MLLM. As with AnyMAL, the modalities are bridged by projection; actually, it uses ImageBind for the input side before projecting. The interesting idea here is to use the LLM’s output as an input to diffusion models to generate an answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FcQzxfpZv9WCHFqdoDmi-Q.png" /><figcaption>Fig. : Taking input of and outputting multiple modalities as per Next-GPT (<a href="https://github.com/NExT-GPT/NExT-GPT">Source</a>).</figcaption></figure><p>A unique model more related to is Ferret, which offers the capability to prompt about an image using text, as well as points and masks on top of being able to ground its output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zos4F3OIAh9x1EzmfkNYWw.png" /><figcaption>Fig. 15: Referring and grounding capabilities for MLLMs (<a href="https://arxiv.org/pdf/2310.07704.pdf">You et al., 2023</a>)</figcaption></figure><p>It is work such as Ferret and LISA that pave the way for the more broad application of VLMs in pure vision tasks.</p><h3>Conclusion</h3><p>This blog <strong>categorized </strong>models that take images as <strong>input </strong>into traditional, textually prompted, visually prompted and heterogeneous models. The <strong>output </strong>of the traditional models and the visually prompted models are regular vision outputs (e.g. masks), while the textually prompted models output text and the heterogeneous models can basically output anything.</p><p>As for future, I see a <strong>positive feedback loop</strong> with models feeding on model data (cfr. how SAM‘s dataset), enabling <strong>domain-specific models</strong> as well as further <strong>generalization.</strong> The generalization entails being able to handle more or more abstract tasks. This includes VLMs performing pure vision tasks.</p><h3>Resources</h3><p>A shortlist of comprehensive resources on the subject:</p><ul><li><a href="https://arxiv.org/pdf/2307.13721.pdf">Foundation models in Vision</a>, by (Awais et al., 2023)</li><li><a href="https://huyenchip.com/2023/10/10/multimodal.html">Chip Huygen’s blog post</a> on LMMs: focusses on VLMs and MLLMs</li></ul><h3>Appendix 1: SSL</h3><p>This appendix lists the equivalent sections of the vision-focused overview of SLL methods from (<a href="https://openreview.net/pdf?id=Ma25S4ludQ">Ozbulak et al., 2023</a>) to the more general <a href="https://arxiv.org/pdf/2304.12210.pdf">Cookbook of SSL</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FNMoff3QjZ-Q5mKgea0-4g.png" /></figure><h3>Appendix 2: Tasks</h3><p>This sections lists all the tasks mentioned for each category. It is not meant to be an exhaustive list of all possible tasks for each category.</p><p><strong>Traditional Models</strong>:</p><ul><li>Classification</li><li>Object detection</li><li>Segmentation</li><li>Generalized open-set semantic segmentation: combines open set segmentation and generalized segmentation. The goal is to recognize both known and unknown objects and provide segmentation masks for all; recently introduced by GOSS (<a href="https://link.springer.com/article/10.1007/s00371-023-02925-8">Hong et al., 2023</a>).</li></ul><p><strong>VLMs</strong>:</p><ul><li>Zero-shot classification</li><li>Captioning</li><li>Image search/retrieval</li><li>Image tagging: multi-label classification (cfr. RAM)</li><li>Open-set Object Detection: The categories during testing were not seen during training.</li><li>Closed-set Object Detection: categories are known during training and testing.</li><li>Referring Expression Object Detection/Segmentation: the model is given a natural language description or a referring expression, and it has to detect the object based on it.</li><li>Generalized Referring Expression Segmentation: Same as RES, but supports expressions indicating an arbitrary number of target objects.</li><li>Open Vocabulary Object Detection/Segmentation: the tasks to detect objects across a wide and potentially open-ended range of categories, even those not seen during training. It is more difficult than open-set OD/segmentation.</li><li>Reasoning Segmentation; introduced by LISA (<a href="https://arxiv.org/pdf/2308.00692.pdf">Lai et al., 2023</a>).</li></ul><p><strong>Visually Prompted Models</strong>:</p><ul><li>Referring Segmentation: cfr. above, though referring segmentation can be referring expression segmentation (segmentation based on text) or referring image segmentation (based on a prototype image).</li><li>General Segmentation: the segmentation mask of outputting masks without further meaning, i.e. not tied to an object or instance.</li><li>Interactive Segmentation: a segmentation task where user interaction is involved to guide or refine the segmentation process. The interaction can be in the form of bounding boxes, points, scribbles, or other cues.</li><li>Universal Segmentation: the process of accommodating various<br>types of human prompts and tackling different segmentation tasks.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64ac85f6ff90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to land a job after your first AI course]]></title>
            <link>https://medium.com/@joris.c/how-to-land-a-job-after-your-first-ai-course-88f199344c7c?source=rss-ac351149cd48------2</link>
            <guid isPermaLink="false">https://medium.com/p/88f199344c7c</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science-training]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[learning-and-development]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Joris C.]]></dc:creator>
            <pubDate>Mon, 03 Jul 2023 07:34:34 GMT</pubDate>
            <atom:updated>2025-05-05T12:07:54.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VdMqKMx3EEPmd1Vg3xDQ6w.jpeg" /></figure><p>It has been a few months since I finished my first course on AI (from <a href="https://www.mygreatlearning.com/mit-data-science-and-machine-learning-program">MIT</a>), and I wanted to share what I’ve been doing to secure a job in Data Science/Machine Learning. Despite being an Engineer in Computer Sciences, it has been rather rough for me finding a job in the field. The main goal of this article is to show you what’s out there, and what you can do to get the job you <em>really</em> want.</p><h3>Choose your role</h3><p>Choose a role you want to go for. Are you a Data Scientist or a Machine Learning Engineer? What is the subject you are specialized in: computer vision, LLMs, … ?</p><p>It also pays off to get to know other possible roles, to get a better grip on the system. These are the roles I see:</p><ul><li>Data Engineer</li><li>Data Analyst</li><li>Data Scientist</li><li>AI/ML Engineer</li></ul><p>The trend I see is that all of these domains are getting more mature and trending more to general software development and software development best practices.</p><p>This post will largely focus on the Data Scientist and AI/ML Engineer roles, though its principles are certainly expandable to the other roles.</p><h3>Keep on Learning</h3><p>I know it sounds cliché, but there were quite some subjects I was not aware of after finishing my first course. It goes from broadly applied <a href="https://neptune.ai/blog/mlops-tools-platforms-landscape">MLOps</a>, to <a href="https://www.simplilearn.com/spark-vs-hadoop-article">Apache Spark</a> and more specific topics like <a href="https://learn.microsoft.com/en-us/training/paths/ai-edge-engineer/">edge computing</a>.</p><p>At the same time, be <strong>selective</strong>, as topics like <a href="https://huggingface.co/learn/deep-rl-course/unit0/introduction?fw=pt">reinforcement learning</a> are very interesting, but its application quite niche. For RL, this is mainly applied in the context of LLMs (for fine-tuning) and robotics (together with imitation learning). It is also applied in games, with DeepMind having a strong presence, but the approach has limits when there’s an open world and there aren’t clear “rules”, cfr. this <a href="https://arstechnica.com/ai/2023/06/they-plugged-gpt-4-into-minecraft-and-unearthed-new-potential-for-ai/">Minecraft agent</a>.</p><p>Subjects like <strong>computer vision</strong> kinda require a separate course (though a lot are outdated, if you have a good recommendation let me know!). <strong>LLM</strong>’s are so fresh the <a href="https://a16z.com/2023/06/20/emerging-architectures-for-llm-applications/">ecosystem</a> is limited, but evolving quite fast. Here, again, beware of more general NLP courses, as a lot of NLP techniques (apart from sentiment analysis with BERT) have become irrelevant —<a href="https://www.coursera.org/learn/generative-ai-with-llms"> Coursera’s</a> is a great one. The commonality between these two fields is the importance of <a href="https://d2l.ai/chapter_attention-mechanisms-and-transformers/index.html">Transformers</a> and how they upended existing techniques in both fields.</p><p>For any application, it pays off to have an overview of <strong>relevant models</strong> for a specific, as fine-tuning is becoming more and more common. You will find there is a trend to <a href="https://towardsdatascience.com/supervised-semi-supervised-unsupervised-and-self-supervised-learning-7fa79aa9247c">self-supervised learning</a> (SSL), of which <a href="https://towardsdatascience.com/paper-explained-dino-emerging-properties-in-self-supervised-vision-transformers-f9386df266f1">DINO</a> is an excellent example, able to combine SSL and Transformers.</p><p>In any case, several domains are evolving fast, and <strong>keeping up to date</strong> with the latest developments is important. Find your ‘system’ or websites that you use. For me, that’s a combination of <a href="https://arstechnica.com/">Ars Technica</a> and <a href="https://support.google.com/websearch/answer/2819496">Google Discover</a> (trained on Medium and MarkTechPost). In this regard, one of the biggest innovations in recent months is Facebook’s <a href="https://huggingface.co/facebook/sam-vit-huge">Segment Anything</a> model. This has already been incorporated in labeling software to speed up preprocessing.</p><h3>Master Python</h3><p>Most of your code-writing will happen in Python, so be sure to master both the standard library and any relevant packages.</p><p>In the standard library, <a href="https://docs.python.org/3/library/typing.html">type hints</a> is a more recent addition. It’s also very useful for <a href="https://realpython.com/python-data-classes/">data classes</a>. For parallelization, <a href="https://superfastpython.com/threadpoolexecutor-vs-processpoolexecutor/">ThreadPool or ProcessPool</a> can be interesting. Lastly, I recommend scrolling through the standard library <a href="https://docs.python.org/3/library/">documentation</a> to get a sense of what is available. This will help you write more compact and more efficient code, for example leveraging the <a href="https://docs.python.org/3/library/collections.html#counter-objects">Counter object</a> for rapid tallies of collections.</p><p>For each domain, there several relevant packages; a selection of these is:</p><p>Data Science:</p><ul><li><a href="https://towardsdatascience.com/pandas-2-0-a-game-changer-for-data-scientists-3cd281fcc4b4">Pandas 2.0</a></li><li>Fairness: makes your algorithms fair, i.e. non-discriminating against e.g. age</li><li>SmartNoise: privacy for DS projects</li><li><a href="https://interpret.ml/">InterpretML</a>: interpretability for ML models, i.e. gain a comprehensive understanding of your model</li><li>Joblib: for serializing (also known as pickling) and de-serializing Python objects (esp. models)</li></ul><p>CV:</p><ul><li>PIL: Python Image Library, a base library to read, write and work with images</li><li>OpenCV: computer vision library</li></ul><p>LLMs:</p><ul><li>LangChain: central to any LLM app, take a look at this great <a href="https://www.udemy.com/course/langchain/learn/lecture/37556406#overview">Udemy course</a>.</li><li>Streamlit: get a GUI fast (also part of the course mentioned above)</li></ul><h4>Software Development</h4><p>Ideally, you also created, uploaded (to PyPi/Github) and installed <a href="https://packaging.python.org/en/latest/tutorials/packaging-projects/">your own</a> <strong>Python package</strong>. Apply <a href="https://semver.org/">semantic versioning</a> and create appropriate git tags. For easy development, consider using the pip’s <a href="https://stackoverflow.com/a/35064498">-e option</a> and the <a href="http://autoreload/">autoreload</a> magic in Jupyter. For <strong>testing</strong> and quality control, consider adding unit tests, CI/CD through e.g. Jenkins and documentation generation. If your software is more complex, <a href="https://realpython.com/python-mock-library/">mocking</a> is a great way to isolate the scope of your unit tests, although it can be intimidating to start with. For <strong>logging</strong>, you will want to resort to a combination of <a href="https://realpython.com/python-f-strings/#doing-string-interpolation-with-f-strings-in-python">f-strings</a> and the <a href="https://github.com/Delgan/loguru">loguru</a> package.</p><p>Get to know the ins and outs of the <strong>IDE </strong>you use. Visual Studio Code is really great in my opinion. The online documentation is very clear, and VS Code integrates well with both Git and <a href="https://code.visualstudio.com/docs/editor/github-copilot#_getting-the-most-out-of-copilot">Github Copilot</a>. Relatedly, you can install <a href="https://marketplace.visualstudio.com/items?itemName=ms-toolsai.vscode-jupyter-powertoys">Jupyter Powertools</a> to get Contextual Help in notebooks. Set up a <a href="https://code.visualstudio.com/docs/python/formatting">formatter</a> such as autopep8 or black, which can be run when saving a file. This pairs well with <a href="https://stefaniemolin.com/articles/devx/pre-commit/setup-guide/">pre-commit hooks</a>. Lastly, you can enable <a href="https://docs.pydantic.dev/latest/integrations/visual_studio_code/#configure-pylance">type checking</a>.</p><p>Make sure you know how to set up and use virtual &amp; conda <strong>environments</strong>, and save the packages you install to a requirements.txtor environment.yaml file, respectively. Note that using Conda&#39;s environment.yaml over pip&#39;s requirements.txt is preferable because of Conda’s dependency resolver. <a href="https://python-poetry.org/">Poetry</a> can be a great alternative if you are looking to ship a package yourself. Additionally, at company level, you might want to use <a href="https://jfrog.com/whitepaper/python-12-reasons-to-use-a-binary-repository-manager-when-developing-with-python/">Artifactory</a> — the equivalent to git for binary files. Lastly, if you have <strong>environment variables</strong>, store them in a .env file and use the <a href="https://pypi.org/project/python-dotenv/">dotenv package</a> (python-dotenv and not dotenv; in VS Code, launch.json only applies when debugging).</p><h4>Speeding Up Python</h4><p>My next venture will be into ways to <strong>speed up Python</strong> code execution, as this is the biggest problem with Python — though running Python 3.11 <a href="https://betterdatascience.com/python-310-vs-python-311/">helps</a>. <a href="https://pub.towardsai.net/python-pandas-vs-dask-dataframes-a-comparative-analysis-c0f59dad5eeb">Dask</a> &amp; Numba are two libraries that offer complementary features on speeding up — with Dask focusing on parallelization and Numba on raw code execution. Moving to <a href="https://www.pypy.org/">PyPy</a> as an alternative interpreter to CPython can be interesting as well, though at the expense of not being able to use the latest Python version. Moreover, CPython is also moving to the use of <a href="https://devclass.com/2024/01/10/just-in-time-compiler-likely-to-arrive-in-python-3-13/">JIT compiler</a>. Last, in the specific context of deep learning, <a href="https://huggingface.co/docs/transformers/main_classes/deepspeed">DeepSpeed</a> is good to be aware of.</p><h3>Keep on exercising</h3><p>Also cliché, but e.g. working with the same dataset (I took EuroSAT, which are satellite images) through different packages (TF, PT, Hugging Face) has taught me a lot (cfr. <a href="https://github.com/JorisCod/earthObservation">https://github.com/JorisCod/earthObservation</a>). In today’s work, fine-tuning is applied often, so be sure to get the grips of it.</p><p>In any case, learn to leverage GPU’s for training, and exhibit best practices such as <a href="https://code.visualstudio.com/docs/datascience/jupyter-notebooks#_table-of-contents">structuring</a> your Jupyter notebooks, <a href="https://neptune.ai/blog/best-ml-experiment-tracking-tools">experiment tracking</a> and more MLOps (e.g. MLFlow). In this regard, my next project is to trigger training on a GitHub pull request.</p><p>Lastly, deploy your stuff in a Docker container. This <a href="https://pub.towardsai.net/a-step-by-step-guide-to-developing-a-streamlit-application-with-redis-data-storage-and-deploying-it-bd429e5b8035">tutorial</a> gives a brief overview of how to achieve that for a streamlit application with a redis db (Note: you will have to add <a href="https://medium.com/featurepreneur/streamlit-with-nginx-bde7a9a41e6c">nginx</a> to the mix to get it to connect to yourwebsite.com).</p><h3>Get Certification</h3><p>With the background of a decent course, it’s relatively easy to get <strong>cloud</strong> certification. It shows that you can work with the stuff in practice, most employers see it as an advantage especially if it matches with which cloud they use. I think a good choice is <a href="https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4wyqh">Microsoft</a> seeing their head start with OpenAI. Their learning material is also quite clear. You can start with the Fundamentals and then move on to more advanced ‘Associate’ certifications. I recently attained ‘<a href="https://learn.microsoft.com/en-us/certifications/azure-data-scientist/">Data Science Associate</a>’, which is feasible to get with a week of hard work.</p><p>While the certificates are for only one provider, what I have learned is certainly more broadly applicable. For example, several of the Python packages mentioned earlier I came to know through the (additional) Data Science Associate <a href="https://learn.microsoft.com/en-us/training/paths/build-ai-solutions-with-azure-ml-service/">learning material</a>. You will also learn about some specific services, but competitors will often have similar offerings. For Microsoft, I would say roughly 25% is non-transferable.</p><p>From my limited polls Amazon (<a href="https://aws.amazon.com/certification/certified-machine-learning-specialty/">SageMaker</a>) seems like a good 2nd. Personally, I am less sure about Google, though Colab is still the easiest environment for experimentation.</p><p>For an AI / ML Engineer role, there is <a href="https://www.tensorflow.org/certificate">TensorFlow certification</a>; although PyTorch does not have similar, it’s actually better to invest in PyTorch, seeing it has <a href="https://www.semianalysis.com/i/97006309/tensorflow-vs-pytorch">won out of TensorFlow</a>.</p><h3>Timespan</h3><p>How long does it take to discover and execute this? First of all, I was fortunate enough to be able to quit my job and spend (most of) my working hours pursuing my dream job. The course I was following was 2/3rds finished by the time I quit. Certainly doable while having a job, it wasn’t too hard to finish this.</p><p>The first two months, I spent my time discovering what’s out there, widening my knowledge and deepening my skills. I applied for a few jobs, but I was super selective and it did not lead anywhere. The third month, I started applying seriously, handing in about 5 applications a week. As most applications take time and multiple rounds, the effect was really noticeable in the 4th month.</p><h3>Application Process</h3><p>The application process started a positive (feedback) loop, as they gave me more information on what’s needed to get a certain job, as well as the motivation and inspiration to go all-in in the preparation process. This leads us to the relevance of each of the previous sections:</p><ul><li>Role: know what you want and need to search for.</li><li>Learning &amp; Python: both mostly enable passing technical tests, as well as giving the foundation for personal projects.</li><li>Exercises/projects: passing technical tests as well as being able to show a portfolio.</li><li>Certification: proof of your skills, firstly making your CV/linkedin more attractive.</li></ul><p>The core is 1) having an attractive CV, to get the feedback loop started and 2) having projects you can show. Employers will ask for your experience in the field, and course exercises aren’t persuasive enough obviously.</p><h3>Conclusion</h3><p>There is a lot to learn &amp; do after completing your first course. I hope this blog post inspired you for your next venture. Keep up the good work and work towards that job you are aiming for!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88f199344c7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>