<?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 Leonardo on Medium]]></title>
        <description><![CDATA[Stories by Leonardo on Medium]]></description>
        <link>https://medium.com/@le0.d4ta.d3v?source=rss-61245492e698------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ni3WO7wJmYL2IwfL</url>
            <title>Stories by Leonardo on Medium</title>
            <link>https://medium.com/@le0.d4ta.d3v?source=rss-61245492e698------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:48:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@le0.d4ta.d3v/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[Artificial intelligence in the real world: when an imperfect model, flawed automation, and an AI…]]></title>
            <link>https://medium.com/@le0.d4ta.d3v/artificial-intelligence-in-the-real-world-when-an-imperfect-model-flawed-automation-and-an-ai-85cb9c4dec2a?source=rss-61245492e698------2</link>
            <guid isPermaLink="false">https://medium.com/p/85cb9c4dec2a</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Leonardo]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 02:49:05 GMT</pubDate>
            <atom:updated>2026-10-15T02:49:05.804Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Artificial intelligence in the real world: when an imperfect model, flawed automation, and an AI agent that makes mistakes can create value</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*NALGTZLXvFBFG27TkMhGfg.png" /></figure><p>Machine Learning, Automation with n8n, and AI Agents in Production: Why Metrics, Costs, and Reliability Must Be Evaluated Together.</p><h3>1. Introduction</h3><p>When we learn about Artificial Intelligence at a school or in a course, instructors sometimes explain tools like LLMs, machine learning, and automation as if they were perfect: predictions must be excellent — otherwise, they’re wrong; automation must reach the right customers without error; and if an AI agent fails locally, it fails in production. In the real world, things don’t necessarily have to be that way. We’ll explore why sometimes a prediction using Machine Learning with a 60% positive prediction rate is acceptable, why an automation in n8n might make mistakes, yet still function in production; an AI agent runs on your server, answers your questions, and never makes mistakes; in production, when it receives questions from different people, its memory is stored, and it might give incorrect answers — yet it could still function well if the cost is minimal and the customer continues to trust the company.</p><p>In a company, artificial intelligence systems aren’t just there to achieve high metrics. Sometimes real-world problems don’t yield perfect results; what we can do is reduce costs and create value. An incorrect prediction might result in a loss of just a few soles. In contrast, a failure in fraud detection can lead to significant financial losses. Automation that sends an irrelevant promotion doesn’t have the same consequences as an automated report. The following questions arise: How much does each error cost? What happens when the data changes? How do I prevent a technical glitch from becoming a business problem?</p><p>However, there are situations where the company does need predictions, automation, and agents to function very efficiently, since the cost per loss would be high, and AI governance dictates that there must be someone accountable if something goes wrong.</p><h3>2. Machine Learning: When Is a Model With a 60% Recall-Precision Sufficient?</h3><p>Let’s imagine a company that wants to use machine learning to identify customers who might be interested in buying a new cell phone. The company has a history of purchases, inquiries, and promotions; it uses this data to train its ML model and generate a classifier that estimates which people are most likely to be interested in the offer.</p><p>There is no such thing as a perfect model; some customers will receive promotions that don’t interest them, while others who are interested will not be identified. This does not mean the model is useless.</p><p>Precision and recall measure different things. Recall measures how many of the interested customers we manage to find. Precision measures how many of the selected customers are actually interested.</p><p>2.1. Complete Example with 1,500 Customers</p><p>To visualize both metrics at the same time, we’ll use this illustrative data:</p><p>• 1,500 customers in total.</p><p>• 500 genuinely interested customers.</p><p>• 1,000 customers who are not interested.</p><p>• 500 customers selected by the model.</p><ul><li>Of the 500 selected, 300 are true positives and 200 are false positives.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*ZEe116BE8GsL40eA-_gxog.png" /></figure><p>The metric is as follows:</p><p>Based on this matrix, we can derive several metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*htjcvcdHSOqT6toP2jDPwg.png" /></figure><p>2.2. What if making a mistake costs very little?</p><p>Now let’s suppose a company uses this model for a cell phone promotion campaign.</p><p>Sending an email has a low operational cost. The company already has a marketing platform in place, there is sufficient inventory, and customers can ignore the promotion without causing any significant harm.</p><p>The model identifies 500 customers, and the campaign reaches all of them.</p><p>Let’s assume the following costs, solely to illustrate the economic analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*W1oEpDRho6Dc_oy6IVIvqw.png" /></figure><p>The S/ 4 represents the direct cost of messages sent to people who were not part of the target audience, not the total cost of the campaign.</p><p>If the 300 correctly selected customers generate enough additional sales to cover the campaign costs, the model could be economically viable even with a recall and precision of 60%.</p><p>But we must consider one thing: the real cost of a false positive isn’t always just the price of the email. It can also include unnecessary discounts, marketing fatigue, unsubscribes, or a loss of trust. Similarly, a false negative can represent a sale that never happened.</p><p>The decision should be based on the total cost and expected benefit, not solely on the cost of sending a notification.</p><p>2.3. How do you explain this to a client who wants to improve their business with AI?</p><p>Let’s imagine that a company hires a consulting team to develop a promotional recommendation system.</p><p>The client asks:</p><p>“Why is the model only 60% accurate? Shouldn’t we improve it to 95%?”</p><p>A professional response shouldn’t simply be that 60% is sufficient just because. First, you must explain what that figure means and how much it would cost to improve it.</p><p>We could respond:</p><p>We’ve determined that the model allows us to select a group of customers with a reasonable probability of being interested in the promotion. Given the current campaign costs, the observed errors may be acceptable. Before investing more resources to improve the metrics, we’ll evaluate whether that improvement generates enough additional sales to justify the cost.</p><p>This conversation shifts the focus. It’s no longer about achieving the best possible figure, but about finding a balance between performance, investment, and profit.</p><p>That doesn’t mean we should settle for a mediocre model. It means that improvements must be justified both technically and economically.</p><h3>3. Machine Learning in Production: Training a model once doesn’t mean it will perform well forever</h3><p>A trained model learns patterns present in the available data. If those patterns change, its performance may deteriorate.</p><p>Imagine a store that trains a model to predict which cell phones its customers will buy. During training, most shoppers prefer mid-range devices.</p><p>Months later, the company begins offering new brands, changes its prices, introduces financing options, and launches promotions for high-end phones.</p><p>The model continues to use the patterns it learned previously. It can still generate predictions, but it no longer necessarily reflects current customer behavior.</p><p>This problem is related to data drift and concept drift.</p><p>• Data drift: The distribution of the input data changes relative to the reference used during training.</p><p>• Concept drift: The relationship between the input variables and the outcome being predicted changes.</p><p>Detecting changes in the data does not automatically prove that the model’s quality has declined, but it is a signal to investigate further. Model degradation must be evaluated using metrics, actual results, and business context.</p><p>3.1. What does it mean to version a machine learning model?</p><p>Versioning means keeping track of and recording the different versions of a model and the elements needed to reproduce its behavior.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*Wt7q2iy-_u3Ld34k4XxJlw.png" /></figure><h3><strong>4. Automation with n8n: When a Small Mistake Doesn’t Ruin the Business</strong></h3><p>Now let’s imagine that we want to use its predictions to automatically carry out actions.</p><p>This is where n8n comes in — a workflow automation platform that lets you connect applications, services, APIs, and AI models.</p><p>This combination is particularly interesting because the model doesn’t have to perform all the tasks. It can handle the predictions, while n8n takes care of executing the corresponding actions.</p><p>4.1. The Story of a Cell Phone Store</p><p>Let’s imagine a fictional company called Móvil Conecta, which sells cell phones and accessories.</p><p>The company has thousands of customers, but its marketing team doesn’t want to send the same promotion to everyone. Some customers buy high-end phones; others prefer budget-friendly devices; still others frequently ask about batteries, cameras, or storage.</p><p>The company decides to build a system that combines machine learning, n8n, and an AI API.</p><p>The process begins when a customer’s purchase history is updated. The predictive model analyzes the data and estimates which product category might interest them.</p><p>Next, n8n receives the prediction and executes the corresponding workflow.</p><p>The complete workflow has five stages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*KXyF_okXD9rAXkWf06GYZQ.png" /></figure><h3>4.2. What happens if the system makes a mistake?</h3><p>Let’s go back to Móvil Conecta.</p><p>The model identifies a customer as a potential buyer of a high-end cell phone, but in reality, that person is looking for an affordable device. n8n sends a promotion that doesn’t interest them.</p><p>Is this a mistake? Yes.</p><p>Does that mean the whole system is useless? Not necessarily.</p><p>If the campaign’s cost is low, the customer can ignore the message, and the company can still make a net profit. In that context, it might be reasonable to accept a certain proportion of incorrect recommendations, provided the company measures their impact and controls the frequency of the messages.</p><p>Let’s imagine the system repeats this error many times. The customer begins to receive irrelevant promotions, unsubscribes from the list, or loses trust in the brand.</p><p>For this reason, imperfect automation may be acceptable, but it should not operate without limits or supervision.</p><h3>5. AI Agents: It works locally, but fails when users log in</h3><p>AI agents present another challenge.</p><p>Let’s imagine we develop an assistant using the API of an AI company, such as OpenAI, Anthropic, or DeepSeek. The agent runs on our server and uses a model hosted by the provider.</p><p>From our computer, we can ask questions, get answers, and look up information in a database. Everything seems to be working correctly.</p><p>However, when we release the application and different people start using it, problems arise that we didn’t notice during testing.</p><p>5.1. The Story of a Business Assistant</p><p>A company develops an AI agent to help its customers improve their businesses. The agent can answer questions, consult internal documentation, and use tools to retrieve information.</p><p>During testing, a developer asks:</p><p>“How can I increase sales at my cell phone store?”</p><p>The agent responds correctly and saves information about the business to personalize future responses.</p><p>Later, another user asks:</p><p>“How can I reduce costs at my restaurant?”</p><p>If the system is poorly designed and reuses the same conversational memory, it could mix up information from both users. The second customer might receive recommendations based on the first customer’s data.</p><p>The problem isn’t necessarily with the language model. It could lie in the application’s architecture.</p><p>The agent may generate good responses, but if the system provides it with the wrong history, the final response may also be incorrect.</p><p>And if the memory contains confidential information, the error could result in a privacy breach.</p><p>5.2 What does an AI agent need to run in production?</p><p>An AI agent in production requires much more than just an API key and a good prompt. It must operate within an application that controls access to data, manages conversations, and monitors the actions the agent can perform.</p><p>Here are some of the most important best practices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*kXjVDxozX2QI-bNVeAWIKA.png" /></figure><p>5.3 AI Assistant That Recommends Cell Phones: When Making a Mistake Doesn’t Necessarily Mean Failure</p><p>Let’s imagine that a cell phone store implements an AI agent to recommend products based on each customer’s needs. The agent analyzes the customer’s budget, preferences, and purchase history to suggest the most suitable device.</p><p>However, the system doesn’t always get it right. Sometimes, it recommends a high-end cell phone to someone looking for an affordable model. The recommendation is incorrect, but does that mean the agent is useless?</p><p>Not necessarily.</p><p>The customer can reject the recommendation, clarify their budget, and allow the agent to generate a new response. The company, for its part, can evaluate the system’s performance using metrics such as customer satisfaction, conversion rate, and cost per inquiry.</p><p>It must also consider the consequences of errors. If incorrect recommendations are frequent, customers might lose confidence in the service or abandon the conversation. That’s why it’s not enough to simply verify that the agent responds quickly — it’s necessary to determine whether it actually helps users make better decisions.</p><p>In this scenario, the agent does not need to get every recommendation right to be useful. It can generate value if it resolves enough inquiries, improves the customer experience, and reduces operating costs compared to a viable alternative.<br>The condition is that its errors are manageable, that the system can correct itself when it receives additional information, and that its overall benefit justifies the operating costs and any problems it may cause.<br>An AI agent can be good enough even if some of its recommendations are incorrect, provided that its overall performance adds value and the errors do not lead to unacceptable consequences. The goal is not to accept any errors, but to determine which ones can be tolerated and which ones must be prevented.</p><h3>8. Conclusions: It’s Not About Accepting Errors, but About Managing Them</h3><p>The real difference between a prototype and a professional solution isn’t that the latter never fails. It’s that its risks are known, its errors can be detected, its consequences are controlled, and there’s a plan in place to recover when something goes wrong.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85cb9c4dec2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do You Really Need an LLM?
