<?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 Falonne KPAMEGAN on Medium]]></title>
        <description><![CDATA[Stories by Falonne KPAMEGAN on Medium]]></description>
        <link>https://medium.com/@falonnekpamegan?source=rss-cdb3d440a1ab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6BzMzeX99hbAkGMkNlQuaQ.png</url>
            <title>Stories by Falonne KPAMEGAN on Medium</title>
            <link>https://medium.com/@falonnekpamegan?source=rss-cdb3d440a1ab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:46:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@falonnekpamegan/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[How to connect custom Agents to MCP Servers using LangGraph]]></title>
            <link>https://medium.com/@falonnekpamegan/how-to-connect-custom-agents-to-mcp-servers-using-langgraph-dc5417ac6f28?source=rss-cdb3d440a1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc5417ac6f28</guid>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[datagouv]]></category>
            <dc:creator><![CDATA[Falonne KPAMEGAN]]></dc:creator>
            <pubDate>Tue, 12 May 2026 07:36:11 GMT</pubDate>
            <atom:updated>2026-05-12T07:36:11.225Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Isolated Models to Context-Aware Agents</h3><p>The biggest limitation of modern Large Language Models (LLMs) isn’t their reasoning capability : it’s their <strong>isolation</strong>. Out of the box, an LLM is a “brain in a jar,” brilliant but cut off from your local files, your company’s Slack, or your private databases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2L9aMtweCXWEzMxqnldtg.png" /></figure><p>The <strong>Model Context Protocol (MCP)</strong> changes the game. By introducing an open, universal standard for how AI models interact with data sources and tools, it allows us to build agents that are truly context-aware. But to make these agents reliable and capable of complex logic, you need more than just a connection — you need a brain that can plan and execute.</p><p>In this guide, we’ll use <a href="https://github.com/datagouv/datagouv-mcp">DataGouv MCP</a>, a server that allows AI chatbots (Claude, ChatGPT, Gemini, etc.) to search, explore, and analyze datasets from <a href="https://www.data.gouv.fr/">data.gouv.fr</a>, the French national Open Data platform.</p><p>First, to understand MCP, think about a USB plug, a universal key that can be connected to any machine. That is exactly the concept of MCP: instead of every “store” (Google Drive, Slack, GitHub, or <strong>data.gouv.fr</strong>) having its own complicated entrance, they all now use the same type of “plug.”</p><h4>MCP three pillars</h4><ul><li><strong>Host:</strong> The application your user interacts with directly. Think of it as the “front desk” of the whole system. It could be a chat interface, an IDE like Cursor, or your custom LangGraph agent. The Host is responsible for starting connections and deciding which MCP Servers to talk to.</li><li><strong>Client:</strong> The invisible diplomat living inside the Host. It speaks the MCP language fluently and handles all the back-and-forth communication with the Server on the Host’s behalf. One Host can manage multiple Clients, each connected to a different Server.</li><li><strong>Server:</strong> The specialist. It exposes a specific capability like searching datasets on <strong><em>data.gouv.fr,</em></strong> reading your Google Drive, querying a databasethrough a standardized interface. The Server doesn’t care who’s calling; as long as the request follows the MCP protocol, it responds.</li></ul><p>In our case LangGraph Agent<strong>= Host</strong>, the mcp Python library = <strong>Client</strong>, and mcp.data.gouv.fr = <strong>Server</strong>.</p><h4>MCP primitives : what a Server can expose</h4><ul><li><strong><em>tools</em></strong> : <strong>Actions</strong> the agent can <em>execute</em>. These are the “verbs”: search, query, send, fetch. In <strong><em>data.gouv.fr </em></strong>server, search_datasets and query_resource_data are tools. The LLM decides <em>when</em> to call them, but <em>you, </em>through your <strong>system prompt</strong>, define the rules, the order, and the conditions under which they should be used.</li><li><strong><em>resources</em></strong> : <strong>Data</strong> the agent can <em>read</em>, like files, database records, or API responses. Think of them as “nouns”, static or dynamic content the Server makes available without the agent having to trigger an action.</li><li><strong><em>prompts</em></strong> : <strong>Pre-built instruction</strong> templates exposed by the Server. They let the Server suggest <em>how</em> to use its own tools effectively. Less common in practice, but useful when a Server wants to guide agent behavior.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITT_sbTDy-g73mwxj6G1-w.png" /></figure><h4>The Technical Backbone: How MCP Communicates (Data layer protocol and transport layer)</h4><p>MCP uses <strong>JSON-RPC 2.0</strong> as its messaging format. It’s a simple, stateless protocol that allows the Client and Server to send “requests” and “notifications” to each other.</p><p>MCP is “transport agnostic,” meaning it can travel over different types of “pipes.” The two most common are:</p><ul><li><strong>Stdio</strong> (Standard Input/Output): best for local development. The host starts the MCP server as a child process. They talk to each other through the same channel your terminal uses. It’s incredibly fast and requires zero network configuration.</li><li><strong>HTTP (with Server-Sent Events </strong>alias<strong> SSE): </strong>best for cloud-based or remote servers. This is what we use for <strong>data.gouv.fr</strong>. The client sends requests via POST to the server, and the server streams updates back to the client using <strong>SSE</strong>. This keeps the connection open and efficient without the complexity of WebSockets.</li></ul><p>You can read the <a href="https://modelcontextprotocol.io/docs/learn/architecture">official doc</a> if you want to go further.</p><p>As you understand how an MCP works, let’s dive in the code.</p><pre># copy and paste in your terminal<br>pip install mcp langchain-mcp-adapters langchain-google-genai langgraph python-dotenv</pre><pre>import asyncio<br>import logging<br>from dotenv import load_dotenv<br>from mcp import ClientSession<br>from mcp.client.streamable_http import streamable_http_client<br>from langchain_mcp_adapters.tools import load_mcp_tools<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langgraph.prebuilt import create_react_agent<br><br># Config logging<br>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(__name__)<br><br># Loading Environment variables<br>load_dotenv()<br><br># MCP URL (Transport: Streamable HTTP)<br>MCP_URL = &quot;https://mcp.data.gouv.fr/mcp&quot;<br><br># Add your API key in .env file. You can get one here: https://aistudio.google.com/api-keys<br># GOOGLE_API_KEY=your_api_key<br><br><br>async def main():<br>    logger.info(f&quot;Connexion au serveur MCP : {MCP_URL}&quot;)<br>    <br>    try:<br>        # Utilisation de streamable_http_client avec déballage des 3 valeurs (read, write, session_id_getter)<br>        async with streamable_http_client(MCP_URL) as (read, write, _):<br>            async with ClientSession(read, write) as session:<br>                # Initialization of the MCP session<br>                await session.initialize()<br>                <br>                # Conversion MCP tools into LangChain tools<br>                tools = await load_mcp_tools(session)<br>                # logger.info(f&quot;✅ {len(tools)} outils chargés : {[t.name for t in tools]}&quot;)<br>                print(f&quot;\n\n\n ===========&gt;  {len(tools)} tools available: {[t.name for t in tools]}\n\n\n&quot;)<br></pre><p>Note that http_client(MCP_URL) open a http tunnel to <strong>data.gouv.fr</strong> server, session.initialize()is the “handshake”, the agent says “hello” to the server and they agree on the protocol to use and load_mcp_tools(session) retrieve the list of available tools.</p><p>Datagouv MCP offers a lot of tools, but only three (03) will be used in this article:</p><p>search_datasets: Search by keyword (e.g., &quot;écoles&quot;, &quot;budget&quot;) and return a dataset ID.</p><p>get_dataset_info: Retrieve metadata for a specific dataset.</p><p>query_resource_data: The &quot;magic&quot; tool. It allows the agent to query CSV/Excel data directly via the Tabular API without downloading the whole file.</p><p>With your custom agent, you can use tools strategically through a strong prompt.</p><p>A custom agent is only as good as its instructions. In our LangGraph setup, we don’t just give the agent tools; we give it a <strong>methodology</strong>. For the <strong>data.gouv.fr</strong> agent, we use a <strong>“Funnel Method” (<em>Méthode en entonnoir</em> </strong>in french<strong>)</strong>. This ensures the agent doesn’t get lost in the 50,000+ datasets available. It forces a logical progression.</p><pre># This is the &#39;Brain&#39; of your custom agent<br>SYSTEM_PROMPT = &quot;&quot;&quot;<br>Tu es un expert Data Analyst spécialisé sur Data.gouv.fr.<br>Règle absolue : suis STRICTEMENT cette méthode en entonnoir :<br><br>1. DÉCOUVERTE : Recherche des datasets avec &#39;search_datasets&#39;. Trouve l&#39;ID le plus pertinent.<br>2. EXPLORATION : Utilise &#39;get_dataset_info&#39; avec cet ID pour identifier les fichiers disponibles.<br>3. EXTRACTION : Utilise &#39;query_resource_data&#39; sur les fichiers CSV/JSON pour obtenir les vraies données.<br>4. FINALISATION : Ne retourne jamais de métadonnées. Retourne toujours une réponse factuelle avec des chiffres.<br>&quot;&quot;&quot;<br><br># Initialization of the Gemini 2.5 Flash model<br>model = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)<br><br># Creation of the ReAct agent with LangGraph (argument &#39;prompt&#39; for the system)<br>agent = create_react_agent(model, tools=tools, prompt=SYSTEM_PROMPT)<br><br>query = &quot;Combien y a-t-il d&#39;écoles primaires en France ?&quot;<br>logger.info(f&quot;Question : {query}&quot;)</pre><p><strong>Why French?</strong> data.gouv.fr indexes datasets with French keywords. Searching <strong>“écoles”</strong> will return far more relevant results than <strong>“schools”</strong>, your agent needs to think in the same language as the data.</p><pre># Invocation of the agent<br>response = await agent.ainvoke({<br>    &quot;messages&quot;: [(&quot;user&quot;, query)]<br>})<br><br># Displaying the final result (extracting only the text)<br>final_message = response[&quot;messages&quot;][-1]<br>final_text = final_message.content<br><br>if isinstance(final_text, list):<br>    # If it&#39;s a list of blocks (Gemini format), merge the text parts<br>    final_text = &quot;&quot;.join([block.get(&quot;text&quot;, &quot;&quot;) for block in final_text if isinstance(block, dict) and block.get(&quot;type&quot;) == &quot;text&quot;])<br><br>print(&quot;\n&quot; + &quot;=&quot;*50)<br>print(&quot;FINAL RESPONSE :&quot;)<br>print(final_text)<br>print(&quot;=&quot;*50 + &quot;\n&quot;)</pre><p><strong>What happens under the hood?</strong> The agent doesn’t answer immediately. It goes through multiple steps exactly like a junior analyst you’d ask to find a number: they search, open files, cross-check, then come back with the answer. Here is an execution in my terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z6DgdW72gDLnN0Uy6vAIUQ.png" /></figure><p>Here is the full code :</p><pre>import asyncio<br>import logging<br>from dotenv import load_dotenv<br>from mcp import ClientSession<br>from mcp.client.streamable_http import streamable_http_client<br>from langchain_mcp_adapters.tools import load_mcp_tools<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langgraph.prebuilt import create_react_agent<br><br># Config logging<br>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(__name__)<br><br># Loading Environment variables<br>load_dotenv()<br><br># MCP URL (Transport: Streamable HTTP)<br>MCP_URL = &quot;https://mcp.data.gouv.fr/mcp&quot;<br><br># Add your API key in .env file. You can get one here: https://aistudio.google.com/api-keys<br># GOOGLE_API_KEY=your_api_key<br><br>SYSTEM_PROMPT = &quot;&quot;&quot;<br>Tu es un expert Data Analyst spécialisé sur Data.gouv.fr.<br>Règle absolue : suis STRICTEMENT cette méthode en entonnoir :<br><br>1. DÉCOUVERTE : Recherche des datasets avec &#39;search_datasets&#39;. Trouve l&#39;ID le plus pertinent.<br>2. EXPLORATION : Utilise &#39;get_dataset_info&#39; avec cet ID pour identifier les fichiers disponibles.<br>3. EXTRACTION : Utilise &#39;query_resource_data&#39; sur les fichiers CSV/JSON pour obtenir les vraies données.<br>4. FINALISATION : Ne retourne jamais de métadonnées. Retourne toujours une réponse factuelle avec des chiffres.<br>&quot;&quot;&quot;<br><br>async def main():<br>    logger.info(f&quot;Connexion au serveur MCP : {MCP_URL}&quot;)<br>    <br>    try:<br>        # Utilisation de streamable_http_client avec déballage des 3 valeurs (read, write, session_id_getter)<br>        async with streamable_http_client(MCP_URL) as (read, write, _):<br>            async with ClientSession(read, write) as session:<br>                # Initialization of the MCP session<br>                await session.initialize()<br>                <br>                # Conversion MCP tools into LangChain tools<br>                tools = await load_mcp_tools(session)<br>                print(f&quot;\n\n\n ===========&gt;  {len(tools)} tools available: {[t.name for t in tools]}\n\n\n&quot;)<br><br>                # Initialization of the Gemini 2.5 Flash model<br>                model = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)<br>                <br>                # Creation of the ReAct agent with LangGraph (argument &#39;prompt&#39; for the system)<br>                agent = create_react_agent(model, tools=tools, prompt=SYSTEM_PROMPT)<br><br>                query = &quot;Combien y a-t-il d&#39;écoles primaires en France ?&quot;<br>                logger.info(f&quot;Question : {query}&quot;)<br>                <br>                # Invocation of the agent<br>                response = await agent.ainvoke({<br>                    &quot;messages&quot;: [(&quot;user&quot;, query)]<br>                })<br><br>                # Displaying the final result (extracting only the text)<br>                final_message = response[&quot;messages&quot;][-1]<br>                final_text = final_message.content<br>                <br>                if isinstance(final_text, list):<br>                    # If it&#39;s a list of blocks (Gemini format), merge the text parts<br>                    final_text = &quot;&quot;.join([block.get(&quot;text&quot;, &quot;&quot;) for block in final_text if isinstance(block, dict) and block.get(&quot;type&quot;) == &quot;text&quot;])<br><br>                print(&quot;\n&quot; + &quot;=&quot;*50)<br>                print(&quot;FINAL RESPONSE :&quot;)<br>                print(final_text)<br>                print(&quot;=&quot;*50 + &quot;\n&quot;)<br>                <br>    except Exception:<br>        logger.exception(&quot;Error during execution&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><p>I built this agent while working on a larger Research Agent project. What struck me wasn’t the technical complexity, it was how little code it took to go from “<strong>isolated LLM</strong>” to <strong>“agent that can reason over 50,000 open datasets.”</strong></p><p>MCP doesn’t just solve a technical problem. It changes how we think about what an AI agent <em>can know </em>and that’s worth exploring.</p><p>If this article helped you, leave a clap 👏 and share what you build. You can also check my Research Agent <a href="https://github.com/marinaKpamegan/research-agent">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc5417ac6f28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Isolation Forest for Anomaly Detection]]></title>
            <link>https://medium.com/@falonnekpamegan/understanding-isolation-forest-for-anomaly-detection-c5b3ee6006ce?source=rss-cdb3d440a1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5b3ee6006ce</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[isolation-forests]]></category>
            <dc:creator><![CDATA[Falonne KPAMEGAN]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 13:35:02 GMT</pubDate>
            <atom:updated>2025-10-07T13:35:02.271Z</atom:updated>
            <content:encoded><![CDATA[<p>Isolation Forest is one of those machine learning algorithms that seems almost too simple, yet surprisingly powerful. In this post, we’ll unpack how it works, when you should (and shouldn’t) use it, and walk through a simple example in Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JmrWlvLr0KmtUrmK" /><figcaption>Photo by <a href="https://unsplash.com/@smwallday?utm_source=medium&amp;utm_medium=referral">Shay</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is isolation Forest ?</h3><p><strong>Isolation Forest</strong> is an unsupervised algorithm designed for <strong>anomaly detection, </strong>finding data points that behave differently from the rest. Instead of trying to <em>model normal behavior</em> (like many algorithms do), Isolation Forest takes the opposite approach: it tries to <strong>isolate anomalies</strong>. Why? Because anomalies are <em>rare</em> and <em>different</em>.<br> They can be isolated faster, meaning it takes fewer decisions (splits) to separate them from the rest of the data.</p><h3>and how it works ?</h3><p>Imagine you have a scatter plot of points. Most of them are clustered closely together, but a few lie far away from the rest. Isolation Forest builds many random binary trees to separate these points. For each tree, the algorithm randomly selects a feature and then chooses a split value somewhere between that feature’s minimum and maximum. It keeps splitting the data in this random way until every point is isolated in its own “leaf.” Now, count how many splits (decisions) it took to isolate each point:</p><ul><li>if it takes very few splits, that point is likely an <strong>anomaly</strong>,</li><li>if it takes many splits, it’s probably <strong>normal</strong></li></ul><p>This is why it’s called an Isoaltion Forest, it solates outliers instead of profiling normal data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*z-ri88i_0VjtDd-tya34Lw.png" /><figcaption>Source <a href="https://www.researchgate.net/figure/Conceptual-illustration-of-isolation-forest-a-isolation-operations-of-data-points_fig3_353615159">Researchgate</a></figcaption></figure><h3>When to use Isolation Forest ?</h3><ul><li>You have <strong>large</strong> or <strong>high-dimensional</strong> data (it scales very well).</li><li>You want a <strong>fast and efficient</strong> unsupervised method.</li><li>Your data doesn’t follow a known distribution (it’s non-parametric).</li><li>You just need a <strong>quick, practical</strong> way to flag potential outliers.</li></ul><p>It can be apply for fraudulent transaction banking detection, finding abnormal sensor readings in IoT systems, identifying unusual network behavior in cybersecurity.</p><h3>When not to use it ?</h3><p>Isolation Forest is powerful, but it’s not a silver bullet. You should avoid when:</p><ul><li>You have a small dataset : randomness can lead to unstable results</li><li>Anomalies are not clearly seperated from normal points</li><li>You have a lot of noise : the model might isolate noise instead of real outliers</li><li>You need detailed explanations: Isolation Forest tells you that something is strange but not <em>why.</em></li><li>The contamination rate (expected fraction of anomalies in the dataset) is unknown or changes over time.</li></ul><p>In those cases, consider alternatives like Local Outlier Factor (LOF), One-Class SVM or Auto encoders for deeper insight.</p><p>If you need detailed informations, here are some links :</p><ul><li><a href="https://www.datacamp.com/tutorial/isolation-forest">https://www.datacamp.com/tutorial/isolation-forest</a></li><li><a href="https://medium.com/@corymaklin/isolation-forest-799fceacdda4">https://medium.com/@corymaklin/isolation-forest-799fceacdda4</a></li><li><a href="https://www.geeksforgeeks.org/machine-learning/what-is-isolation-forest/">https://www.geeksforgeeks.org/machine-learning/what-is-isolation-forest/</a></li></ul><p>Thanks for reading !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5b3ee6006ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anomaly Detection in Sequential Data using LSTM Autoencoder and KMeans Clustering (unsupervised)]]></title>
            <link>https://medium.com/@falonnekpamegan/anomaly-detection-in-sequential-data-using-lstm-autoencoder-and-kmeans-clustering-unsupervised-6c6f27149358?source=rss-cdb3d440a1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c6f27149358</guid>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[sequential-data]]></category>
            <dc:creator><![CDATA[Falonne KPAMEGAN]]></dc:creator>
            <pubDate>Sat, 21 Jun 2025 14:35:13 GMT</pubDate>
            <atom:updated>2025-06-21T14:35:13.286Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Anomaly detection in time series data is a critical task in many fields such as finance, cybersecurity, manufacturing, and IoT. In this post, we explore how to detect anomalies in sequential data using a </em><strong><em>deep learning-based LSTM Autoencoder</em></strong><em>, followed by </em><strong><em>KMeans clustering</em></strong><em> on the latent space for unsupervised anomaly classification.</em></p><p><em>We use the </em><strong><em>Numenta Anomaly Benchmark (NAB)</em></strong><em> dataset, a well-known collection of real-world time series.</em></p><h3>Dataset Overview</h3><p>The <a href="https://github.com/numenta/NAB">Numenta Anomaly Benchmark (NAB)</a> contains multiple time series from different domains, including:</p><ul><li>Industrial measurements</li><li>Real traffic data</li><li>Real Ad exchange</li><li>Generated data</li></ul><p>In this post, we use the <strong>artificialWithAnomaly</strong> dataset from the <a href="https://github.com/numenta/NAB">Numenta Anomaly Benchmark (NAB)</a>. This subset contains <strong>synthetically generated time series</strong> with well-defined injected anomalies, making it ideal for validating unsupervised anomaly detection approaches.</p><p>Each record consists of: a <strong>timestamp</strong> and a <strong>value</strong> generated to simulate real-word metrics. Here’s a preview of the dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*ls-ZrlkJ0P76XonsVDzSWA.png" /><figcaption>dataset preview</figcaption></figure><p>Before diving into the core methodology, let’s first define what sequential data is and how an LSTM Autoencoder can be used to detect anomalies.</p><h4>What are sequential data ?</h4><p><strong>Sequential data</strong>, or <strong>time series data</strong>, consists of data points collected or recorded in <strong>chronological order</strong>. Each observation is dependent on one or more previous observations, making <strong>temporal relationships</strong> essential for analysis. This type of data appears across many domains like sensor readings in IoT devices, financial price movements, log events in IT systems, etc. Because sequential data contains patterns that unfold over time, conventional machine learning methods often fall short. Instead, models capable of understanding temporal dynamics — such as <strong>LSTM networks</strong> — are well-suited for these tasks.</p><h3>Why LSTM Autoencoders and How They Work?</h3><p>Unlike a standard LSTM used for forecasting or classification, an <strong>LSTM Autoencoder</strong> is designed to <strong>reconstruct its input sequence</strong>. It consists of two parts: an <strong>encoder</strong> LSTM that compresses the input into a low-dimensional latent representation, and a <strong>decoder</strong> LSTM that attempts to reconstruct the original sequence from this compressed code. The key idea is that the model learns to reproduce normal patterns well, but struggles to reconstruct sequences that deviate from the norm — such as anomalies. By analyzing either the <strong>reconstruction error</strong> or the <strong>structure of the latent space</strong>, we can effectively identify anomalous behavior in sequential data.</p><p>Once the LSTM Autoencoder compresses each input sequence into a <strong>latent vector</strong>, we obtain a compact representation that captures the essential temporal patterns of the data. These latent vectors form a new feature space where normal and abnormal behaviors may become <strong>more separable</strong>. Instead of relying solely on reconstruction error, we apply <strong>KMeans clustering</strong> to group similar latent representations. The idea is that <strong>normal sequences cluster together</strong>, while <strong>anomalous ones appear as outliers</strong> or form smaller, distinct clusters. This approach allows us to detect subtle anomalies that may not cause large reconstruction errors, but still exhibit different temporal dynamics in the latent space.</p><p><em>Let’s dive into the subject.</em></p><h3>Data Exploration</h3><p>Let’s visualize our data :</p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br>%matplotlib inline<br><br>plt.figure(figsize=(12,6))<br>sns.lineplot(x=df.index, y=df[&#39;value&#39;])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*QUiBq54ccgoGtNXTpLecPQ.png" /></figure><pre>sns.histplot(df[&#39;value&#39;], bins=100, kde=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*Y73w-IqahWurakeq4UiH-g.png" /></figure><h3>Data Preparation</h3><p>After verifying data are well formated, we normalized the time series using <em>MinMaxScaler </em>and generated overlapping windows of fixed length (SEQ_LENGTH) to feed into the LSTM.</p><pre>scaler = MinMaxScaler()<br>scaled_data = scaler.fit_transform(df[[&#39;value&#39;]])<br><br>def create_sequences(data, seq_length):<br>    X = []<br>    for i in range(len(data) - seq_length):<br>        X.append(data[i:i + seq_length])<br>    return np.array(X)<br><br>SEQ_LENGTH = 50<br>X = create_sequences(scaled_data, SEQ_LENGTH)</pre><h3>Building the LSTM Autoencoder</h3><pre>input_dim = X.shape[2]<br>timesteps = X.shape[1]<br><br>inputs = Input(shape=(timesteps, input_dim))<br>encoded = LSTM(64, activation=&#39;relu&#39;, return_sequences=False, name=&quot;encoder&quot;)(inputs)<br>decoded = RepeatVector(timesteps)(encoded)<br>decoded = LSTM(64, activation=&#39;relu&#39;, return_sequences=True)(decoded)<br><br>autoencoder = Model(inputs, decoded)<br>autoencoder.compile(optimizer=&#39;adam&#39;, loss=&#39;mse&#39;)<br>autoencoder.fit(X, X, epochs=50, batch_size=64, validation_split=0.1, shuffle=True)</pre><p>To access the latent representation, we define a seperate encoder model:</p><pre>encoder_model = Model(inputs, encoded)<br>latent_vectors = encoder_model.predict(X, verbose=1, batch_size=32)  # shape = (num_samples, 64)</pre><h3>Clustering with KMeans in Latent Space</h3><p>Rather than thresholding reconstruction errors, we apply <strong>KMeans clustering</strong> to the compressed latent vectors:</p><pre>from sklearn.cluster import KMeans<br><br>kmeans = KMeans(n_clusters=2, random_state=42)<br>labels = kmeans.fit_predict(latent_vectors)<br><br># We assume the larger cluster is &quot;normal&quot;<br>normal_cluster = np.bincount(labels).argmax()<br>anomaly_mask = labels != normal_cluster</pre><p>We visualize the latent space with PCA</p><pre>from sklearn.decomposition import PCA<br><br>pca = PCA(n_components=2)<br>latent_pca = pca.fit_transform(latent_vectors)<br><br>plt.figure(figsize=(10, 6))<br>sns.scatterplot(x=latent_pca[:, 0], y=latent_pca[:, 1], hue=labels, palette=&#39;Set1&#39;, s=50, alpha=0.7)<br>plt.title(&quot;Kmeans cluster in latent space (PCA 2D)&quot;)<br>plt.xlabel(&quot;principal component 1&quot;)<br>plt.ylabel(&quot;principal component 2&quot;)<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*9-NApw12aDrCA6pWq_I9VQ.png" /></figure><h3>Final Anomaly Detection</h3><pre>timestamps = balancer.index[SEQ_LENGTH:]<br><br>plt.figure(figsize=(15, 5))<br>plt.plot(timestamps, df[&#39;value&#39;][SEQ_LENGTH:], label=&#39;Value&#39;)<br>plt.scatter(timestamps[anomaly_mask], df[&#39;value&#39;][SEQ_LENGTH:][anomaly_mask], color=&#39;red&#39;, label=&#39;Detected Anomalies&#39;)<br>plt.legend()<br>plt.title(&quot;Anomalies Detected via KMeans on LSTM Latent Space&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_1LCFKw5Y9NISIZIVBWwNg.png" /></figure><h3>Conclusion</h3><p>By combining the sequence modeling capabilities of <strong>LSTM Autoencoders</strong> with the unsupervised grouping of <strong>KMeans</strong>, we were able to effectively detect anomalies in time series data — even without labeled anomalies.</p><p>This approach is powerful because:</p><ul><li>It doesn’t require labeled training data.</li><li>It adapts to complex sequential patterns.</li><li>It allows latent space exploration for clustering and visualization.</li></ul><p><em>Thanks for reading, I hope it is useful !</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c6f27149358" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>