<?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 yasmine karray on Medium]]></title>
        <description><![CDATA[Stories by yasmine karray on Medium]]></description>
        <link>https://medium.com/@ykarray29?source=rss-25b22d7e4148------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0I1Jt8FqF8jWuodwQyXlog.jpeg</url>
            <title>Stories by yasmine karray on Medium</title>
            <link>https://medium.com/@ykarray29?source=rss-25b22d7e4148------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 16:56:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ykarray29/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[Neuromorphic Computing : A Complete Guide]]></title>
            <link>https://medium.com/@ykarray29/neuromorphic-computing-a-complete-guide-33ed404e60dd?source=rss-25b22d7e4148------2</link>
            <guid isPermaLink="false">https://medium.com/p/33ed404e60dd</guid>
            <category><![CDATA[spiking-neural-network]]></category>
            <category><![CDATA[asynchronicity]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neuromorphic-computing]]></category>
            <category><![CDATA[sparsity]]></category>
            <dc:creator><![CDATA[yasmine karray]]></dc:creator>
            <pubDate>Sat, 18 Apr 2026 20:46:25 GMT</pubDate>
            <atom:updated>2026-04-18T20:46:25.060Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How brain-inspired hardware is redefining the limits of artificial intelligence</em></p><h3>1. The Human Brain — The Original Machine</h3><p>To understand why neuromorphic computing is revolutionary, we first need to understand what it aims to imitate. The human brain is, by far, the most efficient and complex machine that has ever existed. It weighs roughly 1.4 kg, consumes between 12 and 20 watts — about the power of an energy-saving light bulb — and yet it continuously manages vision, hearing, emotions, memory, movement, language, and billions of other processes we are not even consciously aware of performing.</p><p>It contains approximately <strong>86 billion neurons</strong>, connected by around <strong>100 trillion synapses</strong>. To put this in perspective: there are more connections in a single human brain than there are stars in the Milky Way.</p><h3>1.1 The Neuron: The Basic Unit</h3><p>The neuron is the fundamental cell of the brain. It resembles a tree: it has roots (the <strong>dendrites</strong>), a trunk (the <strong>soma</strong>, or cell body), and branches (the <strong>axon</strong> and its terminals). Each neuron is an autonomous mini-processor.</p><p><strong>Dendrites</strong> are the neuron’s receiving antennae — long branching extensions that collect electrochemical signals from other neurons. A single neuron can have thousands of dendrites, allowing it to receive information simultaneously from thousands of different sources.</p><p><strong>The soma</strong> is the neuron’s decision center. It contains the cell nucleus and all the biological machinery necessary for life. Its computational role is crucial: it integrates all incoming signals from the dendrites, sums them up, and decides whether to emit an output signal. This decision is binary in its triggering but analog in its mechanism — if the sum of incoming signals exceeds a certain electrical threshold called the <strong>action potential</strong>, the neuron <em>fires</em>: it sends an electrical signal down its axon. If the threshold is not reached, the neuron stays silent. This mechanism corresponds exactly to what we call an <strong>activation function</strong> in artificial neural networks (ReLU, sigmoid), except that in the brain this function is carried out physically by the cell’s chemistry.</p><p><strong>The axon</strong> is the neuron’s transmission cable — a long nerve fiber that can measure a few micrometers or extend over a meter for neurons connecting the spinal cord to the body’s extremities. The axon carries the electrical signal — called a <em>spike</em> or action potential — from the soma to the axonal terminals, which are the contact points with other neurons.</p><h3>1.2 The Synapse: Where the Magic Happens</h3><p>The synapse is the microscopic gap between one neuron’s axonal terminal and the dendrite of the next. It is not a direct physical connection: there is a tiny empty space between the two cells, called the <strong>synaptic cleft</strong>. When a spike arrives at the axonal terminal, it triggers the release of chemical molecules called <strong>neurotransmitters</strong> — dopamine, serotonin, glutamate, GABA, among others. These molecules cross the synaptic cleft and bind to receptors on the next dendrite, creating a new electrical signal in that neuron.</p><p>This mechanism is fundamental because <strong>this is where memory and learning reside</strong>. The strength of a synapse — the quantity of neurotransmitters released and the sensitivity of the facing receptors — can change over time. This is called <strong>synaptic plasticity</strong>. If two neurons fire together frequently, their synapse strengthens: <em>“neurons that fire together, wire together.”</em> This is the biological mechanism behind every memory and every learned skill. In computing terms, this synaptic strength corresponds exactly to what we call a <strong>weight</strong> in an artificial neural network.</p><h3>1.3 Spikes: The Brain’s Language</h3><p>The brain communicates via brief, standardized electrical pulses called <strong>spikes</strong> or action potentials. Each spike lasts roughly 1 millisecond and has a nearly fixed amplitude of about 100 millivolts. The brain does not encode information in the <em>intensity</em> of the spike (they are all the same size), but in the <strong>rate</strong> at which they are emitted, in their <strong>precise timing</strong>, and in which neurons fire simultaneously. This is called <strong>temporal coding</strong>. A strong or urgent signal translates into a high spike frequency; a weak signal produces few spikes, or none at all.</p><p>This system is extraordinarily energy-efficient because a neuron only consumes energy when it fires a spike. At rest, it consumes almost nothing. In a typical brain state, only <strong>1–5% of neurons are active at any given moment</strong> — a property known as <strong>sparsity</strong>. Imagine an office building where at any moment only 2 floors out of 100 have their lights on: this is one of the main reasons the brain is so energy-efficient despite its colossal complexity.</p><h3>1.4 Distributed Architecture: No Central Conductor</h3><p>Unlike a classical computer that has a central processor controlling everything, <strong>the brain has no conductor</strong>. There is no central clock synchronizing all operations. Each neuron is autonomous: it receives its signals, makes its decision, and sends its output completely independently of all others. This is called an <strong>asynchronous system</strong>. Millions of neurons do this simultaneously, in parallel, without explicitly coordinating — and from all of this emerge consciousness, thought, and intelligence.</p><p>Memory in the brain is not stored in a specific location like a hard drive. It is <strong>distributed across the patterns of synaptic connections</strong> throughout the brain — not a file stored somewhere, but a network of relationships between neurons that strengthen or weaken. This means that <strong>computation and memory are co-located</strong> in the same structures. In a classical computer, by contrast, the processor (where computation happens) is physically separate from RAM (where data is stored), and the two must constantly communicate via a bus — a major source of bottlenecks and energy consumption.</p><h3>1.5 The Fruit Fly Brain: A Model of Efficiency</h3><p>To put things in perspective, the brain of a <em>Drosophila</em> (a small laboratory fruit fly) weighs 0.1 grams and contains around 100,000 neurons connected by 20 million connections. Yet this fly can fly, avoid obstacles, recognize odors, find food, reproduce, and learn from experience — all while consuming an infinitesimal amount of energy.</p><p>Neuromorphic computing researchers study insect brains with as much attention as the human brain, because they represent ultra-efficient evolutionary solutions to real-time computational problems. A bee’s brain contains around 1 million neurons, and the fruit fly’s around 100,000 — far more accessible targets than the human brain’s 86 billion neurons. Despite their small size, these brains perform remarkable tasks at energy levels in the microwatt range.</p><p>One particularly studied example is the <strong>locust</strong>, which possesses a dedicated neuron called the <strong>LGMD</strong> (Lobula Giant Movement Detector), responsible solely for visual collision avoidance. Engineers reproduce this exact architecture to create neuromorphic event cameras for drones, capable of dodging obstacles in a few milliseconds without a central processor. The most notable real-world systems include <strong>DAVIS cameras</strong> (Dynamic and Active-Pixel Vision Sensor) developed at ETH Zurich and commercialized by <strong>Inivation</strong>, and <strong>Metavision cameras</strong> by <strong>Prophesee</strong>, used in automotive and industrial settings. On the drone side, platforms such as <strong>DelFly</strong> (TU Delft) and MIT’s insect-inspired vehicles combine event cameras with neuromorphic chips for ultra-fast obstacle avoidance. The spatial orientation and olfactory circuits of flies and bees are also being translated into chips for autonomous robotics.</p><h3>2. Classical Processors and Their Limits</h3><h3>2.1 How a Classical Processor Works</h3><p>A modern processor like an Intel Core i7 or AMD Ryzen is built on a principle invented in the 1940s by mathematician John von Neumann. This <strong>Von Neumann architecture</strong> dictates that the processor and memory are two separate components communicating via a data bus. The processor executes instructions one at a time or in small groups with multi-core processors stores data in RAM, and the result of each calculation is sent back to memory to be used in the next one.</p><p>Operation relies on a <strong>global clock cycle</strong> that paces all operations. When we say a processor runs at 3.5 GHz, it means this clock ticks 3.5 billion times per second, and at each tick the processor executes a certain number of basic operations. Everything is synchronized, ordered, and predictable — but also fundamentally linear in logic.</p><p>At the physical level, everything relies on <strong>transistors</strong>: micro-switches fabricated from doped silicon. When sufficient voltage is applied to its gate, the transistor lets current through (state 1); otherwise, it blocks it (state 0). Billions of transistors combined form logic gates (AND, OR, NOT, XOR…), which in turn form a processor capable of adding, multiplying, comparing, and storing data. A modern processor contains between 10 and 50 billion transistors in a space the size of a postage stamp.</p><h3>2.2 The Miniaturization Wall</h3><p>For decades, the industry followed <strong>Moore’s Law</strong>: the number of transistors on a chip doubles every two years, enabling exponential performance gains. But this law now runs up against the fundamental physical limits of matter. Today, the smallest transistors are about <strong>2–3 nanometers</strong> in size — just a few dozen atoms. At this scale, quantum effects disrupt transistor behavior: electrons tunnel through barriers, current leakage becomes uncontrollable, and the heat generated is impossible to dissipate in such a small space.</p><p>Significant further miniaturization is therefore no longer feasible. To continue improving performance, manufacturers have adopted other strategies: adding more cores to a single processor, improving software architectures, developing specialized chips like GPUs for AI or Google’s TPUs. But all these approaches remain fundamentally limited by the same problem: <strong>the Von Neumann architecture itself</strong>.</p><h3>2.3 The Von Neumann Bottleneck</h3><p>This problem has a name: the <strong>Von Neumann bottleneck</strong>. In any classical processor, even the most powerful ones, the limiting factor is generally not the speed of computation — it is the time spent transferring data between memory and the processor. This transfer consumes enormous energy and introduces latency.</p><p>For artificial intelligence tasks, which involve multiplying matrices of billions of weights by data vectors, this bottleneck is devastating: a data center GPU can consume <strong>300–700 watts</strong>, of which only a fraction is spent on actual computation — the rest goes into moving data, heating interconnects, and maintaining the global clock.</p><h3>3. What Is Neuromorphic Computing?</h3><h3>3.1 The Fundamental Principle</h3><p>Neuromorphic computing is a radically different approach to processor design. Instead of improving or modifying the Von Neumann architecture, <strong>it abandons it entirely</strong>. The idea is to build chips that operate according to the same principles as the biological brain: asynchronous, event-driven, distributed, and with computation and memory co-located.</p><p>The term “neuromorphic” was coined in the 1980s by <strong>Carver Mead</strong>, an engineer at Caltech (California Institute of Technology), who had the intuition that analog circuits could imitate the behavior of biological neurons very efficiently. Since then, the field has evolved considerably and now encompasses both analog and digital approaches.</p><h3>3.2 Spiking Neural Networks (SNNs)</h3><p>The <strong>Spiking Neural Network (SNN)</strong> is the engine of neuromorphic computing. Its defining feature: it does not process information like a classical computer, but imitates the biological functioning of the human brain.</p><p>To understand the difference intuitively, imagine you are watching a door. In a classical artificial neural network (ANN), you stare at the door and every second send a report: “Nothing changed,” “Nothing changed,” “It’s opening.” Your brain and notepad work continuously — even when nothing happens, you consume energy confirming the absence of movement. This is a <strong>synchronous and energy-hungry system</strong>. In an SNN, you instead install a sensor that only triggers a signal (a <em>spike</em>) when the door actually moves. The rest of the time the system is dormant. If there is no spike, there is no computation. This single principle saves over <strong>99% of energy</strong> by processing only novelty — a property called sparsity.</p><h3>3.3 The Leaky Integrate-and-Fire (LIF) Model</h3><p>In a Spiking Neural Network, the neuron is not a simple static activation function but a <strong>dynamic unit</strong> defined by its <strong>membrane potential</strong> V(t). Its behavior unfolds in three steps.</p><p><strong>Accumulation and leak.</strong> The potential V(t) evolves continuously over time. When the neuron receives input spikes from neighboring neurons, its potential climbs — but it also constantly &quot;leaks&quot; back toward its resting value. The time constant τ_m controls how fast this leak occurs, V_rest is the resting potential the neuron naturally returns to, and R_m I(t) represents the energy contributed by incoming spikes.</p><p>τ_mdV(t)dt=−(V(t)−V_rest)+R_m I(t)</p><p><strong>Firing and reset.</strong> The neuron monitors its own state. As soon as the potential reaches a critical threshold V_th, a discrete event — the spike — is generated and broadcast to downstream neurons. Immediately after, the potential is reset to its resting value V_reset, ready to integrate new inputs.</p><p><strong>Energy efficiency through sparsity.</strong> If V(t) never reaches V_th, the neuron stays completely silent: S(t) = 0. No multiplication is performed, no data is transmitted, and the corresponding hardware sits at rest. In a network of millions of neurons, the vast majority never cross the threshold at the same instant — meaning the chip spends most of its time doing nothing, consuming nothing.</p><h3>3.4 ANN vs. SNN: How They Actually Differ</h3><p>In a classical ANN, data flows as streams of floating-point numbers (such as 0.85 or −1.2), computation is synchronous and happens at every forward pass, and all neurons are computed regardless of whether their output is meaningful or near zero. The base operation is z = Σwᵢxᵢ + b followed by an activation function applied across the entire layer simultaneously.</p><p>In an SNN, communication happens through binary spikes (0 or 1), computation is asynchronous and event-driven, and only neurons that actually fire participate in further calculation. The base model is the Leaky Integrate-and-Fire described above, where the timing and frequency of spikes encode information rather than the magnitude of floating-point values.</p><p>The practical consequence is stark: in a classical ANN, multiplying by zero or obtaining a null result costs exactly as much energy and as many clock cycles as obtaining a result of 0.99. The synchronous infrastructure processes the entire layer at once, whether the data is relevant or not. In an SNN, there is no concept of “computing zero” — there is simply no computation at all.</p><h3>3.5 The Architecture of a Neuromorphic Chip</h3><p>A neuromorphic chip is not built like a classical processor. It is organized into <strong>neuromorphic nodes</strong>, each containing thousands of artificial neurons and their synapses with associated weights. These nodes are connected by a communication network that transports only spikes — simple messages stating “neuron X fired at time T.” This network is <strong>asynchronous</strong>: messages circulate when there are some to send, not according to a clock.</p><p>The crucial point is that in each node, the synaptic weights are <strong>stored locally</strong>, physically adjacent to the computation units. There is no longer a memory → processor → memory round trip. Computation happens right where the data resides. This is called <strong>in-memory computing</strong> (or compute-in-memory), and it is one of the primary sources of these chips’ exceptional energy efficiency.</p><h3>4. Why Neuromorphic Computing Is Radically More Efficient</h3><p>The answer operates on several levels simultaneously. This is not a simple speed improvement but a fundamental architectural difference that changes the very nature of computation.</p><h3>Level 1 — Eliminating the Memory–Compute Bottleneck</h3><p>When a classical neural network runs on a GPU, the weights are stored in VRAM. For every forward pass, the processor retrieves them, multiplies them with activations, stores the intermediate result, retrieves it, adds it to the next, and repeats this for every layer, every neuron, every weight. This constant data transfer between memory and processor often <strong>consumes more energy than the computation itself</strong>.</p><p>On a neuromorphic chip, the synaptic weights are stored physically within the same structures that perform the computation. When a spike arrives at a node, the calculation happens immediately on the spot. This source of consumption is eliminated at the root.</p><h3>Level 2 — Sparsity: Only Compute What Is Necessary</h3><p>On a GPU, a classical ANN computes all neurons in all layers at every forward pass, even those whose activation is near zero. On a neuromorphic chip with an SNN, only neurons that emit a spike participate in subsequent computations. As in the brain, typically <strong>1–5% of neurons are active at any moment</strong>, meaning only 1–5% of the network is computed instead of 100%. Energy savings are directly proportional to this sparsity, which largely explains the <strong>100× to 1000× efficiency factors</strong> observed experimentally.</p><h3>Level 3 — Asynchronous Computation Without a Global Clock</h3><p>A GPU, despite its thousands of cores, is fundamentally synchronous: all cores compute at the same clock frequency and synchronize at each layer. The clock itself — which must be distributed across the entire chip to billions of transistors — can consume up to <strong>30–40% of the chip’s total energy</strong>.</p><p>On a neuromorphic chip, there is no global clock. Each node acts when it receives a spike. Computations happen in massive parallelism and completely asynchronously. A spike triggered by input propagates through the network in a cascade, each neuron responding in its own time, like a wave. The clock distribution energy is simply absent.</p><h3>Level 4 — Real-Time Processing Without Batching</h3><p>GPUs are most efficient when given large amounts of data to process simultaneously — a technique called <strong>batching</strong>. With a single example to process, the GPU is massively underutilized. Data centers therefore accumulate requests into batches before processing them together, which introduces latency.</p><p>A neuromorphic chip does not need batching: it processes data on the fly, example by example, spike by spike, in real time. For edge applications — a surveillance camera that must detect an anomaly immediately, a microphone that must recognize a keyword instantly, a sensor on an autonomous vehicle that must react in milliseconds — this capability is decisive.</p><h3>4.1 Industrial Applications</h3><p><strong>In the automotive sector</strong>, manufacturers such as Mercedes-Benz (through partnerships with Intel) and various suppliers are exploring event-based vision sensors. These systems can achieve sub-millisecond reaction times for autonomous braking. The key advantage is not only energy-related — it is latency. Unlike a classical camera that waits to capture a complete image (approximately 15–30 ms), neuromorphic chips process the data stream asynchronously, reacting instantly as soon as a pixel detects a light change.</p><p><strong>In robotics</strong>, the <strong>ANYmal</strong> quadruped robot developed by ETH Zurich, when coupled with Intel’s <strong>Loihi 2</strong> research chip, demonstrated remarkable efficiency for complex navigation. The AI computation part consumes up to <strong>100× less energy</strong> than a classical GPU-based solution such as an Nvidia Jetson. In certain walking control tests, the neuromorphic system reduced overall processor consumption by <strong>90%</strong>, freeing power for sensors or extending mission operating time.</p><h3>4.2 Migration Guide: From Deep Learning to Neuromorphic</h3><p>For an engineer accustomed to classical frameworks, migrating to neuromorphic computing is not about abandoning existing knowledge — it is about adopting a <strong>temporal and event-driven approach</strong> to computation.</p><p><strong>Software transition.</strong> The entry point remains Python. Libraries like <strong>SpikingJelly</strong> or <strong>Norse</strong> import directly on top of PyTorch. The syntax shift is modest: instead of importing torch.nn.ReLU, you import dynamic neuron modules like neuron.LIFNode. The more significant change is state management — unlike dense networks, these neurons have memory, so you must reset network states between data batches using utility functions like functional.reset_net(model).</p><p><strong>Training adaptation: Surrogate Gradients.</strong> The biggest technical challenge is that a spike is a discontinuous function (0 or 1), which makes the derivative zero and blocks classical backpropagation. The solution used by most frameworks is <strong>Surrogate Gradients</strong>: during the backward pass, the step function is replaced by a continuous curve (typically a sigmoid or triangle function), allowing weight updates via standard optimizers like Adam or SGD.</p><p><strong>The temporal dimension.</strong> In classical deep learning, data are static blocks of shape [Batch, Channels, H, W]. In neuromorphic computing, a time dimension is introduced and data become sequences of shape [Time, Batch, …]. The network processes information step by step, and if nothing changes in the input, the sensor generates no spikes and the processor consumes almost nothing. Optimization goals also shift: beyond minimizing loss, the aim is to <strong>maximize sparsity</strong> — ensuring as few neurons as possible activate for a given task.</p><h3>4.3 GPU and Neuromorphic: A Strategic Alliance</h3><p>In 2026, GPUs and neuromorphic chips form an inseparable duo within the AI ecosystem. The GPU remains the indispensable training center: thanks to its raw power, it is used in data centers to train massive models on terabytes of data — a task requiring floating-point precision and dense matrix operations. Once a model is optimized, it is converted for execution on a neuromorphic chip, which becomes the field unit: handling real-time inference on edge devices such as smartphones, drones, and industrial sensors, with autonomy and reactivity that a GPU could never sustain on battery.</p><p>The result is a clear division of labor. The <strong>GPU manages global knowledge</strong> through heavy, offline learning. The <strong>neuromorphic chip manages local action</strong> through live interaction with the physical world.</p><h3>5. Conclusion — A New Paradigm</h3><p>Neuromorphic computing is not destined to replace the GPU for training large models. It represents something deeper: a third way between classical computing blocked by its physical limits and quantum computing still out of practical reach.</p><p>It is the architecture that makes AI sustainable, embedded, and ubiquitous — capable of running in a hand prosthesis, in augmented reality glasses, in an industrial sensor, or in an autonomous vehicle, drawing the power of a neuron rather than a power plant.</p><p>This field also forces us to rethink what “programming” means: instead of writing functions and loops, we design neural networks whose temporal dynamics carry the information. This is a paradigm shift as radical as the transition from procedural to object-oriented programming, but with a far broader transformational potential, since it touches the very foundation of the hardware on which all artificial intelligence rests.</p><p>This brings us to perhaps the most important takeaway for anyone studying artificial intelligence or processor architecture today: <strong>a solid understanding of neuroscience is no longer optional — it is becoming a core engineering skill.</strong> Looking at the trajectory of the field, almost every major breakthrough in computing efficiency has come from a deeper imitation of how the brain actually works. Sparsity, asynchronous processing, in-memory computation, event-driven signaling — none of these ideas originated in a computer science lab. They were borrowed from biology. The engineers who will shape the next generation of hardware are not those who know more transistors, but those who understand why a locust can dodge an obstacle in two milliseconds with a hundred thousand neurons and no operating system. The brain has already solved, through billions of years of evolution, the very problems we are only now learning to formulate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33ed404e60dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG vs Chain of Thought: Two Techniques for Smarter LLM Usage]]></title>
            <link>https://medium.com/@ykarray29/rag-vs-chain-of-thought-two-techniques-for-smarter-llm-usage-77119a7cd4a5?source=rss-25b22d7e4148------2</link>
            <guid isPermaLink="false">https://medium.com/p/77119a7cd4a5</guid>
            <category><![CDATA[chain-of-thought]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[yasmine karray]]></dc:creator>
            <pubDate>Sat, 11 Apr 2026 15:03:07 GMT</pubDate>
            <atom:updated>2026-04-11T15:03:07.367Z</atom:updated>
            <content:encoded><![CDATA[<h3>Before We Start: A Common Misconception</h3><p>When people hear “RAG” or “Chain of Thought,” they often assume these are new model architectures ways of training a better LLM from scratch. They are not. Both are techniques for using existing language models more effectively. The model itself does not change; what changes is how you prepare the information you feed it, and how you instruct it to think. RAG solves the problem of <em>what information the model sees</em>. Chain of Thought solves the problem of <em>how the model reasons over that information</em>.</p><h3>A Brief History: Which Came First?</h3><p><strong>RAG</strong> came first. The seminal paper, <em>“Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks,”</em> was published by Facebook AI Research in May 2020. The problem it addressed was straightforward: a language model’s knowledge is frozen at training time, with no way to consult external documents at inference. RAG solved this by pairing a retrieval system with a generative model, allowing the LLM to ground its answers in documents it had never seen during training.</p><p><strong>Chain of Thought</strong> followed roughly two years later. Google Brain researchers introduced it in <em>“Chain-of-Thought Prompting Elicits Reasoning in Large Language Models”</em> in January 2022. The core insight was surprisingly simple: if you show a language model examples of step-by-step reasoning in the prompt, it begins reasoning step by step on its own. No new architecture was needed — just a smarter way of writing prompts. CoT is therefore a prompt-engineering discovery, not a system design.</p><p>The key takeaway: <strong>CoT is about how the model thinks. RAG is about what information the model has access to.</strong> They were designed to solve different problems, which is precisely why they complement each other so well.</p><h3>RAG: Retrieval-Augmented Generation</h3><h3>The Core Idea</h3><p>RAG is designed for situations where your document collection is too large to fit inside an LLM’s context window. Instead of giving the model everything at once, you build a retrieval system that finds only the most relevant pieces of text for a given question and passes only those pieces to the model.</p><h3>Step 1: Divide Your Documents into Chunks</h3><p>The first step is to break your documents into smaller pieces called <em>chunks</em>. There are three main strategies:</p><p><strong>Fixed splitting</strong> divides text by word or token count. This is the simplest but riskiest method, it can cut a sentence in the middle and destroy meaning. Avoid it unless you have no alternative.</p><p><strong>Semantic splitting</strong> groups information that naturally belongs together. For example, all paragraphs about mathematics form one chunk, and all paragraphs about physics form another.</p><p><strong>Document structure splitting</strong> follows the natural divisions of the document itself , chapters, sections, or course modules each become their own chunk.</p><p>The chunk size must respect your embedding model’s token limit. If a chunk exceeds this limit, the model truncates it and you lose context. To prevent meaning from breaking across consecutive chunks, use an <strong>overlap</strong>: repeat the last few sentences of one chunk at the beginning of the next. A 10–15% overlap is a reasonable starting point.</p><p><strong>Token limits for common embedding models:</strong></p><ul><li>OpenAI text-embedding-3-small and text-embedding-ada-002: up to 8,191 tokens</li><li>Ollama nomic-embed-text: up to 2,048 tokens</li><li>Ollama mxbai-embed-large: up to 512 tokens</li></ul><h3>Step 2: Generate Embeddings</h3><p>Once the chunks are created, each piece of text is passed through an <strong>embedding model</strong>, which converts it into a numerical vector. These numbers capture the semantic meaning of the text , two sentences that mean the same thing produce vectors that are very close to each other, while two unrelated sentences produce vectors that point in very different directions.</p><p>Think of each embedding as a set of coordinates in a very high-dimensional space. Every word, sentence, or paragraph can be mapped to a point in that space. The embedding model has learned, through training on enormous amounts of text, that the point for “dog” should sit near the point for “puppy” and far from the point for “thermodynamics.”</p><p>There is one absolute rule: <strong>the embedding model used at storage time must be exactly the same as the one used at query time.</strong> If you embed your documents with OpenAI and then embed the user’s question with Ollama, the results will be completely wrong , the two models do not speak the same mathematical language, and their vectors are not comparable.</p><p>These vectors are stored in a <strong>vector database</strong> such as PgVector (a PostgreSQL extension). Unlike a traditional relational database with rows and columns of structured data, a vector database stores and retrieves records based on <em>mathematical similarity between vectors</em>. You don’t query it with “WHERE title = ‘X’ , you query it with “give me the 10 vectors most similar to this query vector,” and the database finds them efficiently even across millions of entries. for more details : <a href="https://www.infracloud.io/blogs/vector-databases-beginners-guide/">https://www.infracloud.io/blogs/vector-databases-beginners-guide/</a></p><h3>Step 3: Query and Semantic Search</h3><p>When a user asks a question, that question is transformed into a vector using the same embedding model. This query vector is then compared to all stored vectors to find the closest chunks.</p><p><strong>Cosine similarity</strong> performs this comparison. Each vector can be thought of as an arrow pointing in a specific direction in high-dimensional space. Two vectors are semantically close if their arrows point in similar directions — that is, if the angle between them is small. Cosine similarity measures this angle.</p><p>Why not use plain Euclidean distance (the straight-line distance between two points)? In very high-dimensional spaces, Euclidean distances become unreliable: all points tend to appear roughly equidistant from one another a well-known problem called the <strong>curse of dimensionality</strong>. By measuring only the orientation of vectors and ignoring their magnitude, cosine similarity remains robust regardless of the number of dimensions.</p><p>The database returns the top 5–10 chunks whose direction most closely matches the query vector. You can also filter by a threshold for example, only return chunks where the cosine similarity exceeds 0.75.</p><h3>Step 4: Augment and Generate</h3><p>Instead of sending just the question to the LLM, you build an <em>augmented prompt</em>: the retrieved chunks are prepended to the user’s question before being sent to the model. The LLM then generates a natural-language response grounded in this context. It never searches through all your documents, it only ever sees the small selection of chunks the retrieval system chose for it.</p><p><strong>What the full flow looks like:</strong></p><pre>User question<br>    → Embed the question (same model used at storage time)<br>    → Compare query embedding against all stored embeddings (cosine similarity)<br>    → Retrieve top N chunks above threshold<br>    → Build prompt: [retrieved chunks] + [user question]<br>    → Send to LLM (OpenAI, Ollama, etc.)<br>    → Return the model&#39;s response</pre><p><strong>Example of a RAG prompt:</strong></p><pre>You are a helpful assistant. Answer the user&#39;s question using ONLY the <br>context provided below. If the context does not contain enough information <br>to answer, say so.</pre><pre>Context:<br>[Chunk 1] The Eiffel Tower was completed in 1889 and stands 330 metres tall.<br>[Chunk 2] The tower was initially criticised by prominent French artists but <br>has since become one of the most visited monuments in the world.</pre><pre>Question: How tall is the Eiffel Tower and when was it built?</pre><h3>The RAG Acronym, Decoded</h3><ul><li><strong>Retrieval</strong> — steps 1, 2, and 3: documents are chunked, embedded, and stored so they can be retrieved intelligently.</li><li><strong>Augmented</strong> — the bridge between steps 3 and 4: the user’s question is augmented with the retrieved chunks before being sent to the LLM.</li><li><strong>Generation</strong> — step 4: the LLM generates a natural-language response based on the augmented context.</li></ul><h3>Chain of Thought (CoT) Prompting</h3><h3>The Core Idea</h3><p>Chain of Thought is a prompt-engineering technique, not a retrieval architecture. It requires no external infrastructure , no embedding model, no vector database. Instead, the entire document (or set of documents) is placed directly inside the prompt’s context window, and the LLM is explicitly instructed to reason step by step before producing its final answer.</p><p>The insight behind CoT is that language models, much like humans, make fewer mistakes when they are forced to show their work. A model that must externalize its reasoning before concluding is less likely to jump to an incorrect answer, because each intermediate step must be logically consistent with the previous one.</p><h3>Step 1: Load the Full Document into Context</h3><p>The document is placed directly into the prompt. No chunking or embedding is required — the entire content is available to the model at once. This is CoT’s main constraint: <strong>everything must fit within the model’s context window</strong>, which ranges from a few thousand tokens for older models to several hundred thousand for the most recent ones.</p><blockquote><strong><em>A familiar example:</em></strong><em> When you upload a PDF to Claude or ChatGPT, the system performs what is sometimes called a “long-context read.” This isn’t necessarily RAG it isn’t searching a database it is often just placing the whole file into the context window. CoT then helps the model work through that file carefully by reasoning step by step.</em></blockquote><h3>Step 2: Write a Structured Prompt</h3><p>The prompt must explicitly instruct the model to reason before answering. Simply asking a question is not enough. The key instruction is some variation of:</p><ul><li>“Think step by step”</li><li>“Explain your reasoning before concluding”</li><li>“Show your work”</li></ul><p>This instruction forces the model to decompose the problem rather than jumping to a potentially incorrect shortcut answer.</p><p><strong>Example of a CoT prompt:</strong></p><pre>Here is the document:<br>[full document text]<br>Using ONLY the information in this document, think step by step before <br>answering the following question. Show your reasoning clearly, then <br>give your final answer.<br>Question: Based on the sales data in the document, which product <br>category had the highest growth rate between Q1 and Q3?</pre><h3>Step 3: The Model Reasons Explicitly</h3><p>The LLM produces its reasoning chain as visible output before giving the final answer. Each intermediate step builds on the previous one, making the logic transparent and easy to verify. If the model makes an error, it is visible in the reasoning chain , which makes CoT responses significantly easier to audit than a plain answer. The model cannot hide a logical leap.</p><p><strong>Example of a CoT reasoning chain:</strong></p><pre>Step 1: Identify the product categories mentioned in the document.<br>The document lists three categories: Electronics, Clothing, and Home Goods.<br>Step 2: Find Q1 sales figures.<br>Electronics: $120,000 | Clothing: $85,000 | Home Goods: $40,000<br>Step 3: Find Q3 sales figures.<br>Electronics: $150,000 | Clothing: $95,000 | Home Goods: $72,000<br>Step 4: Calculate growth rates.<br>Electronics: (150,000 - 120,000) / 120,000 = 25%<br>Clothing: (95,000 - 85,000) / 85,000 = 11.8%<br>Home Goods: (72,000 - 40,000) / 40,000 = 80%<br>Final answer: Home Goods had the highest growth rate at 80%, despite <br>having the lowest absolute sales figures.</pre><h3>Step 4: Generate the Final Answer</h3><p>The LLM concludes its reasoning chain and produces the final natural-language answer, grounded in the visible steps it has just worked through.</p><h3>The different variants of <strong>Chain of Thought</strong> are</h3><ul><li><strong>Zero-shot CoT:</strong> This is the most direct method. You take the user’s question and simply add a phrase like “Let’s think step by step” to force the AI to break down its reasoning without providing any prior examples.</li><li><strong>Automatic CoT:</strong> This involves the AI generating its own complete examples (a similar question + detailed reasoning + the solution). It then uses these self-created examples as templates to better answer your original question.</li><li><strong>Multimodal CoT:</strong> This is when the AI merges different types of sources (such as an image, a graph, or sound) with text. It visually analyzes the document at the same time it “thinks” in writing to construct its reasoning.</li></ul><h3>Do People Combine Both Techniques?</h3><p>Yes, and this is increasingly the norm in production systems. The combination is sometimes called <strong>CoT-augmented RAG</strong>. The two techniques are not competitors — they address different layers of the same problem:</p><ul><li><strong>RAG decides <em>what</em> information the model sees.</strong></li><li><strong>CoT decides <em>how</em> the model thinks about that information.</strong></li></ul><p>Pairing them gives you both breadth and depth. Several research groups and practitioners have confirmed that combining retrieval with explicit chain-of-thought reasoning yields better results than either technique alone, particularly on tasks requiring multi-step reasoning over retrieved evidence.</p><p><strong>Example of a combined RAG + CoT prompt:</strong></p><pre>You are a research assistant. You have been provided with the following <br>retrieved document excerpts. Reason step by step over these excerpts to <br>answer the question. For each reasoning step, note which excerpt supports it.</pre><pre>[Excerpt 1] Climate models project a 1.5–4.5°C increase in global average <br>temperature by 2100 under a high-emissions scenario.</pre><pre>[Excerpt 2] Agricultural yields for wheat are expected to decline by 6% <br>for every 1°C rise in temperature.</pre><pre>[Excerpt 3] Global wheat consumption is approximately 780 million tonnes <br>per year.</pre><pre>Think step by step, citing excerpts, then provide your final answer.</pre><pre>Question: Under a high-emissions scenario, what is the projected range <br>of wheat production loss by 2100?</pre><h3>Key Principles to Keep in Mind</h3><h3>RAG and CoT operate at different levels</h3><p>RAG is an infrastructure and retrieval problem. CoT is a prompting and reasoning problem. Confusing the two leads to choosing the wrong tool for the job.</p><p><strong>Use RAG when:</strong></p><ul><li>Your document collection is too large to fit in the context window</li><li>You need to search across many documents dynamically</li><li>You need to cite specific sources in your answers</li></ul><p>The quality of a RAG system depends almost entirely on two things: the quality of your chunking strategy, and the consistency of your embedding model. The same model must be used at storage time and at query time, without exception.</p><p><strong>Use CoT when:</strong></p><ul><li>Your documents are small enough to fit in context</li><li>The task requires multi-step reasoning rather than simple lookup</li><li>You want the model’s reasoning to be visible and auditable</li></ul><p>CoT requires no infrastructure its entire value is in how you write the prompt.</p><h3>The shared failure mode: hallucination</h3><p>RAG can return the wrong chunk, causing the model to answer confidently from irrelevant material. CoT can allow the model to make a logical error mid-chain and then compound it in subsequent steps. Combining the two techniques mitigates both risks: accurate retrieval reduces the chance of the model reasoning over wrong information, and explicit reasoning reduces the chance of the model jumping to an unjustified conclusion.</p><h3>Step-by-Step Implementation Guide: RAG</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*biDHaomtAqAgzA01UN7H3Q.png" /></figure><h3>Step-by-Step Implementation Guide: Chain of Thought</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lHNVIj25O_9V2EQa0xI2FQ.png" /></figure><h3>Step-by-Step Implementation Guide: RAG + CoT Combined</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2Ujcu3MAK8ih03RXlonxw.png" /></figure><p>This combined approach is the most robust of the three for complex question-answering tasks. It delivers the scale of RAG, the transparency of CoT, and the auditability of explicit citation — at the cost of a slightly more complex prompt and marginally higher token usage.</p><h3>Other concepts that may interest you</h3><h4>Prompt Chaining vs. Chain of Thought (CoT)</h4><p>While both techniques aim to tackle complexity, they operate on different structural levels:</p><ul><li><strong>Prompt Chaining</strong> involves breaking a complex task into a sequence of <strong>distinct prompts</strong>. The output of one prompt becomes the input for the next, allowing the AI to focus on one specific sub-task at a time. It is an external workflow where you guide the model through a multi-step process.</li><li><strong>Chain of Thought (CoT)</strong> focuses on eliciting the model’s internal reasoning within a <strong>single prompt</strong>. By asking the model to “think step-by-step,” you encourage it to generate intermediate logical steps before arriving at a final answer, improving its accuracy on logic-heavy tasks.</li></ul><h4>directional stimulus prompting (DSP) :</h4><p><strong>Directional Stimulus Prompting (DSP)</strong> introduces a middle ground between these two by using an external “guide” to shape internal reasoning. Unlike Prompt Chaining (where you manually link steps) or CoT (where the model reasons on its own), DSP uses a specialized <strong>small-scale policy model</strong> to generate a specific “nudge” for each individual input.</p><h4>How it compares to other methods:</h4><ul><li><strong>Prompt Chaining vs. DSP:</strong> Prompt Chaining requires a human or a script to manage the flow between multiple LLM calls. DSP is more automated; it uses a tiny, optimized model to “preprocess” your request and insert the perfect hints (stimuli) that steer the larger LLM toward the correct output in one go.</li><li><strong>CoT vs. DSP:</strong> While CoT relies on the LLM’s general knowledge to figure out the steps, DSP provides “anchors.” For example, if you want a summary, CoT might just summarize step-by-step, but DSP will extract specific keywords first and say: <em>“Summarize this text, ensuring you include [Keyword A] and [Keyword B].”</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77119a7cd4a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Language Models Smarter: A Guide to Prompt Engineering, RAG, and Fine-Tuning]]></title>
            <link>https://medium.com/@ykarray29/making-language-models-smarter-a-guide-to-prompt-engineering-rag-and-fine-tuning-9e927bebc165?source=rss-25b22d7e4148------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e927bebc165</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chain-of-thought]]></category>
            <dc:creator><![CDATA[yasmine karray]]></dc:creator>
            <pubDate>Sat, 11 Apr 2026 14:51:45 GMT</pubDate>
            <atom:updated>2026-04-11T14:51:45.213Z</atom:updated>
            <content:encoded><![CDATA[<p>There is a common misconception that a large language model, once trained, simply does its job on its own. In reality, getting the most out of a model requires deliberate effort, and the techniques used to do so vary enormously in complexity, cost, and the kind of results they produce. Three approaches dominate the conversation today: prompt engineering, retrieval-augmented generation, and fine-tuning. Understanding each of them what they are, how they work, and when to use them is essential for anyone building or working with AI systems. And while each technique stands on its own, their true power is unlocked when they are used together.</p><h3>The Simplest Starting Point: Prompt Engineering</h3><p>Prompt engineering is the practice of crafting the text input given to a language model in order to steer its output in a desired direction. Crucially, the model itself is never touched. No weights are updated, no training occurs. Everything happens at the level of the text you write before pressing send. There are four main approaches, each building on the previous in sophistication.</p><p>The first and most accessible is few-shot prompting. Instead of simply asking the model a question, you first show it two or three examples of the kind of question-and-answer pair you are looking for. The model reads these examples, understands the expected pattern, and then applies that understanding to your actual question. If you want the model to classify customer complaints by urgency, you show it a few classified examples before presenting the real ones. This alone produces dramatically more consistent and appropriately formatted outputs compared to asking the model with no context at all.</p><p>The second approach is chain-of-thought prompting. Here, you instruct the model to reason through a problem step by step before giving its final answer, rather than jumping straight to a conclusion. A simple instruction like “think through this carefully and explain each step of your reasoning” is often enough to trigger this behavior. The benefit is particularly visible on tasks involving logic, mathematics, or multi-step inference, where a model that rushes to an answer frequently makes errors that a model walking through the problem carefully would avoid. Chain-of-thought prompting works best when combined with few-shot examples, where the examples themselves demonstrate the kind of step-by-step reasoning you want the model to replicate.</p><p>The third approach is tree of thoughts. This is a more advanced extension of chain-of-thought that changes not just how the model reasons but the shape of that reasoning. Instead of following a single linear path from question to answer, the model is guided to generate multiple candidate reasoning paths simultaneously, evaluate each one, discard the dead ends, and converge on the best option. This mirrors how a human expert actually approaches a difficult problem: by mentally exploring several possibilities before committing. Tree of thoughts is particularly powerful for complex tasks like puzzle-solving or strategic planning, where a single train of thought will often lead the model into a corner.</p><p>The fourth approach is prompt chaining. Rather than asking the model to do everything in a single prompt, prompt chaining breaks the task into a sequence of smaller prompts where the output of each step becomes the input of the next. A practical example: a first prompt takes the user’s original question and reformulates it into three clearer, more specific sub-questions. A second prompt answers each sub-question individually. A third prompt synthesizes those answers into a coherent final response. Each individual prompt is simpler and easier for the model to handle well, and the overall quality of the final output is substantially higher than what a single monolithic prompt would produce. This approach is the backbone of most production AI pipelines, where tasks are too complex to be handled reliably in one shot.</p><p>Prompt engineering is, by a wide margin, the least resource-intensive of the three techniques covered in this article. It requires no additional compute, no labeled datasets, and no special infrastructure. It is the natural first step for any team looking to improve model performance.</p><h3>Going Deeper: Retrieval-Augmented Generation</h3><p>Retrieval-augmented generation, commonly known as RAG, shares the spirit of prompt engineering but goes further. The fundamental idea is the same “give the model better context in order to get better answers” but instead of relying on the human to craft that context by hand, RAG automatically retrieves it from a structured knowledge base.</p><p>Here is how it works in practice. When a user asks a question, the system first searches an internal database for the passages, documents, or records most relevant to that query. Those results are then injected into the prompt alongside the original question, giving the model a rich, specific context to draw from when generating its answer. If a user asks about radiative transfer, for example, the system pulls every relevant excerpt from the knowledge base and passes it to the model. The model no longer has to rely solely on what it learned during training; it has access to domain-specific information provided in real time.</p><p>The effect of this is significant. Models without RAG are prone to giving answers that are generic, outdated, or simply wrong when asked about specialized topics. RAG anchors the model’s responses to verified, up-to-date content from sources the developer controls. It dramatically reduces the problem of hallucination the tendency of language models to generate plausible-sounding but factually incorrect information.</p><p>Implementing RAG well requires genuine data engineering work. The knowledge base must be organized thoughtfully, the retrieval pipeline must be fast and accurate, and the retrieved content must be formatted in a way the model can use effectively. This is meaningfully more demanding than basic prompt engineering, but far less demanding than the third technique.</p><h3>The Most Powerful Option: Fine-Tuning</h3><p>Fine-tuning is the process of continuing to train a model that has already been trained, using a curated dataset specific to a particular domain or task. Unlike prompt engineering and RAG, fine-tuning actually changes the model’s internal parameters. It does not merely influence the model at the input level; it shapes what the model fundamentally knows and how it responds. The result is a model with genuine expertise in a specific area one that understands domain-specific terminology naturally and outperforms its base version without needing elaborate prompts at runtime.</p><p>The cost of this power is real. Fine-tuning requires a labeled dataset, meaning pairs of prompts and ideal responses, that is large enough and representative enough to actually shift the model’s behavior. The training process is compute-intensive, and the entire pipeline must be managed carefully to avoid catastrophic forgetting, where gains in one domain come at the expense of the model’s general capabilities. There are four main methods for doing this, each with a different balance of cost, expressiveness, and complexity.</p><p>Full fine-tuning is the most direct method. Every single parameter in the model is updated during training. To do this in practice with a model like GPT-2, the first step is to load the pre-trained model and its tokenizer from a library like Hugging Face Transformers. You then prepare your labeled dataset in a format where each entry pairs an input text with the expected output. That dataset is tokenized and loaded into a training dataloader. You define an optimizer “Adam is the standard choice “ set a learning rate, and run training for a number of epochs, updating all model weights at each step based on the computed loss. After training, you save the updated model to disk. The upside is that this method produces the most thoroughly adapted model possible. The downside is that it requires significant GPU memory and time, because every one of the model’s millions or billions of parameters must be held in memory and updated simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*w1vnKadcqusyZVX5Y8D2Kg.png" /></figure><p>LoRA, which stands for low-rank adaptation, was designed specifically to address this problem. Instead of updating every parameter, LoRA freezes the original model entirely and injects a pair of small trainable matrices alongside each of the model’s attention layers. These matrices are far smaller than the original weight matrices they capture only the direction of change needed, not the full weight space. In practice, using a model like GPT-2, you first load the frozen base model. You then use a library like PEFT from Hugging Face to wrap the model and specify which layers should receive LoRA adapters and what rank those adapters should have rank 8 or 16 is a typical starting point. Only the adapter matrices are registered as trainable parameters. You run training exactly as you would for full fine-tuning, but the optimizer only touches the adapter matrices. After training, the adapters can optionally be merged back into the original weights, meaning the final model has no added inference cost. LoRA is currently the most popular fine-tuning method in practice precisely because it achieves results close to full fine-tuning at a fraction of the compute cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*GWRUnJxs0MRWFTD0IsTUNQ.png" /></figure><p>Deep prompt tuning, also known as P-tuning v2, takes a fundamentally different approach. Rather than modifying any weights at all including adapter matrices it introduces a set of trainable vectors, called soft prompts, that are inserted into the model’s input at every layer. The model’s weights remain completely frozen throughout. To apply this method to GPT-2, you begin by loading the frozen model and defining a set of soft prompt embeddings essentially a small tensor of randomly initialized or strategically seeded vectors. These vectors are prepended to the tokenized input at each transformer layer before the forward pass. During training, only these vectors receive gradient updates. The key distinction from LoRA is that P-tuning does not learn new attention patterns; it steers the existing ones by adding persistent signals at every layer of processing. This makes it slightly less expressive than LoRA for tasks that require the model to learn entirely new behaviors, but it is simpler to implement and still highly effective for most classification and generation tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*74Cr30IiszUi4g6OsdUZuQ.png" /></figure><p>Adapters represent the third parameter-efficient approach. They work by inserting small, fully connected neural network modules typically two linear layers with a non-linearity in between inside each transformer block, placed serially after the attention and feed-forward sub-layers. To apply adapters to GPT-2, you first modify the model architecture to insert these adapter modules at the correct positions within each layer. The original model weights are frozen, and only the adapter modules are registered as trainable. Training then proceeds normally, with gradients flowing only through the adapter modules. Unlike LoRA, adapters cannot be merged back into the base model after training, which means every inference pass must run the additional adapter computations, introducing a small but measurable latency cost. Adapters are well-established and highly modular you can swap different adapters in and out for different tasks without retraining the entire model which makes them a strong choice when you need to serve multiple specialized tasks from a single shared backbone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*xn2WwL6fuQ4-_vgFd1cx2Q.png" /></figure><p>A final concept worth understanding alongside these methods is continuous pretraining. Before any of the above fine-tuning methods are applied, a model can first be exposed to large amounts of unlabeled domain-specific text in order to deepen its general familiarity with a field’s vocabulary, writing style, and common concepts. Unlike fine-tuning, no question-answer pairs are needed only raw text.</p><p>To apply continuous pretraining to GPT-2, the process works as follows. You begin by collecting your domain corpus: this is simply a large body of plain text relevant to your field, such as research papers, technical documentation, or industry reports, concatenated into one or several large text files. You then load the pre-trained GPT-2 model and its tokenizer from Hugging Face. The corpus is tokenized and chunked into fixed-length sequences typically 512 or 1024 tokens to match GPT-2’s context window. Each chunk is treated as a single training example where the model’s objective is to predict the next token at every position in the sequence, using the standard cross-entropy language modeling loss. Crucially, both the input and the label for each example are the same token sequence; the model simply tries to predict each token from the ones before it. You then run training for several epochs with a very small learning rate, since the model already has strong general language knowledge and you are nudging rather than overwriting it. After training, you save the updated model weights.</p><p>An important detail about what actually changes during this process: continuous pretraining updates all the weights in the model, with no layers frozen. Every attention layer, every feed-forward layer, and the embedding layer all participate in gradient updates at each step. This is precisely why the learning rate must be kept very small large updates would overwrite the model’s existing general knowledge rather than build on it. In practice, however, the meaningful change is concentrated toward the upper layers of the network. Early layers capture general syntactic and low-level linguistic patterns that are largely universal across any coherent text, so they shift very little even when technically eligible for updates. The later layers, which encode more semantic and domain-specific representations, are where the domain shift actually happens.</p><p>This full-weight update also means that continuous pretraining is computationally expensive its memory footprint and compute requirement are identical to full fine-tuning. For GPT-2 small at 117 million parameters this is manageable on a single consumer GPU, but GPT-2 XL at 1.5 billion parameters already pushes the limits of what a single GPU can handle without techniques like gradient checkpointing or mixed precision training. For larger models, continuous pretraining becomes a multi-GPU operation. This cost is best accepted once, up front, on a large domain corpus. The continuously pretrained model then becomes the starting point for any of the parameter-efficient methods described above LoRA, P-tuning, or adapters ,keeping all subsequent task-specific fine-tuning fast and cheap. Continuous pretraining builds broad domain knowledge first, and fine-tuning then sharpens the model on the specific tasks that matter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*On30YTxSnT5DE2KY0Nj5kA.png" /></figure><h3>Conclusion</h3><p>Language models are remarkable, but they are not magic. Getting the most out of them requires deliberate design choices at every level, from the words in a single prompt to the architecture of a full training pipeline. Prompt engineering gives us control over how we ask questions. Retrieval-augmented generation gives us control over what context the model works with. Fine-tuning gives us control over what the model has internalized as knowledge. Each technique has its own cost, its own ceiling, and its own appropriate moment of application. Understanding all three and knowing when and how to combine them is what separates systems that merely function from systems that genuinely excel.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e927bebc165" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Architecture Search: A Deep Dive into Automated Deep Learning]]></title>
            <link>https://medium.com/@ykarray29/neural-architecture-search-a-deep-dive-into-automated-deep-learning-a922eb1114a0?source=rss-25b22d7e4148------2</link>
            <guid isPermaLink="false">https://medium.com/p/a922eb1114a0</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neuralarchitecturesearch]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nas]]></category>
            <dc:creator><![CDATA[yasmine karray]]></dc:creator>
            <pubDate>Sat, 07 Mar 2026 00:29:12 GMT</pubDate>
            <atom:updated>2026-03-07T14:20:49.010Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This blog is written after reading two survey papers: </em>White, C., Safari, M., Sukthanker, R., Ru, B., Elsken, T., Zela, A., Dey, D. &amp; Hutter, F. (2023). “Neural Architecture Search: Insights from 1000 Papers.” <em>arXiv:2301.08727</em>.<a href="https://arxiv.org/abs/2301.08727"> https://arxiv.org/abs/2301.08727</a> Chitty-Venkata, K. T. et al. (2024). “Systematic Review on Neural Architecture Search.” <em>Artificial Intelligence Review</em>, Springer.<a href="https://link.springer.com/article/10.1007/s10462-024-11058-w"> https://link.springer.com/article/10.1007/s10462-024-11058-w</a><em>. My goal is not just to summarize those papers, but to give you real intuition for what NAS is, why it works the way it does, and how all the pieces connect.</em></p><p>Designing a neural network is hard. You have to decide how many layers to use, which operations to include at each layer, how to connect them, and dozens of other choices — and each choice affects performance in ways that are rarely obvious. For years, these decisions were made by human experts through experience, intuition, and a lot of trial and error.</p><p>Neural Architecture Search (NAS) is the field that asks: what if we automated this process? What if, instead of a human engineer searching for a good architecture, an algorithm did it? That question has driven one of the most active and consequential research areas in deep learning over the past decade.</p><h3>What Exactly Are We Trying to Solve?</h3><p>Before diving into methods, let’s be precise about the problem.</p><p>We have a search space <strong>A</strong> — a set of all candidate architectures we are willing to consider. We have a dataset <strong>D</strong> and a fixed training pipeline <strong>P</strong> (optimizer, learning rate schedule, augmentation, etc.). We have a compute budget <strong>t</strong>. The goal is to find the architecture <strong>a ∈ A</strong> that, when trained with D and P, achieves the best possible validation performance.</p><p>Formally, we want to solve:</p><pre>min_{a ∈ A}  L_val(w*(a), a)</pre><pre>where  w*(a) = argmin_w L_train(w, a)</pre><p>Read this carefully: we’re not just minimizing training loss. We want the architecture whose <em>best possible weights</em> lead to the <em>best validation performance</em>. There’s a nested optimization here — the inner problem finds the best weights for a given architecture, and the outer problem finds the best architecture. This nested structure is what makes NAS genuinely difficult.</p><p>In practice, fully solving this problem is computationally intractable. The search space can contain anywhere from thousands to over 10 ²⁰ candidate architectures, and each evaluation requires training a model. That’s why the entire field is essentially an answer to the question: <em>how do we make this tractable?</em></p><h3>The Three Pillars of NAS</h3><p>Every NAS method, regardless of how sophisticated, is built on three components that interact with each other:</p><p><strong>The Search Space</strong> defines <em>which</em> architectures can be considered. If an architecture isn’t in your search space, you can’t find it — no matter how good your search algorithm is.</p><p><strong>The Search Strategy</strong> defines <em>how</em> you explore the search space. Given that you can’t evaluate everything, how do you decide what to try next?</p><p><strong>The Performance Estimation Strategy</strong> defines <em>how you evaluate</em> a candidate architecture efficiently — without having to train it from scratch every time.</p><p>These three pillars are not independent. The search space you choose constrains which strategies are feasible. Your estimation strategy affects how much signal your search algorithm actually receives. Understanding NAS means understanding not just each pillar in isolation, but how they interact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*wj1Ubinga2vZiWPHFDtheg.png" /></figure><h3>Pillar 1 — The Search Space</h3><p>Think of the search space as the “design vocabulary” of your NAS system. A human architect choosing to design buildings can only work with the materials and concepts they know exist. Similarly, a NAS algorithm can only find architectures that exist within its defined search space.</p><p>This creates a fundamental trade-off:</p><ul><li>A <strong>small, highly constrained</strong> search space makes search fast, but you’re essentially encoding the biases of whoever designed the space. You won’t discover anything genuinely surprising.</li><li>A <strong>large, loosely constrained</strong> search space gives the algorithm more creative freedom, but makes search far more expensive.</li></ul><p>There are four main types of search spaces, each making different trade-offs.</p><h3>Global (Macro) Search Space</h3><p>In a global search space, the NAS algorithm designs the <strong>entire network architecture</strong>. For example, it might discover a model like:<br> Input → Conv3×3 (32 filters) → MaxPool → Conv5×5 (64 filters) → Conv3×3 (128 filters) → Fully Connected → Output.<br> Another architecture could have a completely different number of layers or connections. The algorithm is free to change <strong>everything in the network</strong>, which makes the search space extremely large.</p><h3>Chain-Structured Search Space</h3><p>In a chain-structured search space, the architecture must follow a <strong>simple sequential structure</strong>, where each layer receives input only from the previous one. For example:<br> Input → Conv3×3 (32) → Conv3×3 (64) → MaxPool → Conv5×5 (128) → Fully Connected → Output.<br> The NAS algorithm chooses the <strong>type and parameters of each layer</strong>, but it is constrained because the design of layer <em>i</em> depends on layer <em>i-1</em>. For instance, to decide the configuration of layer 2, the algorithm must consider the output of layer 1. This means the search is <strong>not completely free</strong>, and skip connections or branching are not allowed.</p><h3>Cell-Based Search Space</h3><p>In a cell-based search space, the algorithm searches for a <strong>small building block called a cell</strong>, instead of designing the entire network.</p><p>A <strong>cell</strong> is a small computational graph composed of a few nodes connected by operations such as Conv3×3, Conv5×5, MaxPool, or Skip Connection. It defines how data flows between these nodes.</p><p>Once the best cell is discovered, the final network is built by <strong>repeating this cell multiple times</strong>, for example:</p><p>Input → Cell → Cell → Cell → Cell → Output.</p><p>This approach reduces the size of the search space while still allowing complex architectures to emerge.</p><h3>Hierarchical Search Space</h3><p>In a hierarchical search space, the architecture is built at <strong>multiple levels of abstraction</strong>.</p><p>A <strong>cell</strong> is the basic building block composed of operations and connections.<br> Several cells can then be grouped into a <strong>block</strong>, which is a larger module that repeats a pattern of cells.</p><p>The full network is built by stacking these blocks:</p><p>Input → Block1 (3 cells) → Block2 (3 cells) → Block3 (3 cells) → Output.</p><p>This hierarchical structure allows the algorithm to represent more complex architectures, but it also makes the search process more difficult because decisions at different levels interact with each other.</p><h3>Pillar 2 — The Search Strategy</h3><p>Once the search space is defined, the next question is: <strong>how do we explore it efficiently?</strong> Since training neural networks is expensive, we usually have a limited <strong>budget of architecture evaluations</strong>. The challenge is deciding how to spend this budget to find a good model.</p><p>Search strategies generally fall into two main families:</p><ul><li><strong>Black-Box Optimization (BBO) methods</strong> treat each architecture as an independent candidate. For every architecture proposed during the search, a <strong>separate model is trained and evaluated</strong> to measure its performance. The algorithm then uses these results to decide which architectures to try next.</li><li><strong>One-Shot methods</strong> take a different approach. Instead of training each architecture separately, they train <strong>a single large network (often called a supernetwork)</strong> that contains all possible architectures in the search space. Different architectures correspond to different paths inside this network, and they <strong>share the same weights</strong>, allowing many architectures to be evaluated much faster.</li></ul><p>In short, <strong>BBO methods evaluate architectures one by one</strong>, while <strong>One-Shot methods evaluate many architectures simultaneously through weight sharing</strong>.</p><h3>Black-Box Optimization</h3><p>The defining feature of BBO is that each iteration trains an architecture from scratch and measures its performance. The algorithm uses those measurements to guide future choices. It’s “black-box” because the algorithm doesn’t look inside the training process — it just sees the input (architecture) and output (performance).</p><p><strong>The big disadvantage:</strong> training each architecture independently is expensive. But the <strong>big advantage</strong> is flexibility — BBO makes no assumptions about the structure of the search space or the training process, which means it works broadly.</p><h4>Random Search — The Baseline You Shouldn’t Underestimate</h4><p>The simplest possible strategy: sample architectures uniformly at random and keep the best.</p><pre>For i = 1 to K:<br>    Sample architecture a_i uniformly from A<br>    Evaluate performance(a_i)<br>Return the best a_i</pre><p>Surprisingly, random search is a remarkably strong baseline. On well-designed search spaces where most architectures achieve reasonable performance, random search with a sufficient budget can match or beat far more sophisticated methods.</p><h4>Local Search</h4><p>Local search starts with a random architecture and iteratively moves to neighboring architectures (those differing by a single operation or connection change), keeping only improvements.</p><h4>Reinforcement Learning</h4><p>RL treats architecture design as a sequential decision-making problem. An agent (called the “controller”) generates architectures one decision at a time — choosing the operation for each layer, the number of filters, which connections to make. After each architecture is generated, it’s trained and its validation accuracy becomes the <strong>reward</strong> signal.</p><p>To understand the setup clearly, let’s name each component:</p><p><strong>The agent</strong> is the controller — the entity that learns to make better decisions over time. It implements a <strong>policy</strong> (a strategy for choosing actions given the current state). <strong>Actions</strong> are architectural choices: picking an operation, deciding on a connection. <strong>The environment</strong> is the training and evaluation process: the agent proposes an architecture, the environment trains it and returns a reward.</p><p>The reward can be as simple as:</p><pre>Reward = Validation Accuracy</pre><p>Or more nuanced, incorporating hardware constraints:</p><pre>Reward = Accuracy - λ × Latency</pre><p>The controller is trained using policy gradient methods , gradually shifting its distribution toward architectures that yield higher rewards.</p><h4>Evolutionary Algorithms</h4><p>Evolutionary algorithms maintain a <strong>population</strong> of architectures that evolve over time, mimicking biological evolution. The core loop is:</p><pre>Initialize population P with randomly sampled (trained) architectures<br>For each generation t:<br>    Select parent architectures from P<br>    Apply mutations to create child architectures<br>    Train the children<br>    Add children to P; remove the weakest (or oldest)<br>Return the best architecture in P</pre><p><strong>Mutations</strong> can include: changing a single operation on an edge, adding or removing a skip connection, or modifying the number of filters. Importantly, children can <strong>inherit weights</strong> from their parents for the unchanged portions of the architecture, which dramatically speeds up evaluation.</p><p>One powerful concept is <strong>island evolution</strong>: maintain several subpopulations that evolve independently (for example, one island where networks have at most 4 layers, another where they have more), and occasionally allow the best architectures from different islands to mix. This balances exploration (each island develops its own niche) with exploitation (the best solutions from all islands eventually compete).</p><p>A particularly effective variant is <strong>Regularized Evolution</strong> (Real et al., 2019), which eliminates the <em>oldest</em> individual from the population rather than the weakest. This might seem counterintuitive, but it forces continuous exploration by preventing the population from converging prematurely to a single strong solution. Regularized Evolution outperformed both RL-based and random search methods in direct comparison.</p><h4>Bayesian Optimization</h4><p>Bayesian optimization takes a more principled approach to the exploration-exploitation trade-off. Rather than randomly or heuristically choosing the next architecture to evaluate, it builds a <strong>probabilistic model</strong> (called a surrogate) that predicts the performance of any architecture based on past evaluations — including a measure of <em>uncertainty</em>.</p><p>The algorithm has two key components working together:</p><p><strong>The surrogate model</strong> is trained on all past (architecture, performance) pairs. It outputs not just a predicted performance but also a confidence interval.</p><p><strong>The acquisition function</strong> uses the surrogate’s prediction and uncertainty to score every unvisited architecture and select the most promising one to evaluate next. It explicitly balances:</p><ul><li><em>Exploitation:</em> evaluating architectures the model thinks are probably good.</li><li><em>Exploration:</em> evaluating architectures the model is uncertain about (they might be surprisingly good).</li></ul><pre>Initialize with a few random evaluations<br>For t = 1 to T:<br>    Fit surrogate model on all past evaluations<br>    Select next architecture: a_t = argmax_a AcquisitionFunction(a)<br>    Train a_t, record performance<br>    Add to dataset<br>Return best architecture found</pre><p>Common acquisition functions include <strong>Expected Improvement (EI)</strong> and <strong>Upper Confidence Bound (UCB)</strong>, but they prioritize candidates in different ways.</p><p><strong>Expected Improvement (EI)</strong> focuses on <strong>how much an architecture is expected to improve over the current best result</strong>. It favors architectures that are likely to produce a <strong>measurable gain compared to the best architecture found so far</strong>, balancing good predicted performance with some uncertainty.</p><p><strong>Upper Confidence Bound (UCB)</strong>, on the other hand, explicitly balances <strong>exploitation and exploration</strong>. It scores each architecture using its <strong>predicted performance plus a term proportional to its uncertainty</strong>. This means it may select architectures that are uncertain but potentially promising, encouraging the algorithm to explore less-tested regions of the search space.</p><p>BO shines when each evaluation is expensive and you want maximum <strong>sample efficiency</strong> — getting the most out of every training run. If you have a budget of 50–500 architecture evaluations, BO is often the right tool.</p><h4>Monte Carlo Tree Search</h4><p>MCTS reframes architecture design as a tree search problem. Building an architecture is a sequence of decisions (choose a layer type, then an operation, then connections…) — exactly the kind of problem MCTS was designed for.</p><p>The tree has a simple structure:</p><ul><li>The <strong>root</strong> represents an empty network.</li><li>Each <strong>branch</strong> represents a single architectural decision.</li><li>Each <strong>leaf</strong> represents a complete architecture.</li></ul><p>MCTS explores this tree over four repeating steps:</p><p><strong>1. Selection</strong> — Starting from the root, descend the tree by always choosing the action with the highest UCB score:</p><pre>UCB(s, a) = Q(s,a) + c × sqrt( ln N(s) / N(s,a) )</pre><p>where Q(s,a) is the average performance of action a from state s, N(s) is how many times state s has been visited, and N(s,a) is how many times action a was chosen from s. The first term exploits what we know; the second term encourages visiting less-explored branches.</p><p><strong>2. Expansion</strong> — When we reach a node that hasn’t been fully explored, add a new child node representing a new architectural decision.</p><p><strong>3. Simulation (Rollout)</strong> — From the new node, complete the architecture randomly, then quickly evaluate it (often with a partial training run or a proxy metric).</p><p><strong>4. Backpropagation</strong> — Propagate the evaluation result back up the tree, updating the visit counts and average performance of all ancestor nodes.</p><p>Over many iterations, MCTS builds up a detailed map of which early decisions tend to lead to strong final architectures, and concentrates its search budget accordingly.</p><h3>One-Shot Techniques — The Game Changer</h3><p><strong>The core problem</strong> with traditional NAS is cost: evaluating 1,000 architectures means training 1,000 separate networks, which can take days or weeks. One-shot methods eliminate this by training a single large network — called a <strong>supernetwork</strong> — that contains all possible operations and connections at once. Every candidate architecture is simply a path through this shared network, so instead of training each one independently, you train the supernetwork once and extract architectures from it for free.</p><p><strong>Non-differentiable one-shot methods</strong> work in two stages. First, you train the supernetwork by randomly sampling a different architectural path at each training step — one iteration might use Conv3×3 followed by a skip connection, the next might use MaxPool followed by Conv3×3. Only the weights involved in the sampled path get updated that step. Over many iterations, all parts of the supernetwork receive training. Second, once the supernetwork is trained, you run a search — often just random search — by testing many architectural paths using the already-trained weights, and keeping the best one. The key saving is that no architecture needs to be trained from scratch. <strong>Once-for-All (OFA)</strong> is the most prominent example: it trains one supernetwork and then extracts tailored sub-networks for different devices without retraining.</p><p><strong>DARTS</strong> (Differentiable Architecture Search) takes a more elegant approach. Rather than sampling one operation per step, it runs all candidate operations simultaneously and assigns each a learnable weight. The output of a layer becomes a weighted mixture — for example, 60% Conv3×3, 30% Conv5×5, 10% MaxPool. These weights are learned jointly with the network weights through standard gradient descent. Once training converges, the architecture is discretized by keeping only the operation with the highest weight at each layer, and the resulting architecture is retrained from scratch. The appeal of DARTS is that the architecture search itself becomes differentiable, turning what was a discrete combinatorial problem into a continuous optimization.</p><p><strong>Hypernetworks</strong> take a different angle entirely: instead of sharing weights through a supernetwork, a separate neural network — the hypernetwork — learns to <em>generate</em> the weights of any given architecture on demand. You describe an architecture as input, and the hypernetwork outputs a full set of weights for it instantly, without any training. This allows you to evaluate thousands of architectures in seconds. The trade-off is accuracy: generated weights are rougher than fully trained ones, so hypernetworks are best used as a fast filter to identify promising candidates, which can then be evaluated more carefully.</p><h3>Pillar 3 — Performance Estimation</h3><p>Every search strategy needs feedback: which architectures are promising? Full training is too expensive, so we need faster approximations.</p><h3>Learning Curve Extrapolation</h3><p>Instead of training an architecture to convergence, train it for a few epochs and <strong>extrapolate</strong> the performance curve to predict its final value. The partial curve (a sequence of validation accuracies at each epoch) is fit to a parameterized model known to capture learning curve shapes well (Weibull, log-power, log-log linear, Janoschek, etc.).</p><p>The intuition is straightforward: some architectures start converging quickly toward high accuracy; others plateau early at mediocre values. A few epochs are often enough to distinguish these trajectories.</p><p>This works well when combined with Bayesian optimization (the surrogate can take both the architecture encoding and the partial curve as input) and with multi-fidelity methods. It’s less reliable for architectures with unusual training dynamics.</p><h3>Zero-Cost Proxies</h3><p>Zero-cost proxies are the most recent and ambitious approach: assign a score to an architecture using only a single forward/backward pass — or even no data at all. No training required whatsoever.</p><p>Some examples:</p><p><strong>SynFlow — measures gradient flow</strong></p><p>The core question it answers: <em>Can gradients travel through this network without vanishing?</em></p><p>At initialization, some networks have many strong, connected paths from input to output. Others have bottleneck layers where signals die out. SynFlow scores each architecture by computing how well information can propagate through all paths — essentially multiplying weight magnitudes along every route. A high score means gradients are likely to flow well during actual training. A low score is a warning sign of dead zones.</p><p><strong>NASWOT — measures expressivity</strong></p><p>The core question it answers: <em>Can this network distinguish between different inputs?</em></p><p>A powerful network should produce different activation patterns for different inputs. A weak one treats many distinct inputs as similar — it can’t separate them. NASWOT feeds a batch of inputs through the network and looks at the binary activation patterns produced by ReLU layers. If two inputs produce identical patterns, the network can’t tell them apart. More unique patterns = more expressive architecture.</p><p>The core question it answers: <em>How efficiently will gradient descent improve this network?</em></p><p>The Neural Tangent Kernel captures how much the network’s output changes when its weights are updated. If a small weight change causes a meaningful output change, gradient descent can make fast progress. If weight updates barely affect outputs, training will be slow and inefficient. A well-conditioned NTK (eigenvalues are neither too large nor too small) signals that the network will learn smoothly.</p><p>Zero-cost proxies are most valuable as a <strong>pre-filtering step</strong>: use them to eliminate obviously bad candidates before doing more expensive evaluations on the survivors.</p><h3>Multi-Fidelity Algorithms</h3><p>Multi-fidelity methods solve a simple problem: you can’t afford to fully train every candidate architecture, so instead you allocate compute dynamically — evaluate many architectures cheaply first, then spend more resources only on the ones that look promising.</p><p>The foundation is <strong>Successive Halving (SH)</strong>. You start with N architectures and give each a small budget — say, a few epochs on a subset of the data. After this cheap evaluation, you throw away the bottom half and give the survivors twice the budget. You repeat this cycle — train longer, eliminate the worst half — until one architecture remains. The logic is that a bad architecture usually reveals itself early, so there’s no point training it to convergence.</p><p>The problem with SH is that you have to manually decide the minimum starting budget, and the wrong choice can hurt performance significantly. <strong>Hyperband</strong> solves this by simply running SH multiple times in parallel, each time with a different starting budget. This removes the need to guess the right setting upfront — you cover multiple strategies at once and let the results speak for themselves.</p><p><strong>BOHB</strong> (Bayesian Optimization + Hyperband) takes this a step further by making the search smarter over time. In early iterations it behaves exactly like Hyperband, sampling architectures at random because there isn’t enough data yet to do better. But as evaluations accumulate, BOHB builds a surrogate model — a learned approximation of which configurations tend to perform well — and uses it to propose better candidates rather than guessing blindly. The result is an algorithm that is both efficient in compute (thanks to Hyperband’s multi-fidelity structure) and increasingly intelligent in its choices (thanks to Bayesian optimization). In practice, BOHB consistently ranks among the best-performing methods when resources are limited.</p><h3>Meta-Learning</h3><p>Meta-learning (“learning to learn”) uses knowledge from previous NAS runs to accelerate new ones. Instead of starting from scratch each time, you warm-start the search using configurations that worked well on similar tasks.</p><p>In NAS, this can mean initializing the search with architectures that performed well on related datasets, or training a surrogate model that predicts performance on a new task using an encoding of that task’s dataset.</p><p>Meta-learning pays off when you run NAS on many similar tasks (e.g., a company applying NAS across dozens of datasets). For a single isolated task, the overhead of meta-learning isn’t justified.</p><h3>Weight Inheritance and Network Morphisms</h3><p>When you mutate an architecture (say, by adding a layer or changing one operation), you don’t need to retrain it from scratch. <strong>Weight inheritance</strong> copies unchanged portions of the weights directly from the parent architecture, then trains only the new or changed portions. This is extensively used in evolutionary NAS and can dramatically reduce evaluation cost.</p><p>Network morphisms take this idea further with a clever trick: when you modify an architecture, you do it in a way that preserves the function it computes. In other words, the new, larger network starts by doing <em>exactly the same thing</em> as the old one — then you train it from there.</p><p>To make this concrete: suppose your network has a layer that applies some transformation. You want to add a new layer after it. A naive approach would initialize that new layer randomly, which disrupts everything the network has already learned. A network morphism instead initializes the new layer as an <strong>identity</strong> — it just passes its input through unchanged. The network now has one more layer, but its output is identical to before. Training then picks up from this stable starting point, and the new layer gradually learns to do something useful.</p><p>The same principle applies to widening: if you want to double the number of filters in a layer, you copy the existing filters rather than generating random ones. Again, the output is preserved, and training continues from a functioning model rather than starting over.</p><p>The benefit is significant — instead of training a large network from scratch, you grow it incrementally and each new piece begins life in a useful state rather than a random one</p><h3>Extensions: Where NAS Goes From Here</h3><h3>Joint NAS + Hyperparameter Optimization</h3><p>Joint NAS + HPO search over the combined space of architectures and training hyperparameters simultaneously. The challenge is that the interactions between architecture choices and hyperparameter choices are complex — the best learning rate for one architecture may be terrible for another. BO and evolutionary methods with weight sharing are the most natural fits for this joint optimization.</p><h3>Constrained and Multi-Objective NAS</h3><p>In real deployments, accuracy alone is not enough. A model running on a smartphone must be fast and lightweight; a medical model may need to satisfy fairness requirements. NAS can account for this in two ways.</p><p>The first is <strong>constrained NAS</strong>: you optimize for accuracy as usual, but only consider architectures that stay within hard limits — for example, latency under 10ms or memory under 50MB. You get the best accurate model that still fits your device.</p><p>The second is <strong>multi-objective NAS</strong>: instead of enforcing hard limits, you search for the full trade-off curve — called the <strong>Pareto front</strong> — which contains all architectures where no other candidate is strictly better on every objective at once. The advantage is flexibility: once you have the Pareto front, you can pick your preferred trade-off point (say, slightly slower but much more accurate) without re-running the search from scratch.</p><p>Measuring hardware cost in practice ranges from simple proxies like parameter count to more accurate surrogate models trained on real device measurements. <strong>Once For All (OFA)</strong> is the most prominent example of this approach at scale — it trains a single large network from which sub-networks of different sizes and latencies can be extracted, avoiding the need to run a separate search for each target device.</p><h3>Putting It All Together</h3><p>NAS is not one method — it’s a framework, and every real-world NAS system makes concrete choices at each of the three pillars. Those choices interact:</p><p>A cell-based search space pairs naturally with DARTS (differentiable, works on small structured spaces) or random search with weight sharing. A large macro space probably requires evolutionary methods or BO with a powerful surrogate. Hardware-constrained deployment calls for multi-objective optimization and OFA-style supernetworks. Limited compute pushes you toward zero-cost proxies and multi-fidelity methods.</p><p>The most important lesson from the NAS literature — supported by White et al.’s analysis of 1000 papers — is that <strong>the search space matters more than the search algorithm</strong>. A good search space with random search will outperform a bad search space with a sophisticated algorithm. Before reaching for the most complex optimization method, ask: is my search space well-designed? Does it contain many strong architectures? Are bad architectures easy to distinguish from good ones?</p><p>If the answers are yes, you’re most of the way there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a922eb1114a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[L’algorithme TES d’ASTER : Séparation température-émissivité par les modules NEM, RATIO et MMD]]></title>
            <link>https://medium.com/@ykarray29/lalgorithme-tes-d-aster-s%C3%A9paration-temp%C3%A9rature-%C3%A9missivit%C3%A9-par-les-modules-nem-ratio-et-mmd-ceaf27d3fb1d?source=rss-25b22d7e4148------2</link>
            <guid isPermaLink="false">https://medium.com/p/ceaf27d3fb1d</guid>
            <category><![CDATA[te]]></category>
            <category><![CDATA[asters]]></category>
            <category><![CDATA[temperature]]></category>
            <category><![CDATA[remote-sensing]]></category>
            <category><![CDATA[emissivity]]></category>
            <dc:creator><![CDATA[yasmine karray]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 16:23:31 GMT</pubDate>
            <atom:updated>2025-12-19T17:46:33.004Z</atom:updated>
            <content:encoded><![CDATA[<h3>L’algorithme TES d’ASTER : Séparation température-émissivité par les modules NEM, RATIO et MMD</h3><p><strong>Source:</strong> <a href="https://ieeexplore.ieee.org/document/700995">https://ieeexplore.ieee.org/document/700995</a><br> <strong>DOI:</strong> 10.1109/36.700995<br> <strong>Auteurs:</strong> A. Gillespie; S. Rokugawa; T. Matsunaga; J.S. Cothern; S. Hook; A.B. Kahle<br> <strong>Date de Publication:</strong> 31 July 1998</p><h3>Introduction</h3><p>L’instrument ASTER (Advanced Spaceborne Thermal Emission and Reflection Radiometer) embarqué sur le satellite Terra a révolutionné l’observation thermique de la Terre. Au cœur de ses capacités se trouve l’algorithme TES (Temperature-Emissivity Separation), une innovation majeure qui résout l’un des problèmes les plus complexes de la télédétection thermique : séparer la température de surface de l’émissivité spectrale d’un matériau.</p><p>Cette distinction est cruciale car la radiance mesurée par un capteur thermique dépend simultanément de deux facteurs : la température de la surface et sa capacité à émettre du rayonnement infrarouge (l’émissivité). Sans méthode robuste pour les dissocier, toute analyse quantitative devient impossible. L’algorithme TES combine trois modules complémentaires (NEM, RATIO et MMD) pour résoudre ce défi mathématique avec une précision remarquable de 1,5 K sur la température.</p><h3>Les bandes thermiques d’ASTER</h3><p>ASTER dispose de cinq bandes dédiées à l’infrarouge thermique (TIR), numérotées de 10 à 14. Toutes sont positionnées dans la fenêtre atmosphérique de 8 à 12 µm, zone où l’absorption par la vapeur d’eau est minimale, maximisant ainsi la transmission du signal thermique de surface :</p><ul><li><strong>Bande 10 :</strong> 8,125–8,475 µm</li><li><strong>Bande 11 :</strong> 8,475–8,825 µm</li><li><strong>Bande 12 :</strong> 8,925–9,275 µm</li><li><strong>Bande 13 :</strong> 10,25–10,95 µm</li><li><strong>Bande 14 :</strong> 10,95–11,65 µm</li></ul><p>Chaque pixel thermique couvre une surface de 90 mètres, avec un cycle de revisite nominal de 16 jours à l’équateur. Ce compromis entre résolution spatiale et sensibilité radiométrique permet d’obtenir des mesures précises tout en couvrant de vastes territoires.</p><p><strong>Source:</strong> <a href="https://www.earthdata.nasa.gov/data/instruments/aster/spectral-bands">https://www.earthdata.nasa.gov/data/instruments/aster/spectral-bands</a></p><h3>Architecture de l’algorithme TES</h3><p>L’algorithme TES fonctionne en quatre étapes séquentielles, chacune corrigeant les limitations de la précédente :</p><ol><li><strong>NEM (Normalized Emissivity Method) :</strong> Un processus itératif pour estimer la température et l’émissivité en corrigeant le rayonnement atmosphérique.</li><li><strong>Module RATIO :</strong> Calcul d’émissivités relatives stables indépendantes de la température</li><li><strong>MMD (Maximum-Minimum Difference) :</strong> Prédiction de l’émissivité minimale réelle via une relation empirique</li><li><strong>Calcul final :</strong> Raffinement de la température et du spectre d’émissivité complet</li></ol><h3>Exemple détaillé avec deux bandes spectrales</h3><p>Pour illustrer concrètement le fonctionnement de l’algorithme, suivons un exemple simplifié avec deux bandes uniquement.</p><h3>Données d’entrée</h3><p><strong>Bandes spectrales :</strong></p><ul><li>Bande 1 : λ₁ = 9,0 µm</li><li>Bande 2 : λ₂ = 10,0 µm</li></ul><p><strong>Radiances mesurées (après correction atmosphérique) :</strong></p><ul><li>L_surface,1 = 12,5 W/(m²·sr·µm)</li><li>L_surface,2 = 11,8 W/(m²·sr·µm)</li></ul><p><strong>Constantes :</strong></p><ul><li>c₁ = 2·h·c² = 1,191 × 1⁰⁸ W·µm⁴/(m²·sr)<br> où h est la constante de Planck (6,626 × 10⁻³⁴ J·s)<br> et c est la vitesse de la lumière (2,998 × 1⁰⁸ m/s)</li><li>c₂ = h·c/k = 1,439 × 1⁰⁴ µm·K<br> où k est la constante de Boltzmann (1,381 × 10⁻²³ J/K)</li></ul><h3>Étape 1 : Module NEM (Normalized Emissivity Method)</h3><p>Le NEM est un processus itératif qui permet de séparer la radiance émise par la surface de celle réfléchie par l’atmosphère descendante. Contrairement à une simple lecture directe, il fonctionne par raffinements successifs jusqu’à convergence.</p><h3>Principe physique</h3><p>La radiance mesurée au niveau de la surface combine deux contributions :</p><p><strong>L_surface,i = ε_i · B_i(T) + (1 — ε_i) · L_ciel,i</strong></p><p>où :</p><ul><li>ε_i · B_i(T) est la radiance émise par la surface</li><li>(1 — ε_i) · L_ciel,i est le rayonnement atmosphérique réfléchi</li></ul><p><strong>Le problème circulaire :</strong> Pour calculer l’émissivité ε_i, on a besoin de connaître la contribution réfléchie, mais pour calculer cette réflexion, il faut déjà connaître ε_i (via la loi de Kirchhoff : ρ = 1 — ε). D’où la nécessité d’une approche itérative.</p><h3>1.1 — Initialisation : Hypothèse de l’émissivité maximale</h3><p>Le module NEM commence par une hypothèse simplificatrice : on suppose qu’au moins une bande spectrale atteint une émissivité maximale fixée à ε_max = 0,98. Cette valeur est réaliste pour la plupart des surfaces naturelles.</p><p>Première itération : On néglige le terme de réflexion atmosphérique ou on utilise une estimation approximative de L_ciel.</p><h3>1.2 — Identification du canal à radiance maximale</h3><p>On identifie la bande qui présente la radiance mesurée la plus élevée :</p><ul><li>L_surface,1 = 12,5 W/(m²·sr·µm) ← <strong>Maximum</strong></li><li>L_surface,2 = 11,8 W/(m²·sr·µm)</li></ul><p>Le canal 1 (λ₁ = 9,0 µm) présente la radiance maximale et est donc supposé avoir l’émissivité maximale.</p><h3>1.3 — Calcul de la radiance du corps noir équivalente (itération n)</h3><p>En supposant que ce canal a l’émissivité ε_max, on calcule quelle serait la radiance d’un corps noir :</p><p><strong>B₁(T⁽ⁿ⁾) = [L_surface,1 — (1 — ε_max) · L_ciel,1] / ε_max</strong></p><p>Pour la première itération, si on néglige la réflexion :</p><p><strong>B₁(T⁽⁰⁾) = L_surface,1 / ε_max = 12,5 / 0,98 = 12,755 W/(m²·sr·µm)</strong></p><h3>1.4 — Inversion de la loi de Planck</h3><p>La loi de Planck inversée donne la température :</p><p><strong>T⁽ⁿ⁾ = c₂ / [λ · ln(1 + c₁/(B · λ⁵))]</strong></p><p>Pour λ₁ = 9,0 µm et B₁ = 12,755 W/(m²·sr·µm) :</p><p><strong>T⁽⁰⁾ = 14390 / [9,0 · ln(1 + 1,191×1⁰⁸/(12,755 × 9,⁰⁵))] ≈ 315,4 K</strong></p><h3>1.5 — Calcul des émissivités (itération n)</h3><p>Avec la température T⁽ⁿ⁾, on calcule l’émissivité de chaque bande :</p><p><strong>Pour la bande 1 :</strong></p><p>ε₁⁽ⁿ⁾ = [L_surface,1 — L_ciel,1 · (1 — ε₁⁽ⁿ⁻¹⁾)] / B₁(T⁽ⁿ⁾)</p><p>En première approximation (négligeant la réflexion) :</p><p><strong>ε₁⁽⁰⁾ = L_surface,1 / B₁(T⁽⁰⁾) = 12,5 / 12,755 = 0,98</strong></p><p><strong>Pour la bande 2 :</strong></p><p>Calcul de B₂ à cette température :</p><p><strong>B₂(315,4 K, 10,0 µm) ≈ 12,55 W/(m²·sr·µm)</strong></p><p>Puis l’émissivité :</p><p><strong>ε₂⁽⁰⁾ = L_surface,2 / B₂(T⁽⁰⁾) = 11,8 / 12,55 ≈ 0,940</strong></p><h3>1.6 — Boucle itérative et convergence</h3><p><strong>Étapes répétées jusqu’à convergence :</strong></p><ol><li>Avec les émissivités ε_i⁽ⁿ⁾, on calcule la réflectance : ρ_i⁽ⁿ⁾ = 1 — ε_i⁽ⁿ⁾</li><li>On estime la contribution réfléchie : (1 — ε_i⁽ⁿ⁾) · L_ciel,i</li><li>On soustrait cette contribution de L_surface,i pour obtenir la radiance émise “pure”</li><li>On recalcule une nouvelle température T⁽ⁿ⁺¹⁾</li><li>On recalcule de nouvelles émissivités ε_i⁽ⁿ⁺¹⁾</li></ol><p><strong>Critère d’arrêt :</strong> On arrête lorsque |T⁽ⁿ⁺¹⁾ — T⁽ⁿ⁾| &lt; 0,01 K</p><p>En pratique, la convergence est généralement atteinte en 3 à 5 itérations pour des surfaces courantes.</p><h3>Résultat du module NEM (après convergence)</h3><ul><li><strong>Température initiale :</strong> T_NEM = 315,4 K</li><li><strong>Spectre d’émissivité initial :</strong></li><li>ε₁,NEM = 0,98 (bande à 9,0 µm)</li><li>ε₂,NEM = 0,94 (bande à 10,0 µm)</li></ul><p><strong>Limitation :</strong> Cette estimation reste sensible au choix de ε_max et à la qualité de l’estimation de L_ciel. C’est pourquoi les modules RATIO et MMD sont nécessaires pour raffiner ces résultats.</p><h3>Étape 2 : Module RATIO</h3><p>Le module RATIO s’affranchit de l’incertitude sur la température absolue en travaillant avec des émissivités relatives.</p><h3>2.1 — Calcul de l’émissivité moyenne</h3><p>On calcule la moyenne arithmétique des émissivités obtenues par NEM :</p><p><strong>ε_moy = (0,98 + 0,94) / 2 = 0,96</strong></p><h3>2.2 — Calcul des ratios d’émissivité (β)</h3><p>On normalise chaque émissivité par cette moyenne. Ces valeurs β sont les “émissivités relatives” :</p><p><strong>β_i = ε_i,NEM / ε_moy</strong></p><p>Calcul numérique :</p><ul><li>β₁ = 0,98 / 0,96 ≈ 1,0208</li><li>β₂ = 0,94 / 0,96 ≈ 0,9792</li></ul><p><strong>Point clé :</strong> Le spectre des β est très stable. Même si T_init comportait une erreur, les rapports entre bandes resteraient pratiquement inchangés. C’est la force du module RATIO.</p><h3>Étape 3 : Module MMD (Maximum-Minimum Difference)</h3><p>Le module MMD utilise une relation empirique établie en laboratoire sur des centaines d’échantillons pour prédire l’émissivité minimale réelle.</p><h3>3.1 — Calcul du contraste spectral (MMD)</h3><p>On calcule la différence entre le maximum et le minimum des ratios β :</p><p><strong>MMD = max(β_i) — min(β_i) = 1,0208–0,9792 = 0,0416</strong></p><h3>3.2 — Prédiction de l’émissivité minimale</h3><p>ASTER utilise une formule de régression du type :</p><p><strong>ε_min = a — b · (MMD)^c</strong></p><p>Avec les coefficients standards d’ASTER : a = 0,994, b = 0,687, c = 0,737</p><p><strong>ε_min = 0,994–0,687 · (0,0416)⁰,737</strong></p><p><strong>ε_min ≈ 0,994–0,687 · 0,0969 ≈ 0,927</strong></p><p>Cette relation empirique est le cœur de l’innovation TES : elle relie la forme du spectre (le contraste) à sa valeur minimale absolue.</p><h3>Étape 4 : Calcul final</h3><h3>4.1 — Recalcul du spectre d’émissivité final</h3><p>On utilise ε_min prédit pour remettre à l’échelle tous les β :</p><p><strong>ε_i,final = β_i · (ε_min / min(β_i))</strong></p><p>Calcul numérique :</p><ul><li>ε₁,final = 1,0208 · (0,927 / 0,9792) ≈ 0,966</li><li>ε₂,final = 0,9792 · (0,927 / 0,9792) = 0,927</li></ul><p>On retrouve bien ε_min comme valeur minimale du spectre.</p><h3>4.2 — Calcul de la température finale (T_TES)</h3><p>On réapplique l’inverse de la loi de Planck, cette fois avec les émissivités corrigées. On utilise généralement la bande à plus forte émissivité pour minimiser les erreurs.</p><p>Avec la bande 1 et ε₁,final = 0,966 :</p><p><strong>B₁(T_final) = L_surface,1 / ε₁,final = 12,5 / 0,966 ≈ 12,940 W/(m²·sr·µm)</strong></p><p>En appliquant l’inversion de Planck :</p><p><strong>T_final = c₂ / [λ₁ · ln(1 + c₁/(B₁·λ₁⁵))]</strong></p><p><strong>T_final ≈ 314,8 K (soit environ 41,6°C)</strong></p><h3>Résultats finaux</h3><ul><li><strong>Température de surface :</strong> T_TES = 314,8 K</li><li><strong>Spectre d’émissivité :</strong></li><li>ε₁ = 0,966 (bande à 9,0 µm)</li><li>ε₂ = 0,927 (bande à 10,0 µm)</li></ul><p><strong>Amélioration :</strong> La température a été corrigée de 315,4 K à 314,8 K, soit une différence de 0,6 K, et le spectre d’émissivité reflète maintenant plus fidèlement les propriétés physiques de la surface.</p><h3>Performance et applications</h3><p>Les simulations numériques et tests aéroportés démontrent que l’algorithme TES restitue les températures avec une précision de ±1,5 K, même en présence d’humidité atmosphérique résiduelle. Cette performance remarquable ouvre la voie à de nombreuses applications :</p><h3>Applications géologiques</h3><ul><li>Identification des types de roches par leur signature d’émissivité</li><li>Cartographie des altérations hydrothermales</li><li>Détection de gisements minéraux</li></ul><h3>Bilans énergétiques</h3><ul><li>Estimation de l’évapotranspiration</li><li>Suivi des îlots de chaleur urbains</li><li>Études climatiques et hydriques</li></ul><h3>Surveillance environnementale</h3><ul><li>Détection de feux actifs</li><li>Suivi de la végétation stressée</li><li>Cartographie des zones arides</li></ul><h3>Conclusion</h3><p>L’algorithme TES représente une avancée majeure en télédétection thermique. En combinant intelligemment trois approches complémentaires, il transforme un problème mathématiquement indéterminé (plus d’inconnues que de mesures) en une solution opérationnelle robuste. Le module NEM fournit une première estimation, le module RATIO stabilise la forme spectrale, et le module MMD ancre le spectre à sa valeur physique réelle grâce à une relation empirique validée.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ceaf27d3fb1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide Complet : L’IA Explicable (XAI) pour les Modèles de Régression]]></title>
            <link>https://medium.com/@ykarray29/guide-complet-lia-explicable-xai-pour-les-mod%C3%A8les-de-r%C3%A9gression-781a3f0f16cb?source=rss-25b22d7e4148------2</link>
            <guid isPermaLink="false">https://medium.com/p/781a3f0f16cb</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[xai]]></category>
            <dc:creator><![CDATA[yasmine karray]]></dc:creator>
            <pubDate>Sat, 08 Nov 2025 12:15:00 GMT</pubDate>
            <atom:updated>2025-12-01T09:24:33.761Z</atom:updated>
            <content:encoded><![CDATA[<h3>Guide Complet : L’IA Explicable (XAI) pour les Modèles de Régression</h3><p>Imaginez que vous demandez de participer à un concours. L’algorithme refuse votre demande. Vous demandez “pourquoi ?”. Le site répond : “l’algorithme a décidé”. C’est inacceptable.</p><p>C’est exactement le problème que résout l’Explainable AI (XAI) : rendre les décisions des algorithmes d’Intelligence Artificielle compréhensibles, transparentes et vérifiables.</p><p>Avec l’explosion des modèles Deep Learning ultra-performants mais opaques (des “boîtes noires”), le besoin d’explications est devenu critique. Comment faire confiance à un système qu’on ne peut pas comprendre ?</p><p>Ce guide vous expliquera concrètement comment fonctionnent les principales méthodes XAI pour les problèmes de régression (prédiction de valeurs continues : prix, salaires, température, etc.).</p><h3>Partie 1 : Concepts Fondamentaux et Classifications</h3><h4>1.1 Les Dimensions de Classification des Méthodes XAI</h4><p>Les méthodes XAI se classifient selon trois axes principaux :</p><h4>Classification par Moment d’Application</h4><p><strong>Ante-hoc (Intrinsèque)</strong> : L’interprétabilité est intégrée dans la conception du modèle dès le départ.</p><p><em>Exemple concret</em> : Une régression linéaire simple<br><strong>Prix = 2000 × Surface + 50000 × Chambres + 80000</strong></p><ul><li>✅ Avantages : Transparence totale, pas besoin de calculs supplémentaires</li><li>Modèles typiques : Régression linéaire, arbres de décision, modèles à base de règles</li></ul><p><strong>Post-hoc</strong> : On applique une méthode d’explication externe après avoir entraîné un modèle complexe.</p><p><em>Exemple concret</em> : Vous avez un réseau de neurones profond qui prédit les prix immobiliers avec 95% de précision, mais c’est une boîte noire. Vous appliquez SHAP pour comprendre ses décisions.</p><ul><li>✅ Avantages : Permet d’utiliser des modèles très performants tout en obtenant des explications</li><li>❌ Inconvénients : Calculs supplémentaires, explications approximatives</li><li>Techniques typiques : LIME, SHAP, Integrated Gradients</li></ul><h4>Classification par Portée</h4><p><strong>Locale</strong> : Explique une seule prédiction spécifique.</p><p><em>Question répondue</em> : “Pourquoi ce client précis s’est-il vu refuser son prêt ?”</p><p><strong>Exemple complet :</strong><br> Pour <strong>M. Dupont</strong> (salaire : <strong>35 000 €</strong>, taux d’endettement : <strong>45 %</strong>, historique de paiement : <strong>2 retards sur 12 mois</strong>), le modèle prédit un <strong>score de risque de 7,2 / 10</strong>.<br> <strong>LIME explique :</strong><br> — Taux d’endettement élevé (<strong>+2,1 points</strong>)<br> — Retards de paiement récents (<strong>+1,2 points</strong>)<br> — Salaire stable (<strong>–1,1 points</strong>)</p><p><strong>Score final estimé :</strong> 5 (base) + 2,1 + 1,2–1,1 = <strong>7,2 / 10</strong></p><p><em>Usage</em> : Décisions individuelles, recours juridiques, diagnostic</p><p><strong>Globale</strong> : Comprend le comportement général du modèle sur tout le dataset.</p><p><em>Question répondue</em> : “Quels sont les facteurs les plus importants que le modèle utilise en général ?”</p><p><em>Exemple</em> : Après analyse de 10,000 prédictions avec SHAP, on découvre que globalement, la surface du logement contribue en moyenne à 50% de la prédiction du prix, le quartier à 30%, et le nombre de chambres à 20%.</p><p><em>Usage</em> : Audit du modèle, conformité réglementaire, amélioration du modèle</p><h4>Classification par Dépendance au Modèle</h4><p><strong>Model-Agnostic (Indépendant du modèle)</strong> : La méthode fonctionne avec n’importe quel type de modèle.</p><ul><li>Principe : Traite le modèle comme une boîte noire. Ne s’intéresse qu’aux entrées (features) et sorties (prédictions).</li><li>✅ Avantages : Universalité totale — même technique pour une régression linéaire, un Random Forest, ou un réseau de neurones</li><li>Techniques : LIME, SHAP (version Kernel), Counterfactuals</li></ul><p><strong>Model-Specific (Spécifique au modèle)</strong> : Exploite la structure interne d’un type de modèle particulier.</p><ul><li>Principe : Utilise l’architecture, les poids, ou les calculs internes du modèle</li><li>✅ Avantages : Souvent plus rapide et plus précis pour le modèle ciblé</li><li>Techniques : LRP (pour deep learning), TreeSHAP (pour arbres), Integrated Gradients (pour deep learning)</li></ul><h3>Partie 2 : Les Techniques XAI en Détail</h3><h4>2.1 Modèles Ante-hoc: La Régression Linéaire : L’Étalon-Or de l’Interprétabilité</h4><p><strong>Formule</strong> : y = β₀ + β₁X₁ + β₂X₂ + … + βₙXₙ</p><p><strong>Pourquoi c’est interprétable ?</strong> Chaque coefficient βᵢ indique directement la contribution de la variable.</p><p><strong>Exemple Concret Complet : Prédiction du salaire annuel</strong></p><p><strong>Salaire = 25000 + 1500×Années_Expérience + 8000×Diplôme_Master</strong></p><p>Pour un candidat avec :</p><ul><li>5 ans d’expérience</li><li>Master (=1)</li></ul><p><strong>Calcul détaillé :</strong></p><pre>Salaire = 25000 (base)<br>        + 1500×5 = 7500 (contribution expérience)<br>        + 8000×1 = 8000 (contribution diplôme)<br>        = 40,500€</pre><p><strong>Interprétation claire :</strong></p><ul><li>✓ Chaque année d’expérience rapporte 1500€</li><li>✓ Avoir un Master ajoute 8000€</li></ul><p><strong>Les Arbres de Décision : La Logique Visuelle</strong></p><p><strong>Structure</strong> : Succession de règles “Si… Alors…” formant un arbre.</p><p><strong>Exemple Concret : Estimation du risque de défaut de crédit</strong></p><pre>[Revenu Annuel]<br>                      |<br>          ≥ 40k€ ─────────────── &lt; 40k€<br>            |                      |<br>      RISQUE FAIBLE           RISQUE ÉLEVÉ<br>          (5%)                    (35%)</pre><p><strong>Lecture</strong> : Pour quelqu’un avec revenu = 35k€ (&lt; 40k€) → RISQUE ÉLEVÉ (35% de probabilité de défaut)</p><h4>2.2 LIME (Local Interpretable Model-agnostic Explanations)</h4><p>LIME crée un modèle simple (linéaire) qui approxime localement le comportement du modèle complexe autour d’une prédiction spécifique.</p><p><strong>Métaphore :</strong> Imaginez une montagne (le modèle complexe). LIME ne cherche pas à décrire toute la montagne, mais juste la petite zone plate où vous êtes. Dans cette zone, une simple pente linéaire suffit.</p><h4>Les 4 Étapes de LIME : Exemple Simplifié</h4><p><strong>Contexte :</strong> Modèle complexe de prédiction des prix immobiliers</p><p><strong>Maison cible :</strong></p><ul><li>Surface (X₁) = 120 m²</li><li>Distance centre-ville (X₂) = 10 km</li><li>Prédiction du modèle : 300,000€</li></ul><p><strong>Question :</strong> Pourquoi 300k€ ?</p><h4>Étape 1 : Génération de Voisins Perturbés</h4><p>LIME crée des maisons fictives légèrement différentes :</p><p>Maison|Surface (X₁)|Distance (X₂)|Prédiction f(X)</p><p>A (originale)|120|10|300,000€</p><p>B|115|8|310,000€</p><h4>Étape 2 : Calcul des Poids de Proximité</h4><p>On calcule à quel point chaque maison est proche de la maison cible.</p><p><strong>Formule de distance euclidienne :</strong></p><pre>D(x₀, xᵢ) = √[(X₁ - 120)² + (X₂ - 10)²]</pre><p><strong>Transformation en poids avec une fonction gaussienne :</strong></p><pre>πₓ₀(xᵢ) = e^(-D²/σ²)  où σ = 5</pre><p><strong>Calculs détaillés :</strong></p><p>Maison|Calcul Distance|D|Calcul Poids|Poids π</p><p>A|√[(120–120)² + (10–10)²]|0.0|e^(-⁰²/25)|1.00 ← poids maximal</p><p>B|√[(115–120)² + (8–10)²]|5.4|e^(-29/25)|0.31</p><p><strong>Interprétation :</strong></p><ul><li>Maison A (identique) : poids = 1.00 → LIME lui fait totalement confiance</li><li>Maison B (éloignée) : poids = 0.31 → LIME lui fait moins confiance</li></ul><h4>Étape 3 : Entraînement du Modèle Linéaire Local</h4><p>On cherche un modèle simple :</p><pre>ŷ = a₁X₁ + a₂X₂ + b</pre><p>qui minimise l’erreur pondérée :</p><pre>Erreur = Σ πₓ₀(xᵢ) × [f(xᵢ) - ŷᵢ]²</pre><p><strong>Tableau des données d’entraînement pondérées :</strong></p><p>Maison|X₁|X₂|Prédiction f(X)|Poids π</p><p>A|120|10|300,000|1.00</p><p>B|115|8|310,000|0.31</p><p><strong>Analyse des variations locales :</strong></p><ul><li><strong>Effet Surface (X₁) :</strong> De B (115m²) à A (120m²) : +5m² → -10,000€<br> Impact local : a₁ ≈ -2,000€/m²</li><li><strong>Effet Distance (X₂) :</strong> De B (8km) à A (10km) : +2km → -10,000€<br> Impact local : a₂ ≈ -5,000€/km</li></ul><p><strong>Modèle linéaire local trouvé :</strong></p><pre>ŷ = -2000X₁ - 5000X₂ + b</pre><p><strong>Calcul du biais b :</strong></p><pre>Pour la maison A (120, 10) :<br>300,000 = -2000(120) - 5000(10) + b<br>300,000 = -240,000 - 50,000 + b<br>b = 590,000</pre><p><strong>Modèle final :</strong></p><pre>ŷ = -2000X₁ - 5000X₂ + 590,000</pre><h4>Étape 4 : Interprétation des Coefficients</h4><p><strong>Décomposition de la prédiction de 300,000€ :</strong></p><p>Feature|Valeur|Coefficient|Contribution|Interprétation Biais de base|</p><p>Surface|120 m²|-2,000|-240,000€|Localement, effet négatif (non-linéarité)</p><p>Distance|10 km|-5,000|-50,000€|Chaque km du centre retire 5k€ TOTAL||||300,000€|✓ Correspond à la prédiction !</p><h3>Points Clés de LIME</h3><p><strong>✅ Avantages :</strong></p><ul><li>Fonctionne avec N’IMPORTE QUEL modèle</li><li>Explications intuitives (modèle linéaire)</li><li>Rapide à calculer</li><li>Applicable à texte, images, tableaux</li></ul><p><strong>❌ Limitations :</strong></p><ul><li>Explications locales seulement (change pour chaque prédiction)</li><li>Instabilité : petits changements → explications différentes</li><li>Choix de σ (taille du voisinage) influence les résultats</li><li>Approximation : peut être imprécise si le modèle est très non-linéaire localement</li></ul><h4>2.3 SHAP (SHapley Additive exPlanations)</h4><p>SHAP s’appuie sur les <strong>valeurs de Shapley</strong>, un concept issu de la théorie des jeux pour répartir équitablement une récompense entre des joueurs ayant contribué à un résultat commun.</p><p>Les valeurs de Shapley répondent : chacun reçoit sa contribution marginale moyenne à travers toutes les coalitions possibles.</p><p><strong>SHAP pour la Régression : Formulation Mathématique</strong></p><p>Pour une prédiction f(x), SHAP calcule une valeur φᵢ (phi) pour chaque feature Xᵢ :</p><pre>f(x) = f(baseline) + φ₁ + φ₂ + ... + φₙ</pre><p><strong>Propriété d’Additivité (Essentielle en régression) :</strong></p><pre>Σφᵢ = f(x) - f(baseline)</pre><p>La somme des contributions = différence totale → pas d’effet “perdu” !</p><p><strong>Calcul d’une Valeur SHAP : Formule Complète</strong></p><p>Pour une feature Xᵢ :</p><pre>φᵢ = Σ [poids(S) × contribution_marginale(S, Xᵢ)]<br>     S⊆Features\{Xᵢ}</pre><p>Où :</p><ul><li><strong>S</strong> = coalition (sous-ensemble) de features sans Xᵢ</li><li><strong>poids(S)</strong> = |S|! × (N-|S|-1)! / N!</li><li><strong>contribution_marginale</strong> = f(S ∪ {Xᵢ}) — f(S)</li></ul><p><strong>Exemple Concret Simplifié : Prix de Maison avec SHAP</strong></p><p><strong>Setup :</strong></p><ul><li>2 features : X₁ (Surface), X₂ (Chambres)</li><li>Maison cible : (120m², 3 chambres) → <strong>Prédiction : 300,000€</strong></li><li>Baseline (moyenne dataset) : <strong>250,000€</strong></li></ul><p><strong>Question</strong> : Comment les features contribuent-elles à la différence de +50,000€ ?</p><p><strong>Étape 1 : Énumération des Coalitions</strong></p><p>Pour X₁ (Surface), on considère toutes les coalitions sans X₁ :</p><p>Coalition S | Features présentes | Taille S|<br>∅ | Aucune (juste baseline) | 0<br>{X₂} | Chambres seules | 1</p><p><strong>Étape 2 : Calcul des Prédictions pour Chaque Coalition</strong></p><pre>Coalition S | Valeurs utilisées | Prédiction f(S)<br>∅ | (110*, 2.5*) | 250,000€ (baseline)<br>{X₂} | (110*, 3) | 265,000€</pre><p><strong>Maintenant avec X₁ ajouté (120 m²)</strong></p><pre>Coalition S ∪ {X₁} | Valeurs utilisées | Prédiction f(S∪{X₁})<br>{X₁} | (120, 2.5*) | 280,000€<br>{X₁, X₂} | (120, 3) | 300,000€</pre><p><strong>Étape 3 : Contributions Marginales de X₁</strong></p><pre>Coalition S | f(S∪{X₁}) - f(S) | Contribution marginale<br>∅ | 280,000 – 250,000 | +30,000€<br>{X₂} | 300,000 – 265,000 | +35,000€</pre><p>Observation : La contribution de X₁ varie selon le contexte !</p><ul><li>Seul : +30k€</li><li>Avec X₂ : +35k€ (effet d’interaction)</li></ul><p><strong>Étape 4 : Calcul des Poids de Coalition</strong></p><pre>Coalition S | |S| | Calcul | Poids<br>∅ | 0 | 0! × 1! / 2! | 1/2<br>{X₂} | 1 | 1! × 0! / 2! | 1/2</pre><p>Vérification : 1/2 + 1/2 = 1 ✓</p><p>Coalition 1 : S = ∅ (pas de features avec X₁)</p><ul><li>|S| = 0 (taille de la coalition)</li><li>N = 2 (total des features)</li><li>Calcul :</li><li>Numérateur : |S|! × (N - |S| - 1)! = 0! × (2 - 0 - 1)!</li><li>0! = 1</li><li>(2 - 0 - 1)! = (1)! = 1</li><li>Donc numérateur = 1 × 1 = 1</li><li>Dénominateur : N! = 2! = 2×1 = 2</li><li>Poids = 1 / 2 =</li></ul><p>Interprétation physique : C’est la probabilité que X₁ arrive en premier dans un ordre aléatoire d&#39;ajout des features. Avec 2 features, la probabilité que X₁ soit ajoutée en premier (alors qu&#39;aucune autre feature n&#39;est encore présente) est bien de 1/2.</p><p>Coalition 2 : S = {X₂} (seulement X₂ avec X₁)</p><ul><li>|S| = 1 (taille de la coalition, qui contient X₂)</li><li>N = 2 (total des features)</li><li>Calcul :</li><li>Numérateur : |S|! × (N - |S| - 1)! = 1! × (2 - 1 - 1)!</li><li>1! = 1</li><li>(2 - 1 - 1)! = (0)! = 1</li><li>Donc numérateur = 1 × 1 = 1</li><li>Dénominateur : N! = 2! = 2×1 = 2</li><li>Poids = 1 / 2 = 0.5</li></ul><p>Interprétation physique : C’est la probabilité que X₁ arrive en dernier dans un ordre aléatoire d&#39;ajout des features. Avec 2 features, la probabilité que l&#39;ordre soit [X₂, X₁] (c&#39;est-à-dire que X₁ soit ajoutée après que S={X₂} soit déjà formée) est aussi de 1/2.</p><p><strong>Étape 5 : Valeur SHAP de X₁</strong></p><pre>φ₁ = Σ [poids(S) × contribution_marginale(S, X₁)]<br>φ₁ = (1/2 × 30,000) + (1/2 × 35,000)<br>φ₁ = 15,000 + 17,500<br>φ₁ = 32,500€</pre><p>Répétons pour X₂ (calculs similaires) :</p><pre>φ₂ (Chambres) = +17,500€</pre><p><strong>Étape 6 : Vérification de l’Additivité</strong></p><pre>f(x) - f(baseline) = φ₁ + φ₂<br>300,000 - 250,000 = 32,500 + 17,500<br>50,000 = 50,000 ✓ Parfait !</pre><p><strong>Interprétation Finale SHAP</strong></p><p><strong>Décomposition de la prédiction 300,000€ :</strong></p><pre>Baseline (moyenne)              250,000€<br>    ↓<br>+ Surface (120m²)              +32,500€  (effet le plus fort)<br>+ Chambres (3)                 +17,500€  (effet moyen)<br>    ↓<br>= Prédiction finale            300,000€</pre><p><strong>Visualisation :</strong></p><pre>← Diminue le prix    |    Augmente le prix →<br>                     |<br>                     |<br>Chambres (3)         | ▓▓▓▓▓ +17.5k<br>                     |<br>Surface (120m²)      | ▓▓▓▓▓▓▓▓ +32.5k<br>━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━<br>          250k (baseline) ↑ 300k (prédiction)</pre><p><strong>SHAP : Points Clés</strong></p><p>✅ <strong>Avantages Majeurs :</strong></p><ul><li>Théoriquement solide : basé sur la théorie des jeux</li><li>Additivité garantie : Σφᵢ = différence exacte</li><li>Équitable : prend en compte toutes les coalitions possibles</li><li>Cohérent : même feature → même contribution dans des modèles similaires</li><li>Applicable localement ET globalement (moyenne des SHAP values)</li></ul><p>❌ <strong>Limitations :</strong></p><ul><li>Coût computationnel : 2^N coalitions à évaluer (exponentiel !)</li><li>Pour 10 features : 1,024 coalitions</li><li>Pour 20 features : 1,048,576 coalitions (impraticable)</li><li>Solutions : approximations (Kernel SHAP, TreeSHAP pour arbres)</li><li>Suppose l’indépendance des features (problématique si corrélations fortes)</li></ul><h4>2.4 Integrated Gradients (IG)</h4><p>Integrated Gradients est une technique Post-hoc spécialisée pour les modèles Deep Learning (réseaux de neurones). Son idée centrale : plutôt que de regarder le gradient en un seul point (instable et incomplet), on intègre le gradient le long d’un chemin entre une référence et l’entrée cible.</p><p><strong>Métaphore de la Randonnée :</strong></p><p>Vous êtes au pied d’une montagne (référence) et vous voulez atteindre le sommet (votre prédiction). Plutôt que de regarder uniquement la pente où vous êtes, IG calcule l’accumulation totale de pente sur tout votre trajet. Chaque feature contribue selon “combien elle a fait monter” durant le voyage complet.</p><p><strong>Formulation Mathématique</strong></p><p>Pour une feature Xi, l’attribution IG est :</p><pre>IGi(x) = (xi - xi_baseline) × ∫₀¹ [∂f/∂Xi](x_baseline + α(x - x_baseline)) dα</pre><p><strong>Décomposition :</strong></p><ul><li><strong>x_baseline</strong> : point de référence (souvent zéros ou moyenne)</li><li><strong>x</strong> : entrée à expliquer</li><li><strong>α</strong> : paramètre variant de 0 à 1 (progression le long du chemin)</li><li><strong>x(α) = x_baseline + α(x — x_baseline)</strong> : interpolation linéaire</li><li><strong>∂f/∂Xi</strong> : gradient (sensibilité) du modèle par rapport à Xi</li><li><strong>∫</strong> : intégrale = accumulation sur tout le chemin</li></ul><p>f est le modèle de deep learning (réseau de neurones) lui-même, vu comme une fonction mathématique qui transforme les entrées en sorties.</p><p>∂f/∂Xᵢ est la dérivée partielle de f par rapport à la i-ème caractéristique.</p><ul><li>Signification : “À quel point le prix prédit change-t-il quand on modifie <em>un tout petit peu</em> la surface (ou le nombre de chambres), en gardant toutes les autres caractéristiques constantes ?”</li><li>Mesure : Sensibilité locale du modèle à chaque caractéristique.</li><li>Unité : €/(unité normalisée) ou €/m² dans notre exemple.</li></ul><p>Comment calcule-t-on concrètement ∂f/∂Xᵢ ?</p><p>Par la rétropropagation (backpropagation) — le même algorithme utilisé pour entraîner le réseau !</p><p>Pour chaque point x(α) :</p><ol><li>Forward pass : On passe x(α) à travers le réseau pour obtenir f(x(α))</li><li>Backward pass : On propage “1” en arrière pour calculer les gradients</li></ol><p># Pseudo-code PyTorch/TensorFlow<br>x_alpha = baseline + alpha * (input — baseline)<br>x_alpha.requires_grad = True</p><p>prediction = model(x_alpha) # Forward pass<br>prediction.backward() # Backward pass</p><p>gradient_x1 = x_alpha.grad[0] # ∂f/∂X₁<br>gradient_x2 = x_alpha.grad[1] # ∂f/∂X₂</p><p><strong>Propriété d’Additivité :</strong></p><pre>Σ IGi(x) = f(x) - f(x_baseline)</pre><p>Comme SHAP, IG garantit que la somme des contributions = différence totale !</p><p><strong>Exemple Concret Simplifié : Prédiction de Prix Immobilier</strong></p><p><strong>Configuration :</strong></p><ul><li>Modèle : Réseau de neurones profond</li><li>Features :</li><li>X₁ = Surface normalisée (120m² → 1.2)</li><li>X₂ = Chambres normalisées (3 → 0.6)</li><li>Baseline : vecteur zéro [0, 0]</li><li>Input cible : [1.2, 0.6]</li><li><strong>Prédiction : f([1.2, 0.6]) = 300,000€</strong></li><li><strong>Prédiction baseline : f([0, 0]) = 200,000€</strong></li><li><strong>Différence à expliquer : 100,000€</strong></li></ul><p><strong>Étape 1 : Création du Chemin d’Interpolation</strong></p><p>On crée des points intermédiaires entre baseline et input :</p><pre>x(α) = [0, 0] + α × ([1.2, 0.6] - [0, 0])<br>     = α × [1.2, 0.6]</pre><p><strong>Discrétisation avec m = 3 étapes :</strong></p><p>α | x₁(α) | x₂(α) | Point<br>0.00 | 0.0 | 0.0 | Baseline<br>0.50 | 0.6 | 0.3 | Mi-chemin<br>1.00 | 1.2 | 0.6 | Input cible</p><p><strong>Étape 2 : Calcul des Gradients à Chaque Point</strong></p><p>À chaque point x(α), on calcule les gradients partiels ∂f/∂Xi.</p><p><strong>En pratique</strong> : BackPropagation dans le réseau de neurones.</p><p><strong>Exemple de gradients calculés :</strong></p><p>α | x(α) | f(x(α)) | ∂f/∂X₁ | ∂f/∂X₂<br>0.00 | [0, 0] | 200,000 | 45,000 | 20,000<br>0.50 | [0.60, 0.30] | 265,000 | 60,000 | 32,000<br>1.00 | [1.20, 0.60] | 300,000 | 63,000 | 34,500</p><p><strong>Observations :</strong></p><ul><li>∂f/∂X₁ augmente le long du chemin : l’effet de la surface s’amplifie</li><li>∂f/∂X₂ augmente aussi : les chambres deviennent plus importantes</li></ul><p><strong>Étape 3 : Approximation de l’Intégrale (Méthode des Trapèzes)</strong></p><p>Pour X₁ (Surface) :</p><pre>∫₀¹ (∂f/∂X₁) dα ≈ Σᵢ₌₁ᵐ [(∂f/∂X₁)ᵢ₋₁ + (∂f/∂X₁)ᵢ] / 2 × Δα</pre><p>Avec Δα = 1/2 = 0.50</p><p><strong>Calcul simplifié sur les intervalles :</strong></p><p><strong>Intervalle [0.00 → 0.50] :</strong></p><pre>Moyenne gradients : (45,000 + 60,000) / 2 = 52,500<br>Contribution : 52,500 × 0.50 = 26,250</pre><p><strong>Intervalle [0.50 → 1.00] :</strong></p><pre>Moyenne : (60,000 + 63,000) / 2 = 61,500<br>Contribution : 61,500 × 0.50 = 30,750</pre><p><strong>Intégrale totale ≈ 26,250 + 30,750 = 57,000</strong></p><p><strong>Étape 4 : Calcul de l’Attribution IG</strong></p><pre>IG₁ = (x₁ - x₁_baseline) × ∫₀¹ (∂f/∂X₁) dα<br>    = (1.2 - 0) × 57,000<br>    = 68,400€</pre><p>Répétons pour X₂ :</p><p><strong>Pour X₂ (calcul similaire) :</strong></p><ul><li>Intégrale : ≈ 29,000</li></ul><pre>IG₂ = (0.6 - 0) × 29,000<br>    = 17,400€</pre><p>Étape 5 : Vérification de la Complétude</p><p><strong>Somme des attributions :</strong></p><pre>IG₁ + IG₂ = 68,400 + 17,400 = 85,800€</pre><p><strong>Différence modèle :</strong></p><pre>f(x) - f(baseline) = 300,000 - 200,000 = 100,000€</pre><p><strong>Écart résiduel : 100,000–85,800 = 14,200€</strong></p><p>💡 <strong>Note :</strong> Augmenter m (5, 10, ou 20 étapes) → précision améliorée.<br>Avec m = 20 : écart résiduel &lt; 1,000€ (négligeable)</p><p><strong>Visualisation IG</strong></p><p><strong>Évolution des Gradients :</strong></p><pre>∂f/∂X₁ (Surface)<br>65k |                          ___<br>    |                    _____/<br>60k |              _____/<br>    |        _____/<br>50k |  _____/<br>    | /<br>45k +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━→<br>    0         0.5              1.0  α<br>    <br>    Aire sous la courbe = Intégrale ≈ 57,000</pre><p><strong>Attributions Finales:</strong></p><pre>Contribution à l&#39;écart de +100k€ :</pre><pre>Surface (120m²)     ████████████████ +68.4k€  (68%)<br>Chambres (3)        ████████ +17.4k€          (17%)<br>Résiduel            ▓ +14.2k€                 (14%)<br>                    ━━━━━━━━━━━━━━━━━━━━━━━━━<br>                    Total : +100k€</pre><p><strong>IG : Points Clés</strong></p><p>✅ <strong>Avantages :</strong></p><ul><li>Axiomatiquement solide : propriétés de Sensibilité et Implementation Invariance</li><li>Additivité garantie (avec suffisamment d’étapes)</li><li>Capture les non-linéarités : intègre sur tout le chemin</li><li>Stable : déterministe, reproductible</li><li>Idéal pour Deep Learning : utilise naturellement les gradients</li></ul><p>❌ <strong>Limitations :</strong></p><ul><li>Spécifique aux modèles différentiables (réseaux de neurones)</li><li>Choix de la baseline critique : résultats différents selon la référence</li><li>Coût computationnel : m forward passes + m backward passes</li><li>Chemin linéaire : suppose interpolation droite (pas toujours optimal)</li></ul><p><strong>Choix de la Baseline : Impact Crucial</strong></p><p><strong>Exemples de baselines possibles :</strong></p><p>Baseline | Valeur | Usage | Impact<br>Zéros | [0, 0] | Par défaut | Compare à “rien”<br>Moyenne | [0.8, 0.5] | Fréquent | Compare à “maison typique”<br>Médiane | [0.7, 0.5] | Robuste outliers | Compare à “médian”<br>Min/Max | [0, 0] ou [2, 1] | Bornes | Extrêmes</p><h4>2.5 Layer-wise Relevance Propagation (LRP)</h4><p><strong>Principe Fondamental : Propagation Inverse de la Pertinence</strong></p><p>LRP est une technique Model-Specific conçue pour les réseaux de neurones. Son approche : propager la prédiction finale en arrière à travers les couches, en redistribuant la “pertinence” (relevance) à chaque neurone selon sa contribution.</p><p><strong>Architecture et Notations</strong></p><p><strong>Réseau de neurones simplifié :</strong></p><pre>Input Layer     Hidden Layer    Output Layer<br>    X₁ ──────→ h₁ ──────────→ y (prédiction)<br>    X₂ ──────→ h₂ ──────────→</pre><p>Notations :</p><ul><li>aⱼ⁽ˡ⁾ : activation du neurone j dans la couche l</li><li>wⱼₖ⁽ˡ⁾ : poids de connexion de j (couche l) vers k (couche l+1)</li><li>Rₖ⁽ˡ⁺¹⁾ : pertinence du neurone k dans la couche l+1</li><li>Rⱼ⁽ˡ⁾ : pertinence du neurone j dans la couche l (à calculer)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/0*H3TCJ8pEpBIEHdJ8.png" /><figcaption><a href="https://miro.medium.com/v2/resize:fit:766/1*1sXY17hFy3cw-5u7mIcaAg.png">SOURCE</a></figcaption></figure><p><strong>Formule de Propagation LRP</strong></p><p>Règle de base (LRP-0) :</p><pre>couche l | couche l+1<br>j        | k      : neurone<br>Rⱼ⁽ˡ⁾    |Rₖ⁽ˡ⁺¹⁾ : pertinence du neurone j/k dans la couche l / l+1<br>       wⱼₖ⁽ˡ⁾ :poids de connexion de j (couche l) vers k (couche l+1)</pre><pre>Rⱼ⁽ˡ⁾ = Σₖ [ (aⱼ⁽ˡ⁾ · wⱼₖ⁽ˡ⁾) / Σₘ(aₘ⁽ˡ⁾ · wₘₖ⁽ˡ⁾) ] × Rₖ⁽ˡ⁺¹⁾</pre><p>En mots :</p><ul><li>La pertinence de j = somme sur tous les neurones k de la couche suivante</li><li>Pour chaque k : on prend sa pertinence Rₖ</li><li>On la multiplie par la fraction : (contribution de j vers k) / (contributions totales vers k)</li></ul><p>Propriété de Conservation :</p><pre>Σⱼ Rⱼ⁽ˡ⁾ = Σₖ Rₖ⁽ˡ⁺¹⁾</pre><p>La pertinence totale est conservée à chaque couche !</p><p><strong>Exemple Concret Détaillé : Prédiction de Prix</strong></p><p>Architecture du Réseau</p><p>LAYER 0 (Couche d’Entrée)</p><ul><li>2 neurones : X₁ et X₂</li><li>Ce sont nos features (caractéristiques)</li></ul><p>LAYER 1 (Couche Cachée)</p><ul><li>2 neurones : h₁ et h₂</li><li>Ces neurones font des calculs intermédiaires</li><li>Ils combinent X₁ et X₂ de différentes façons</li></ul><p>LAYER 2 (Couche de Sortie)</p><ul><li>1 neurone : y</li><li>C’est la prédiction finale (le prix)</li></ul><pre>X₁ (Surface)  ──┐<br>                ├──→ h₁ ──┐<br>X₂ (Chambres) ──┤         ├──→ y (Prix)<br>                └──→ h₂ ──┘</pre><p><strong>ÉTAPE 0 : Les Données d’Entrée</strong></p><pre>X₁ = 2  (Surface en unités normalisées)<br>X₂ = 1  (Nombre de chambres)</pre><p><strong>ÉTAPE 1 : Calcul des Activations h₁ et h₂</strong></p><p>Poids de la couche cachée W⁽¹⁾:</p><pre>       h₁    h₂<br>X₁  [  3     2  ]<br>X₂  [  1     1  ]</pre><p>Calcul de h₁:</p><pre>h₁ = X₁ × w₁₁ + X₂ × w₂₁<br>h₁ = 2 × 3 + 1 × 1<br>h₁ = 6 + 1<br>h₁ = 7</pre><p>Calcul de h₂:</p><pre>h₂ = X₁ × w₁₂ + X₂ × w₂₂<br>h₂ = 2 × 2 + 1 × 1<br>h₂ = 4 + 1<br>h₂ = 5</pre><p><strong>Résultat:</strong> h₁ = 7 et h₂ = 5</p><p><strong>ÉTAPE 2 : Calcul de la Prédiction y</strong></p><p>Poids de la couche de sortie W⁽²⁾:</p><pre>       y<br>h₁  [ 10 ]<br>h₂  [  6 ]</pre><p>Calcul de y:</p><pre>y = h₁ × w₁ + h₂ × w₂<br>y = 7 × 10 + 5 × 6<br>y = 70 + 30<br>y = 100k€</pre><p>Prédiction finale: 100k€</p><p>MAINTENANT ON FAIT LRP (Retour en Arrière)</p><p><strong>ÉTAPE LRP-1 : Initialisation</strong></p><pre>R_y = 100k€  (la prédiction qu&#39;on veut expliquer)</pre><p><strong>ÉTAPE LRP-2 : De y → h₁ et h₂</strong></p><p>Calcul des contributions:</p><p>Contribution de h₁:</p><pre>z₁ = h₁ × w₁ = 7 × 10 = 70</pre><p>Contribution de h₂:</p><pre>z₂ = h₂ × w₂ = 5 × 6 = 30</pre><p>Total:</p><pre>z_total = 70 + 30 = 100</pre><p>Répartition de la pertinence:</p><p>Pertinence de h₁:</p><pre>R_h₁ = (z₁ / z_total) × R_y<br>R_h₁ = (70 / 100) × 100k€<br>R_h₁ = 0.7 × 100k€<br>R_h₁ = 70k€</pre><p>Pertinence de h₂:</p><pre>R_h₂ = (z₂ / z_total) × R_y<br>R_h₂ = (30 / 100) × 100k€<br>R_h₂ = 0.3 × 100k€<br>R_h₂ = 30k€</pre><p><strong>Vérification:</strong> 70k€ + 30k€ = 100k€ ✓</p><p><strong>ÉTAPE LRP-3 : De h₁ et h₂ → X₁ et X₂</strong></p><p>Redistribution des 70k€ de h₁</p><p>Contributions vers h₁:</p><pre>X₁ → h₁ : z₁₁ = X₁ × w₁₁ = 2 × 3 = 6<br>X₂ → h₁ : z₂₁ = X₂ × w₂₁ = 1 × 1 = 1<br>Total    : z_total = 6 + 1 = 7</pre><p><strong>Pertinence de X₁ via h₁:</strong></p><pre>R_X₁←h₁ = (6 / 7) × 70k€<br>R_X₁←h₁ = 0.857 × 70k€<br>R_X₁←h₁ = 60k€</pre><p><strong>Pertinence de X₂ via h₁:</strong></p><pre>R_X₂←h₁ = (1 / 7) × 70k€<br>R_X₂←h₁ = 0.143 × 70k€<br>R_X₂←h₁ = 10k€</pre><p>Redistribution des 30k€ de h₂</p><p>Contributions vers h₂:</p><pre>X₁ → h₂ : z₁₂ = X₁ × w₁₂ = 2 × 2 = 4<br>X₂ → h₂ : z₂₂ = X₂ × w₂₂ = 1 × 1 = 1<br>Total    : z_total = 4 + 1 = 5</pre><p><strong>Pertinence de X₁ via h₂:</strong></p><pre>R_X₁←h₂ = (4 / 5) × 30k€<br>R_X₁←h₂ = 0.8 × 30k€<br>R_X₁←h₂ = 24k€</pre><p><strong>Pertinence de X₂ via h₂:</strong></p><pre>R_X₂←h₂ = (1 / 5) × 30k€<br>R_X₂←h₂ = 0.2 × 30k€<br>R_X₂←h₂ = 6k€</pre><p><strong>ÉTAPE LRP-4 : Somme Finale</strong></p><p>Pertinence totale de X₁ (Surface):</p><pre>R_X₁ = R_X₁←h₁ + R_X₁←h₂<br>R_X₁ = 60k€ + 24k€<br>R_X₁ = 84k€</pre><p>Pertinence totale de X₂ (Chambres):</p><pre>R_X₂ = R_X₂←h₁ + R_X₂←h₂<br>R_X₂ = 10k€ + 6k€<br>R_X₂ = 16k€</pre><p>Résultat Final</p><pre>Prix prédit = 100k€</pre><pre>┌──────────────────────────────────────┐<br>│                                      │<br>│ Surface (X₁=2)  : 84k€ (84%)        │ ████████████████<br>│   ├─ via h₁=7  : 60k€               │<br>│   └─ via h₂=5  : 24k€               │<br>│                                      │<br>│ Chambres (X₂=1) : 16k€ (16%)        │ ███<br>│   ├─ via h₁=7  : 10k€               │<br>│   └─ via h₂=5  : 6k€                │<br>│                                      │<br>└──────────────────────────────────────┘<br>Total = 100k€ ✓</pre><p>Récapitulatif des Calculs</p><p>Forward Pass (Calcul normal):</p><pre>X₁=2, X₂=1 <br>    ↓<br>h₁ = 2×3 + 1×1 = 7<br>h₂ = 2×2 + 1×1 = 5<br>    ↓<br>y = 7×10 + 5×6 = 100k€</pre><p>Backward Pass (LRP):</p><pre>R_y = 100k€<br>    ↓<br>R_h₁ = (70/100) × 100k€ = 70k€<br>R_h₂ = (30/100) × 100k€ = 30k€<br>    ↓<br>R_X₁ = (6/7)×70k€ + (4/5)×30k€ = 84k€<br>R_X₂ = (1/7)×70k€ + (1/5)×30k€ = 16k€</pre><h3>LRP : Points Clés</h3><p>✅ <strong>Avantages :</strong></p><ul><li>Conservation parfaite de la pertinence</li><li>Pas de référence baseline nécessaire</li><li>Rapide : une seule passe arrière</li><li>Interprétabilité au niveau des couches (quels neurones comptent)</li><li>Adapté aux réseaux profonds</li></ul><p>❌ <strong>Limitations :</strong></p><ul><li>Spécifique aux réseaux de neurones (pas model-agnostic)</li><li>Sensible à l’architecture (difficile avec Batch Norm, Dropout)</li><li>Choix de la règle de propagation impact les résultats</li><li>Moins théoriquement justifié que SHAP ou IG</li></ul><h4>2.6 Counterfactual Explanations (CE)</h4><h4>Principe Fondamental : “Et Si…” ?</h4><p>Les Counterfactuals répondent à la question : “Qu’est-ce qui devrait changer minimalement pour obtenir un résultat différent ?”</p><p><strong>Métaphore du Concours :</strong></p><p>Vous postulez à une université. Rejet avec score 7.2/10 (seuil d’admission : 8.0).</p><ul><li><strong>Explication classique</strong> : “Vos notes sont insuffisantes”</li><li><strong>Counterfactual</strong> : “Si votre moyenne en maths passait de 12/20 à 14/20, vous seriez admis(e)”</li></ul><p>→ Actionnable et concret !</p><h4>Formulation Mathématique</h4><p><strong>Trouver x’ (counterfactual) tel que :</strong></p><pre>Minimiser : distance(x, x&#39;)<br>Sous contrainte : f(x&#39;) atteint l&#39;objectif désiré</pre><p><strong>Distance peut être :</strong></p><ul><li>Euclidienne : ||x — x’||₂</li><li>Manhattan : ||x — x’||₁</li><li>Nombre de features modifiées</li><li>Coût pondéré (certaines features plus faciles à changer)</li></ul><h4>CE pour la Régression : Deux Cas d’Usage</h4><p><strong>Cas 1 : Recours (Atteindre un Seuil)</strong></p><p><strong>Exemple : Demande de Prêt Refusée</strong></p><p><strong>Situation :</strong></p><ul><li>Seuil d’approbation : Score ≥ 9.0/10</li><li>Votre profil actuel :</li><li>Revenu : 35k€/an</li><li>Taux d’endettement : 45%</li><li><strong>Score prédit : 7.5/10 ❌ Refusé</strong></li></ul><p><strong>Counterfactual calculé :</strong></p><pre>Option 1 (changement minimal) :<br>  - Revenu : 35k€ → 42k€ (+7k€, +20%)<br>  - Endettement : 45% → 45% (inchangé)<br>  → Nouveau score : 9.1/10 ✓ Approuvé<br>  Distance : 7,000 (1 feature modifiée)</pre><pre>Option 2 (alternative) :<br>  - Revenu : 35k€ → 35k€ (inchangé)<br>  - Endettement : 45% → 32% (-13 points)<br>  → Nouveau score : 9.0/10 ✓ Approuvé<br>  Distance : 13 (1 feature modifiée)Recommandation : Option 1 plus réaliste</pre><p><strong>Cas 2 : Protection (Maintenir l’Éligibilité)</strong></p><p><strong>Exemple : Bourse Universitaire</strong></p><p><strong>Situation :</strong></p><ul><li>Seuil de maintien : Moyenne ≥ 12/20</li><li>Profil actuel :</li><li>Moyenne : 14.5/20 ✓ Éligible</li><li>Assiduité : 95%</li></ul><p><strong>Counterfactual d’alerte :</strong></p><pre>⚠️ ATTENTION - Points de fragilité :</pre><pre>Scénario de perte d&#39;éligibilité le plus proche :<br>  - Moyenne : 14.5 → 11.8 (-2.7 points)<br>  → Nouveau score : 11.9/20 ❌ Perte de bourse<br>  <br>  Interprétation : Une baisse de seulement 2.7 points<br>  (équivalent à 2 mauvaises notes) = perte d&#39;éligibilité<br>  <br>  → Votre moyenne est votre feature la PLUS CRITIQUE<br>  → Assiduité est plus stable</pre><h4>Algorithme de Recherche de Counterfactuals</h4><p><strong>Méthode 1 : Optimisation par Gradient (pour modèles différentiables)</strong></p><pre>Objectif :<br>  Minimiser : λ₁·||x - x&#39;||² + λ₂·(f(x&#39;) - y_target)²<br>  <br>Où :<br>  - λ₁ contrôle la proximité (ex: 1.0)<br>  - λ₂ contrôle l&#39;atteinte de l&#39;objectif (ex: 10.0)<br>  - y_target est la valeur désirée</pre><pre>Étapes :<br>1. Initialiser x&#39; = x<br>2. Répéter jusqu&#39;à convergence :<br>   a. Calculer ∇_x&#39;[λ₁·||x - x&#39;||² + λ₂·(f(x&#39;) - y_target)²]<br>   b. Mettre à jour : x&#39; ← x&#39; - η·∇_x&#39;<br>   c. Projeter x&#39; dans les contraintes (ex: revenu ≥ 0)<br>3. Retourner x&#39; final</pre><p><strong>Méthode 2 : Algorithme Génétique (model-agnostic)</strong></p><pre>Population initiale : variations aléatoires de x</pre><pre>Pour chaque génération :<br>  1. Évaluer fitness de chaque individu :<br>     fitness = -distance(x, x&#39;) si f(x&#39;) atteint l&#39;objectif<br>     fitness = -∞ sinon<br>     <br>  2. Sélection des meilleurs<br>  3. Croisement et mutation<br>  4. Nouvelle génération<br>  <br>Retourner : meilleur individu final</pre><p><strong>Exemple Concret Simplifié : Prix Immobilier</strong></p><p><strong>Contexte :</strong></p><ul><li>Vous voulez vendre votre maison</li><li><strong>Prix actuel prédit : 280,000€</strong></li><li><strong>Objectif : atteindre 320,000€ (+40k€)</strong></li></ul><p><strong>Profil actuel :</strong></p><ul><li>Surface : 110 m²</li><li>État : “Bon” (score 7/10)</li></ul><p><strong>Étape 1 : Exploration des Modifications Possibles</strong></p><p>On teste différentes combinaisons :</p><p>Scenario | Modifications | Nouveau Prix | Distance | Faisabilité<br>A | Surface +20m² (110→130) | 315,000€ | 20 | ⚠️ Extension coûteuse<br>B | État +2 points (7→9) | 305,000€ | 2 | ✓ Rénovations (~30k€)<br>C | Surface +10m² ET État +1 | 322,000€ | 11 | ✓ Possible</p><p><strong>Étape 2 : Calcul des Distances</strong></p><p>Distance pondérée par faisabilité :</p><pre>d(x, x&#39;) = Σᵢ wᵢ × |xᵢ - xᵢ&#39;|</pre><pre>Poids wᵢ (coût de changement) :<br>  - Surface : w=5 (extension = cher)<br>  - État : w=1 (rénovations = relativement accessible)Calculs :<br>Scenario A :<br>  d = 5 × 20 = 100Scenario B :<br>  d = 1 × 2 = 2Scenario C :<br>  d = 5 × 10 + 1 × 1 = 51</pre><p><strong>Étape 3 : Sélection du Counterfactual Optimal</strong></p><p><strong>Critères combinés :</strong></p><p>Scenario | Atteint objectif ? | Distance | Faisabilité | Score Final<br>A | ❌ (315k &lt; 320k) | 100 | Moyenne | -<br>B | ❌ (305k &lt; 320k) | 2 | Haute | -<br>C | ✅ (322k ≥ 320k) | 51 | Haute | ⭐ MEILLEUR</p><p><strong>Étape 4 : Explication Counterfactual Finale</strong></p><pre>╔════════════════════════════════════════════════════════════╗<br>║  COUNTERFACTUAL EXPLANATION - Atteindre 320,000€          ║<br>╚════════════════════════════════════════════════════════════╝</pre><pre>SITUATION ACTUELLE :<br>  Prix prédit : 280,000€<br>  Écart objectif : -40,000€ ❌RECOMMANDATION (Scenario C) :<br>  ✓ Ajouter 10m² de surface (110 → 120m²)<br>    → Via véranda ou extension modeste<br>    → Coût estimé : ~25,000€<br>    → Impact : +20,000€ sur le prix<br>    <br>  ✓ Améliorer l&#39;état de 1 point (7/10 → 8/10)<br>    → Via rafraîchissement peinture, cuisine, salle de bain<br>    → Coût estimé : ~15,000€<br>    → Impact : +22,000€ sur le prix<br>    <br>RÉSULTAT ATTENDU :<br>  Nouveau prix prédit : 322,000€ ✅<br>  Investissement total : ~40,000€<br>  Plus-value nette : 322k - 280k - 40k = +2,000€<br>  <br>⚠️ Alternative moins coûteuse (Scenario B) :<br>  Améliorer état de 2 points → 305,000€<br>  (n&#39;atteint pas 320k mais meilleur ROI)</pre><p><strong>Counterfactuals Multiples : Le Concept de “Diversité”</strong></p><p><strong>Problème :</strong> Un seul counterfactual peut être insuffisant ou biaisé.</p><p><strong>Solution :</strong> Générer plusieurs counterfactuals diversifiés.</p><p><strong>Exemple :</strong></p><pre>Objectif : Augmenter score de crédit de 7.2 → 9.0</pre><pre>Counterfactual 1 (axe revenu) :<br>  Revenu +20% → Score 9.1Counterfactual 2 (axe endettement) :<br>  Endettement -15 points → Score 9.0Counterfactual 3 (mixte) :<br>  Revenu +10% ET Endettement -8 points → Score 9.2</pre><p><strong>Avantage :</strong> L’utilisateur choisit la stratégie qui lui convient le mieux.</p><p><strong>Contraintes de Faisabilité</strong></p><p>Pas toutes les modifications ne sont possibles :</p><p><strong>Types de contraintes :</strong></p><p><strong>Immutables</strong> : Ne peuvent JAMAIS changer</p><ul><li>Exemple : Âge, genre, origine ethnique</li><li>Dans l’algorithme : fixer ces features</li></ul><p><strong>Monotones</strong> : Ne peuvent qu’augmenter</p><ul><li>Exemple : Âge, années d’expérience, diplôme obtenu</li><li>Contrainte : x’ᵢ ≥ xᵢ</li></ul><p><strong>Plages valides</strong> : Doivent rester dans un intervalle</p><ul><li>Exemple : Taux d’endettement ∈ [0%, 100%]</li><li>Contrainte : 0 ≤ x’ᵢ ≤ 100</li></ul><p><strong>Causales</strong> : Certains changements impliquent d’autres</p><ul><li>Exemple : Augmenter revenu → souvent augmente aussi l’âge</li><li>Modélisation par réseau causal</li></ul><h3>CE : Points Clés</h3><p>✅ <strong>Avantages :</strong></p><ul><li>Extrêmement actionnable : dit QUOI faire</li><li>Intuitif : format “et si…” naturel pour humains</li><li>Model-agnostic : fonctionne avec tout modèle</li><li>Applicable en classification ET régression</li><li>Permet planification : plusieurs options possibles</li><li>Juridiquement pertinent : droit au recours (RGPD)</li></ul><p>❌ <strong>Limitations :</strong></p><ul><li>Coûteux à calculer : problème d’optimisation complexe</li><li>Non-unique : multiples counterfactuals possibles</li><li>Suppose causalité : changement de X cause changement de Y (pas toujours vrai)</li><li>Faisabilité subjective : ce qui est “réaliste” varie selon contexte</li><li>Peut être instable : petits changements → counterfactual très différent</li></ul><h3>Partie 3 : Considérations Spécifiques pour la Régression (XAIR)</h3><h4>3.1 Le Problème des Unités de Mesure et de la Conservation</h4><p><strong>Pourquoi c’est crucial en régression ?</strong></p><p>En classification, la sortie est une probabilité (sans unité) ou une catégorie. En régression, la sortie a une unité physique : €, années, kg, km, etc.</p><p><strong>Conséquence :</strong> Les explications doivent respecter cette unité pour être interprétables.</p><p><strong>Techniques Satisfaisant la Conservation</strong></p><p>Technique | Conservation ? | Unités Physiques ?<br>LIME | ❌ Approximation | ⚠️ Coefficients locaux<br>SHAP | ✅ Garantie mathématique | ✅ En unité de l’output<br>Integrated Gradients | ✅ Garantie (axiome) | ✅ En unité de l’output<br>LRP | ✅ Conservation par design | ✅ En unité de l’output</p><p><strong>Recommandation pour XAIR :</strong> Privilégier SHAP, IG, ou LRP.</p><h3>3.2 La Nécessité d’une Valeur de Référence Contextuelle</h3><p><strong>Le Problème de l’Absence de Seuil Naturel</strong></p><p><strong>En classification :</strong></p><ul><li>Seuil naturel : frontière de décision</li><li>“Pourquoi Classe A et pas Classe B ?” → question évidente</li></ul><p><strong>En régression :</strong></p><ul><li>Pas de seuil naturel : continuum de valeurs</li><li>“Pourquoi 300k€ ?” → question incomplète</li><li><strong>Question complète :</strong> “Pourquoi 300k€ plutôt que [référence] ?”</li></ul><p><strong>Types de Valeurs de Référence</strong></p><p><strong>1. Moyenne du Dataset (μ)</strong></p><pre>Référence : Prix moyen = 250,000€<br>Question : &quot;Pourquoi cette maison coûte 300k€ <br>           alors que la moyenne est 250k€ ?&quot;<br>           <br>Réponse : Contributions expliquant +50k€<br>Usage : Comparaison à la &quot;maison typique&quot;</pre><p><strong>2. Médiane du Dataset</strong></p><pre>Référence : Prix médian = 240,000€<br>Question : &quot;Pourquoi cette maison coûte 300k€ <br>           alors que 50% sont ≤ 240k€ ?</pre><pre>Avantage : Robuste aux outliers (maisons de luxe extrêmes)</pre><p><strong>3. Sous-population Pertinente</strong></p><pre>Référence : Moyenne des maisons du même quartier = 280,000€<br>Question : &quot;Pourquoi cette maison coûte 300k€ <br>           alors que le quartier est à 280k€ ?&quot;<br>           <br>Réponse : Focus sur différences intra-quartier<br>          (surface, état, etc.)</pre><pre>Usage : Comparaison locale contextuelle</pre><h3>Partie 4 : Comparaisons et Guide de Choix</h3><h4>4.1 Arbre de Décision : Quelle Technique Choisir ?</h4><pre>[Type de modèle ?]<br>                          |<br>        ┌─────────────────┴─────────────────┐<br>        |                                   |<br>   [Linéaire/Arbre]                  [Boîte noire]<br>        |                                   |<br>   Déjà interprétable !              [Besoin recours ?]<br>   → Utiliser directement                   |<br>                                    ┌───────┴───────┐<br>                                   OUI             NON<br>                                    |               |<br>                            [Counterfactuals]  [Type modèle ?]<br>                            + SHAP                  |<br>                                            ┌───────┴───────┐<br>                                       [Arbre/      [Réseau de<br>                                        Forêt]       Neurones]<br>                                           |              |<br>                                      [TreeSHAP]    [IG ou LRP]<br>                                      (rapide!)      (gradients)</pre><h4>4.2 Recommandations par Cas d’Usage</h4><p><strong>Cas 1 : Application Client (Banque, Assurance)</strong></p><p>Besoin : Expliquer une décision individuelle à un client</p><p>Recommandation :</p><ol><li>Counterfactuals en priorité (actionnable)</li><li>SHAP pour détails techniques si demandé</li><li>LIME pour exploration rapide interne</li></ol><p>Exemple de sortie :</p><pre>Votre demande de crédit a été refusée (score 7.2/10, seuil 8.0).</pre><pre>💡 POUR ÊTRE APPROUVÉ :<br>   Option 1 : Augmenter votre revenu de 6,000€/an<br>   Option 2 : Réduire votre endettement de 12 points<br>   <br>📊 DÉTAILS DE VOTRE SCORE :<br>   Revenu actuel (35k€) : +2.5 points<br>   Taux endettement (45%) : -1.8 points<br>   Historique crédit : +3.2 points<br>   Ancienneté emploi : +1.3 points</pre><p><strong>Cas 2 : Audit Réglementaire / Conformité</strong></p><p>Besoin : Prouver l’équité et la transparence du modèle</p><p>Recommandation :</p><ol><li>SHAP (garanties mathématiques)</li><li>Integrated Gradients (si deep learning)</li><li>Analyses globales (fairness, biais)</li></ol><p>Exemple de rapport :</p><pre>AUDIT DU MODÈLE DE SCORING CRÉDIT</pre><pre>Technique : SHAP values (10,000 prédictions analysées)Features les plus impactantes (globalement) :<br>  1. Revenu : 35% de la variance expliquée<br>  2. Taux endettement : 28%<br>  3. Historique crédit : 22%<br>  4. Âge : 15%✅ Vérification non-discrimination :<br>   - Genre : contribution moyenne 0.02 points (non-significatif)<br>   - Origine : contribution moyenne -0.01 points (non-significatif)<br>   <br>✅ Conservation : Σφᵢ = f(x) - E[f(X)] vérifiée sur 100% des cas</pre><p><strong>Cas 3 : R&amp;D / Amélioration du Modèle</strong></p><p>Besoin : Comprendre le comportement global, identifier bugs</p><p>Recommandation :</p><ol><li>LIME pour itérations rapides</li><li>SHAP global pour insights profonds</li><li>Feature Importance pour vue d’ensemble</li></ol><p>Workflow :</p><pre>1. Feature Importance → Identifier features clés<br>2. LIME sur échantillon → Détecter patterns locaux<br>3. SHAP global → Confirmer insights<br>4. Analyse des outliers → Corriger bugs</pre><p><strong>Cas 4 : Interface Utilisateur Interactive</strong></p><p>Besoin : Permettre à l’utilisateur d’explorer “et si…”</p><p>Recommandation :</p><ol><li>Counterfactuals interactifs</li><li>LIME temps réel (rapide)</li><li>Visualisations dynamiques</li></ol><p>Exemple d’interface :</p><pre>┌─────────────────────────────────────┐<br>│ VOTRE PROFIL : Score 7.2/10         │<br>│ OBJECTIF : 8.0/10                   │<br>│                                     │<br>│ 🔧 MODIFIEZ VOS DONNÉES :           │<br>│   Revenu : [35,000] → [ 42,000 ] €  │<br>│   Endettement : [45%] → [ 35% ]     │<br>│                                     │<br>│ 📈 NOUVEAU SCORE ESTIMÉ : 8.3/10 ✅ │<br>│                                     │<br>│ 💡 AUTRES OPTIONS :                 │<br>│   • Augmenter épargne de 5k€ → 7.8  │<br>│   • Réduire incidents → 7.9         │<br>└─────────────────────────────────────┘</pre><h3>Conclusion Finale</h3><p>L’IA Explicable pour la régression n’est plus une option mais une composante essentielle des systèmes d’IA responsables. En comprenant et en appliquant les techniques présentées dans ce guide, vous pourrez :</p><p>✅ Développer la confiance des utilisateurs dans vos systèmes<br>✅ Respecter les réglementations croissantes en matière de transparence<br>✅ Améliorer la qualité de vos modèles en détectant les biais<br>✅ Créer plus de valeur avec des explications actionnables</p><p>Le futur de l’IA ne se situe pas dans la performance pure, mais dans l’alliance entre performance et compréhension.</p><p><em>“Une IA qu’on ne comprend pas est une IA à laquelle on ne peut pas faire confiance. Une IA à laquelle on ne fait pas confiance est une IA qui ne sera pas adoptée.”</em></p><h3>Références :</h3><p><a href="https://www.researchgate.net/publication/396621336_Explainable_AI_in_Credit_Decisioning_Balancing_Accuracy_and_Transparency#:~:text=The%20integration%20of%20artificial%20intelligence,capacity%20of%20traditional%20statistical%20models.">Explainable AI in Credit Decisioning: Balancing Accuracy and Transparency</a></p><p><a href="https://ieeexplore.ieee.org/document/9810062">Toward Explainable Artificial Intelligence for Regression Models: A methodological perspective</a></p><p><a href="https://link.springer.com/article/10.1007/s10462-024-10854-8">Explainable artificial intelligence (XAI) in finance:<br>a systematic literature review</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=781a3f0f16cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vers une Intelligence Artificielle Explicable pour les Modèles de Régression : Une Synthèse…]]></title>
            <link>https://medium.com/@ykarray29/vers-une-intelligence-artificielle-explicable-pour-les-mod%C3%A8les-de-r%C3%A9gression-une-synth%C3%A8se-f7858ca84df8?source=rss-25b22d7e4148------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7858ca84df8</guid>
            <category><![CDATA[xai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <dc:creator><![CDATA[yasmine karray]]></dc:creator>
            <pubDate>Fri, 07 Nov 2025 10:49:02 GMT</pubDate>
            <atom:updated>2025-11-07T10:58:45.357Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vers une Intelligence Artificielle Explicable pour les Modèles de Régression : Une Synthèse Complète</h3><p><strong>Article de référence :</strong> “Toward Explainable Artificial Intelligence for Regression Models”<br> <strong>Auteurs :</strong> Simon Letzgus, Patrick Wagner, Jonas Lederer, Wojciech Samek, Klaus-Robert Müller, Grégoire Montavon<br> <strong>Lien :</strong> <a href="https://arxiv.org/pdf/2112.11407">https://arxiv.org/pdf/2112.11407</a></p><h3>Introduction : Le Défi Négligé de l’Explicabilité en Régression</h3><p>L’Intelligence Artificielle Explicable (XAI) a connu des avancées majeures pour la classification, mais son application à la régression reste largement sous-explorée. Pourtant, la régression constitue l’un des outils fondamentaux du machine learning, utilisé dans des domaines critiques comme la finance, la médecine prédictive et la chimie quantique.</p><p><strong>XAIR (eXplainable AI for Regression)</strong> vise à combler cette lacune en permettant l’interprétation de modèles complexes, particulièrement les réseaux neuronaux profonds, dans un contexte de régression. L’objectif est double :</p><ol><li><strong>Valider la fiabilité</strong> des modèles dans des applications à enjeux élevés</li><li><strong>Extraire de nouvelles connaissances</strong> pour mieux comprendre les phénomènes sous-jacents</li></ol><p>L’article se concentre sur les explications <strong>post-hoc</strong> (appliquées à un modèle déjà entraîné), <strong>locales</strong> (au niveau de chaque instance) et de type <strong>attribution</strong> (qui assignent un score de contribution à chaque caractéristique d’entrée).</p><h3>Les Spécificités Fondamentales de la Régression</h3><h3>1. Le Problème de l’Unité de Mesure</h3><p><strong>Défi central :</strong> Les prédictions de régression sont souvent associées à une unité physique spécifique (prix en euros, énergie en kJ/mol, âge en années).</p><p><strong>Solution XAIR :</strong> Une méthode d’explication appropriée doit hériter de cette unité. Si le modèle prédit un prix, l’attribution Rᵢ doit s’exprimer dans la même unité monétaire.</p><p><strong>Condition requise :</strong> La propriété de <strong>conservation</strong> devient cruciale :</p><pre>∑ᵢ Rᵢ = f(x)</pre><p>Cette équation garantit que la somme des contributions individuelles égale exactement la prédiction, préservant ainsi l’interprétation physique.</p><h3>2. La Nécessité d’une Valeur de Référence Contextuelle (yᵤ)</h3><p><strong>Défi :</strong> Contrairement à la classification où existe une frontière de décision naturelle (ex: “chat” vs “non-chat”), la régression produit des valeurs continues sans seuil inhérent.</p><p><strong>Solution XAIR :</strong> Introduire une valeur de référence <strong>yᵤ</strong> spécifiée par l’utilisateur pour contextualiser l’explication. La question devient :</p><blockquote>“Pourquoi la valeur prédite est-elle y et non yᵤ ?”</blockquote><p><strong>Avantage :</strong> Cela évite que l’explication soit dominée par des effets grossiers et non pertinents, permettant de se concentrer sur des variations fines et intéressantes.</p><p>La figure ci-dessous illustre ces différences fondamentales :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*YdwM75Udav0NQoYj41KvMQ.png" /><figcaption>FIGURE 1. Vue d’ensemble de l’XAI pour la régression et la classification. La variable x désigne un point d’intérêt pour lequel nous souhaitons expliquer la prédiction y = f(x). L’XAI pour la régression diffère de la classification sur deux points : 1) les scores d’explication peuvent être interprétés comme des quantités physiques ayant la même unité que la prédiction, et 2) l’explication est produite par rapport à une valeur de référence yᵤ définie par l’utilisateur, ce qui affecte substantiellement l’explication. <a href="https://arxiv.org/pdf/2112.11407">source</a></figcaption></figure><h3>Exemple Illustratif : Scénario d’Enchères</h3><p>Prenons l’exemple d’une enchère au premier prix avec deux enchérisseurs :</p><ul><li><strong>Enchérisseur 1 :</strong> 1001 €</li><li><strong>Enchérisseur 2 :</strong> 900 €</li><li><strong>Prix de vente :</strong> y = max(1001, 900) = 1001 €</li></ul><p><strong>Question 1 : “Pourquoi le prix est-il de 1001 € et non 0 € ?” (yᵤ = 0)</strong></p><p><strong>Explication (naïve) :</strong> Les deux enchérisseurs contribuent positivement.</p><p><strong>Question 2 (contextuelle) : “Pourquoi le prix est-il de 1001 € et non 1000 € ?” (yᵤ = 1000 €, le prix de base du vendeur)</strong></p><p><strong>Explication (XAIR) :</strong> Seul le premier enchérisseur contribue au bénéfice supplémentaire de 1 €.</p><p>Cette contextualisation fournit une information bien plus pertinente pour le vendeur, car elle identifie précisément quelle enchère a permis de dépasser le prix de réserve.</p><p>La figure 2 schématise ce scénario :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*mLhFhamkoLT-bSPiUk9-Gw.png" /><figcaption><em>FIGURE 2. Scénario d’enchère. La fonction ML prédit le résultat (prix de vente) de l’enchère. La prédiction doit être expliquée de manière significative en termes d’acheteurs individuels et de leurs caractéristiques. L’explication standard (à gauche) et l’explication proposée (à droite) montrent comment la référence yᵤ change l’interprétation.</em> <a href="https://arxiv.org/pdf/2112.11407">source</a></figcaption></figure><h3>Cadre Mathématique Fondamental et Défis Techniques</h3><h4>Le Problème des Points Racines après Décalage</h4><p>Pour expliquer la fonction décalée <strong>g(x) = f(x) — yᵤ</strong>, de nombreuses méthodes (comme les Integrated Gradients) nécessitent un <strong>point racine x’ᵤ</strong> où <strong>g(x’ᵤ) = 0</strong> (c’est-à-dire où <strong>f(x’ᵤ) = yᵤ</strong>).</p><h4>Qu’est-ce qu’un point racine ?</h4><p>C’est le point de départ à partir duquel l’algorithme commence ses calculs d’attribution. C’est la “référence” ou “état neutre” par rapport auquel on mesure les contributions.</p><p>Cependant, après décalage de la fonction, le point racine original n’est plus valable et de nouveaux points racines apparaissent, comme le montre la figure 3 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*B3UsLijWzCp7mROzRNyzxg.png" /><figcaption><em>FIGURE 3. L’effet du décalage de la fonction sur les points racines de la fonction. Après le décalage, le point racine original xᵤ n’est plus un point racine, et il existe potentiellement de nombreux nouveaux points racines xᵤ’ parmi lesquels choisir. Le choix de ce point peut introduire un biais dans l’explication.</em> <a href="https://arxiv.org/pdf/2112.11407">source</a></figcaption></figure><h4>Pourquoi ce problème est crucial ?</h4><ol><li>Les méthodes basées sur le gradient ou le retrait de features dépendent fortement du choix du point racine</li><li>Chaque nouveau point racine potentiel peut produire une explication différente</li><li>Le choix d’un point racine inapproprié peut introduire un biais significatif dans l’explication</li></ol><h4>Le Vrai Problème : Qui choisit le point racine et comment ?</h4><p>⚠️ <strong>Le point racine N’EST PAS nécessairement une moyenne statistique !</strong></p><p>Le point racine peut être choisi indépendamment de la moyenne des données, bien que la moyenne puisse parfois servir de point de référence.</p><h4>Méthodes de Choix du Point Racine</h4><p><strong>✅ Méthodes “Intelligentes” (Recommandées)</strong></p><p>Choix par expertise du domaine</p><p>Point de bascule naturel</p><ul><li>Exemple : Température corporelle normale (37°C)</li></ul><p>État “neutre” ou “zéro” du système</p><p><strong>❌ Méthodes “Moins Intelligentes” (À éviter)</strong></p><ol><li>Choix arbitraire “aveugle”</li><li>Extrapolation hasardeuse</li><li>Point “par défaut” sans justification</li></ol><h3>Solutions Proposées par l’Article</h3><h3>1. Moyenne sur plusieurs points racines (Robuste mais coûteux)</h3><pre>attribution_finale = moyenne(<br>    attribution(x&#39;ᵤ₁),<br>    attribution(x&#39;ᵤ₂), <br>    attribution(x&#39;ᵤ₃)<br>)</pre><h3>2. Fonction de clipping (Simple mais limité)</h3><pre>g⁺(x) = max(0, f(x) - yᵤ)  # Préserve le point racine original</pre><p><strong>Note importante :</strong> la raison pour laquelle on peut avoir plusieurs de ces points (ou plutôt, plusieurs choix possibles pour un point de référence) dans la méthode des Gradients Intégrés est liée à la nécessité d’obtenir des explications robustes et complètes qui ne sont pas biaisées par une exploration trop locale de l’espace d’entrée. La flexibilité dans le choix du point de référence et l’utilisation de techniques de randomisation visent à améliorer la qualité et la fiabilité des explications en XAIR.</p><h3>Les Trois Familles de Méthodes d’Explication (Post-Hoc)</h3><p>Nous allons maintenant expliquer les méthodes sans l’utilisation des points de référence, juste pour comprendre les fondamentaux des différentes idées.</p><h3>1. Méthodes Basées sur le Retrait (Removal-based)</h3><p><strong>Principe fondamental :</strong> Évaluer la contribution d’une caractéristique en la retirant et en mesurant l’impact sur la sortie du modèle. C’est une méthode de perturbation par retrait qui étudie comment le changement d’un input affecte le résultat.</p><h4>Valeurs de Shapley — Explication Détaillée</h4><p><strong>Origine :</strong> Issues de la théorie des jeux coopératifs, conçues pour résoudre le problème : <em>“Comment répartir équitablement les gains entre des joueurs qui coopèrent ?”</em></p><p><strong>Analogie intuitive :</strong> Imaginez que vous et un ami gagnez 10 000€ dans un concours. Comment diviser équitablement l’argent ? Les valeurs de Shapley répondent à cette question en considérant :</p><ul><li>Votre performance individuelle (7 500€ seul)</li><li>La performance de votre ami (5 000€ seul)</li><li>Votre performance ensemble (10 000€)</li></ul><p><strong>Formule mathématique :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*uHvk9vm41mnHcDun0RTQUw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*YBc9DxnKEs2YX8jyYvWVgA.png" /></figure><p>Exemple de calcule :</p><p>Dataset :</p><p>X1: 1, 2, 3<br>X2: 5, 6, 7<br>Y = X1 + X2: 6, 8, 10</p><p>Calcul pour une instance spécifique : X1=3, X2=7, Y=10</p><p><strong>Calcul pour X1</strong></p><p>Coalition S = {} (ensemble vide)</p><p>f(S) = f({}) = 0 (par convention, modèle sans features)</p><p>f(S ∪ {X1}) = f({X1}) = X1 = 3</p><p>Contribution marginale = f(S ∪ {X1}) — f(S) = 3–0 = 3</p><p>Poids = |S|!(N-|S|-1)!/N! = 0!(2–0–1)!/2! = 1×1/2 = 0.5</p><p>Coalition S = {X2}</p><ul><li>f(S) = f({X2}) = X2 = 7</li><li>f(S ∪ {X1}) = f({X1,X2}) = X1 + X2 = 3 + 7 = 10</li><li>Contribution marginale = 10–7 = 3</li><li>Poids = |S|!(N-|S|-1)!/N! = 1!(2–1–1)!/2! = 1×1/2 = 0.5</li></ul><p><strong>Valeur de Shapley pour X1 :</strong></p><pre>R_X1 = (0.5 × 3) + (0.5 × 3) = 1.5 + 1.5 = 3</pre><p><strong>Calcul pour X2</strong></p><p>Coalition S = {} (ensemble vide)</p><p>f(S) = f({}) = 0</p><p>f(S ∪ {X2}) = f({X2}) = X2 = 7</p><p>Contribution marginale = 7–0 = 7</p><p>Poids = 0.5</p><p>Coalition S = {X1}</p><p>f(S) = f({X1}) = X1 = 3</p><ul><li>f(S ∪ {X2}) = f({X1,X2}) = X1 + X2 = 3 + 7 = 10</li><li>Contribution marginale = 10–3 = 7</li><li>Poids = 0.5</li></ul><p><strong>Valeur de Shapley pour X2 :</strong></p><pre>R_X2 = (0.5 × 7) + (0.5 × 7) = 3.5 + 3.5 = 7</pre><h3>Vérification de la Propriété d’Efficacité</h3><p>Somme des contributions = R_X1 + R_X2 = 3 + 7 = 10</p><p>Valeur du modèle = f(X1,X2) = 3 + 7 = 10</p><p>📹 <strong>Pour une explication visuelle :</strong> <a href="https://www.youtube.com/watch?v=VB9uV-x0gtg">Vidéo Shapley Values</a></p><h3>2. Méthodes Basées sur le Gradient (Gradient-based)</h3><p><strong>Principe :</strong> Éviter le coût exponentiel en exploitant le gradient du modèle, calculable efficacement en une seule passe.</p><h4>Gradients Intégrés (Integrated Gradients — IGs) — Explication Détaillée</h4><p><strong>Idée fondamentale :</strong> Au lieu de regarder le gradient à un seul point, intégrer le gradient le long d’un chemin entre une référence et l’input.</p><p><strong>Explication du gradient :</strong> Pour chaque variable d’entrée (comme la température), on calcule la dérivée partielle de la fonction de sortie f(x) par rapport à cette variable. Concrètement, cela signifie qu’on calcule comment la sortie change quand on modifie légèrement chaque variable d’entrée, en tenant compte de toutes les transformations que cette variable subit à travers les différentes couches du réseau neuronal.</p><p><strong>Analogie concrète : Mesurer une pente</strong></p><p>Imaginez que vous marchez sur une colline :</p><ul><li><strong>xᵤ</strong> : point de départ (bas de la colline)</li><li><strong>x</strong> : point d’arrivée (haut de la colline)</li><li><strong>f(x)</strong> : altitude au point x</li><li><strong>∂f/∂xᵢ</strong> : pente dans la direction i à votre position actuelle</li><li><strong>dxᵢ/dt</strong> : vitesse à laquelle vous avancez dans la direction i</li></ul><p><strong>Clarification sur t :</strong></p><p><strong>t est un paramètre de parcours dans [0,1]</strong> :</p><ul><li>t = 0 correspond au point de référence xᵤ</li><li>t = 1 correspond au point d’intérêt x</li><li>t c’est simplement un paramètre qui permet de parcourir linéairement le segment entre xᵤ et x</li></ul><p>L’intégrale mesure : l’accumulation totale de votre “gain d’altitude” dû spécifiquement au déplacement dans chaque direction.</p><p><strong>Formule mathématique :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*Wxd5mXeNZXU6189K6VTb6A.png" /></figure><p>où <strong>x(t) = xᵤ + t(x — xᵤ)</strong> avec t de 0 à 1</p><p><strong>Interprétation intuitive :</strong></p><ol><li>On suit un chemin linéaire du point de référence xᵤ au point d’intérêt x</li><li>À chaque petit pas, on mesure combien la fonction change par rapport à chaque feature</li><li>On accumule ces contributions infinitésimales</li></ol><p><strong>Les axiomes satisfaits :</strong></p><ol><li><strong>Complétude :</strong> ∑ Rᵢ = f(x) — f(xᵤ)</li><li><strong>Sensibilité :</strong> Si une feature change la prédiction, elle reçoit une attribution non-nulle</li><li><strong>Invariance d’implémentation :</strong> Modèles équivalents donnent les mêmes explications</li></ol><p><strong>Avantage :</strong> Conservation garantie, efficacité computationnelle<br> <strong>Limite :</strong> N’explore qu’une région locale (le segment entre xᵤ et x)</p><p>📹 <strong>Pour une explication visuelle :</strong> <a href="https://www.youtube.com/watch?v=o_HuURALtdc">Vidéo Integrated Gradients</a></p><h3>3. Méthodes Basées sur la Propagation Rétrograde (Propagation-based)</h3><p><strong>Principe :</strong> Exploiter la structure spécifique des réseaux neuronaux pour propager la prédiction (la “pertinence”) de la sortie vers l’entrée, couche par couche.</p><h4>🔍 Layer-wise Relevance Propagation (LRP) — Explication Détaillée</h4><p><strong>Concept clé :</strong> Chaque neurone reçoit une part de la “pertinence” et la redistribue aux neurones de la couche précédente selon son importance relative.</p><p>⚡ <strong>Différence clé avec IG :</strong> LRP exploite directement l’architecture du réseau neuronal et ses poids appris, sans nécessiter de parcours de chemin ni de point de référence explicite. On utilise les poids déjà calculés durant l’entraînement. On fait une somme pondérée pour déterminer si un neurone i dans la couche l est important pour un neurone j dans la couche l+1, et on propage cette importance de manière rétrograde (couche l+1 → l → l-1, etc.).</p><p><strong>Équation fondamentale :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/1*PDHFo9ZfEe2O3jMYDiiBWQ.png" /></figure><p><strong>où :</strong></p><ul><li><strong>Rⱼ</strong> : pertinence du neurone j</li><li><strong>Rₖ</strong> : pertinence du neurone k dans la couche suivante</li><li><strong>zⱼₖ</strong> : contribution du neurone j à l’activation du neurone k</li></ul><p><strong>Règles LRP courantes :</strong></p><ol><li><strong>LRP-0 :</strong> zⱼₖ = aⱼwⱼₖ (simple produit activation×poids)</li><li><strong>LRP-ε :</strong> zⱼₖ = aⱼwⱼₖ + ε·sign(aⱼwⱼₖ) (régularisation)</li><li><strong>LRP-γ :</strong> zⱼₖ = aⱼwⱼₖ + γ·aⱼwⱼₖ⁺ (favorise les contributions positives)</li></ol><p><strong>Processus en 3 étapes :</strong></p><ol><li><strong>Initialisation :</strong> Rₗ = f(x) pour la couche de sortie</li><li><strong>Propagation rétrograde :</strong> Calculer Rⱼ pour chaque couche</li><li><strong>Attribution finale :</strong> Rᵢ pour les features d’entrée</li></ol><p><strong>Avantages :</strong></p><ul><li><strong>Conservation :</strong> ∑ Rᵢ = f(x) à chaque couche</li><li><strong>Efficacité :</strong> Une seule passe avant/arrière</li><li><strong>Applicabilité :</strong> CNN, GNN, LSTM, etc.</li></ul><p><strong>Défi pour XAIR :</strong> LRP ne nécessite pas de point de référence xᵤ mais dépend de la représentation interne du réseau.</p><p>📹 <strong>Pour une explication visuelle :</strong> <a href="https://www.youtube.com/watch?v=PDRewtcqmaI">Vidéo LRP</a></p><h3>Stratégies XAIR pour Intégrer la Valeur de Référence</h3><p>Maintenant, nous allons voir comment appliquer ces méthodes, mais cette fois au lieu d’utiliser simplement f(x), on va intégrer la méthode avec la valeur de référence yᵤ.</p><p><strong>Ces deux stratégies servent à adapter les méthodes d’explication existantes</strong> (comme LRP) pour qu’elles puissent expliquer la fonction décalée <strong>g(x) = f(x) — yᵤ</strong> au lieu de la fonction originale f(x).</p><p><strong>Point clé :</strong> Les méthodes (Shapley, IG, LRP) existent déjà, mais l’innovation de l’article est de les adapter pour expliquer <strong>g(x) = f(x) — yᵤ</strong> au lieu de <strong>f(x)</strong>.</p><h3>Stratégie A. Retraining (Réentraînement)</h3><p>Cette méthode est conceptuellement simple : il s’agit de réentraîner le même modèle, mais au lieu de prédire f(x), on prédit g(x) = f(x) — yᵤ.</p><p>⚠️ <strong>Cependant, ce n’est pas anodin</strong> : cela modifie fondamentalement les représentations internes apprises par le modèle.</p><p><strong>Approche :</strong> Entraîner un réseau neuronal de substitution <strong>g(x; θ)</strong> pour répliquer la fonction décalée g(x) sur une plage pertinente de valeurs de prédiction.</p><p><strong>où :</strong></p><ul><li><strong>θ</strong> représente les paramètres du modèle (poids et biais du réseau neuronal)</li><li><strong>x</strong> représente le vecteur d’entrée (par exemple : [taille, poids, âge])</li><li><strong>yᵤ</strong> est la valeur de référence choisie</li></ul><p><strong>Avant :</strong> Modèle apprend f(x) → âge<br> <strong>Après recyclage :</strong> Modèle apprend g(x) = f(x) — yᵤ → (âge — référence)</p><p><strong>Pourquoi réentraîner ?</strong></p><p>Quand on applique LRP directement à un modèle entraîné sur f(x), les explications reflètent la structure interne apprise pour prédire f(x). En réentraînant sur g(x), on force le modèle à représenter différemment les variations autour de yᵤ.</p><p><strong>Analogie :</strong> C’est comme si on « neutralisait » la prédiction de base et qu’on se concentrait uniquement sur l’écart par rapport à la référence. Si on sait déjà que l’âge moyen dans une ville est de 30 ans, prédire l’écart permet au modèle de se concentrer sur les facteurs qui rendent quelqu’un plus jeune ou plus vieux que cette référence.</p><p><strong>Fonction objectif (MSE) :</strong></p><pre>min_θ ∑ₙ (g(xₙ) - g(xₙ;θ))² · 1{yᵤ-ξ₋ ≤ f(xₙ) ≤ yᵤ+ξ₊}</pre><p><strong>Avantages :</strong></p><ul><li>Préserve l’unité de mesure</li><li>Flexible et théoriquement solide</li></ul><p><strong>Inconvénients :</strong></p><ul><li>Coût computationnel élevé</li><li>Nécessite l’accès aux données d’entraînement originales</li><li>Risque d’altérer la stratégie de décision du modèle original</li></ul><h3>Stratégie B. Restructuring (Restructuration)</h3><p><strong>Approche :</strong> Modifier manuellement les dernières couches du réseau pour que sa sortie devienne exactement g(x), sans réentraînement. Suppose une architecture avec une couche ReLU suivie d’une couche linéaire en sortie.</p><p>⚠️ <strong>CRUCIAL : Ce n’est PAS du fine-tuning !</strong></p><ul><li><strong>Fine-tuning</strong> : Réentraînement partiel qui modifie les poids</li><li><strong>Restructuring</strong> : Transformation algébrique de l’architecture qui préserve la fonction f(x) mais reformule sa structure pour faciliter l’explication de g(x) = f(x) — yᵤ</li><li><strong>Aucun poids n’est modifié par apprentissage</strong></li></ul><p><strong>Attention :</strong> L’astuce n’est pas de changer le type de tâche, mais de reformuler mathématiquement le problème pour que les explications soient plus significatives.</p><h4>Étape 1 : Propagation dans la couche Linéaire</h4><p>Le décalage y — yᵤ est réécrit en transformant yᵤ en un vecteur d’activation de référence aᵤ :</p><pre>y - yᵤ = ∑ⱼ (aⱼ - aᵤ,ⱼ)wⱼ + b</pre><p><strong>Technique du “Flooding” :</strong></p><ol><li>On identifie les neurones qui capturent des concepts généraux (ex: “visage humain”)</li><li>On choisit aᵤ pour “absorber” ou “neutraliser” ces activations de grande magnitude</li><li><strong>Résultat :</strong> Les explications se concentrent sur les variations fines autour de yᵤ</li></ol><p><strong>Métaphore :</strong> C’est comme retirer le “bruit de fond” pour entendre les détails subtils.</p><p><strong>Exemple concret avec l’âge facial</strong></p><p><strong>Sans restructuration :</strong></p><ul><li>Neurone A : activation = 1000 (capture “visage humain” en général)</li><li>Neurone B : activation = 50 (capture “rides autour des yeux”)</li><li>L’explication sera dominée par le neurone A</li></ul><p><strong>Avec restructuration (flooding) :</strong></p><ul><li>On “absorbe” l’activation 1000 dans aᵤ (comme si on donne moins d’importance à ce neurone)</li><li>L’explication se concentre sur le neurone B (rides)</li><li><strong>Résultat :</strong> On explique pourquoi la personne a 96 ans et non 80 ans, basé sur les rides spécifiques</li></ul><h4>Étape 2 : Propagation dans la couche ReLU</h4><p>Un neurone ReLU décalé ReLU(aⱼ — aᵤ,ⱼ) est réécrit comme une combinaison linéaire de trois ReLU standard, comme illustré dans la figure 4 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*rPK-C7vj6qAg8WDsJ9_uIQ.png" /><figcaption><em>FIGURE 4. La transformation d’un neurone ReLU décalé (bleu) en une somme de plusieurs ReLU non décalés (rouge). Cette dernière est fonctionnellement équivalente mais plus adaptée à la technique de propagation LRP.</em> <a href="https://arxiv.org/pdf/2112.11407">source</a></figcaption></figure><p><strong>Transformation mathématique :</strong></p><pre>ReLU(aⱼ - aᵤ,ⱼ) = ReLU(aⱼ) + ReLU(-aᵤ,ⱼ) - ReLU(aⱼ - aᵤ,ⱼ)</pre><p>Cette transformation permet de créer un nouveau réseau, fonctionnellement équivalent, mais dont la structure interne est plus adaptée à une explication fine autour de yᵤ.</p><h4>Architecture avant reconstruction :</h4><p>python</p><pre>h = self.relu(x)      # h = max(0, x)<br>y = self.linear(h)    # y = W*h + b</pre><p><strong>1️⃣ ReLU layer</strong></p><pre>h = ReLU(x) = max(0, x)</pre><p><strong>2️⃣ Linear layer</strong></p><pre>y = W h + b</pre><p><strong>Donc la fonction totale est :</strong></p><pre>f(x) = W ReLU(x) + b</pre><h4>Architecture après reconstruction :</h4><p>On veut :</p><pre>y&#39; = y - yₑ = W h + b - yₑ</pre><p>Au lieu de faire une simple soustraction, l’auteur introduit un nouveau vecteur d’activation de référence <strong>hₑ</strong> (qu’il appelle <strong>aₑ</strong> dans le papier).</p><p>On choisit <strong>hₑ</strong> tel que :</p><pre>W hₑ = yₑ</pre><p>puis on réécrit :</p><pre>y&#39; = W(h - hₑ) + b</pre><h4>Étape 2 : Répercussion dans la couche ReLU</h4><p>Maintenant, la couche précédente faisait :</p><pre>h = ReLU(z)</pre><p>et on veut remplacer <strong>h</strong> par <strong>h — hₑ</strong>.</p><p>La transformation clé est :</p><pre>h - hₑ = ReLU(z - hₑ) + ReLU(-z) - ReLU(-z + hₑ)</pre><p><strong>Vérifions que cette transformation est correcte dans tous les cas :</strong></p><p><strong>Cas 1 : z &lt; 0</strong></p><ul><li>z — hₑ &lt; 0 ⇒ ReLU(z — hₑ) = 0</li><li>-z &gt; 0 ⇒ ReLU(-z) = -z</li><li>Si hₑ &gt; 0, alors -z + hₑ peut être &gt; 0 ⇒ ReLU(-z + hₑ) = -z + hₑ</li></ul><p>Donc : g(z) = 0 + (-z) — (-z + hₑ) = -hₑ ✅</p><p>→ ✅ Même résultat que ReLU(z) — hₑ = -hₑ</p><p><strong>Cas 2 : 0 ≤ z &lt; hₑ</strong></p><ul><li>z — hₑ &lt; 0 ⇒ ReLU(z — hₑ) = 0</li><li>-z &lt; 0 ⇒ ReLU(-z) = 0</li><li>-z + hₑ &gt; 0 ⇒ ReLU(-z + hₑ) = hₑ — z</li></ul><p>Donc : g(z) = 0 + 0 — (hₑ — z) = z — hₑ ✅</p><p>→ ✅ Même résultat que ReLU(z) — hₑ = z — hₑ</p><p><strong>Cas 3 : z ≥ hₑ</strong></p><ul><li>z — hₑ &gt; 0 ⇒ ReLU(z — hₑ) = z — hₑ</li><li>-z &lt; 0 ⇒ ReLU(-z) = 0</li><li>-z + hₑ &lt; 0 ⇒ ReLU(-z + hₑ) = 0</li></ul><p>Donc : g(z) = (z — hₑ) + 0–0 = z — hₑ ✅</p><p>→ ✅ Même résultat encore.</p><h4>Code de l’architecture restructurée :</h4><p>python</p><pre># Décomposition de ReLU(z - h_e) en trois ReLU standards<br>h1 = F.relu(z - self.h_e)      # Partie positive décalée<br>h2 = F.relu(-z)                 # Partie négative de z<br>h3 = F.relu(-z + self.h_e)      # Correction pour préserver l&#39;équivalence<br>h_prime = h1 + h2 - h3          # Combinaison linéaire équivalente<br>y_prime = self.linear(h_prime)</pre><p><strong>Note importante :</strong> <strong>hₑ</strong> (ou <strong>aₑ</strong> dans le papier) est un vecteur de référence choisi manuellement.</p><h3>Validation Expérimentale : Restructuration et Retraining</h3><h3>Protocole Expérimental</h3><p>L’étude a évalué les méthodes XAIR sur cinq jeux de données de régression variés :</p><ol><li><strong>Max :</strong> Fonction maximum de 8 variables</li><li><strong>Linear :</strong> Problème linéaire avec 4 features pertinentes</li><li><strong>Friedman :</strong> Régression non-linéaire synthétique complexe</li><li><strong>Diabetes :</strong> Progression du diabète (442 patients, 10 features)</li><li><strong>Boston :</strong> Prix immobiliers (506 propriétés, 13 features)</li></ol><p>Le modèle testé était un réseau de neurones à deux couches (256 neurones ReLU + sortie linéaire). Les <strong>Valeurs de Shapley</strong> ont servi de référence théorique pour évaluer la qualité des explications.</p><h3>Méthodes Comparées</h3><p><strong>Méthodes XAIR Proposées :</strong></p><ul><li><strong>Model Retraining :</strong> Recyclage du modèle pour apprendre g(x) = f(x) — yᵤ</li><li><strong>Model Restructuring :</strong> Restructuration architecturale sans réentraînement</li></ul><p><strong>Méthodes de Référence (Baselines) :</strong></p><ul><li><strong>Explanation Scaling :</strong> Simple mise à l’échelle des explications LRP standard</li><li><strong>Explanation Shift :</strong> Décalage uniforme des attributions</li></ul><p><strong>Explanation Scaling</strong> (approche naïve de référence) :</p><ul><li>Prend les explications LRP standards pour f(x)</li><li>Les met à l’échelle proportionnellement pour correspondre à g(x) = f(x) — yᵤ</li><li>Formule : R’ᵢ = Rᵢ · [g(x) / f(x)]</li><li><strong>Problème :</strong> Ne modifie pas la structure interne du modèle, donc les explications restent biaisées vers f(x) plutôt que g(x)</li></ul><h3>Résultats Clés</h3><p>L’analyse révèle une supériorité marquée et statistiquement significative des méthodes XAIR proposées sur tous les jeux de données testés :</p><ul><li><strong>Model Restructuring</strong> obtient les meilleures performances globales avec une réduction d’erreur de plus de <strong>22%</strong> par rapport à Explanation Scaling</li><li><strong>Model Retraining</strong> se place en deuxième position avec environ <strong>17%</strong> de réduction d’erreur</li><li>L’avantage des méthodes XAIR est consistant across tous les jeux de données</li><li>L’impact positif est plus prononcé lorsque la référence yᵤ s’éloigne de zéro</li></ul><h3>Conclusions des expériences :</h3><ol><li><strong>Supériorité générale :</strong> La Restructuration et le Recyclage surpassent substantiellement les méthodes de base dans toutes les configurations</li><li><strong>Performance de la Restructuration :</strong> Réduction globale du MSE de plus de 22% par rapport à la meilleure baseline</li><li><strong>Performance du Recyclage :</strong> Se place en deuxième position avec une réduction d’environ 17%</li><li><strong>Impact de yᵤ :</strong> Plus yᵤ s’éloigne de zéro, plus l’amélioration apportée par les méthodes XAIR est marquée</li></ol><h3>Applications Concrètes : De la Vision à la Chimie Quantique</h3><h3>Application 1 : Prédiction de l’Âge Facial</h3><p><strong>Contexte :</strong> Tâche de régression populaire en vision par ordinateur, souvent approchée par classification en bins d’âge.</p><p><strong>Modèle :</strong> CNN VGG-16 fine-tuné pour prédire l’âge à partir de photos faciales</p><p><strong>Méthode :</strong> Restructuration XAIR avec trois valeurs de référence (yᵤ = 10, 40, 80 ans)</p><h4>Résultats remarquables :</h4><p><strong>Cas 1 : Personne de 96 ans</strong></p><ul><li><strong>Avec yᵤ = 10 ans :</strong> Toutes les caractéristiques faciales contribuent positivement à un âge avancé (explication peu discriminante)</li><li><strong>Avec yᵤ = 80 ans :</strong> Le heatmap se différencie. Seule la zone autour des yeux est identifiée comme rendant la personne plus âgée que 80 ans</li></ul><p><strong>Cas 2 : Personne de 50 ans</strong></p><ul><li><strong>Avec yᵤ = 40 ans :</strong> Aucune caractéristique fortement saillante, ce qui suggère que le visage présente des caractéristiques cohérentes avec un âge autour de 50 ans, sans traits particulièrement atypiques pour cette tranche d’âge.</li></ul><p><strong>Cas 3 : Bébé de 1 an</strong></p><ul><li><strong>Avec yᵤ = 10 ans :</strong> Le modèle se concentre sur les yeux pour décider que la personne est plus jeune</li><li><strong>Avec yᵤ = 80 ans :</strong> Le modèle attribue plus d’importance aux cheveux (associés aux cheveux blancs)</li></ul><h4>Avantage XAIR vs Classification :</h4><ul><li><strong>Préservation de l’unité :</strong> Attribution d’un nombre d’années précis à des traits faciaux</li><li><strong>Contextualisation granulaire :</strong> Explications fines inaccessibles avec une classification binaire</li></ul><h3>Application 2 : Chimie Quantique (Prédiction d’Énergie)</h3><p><strong>Contexte :</strong> Les méthodes ML révolutionnent les simulations atomistiques, offrant des accélérations jusqu’à <strong>1⁰⁷ fois</strong> (10 millions de fois) par rapport aux méthodes quantiques traditionnelles comme DFT (Density Functional Theory).</p><p><strong>Modèle :</strong> SchNet (Graph Neural Network spécialisé) pour prédire l’énergie d’atomisation des molécules</p><p><strong>Méthode :</strong> Recyclage (Retraining) avec référence physiquement pertinente (yᵤ = énergie moyenne par atome pour molécules à liaisons simples)</p><h4>Problème du Modèle à Référence Zéro (yᵤ = 0)</h4><ul><li>Les atomes reçoivent la majeure partie de la pertinence</li><li>L’importance des liaisons chimiques est masquée</li><li>Les contributions des différentes liaisons sont indiscernables</li></ul><h4>Solution XAIR (avec yᵤ non nul)</h4><ul><li>L’attribution moyenne aux atomes est forcée vers zéro</li><li>La structure des liaisons devient parfaitement saillante</li><li>Les contributions énergétiques augmentent avec l’ordre de liaison</li></ul><p><strong>Ordre croissant d’énergie de liaison :</strong></p><ul><li><strong>Liaison simple</strong> (C-C) : ~348 kJ/mol</li><li><strong>Liaison aromatique</strong> (dans benzène) : ~518 kJ/mol</li><li><strong>Liaison double</strong> (C=C) : ~614 kJ/mol</li><li><strong>Liaison triple</strong> (C≡C) : ~839 kJ/mol</li></ul><p>✅ <strong>Les explications XAIR respectent cet ordre physique</strong></p><p>La figure 9 illustre parfaitement cet impact :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*ZZqjwBs93XiSa-IJiq-3wQ.png" /><figcaption><em>FIGURE 9. La contribution énergétique moyenne par liaison et atome pour un modèle SchNet entraîné avec une valeur de référence nulle et un autre modèle SchNet entraîné avec une valeur de référence non nulle. Les liaisons sont distinguées par leur ordre. La contribution énergétique représentée est en unités arbitraires. Le modèle avec référence non nulle permet de bien mieux distinguer l’importance des différentes liaisons.</em> <a href="https://arxiv.org/pdf/2112.11407">source</a></figcaption></figure><h4>Impact pratique :</h4><ul><li>Le modèle devient validable par un expert</li><li>Détection de distorsions de liaisons invisibles avec référence zéro</li><li>Nouveaux insights sur la structure énergétique des molécules</li></ul><h3>Guide Pratique : 7 Bonnes Pratiques XAIR Essentielles</h3><h3>1. Conserver les Unités de Mesure</h3><p><strong>À FAIRE :</strong></p><ul><li>Préserver l’unité originale de la cible</li><li>Si normalisation nécessaire, remettre le modèle à l’échelle des unités d’origine pour l’explication</li></ul><p><strong>À ÉVITER :</strong></p><ul><li>Transformations non linéaires irréversibles (log, racine carrée) sans déconversion</li><li>Normalisation min-max sans mise à l’échelle inverse</li></ul><h3>2. Utiliser une Technique Conservative</h3><p><strong>Privilégier :</strong> LRP, Integrated Gradients, Valeurs de Shapley</p><p><strong>Propriété requise :</strong></p><pre>∑ᵢ Rᵢ = g(x) = f(x) - yᵤ</pre><h3>3. Demander une Valeur de Référence yᵤ</h3><p><strong>Questions à poser à l’utilisateur :</strong></p><ul><li>“Quelle valeur de comparaison est pertinente pour votre contexte ?”</li><li>“Existe-t-il un seuil réglementaire, un prix de base, une valeur moyenne ?”</li><li>“Quelle question spécifique voulez-vous poser au modèle ?”</li></ul><p><strong>Exemples de yᵤ pertinents :</strong></p><ul><li><strong>Finance :</strong> Prix de base, coût de revient</li><li><strong>Médecine :</strong> Valeur normale, seuil pathologique</li><li><strong>Chimie :</strong> Énergie d’état de référence</li></ul><h3>4. Choisir la Bonne Stratégie d’Implémentation</h3><p><strong>Quand utiliser la Restructuration ?</strong></p><ul><li>Architecture compatible (ReLU + Linear en sortie)</li><li>Accès complet à l’architecture du modèle</li><li>Besoin de préserver exactement le modèle original</li><li>Coût computationnel limité</li></ul><p><strong>Quand utiliser le Réentraînement ?</strong></p><ul><li>Architectures complexes (Transformers, etc.)</li><li>Accès aux données d’entraînement</li><li>Acceptation d’une approximation légère du modèle original</li><li>Besoin d’adaptabilité à différentes valeurs yᵤ</li></ul><h3>5. Réentraînement comme Alternative</h3><p>Si restructuration impossible :</p><ol><li>Vérifier disponibilité des données d’entraînement</li><li>Geler certaines couches pour préserver les représentations</li><li>Surveiller le processus pour éviter solutions triviales</li><li>Tester sur validation set la fidélité au modèle original</li></ol><h3>6. Tests de Cohérence (Sanity Checks)</h3><p><strong>Vérifications obligatoires :</strong></p><pre># Test 1 : Conservation (complétude)<br>g_x = f(x) - y_u<br>total_attribution = sum(attributions)<br>epsilon = 1e-6  # Tolérance numérique</pre><pre>assert abs(total_attribution - g_x) &lt; epsilon, \<br>    f&quot;Conservation violée: {total_attribution} ≠ {g_x}&quot;</pre><pre># Test 2 : Sensibilité<br># Petite perturbation → petite variation dans attributions</pre><pre># Test 3 : Cohérence avec domaine<br># Les features importantes selon le modèle<br># correspondent-elles à l&#39;expertise métier ?</pre><h3>7. Visualisation Appropriée</h3><p><strong>Pour explications quantitatives :</strong></p><ul><li>Graphiques en barres avec unités explicites</li><li>Heatmaps pour données spatiales (images, cartes)</li><li>Tables de contributions triées par magnitude</li></ul><p><strong>Toujours inclure :</strong></p><ul><li>Valeur prédite f(x)</li><li>Valeur de référence yᵤ</li><li>Différence g(x) = f(x) — yᵤ</li><li>Unité de mesure</li></ul><h3>Contributions Majeures de l’Article</h3><ol><li><strong>Formalisation du problème XAIR :</strong> Identification des spécificités de la régression (unités, référence yᵤ, absence de frontière naturelle)</li><li><strong>Deux stratégies innovantes :</strong> Recyclage et Restructuration pour adapter LRP à XAIR</li><li><strong>Validation rigoureuse :</strong> Démonstration empirique de la supériorité des méthodes proposées (&gt;22% d’amélioration)</li><li><strong>Applications réelles :</strong> Vision par ordinateur et chimie quantique montrant l’utilité pratique</li></ol><h3>Références</h3><p><strong>Article principal :</strong> Letzgus, S., Wagner, P., Lederer, J., Samek, W., Müller, K. R., &amp; Montavon, G. (2022). Toward explainable artificial intelligence for regression models. <em>arXiv preprint arXiv:2112.11407</em>.</p><p><strong>Ressources vidéo :</strong></p><ul><li><a href="https://www.youtube.com/watch?v=VB9uV-x0gtg">Shapley Values Explained</a></li><li><a href="https://www.youtube.com/watch?v=o_HuURALtdc">Integrated Gradients Explained</a></li><li><a href="https://www.youtube.com/watch?v=PDRewtcqmaI">Layer-wise Relevance Propagation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7858ca84df8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Active Learning et Bayesian Optimization : Une Perspective Unifiée pour notre Problème — Part 3]]></title>
            <link>https://medium.com/@ykarray29/active-learning-et-bayesian-optimization-une-perspective-unifi%C3%A9e-pour-notre-probl%C3%A8me-part-3-5f2d755e76a8?source=rss-25b22d7e4148------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f2d755e76a8</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-sampling]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sampling]]></category>
            <dc:creator><![CDATA[yasmine karray]]></dc:creator>
            <pubDate>Sat, 01 Nov 2025 10:33:47 GMT</pubDate>
            <atom:updated>2025-11-01T10:33:47.002Z</atom:updated>
            <content:encoded><![CDATA[<h3>Active Learning et Bayesian Optimization : Une Perspective Unifiée pour notre Problème — Part 3</h3><p><strong>Contexte</strong> : Dans la Part 1, nous avons présenté cinq méthodes d’échantillonnage adaptatif pour notre problème d’apprentissage de fonction f(lambda, x1…xn) avec budget limité, dont la <strong>Méthode 1 (Échantillonnage Adaptatif/Active Learning)</strong>. La Part 2 a exploré les fondements théoriques de la <strong>Méthode 4 (OED)</strong>. Nous examinons maintenant comment l’Apprentissage Actif et l’Optimisation Bayésienne offrent une perspective unifiée pour résoudre efficacement notre problème spécifique.</p><p><strong>Article de référence</strong> : “ACTIVE LEARNING AND BAYESIAN OPTIMIZATION: A UNIFIED PERSPECTIVE TO LEARN WITH A GOAL”</p><p><a href="https://arxiv.org/abs/2303.01560">Active Learning and Bayesian Optimization: a Unified Perspective to Learn with a Goal</a></p><h3>Introduction : Résoudre notre problème de fonction coûteuse</h3><p>Dans notre contexte d’apprentissage de f(lambda, x1…xn) avec budget limité, chaque évaluation de la fonction dans les régions à haute variance est coûteuse. Le défi central est : comment transformer notre recherche d’information en une quête ciblée, allouant dynamiquement notre budget limité aux régions où l’incertitude ou la complexité de la fonction est la plus élevée ?</p><p>C’est précisément ici qu’interviennent l’Optimisation Bayesienne (BO) et l’Apprentissage Actif (AL), les deux piliers de notre <strong>Méthode 1</strong> présentée en Part 1.</p><h3>Définitions Clés pour notre Problème</h3><h3>Modèle de Substitution (Surrogate Model)</h3><p>Un modèle mathématique rapide qui “imite” le comportement de notre fonction coûteuse f(lambda, x1…xn). Plutôt que d’évaluer f directement dans chaque région, nous construisons une approximation rapide.</p><p><strong>Formellement pour notre contexte</strong> : Soit f(lambda, x) notre fonction coûteuse, le modèle de substitution f̂(lambda, x) approxime f à moindre coût, nous permettant d’explorer virtuellement l’espace avant de décider où investir notre budget limité d’évaluations.</p><h3>Fonction d’Acquisition (Acquisition Function)</h3><p>Le “cerveau” qui décide où allouer notre prochain point d’échantillonnage. Elle utilise le modèle de substitution pour quantifier l’utilité d’évaluer f dans une région donnée, en tenant compte de notre contrainte : la fonction est difficile à prédire (haute variance) dans certaines plages de lambda et facile (faible variance) dans d’autres.</p><p><strong>Équation générale pour notre problème</strong> : (lambda_new, x_new) = argmax_{(lambda,x) ∈ χ} U(lambda, x)</p><p>où U(lambda, x) est la fonction d’acquisition qui guide notre stratégie d’échantillonnage.</p><h3>Optimisation Bayesienne (BO) pour notre contexte</h3><p>Une stratégie pour apprendre f(lambda, x1…xn) efficacement en combinant modèle de substitution et fonction d’acquisition. Son objectif dans notre problème : construire le meilleur modèle de f avec le minimum d’évaluations, en concentrant les ressources dans les régions à haute variance ou complexité.</p><h3>Apprentissage Actif (AL) pour notre contexte</h3><p>Une stratégie où l’algorithme choisit activement les points (lambda, x) les plus instructifs à évaluer. Son objectif pour notre problème : construire le meilleur modèle de f avec le minimum de données, guidé par l’incertitude du modèle et la variance connue v(lambda).</p><h3>🔍 La Révélation Fondamentale : BO et AL résolvent notre problème de la même manière</h3><p>Comme le démontre l’article, ces deux méthodes qui forment notre <strong>Méthode 1</strong> sont symbiotiques plutôt que distinctes pour résoudre notre problème d’échantillonnage intelligent.</p><p><strong>L’analogie mathématique appliquée à notre contexte</strong> :</p><ul><li>La BO apprend f(lambda, x) via un apprentissage séquentiel guidé par l’objectif</li><li>L’AL maximise la qualité du modèle f̂ via une sélection stratégique</li></ul><p>Mais leur stratégie sous-jacente est identique pour notre problème : <strong>apprendre f avec un objectif précis grâce à une boucle d’échange entre modèle et décision</strong>, en allouant dynamiquement plus de points d’échantillonnage aux régions où l’incertitude ou la complexité est la plus élevée.</p><h3>Le Dilemme Central pour notre Problème : Exploration vs Exploitation</h3><p>Ce dilemme est au cœur de notre stratégie d’échantillonnage adaptatif.</p><h3>En Optimisation Bayesienne pour f(lambda, x)</h3><p><strong>Exploitation</strong> : U_exploit(lambda, x) favorise les zones où notre connaissance a priori v(lambda) indique une haute variance, ou où notre modèle actuel prédit une forte incertitude.</p><p><strong>Exploration</strong> : U_explore(lambda, x) favorise les zones où notre modèle de substitution σ(lambda, x) est le plus incertain, découvrant potentiellement des régions de complexité non capturées par v(lambda).</p><h3>En Apprentissage Actif pour f(lambda, x)</h3><p><strong>Informativité</strong> : Sélection basée sur l’incertitude p(y|lambda, x) — échantillonner où le modèle actuel de f est le plus incertain.</p><p><strong>Représentativité</strong> : Sélection basée sur la couverture du domaine (lambda, x) — s’assurer que toutes les régions de l’espace sont adéquatement représentées.</p><h3>La Correspondance Mathématique appliquée à notre contexte</h3><p><strong>EXPLOITATION (BO) ⇔ INFORMATIVITÉ (AL)</strong> : Recherche orientée vers notre objectif d’apprendre f dans les régions critiques (haute variance/complexité).</p><p><strong>EXPLORATION (BO) ⇔ REPRÉSENTATIVITÉ (AL)</strong> : Amélioration de la connaissance globale de f sur tout l’espace (lambda, x), découvrant des complexités non anticipées par v(lambda).</p><p>Cette dualité est précisément ce qui rend notre <strong>Méthode 1</strong> (Échantillonnage Adaptatif) si puissante pour notre problème : elle équilibre automatiquement l’utilisation de notre connaissance a priori v(lambda) avec la découverte adaptative de nouvelles complexités dans f.</p><h3>Classification Hiérarchique : où se situe notre Méthode 1 ?</h3><p>L’article propose une taxonomie qui clarifie la position de notre <strong>Méthode 1</strong> parmi les stratégies d’échantillonnage.</p><h3>Niveau 1 : Sondage Adaptatif</h3><p>S’adapte aux données passées mais sans modèle de substitution de f.</p><p><strong>Exemple</strong> : Échantillonnage par Importance Adaptatif (AIS) I_hat_N(f) = Σ_{n=1}^N w̄_n f(w_n)</p><p><strong>Limitation pour notre problème</strong> : Ne construit pas de modèle prédictif de f, donc ne peut pas anticiper où la variance ou la complexité sera élevée.</p><h3>Niveau 2 : Modélisation Adaptative</h3><p>Construit un modèle de substitution de f, mais ne l’utilise pas pour guider activement la recherche.</p><p><strong>Exemple</strong> : Collocation Stochastique Adaptative (ASC) A_{q,N}(f) = Σ_{|i| ≤ q} (ΔU^{i_1} ⊗ … ⊗ ΔU^{i_N})(f)</p><p><strong>Limitation pour notre problème</strong> : Le modèle de f est construit passivement, sans exploiter activement l’information pour guider l’échantillonnage vers les régions critiques.</p><h3>Niveau 3 : Apprentissage Adaptatif</h3><p><strong>C’est ici que se situe notre Méthode 1</strong> : Échange mutuel entre modèle de f et décision d’échantillonnage, avec boucle de rétroaction.</p><p><strong>Équation caractéristique pour notre problème</strong> : (lambda_{N+1}, x_{N+1}) = argmax U(p_N(f_n=f|(lambda_n, x_n)))</p><p>Cette formulation capture l’essence de notre <strong>Méthode 1</strong> : à chaque itération N, nous utilisons notre modèle actuel p_N de f pour décider où placer le prochain point (lambda_{N+1}, x_{N+1}), puis nous mettons à jour le modèle avec cette nouvelle observation, créant une boucle d’apprentissage qui s’améliore continuellement.</p><p><strong>Pourquoi c’est optimal pour notre problème ?</strong> Parce que cette boucle de rétroaction permet de :</p><ol><li>Exploiter notre connaissance a priori v(lambda) dès le départ</li><li>S’adapter dynamiquement aux complexités découvertes dans f</li><li>Corriger les imprécisions de v(lambda) au fur et à mesure</li><li>Maximiser l’information extraite de chaque évaluation coûteuse</li></ol><h3>Extensions Multi-Fidélité : optimiser davantage notre budget</h3><p>Pour notre problème où les évaluations de f sont coûteuses, le paradigme multi-fidélité offre une extension puissante de notre <strong>Méthode 1</strong>.</p><h3>Principe pour notre contexte</h3><p>Au lieu d’évaluer toujours f(lambda, x) à pleine résolution (coûteux), nous pouvons exploiter des évaluations à fidélité réduite (moins coûteuses mais moins précises) pour guider notre recherche, réservant les évaluations haute fidélité pour les régions les plus prometteuses.</p><h3>Formulation Multi-Fidélité pour f</h3><p><strong>Équation d’autorégression</strong> : f^(l)(lambda, x) = g^(l-1) f^(l-1)(lambda, x) + ζ^(l)(lambda, x)</p><p>où :</p><ul><li>f^(l) représente f évaluée au niveau de fidélité l</li><li>g est un facteur d’échelle</li><li>ζ^(l) est l’erreur résiduelle</li></ul><p><strong>Interprétation pour notre problème</strong> : Les évaluations basse fidélité de f capturent les tendances principales (où sont les régions à haute variance ?), tandis que les évaluations haute fidélité affinent la connaissance dans les régions critiques.</p><h3>Fonctions d’Acquisition Multi-Fidélité adaptées à notre contexte</h3><p><strong>MFEI (Multifidelity Expected Improvement)</strong> : U_MFEI(lambda, x, l) = U_EI(lambda, x, L) · α_1(lambda, x, l) · α_2(lambda, x, l) · α_3(l)</p><p>où :</p><ul><li>α_1(lambda, x, l) = corr[f^(l), f^(L)] : corrélation entre fidélités (est-ce que basse fidélité prédit bien haute fidélité dans cette région ?)</li><li>α_2(lambda, x, l) = 1 — σ_ε/√(σ²(l)(lambda, x) + σ_ε²) : ajustement pour le bruit</li><li>α_3(l) = λ^(L)/λ^(l) : ratio des coûts (privilégier les évaluations bon marché)</li></ul><p><strong>Application à notre problème</strong> : MFEI équilibre le gain d’information attendu dans les régions à haute variance avec le coût computationnel, permettant d’explorer plus largement l’espace (lambda, x) avec le même budget.</p><p><strong>MFMES (Multifidelity Max-Value Entropy Search)</strong> : U_MFMES(lambda, x, l) = [H(p(f^(l)|D)) — E_{f^(l)(lambda,x)|D}[H(p(f^(l)|f*(L),D))]] / λ^(l)</p><p><strong>Application à notre problème</strong> : MFMES maximise le gain d’information par unité de coût, particulièrement adapté quand notre budget est très contraint et que nous devons prioriser l’apprentissage des régions les plus incertaines de f.</p><h3>Guidance Pratique : quand utiliser quelle variante pour notre problème</h3><h3>Pour les régions simples de f (faible variance v(lambda))</h3><p>✅ <strong>Privilégiez l’exploitation pure (Probability of Improvement)</strong></p><p><strong>Équation PI</strong> : U_PI(lambda, x) = Φ(I(lambda, x)) où I(lambda, x) = (f(lambda_best, x_best) — μ(lambda, x))/σ(lambda, x)</p><p><strong>Raison pour notre problème</strong> : Dans les régions où f est prévisible (faible v(lambda)), il est plus efficace de concentrer les évaluations autour des zones déjà connues pour être informatives, affinant notre modèle local.</p><h3>Pour les régions complexes de f (haute variance v(lambda))</h3><p>✅ <strong>Privilégiez l’exploration pure (Max-Value Entropy Search)</strong></p><p><strong>Équation MES</strong> : U_MES(lambda, x) = H(p(f|D)) — E_{f(lambda,x)|D}[H(p(f|f*,D))]</p><p><strong>Raison pour notre problème</strong> : Dans les régions où f présente haute variance ou complexité, l’exploration large est cruciale pour découvrir la structure sous-jacente et éviter de manquer des zones critiques.</p><h3>En cas d’incertitude sur la structure de f</h3><p>✅ <strong>Équilibrez exploration/exploitation (Expected Improvement)</strong></p><p><strong>Équation EI</strong> : U_EI(lambda, x) = σ(lambda, x)[I(lambda, x)Φ(I(lambda, x)) + φ(I(lambda, x))]</p><p><strong>Raison pour notre problème</strong> : EI équilibre naturellement l’exploration des régions incertaines avec l’exploitation de notre connaissance a priori v(lambda), s’adaptant dynamiquement au comportement local de f. C’est le choix par défaut pour notre <strong>Méthode 1</strong>.</p><h3>Quand notre budget d’évaluations est très limité</h3><p>✅ <strong>Adoptez le multi-fidélité (MFEI, MFMES)</strong></p><p><strong>Raison pour notre problème</strong> : En exploitant des évaluations basse fidélité de f (simulations rapides mais approximatives), nous pouvons explorer plus largement l’espace (lambda, x) pour identifier les régions à haute variance, puis concentrer nos précieuses évaluations haute fidélité sur ces régions critiques.</p><h3>Le Processus Unifié en 5 Étapes</h3><p>Cette boucle est au cœur de notre <strong>Méthode 1</strong> présentée en Part 1.</p><h3>Étape 1 : Initialisation</h3><p>Évaluez quelques points {(lambda_1, x_1, y_1), …, (lambda_n, x_n, y_n)} dans notre espace.</p><p><strong>Application pratique</strong> : Utiliser notre connaissance a priori v(lambda) pour placer ces points initiaux (comme dans la <strong>Méthode 5 — Stratégie Hybride</strong> de la Part 1), en sur-échantillonnant les régions à haute variance anticipée.</p><h3>Étape 2 : Modélisation</h3><p>Construisez un Processus Gaussien (GP) modélisant f : p(f|D)</p><p><strong>Équation de mise à jour du GP</strong> : p(f|D) ∝ p(D|f) · p(f)</p><p><strong>Pour notre problème</strong> : Le GP fournit non seulement une prédiction μ(lambda, x) de f, mais aussi une mesure d’incertitude σ(lambda, x), essentielle pour décider où échantillonner ensuite.</p><h3>Étape 3 : Décision</h3><p>Identifiez le point le plus prometteur : (lambda_new, x_new) = argmax_{(lambda,x) ∈ χ} U(lambda, x)</p><p><strong>Application de la fonction d’acquisition</strong> : U(lambda, x) combine :</p><ul><li>L’incertitude du modèle σ(lambda, x) (exploration)</li><li>Notre connaissance a priori v(lambda) (exploitation)</li><li>Le coût d’évaluation dans cette région (si multi-fidélité)</li></ul><h3>Étape 4 : Évaluation</h3><p>Obtenez y_new = f(lambda_new, x_new) + ε</p><p><strong>Investissement du budget</strong> : Cette évaluation consomme une partie de notre budget limité, d’où l’importance cruciale de l’étape 3 pour maximiser le gain d’information.</p><h3>Étape 5 : Mise à jour et Itération</h3><p>Enrichissez les données : D_new = D ∪ {(lambda_new, x_new, y_new)}</p><p>Recalibrez le GP : p(f|D_new)</p><p>Retournez à l’étape 3 jusqu’à épuisement du budget.</p><p><strong>Convergence pour notre problème</strong> : À chaque itération, notre modèle de f s’améliore dans les régions échantillonnées, et notre fonction d’acquisition s’adapte pour cibler les zones restantes de haute incertitude ou variance, assurant une couverture optimale de l’espace critique avec notre budget limité.</p><h3>Synthèse : Comment cette perspective unifiée résout notre problème</h3><p>La perspective unifiée entre AL et BO révèle que notre <strong>Méthode 1</strong> (Échantillonnage Adaptatif) de la Part 1 n’est pas une technique isolée, mais s’inscrit dans un cadre théorique riche qui formalise mathématiquement comment :</p><h3>1. Exploiter notre connaissance a priori v(lambda)</h3><p>Les fonctions d’acquisition peuvent intégrer v(lambda) directement, comme dans notre <strong>Méthode 5 (Stratégie Hybride)</strong> : a(lambda, x) = [σ_GP(lambda, x) · √v(lambda)]^β</p><p>Cette intégration garantit que notre échantillonnage initial privilégie naturellement les régions à haute variance connue.</p><h3>2. S’adapter aux complexités découvertes</h3><p>La boucle de rétroaction entre modèle et décision permet de découvrir des régions de f présentant une complexité non anticipée par v(lambda), raffinant continuellement notre stratégie d’échantillonnage.</p><h3>3. Équilibrer exploration et exploitation automatiquement</h3><p>Les fonctions d’acquisition modernes (EI, MES) équilibrent naturellement :</p><ul><li><strong>L’exploitation</strong> de notre connaissance (échantillonner où v(lambda) est élevé ou où μ(lambda, x) est informatif)</li><li><strong>L’exploration</strong> de l’inconnu (échantillonner où σ(lambda, x) est élevé)</li></ul><p>Cet équilibre s’ajuste dynamiquement au fur et à mesure que notre modèle de f s’améliore.</p><h3>4. Maximiser l’efficacité de notre budget limité</h3><p>L’approche multi-fidélité étend notre capacité d’exploration en exploitant des évaluations bon marché de f pour guider les évaluations coûteuses, multipliant effectivement notre budget d’information.</p><h3>5. Garantir la convergence vers les régions critiques</h3><p>Les garanties théoriques (comme la sous-modularité de l’information mutuelle) assurent que notre stratégie d’échantillonnage converge vers une couverture optimale des régions à haute variance/complexité de f, même avec un budget très limité.</p><h3>Conclusion des Trois Parties : Une Vision Complète pour notre Problème</h3><p><strong>Part 1</strong> a présenté cinq méthodes d’échantillonnage adaptatif, identifiant notre problème central : apprendre f(lambda, x1…xn) avec un budget limité, en allouant dynamiquement plus de points aux régions de haute variance ou complexité.</p><p><strong>Part 2</strong> a approfondi les fondements mathématiques de l’<strong>OED (Méthode 4)</strong>, formalisant comment maximiser l’information extraite de chaque évaluation via la théorie de l’information et les critères d’optimalité (D-optimalité, EIG).</p><p><strong>Part 3</strong> a révélé la perspective unifiée entre <strong>AL et BO (Méthode 1)</strong>, montrant que ces approches partagent des principes fondamentaux pour résoudre notre problème : l’apprentissage avec objectif via une boucle d’échange entre modèle et décision.</p><h3>Le Fil Conducteur</h3><p>Ces trois parties convergent vers une conclusion fondamentale : <strong>l’échantillonnage intelligent pour notre problème n’est pas une question de distribution uniforme, mais d’allocation optimale de ressources limitées guidée par l’information</strong>.</p><p>Que ce soit via :</p><ul><li>L’échantillonnage basé sur la variance connue v(lambda) (<strong>Méthode 2</strong>)</li><li>L’échantillonnage basé sur la courbure (<strong>Méthode 3</strong>)</li><li>L’OED avec ses critères d’optimalité (<strong>Méthode 4</strong>)</li><li>L’apprentissage actif et l’optimisation Bayésienne (<strong>Méthode 1</strong>)</li><li>Ou la stratégie hybride combinant connaissance a priori et adaptation (<strong>Méthode 5</strong>)</li></ul><p>Toutes ces approches répondent à la même question fondamentale : <strong>comment échantillonner notre espace au-delà de l’uniformité pour apprendre efficacement f(lambda, x1…xn) dans les régions qui importent le plus ?</strong></p><p>La <strong>Méthode 5 (Stratégie Hybride)</strong> émerge comme la solution optimale pour notre contexte spécifique, car elle :</p><ol><li>Exploite notre connaissance a priori v(lambda) (via <strong>Méthode 2</strong>)</li><li>S’adapte dynamiquement via apprentissage actif (via <strong>Méthode 1</strong>)</li><li>Maximise l’information extraite (principes de <strong>Méthode 4</strong>)</li><li>Découvre les complexités géométriques de f (esprit de <strong>Méthode 3</strong>)</li></ol><p>Cette synthèse unifiée nous donne non seulement une solution pratique, mais une compréhension profonde des principes qui la sous-tendent, nous permettant d’adapter notre stratégie aux spécificités de chaque problème d’apprentissage de fonction avec budget limité.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f2d755e76a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[L’Optimisation de la Conception Expérimentale : Fondements Mathématiques — Part 2]]></title>
            <link>https://medium.com/@ykarray29/loptimisation-de-la-conception-exp%C3%A9rimentale-fondements-math%C3%A9matiques-part-2-497bc95d01cc?source=rss-25b22d7e4148------2</link>
            <guid isPermaLink="false">https://medium.com/p/497bc95d01cc</guid>
            <category><![CDATA[data-sampling]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[sampling]]></category>
            <dc:creator><![CDATA[yasmine karray]]></dc:creator>
            <pubDate>Sat, 01 Nov 2025 10:22:42 GMT</pubDate>
            <atom:updated>2025-11-01T10:22:42.010Z</atom:updated>
            <content:encoded><![CDATA[<h3>L’Optimisation de la Conception Expérimentale : Fondements Mathématiques — Part 2</h3><p><strong>Contexte</strong> : Dans la Part 1, nous avons présenté cinq méthodes d’échantillonnage adaptatif pour notre problème d’apprentissage de fonction f(lambda, x1…xn) avec budget limité. Nous explorons maintenant les fondements théoriques de la <strong>Méthode 4 (OED — Optimal Experimental Design)</strong> telle que formalisée dans la littérature scientifique. La Part 3 complétera cette exploration en examinant les bases théoriques de la <strong>Méthode 1 (Active Learning)</strong>.</p><p><strong>Article de référence</strong> : “Optimal experimental design: Formulations and computations” — Xun Huan, Jayanth Jagalur et Youssef Marzouk</p><p><a href="https://arxiv.org/abs/2407.16212">Optimal experimental design: Formulations and computations</a></p><h3>1. Introduction : Optimiser l’acquisition de données pour notre problème</h3><p>Dans notre contexte d’apprentissage de fonction avec budget limité, l’acquisition de données est particulièrement coûteuse. L’Optimisation de la Conception Expérimentale (OED) formalise mathématiquement comment déterminer, avant même de commencer l’expérience, quels points d’échantillonnage seront les plus informatifs pour notre objectif spécifique.</p><p>L’OED répond directement à notre contrainte principale : comment allouer intelligemment notre budget limité d’évaluations dans les régions où la fonction présente haute variance ou complexité ?</p><p>Tout problème d’OED repose sur deux piliers :</p><ol><li><strong>L’Expérience</strong> : La source de données que nous contrôlons (choix des points lambda, x à évaluer)</li><li><strong>Le Modèle Mathématique</strong> : Le simulateur qui prédit le comportement de notre fonction f(lambda, x1…xn)</li></ol><p>“Questions of ‘how best to acquire data’ are essential to modeling and prediction in the natural and social sciences, engineering applications, and beyond.”</p><h3>2. Formalisation : Qu’est-ce qu’un “bon” design pour notre problème ?</h3><p>Pour notre problème d’apprentissage de fonction, un “bon” design est celui qui maximise l’information obtenue sur f(lambda, x1…xn) étant donné notre budget limité. L’OED formalise cela en utilisant un modèle statistique qui décrit la distribution de probabilité des observations (Y) en fonction des paramètres inconnus (λ) et du design choisi (b).</p><h3>Le Cadre Bayésien appliqué à notre contexte</h3><p>Dans notre problème, les paramètres inconnus de la fonction sont considérés comme des variables aléatoires Θ, auxquelles on attribue une distribution a priori. Après avoir observé les données H aux points échantillonnés, cette distribution est mise à jour pour former la distribution a posteriori (selon la règle de Bayes).</p><p>Cette approche est particulièrement adaptée à notre problème car elle permet d’intégrer notre connaissance a priori v(lambda) de la variance et reste flexible face aux non-linéarités de notre fonction.</p><h3>2.1. Critères Classiques : L’Optimalité Alphabétique</h3><p>Pour notre fonction f(lambda, x1…xn), si nous pouvons l’approximer localement par un modèle linéaire avec des erreurs Gaussiennes, les critères d’optimalité sont basés sur la Matrice d’Information de Fisher I(b).</p><p><strong>Interprétation pour notre problème</strong> : La Matrice de Fisher I mesure la quantité d’information que nos points échantillonnés apportent sur les paramètres de f que nous essayons d’estimer. Une I plus grande signifie généralement que nos estimations seront plus précises dans les régions à haute variance.</p><p>Puisque I est une matrice, nous devons la “scalariser” pour en faire un objectif d’optimisation :</p><ul><li><strong>Optimalité A</strong> : min tr(I⁻¹(b)) — Minimise la variance moyenne des paramètres estimés dans notre fonction</li><li><strong>Optimalité D</strong> : min log det(I⁻¹(b)) — Minimise le volume de l’ellipsoïde de confiance.</li><li><strong>Optimalité E</strong> : Minimise la valeur propre maximale de I⁻¹(b) — Garantit que la variance d’estimation dans la direction la moins bien estimée est minimisée</li></ul><p>Dans le contexte bayésien, ces critères utilisent la matrice de covariance a posteriori Γ_Θ|·(b). Par exemple, l’Optimalité D Bayésienne minimise log det(Γ_Θ|·(b)), maximisant ainsi l’information extraite de chaque évaluation de notre fonction coûteuse.</p><h3>3. Critères Avancés : Information et Décision pour notre contexte</h3><p>Pour notre fonction f(lambda, x1…xn) qui peut être hautement non-linéaire dans certaines régions, les critères basés sur la Matrice de Fisher seule deviennent insuffisants. L’approche la plus adaptée à notre problème est la théorie de la décision.</p><h3>3.1. L’Utilité Attendue pour notre budget limité</h3><p>L’OED consiste à trouver le design b* qui maximise l’Utilité Attendue U(b) : U(b) = E_Y,Θ|b[D(b,Y,Θ)]</p><p><strong>Application à notre problème</strong> : L’utilité D quantifie la valeur de chaque évaluation de f(lambda, x) si nous connaissions les vrais paramètres Θ et observions Y. Comme nous prenons la décision avant l’évaluation, nous faisons la moyenne sur toutes les observations Y possibles et tous les paramètres Θ probables, en tenant compte de notre connaissance a priori v(lambda).</p><h3>3.2. Le Gain d’Information Attendu (EIG) : critère optimal pour notre problème</h3><p>Le critère d’utilité le plus adapté à notre contexte d’apprentissage de fonction est le Gain d’Information Attendu (EIG).</p><p><strong>Application directe</strong> : L’EIG mesure à quel point chaque évaluation de f(lambda, x) va réduire notre incertitude. Il s’agit du gain attendu en information de Shannon (Divergence de Kullback–Leibler, D_KL) entre notre distribution a priori et la distribution a posteriori après avoir échantillonné un nouveau point.</p><p>L’EIG est équivalent à l’Information Mutuelle I(Y;Θ|b) entre les paramètres Θ de notre fonction et les observations Y, étant donné le design b.</p><p><strong>Propriété cruciale pour notre problème</strong> : L’EIG est invariant sous les transformations bijectives des paramètres Θ, garantissant que notre design optimal ne change pas si nous re-scalons nos variables.</p><h3>3.3. OED Orientée vers notre objectif d’apprentissage</h3><p>Dans notre problème, l’intérêt ne porte pas nécessairement sur tous les paramètres Θ de la fonction, mais peut se concentrer sur certaines régions de l’espace (lambda, x) où la variance est élevée. On maximise alors l’EIG pour cette quantité d’intérêt spécifique.</p><p><strong>Application pratique</strong> : Si notre objectif est de bien prédire f dans les régions à haute variance v(lambda), nous maximisons I(Y;Θ₁|b) où Θ₁ représente les paramètres influençant ces régions critiques. Ce critère nous guide naturellement vers l’échantillonnage des zones les plus incertaines, aligné avec notre stratégie générale de la Part 1.</p><h3>4. Défis Computationnels : Évaluer l’EIG pour notre fonction</h3><p>L’évaluation de l’EIG/MI est l’un des principaux défis pour notre problème d’apprentissage de fonction, car elle implique un ratio de densités sous une attente extérieure :</p><p>I(Y;Θ|b) = E_Y,Θ|b[log p(Y|Θ,b)/p(Y|b)]</p><h3>4.1. Estimateurs Monte Carlo Emboîtés (NMC)</h3><p>La méthode standard repose sur les Estimateurs Monte Carlo Emboîtés (NMC), mais présente un défi majeur pour notre problème.</p><p><strong>Le Problème du Biais</strong> : L’estimateur NMC est biaisé positivement pour un nombre fini d’échantillons. Plus critique encore, la convergence du taux d’erreur est plus lente que Monte Carlo standard : O(N^(-2/3)). Ce biais peut masquer la vraie localisation du design optimal dans notre espace (lambda, x), car le biais varie en fonction du design b.</p><h3>4.2. Bornes Variationnelles : solution moderne pour notre contexte</h3><p>Une alternative plus efficace pour notre problème consiste à construire des bornes variationnelles qui encadrent l’EIG. Ces méthodes approximent les densités complexes de notre fonction à l’aide de familles de distributions plus simples (q).</p><p><strong>Encadrement par Approximation de Densité pour notre fonction</strong> :</p><ol><li><strong>Borne Supérieure</strong> : Si nous remplaçons la vraie densité marginale p(Y|b) par une approximation q_mar(Y|b), nous obtenons une borne supérieure à l’EIG.</li><li><strong>Borne Inférieure (Barber–Agakov)</strong> : Si nous remplaçons la vraie densité a posteriori p(Θ|Y,b) par une approximation q_pos(Θ|Y,b), nous obtenons une borne inférieure à l’EIG.</li></ol><p><strong>Avantage pour les Modèles Complexes</strong> : Si notre fonction f est implicite (nous pouvons simuler des évaluations mais la vraisemblance p(Y|λ,b) est difficile à calculer), l’estimation de la borne inférieure reste possible.</p><p>Pour rendre ces bornes “étroites” dans notre contexte, on utilise des flux normalisants (Normalizing Flows) ou des cartes de transport. Ces outils paramètrent des transformations inversibles complexes pour modéliser la distribution de notre fonction, permettant d’optimiser l’approximation de densité. L’objectif est de s’assurer que l’approximation q capture fidèlement le comportement complexe de f(lambda, x) dans les régions à haute variance.</p><h3>5. Optimisation des Designs : trouver les meilleurs points pour notre fonction</h3><p>Une fois le critère d’optimalité choisi, il faut trouver le design b* qui le maximise dans notre espace (lambda, x1…xn). La stratégie dépend de la nature de nos variables de design.</p><h3>5.1. Variables Discrètes : choisir parmi un ensemble fini de points</h3><p>Lorsque notre design consiste à choisir un sous-ensemble de m évaluations parmi N emplacements possibles dans l’espace (lambda, x), le problème est combinatoire.</p><p><strong>Algorithmes d’Échange</strong> : Des méthodes comme l’algorithme d’échange de Fedorov améliorent itérativement le design en échangeant des points (un point est retiré d’une région triviale et un autre est ajouté dans une région à haute variance).</p><p><strong>Heuristique Gloutonne (Greedy)</strong> : Pour notre critère EIG/MI qui est souvent sous-modulaire dans les régions à évaluer, l’approche gloutonne (choisir à chaque étape le point qui apporte le plus grand gain incrémentiel d’information) fonctionne bien. L’heuristique gloutonne offre une garantie d’approximation théorique de 1–1/e par rapport à l’optimum.</p><h3>5.2. Variables Continues : optimisation dans l’espace (lambda, x)</h3><p>Lorsque nos variables de design sont continues (coordonnées lambda, valeurs x), le problème est une optimisation stochastique.</p><p><strong>Méthodes Basées sur le Gradient (Robbins–Monro)</strong> : Ces méthodes nécessitent un estimateur du gradient non biaisé. L’algorithme de Robbins–Monro permet de trouver le design optimal dans notre espace continu en mettant à jour b de manière itérative.</p><p><strong>Défis de l’EIG Biassé pour notre problème</strong> : Si l’estimateur de l’EIG est biaisé (comme le NMC), appliquer un algorithme basé sur le gradient nous mènera à un maximum du critère biassé, qui peut placer des points loin des vraies régions à haute variance de notre fonction.</p><p><strong>Optimisation Simultanée</strong> : Une stratégie intelligente pour notre contexte consiste à maximiser simultanément le design b et les paramètres variationnels ξ : max_(b,ξ) L(ξ,b). Cette approche cherche les meilleurs points d’échantillonnage tout en s’assurant que la borne inférieure capture fidèlement le comportement de f.</p><h3>6. Perspectives pour notre problème d’apprentissage</h3><p>L’OED pour notre problème d’apprentissage de fonction f(lambda, x1…xn) fait face à plusieurs défis fondamentaux.</p><h3>6.1. Mauvaise Spécification du Modèle</h3><p>Notre modèle de f est nécessairement imparfait. Un design optimal selon un modèle donné peut être sous-optimal si le modèle ne capture pas toute la complexité de f dans certaines régions.</p><p><strong>Solutions pour notre contexte</strong> :</p><ul><li><strong>Modèles Augmentés</strong> : Augmenter le modèle avec des paramètres de nuisance pour capturer l’erreur de modélisation dans f.</li><li><strong>OED Robuste</strong> : Chercher le design qui maximise l’information mutuelle dans le pire des cas, garantissant de bonnes performances même si notre modèle de f est imparfait.</li></ul><h3>6.2. Critères Sensibles au Risque pour notre budget limité</h3><p>L’OED traditionnelle se concentre sur l’espérance de l’utilité. Le design sensible au risque quantifie et contrôle la probabilité d’un mauvais résultat expérimental (faible gain d’information pour notre budget limité).</p><p><strong>R-Optimalité et CVaR</strong> : Cette approche utilise la Valeur à Risque Conditionnelle (CVaR) pour notre problème. Elle minimise la CVaR de la variance de prédiction de f sur le domaine (lambda, x), garantissant que même dans le pire des cas, notre échantillonnage capture les régions critiques.</p><p>Cette Part 2 a approfondi les fondements mathématiques de la <strong>Méthode 4 (OED)</strong> présentée en Part 1. Ces concepts formalisent rigoureusement comment maximiser l’information extraite de chaque évaluation de notre fonction coûteuse. La <strong>Part 3</strong> complétera cette exploration en examinant comment l’<strong>Apprentissage Actif et l’Optimisation Bayésienne (Méthode 1 de la Part 1)</strong> partagent des principes fondamentaux similaires, offrant une perspective unifiée pour résoudre notre problème d’échantillonnage intelligent.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=497bc95d01cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comment échantillonner notre espace : Au-delà de l’uniformité — Part 1]]></title>
            <link>https://medium.com/@ykarray29/comment-%C3%A9chantillonner-notre-espace-au-del%C3%A0-de-luniformit%C3%A9-part-1-cb9a1dd18e71?source=rss-25b22d7e4148------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb9a1dd18e71</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[sampling]]></category>
            <category><![CDATA[sample]]></category>
            <dc:creator><![CDATA[yasmine karray]]></dc:creator>
            <pubDate>Sat, 01 Nov 2025 10:20:56 GMT</pubDate>
            <atom:updated>2025-11-01T10:20:56.702Z</atom:updated>
            <content:encoded><![CDATA[<h3>Comment échantillonner notre espace : Au-delà de l’uniformité — Part 1</h3><p>La plupart du temps, on a tendance à qualifier une base de données d’équilibrée si l’on observe le même nombre N de variables (ou d’échantillons) pour chaque group ou classe. Cependant, bien que cette uniformité puisse être adéquate dans certains cas, elle n’est pas toujours la stratégie la plus judicieuse.</p><p>C’est comparable au fait de donner exactement la même chose à deux enfants : cela ne garantit pas l’égalité ou l’équité, car il faut parfois prendre en considération les besoins spécifiques ou la compétence de chacun. De même, pour les données, avoir un nombre d’échantillons uniforme (une distribution uniforme) pour tout l’espace n’est pas la solution la plus intelligente. En effet, certaines zones sont intrinsèquement plus complexes ou plus incertaines que d’autres, et il peut être inutile de former un modèle complet avec une densité d’échantillonnage élevée dans des régions triviales.</p><p>J’aurais tendance à dire qu’une distribution uniforme pourrait être une bonne solution pour les espaces discrets simples, mais qu’elle devient moins pertinente pour les espaces continus. Il est évident que même dans les espaces discrets, une approche plus fine peut être nécessaire.</p><p>Pour identifier la manière la plus adéquate d’échantillonner notre base de données, nous sommes amenés à utiliser différentes techniques, chacune étant adaptée à des contextes spécifiques (une connaissance des statistiques paramétriques, non-paramétriques, et de l’analyse numérique permet une meilleure compréhension).</p><h3>Objectif et Contrainte</h3><p><strong>Objectif</strong> : Apprendre une fonction f(lambda, x1…xn) avec un budget limité d’évaluations (échantillons).</p><p><strong>Contrainte</strong> : La fonction est difficile à prédire (haute variance ou complexité) dans certaines plages de lambda et facile (faible variance) dans d’autres.</p><p><strong>Stratégie Générale</strong> : Allouer dynamiquement plus de points d’échantillonnage aux régions où l’incertitude ou la complexité de la fonction est la plus élevée.</p><h3>Méthode 1 : Échantillonnage Adaptatif (Active Learning)</h3><p>Cette méthode repose sur un processus itératif de rétroaction entre un modèle statistique et une fonction d’acquisition.</p><p><strong>Initialisation</strong> : On commence avec un petit ensemble de données initial D₀ = {(lambda₁, x₁, y₁), …, (lambdaₙ, xₙ, yₙ)} obtenu par un plan d’expériences classique.</p><p><strong>Modélisation</strong> : On entraîne un modèle de régression non-paramétrique, très souvent un Processus Gaussien (GP), sur D₀. Le GP fournit une distribution prédictive postérieure pour tout nouveau point (lambda*, x*) : une moyenne μ(lambda*, x*) et une variance σ²(lambda*, x*) (mesure de l’incertitude).</p><p><strong>Optimisation de la Fonction d’Acquisition a(lambda, x)</strong> : On définit une fonction qui quantifie l’utilité de l’échantillonnage au point (lambda, x). Les choix classiques sont :</p><ul><li><strong>Maximisation de l’Incertitude</strong> : a(lambda, x) = σ(lambda, x). On explore là où le modèle est le plus incertain.</li><li><strong>Amélioration Espérée (EI)</strong> : a(lambda, x) = E[max(0, f(lambda, x) — fₚ)], où fₚ est la meilleure valeur observée. Idéal pour l’optimisation globale.</li><li><strong>Réduction de Variance Intégrée (IVR)</strong> : a(lambda, x) est la réduction attendue de la variance intégrée du modèle si l’on échantillonne en (lambda, x). C’est le critère le plus axé sur l’apprentissage pur (pure learning).</li></ul><p><strong>Sélection et Évaluation</strong> : On trouve le point (lambdaₙ₊₁, xₙ₊₁) qui maximise a(lambda, x). On évalue la fonction coûteuse yₙ₊₁ = f(lambdaₙ₊₁, xₙ₊₁) et on met à jour l’ensemble : Dₙ₊₁ = Dₙ ∪ {(lambdaₙ₊₁, xₙ₊₁, yₙ₊₁)}.</p><p><strong>Itération</strong> : On répète les étapes 2 à 4 jusqu’à épuisement du budget.</p><p>✅ <strong>Quand l’utiliser ?</strong> Quand la fonction est une “boîte noire” coûteuse, que son comportement est inconnu a priori et que le coût computationnel de la boucle d’optimisation est tolérable.</p><h3>Méthode 2 : Échantillonnage Basé sur la Variance Connue (Non-Adaptatif)</h3><p>Cette méthode utilise une connaissance a priori de la variabilité pour définir un plan d’échantillonnage fixe.</p><p><strong>Discrétisation</strong> : On discrétise l’espace des lambda en une grille fine {lambda₁, lambda₂, …, lambdaₘ}.</p><p><strong>Pondération</strong> : On calcule les poids wᵢ = √v(lambdaᵢ) pour chaque point de la grille, où v(lambdaᵢ) est la variance connue à ce point.</p><p><strong>Normalisation</strong> : On normalise pour obtenir une distribution de probabilité : pᵢ = wᵢ / Σwⱼ.</p><p><strong>Échantillonnage Stratifié</strong> : On utilise l’échantillonnage stratifié pour générer N points. On calcule la Fonction de Répartition (CDF) P(lambda), on prend N quantiles régulièrement espacés qₖ = (k — 0.5)/N, puis on inverse la CDF pour obtenir les échantillons lambdaₖ = P⁻¹(qₖ). Ceci garantit une couverture uniforme de l’espace de probabilité et est préférable à un tirage aléatoire simple (Monte Carlo).</p><p>✅ <strong>Quand l’utiliser ?</strong> Lorsque la variance v(lambda) est connue de manière fiable dans notre problème et qu’un plan d’échantillonnage fixe et prédéterminé est requis.</p><h3>Méthode 3 : Échantillonnage Basé sur la Courbure (Gradient/Hessien) 📈</h3><p><strong>Mesure de la Complexité</strong> : La courbure d’une fonction f(lambda) en un point est capturée par sa dérivée seconde f’’(lambda) (ou le Hessien dans le cas multivariable). Une valeur absolue élevée de |f’’(lambda)| indique un changement rapide de la pente, typique des pics, des vallées et des points d’inflexion. Ces régions sont difficiles à approximer.</p><p><strong>Processus</strong> :</p><ul><li><strong>Campagne Pilote</strong> : On effectue une campagne pilote avec un échantillonnage uniforme ou à faible résolution pour obtenir une estimation initiale de la fonction, f̂(lambda).</li><li><strong>Estimation de la Dérivée Seconde</strong> : Différences Finies sur les données discrètes (moins robuste au bruit), Lissage par Splines (fournit directement une estimation lisse de f’’(lambda)), ou Processus Gaussien (si un GP est utilisé pour le pilote, la dérivée d’un GP est également un GP, fournissant une estimation probabiliste de f’’(lambda)).</li><li><strong>Densité d’Échantillonnage</strong> : On définit la densité d’échantillonnage comme p(lambda) ∝ |f’’(lambda)|^α. Le paramètre α (souvent 0.5 ou 1) contrôle la sensibilité à la courbure.</li><li><strong>Échantillonnage</strong> : On procède à un échantillonnage stratifié comme dans la Méthode 2, mais en utilisant |f’’(lambda)| comme poids.</li></ul><p>✅ <strong>Quand l’utiliser ?</strong> Lorsque notre fonction est déterministe, lisse, et que ses difficultés proviennent principalement de sa non-linéarité intrinsèque (forte courbure).</p><h3>Méthode 4 : Conception d’Expériences Optimale (Optimal Experimental Design — OED) 📐</h3><p>L’OED vise à sélectionner des points de mesure pour maximiser l’information sur les paramètres θ d’un modèle spécifique.</p><p><strong>Définir le Modèle Paramétrique</strong> : Vous devez avoir une forme fonctionnelle spécifique : f(lambda, x; θ).</p><p>Exemple : f(lambda, θ) = θ₀ + θ₁·lambda + θ₂·lambda² (modèle polynomial).</p><p>Important : Les paramètres θ doivent avoir une signification physique ou interprétable.</p><p><strong>Calculer les Dérivées Partielles (Sensibilités)</strong> : Pour chaque point candidat, calculez le vecteur gradient s(lambda, x, θ) = ∇_θ f. Ce vecteur de sensibilité indique “dans quelle direction” l’information pointe.</p><p><strong>Construire la Matrice d’Information de Fisher (FIM)</strong> : Pour un ensemble de points de mesure {xₖ}, la FIM est : FIM(i,j) = (1/σ²) · Σₖ [∂f/∂θᵢ · ∂f/∂θⱼ]. C’est la somme des produits externes des vecteurs de sensibilité.</p><p><strong>Optimisation Combinatoire (Critères d’Optimalité)</strong> : Le vrai défi est de trouver les N points qui maximisent un critère scalaire de la FIM :</p><ul><li><strong>D-optimalité</strong> : Maximiser log det(FIM(θ)). Minimise le volume de l’ellipsoïde de confiance conjoint des paramètres (le plus courant).</li><li><strong>A-optimalité</strong> : Minimiser trace(FIM⁻¹(θ)). Minimise la variance moyenne des paramètres.</li><li><strong>E-optimalité</strong> : Maximiser la plus petite valeur propre de FIM(θ). Améliore la robustesse.</li></ul><p>✅ <strong>Quand l’utiliser ?</strong> Lorsque l’objectif principal est l’estimation précise des paramètres d’un modèle scientifique ou d’ingénierie bien défini dans notre contexte spécifique.</p><h3>Méthode 5 : La Stratégie Hybride du Général 🌐</h3><p>Cette stratégie combine la robustesse d’un plan a priori avec la flexibilité et l’efficacité de l’apprentissage actif.</p><p><strong>Phase 1 : Échantillonnage Pilote Basé sur la Variance (Méthode 2)</strong></p><p>On utilise la connaissance a priori v(lambda) pour générer un premier ensemble de N₁ points {lambda₁, …, lambdaN₁} via un échantillonnage stratifié avec p(lambda) ∝ √v(lambda). Pour chaque lambdaᵢ sélectionné, on échantillonne les autres variables x selon un plan d’échantillonnage à remplissage d’espace (LHS) pour obtenir un ensemble de points (lambdaᵢ, xᵢⱼ). On évalue la fonction sur tous ces points pour constituer l’ensemble de données initial Dpilote.</p><p><strong>Phase 2 : Raffinement par Apprentissage Actif (Méthode 1)</strong></p><p>On entraîne un Processus Gaussien (GP) sur Dpilote. Ce GP modélise f(lambda, x) dans tout l’espace. On définit une fonction d’acquisition hybride qui intègre à la fois l’incertitude du modèle (σGP) et la connaissance a priori (v(lambda)).</p><p>Par exemple : a(lambda, x) = [σGP(lambda, x) · √v(lambda)]^β.</p><p>Le paramètre β permet de contrôler l’importance relative de l’information a priori. On lance la boucle d’Active Learning standard : trouver le point qui maximise a(lambda, x), l’évaluer, mettre à jour le GP, et itérer jusqu’à épuisement du budget total N.</p><p>✅ <strong>Pourquoi c’est la meilleure pour notre problème ?</strong> Parce que nous disposons déjà d’une information a priori cruciale (v(lambda)). Cette stratégie l’exploite pleinement pour éviter un démarrage à l’aveugle de l’Active Learning, ce qui accélère considérablement la convergence. Ensuite, l’étape adaptative permet de corriger les imprécisions de notre connaissance a priori et de découvrir des complexités non capturées par v(lambda). C’est l’alliance parfaite de la théorie et de l’adaptation aux données pour notre contexte spécifique.</p><h3>Pour aller plus loin : Exploration des fondements théoriques</h3><p>Dans cette première partie, nous avons présenté cinq méthodes d’échantillonnage adaptatif, en nous concentrant particulièrement sur leur application à notre problème d’apprentissage de fonction avec budget limité. Les <strong>Méthodes 1 (Échantillonnage Adaptatif) et 4 (OED)</strong> que nous avons introduites reposent sur des fondements théoriques riches et des développements récents en optimisation Bayésienne et apprentissage actif.</p><p>Dans les <strong>Part 2 et Part 3</strong>, nous explorerons ce que dit la littérature scientifique sur ces approches :</p><ul><li><strong>Part 2</strong> approfondira les fondements mathématiques de la <strong>Méthode 4 (OED — Optimal Experimental Design)</strong>, en explorant comment la théorie de l’information et la conception d’expériences optimale permettent de maximiser l’information extraite de chaque mesure.</li><li><strong>Part 3</strong> examinera la perspective unifiée entre l’<strong>Apprentissage Actif et l’Optimisation Bayésienne (Méthode 1)</strong>, révélant comment ces deux approches, bien que développées dans des contextes différents, partagent des principes fondamentaux communs pour résoudre notre problème d’échantillonnage intelligent.</li></ul><p>Ces deux parties complémentaires vous permettront de comprendre les bases théoriques qui justifient l’efficacité de ces méthodes pour notre problème spécifique.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb9a1dd18e71" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>