Traditional Machine Learning vs. Generative AI for Credit Risk]]></title>
            <link>https://medium.com/@le0.d4ta.d3v/do-you-really-need-an-llm-traditional-machine-learning-vs-generative-ai-for-credit-risk-2b85aecb5d26?source=rss-61245492e698------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b85aecb5d26</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Leonardo]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 17:46:41 GMT</pubDate>
            <atom:updated>2026-09-07T17:46:41.834Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Accuracy, speed, RAM usage, and scalability</em></p><p>LLMs accessed through a cloud API can use very little RAM on our computer compared with a Machine Learning model running locally. However, this does not mean that they require fewer resources, because the heavy computation takes place on external servers. While LLMs excel at natural-language tasks, traditional models can be more efficient for structured problems such as credit risk. If both were deployed in the cloud, the comparison should also consider server RAM, CPU/GPU requirements, speed, cost, and scalability to determine which solution is truly more efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*zTysR04190LVE_2LJdkb1w.png" /></figure><h3><strong>The same problem, three approaches</strong></h3><p>The goal of the experiment was to predict default risk from structured customer variables. Logistic Regression, Random Forest, and an LLM accessed through the Groq API were compared. The intention was not to look only at Accuracy, but also to observe what changes when response time, RAM usage, and output reliability are measured.</p><h3><strong>First question: which model predicts better?</strong></h3><p>The observed results were:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*jNcwRyrlBCrkY2JQk6--bg.png" /></figure><p>*The LLM was evaluated on a smaller sample, so its metrics should be interpreted as a preliminary comparative experiment rather than a definitive benchmark against the entire test set.</p><p>Random Forest achieved the best overall balance and the highest F1-score. Logistic Regression achieved the highest Recall. This reminds us that in credit risk there is no single metric that summarizes the entire problem: the cost of failing to detect a risky case may be different from the cost of incorrectly classifying a safe customer.</p><h3><strong>Second question: what happened with the LLM?</strong></h3><p>A traditional model directly returns a class or probability. An LLM, on the other hand, generates text. This introduces a new source of failure: the response may not exactly follow the format expected by the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*1B9XwMmIUVKaKbaVUqgHTg.png" /></figure><p>Therefore, when evaluating an LLM-based system, in addition to Accuracy, Precision, Recall, and F1, it is also useful to measure the valid-response rate, formatting errors, retries, and API failures. In production, a useful prediction must be correct and must also arrive in a form that the system can process.</p><h3><strong>Third question: which one uses more RAM?</strong></h3><p>The local memory observed during the experiment was approximately:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*UvEWXF5nM3kU2LHswD7kxw.png" /></figure><p>At first glance, the LLM appears to use less RAM. But that conclusion would be misleading. Logistic Regression and Random Forest were executed locally, while the LLM ran on remote infrastructure. The local computer only prepared the request, sent it over the Internet, and received the response.</p><h3><strong>The RAM trap</strong></h3><p>Groq’s low local RAM usage does not mean that the complete LLM requires less memory. It means that the computational cost was moved to another server. A large LLM must keep its weights in memory and, during generation, may also use additional memory for structures such as the KV cache.</p><p>For this reason, a correct comparison must distinguish between the client’s local RAM and the total memory required by the infrastructure that actually runs the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*k3gAQeA6nVKm3S90exeIvw.png" /></figure><h3><strong>What if Machine Learning is also in the cloud?</strong></h3><p>If Random Forest or Logistic Regression is deployed behind an API on a cloud server, the user’s computer would also use very little RAM. In that scenario, comparing only the laptop’s RAM is no longer useful.</p><p>The question becomes: how many resources does the infrastructure running each model require? This is where server RAM, CPU or GPU, latency, throughput, cost per request, and the ability to handle concurrent users become important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*vEffiWUW0YJkHyZ1TG94IQ.png" /></figure><h3><strong>Scalability: what happens when thousands of requests arrive?</strong></h3><p>In a small project, we can think about the RAM used by a single execution. In a large project, the unit of analysis changes. The system must respond to many requests at the same time while maintaining acceptable latency and controlled cost.</p><p>Total memory does not necessarily grow linearly with every user. One instance can keep a model loaded and serve multiple predictions. When one instance is no longer sufficient, more replicas can be created through horizontal scaling. Each replica may load another copy of the model, so the total memory used by the infrastructure increases.</p><p>Large LLMs also face memory pressure from active sequences and the KV cache. This is why LLM inference systems use specific techniques such as batching, quantization, and memory management to increase the number of requests that can be served with the same hardware.</p><h3><strong>Does a large project always need more RAM?</strong></h3><p>In terms of total infrastructure, more resources are generally required as the workload increases, but this does not mean that RAM simply grows as ‘memory per prediction × number of users.’ The architecture can share models across requests, group predictions into batches, increase or reduce replicas, and use autoscaling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*RbFtc4gxHpZGHNfiLYw7kA.png" /></figure><h3><strong>Fourth question: which one was faster?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*hiCwqMBpPznnEaHD4vgL7w.png" /></figure><p>These times should not be treated as a universal benchmark because the Groq call includes network communication, remote infrastructure, and token generation. However, they show an important difference: for a simple tabular classification task, traditional models can produce predictions extremely efficiently.</p><h3><strong>So, why use an LLM?</strong></h3><p>It would be incorrect to conclude that Random Forest is ‘better than an LLM’ in general. They were designed around different strengths. A traditional model can be excellent at transforming structured variables into a risk probability. An LLM can add natural-language understanding and generation, user interaction, document analysis, or explanations.</p><p>In a real system, a hybrid architecture may be more reasonable: the traditional model performs the classification and the LLM helps explain the result, consult documentation, or assist an analyst. In this way, each tool solves the part of the problem for which it is best suited.</p><h3><strong>Scalability changes the question</strong></h3><p>The experiment began by asking which model used more RAM. But once the cloud is introduced, that question becomes incomplete. If both models run remotely, the RAM usage on the user’s computer will be small in both cases.</p><p>The important comparison becomes how much infrastructure the entire system needs to maintain a given level of latency and throughput, how much that infrastructure costs, and what predictive performance we obtain in return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*sEphHvzTlp_tDOvJltCfOw.png" /></figure><p><strong>Conclusion: the largest model is not always the best solution</strong></p><p>In these tests, Random Forest achieved the best F1 among the evaluated approaches, while Logistic Regression achieved the highest Recall. The LLM showed very low local RAM usage, but this was because inference occurred remotely.</p><p>As the system grows, new variables appear: concurrency, throughput, latency, batching, replicas, CPU, GPU, server memory, autoscaling, and cost. Therefore, the goal should not be to use the most sophisticated model available, but rather the simplest architecture that solves the problem correctly and can grow as the problem grows.</p><p><strong><em>The question is not only which model uses less RAM, but which one offers the best balance between performance, resources, and scalability for the problem we actually want to solve.</em></strong></p><h3>Technical references</h3><ul><li>Hugging Face Transformers. Optimization and inference of Large Language Models.</li><li>Hugging Face Transformers. KV Cache and memory management during generation.</li><li>Kwon et al. Efficient Memory Management for Large Language Model Serving with PagedAttention (vLLM), 2023.</li><li>Amazon SageMaker. Documentation on endpoints, sizing, and autoscaling for inference.</li><li>Own experiments with Logistic Regression, Random Forest, and Groq for credit-risk classification.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b85aecb5d26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A machine learning model isn’t ready for production just because it has good recall, precision, and…]]></title>
            <link>https://medium.com/@le0.d4ta.d3v/a-machine-learning-model-isnt-ready-for-production-just-because-it-has-good-recall-precision-and-c94ab139b02d?source=rss-61245492e698------2</link>
            <guid isPermaLink="false">https://medium.com/p/c94ab139b02d</guid>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[machine-leanring-engineer]]></category>
            <dc:creator><![CDATA[Leonardo]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 21:08:08 GMT</pubDate>
            <atom:updated>2026-08-19T21:09:58.595Z</atom:updated>
            <content:encoded><![CDATA[<h3>A machine learning model isn’t ready for production just because it has good recall, precision, and ROC-AUC.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*sMa3tU1EFvvs3rdJ7NU88g.png" /></figure><p>Training a machine learning model may seem simple.<br>We load the data, clean it, split the dataset, train a Random Forest, calculate some metrics, and if we see an ROC-AUC of 0.92, a rather dangerous temptation arises:<br>“The model works. Let’s put it into production.”<br>But in a real-world system, that statement can be the beginning of the problem, not the end.<br>A model can have excellent metrics and still make the wrong decisions when it receives data it never saw during training.<br>And that completely changes the question.<br>It’s no longer just about:<br>HOW GOOD IS MY MODEL?<br>But rather:<br>IN WHAT SITUATIONS CAN I TRUST IT?</p><h3>First question before production: Does the data make sense?</h3><p>In my analysis of the credit risk model, the dataset initially contained 32,581 records and 12 variables.<br>While reviewing the data, I came across something that a model cannot resolve on its own.<br>There were people who were 144 years old and had 123 years of work experience.<br>It wasn’t a groundbreaking discovery about human longevity. It was a data issue.<br>After applying quality checks, I removed 902 anomalous records, leaving 31,679 records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*UkTNJvR1xpl7mNK1AbT3mQ.png" /></figure><p>This step may seem small, but it represents a fundamental concept: a machine learning model learns from data, including its errors.</p><p>If we feed it junk data, the model won’t necessarily warn us. It may learn from it.</p><h3>Example in production</h3><p>Let’s imagine a bank that receives an application:</p><p>Age: 29<br>Income: $55,000<br>Loan amount: $8,000<br>Interest rate: 11%</p><p>Everything seems normal.</p><p>But now here’s another one:</p><p>Age: 187<br>Income: $9,000,000,000<br>Years of employment: 154 years</p><p>The model might generate a prediction. And that is precisely the problem.</p><p>Just because a model generates a prediction doesn’t mean that prediction makes sense.</p><p>That’s why a production system should include validations before allowing data to reach the model.</p><h3>Second question: How are the classes scheduled?</h3><p>Another important detail emerged regarding the credit risk problem. The target variable was distributed approximately as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*m6bXyra1NS2GYc0hHNp28g.png" /></figure><p>This means that approximately 8 out of every 10 customers did not default.</p><p>Here lies a classic pitfall. A completely useless model that predicts “No one will default” would have an accuracy of approximately 78%.</p><p>On paper, that might seem acceptable. For a bank, it would be disastrous.</p><p>That is why a metric cannot be chosen solely for convenience.</p><h3>There is no magic metric</h3><p>After training the Random Forest, the results were:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*55OUxsBAZbpuDusL43a_ww.png" /></figure><p>At first glance, it seems like a pretty good model.</p><p>But this is where the really interesting analysis begins.</p><p>The recall for “Default” was 0.74. That means the model does not detect all cases of default.</p><p>Therefore, if this system were used in a financial institution, it would not be accurate to simply say, “Our model has 91% accuracy.”</p><p>The discussion should be much more specific: “Our model has an ROC-AUC of 0.9245 and a recall of 0.74 for the ‘Default’ class. We need to assess whether that level of false negatives is acceptable for the business.”</p><p>The metric must speak the language of the problem.</p><h3>Third question: What is the model actually learning?</h3><p>In the Random Forest model, the most important variables were:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*vXfA22oSXCv09gZSNgqoGA.png" /></figure><p>There’s an interesting insight here.</p><p>The percentage of income allocated to the loan accounts for approximately 28.4%, while the interest rate accounts for approximately 23.5%.</p><p>This does not automatically mean that a variable “causes” default. It means that, within this model and this data set, those variables made a greater contribution to the predictions.</p><p>A data scientist should not automatically equate “The model assigns importance to X” with “X causes Y.”</p><h3>Here’s an even more important point: the model may be correct for the wrong reasons</h3><p>Suppose a company discovers that a certain variable is strongly associated with risk.</p><p>Before using it in production, it would be wise to ask:</p><p>• Is it valid?<br>• Is it available before the decision is made?<br>• Is it biased?<br>• Could it be a proxy for another problematic characteristic?<br>• Is it available in the same way in production?<br>• Could its distribution change over time?<br>• Is there leakage?</p><p>A model does not know what is ethical, legal, or appropriate. It simply mathematically optimizes the pattern it finds.</p><h3>Fourth question: Does the model work only on the dataset?</h3><p>A model can perform very well with data similar to what it was trained on.</p><p>But what happens when a completely different customer comes along?</p><p>To test this, thresholds based on the training data were used for some numerical variables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*Z8bVa-wkbLw7m4sh_ldSTA.png" /></figure><p>These limits do not mean that a customer who falls outside them is incorrect. They mean that the model has less evidence of similar cases in that range.</p><h3>The Typical Case</h3><p>Client:<br>Age: 28<br>Income: $55,000<br>Length of employment: 4 years<br>Interest rate: 11.5%<br>Loan-to-income ratio: 0.18<br>Credit history: 5 years</p><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*GgFGkcXONT3d0PNwKZtAqQ.png" /></figure><h3>The Strange Case</h3><p>Client:<br>Age: 75<br>Income: $1,500,000<br>Years of employment: 30 years<br>Credit history: 20 years<br>Type of housing: OTHER</p><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*A3w-4zjZKiInPZ1cudgl0g.png" /></figure><p>And here’s the most important part: the model did not fail to make a prediction. But the system made it clear that we should not interpret that prediction with the same confidence as a prediction made for a typical case.</p><h3>A production model should know when to raise its hand</h3><p>Now let’s imagine that this model is connected to a banking platform.</p><p>Normal case:<br>Probability of Default: 8%<br>Data confidence: High</p><p>The system can proceed automatically.</p><p>Outlier case:<br>Probability of Default: 12%<br>Data Confidence: Low</p><p>Although 12% may seem like a reassuring figure, the system might flag it for review because the customer’s characteristics fall outside the known range.</p><p>The number alone doesn’t tell the whole story.</p><h3>What would this look like in production?</h3><p>Case 1: Banking<br>A customer applies for a loan. The model calculates a probability and a reliability score.</p><p>If the data falls within the known distribution, the process can continue.</p><p>If the customer’s characteristics deviate significantly from the training data, the system may escalate the case for human review.</p><p>The idea is not for the model to make all the decisions. The idea is to build a system where the model knows when it can act and when it should escalate the case.</p><p>Case 2: Churn in Telecommunications<br>A company has millions of customers.</p><p>Clustering identifies a segment characterized by short tenure, monthly contracts, and low cumulative spending.</p><p>In the analysis conducted, this type of segment showed a significantly higher churn rate.</p><p>In production, the company could use this segment to implement a strategy:</p><p>Customer enters the at-risk segment<br>→ automation system<br>→ personalized offer<br>→ email / WhatsApp<br>→ if the risk is high<br>→ human advisor</p><p>Here, the model is no longer just a notebook. It becomes part of a business process.</p><h3>Question 5: What happens after deployment?</h3><p>We tend to think that production means:</p><p>Train → save model → API → done</p><p>But a machine learning model isn’t a mathematical function frozen in time.</p><p>The world changes.</p><p>Customers change.</p><p>Products change.</p><p>Rates change.</p><p>Habits change.</p><p>And, eventually, the data distribution may change.</p><p>That’s why a real-world system should monitor:</p><ul><li>Distribution of variables.<br>• Percentage of missing values.<br>• New categories.<br>• Changes in predictions.<br>• Precision and recall when ground truth labels are available.<br>• Drift.<br>• Out-of-distribution cases.<br>• Latency.<br>• API errors.<br>• Changes in business behavior.</li></ul><h3>The notebook is the lab. Production is on another planet.</h3><p>In a notebook, we can run:</p><p>model.predict(X_test)</p><p>and get:</p><p>Accuracy: 91%<br>ROC-AUC: 0.9245</p><p>But a real API needs to answer additional questions:</p><p>Is the data valid?<br>Are any variables missing?<br>Is the client within the known distribution?<br>Is the model version correct?<br>Is the prediction being logged?<br>Is the model degrading?<br>Should we escalate the case to a human?<br>What happens if the model fails?</p><p>That’s no longer just machine learning.</p><p>It’s machine learning engineering.</p><h3>So, when is a model really ready?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*KRMSzeEJvFM-8dLfjKP5Ag.png" /></figure><p>This table summarizes a key point: the model is only part of the solution.</p><h3>The Paradox of Machine Learning</h3><p>The more advanced a machine learning project becomes, the less significant this statement seems:</p><p>“My model has 95% accuracy.”</p><p>Because more interesting questions begin to arise:</p><p>95% of what population?<br>What about the other 5%?<br>What kind of errors does it make?<br>How much does each error cost?<br>What happens when it receives data it’s never seen before?<br>Can the business tolerate those errors?<br>How do we know if it will still work in six months?</p><p>That’s where machine learning stops being just modeling and starts becoming decision systems engineering.</p><h3>From Concept to Product</h3><p>In the case of credit risk, the Random Forest achieved an ROC-AUC of 0.9245, but the analysis didn’t end there.</p><p>The following were reviewed:</p><p>• Data quality.<br>• Imbalance.<br>• Metrics by class.<br>• Variable importance.<br>• Typical cases.<br>• Cases outside the known distribution.</p><p>And that last point is probably one of the most important.</p><p>Because it’s one thing to build a model that says:</p><p>Default: 15.57%</p><p>and quite another to build a system that can say:</p><p>Default: 15.57%<br>But be careful: this customer is outside the range where the model has sufficient evidence.</p><p>The second solution is much closer to a system that can function in the real world.</p><h3>Conclusion: Before putting a model into production, it must be tested against reality.</h3><p>A machine learning model shouldn’t go into production simply because it works on the test set.</p><p>First, you need to ask:</p><p>Is your data reliable?<br>What errors do you make?<br>What variables are you using?<br>What happens when you encounter an outlier?<br>When should a human intervene?<br>How will we know if you’re no longer functioning correctly?</p><p>That, to me, is one of the most important shifts in mindset in machine learning:</p><p>“It’s not about building a model that always makes a prediction. It’s about building a system that knows when its prediction is trustworthy.”</p><p>Because in a notebook, an incorrect prediction might just be a red cell.</p><p>In production, it can turn into an incorrectly approved loan, a lost customer, a wasted campaign, or a decision that someone will have to explain.</p><p>And that’s where the machine learning experiment ends and the real engineering work begins.</p><p>Link code: <a href="https://github.com/Lev-Coding-py/Riesgo-Crediticio">https://github.com/Lev-Coding-py/Riesgo-Crediticio</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c94ab139b02d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Clustering Identifies Customer Churn Without Using an LLM]]></title>
            <link>https://medium.com/@le0.d4ta.d3v/how-clustering-identifies-customer-churn-without-using-an-llm-a246bce706f5?source=rss-61245492e698------2</link>
            <guid isPermaLink="false">https://medium.com/p/a246bce706f5</guid>
            <category><![CDATA[ai-enginer]]></category>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[ml-engineering]]></category>
            <dc:creator><![CDATA[Leonardo]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 20:13:11 GMT</pubDate>
            <atom:updated>2026-08-11T20:13:11.312Z</atom:updated>
            <content:encoded><![CDATA[<p>Every customer who leaves without warning costs a company much more than just the lost revenue: it costs the company the opportunity to have retained that customer in time. The question isn’t whether your customers will leave, but whether you can see it coming before they decide to leave. That’s where clustering stops being an academic exercise and becomes a business tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*LtJAdYx2gZjaVuu_3XiE9g.png" /></figure><h3>What is clustering?</h3><p>We define this concept as a machine’s ability to cluster a dataset based on similar characteristics without the need to program it using code or conditions — in other words, simply using the KMeans library is sufficient. It uses a point as a reference and identifies nearby neighbors based on the shortest distances. This method does not understand what it is doing, and it is the responsibility of the data scientist, ML engineer, or AI engineer to provide a real-world application.<br>Today, there are large language models (LLMs) that could also identify these patterns based on a description of the problem. However, for a structured clustering task like this one, an unsupervised model such as K-Means is more cost-effective, faster, and deterministic: it will always classify data in the same way given the same input, whereas an LLM requires more computing power and constant monitoring to rule out hallucinations. Clustering doesn’t “understand” what it’s grouping, but for this type of problem, that’s precisely its advantage: it doesn’t interpret; it simply finds structure in the data consistently.<br>This method can identify patterns that would take a human time to discover at first glance, whether through different methods such as exploratory analysis, A/B testing, Power BI, etc. Applying these methods afterward is necessary for a business application.<br>Machine learning (clustering), like any method, needs to answer certain questions: How many groups do I need? Is there any data that causes the cluster to become confused and classify</p><h3>The Case: Customer Churn</h3><p>To understand this process, I’ll use customer churn as an example, which has the following variables: total expenses, contract type, length of service, retirement, payment method, and churn.</p><h3>Constraints for Optimal Unsupervised Learning</h3><p>The following restrictions should be considered for optimal unsupervised learning:</p><p>If there is a target variable, it should not be included in the ML model, as the model would not learn correctly.</p><p>If some variables are much larger than the others, the Standard Scaler statistical method should be used so that all variables have the same importance and the model can classify data accurately.</p><p>EDA after classification is necessary to understand the results, make actionable decisions, and automate the process.</p><p>Churn should not be included in the cluster, as it would follow the same pattern, and the model needs to identify new patterns — even those the programmer cannot see at a glance. Data such as Total Expenses, Contract Type, Tenure, Retirement, and Payment Method are necessary. However, one piece of data requires special treatment: Total Expenses. Unlike the other variables, this value fluctuates from 500 to much higher values, which skews the classification if not corrected. For this reason, the Standard Scaler method is used, which statistically converts all values to the same scale.</p><p>Once the number of clusters was defined based on the resulting segmentation, the model grouped the 7,043 customers in the dataset into two clearly distinct clusters.</p><h3>From Clusters to Strategy</h3><p>After clustering, it is necessary to apply the results to a real-world business scenario and/or research; before doing so, an exploratory analysis must be conducted to understand the results. This is done by comparing the clusters with tenure, total expenses, contract type, and churn.<br>The results speak for themselves:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*tZLVoykQWPHD-uQ_-SqzPg.png" /></figure><p>Cluster 1 — new customers with month-to-month contracts — has a churn rate more than six times that of Cluster 0 — long-time customers with long-term contracts. Without knowing what “churn” was, the model identified exactly the same pattern, which was later confirmed by cross-referencing it with that variable. This means that, by prioritizing only Cluster 1, a company would focus its retention efforts where nearly 88% of the total churn in the dataset occurs — in other words, with a fraction of the campaign effort, it covers almost all of the actual risk. This is what allows a company and/or research project to have various applications:</p><h3>Recommendations</h3><p><strong>1. Customer Loyalty Strategy</strong></p><p>Long-term customers with one- or two-year contracts demonstrate greater stability and represent the most valuable segment for the company. In contrast, customers with monthly contracts and shorter tenure exhibit more volatile behavior and require retention strategies.</p><p><strong>2. Campaign Automation</strong></p><p>Implement automated campaigns using tools such as Make or n8n to send personalized promotions, discounts, and reminders via email or WhatsApp to customers at the highest risk of churn. In specific cases, the system can refer the customer to a human advisor to provide personalized support.</p><p><strong>3. Generative AI-Based Assistant</strong></p><p>Integrate an assistant using language models such as OpenAI, Claude, or open-source models that analyze customer information and generate explanations in natural language regarding their stability level, the factors influencing their behavior, and recommendations to improve retention.</p><p><strong>4. App Development</strong></p><p>Develop a web application where non-technical users can enter a customer’s information and automatically receive:</p><p>The segment to which the customer belongs.</p><p>An estimate of the customer’s stability level.</p><p>Retention recommendations.</p><p>AI-generated explanations to facilitate decision-making.</p><p><strong>5. Customer Prioritization</strong></p><p>Not all customers require the same retention actions. It is recommended to prioritize</p><h3>Conclusion</h3><p>Without using a single “churn” label during training, the clustering identified the same pattern that every company needs to take timely action: who is at risk of leaving. That’s the difference between reacting after a customer has already left and anticipating the situation while there’s still time to act. The next natural step is to deploy this analysis into production: an automated system that prioritizes, in real time, who to contact first.</p><p>You can view the complete notebook with the analysis and code here:</p><p><a href="https://github.com/Lev-Coding-py/Predije-con-ML-qui-n-va-a-cancelar-su-servicio-sin-usar-un-solo-Churn-S-/blob/main/churn.ipynb">Predije-con-ML-qui-n-va-a-cancelar-su-servicio-sin-usar-un-solo-Churn-S-/churn.ipynb at main · Lev-Coding-py/Predije-con-ML-qui-n-va-a-cancelar-su-servicio-sin-usar-un-solo-Churn-S-</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a246bce706f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Churn Prediction with ML and Generative AI: Why a Model That Only Predicts Is Not Enough]]></title>
            <link>https://medium.com/@le0.d4ta.d3v/churn-prediction-with-ml-and-generative-ai-why-a-model-that-only-predicts-is-not-enough-1964a5097948?source=rss-61245492e698------2</link>
            <guid isPermaLink="false">https://medium.com/p/1964a5097948</guid>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Leonardo]]></dc:creator>
            <pubDate>Sat, 23 May 2026 23:06:16 GMT</pubDate>
            <atom:updated>2026-05-23T23:06:16.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*XXOYPMoGqGsAEHyFsx7mcw.png" /></figure><h3><strong>The problem nobody tells you about</strong></h3><p>Imagine you train a churn prediction model with 80% accuracy. You deploy it. It works. The business team asks you: “Why is this customer going to leave the service?”</p><p>And you reply: “The model says so.”</p><p>That is not enough.</p><p>A model that merely returns a 0 or a 1 is a black box to the team responsible for making decisions. The retention manager cannot call a customer and say, “Our model says you’re going to leave.” They need to understand the *why* in order to take action.</p><p>That is exactly what led me to build this project: a system that not only predicts churn but also explains it in natural language.</p><h3><strong>The Architecture: Six Layers Working Together</strong></h3><p>The central idea is simple yet powerful. Instead of returning only a probability, the system combines three components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*4khLaSjGG6DqOsJKEzXaCA.png" /></figure><h3><strong>Layer 1 — The ML Model</strong></h3><p>The model is a classifier trained on the classic Telco Customer Churn dataset, serialized with joblib and served via FastAPI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*NDxZRXVSRBIsWECShYNWNQ.png" /></figure><h3><strong>Layer 2 — RAG: Domain Context Before the LLM</strong></h3><p>Here is the most important design decision of the project.</p><p>A naive solution would be to pass the customer data directly to the LLM and ask it to provide an explanation. The problem: the LLM would fabricate patterns or generalize incorrectly.</p><p>The solution is RAG (Retrieval-Augmented Generation): before calling the LLM, we retrieve relevant context from a knowledge base specialized in churn.</p><p>The knowledge base is a text file containing real-world patterns from the domain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*ytUHfBhNcHSR91fvaWoMWQ.png" /></figure><p>That text is converted into embeddings using sentence-transformers/all-MiniLM-L6-v2 and stored in a FAISS index:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*NYUe13Dtp4ZDl50H9YYunQ.png" /></figure><p>At inference time, a query is constructed using the client’s data, and the 3 most relevant fragments are retrieved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*lOgvC4CSceEQ-AX0PSP91A.png" /></figure><p>This ensures that the LLM reasons based on actual domain knowledge, rather than general assumptions.</p><h3><strong>Layer 3 — The Explaining LLM</strong></h3><p>With the prediction and retrieved context, a structured prompt is constructed, and the LLM is called via the Groq API:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*-dhe6ro0Uc3pIMHMb_dHpw.png" /></figure><p>The system prompt has very specific restrictions, and this is crucial:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*DqKIm49naVTEM6ZHgZPq7w.png" /></figure><p>This discipline in prompting is what separates a useful explanation from a costly hallucination. The LLM receives real data plus retrieved context, and produces a coherent and actionable explanation.</p><h3>Deployment: Docker + HugingFace</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*0ev6stwB1nmCcNPUBAR5nQ.png" /></figure><h3><strong>Lessons Learned</strong></h3><p>1. RAG isn’t just for chatbots. In this context, RAG serves to enrich the explanation of an ML model using structured domain knowledge. It is a pattern applicable to any prediction system where interpretability matters.</p><p>2. System prompts require explicit constraints. Without rules such as “DO NOT fabricate information” or “DO NOT mention missing variables,” the LLM tends to overgeneralize and contradict actual customer data. Negative constraints are just as important as positive ones.</p><p>3. Predicting without explaining holds little value in a real-world production environment. A customer retention team requires concrete arguments to take action. A churn probability score is merely a number; an explanation articulated in natural language is a working tool.</p><h3><strong>What’s Next?</strong></h3><p>-Add SHAP for quantitative explainability, complementing the narrative explanation.</p><p>-Include model metrics (AUC-ROC, precision, recall) in the README.</p><p>-Implement an improved UI featuring a prediction history.</p><p>-Evaluate whether to replace the static vector store with a dynamic one that learns from new patterns.</p><p>-Automate the delivery of promotional messages via WhatsApp or email using Make, Zapier, or n8n.</p><p>-Utilize function calling to query the customer database and enhance the LLM’s responses.</p><p>-Employ dashboards connected to the database to facilitate business decision-making, given the continuous influx of data.</p><p>-Implement monitoring and version control via GitHub, as the ML model may degrade over time.</p><p>-Establish guardrails to detect instances where the LLM contradicts the model’s data.</p><p>-Detect new customers who lack sufficient historical data to enable confident predictions.</p><p>The application is available in <a href="https://le093-asistente-ia-churn-prediction.hf.space/"><em>https://le093-asistente-ia-churn-prediction.hf.space/</em></a></p><p>Any feedback is welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1964a5097948" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Customer Churn with FastAPI and Docker: From Notebook to Production]]></title>
            <link>https://medium.com/@le0.d4ta.d3v/predicting-customer-churn-with-fastapi-and-docker-from-notebook-to-production-8b51fbdba967?source=rss-61245492e698------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b51fbdba967</guid>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[machine-learning-engineer]]></category>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Leonardo]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 22:26:18 GMT</pubDate>
            <atom:updated>2026-04-01T22:40:41.777Z</atom:updated>
            <content:encoded><![CDATA[<h3>A real problem</h3><p>A dataset containing thousands of customers has many uses, one of which is finding solutions to customer churn. For a company, finding ways to retain customers before they leave is very important. Sometimes these solutions remain just ideas jotted down in a notebook; that’s not very helpful, so it’s necessary to implement them through an application that’s compatible with different devices and versions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*_yViKIQtC-rG8YDOYdNdJA.png" /></figure><h3>Machine learning: 87% recall rate</h3><p>I decided to prioritize an 87% recall rate because, in the world of churn, identifying customers who might leave — or who might not — reduces the cost of contacting those who won’t leave. It wasn’t necessary to use more complex ML models like CatBoost, XGBoost, or a neural network, since logistic regression delivered optimal results.</p><p>I serialized the model using MLflow, ran various tests, and identified the best prediction. Then I imported the JobLib library in PKL format, which allows me to save the prediction results to a file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*taft54IUoJZHFwQaArOUTg.png" /></figure><h3><strong>Exit the Notebook</strong></h3><p>A Jupiter Notebook model works great on your computer, but I wanted to take it beyond that. That’s why I used FastAPI with HTTP requests, which allows me to connect my ML predictive model results to a web-based graphical interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*niwlua9VNabT_mk_c85vRw.png" /></figure><h3><strong>Docker and the Magic of Containerization</strong></h3><p>It runs on our computer, but not on others. To avoid that, I wrapped the entire application in Docker. That way, it doesn’t matter whether you’re on Linux, Windows, or in the cloud. Then I uploaded my container to Docker Hub to make my application available online.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*niwlua9VNabT_mk_c85vRw.png" /></figure><h3><strong>Upload the application to Render</strong></h3><p>Using the image uploaded from Docker Hub, we upload the file to Render.</p><p><a href="https://churnshield-api-p1gs.onrender.com/">https://churnshield-api-p1gs.onrender.com/</a></p><p><a href="https://churnshield-api-p1gs.onrender.com/">ChurnShield</a></p><h3>GitHub</h3><p>If you’d like to see the full project, visit <a href="https://github.com/Lev-Coding-py/Salida-de-clientes-App">https://github.com/Lev-Coding-py/Salida-de-clientes-App</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*eMvkPYBvsAhJ5SA1Ym0ZwA.png" /></figure><h3><strong>Possible Improvements</strong></h3><p>-ML Model Versioning: Implement a versioning structure (v1, v2, v3) to track which version is in use or to deploy new versions, since in real-world scenarios data changes and the models need to be retrained.</p><p>-An interface that allows me to see the number of at-risk customers and smart dashboards.</p><p>-GitHub (CI/CD) so that automatic tests run every time code is uploaded.</p><p>-Use a better predictive model and apply the SHAP method to assess the influence of variables.</p><ul><li>Scale the project and migrate to the cloud.</li><li>-Use Streamlit, which lets you turn your Python scripts into interactive dashboards in minutes. However, it doesn’t offer complete flexibility or scalability.</li><li>- Connect your FastAPI API to n8n so that when the model detects a risk of a leak, an automated workflow is triggered — specifically, an email is sent to alert the sales team.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b51fbdba967" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Notebook to Production: The Complete Machine Learning and Deep Learning Lifecycle]]></title>
            <link>https://medium.com/@le0.d4ta.d3v/from-notebook-to-production-the-complete-machine-learning-and-deep-learning-lifecycle-81765c418723?source=rss-61245492e698------2</link>
            <guid isPermaLink="false">https://medium.com/p/81765c418723</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[machine-learning-engineer]]></category>
            <dc:creator><![CDATA[Leonardo]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 00:41:31 GMT</pubDate>
            <atom:updated>2026-03-26T00:59:29.066Z</atom:updated>
            <content:encoded><![CDATA[<p>Some projects remain in platforms like Jupyter Notebooks, Google Colab, Visual Studio Code, or other application development tools. However, they never make it beyond those platforms. This happens because building the model is the visible part, but turning it into a real application requires a different set of skills that aren’t always found in the same person.</p><h3><strong>Why do so many projects end up just sitting in my notebook?</strong></h3><p>It’s a common scenario: the model works perfectly in a local environment, the results are promising, but the project never makes it out of Jupyter Notebook, Google Colab, or VS Code. This isn’t due to a lack of technical talent, but because building the model and deploying it require entirely different skills that rarely coexist in the same person.</p><p>Deploying a model means bringing it to life: making it work autonomously, accessible to people without technical knowledge, and continuously generating value.</p><h3>Data Scientist — The one who builds the model</h3><p>A data scientist who uses machine learning to solve problems in banking, finance, and healthcare, such as customer churn, news classification, fraud detection, and automation. Deep learning is not commonly used, as most problems are solved using traditional models.</p><h3><strong>Classic Models vs. Deep Learning</strong></h3><p>Deep learning is not commonly used, as most problems are solved using logistic regression, random forests, and XGBoost. These models are preferred because they train faster and are interpretable. A bank cannot deny a loan without justifying its decision, and the SHAP method allows it to answer that question clearly.</p><p>Deep learning comes into play when working with unstructured data such as images and videos, and when the relationships between the input variables and the target are very complex or difficult for the human eye to understand. Its most common applications include classifying thousands of news articles with or without labels, recommendation systems with thousands of users, and personalized chatbots. The most widely used libraries are Scikit-Learn for classical models, and PyTorch and TensorFlow for Deep Learning.</p><h3><strong>Why is it important to open a Notebook?</strong></h3><p>Un proyecto puede funcionar muy bien en tu computadora y cuando lo compartes por internet hay problemas de versión de Python de librerías Scikit-learn, Pytorch, TensorFlow, sistemas operativos Linux, Windows, MacOS. Cuando una despliega una aplicación facilita su uso para personas las personas que no tienen conocimientos técnicos como un gerente, un analista, clientes o hasta un trabajador de otro campo. De esta manera el modelo trabaja sin que estes tu presente, es decir, que se ejecuta cada día/ hora sin la necesidad de tocar el proyecto. Sin embargo, este debe ser monitoreado o observado cada periodo. Un modelo local no puede atender miles de solicitudes a la vez ni integrarse con los sistemas de la empresa. Y si el proyecto solo existe en una computadora, cualquier fallo del equipo o cambio de personal puede significar perderlo por completo.</p><h3>Machine Learning Engineer — The person who deploys the model to production</h3><p>The ML Engineer takes the work of the Data Scientist and turns it into scalable, deployable software via a web or mobile application. Their work includes automating the input of raw data, its transformation, and the final prediction that the user consumes. They automate the prediction and data flow so that it can be used by customers and employees within the application. To connect the data, they use FastAPI, which allows a server and your notebook to be connected via a web or mobile page, thereby automating the data flow for consumption by both technical and non-technical users. However, if scalability is required for any version of libraries or operating systems, Docker is often used to ensure compatibility. This container is deployed on cloud servers such as AWS, Google Cloud, or Azure, or on on-premises servers when industry regulations require it.</p><p>One application for the Machine Learning Engineer is for the Data Scientist to create a predictive model in a notebook to forecast customer churn, host it on a website, use FastAPI and Docker, and automate the results so they can be viewed by any employee who needs the information via queries or dashboards, as well as to reach out to customers who are about to churn via WhatsApp or phone calls.</p><h3>MLOps — Keeping the model alive</h3><p>MLOps continuously monitors performance. Because data is constantly changing — requiring the model to be retrained on an ongoing basis (data drift) — training is periodically refreshed. To maintain an organized training history, new versions are tested and deployed without interrupting service. Additionally, it logs each version of the model using MLflow and Git/GitHub to track which data was used and what results it produces. This allows each version to be used based on the application’s status or to test new versions.</p><h3><strong>No-Code Tools</strong></h3><p>Platforms like Google AutoML, DataRobot, and Azure ML Studio allow you to build models visually without writing code. They’re useful for rapid prototyping or simple problems, but they have clear limitations as projects grow, since they offer limited customization and incur high costs at scale.</p><h3><strong>Conclusion</strong></h3><p>All three roles are important because each plays a vital part in a company. Without the data scientist, there is no model; without the ML engineer, there is no production or deployment; and without MLOps, there is no long-term sustainability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*CQeRZG-jaATP0-arkrqScg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81765c418723" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative AI, the data seems real, but is it?]]></title>
            <link>https://medium.com/@le0.d4ta.d3v/generative-ai-the-data-seems-real-but-is-it-80bfd3a5e115?source=rss-61245492e698------2</link>
            <guid isPermaLink="false">https://medium.com/p/80bfd3a5e115</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Leonardo]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 22:34:41 GMT</pubDate>
            <atom:updated>2026-01-15T22:47:23.648Z</atom:updated>
            <content:encoded><![CDATA[<p>Generative artificial intelligence has learned to produce data with unsettling ease. Plausible time series, coherent physical configurations, images that respect complex statistical patterns. At first glance, everything looks right.</p><p><strong>And what if appearance deceives?</strong></p><p>In science, engineering, and data analysis, generating data is not enough.<br> Every new data point must prove that it belongs to the same world as real data.</p><h3>Generating Is Not Validating</h3><p>Generative models learn distributions. They do not learn truth.</p><p>An autoencoder, a VAE, or a diffusion model can produce data that fits the training set visually and statistically, but that does not guarantee it respects:</p><ul><li>physical laws</li><li>causal relationships</li><li>theoretical constraints</li></ul><p>A generated data point can be plausible and still be impossible.</p><p>That is why generative AI does not close the knowledge loop.<br> It only accelerates it.</p><h3>The Risk of Statistical Realism</h3><p>One of the greatest dangers of generated data is its superficial realism.<br> Correct histograms. Consistent means and variances. Apparently well-formed correlations.</p><p>Yet many critical properties live in deeper layers:</p><ul><li>higher-order dependencies</li><li>extreme or rare behaviors</li><li>theoretical invariants</li></ul><p>If these are not examined, the model may be learning an elegant caricature of reality.</p><h3>Validating Against Statistical Models</h3><p>The first filter must be statistical.</p><p>Generated data should be subjected to:</p><ul><li>hypothesis testing</li><li>distributional comparisons</li><li>correlation and autocorrelation analysis</li><li>detection of structural outliers</li></ul><p>It is not enough for data to “look similar.”<br> It must behave the same under the same analyses.</p><h3>Validating Against Theory</h3><p>In scientific domains, theoretical validation is non-negotiable.</p><p>If generated data violates:</p><ul><li>conservation laws</li><li>symmetries</li><li>known functional relationships</li></ul><p>then the problem is not the theory. It is the generative model.</p><p>AI can approximate complex functions, but it has no intrinsic understanding of causality or physical principles. That responsibility remains human.</p><h3>Validating Against the Literature</h3><p>The third pillar is scientific literature.</p><p>Generated data must be compared against:</p><ul><li>published results</li><li>accepted ranges</li><li>reported trends</li></ul><p>Consistency with prior work is not conservatism.<br> It is epistemological grounding.</p><p>Without this contrast, AI risks producing knowledge that is elegant, self-contained, and disconnected from reality.</p><h3>The Proper Role of Generative AI</h3><p>Generative AI should not be treated as a source of truth, but as a <strong>hypothesis-generating machine</strong>.</p><p>It proposes scenarios. Suggests configurations. Explores regions of the data space.</p><p>But validation remains an external process:</p><ul><li>statistical</li><li>theoretical</li><li>experimental</li></ul><p>When this balance is respected, generative AI does not replace the scientific method.<br> It strengthens it.</p><p>Ultimately, generative models are constrained by the data they learn from. They depend on real or simulated data to infer patterns, but they do not define reality itself. Without continuous grounding in empirical evidence and established theory, generative AI can only approximate what is known, not determine what is true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*nxqGwRt_-qG6M98yAYj5Cg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80bfd3a5e115" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Artificial Intelligence transforms thousands of news items into actionable insights: Automatic…]]></title>
            <link>https://medium.com/@le0.d4ta.d3v/how-artificial-intelligence-transforms-thousands-of-news-items-into-actionable-insights-automatic-4d4fdec891d3?source=rss-61245492e698------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d4fdec891d3</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[natural-language-process]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[power-bi]]></category>
            <dc:creator><![CDATA[Leonardo]]></dc:creator>
            <pubDate>Sat, 13 Dec 2025 18:05:26 GMT</pubDate>
            <atom:updated>2025-12-13T18:05:26.875Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How Artificial Intelligence transforms thousands of news items into actionable insights: Automatic Classification, Affinity Clustering, and Dashboards for decision-making.</strong></h3><p>There are days with positive, negative, neutral, or other hidden but very important news. How can we efficiently understand this immense flow of thousands of data points?</p><p>I’ll tell you how to build a system that reads these headlines, interprets them, and organizes them to make better decisions. A project that combines artificial intelligence, SQL, Python, clustering, and natural</p><h3><strong>1.News dataset</strong></h3><p>It all started with a dataset containing over a million news articles, complete with dates and headlines. But how could I tell which news stories were important and which weren’t?</p><p>That’s how the preprocessing and sentiment analysis began.</p><pre>from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer<br><br>analyzer = SentimentIntensityAnalyzer()<br><br>def vader_sentiment(text):<br>    scores = analyzer.polarity_scores(text)<br>    return scores[&quot;compound&quot;]<br><br>data[&quot;vader_compound&quot;] = data[&quot;headline_text&quot;].astype(str).apply(vader_sentiment)<br><br>def vader_label(score):<br>    if score &gt;= 0.05:<br>        return &quot;positivo&quot;<br>    elif score &lt;= -0.05:<br>        return &quot;negativo&quot;<br>    else:<br>        return &quot;neutral&quot;<br><br>data[&quot;vader_label&quot;] = data[&quot;vader_compound&quot;].apply(vader_label)</pre><p>At the beginning, I used the VADER library, which automatically classifies words based on assigning weight to each word and, accordingly, providing a classification without the need for a pre-established label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*LkuN5_bLw5vQq926AyTBrw.png" /><figcaption>VADER clasification</figcaption></figure><h3><strong>2. How I used clustering to find hidden emotions and group them together.</strong></h3><p>VADER had already classified the words as positive, negative, or neutral, but to discover these groups of related news items, I used clustering to group them according to common themes</p><pre>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.cluster import KMeans<br>vectorizer = TfidfVectorizer(max_features=500, stop_words=&#39;english&#39;)<br>X = vectorizer.fit_transform(data[&#39;headline_text&#39;])<br>for i in range(3):<br>    print(f&quot;\n--- Cluster {i} ---&quot;)<br>    cluster_i = data[data[&#39;cluster&#39;] == i][&#39;headline_text&#39;].head(5)<br>    for idx, texto in enumerate(cluster_i, 1):<br>        print(f&quot;{idx}: {texto}&quot;)<br><br><br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*saIzZDZVjs98zYDBN0LCSQ.png" /><figcaption>Cluster Clasification</figcaption></figure><h3><strong>3. When SQL is useful and applicable</strong></h3><p>Design a query that combines sentiment, clustering, business rules, and impacts. The result is an automatic classification called Thematic Priority and a Recommended Action that turns data into decisions.</p><pre>select * from noticias_analizadas_sin_keywords;<br><br>SELECT<br>  <br>    publish_date,<br>    headline_text,<br>    vader_compound,<br>    vader_label,<br>    cluster,<br>    <br>   <br>    CASE<br>       <br>        WHEN vader_label = &#39;negativo&#39; AND cluster = 1 THEN &#39;RIESGO_FINANCIERO_LEGAL&#39;<br>        <br>        <br>        WHEN vader_label = &#39;positivo&#39; AND cluster = 2 THEN &#39;OPORTUNIDAD_PUBLICIDAD_MARCA&#39;<br>        <br>       <br>        WHEN vader_compound &gt;= 0.5 THEN &#39;ALTO_IMPACTO_GENERAL_POS&#39;<br>        WHEN vader_compound &lt;= -0.5 THEN &#39;ALTO_IMPACTO_GENERAL_NEG&#39;<br>        <br>       <br>        WHEN vader_label = &#39;negativo&#39; THEN &#39;RIESGO_MEDIO_MONITOREO&#39;<br>        <br>       <br>        ELSE &#39;LECTURA_ESTANDAR&#39;<br>    END AS PrioridadTematica,<br><br>    CASE<br>        WHEN vader_label = &#39;negativo&#39; AND cluster = 1 THEN &#39;Reacción Inmediata / Consulta Legal&#39;<br>        WHEN vader_label = &#39;positivo&#39; AND cluster = 2 THEN &#39;Reforzar Marketing en Zona/Tema&#39;<br>        WHEN vader_compound &lt;= -0.5 THEN &#39;Alerta Ejecutiva de Riesgo&#39;<br>        WHEN vader_compound &gt;= 0.5 THEN &#39;Aprovechar Tendencia Positiva&#39;<br>        WHEN vader_label = &#39;negativo&#39; THEN &#39;Monitoreo de Impacto Sectorial&#39;<br>        ELSE &#39;Archivo / Uso Informativo&#39;<br>    END AS AccionRecomendada<br><br>FROM<br>    noticias_analizadas_sin_keywords;<br><br></pre><h3><strong>4. Priority Map</strong></h3><p>With these attributes calculated, each news item occupies a clear place on the strategic board:</p><p>- Financial or Legal Risk</p><p>- Moderate Monitorable Risk</p><p>- High Overall Positive or Negative Impact</p><p>- Advertising and Branding Opportunity</p><p>- Standard Reading/Archive</p><p>A radar was implemented to be used in analysis to identify the most significant trends and make decisions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*H7wiAl02imVZJ0hKUMybVw.png" /><figcaption>RADAR</figcaption></figure><h3><strong>5. Daily sentiment analysis</strong></h3><p>I then built a visualization of the daily emotional rhythm.</p><p>A graph showing how negative, neutral, and positive news rises and falls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*Ja-L-iRSvSLdLXM-ADdWlA.png" /><figcaption>Sentiment</figcaption></figure><h3><strong>6. A dashboard where data is transformed into decisions.</strong></h3><p>Once the calculations were made, a dashboard was implemented in Power BI where an analyst can navigate without losing focus and make positive and crucial decisions.</p><p>Summary panel:</p><p>• Total news items</p><p>• High-impact alerts</p><p>• Marketing opportunities</p><p>• Distribution by sentiment</p><p>Thematic panel:</p><p>• Priority radar</p><p>• Trends</p><p>• Classification by suggested actions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*jVRupCx8plQww3d12ylbQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*AMXgxwnW8gQNC6M9N0rasw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*9K6dRtP21q9Kie_yaAWWPQ.png" /></figure><h3><strong>7.Conclusions</strong></h3><p>The system not only classifies and groups data, but also converts it into actionable decisions. A piece of news takes on value and becomes an action, opportunity, or trend to reinforce.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d4fdec891d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How SQL drives artificial intelligence in businesses]]></title>
            <link>https://medium.com/@le0.d4ta.d3v/how-sql-drives-artificial-intelligence-in-businesses-c1178f1538a6?source=rss-61245492e698------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1178f1538a6</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Leonardo]]></dc:creator>
            <pubDate>Thu, 27 Nov 2025 18:41:03 GMT</pubDate>
            <atom:updated>2025-11-27T18:41:03.200Z</atom:updated>
            <content:encoded><![CDATA[<p>Artificial intelligence has become the driving force behind digital transformation in companies. It has received a lot of attention in the field of technology, but before modeling, AI must prepare its data well. And that’s where SQL comes in as an important tool.</p><p>It is believed that SQL only stores information: it cleans, transforms, structures, and sorts data.<br>We explore how to drive AI projects in various fields of technology.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*81IXmw3PB4M7zFL9jH1dvA.png" /></figure><ol><li><strong>Because SQL is the program behind an AI technology application.</strong></li></ol><p>When we talk about artificial intelligence, many people associate it with Python, neural networks, and machine learning. This is true, but in order to use these programs, the data must be clean and organized.<br>SQL manages millions of rows of data, duplicates, inconsistencies, and missing values. It performs queries with join, where, and begin statements, which facilitates work and decision-making. It also integrates its exploration with programs such as Python, Power BI, Azure, etc.</p><p><strong>2. Querying data in SQL for AI</strong></p><p>Before using an AI-based tool, data must be cleaned so that the AI can work much better. Values that are far from the average, duplicates, errors, and other issues have a negative impact, as the AI receives information but does not have the judgment to tell you if it is right or wrong.</p><p>2.1 Remove duplicates</p><pre>WITH CTE AS (<br>    SELECT *, ROW_NUMBER() OVER(PARTITION BY id ORDER BY id) AS rn<br>    FROM ventas<br>)<br>DELETE FROM CTE WHERE rn &gt; 1;</pre><p>Remove duplicate records, keeping only one per ID.</p><p>2.2 Handling null values</p><pre>UPDATE clientes<br>SET ingreso_mensual = 0<br>WHERE ingreso_mensual IS NULL;</pre><p>Replaces missing values with a valid number for analysis or modeling.</p><p>2.3 Outlier Detection</p><pre>SELECT *<br>FROM transacciones<br>WHERE monto &gt; (SELECT AVG(monto) + 3 * STDEV(monto) FROM transacciones);</pre><p>Identify extreme values using the statistical rule of 3 standard deviations.</p><p>3. SQL is more efficient for querying large-scale data.</p><p>Unlike other programs such as Python and R, this one has greater memory and establishes security for millions or billions of data points.</p><p>4. Transform data for an application</p><p>Data is useful when you give it an application; it is not useful without any necessary queries. Here are some examples:</p><p>4.1 Categorical Variables</p><pre>SELECT <br>    CASE <br>        WHEN genero = &#39;M&#39; THEN 1 <br>        WHEN genero = &#39;F&#39; THEN 0 <br>    END AS genero_binario<br>FROM clientes;</pre><p>Convert categories into numbers for use in models.</p><p>4.2 Aggregation for a prediction.</p><pre>SELECT <br>    cliente_id,<br>    COUNT(*) AS compras_totales,<br>    SUM(monto) AS monto_total,<br>    AVG(monto) AS ticket_promedio<br>FROM transacciones<br>GROUP BY cliente_id;</pre><p>Create variables that summarize customer behavior, which is key to prediction.</p><p>5. Real-world cases driven by SQL for AI</p><p>5.1 Fraud Detection</p><pre>SELECT <br>    transaccion_id,<br>    monto,<br>    ubicacion,<br>    hora,<br>    CASE WHEN monto &gt; (SELECT AVG(monto) FROM transacciones) THEN 1 ELSE 0 END AS monto_sospechoso,<br>    CASE WHEN ubicacion &lt;&gt; ubicacion_habitual THEN 1 ELSE 0 END AS ubicacion_inusual,<br>    CASE WHEN hora NOT BETWEEN 8 AND 22 THEN 1 ELSE 0 END AS hora_riesgo<br>FROM transacciones;</pre><p>Generates features (suspicious amount, unusual location, risky time) that an AI model can then use to predict fraud.</p><p><strong>5.2 Segmentacion de Clientes</strong></p><pre>SELECT <br>    cliente_id,<br>    SUM(monto) AS gasto_total,<br>    COUNT(*) AS frecuencia,<br>    AVG(monto) AS ticket_promedio,<br>    MAX(fecha) AS ultima_compra,<br>    DATEDIFF(DAY, MAX(fecha), GETDATE()) AS dias_desde_ultima_compra<br>FROM transacciones<br>GROUP BY cliente_id;</pre><p>Genera variables como gasto total, frecuencia y recencia.</p><p>Estas variables son usadas por la IA para segmentar clientes</p><p>6. A database such as SQL or similar will be key in the era of artificial intelligence.</p><p>-Companies have data.<br>-AI needs clean, ready-to-use data.<br>-It is scalable.<br>-It is a tool used by administrators, economists, and programmers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1178f1538a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>