<?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 Siva Ganta on Medium]]></title>
        <description><![CDATA[Stories by Siva Ganta on Medium]]></description>
        <link>https://medium.com/@sivaramakrishnaganta1234?source=rss-97a8b112b94a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SinImu4AAFK9hx-GbsfHCg.png</url>
            <title>Stories by Siva Ganta on Medium</title>
            <link>https://medium.com/@sivaramakrishnaganta1234?source=rss-97a8b112b94a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:15:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sivaramakrishnaganta1234/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[Building a RAG-Based Fraud Investigation System with SHAP guided vector search and Dual Retrieval]]></title>
            <link>https://medium.com/data-science-collective/building-a-rag-based-fraud-investigation-system-with-shap-guided-vector-search-and-dual-retrieval-af86c98a4f94?source=rss-97a8b112b94a------2</link>
            <guid isPermaLink="false">https://medium.com/p/af86c98a4f94</guid>
            <category><![CDATA[fraud-detection]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Siva Ganta]]></dc:creator>
            <pubDate>Fri, 28 Aug 2026 12:33:54 GMT</pubDate>
            <atom:updated>2026-08-28T12:33:54.689Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a RAG-Based Fraud Investigation System with SHAP and Dual Retrieval</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*immDMUbJCDvv1tT_E15WqQ.png" /></figure><p><em>How feature attribution can turn RAG from “retrieve something similar” into “retrieve the evidence that actually explains this decision.”</em></p><p>Most RAG systems start the same way.</p><p>Embed the documents. Embed the query. Run a nearest-neighbor search. Put the top results into a prompt. Ask the language model to write an answer.</p><p>For a documentation chatbot, that simple pattern can work surprisingly well. But for a high-stakes decision workflow — fraud investigation, credit review, insurance claims, identity risk, compliance review — it often fails quietly.</p><p>The system retrieves <em>something</em> similar. The answer sounds plausible. The demo looks good.</p><p>But the retrieved evidence may not be relevant to the actual decision.</p><p>In fraud, that difference matters. A transaction can be similar to another transaction in many superficial ways: merchant category, amount range, time of day, channel, device type, geography, or customer segment. But the real question is not simply:</p><blockquote>What looks similar?</blockquote><p>The better question is:</p><blockquote>What was suspicious for the same reasons?</blockquote><p>That is where SHAP-guided retrieval and Dual-RAG become useful.</p><h3>The problem with naive retrieval</h3><p>Imagine a transaction under review with fifty features.</p><p>A standard retrieval system might embed the full transaction record and search historical cases for the nearest neighbors. That means the search is influenced by everything in the record: amount, channel, merchant category, device, location, account age, payment history, address behavior, velocity signals, and many other fields.</p><p>The problem is that most of those features may have very little to do with why the model scored this transaction as risky.</p><p>A nearest-neighbor search over the full record may return cases that share a merchant category or amount band but were flagged for completely different reasons. The generator then writes a report grounded in evidence that looks related but does not actually explain the model’s decision.</p><p>That is the dangerous failure mode:</p><blockquote>The explanation is grounded, but grounded in the wrong evidence.</blockquote><p>The fix is to stop treating every feature as equally important.</p><h3>SHAP turns explainability into a retrieval signal</h3><p>Feature attribution methods such as SHAP are usually used after a model prediction to explain which features pushed the score up or down.</p><p>For a single fraud score, SHAP might show that the major risk drivers were:</p><ul><li>transaction amount is unusually high for this customer;</li><li>shipping address was recently added;</li><li>payment instrument has high recent velocity;</li><li>device location is far from the customer’s historical region;</li><li>customer account age is very new.</li></ul><p>That ranked list is useful for explaining the model.</p><p>But it is also useful for retrieval.</p><p>The key insight is this:</p><blockquote>SHAP does not only tell us why the model scored the record. It tells us what the retriever should care about.</blockquote><p>If address age, amount velocity, and geo-distance are the main drivers of the current score, then the case retriever should prioritize historical cases where those same patterns mattered. It should not waste attention on features that were present but irrelevant.</p><p>In other words:</p><blockquote>The explanation becomes the retrieval plan.</blockquote><h3>Three practical ways to build SHAP-guided retrieval</h3><p>There is no single implementation that fits every system. The right design depends on the feature representation, latency budget, and how your case history is stored. But the pattern usually falls into one of three approaches.</p><h3>1. Attribution-weighted retrieval</h3><p>In attribution-weighted retrieval, each feature’s contribution to the query representation is scaled by the magnitude of its attribution.</p><p>High-impact features dominate the query vector. Low-impact features contribute less.</p><p>This is useful when you already represent cases as structured embeddings and want retrieval to remain continuous rather than rule-based.</p><p>Example intuition:</p><ul><li>amount_velocity had a strong positive SHAP value → high weight</li><li>new_shipping_address_age had a strong positive SHAP value → high weight</li><li>merchant_category had little contribution → low weight</li></ul><p>The search becomes more aligned with the actual reasons for the risk score.</p><h3>2. Top-k driver masking</h3><p>In top-k driver masking, the query is built only from the top attributed features.</p><p>Instead of embedding the full record, the system builds a focused representation using only the most important drivers.</p><p>This can improve relevance when the full record contains many noisy or weakly useful features. It also makes retrieval easier to explain because the search was explicitly based on a small set of drivers.</p><p>Example:</p><blockquote>Retrieve cases where the dominant risk pattern involved high amount velocity, newly added address, and large geo-distance.</blockquote><h3>3. Filter-then-rank retrieval</h3><p>In filter-then-rank retrieval, top attributed features are used as metadata filters or query constraints before ranking.</p><p>For example:</p><ul><li>filter to cases where address_age was a dominant risk signal;</li><li>filter to cases from the same fraud channel;</li><li>filter to recent cases from the last 30 or 90 days;</li><li>rank the filtered set using vector similarity or a reranker.</li></ul><p>This is often the most production-friendly design because it combines structured fraud logic with semantic retrieval.</p><p>A practical implementation may use all three: filter first, build a weighted query, then rerank the retrieved cases.</p><h3>Architecture: SHAP-guided Dual-RAG</h3><p>The architecture becomes more than a simple vector search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CDJm04ykf6ZNUEFI1nY2FA.png" /></figure><p><em>Figure 1 — A production-style SHAP-guided Dual-RAG architecture. The model produces the score, SHAP identifies the decision drivers, the query planner converts them into retrieval intent, and two specialized retrievers collect complementary evidence before the report is generated and governed.</em></p><p>The important components are:</p><ol><li><strong>Decision record</strong> — the transaction, claim, application, or event under review.</li><li><strong>Detection model</strong> — the existing ML model that produces the risk score.</li><li><strong>SHAP explainer</strong> — the local explanation layer that identifies top decision drivers.</li><li><strong>Retrieval orchestrator</strong> — the component that converts top drivers into filters, weights, namespaces, and query text.</li><li><strong>RAG-1: Case retriever</strong> — retrieves comparable historical cases using attribution-guided search.</li><li><strong>RAG-2: Knowledge retriever</strong> — retrieves policies, playbooks, definitions, and workflow rules.</li><li><strong>Evidence assembler</strong> — deduplicates, ranks, and formats evidence for the prompt.</li><li><strong>LLM generator</strong> — creates a structured explanation or investigation report.</li><li><strong>Validator and audit logger</strong> — checks grounding, records evidence, and stores the final decision trail.</li></ol><p>This design keeps the detection model separate from the explanation layer. RAG does not replace the model. It makes the post-model decision workflow more useful.</p><h3>Why one retriever is not enough</h3><p>A common mistake is putting everything into one vector store: historical cases, policy documents, analyst notes, rule descriptions, definitions, and investigation playbooks.</p><p>That sounds convenient, but these objects serve different purposes.</p><p>Historical cases answer:</p><blockquote>What happened in similar situations?</blockquote><p>Policies and playbooks answer:</p><blockquote>What should we do according to the governing rules?</blockquote><p>Those are not the same question.</p><p>If you mix them into one retriever, policy documents can pollute case retrieval, and historical cases can drown out the rule the analyst actually needs. They also have different update cadences. Case outcomes may update daily or hourly. Policy documents may change less frequently but require strict version control.</p><p>Dual-RAG separates the jobs.</p><h3>RAG-1: Case retrieval for analogical evidence</h3><p>The case retriever searches historical decisions.</p><p>Its job is to surface comparable examples:</p><ul><li>confirmed fraud cases;</li><li>confirmed legitimate cases;</li><li>false positives;</li><li>chargeback outcomes;</li><li>analyst-reviewed cases;</li><li>cases from a recent fraud wave;</li><li>cases sharing the same dominant risk drivers.</li></ul><p>This is where SHAP guidance is most valuable.</p><p>Instead of asking for cases similar to the entire transaction, RAG-1 asks for cases similar to the <em>reason the transaction was flagged</em>.</p><p>The output should not be a random list of nearest neighbors. It should be an evidence set that tells the analyst:</p><ul><li>how many similar cases were fraud;</li><li>how many were legitimate;</li><li>what signals they shared;</li><li>how recent they were;</li><li>how they were resolved;</li><li>whether the current case has any important differences.</li></ul><p>This turns case retrieval into analogical evidence.</p><h3>RAG-2: Knowledge retrieval for governing rules</h3><p>The knowledge retriever searches a different index.</p><p>Its job is to retrieve the rules and context that govern the decision:</p><ul><li>fraud policies;</li><li>review playbooks;</li><li>step-up verification rules;</li><li>operational procedures;</li><li>risk definitions;</li><li>model documentation;</li><li>compliance guidance;</li><li>escalation criteria.</li></ul><p>RAG-2 should know which namespace or policy area to search based on the case context. A card-testing pattern should not retrieve the same policy sections as address manipulation, return abuse, synthetic identity, or account takeover.</p><p>This layer helps the report answer:</p><blockquote>What does the business or policy say we should do?</blockquote><p>That makes the explanation more defensible.</p><h3>How the retrieval plan is built</h3><p>The most important design artifact in this system is the retrieval plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPz6PdXRi5oUiZEYFJd9pA.png" /></figure><p><em>Figure 2 — A practical retrieval planner. Top SHAP drivers are converted into filters, feature weights, query text, and reranking signals before the system retrieves evidence from the case index.</em></p><p>A retrieval plan may include:</p><ul><li><strong>top drivers</strong> from SHAP;</li><li><strong>driver groups</strong> such as velocity, address, identity, payment, device, or geo-distance;</li><li><strong>hard filters</strong> such as channel, time window, fraud type, or decision outcome;</li><li><strong>feature weights</strong> for embedding similarity;</li><li><strong>query text</strong> for semantic search;</li><li><strong>reranking rules</strong> to prioritize cases with the same dominant risk pattern;</li><li><strong>diversity constraints</strong> to include both fraud and legitimate counterexamples.</li></ul><p>For example, suppose the current case has these top drivers:</p><ul><li>high amount velocity;</li><li>new shipping address;</li><li>large distance from historical region;</li><li>device not previously trusted.</li></ul><p>The retrieval plan might ask RAG-1 for:</p><blockquote>Recent historical cases where amount velocity, new address behavior, and geo-distance were dominant risk drivers, with both confirmed fraud and confirmed legitimate outcomes.</blockquote><p>Then it might ask RAG-2 for:</p><blockquote>Policies and playbook sections related to high-risk transactions involving new addresses, location anomalies, and step-up verification.</blockquote><p>The result is far more useful than a generic nearest-neighbor search.</p><h3>What the final report should look like</h3><p>The generated report should be structured, not free-form.</p><p>A useful report might include:</p><h3>Decision summary</h3><ul><li>Risk score</li><li>Recommended action</li><li>Short explanation of the main reason</li></ul><h3>Model drivers</h3><ul><li>Top positive drivers</li><li>Top negative drivers</li><li>Feature values and thresholds where appropriate</li></ul><h3>Similar case evidence</h3><ul><li>Similar confirmed fraud cases</li><li>Similar false positives or legitimate cases</li><li>Pattern-level comparison</li><li>Key differences from the current case</li></ul><h3>Governing rules</h3><ul><li>Applicable policies or playbook sections</li><li>Version or effective date where available</li><li>Required action or escalation path</li></ul><h3>Final recommendation</h3><ul><li>Approve, reject, step-up, or manual review</li><li>Evidence supporting the recommendation</li><li>Uncertainties or missing information</li></ul><p>The point is not to make the report sound impressive. The point is to make it useful, grounded, and auditable.</p><h3>Evaluation: what to measure</h3><p>Once retrieval influences the final explanation, retrieval quality becomes a first-class metric.</p><p>Some useful evaluation questions:</p><ul><li>Did RAG-1 retrieve cases with the same dominant risk drivers?</li><li>Did the retrieved cases include both similar fraud and relevant counterexamples?</li><li>Did RAG-2 retrieve the applicable policy or playbook section?</li><li>Did the generated report cite only retrieved evidence?</li><li>Did the report separate facts from recommendations?</li><li>Did the report preserve the top SHAP drivers accurately?</li><li>Did analysts make decisions faster or more consistently?</li></ul><p>In high-stakes systems, “the report reads well” is not enough.</p><p>You need to measure whether the explanation is faithful to the model output and grounded in the retrieved evidence.</p><h3>Trade-offs and failure modes</h3><p>This architecture is useful, but it is not free.</p><h3>SHAP has compute cost</h3><p>Per-prediction explanations may be expensive at high throughput. In practice, you may not need SHAP for every transaction. You can run it only for review-bound cases, high-risk cases, sampled cases, or cases above an uncertainty threshold.</p><h3>Attribution quality matters</h3><p>If SHAP values are noisy or unstable, retrieval will amplify that noise. Attribution-guided retrieval only works if the attribution signal is reliable enough for the workflow.</p><h3>Two indexes require governance</h3><p>Case indexes and policy indexes have different update cycles, ownership, access controls, and retention rules. That separation improves quality, but it also adds operational complexity.</p><h3>Retrieved evidence can still be misleading</h3><p>Similar cases are not proof. A prior case may look similar but differ in a key hidden variable. The report should include uncertainty and counterexamples, not only evidence that supports the score.</p><h3>The LLM must be constrained</h3><p>The generator should not invent policies, prior cases, or unsupported explanations. It should be forced to use retrieved evidence and should clearly identify missing information.</p><h3>When this architecture is worth it</h3><p>SHAP-guided Dual-RAG is not necessary for every ML system.</p><p>It is most useful when:</p><ul><li>decisions are high-stakes;</li><li>manual review is expensive;</li><li>analysts need evidence, not just a score;</li><li>historical cases are informative;</li><li>policies or playbooks influence the final action;</li><li>auditability matters;</li><li>false positives and false negatives both have meaningful cost.</li></ul><p>Fraud investigation is a strong fit because analysts need to understand both the model’s reasoning and the operational rules around the decision.</p><p>But the pattern applies beyond fraud. It can support credit decisioning, insurance claims, compliance review, identity verification, content moderation, and other workflows where a model score must be turned into a defensible human decision.</p><h3>Takeaways</h3><ul><li>Naive RAG retrieves what looks similar; SHAP-guided retrieval retrieves what matters.</li><li>Feature attributions are not only explanation artifacts — they are relevance signals for retrieval.</li><li>Case retrieval and policy retrieval should usually be separated because they answer different questions.</li><li>Dual-RAG gives the generator two evidence streams: analogical evidence from past cases and governing rules from policy knowledge.</li><li>The final report should be grounded, structured, auditable, and honest about uncertainty.</li><li>This architecture is not a model-accuracy upgrade. It is a decision-support upgrade around an existing model.</li></ul><p><em>This article is the technical companion to “</em><a href="https://medium.com/@sivaramakrishnaganta1234/from-fraud-score-to-evidence-building-explainable-ml-decisions-with-rag-3a2211a9a913"><em>From Fraud Score to Evidence</em></a><em>.” That article explains why fraud scores need evidence-backed explanations. This one shows how to make the retriever behind those explanations actually relevant.</em></p><p>Follow me <a href="https://medium.com/@sivaramakrishnaganta1234">here</a> and on <a href="https://www.linkedin.com/in/siva-rama-krishna-ganta-5204ba125/">LinkedIn</a> if you’d like to learn more about building ML for fraud prevention in the real world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af86c98a4f94" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/building-a-rag-based-fraud-investigation-system-with-shap-guided-vector-search-and-dual-retrieval-af86c98a4f94">Building a RAG-Based Fraud Investigation System with SHAP guided vector search and Dual Retrieval</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Fraud Score to Evidence: Building Explainable ML Decisions with RAG]]></title>
            <link>https://medium.com/data-science-collective/from-fraud-score-to-evidence-building-explainable-ml-decisions-with-rag-3a2211a9a913?source=rss-97a8b112b94a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a2211a9a913</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[fraud-detection]]></category>
            <dc:creator><![CDATA[Siva Ganta]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 20:04:17 GMT</pubDate>
            <atom:updated>2026-08-19T20:04:17.125Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How Retrieval-Augmented Generation can turn a fraud model’s score into an evidence-backed explanation a human can actually act on.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9JuI0I4B_HjoGcn8cSEnUQ.png" /></figure><p>A fraud model can tell you that a transaction is risky.</p><p>But can it explain <strong>why</strong>?</p><p>That is the gap most production fraud systems still struggle with. A transaction comes in, the model scores it, and the output is often a single number: 0.94, 0.61, 0.12. Above one threshold, the system rejects. Below another, it approves. Everything in the middle flows into a manual review queue.</p><p>That score is useful. It helps rank risk. It helps automate decisions. It helps teams focus attention where loss exposure is highest.</p><p>But for the human analyst making the final call, a score alone is not enough.</p><p>A 0.61 risk score does not explain whether the transaction looks like stolen-card testing, account takeover, synthetic identity behavior, friendly fraud, address manipulation, or a legitimate customer whose behavior temporarily changed. It does not show which signals mattered most. It does not compare the case with similar historical patterns. It does not explain whether policy says to reject, step up, or send to review.</p><p>So analysts do what they have always done: open multiple tools, inspect customer history, compare recent transactions, search for similar cases, check business rules, and write a short case note.</p><p>That works, but it is slow, inconsistent, and difficult to scale.</p><p>The interesting question is not only whether we can build a better fraud model. Many fraud models are already strong at ranking risk. The more practical question is:</p><blockquote><em>Can we explain a model decision well enough that a human can trust it, audit it, and act faster?</em></blockquote><p>That is where Retrieval-Augmented Generation, or RAG, becomes useful.</p><h3>The problem with a bare fraud score</h3><p>A fraud score answers one question:</p><blockquote><strong><em>How risky does this transaction look?</em></strong></blockquote><blockquote>It does not naturally answer the question analysts care about next:</blockquote><blockquote><strong><em>Why does it look risky, and what evidence supports that conclusion?</em></strong></blockquote><blockquote>For example, a high-risk transaction may be driven by several very different patterns:</blockquote><ul><li>The transaction amount is far above the customer’s normal spend.</li><li>The shipping address is newly added and far from the customer’s usual region.</li><li>The device or IP location is inconsistent with prior activity.</li><li>Multiple accounts recently used similar payment or address attributes.</li><li>The pattern resembles previously confirmed fraud cases.</li><li>A policy rule requires step-up verification or manual review.</li></ul><p>A model may learn all of this. But the score itself hides the reasoning.</p><p>For fraud operations, that creates a practical problem. Analysts need to make fast decisions, but they also need consistency, evidence, and traceability. A bare score forces the analyst to reconstruct the reasoning manually.</p><h3>Why “just add SHAP” is not enough</h3><p>The obvious next step is feature attribution.</p><p>Tools such as SHAP can show which features pushed a prediction higher or lower. Instead of only seeing a score, the analyst can see a ranked list of drivers:</p><ul><li>transaction_amount_vs_customer_average increased risk</li><li>distance_from_home_location increased risk</li><li>new_shipping_address_age increased risk</li><li>trusted_device_history reduced risk</li></ul><p>This is a real improvement. It opens the black box and exposes the model’s local reasoning.</p><p>But feature attribution is still not the same thing as an investigation explanation.</p><p>A ranked feature list tells you what influenced the model mathematically. It does not automatically tell you:</p><ul><li>whether similar cases were confirmed fraud or false positives;</li><li>which policy or playbook applies;</li><li>whether the same customer has legitimate exceptions;</li><li>whether this pattern is part of a recent fraud wave;</li><li>what action the analyst should take.</li></ul><p>In other words, SHAP explains the model.</p><p>The analyst still needs the <strong>case story</strong>.</p><p>A useful explanation sounds more like this:</p><blockquote><em>This transaction was flagged because the amount is far above the customer’s usual spend, the shipping address is newly added and hundreds of miles from the customer’s typical region, and the pattern closely matches confirmed fraud cases from the last 30 days. Two similar-looking prior cases were legitimate, but both had verified travel context, which is not present here. Based on policy, this case should be routed to step-up verification or manual review.</em></blockquote><p>That explanation has attribution, evidence, history, policy context, and a recommended next step.</p><p>Feature attribution alone cannot produce that. The missing layer is retrieval.</p><h3>Enter RAG: retrieval as the investigation layer</h3><p>Retrieval-Augmented Generation is commonly described as a way to make LLM responses more grounded. Instead of asking a language model to answer from memory, we first retrieve relevant documents and then ask the model to generate an answer based on that evidence.</p><p>In fraud decisioning, the “documents” do not have to be ordinary documents. They can be:</p><ul><li>historical fraud cases;</li><li>confirmed false positives;</li><li>chargeback outcomes;</li><li>analyst notes;</li><li>policy documents;</li><li>risk playbooks;</li><li>investigation procedures;</li><li>model documentation;</li><li>known fraud-pattern summaries.</li></ul><p>The transaction under review becomes the query. The model score and feature attributions enrich that query. The generated output becomes a structured case report.</p><p>The architecture looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zSUbygwsp6Z_oPlI70GFuQ.png" /><figcaption>Explainable Fraud decision support Architecture</figcaption></figure><p>At a high level, the system has four layers:</p><ol><li><strong>Detect:</strong> A production fraud model scores the transaction.</li><li><strong>Explain:</strong> Feature attribution identifies the strongest drivers of the score.</li><li><strong>Retrieve:</strong> The system retrieves similar historical cases and relevant domain knowledge.</li><li><strong>Generate:</strong> An LLM produces a grounded, structured investigation report.</li></ol><p>The key point is that the model is still responsible for detection. RAG is not replacing the fraud model. It is wrapping the model with an explanation and decision-support layer.</p><h3>The important design choice: retrieve based on why, not just what</h3><p>A naive RAG system might retrieve similar cases using the raw transaction alone.</p><p>That can work, but it often retrieves cases that are only superficially similar. Two transactions may share the same merchant category, amount band, or geography while being suspicious for completely different reasons.</p><p>A better design is to let the attribution layer steer retrieval.</p><p>For example, suppose SHAP shows that the main risk drivers are:</p><ul><li>unusual transaction amount;</li><li>large distance from historical customer location;</li><li>newly added shipping address;</li><li>high recent velocity on the payment instrument.</li></ul><p>Those drivers should shape the retrieval query. The system should look for past cases that were suspicious for the same reasons, not merely cases with similar surface attributes.</p><p>This is the core pattern:</p><blockquote><em>The explanation of the model becomes the query for retrieval.</em></blockquote><p>That makes the retrieved evidence more useful. The system is not just asking, “What cases look similar?” It is asking, “What cases were suspicious in the same way?”</p><p>That distinction matters.</p><h3>What the generated report should contain</h3><p>The output should not be a free-form paragraph that sounds convincing. It should be a structured report with evidence boundaries.</p><p>A practical report might include:</p><h3>1. Decision summary</h3><p>A short explanation of the model score and recommended action.</p><p>Example:</p><blockquote><em>Risk score: 0.94. Recommended action: reject or step-up verification. The case is primarily driven by abnormal spend, new shipping address behavior, and similarity to confirmed fraud cases.</em></blockquote><h3>2. Top risk drivers</h3><p>A ranked list of the strongest positive and negative contributors.</p><p>Example:</p><ul><li>Transaction amount is 4.8x higher than the customer’s median spend.</li><li>Shipping address was added within the last 24 hours.</li><li>Device location is 340 miles from the customer’s usual region.</li><li>Prior trusted-device history slightly reduces risk.</li></ul><h3>3. Similar historical cases</h3><p>Retrieved cases that are similar for the same risk reasons.</p><p>Example:</p><ul><li>3 confirmed fraud cases in the last 30 days had similar amount, address-age, and distance patterns.</li><li>1 false-positive case had similar amount behavior but included verified travel context.</li></ul><h3>4. Policy or playbook context</h3><p>The applicable rule, operating procedure, or risk policy.</p><p>Example:</p><ul><li>Policy: Newly added address + high-risk payment velocity should be routed to step-up verification when the score exceeds the review threshold.</li></ul><h3>5. Evidence-backed recommendation</h3><p>A recommended action with supporting evidence.</p><p>Example:</p><blockquote><em>Recommend step-up verification before fulfillment. If verification fails or is unavailable, reject the transaction.</em></blockquote><p>This structure makes the report more useful for operations and easier to audit later.</p><h3>Guardrails matter more than style</h3><p>In a high-stakes workflow, a beautiful explanation is not enough.</p><p>The system must be grounded.</p><p>Every generated claim should be traceable to one of the following:</p><ul><li>model output;</li><li>feature attribution;</li><li>retrieved historical case;</li><li>retrieved policy document;</li><li>retrieved analyst note;</li><li>business rule or workflow guideline.</li></ul><p>That means the generation layer needs guardrails:</p><ul><li><strong>Citation of evidence:</strong> each key claim should point back to retrieved evidence.</li><li><strong>No unsupported claims:</strong> the LLM should not invent prior cases, policies, or customer behavior.</li><li><strong>Policy versioning:</strong> reports should identify which policy or playbook version was used.</li><li><strong>PII controls:</strong> sensitive customer information should be masked or minimized.</li><li><strong>Human override:</strong> the analyst should remain responsible for final action where required.</li><li><strong>Audit logging:</strong> score, attribution, retrieval results, prompt, response, and final decision should be stored.</li><li><strong>Grounding evaluation:</strong> reports should be tested for faithfulness, completeness, and unsupported statements.</li></ul><p>This is where many proof-of-concept systems fail. They focus on whether the generated report reads well. In fraud, the more important question is whether the report is faithful to the evidence.</p><h3>What improves — and what does not</h3><p>It is important not to oversell this architecture.</p><p>RAG does not automatically make the fraud model more accurate.</p><p>The detection model still has the same precision, recall, thresholds, and calibration. If the model scored a transaction incorrectly, RAG may explain that incorrect score unless the surrounding evidence reveals contradictions.</p><p>What improves is the decision-support workflow around the model:</p><ul><li>analysts receive explanations faster;</li><li>reviews become more consistent;</li><li>similar cases are surfaced automatically;</li><li>policy context is easier to apply;</li><li>new analysts ramp faster;</li><li>case notes become more structured;</li><li>audit trails become stronger;</li><li>operational decisions become easier to review later.</li></ul><p>This is not a better detector.</p><p>It is a better investigation layer around the detector.</p><p>That distinction is the whole point.</p><h3>A reusable pattern beyond fraud</h3><p>Although fraud is a natural example, the same pattern applies to many high-stakes ML systems:</p><blockquote><em>A model makes a consequential prediction → attribution explains why → retrieval finds comparable cases and governing rules → an LLM generates a grounded explanation → a human reviews and acts.</em></blockquote><p>This pattern can apply to:</p><ul><li>credit decisioning;</li><li>insurance claims;</li><li>healthcare decision support;</li><li>content moderation;</li><li>identity verification;</li><li>compliance review;</li><li>hiring and workforce analytics;</li><li>customer-risk workflows.</li></ul><p>Anywhere a model produces a score and a human must justify the action, this architecture can help convert prediction into decision support.</p><h3>Takeaways</h3><ul><li>A fraud score tells you <strong>how risky</strong> something looks. It does not explain <strong>why</strong>.</li><li>SHAP and feature attribution are useful, but they explain model math more than the full case story.</li><li>RAG can turn model output, similar cases, and policy knowledge into an evidence-backed investigation report.</li><li>The best retrieval strategy is attribution-guided: retrieve cases that are suspicious for the same reasons.</li><li>In fraud systems, grounding and auditability matter more than fluent language.</li><li>This architecture is not a detection upgrade. It is a decision-support upgrade around an existing detector.</li></ul><p><em>Next in this series: how feature attributions can steer retrieval, and why one retriever is rarely enough for fraud investigation workflows.</em></p><p>Follow me <a href="https://medium.com/@sivaramakrishnaganta1234">here</a> and on <a href="https://www.linkedin.com/in/siva-rama-krishna-ganta-5204ba125/">LinkedIn</a> if you’d like to learn more about building ML for fraud prevention in the real world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a2211a9a913" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/from-fraud-score-to-evidence-building-explainable-ml-decisions-with-rag-3a2211a9a913">From Fraud Score to Evidence: Building Explainable ML Decisions with RAG</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Analytics SQL Agent: Natural Language → Safe, Cost-Aware SQL]]></title>
            <link>https://pub.towardsai.net/build-analytics-sql-agent-natural-language-safe-cost-aware-sql-7d52fb373994?source=rss-97a8b112b94a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d52fb373994</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Siva Ganta]]></dc:creator>
            <pubDate>Sun, 15 Feb 2026 22:01:01 GMT</pubDate>
            <atom:updated>2026-02-15T22:01:01.353Z</atom:updated>
            <content:encoded><![CDATA[<p>Business teams want answers <strong>now</strong> — but most of them don’t speak SQL, and analytics teams <strong>can’t scale 1:1 with every quick question</strong>.</p><p>A <strong>BigQuery SQL Agent</strong> solves this by translating natural language into <strong>validated, optimized, and permission-safe</strong> BigQuery SQL — then executing it with guardrails (cost caps, caching, error recovery) and returning results in plain English.</p><p>If you’re building self-serve analytics, internal copilots, or data chatbots, this guide gives you a practical blueprint you can implement and productionize.</p><h3>Table of Contents</h3><p>· Introduction</p><p>· What is a BigQuery Agent?</p><p>· Architecture (4 layers)</p><p>· End-to-End User Flow (example)</p><p>· Core Components (with code)</p><p>· Production Guardrails (security + cost control)</p><p>· Monitoring &amp; Testing</p><p>· Key Takeaways + Resources</p><h3>Why BigQuery Agents Matter</h3><p>A well-designed agent can:</p><p>· <strong>Democratize data access</strong> (non-technical users ask questions directly)</p><p>· <strong>Reduce time-to-insight</strong> from hours → seconds</p><p>· <strong>Prevent expensive mistakes</strong> via query validation + cost estimation</p><p>· <strong>Scale analytics</strong> without creating an analyst bottleneck</p><p>· <strong>Reduce BigQuery spend</strong> via aggressive caching (especially for repeated questions)</p><h3>What is a BigQuery Agent?</h3><p>A <strong>BigQuery Agent</strong> is an AI-powered system that:</p><p>1. Understands a user’s question</p><p>2. Uses schema context to generate SQL</p><p>3. Validates SQL (security + correctness + cost)</p><p>4. Executes on BigQuery</p><p>5. Recovers gracefully from errors</p><p>6. Summarizes results for humans (and optionally charts)</p><p>Think of it as a <strong>Text-to-SQL + Governance + Execution</strong> pipeline.</p><h3>Architecture Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Gjk1xOWGV9iAcYFw0YnZg.png" /><figcaption>Analytics Agent</figcaption></figure><h3>End-to-End Flow (from question → insight)</h3><p>User: <strong>“Top products by revenue this month”</strong></p><p>1. <strong>Schema discovery</strong></p><p>· Fetch table + column metadata (cached)</p><p>2. <strong>Intent parsing</strong></p><p>· “Top products” → group &amp; sort</p><p>· “Revenue” → SUM(amount)</p><p>· “This month” → date filter</p><p>3. <strong>SQL generation</strong></p><p>· LLM generates BigQuery Standard SQL using schema context</p><p>4. <strong>Validation &amp; safety checks</strong></p><p>· Only allow read-only queries (SELECT)</p><p>· Verify tables/columns exist</p><p>· Dry run to estimate bytes processed</p><p>· Enforce maximum_bytes_billed cost cap</p><p>5. <strong>Cache check</strong></p><p>· Hash SQL and return cached results if available</p><p>· Cache hits are fast and avoid query charges (BigQuery cache behavior is a major win)</p><p>6. <strong>Execution</strong></p><p>· Run the query, return results + metadata (time, bytes, cache status)</p><p>7. <strong>Error recovery</strong></p><p>· Classify error → attempt fix → retry once → return helpful feedback</p><p>8. <strong>Human-friendly response</strong></p><p>· Summarize results and show a small table (or chart)</p><h3>Core Components (Practical Implementation)</h3><h3>1) Schema Discovery Tool (cached)</h3><p><strong>Goal:</strong> give the model <em>just enough</em> schema context to generate correct SQL.</p><pre>from google.cloud import bigquery<br>from functools import lru_cache<br><br>class SchemaDiscoveryTool:<br>    def __init__(self, project_id: str):<br>        self.client = bigquery.Client(project=project_id)<br>        self.project_id = project_id<br><br>    @lru_cache(maxsize=128)<br>    def get_table_schema(self, dataset_id: str, table_id: str) -&gt; dict:<br>        table = self.client.get_table(f&quot;{self.project_id}.{dataset_id}.{table_id}&quot;)<br><br>        columns = [{<br>            &quot;name&quot;: field.name,<br>            &quot;type&quot;: field.field_type,<br>            &quot;description&quot;: field.description or &quot;&quot;<br>        } for field in table.schema]<br><br>        return {<br>            &quot;table&quot;: table_id,<br>            &quot;columns&quot;: columns,<br>            &quot;rows&quot;: table.num_rows<br>        }<br><br>    def find_tables(self, dataset_id: str) -&gt; list:<br>        tables = self.client.list_tables(f&quot;{self.project_id}.{dataset_id}&quot;)<br>        return [t.table_id for t in tables]</pre><p><strong>Production tip:</strong> LRU is great for local dev. In production, consider Redis/memcache with TTL so schema updates propagate safely.</p><h3>2) SQL Query Generator (OpenAI Responses API)</h3><p>The best results come from:</p><p>· short, strict instructions</p><p>· schema context</p><p>· a “policy section” (read-only, partition filters, LIMIT, etc.)</p><p>· low temperature for deterministic SQL</p><p>OpenAI’s current primary interface is the <strong>Responses API</strong> (Python example below)</p><pre>import os<br>from openai import OpenAI<br><br>class SQLQueryGenerator:<br>    def __init__(self, model: str = &quot;gpt-5.2&quot;):<br>        self.client = OpenAI(api_key=os.environ.get(&quot;OPENAI_API_KEY&quot;))<br>        self.model = model<br><br>    def generate_query(self, question: str, schema: dict, dataset_id: str) -&gt; str:<br>        schema_text = []<br>        for table_name, table_schema in schema.items():<br>            cols = &quot;, &quot;.join([f&quot;{c[&#39;name&#39;]} ({c[&#39;type&#39;]})&quot; for c in table_schema[&quot;columns&quot;]])<br>            schema_text.append(f&quot;- {table_name}: {cols}&quot;)<br>        schema_text = &quot;\n&quot;.join(schema_text)<br><br>        instructions = f&quot;&quot;&quot;<br>You are a BigQuery SQL expert.<br>Generate ONE BigQuery Standard SQL query for the user&#39;s question.<br><br>Rules:<br>- Read-only SELECT queries only (no INSERT/UPDATE/DELETE/MERGE/DDL).<br>- Prefer partition filters when dates are mentioned.<br>- Include a reasonable LIMIT if the result could be large.<br>- Use fully-qualified tables as `{dataset_id}.table` if needed.<br>Return ONLY SQL (no explanation).<br>&quot;&quot;&quot;.strip()<br><br>        response = self.client.responses.create(<br>            model=self.model,<br>            instructions=instructions,<br>            input=f&quot;Schema:\n{schema_text}\n\nQuestion:\n{question}&quot;<br>        )<br>        return response.output_text.strip()</pre><p>3) Validator + Cost Estimator (dry run + caps)</p><p>BigQuery recommends <strong>dry runs</strong> to estimate cost before executing. <br> You can also cap spend per query using maximum_bytes_billed.</p><pre>from google.cloud import bigquery<br><br>DANGEROUS = [&quot;DROP&quot;, &quot;DELETE&quot;, &quot;TRUNCATE&quot;, &quot;ALTER&quot;, &quot;CREATE&quot;, &quot;MERGE&quot;, &quot;UPDATE&quot;, &quot;INSERT&quot;]<br><br>class QueryValidator:<br>    def __init__(self, project_id: str, max_bytes_billed: int = 2_000_000_000):<br>        self.client = bigquery.Client(project=project_id)<br>        self.max_bytes_billed = max_bytes_billed<br><br>    def validate(self, sql: str) -&gt; dict:<br>        upper = sql.upper()<br>        if any(k in upper for k in DANGEROUS):<br>            return {&quot;ok&quot;: False, &quot;reason&quot;: &quot;Only read-only SELECT queries are allowed.&quot;}<br><br>        job_config = bigquery.QueryJobConfig(<br>            dry_run=True,<br>            use_legacy_sql=False,<br>            maximum_bytes_billed=self.max_bytes_billed<br>        )<br>        try:<br>            job = self.client.query(sql, job_config=job_config)<br>            return {<br>                &quot;ok&quot;: True,<br>                &quot;estimated_bytes&quot;: job.total_bytes_processed,<br>            }<br>        except Exception as e:<br>            return {&quot;ok&quot;: False, &quot;reason&quot;: str(e)}</pre><p><strong>Pricing note:</strong> BigQuery on-demand charges are based on bytes scanned (after the free tier); cost control is why dry runs + caps matter.</p><h3>4) Query Executor (with TTL caching)</h3><pre>import hashlib<br>from datetime import datetime, timedelta<br>from google.cloud import bigquery<br><br>class QueryExecutor:<br>    def __init__(self, project_id: str, cache_ttl_seconds: int = 3600):<br>        self.client = bigquery.Client(project=project_id)<br>        self.cache = {}<br>        self.ttl = cache_ttl_seconds<br><br>    def execute(self, sql: str, max_results: int = 1000) -&gt; dict:<br>        key = hashlib.md5(sql.upper().encode()).hexdigest()<br><br>        # Cache lookup<br>        cached = self.cache.get(key)<br>        if cached and datetime.utcnow() &lt; cached[&quot;expires&quot;]:<br>            return {**cached[&quot;result&quot;], &quot;from_cache&quot;: True}<br><br>        # Execute<br>        try:<br>            job = self.client.query(sql, job_config=bigquery.QueryJobConfig(use_legacy_sql=False))<br>            rows_iter = job.result(max_results=max_results)<br>            rows = [dict(r) for r in rows_iter]<br><br>            result = {<br>                &quot;status&quot;: &quot;success&quot;,<br>                &quot;rows&quot;: rows,<br>                &quot;row_count&quot;: len(rows),<br>                &quot;bytes_processed&quot;: job.total_bytes_processed or 0,<br>            }<br><br>            self.cache[key] = {&quot;result&quot;: result, &quot;expires&quot;: datetime.utcnow() + timedelta(seconds=self.ttl)}<br>            return {**result, &quot;from_cache&quot;: False}<br><br>        except Exception as e:<br>            return {&quot;status&quot;: &quot;error&quot;, &quot;error&quot;: str(e), &quot;rows&quot;: []}</pre><p><strong>Scaling tip:</strong> in production, swap the in-memory dict for Redis + query hash keys + TTL.</p><h3>Putting It Together: The Orchestrator</h3><pre>class BigQueryAgent:<br>    def __init__(self, project_id: str, dataset_id: str):<br>        self.dataset_id = dataset_id<br>        self.schema_tool = SchemaDiscoveryTool(project_id)<br>        self.query_gen = SQLQueryGenerator()<br>        self.validator = QueryValidator(project_id)<br>        self.executor = QueryExecutor(project_id)<br>        self.error_handler = ErrorHandler(self.query_gen)<br><br>    def process(self, question: str) -&gt; dict:<br>        # 1) schema<br>        tables = self.schema_tool.find_tables(self.dataset_id)<br>        schema = {t: self.schema_tool.get_table_schema(self.dataset_id, t) for t in tables}<br><br>        # 2) generate<br>        sql = self.query_gen.generate_query(question, schema, self.dataset_id)<br><br>        # 3) validate + estimate<br>        v = self.validator.validate(sql)<br>        if not v[&quot;ok&quot;]:<br>            return {&quot;status&quot;: &quot;error&quot;, &quot;message&quot;: v[&quot;reason&quot;], &quot;sql&quot;: sql}<br><br>        # 4) execute<br>        result = self.executor.execute(sql)<br><br>        # 5) recover (optional retry once)<br>        if result[&quot;status&quot;] == &quot;error&quot;:<br>            recovery = self.error_handler.recover(result[&quot;error&quot;], question, schema, self.dataset_id)<br>            if recovery[&quot;action&quot;] == &quot;retry&quot;:<br>                return self.executor.execute(recovery[&quot;sql&quot;])<br>            return {&quot;status&quot;: &quot;error&quot;, &quot;message&quot;: recovery.get(&quot;hint&quot;), &quot;sql&quot;: sql}<br><br>        return {**result, &quot;sql&quot;: sql, &quot;estimated_bytes&quot;: v.get(&quot;estimated_bytes&quot;)}</pre><h3>Real-World Use Cases</h3><h3>1) Contact Center Analytics</h3><p><strong>“What are top call categories this month?”</strong><br> → staffing decisions, training gaps, deflection strategies</p><h3>2) E-Commerce Product Analytics</h3><p><strong>“Which products have declining sales trends?”</strong><br> → inventory planning, promo strategy, lifecycle flags</p><h3>3) Finance / Budget Tracking</h3><p><strong>“Which departments are over budget?”</strong><br> → variance monitoring + early alerts</p><h3>3) Fraud Analytics</h3><p><strong>“Which locations/items are more fraud proned ”</strong><br> → product launch + early alerts</p><h3>Production Considerations (the stuff that prevents outages)</h3><h3>Security &amp; Governance (non-negotiable)</h3><p>· Use a <strong>read-only service account</strong> with least-privilege BigQuery IAM</p><p>· Allowlist datasets/tables the agent can touch</p><p>· Prefer <strong>Authorized Views</strong> / <strong>Row-Level Security</strong> for sensitive data</p><p>· Log every question + generated SQL (auditable trail)</p><p>· Block DDL/DML keywords and multi-statement SQL</p><h3>Cost Control (keep bills predictable)</h3><p>· Dry run to estimate bytes before executing</p><p>· Use maximum_bytes_billed caps</p><p>· Encourage partition + cluster filters (huge scan reduction)</p><p>· Cache results aggressively (exact match + optionally semantic cache)</p><p>BigQuery on-demand pricing is tied to bytes scanned, so reducing scanned bytes is the fastest “optimization win.”</p><h3>Monitoring (what to track)</h3><p>· Query latency (p50/p95)</p><p>· Success rate / fix rate</p><p>· Cache hit rate</p><p>· Bytes processed / estimated cost per query</p><p>· Top failing questions (to improve prompts + schema descriptions)</p><h3>Testing (what will save you later)</h3><p>· Unit tests for schema/tooling</p><p>· “Golden” test set of questions with expected SQL patterns</p><p>· Integration tests against a sandbox dataset</p><h3>Example Performance Targets (starter goals)</h3><p>· Latency: &lt; 10s</p><p>· Success rate: &gt; 95%</p><p>· Cache hit rate: &gt; 40%</p><p>· Cost per query: keep under a fixed budget cap</p><p>· Time-to-insight: seconds, not days</p><h3>Key Takeaways</h3><p>1. <strong>Keep it modular</strong>: schema → generate → validate → execute → recover</p><p>2. <strong>Guardrails first</strong>: read-only SQL, allowlists, cost caps</p><p>3. <strong>Dry runs + maximum bytes billed</strong> keep spend predictable</p><p>4. <strong>Caching is your multiplier</strong> for both speed and cost</p><p>5. <strong>Observability matters</strong>: treat queries like production workloads</p><p><strong>References:</strong></p><p>· BigQuery Docs: <a href="https://cloud.google.com/bigquery/docs">https://cloud.google.com/bigquery/docs</a></p><p>· BigQuery Pricing: <a href="https://cloud.google.com/bigquery/pricing">https://cloud.google.com/bigquery/pricing</a></p><p>· BigQuery Cost Best Practices: <a href="https://cloud.google.com/bigquery/docs/best-practices-costs">https://cloud.google.com/bigquery/docs/best-practices-costs</a></p><p>· BigQuery QueryJobConfig (Python): <a href="https://docs.cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.job.QueryJobConfig">https://docs.cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.job.QueryJobConfig</a></p><p>· OpenAI Responses API: <a href="https://platform.openai.com/docs/api-reference/responses">https://platform.openai.com/docs/api-reference/responses</a></p><p>· OpenAI Python Reference: <a href="https://developers.openai.com/api/reference/python/">https://developers.openai.com/api/reference/python/</a></p><p>Follow me <a href="https://medium.com/@sivaramakrishnaganta1234">here</a> and on <a href="https://www.linkedin.com/in/siva-rama-krishna-ganta-5204ba125/">LinkedIn</a> if you’d like to learn more about building ML for fraud prevention in the real world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d52fb373994" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/build-analytics-sql-agent-natural-language-safe-cost-aware-sql-7d52fb373994">Build Analytics SQL Agent: Natural Language → Safe, Cost-Aware SQL</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Types of E-commerce Fraud & How They Happen]]></title>
            <link>https://medium.com/@sivaramakrishnaganta1234/types-of-e-commerce-fraud-how-they-happen-7a0e2ef03491?source=rss-97a8b112b94a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a0e2ef03491</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[credit-cards]]></category>
            <category><![CDATA[fraud]]></category>
            <dc:creator><![CDATA[Siva Ganta]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 05:38:01 GMT</pubDate>
            <atom:updated>2026-01-29T05:38:01.722Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Types of E-commerce Fraud &amp; How They Happen</strong></p><p><strong><em>(and how to stay ahead with the right reports)</em></strong></p><p><strong>Why this matters. </strong>If you only react to chargebacks, you’re <strong>30–90 days</strong> late. In 2024, U.S. consumers reported approximately <strong>$12.5B</strong> <strong>in fraud losses</strong> to the FTC, <strong>up ~25% year over year</strong> and the FBI’s IC3 logged about <strong>$16.6B in internet-crime losses across ~859k complaints</strong> (average loss around $19k). Card-not-present fraud continues to dominate U.S. card losses. (Sources: FTC Consumer Sentinel 2024 Data Book; FBI IC3 2024; Nilson Report.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UhS2ea2Ro6wibdey8HLIpQ.png" /><figcaption>Ecomm fraud</figcaption></figure><h3>The Big Buckets (with real attack flows)</h3><h3>1) Stolen Credit Cards (CNP)</h3><p><strong>How it happens: </strong>Cards from dark markets or skimmed; small “tests” first, then higher-value goods/digital goods/gift cards.</p><p><strong>Early signals: </strong>AVS/CVV mismatches; bursty attempts per card/device/IP; unusual SKU mix; large billing↔shipping↔device distances; “add-card” velocity.</p><p><strong>Controls: </strong>Device/behavior fingerprinting, velocity limits, 3DS where helpful, issuer risk APIs, ML risk scoring plus manual review for edge cases.</p><h3>2) Account Takeover (ATO)</h3><p><strong>How it happens: </strong>Credential stuffing, phishing, SIM swap, or malware. Once inside: change email/phone, add a new card, redeem rewards, place BOPIS/expedited orders.</p><p><strong>Early signals: </strong>Failed→successful login sequences; new device plus profile/payment changes; rapid reward balance drains.</p><p><strong>Controls: </strong>MFA/step-up on sensitive actions; new-device friction; session binding; anomaly alerts on profile changes.</p><h3>3) Stolen PII / Synthetic IDs</h3><p><strong>How it happens: </strong>Clean PII used to open new accounts or spoof KYC; then first‑party abuse or mule activity.</p><p><strong>Early signals: </strong>Fresh-account bursts from the same device/network; immaculate but inconsistent demographics; IP/geo/time-zone mismatch.</p><p><strong>Controls: </strong>Identity graphing across email/phone/device/address; third‑party verification; probation thresholds for new accounts.</p><h3>4) Address Manipulation / Reshipping</h3><p><strong>How it happens: </strong>Near‑duplicate addresses (typos, confusable characters), alternate unit formats, freight forwarders/mules — bypassing rules or rerouting goods.</p><p><strong>Early signals: </strong>Distance anomalies (billing↔shipping↔device↔IP); many cards→one address; one member→many addresses; near‑duplicate strings; known risky hubs.</p><p><strong>Controls: </strong>Address verification/normalization; geocoding lat/long; near‑duplicate detection; rolling per‑entity counts/uniques.</p><h3>5) Friendly Fraud / Chargeback Abuse</h3><p><strong>How it happens: </strong>Customers dispute legitimate orders (“item not received,” “not as described”), exploiting lax refund policies.</p><p><strong>Early signals: </strong>Repeat disputes per member/device; INR spikes by lane; mismatch between carrier scans and claims; short time‑to‑dispute.</p><p><strong>Controls: </strong>Proof‑of‑delivery and telemetry; refund‑risk models; representment playbooks; policy tuning.</p><h3>6) Promo / Coupon / Loyalty Abuse</h3><p><strong>How it happens: </strong>Multi‑accounting for sign‑up credits, referral loops, stacking misconfigured promos, reward arbitrage.</p><p><strong>Early signals: </strong>Many accounts per device/IP/phone; abnormal redemption trajectories and graphs.</p><p><strong>Controls: </strong>Per‑device/account/phone quotas; reputation on promo sources; graph/cluster detection with rules + ML.</p><h3>7) Gift Card &amp; Digital Goods</h3><p><strong>How it happens: </strong>Instant value and easy resale; often targeted for BIN‑testing and post‑hack cash‑outs.</p><p><strong>Early signals: </strong>High gift‑card SKU mix; micro‑tests followed by spikes; odd‑hour activity; geo mismatch.</p><p><strong>Controls: </strong>SKU‑aware thresholds; short fulfillment delays/step‑up; GC‑specific models; tighter review queues.</p><p><strong>Implementation tip. </strong>Keep minute/hour features for real‑time signals (Kafka + low‑latency store) and daily aggregates for history (Spark/Airflow + warehouse). Train/serve parity avoids “it‑worked‑offline” failures.</p><h3>KPIs that align risk with CX (Customer Experience)</h3><p>· True positive rate (Rejected $ / attempted fraud $)</p><p>· False‑positive rate (good orders incorrectly blocked)</p><p>· Friction rate on sensitive actions (MFA/step‑up %)</p><p>· Chargeback Rate — fraud loss control without over-blocking.</p><p>· Approval rate and time‑to‑decision (fast approvals for good users)</p><h3>Fraud‑prevention solution landscape</h3><p>· Full‑stack e‑commerce platforms: Forter, Riskified, Sift</p><p>· Payment processors with built‑in risk: Stripe Radar, Adyen RevenueProtect, Cybersource (Visa)</p><p>· Identity / device / behavioral intelligence: LexisNexis ThreatMetrix, TransUnion TruValidate (iovation), BioCatch</p><p>· Bot &amp; abuse mitigation: HUMAN (PerimeterX), Arkose Labs, Kasada</p><p>· Chargeback alerts / dispute: Ethoca (Mastercard), Verifi (Visa), Midigator</p><h3>Staying Current: trustworthy reports &amp; feeds</h3><p>· <strong>FTC — Consumer Sentinel Network (annual Data Book)</strong> — U.S. fraud &amp; ID-theft trends from millions of consumer reports.<br> <a href="https://www.ftc.gov/system/files/ftc_gov/pdf/csn-annual-data-book-2024.pdf">Data book PDF • Overview page</a></p><p>· <strong>FBI — Internet Crime Complaint Center (IC3)</strong> — Annual Internet Crime Reports with losses by category; official reporting portal.<br> <a href="https://www.ic3.gov/">IC3 portal • Latest report press release</a>.</p><p>· <strong>Nilson Report</strong> — Payment card fraud trends (industry standard for card fraud loss benchmarks).<br> <a href="https://nilsonreport.com/articles/card-fraud-losses-worldwide-in-2023/">2023 card fraud losses • 2022 overview</a>.</p><p>· <strong>LexisNexis Risk — True Cost of Fraud™</strong> — Benchmarks on fraud cost multipliers and operational impacts (retail/e-com).<br> <a href="https://risk.lexisnexis.com/insights-resources/research/us-ca-true-cost-of-fraud-study">Study hub • 2025 highlights/press</a>.</p><p>· <strong>NRF (National Retail Federation)</strong> — Loss prevention &amp; shrink research for retail.<br> <a href="https://nrf.com/research/national-retail-security-survey-2023">National Retail Security Survey • Theft &amp; violence impact study</a>.</p><p>· MRC (Merchant Risk Council) — Best practices, conference decks, and resources (member community).<br> <a href="https://merchantriskcouncil.org/learning/resource-center#sort=%40relevancez32xdate%20descending">Resource Center • Example session.</a></p><p>· <strong>Visa</strong> — Dispute/chargeback rules &amp; merchant guidelines.<br> <a href="https://usa.visa.com/content/dam/VCOM/global/support-legal/documents/merchants-dispute-management-guidelines.pdf">Merchant chargeback guide (PDF) • Program info.</a></p><p>· <strong>CISA / FBI cyber advisories</strong> — Broader threat alerts that can affect fraud vectors (phishing, malware, botnets).<br> <a href="https://www.fbi.gov/investigate/cyber">CISA alerts landing, plus recent FBI/CISA notices.</a></p><h3>Summary</h3><p>Fraud types change slowly; tactics change weekly. Build detection that’s observant (rich signals), adaptable (fast thresholds/retrains), and explainable (so ops can act). Pair that with a steady diet of FTC/IC3/Nilson/LexisNexis reporting and you’ll stay ahead, without crushing Customer experience.</p><p>To learn more about implementing <strong>real-time fraud prevention</strong>, please refer to my published <a href="https://medium.com/me/stories?tab=posts-published">articles</a>.</p><p>Follow me <a href="https://medium.com/@sivaramakrishnaganta1234">here</a> and on <a href="https://www.linkedin.com/in/siva-rama-krishna-ganta-5204ba125/">LinkedIn</a> if you’d like to learn more about building ML for fraud prevention in the real world.</p><p><em>(and how to stay ahead with the right reports)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a0e2ef03491" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML Model & Feature Data Drift: A Practical Guide for Real-Time Fraud Systems]]></title>
            <link>https://medium.com/@sivaramakrishnaganta1234/ml-model-feature-data-drift-a-practical-guide-for-real-time-fraud-systems-bcf3cbe2348b?source=rss-97a8b112b94a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcf3cbe2348b</guid>
            <category><![CDATA[data-drift]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[fraud]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Siva Ganta]]></dc:creator>
            <pubDate>Tue, 27 Jan 2026 04:41:44 GMT</pubDate>
            <atom:updated>2026-01-27T04:41:44.190Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In Ecommerce fraud, labels (chargebacks) can lag 30–90 days. At Amazon/Walmart/E-Bay scale, millions of events/day, hundreds of features, and strict P99 latency budgets, you can’t wait for labels. Detect prediction drift and feature drift continuously with simple, explainable stats (KS, PSI, mean/std), wire alerts into playbooks, and make retrain/rollback/threshold changes cheap.</blockquote><h3><strong>Why Drift Matters (Especially in Fraud)</strong></h3><blockquote>After deployment, the input data distribution changes. Promotions, seasonality, new product lines, bot waves, UX updates, or a broken data job, each can push your model off distribution. In fraud, ground truth (chargebacks) lags by 30–90 days, so you need early warning from the live stream.</blockquote><h3><strong>Operating reality at scale</strong></h3><blockquote><strong>Volume:</strong> 5–10M+ predictions/day across channels; 300–1000 online features.</blockquote><blockquote><strong>Latency:</strong> real-time decisions in tens of ms at P99; can’t run heavy stats in-line.</blockquote><blockquote><strong>Topology:</strong> Kafka streams → Cassandra/low-latency store for minute/hour signals; Spark/Airflow → Hive/BigQuery for daily aggregates; feature store for train/serve parity.</blockquote><blockquote><strong>Reliability:</strong> multi-region, back-pressure handling, shadow/canary deploys.</blockquote><p><strong>Key idea</strong>: If labels lag, monitor the inputs and predictions as proxies. Catch anomalies early → investigate → retrain/rollback/tune thresholds.</p><h4><strong>Four Types of Drift (simple mental model)</strong></h4><blockquote>1. <strong>Prediction drift (P(ŷ))</strong> — your model’s output distribution shifts</blockquote><blockquote>o Example: reject rate jumps from 2% → 6% overnight.</blockquote><blockquote>2. <strong>Feature drift (P(X)) </strong>— inputs shift</blockquote><blockquote>o Example: Club Pickup share rises sharply vs in-store.</blockquote><blockquote>3. <strong>Label drift (P(Y)) </strong>— outcome mix changes</blockquote><blockquote>o Example: more true fraud in peak holidays.</blockquote><blockquote>4. <strong>Concept drift (P(Y|X))</strong> — relationship changes</blockquote><blockquote>o Example: attackers adopt new address-manipulation tactics; old signals lose power.</blockquote><blockquote>With delayed labels, prediction drift + feature drift are your best early signals.</blockquote><h4><strong>Common Causes</strong></h4><blockquote>Data integrity issues:</blockquote><blockquote>Incorrect data at source (schema change, null explosion).</blockquote><blockquote>Correct at source but broken in ETL/feature calculation.</blockquote><blockquote>Real behavior shifts (holidays, policy changes, new payment rails).</blockquote><p><strong>The Drift Monitoring Loop</strong></p><blockquote>1. Observe: build reference distributions from a stable window (train/holdout, e.g., last 2 months).</blockquote><blockquote>2. Detect: compare today’s stream to the reference using KS/PSI/mean-std and prediction rates.</blockquote><blockquote>3. Explain: identify which features moved; trace to source tables/jobs.</blockquote><blockquote>4. Act: alert → threshold tune → retrain/rollback → verify.</blockquote><blockquote>Embed this in MLOps: nightly batch + near real-time checks on top 50–80 features.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3GjJwChgiqWjLy4WCvcH_Q.png" /><figcaption>Drift monitoring Architecture</figcaption></figure><h4><strong>Techniques we can use to detect drift:</strong></h4><blockquote><strong>1. Mean / Standard Deviation (fast sanity check)</strong></blockquote><blockquote>a. Compare mean/std between reference and current samples for each feature.</blockquote><blockquote>b. Great for catching scaled breaks (scale changes, unit flips).</blockquote><blockquote><strong>2. PSI — Population Stability Index</strong></blockquote><blockquote>a. Bins feature values, compares bucket proportions.</blockquote><blockquote>b. Rules of thumb: PSI &lt; 0.1 (stable), 0.1–0.25 (moderate), &gt; 0.25 (significant shift).</blockquote><blockquote>c. Widely used in financial services; easy to explain to stakeholders.</blockquote><blockquote><strong>3. KS — Kolmogorov–Smirnov (my default for fraud features)</strong></blockquote><blockquote>a. Non-parametric; makes no shape assumptions (important for skewed “amount” features).</blockquote><blockquote>b. Sensitive to both location and shape shifts.</blockquote><blockquote>c. Monitor D-stat directly; e.g., alert if D &gt; 0.1 on critical features.</blockquote><h4><strong>Production Workflow (KS at Scale)</strong></h4><h4><strong>Reference window</strong></h4><blockquote>· Use a stable training/holdout slice (e.g., 2 months).</blockquote><blockquote>· Persist ECDF or binned histograms.</blockquote><h4><strong>Live samples</strong></h4><blockquote>· Stream hourly/daily. To avoid “everything significant” with huge n, use random sampling (e.g., 5k–10k rows) or sketches.</blockquote><h4><strong>Compute</strong></h4><blockquote>· Per feature: D = max |F_ref(x) — F_cur(x)|; record p-value but alert on D.</blockquote><blockquote>· Also track prediction drift: accept/review/reject rates vs. baseline.</blockquote><h4><strong>Alerting &amp; SLOs</strong></h4><blockquote>· Tiered alerts:</blockquote><blockquote>o Info: D in [0.05, 0.1] two intervals in a row.</blockquote><blockquote>o Warn: D ≥ 0.1 on a high-importance feature, or reject rate +2σ.</blockquote><blockquote>o Page: D ≥ 0.15 on multiple key features or sudden reject spike.</blockquote><blockquote>· Dashboards (what to show)</blockquote><blockquote>o Top features by KS with trend lines (7–30 days).</blockquote><blockquote>o Prediction drift (accept / review / reject) vs baseline.</blockquote><h4><strong>Remediation</strong></h4><blockquote>· Data integrity (job broke, schema drift): fix job, backfill, clear alert.</blockquote><blockquote>· Behavioral shift (promo/season/attack): threshold tune (Accept/Review/Reject), trigger retrain via MLOps (shadow → canary → ramp).</blockquote><blockquote>· Rollback: one-click rollback to prior model/threshold set if KPIs degrade.</blockquote><blockquote>Feature health: null rate, cardinality, min/max, mean/std.</blockquote><blockquote>Drill-through: feature → upstream job/table → last change → owner.</blockquote><h4><strong>MLOps Notes for High Throughput</strong></h4><blockquote>Train/Serve parity: same feature code for batch &amp; online (feature store or shared lib).</blockquote><blockquote>Shadow → canary → ramp: never blind-flip thresholds or models.</blockquote><blockquote>Cheap retrains: one command/CI job; artifacts tracked; auto-rollback.</blockquote><blockquote>Multi-region: per-region drift baselines; don’t block one region for another.</blockquote><h4><strong>Summary</strong></h4><p>When labels are late, inputs and predictions are your early warning system. At enterprise scale, the winners aren’t just the best models. They’re the teams that observe change, explain it fast, and act safely.</p><p>Follow me <a href="https://medium.com/@sivaramakrishnaganta1234">here</a> and on <a href="https://www.linkedin.com/in/siva-rama-krishna-ganta-5204ba125/">LinkedIn</a> if you’d like to learn more about building ML for fraud prevention in the real world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcf3cbe2348b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Address Manipulation Fraud Using Vector Databases (Milvus + Embeddings)]]></title>
            <link>https://pub.towardsai.net/detecting-address-manipulation-fraud-using-vector-databases-milvus-embeddings-818976c40edd?source=rss-97a8b112b94a------2</link>
            <guid isPermaLink="false">https://medium.com/p/818976c40edd</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[address]]></category>
            <category><![CDATA[fraud]]></category>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Siva Ganta]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 18:59:31 GMT</pubDate>
            <atom:updated>2026-01-29T04:53:07.167Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Why Address Matching Is a Fraud Problem (Not a String Problem)</strong></p><p>Fraudsters almost never reuse addresses verbatim.</p><p>Instead, they introduce <strong>small but deliberate mutations</strong> to bypass traditional checks:</p><ul><li>456 Juniper Street Apt 20 → 456 Ju//per St ap////ent #20</li><li>Houston → Hou-ston, H.o.u.s.t.o.n, Hstn</li><li>Apt 20 → missing, reordered, or replaced with #</li></ul><p>At scale, this breaks:</p><ul><li>Exact matching</li><li>Regex rules</li><li>Traditional fuzzy matching</li></ul><p>What we need is a system that understands <strong>semantic similarity</strong>, not surface-level text equality.</p><p>This is where <strong>vector embeddings + vector databases</strong> become extremely powerful.</p><p><strong>The Core Idea</strong></p><p>Instead of asking:</p><p>“Are these two addresses textually similar?”</p><p>We ask:</p><p>“Do these two addresses <em>mean</em> the same thing?”</p><p>We achieve this by:</p><ol><li>Converting addresses into <strong>vector embeddings</strong></li><li>Storing known risky addresses in a <strong>vector database</strong></li><li>Retrieving the <strong>top-K nearest neighbors</strong> for each transaction address.</li></ol><p><strong>High Level Design</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YMqOAnD54om3c5SQx1xdDA.png" /><figcaption>Address manipulation detection</figcaption></figure><p><strong>Why Vector Databases Work So Well</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OCTX6X_ZYkMPTHgNYVjT7Q.png" /></figure><p>This allows us to detect:</p><ul><li>Near-duplicates</li><li>Misspellings</li><li>Reordered tokens</li><li>Deliberate obfuscation</li></ul><p><strong>Step 1: Canonicalizing Addresses (Critical)</strong></p><p>Before embeddings, <strong>normalization matters more than the model</strong>.</p><p>We must:</p><ul><li>Remove junk characters inside words</li><li>Preserve word boundaries</li><li>Normalize abbreviations</li></ul><p><strong>Example</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jFHinVbsEbs1d7_i-uujRQ.png" /></figure><p><strong>Canonicalization Logic</strong></p><pre>def canon_addr(s: str) -&gt; str:<br>    s = unicodedata.normalize(&quot;NFKC&quot;, s or &quot;&quot;).lower().strip()<br><br>    # Glue junk characters inside tokens (ju//per → juper)<br>    s = re.sub(r&quot;(?&lt;=[a-z0-9])[\/\.\-\_]+(?=[a-z0-9])&quot;, &quot;&quot;, s)<br><br>    # Replace remaining punctuation with space<br>    s = re.sub(r&quot;[^\w\s]&quot;, &quot; &quot;, s)<br>    s = re.sub(r&quot;_&quot;, &quot; &quot;, s)<br><br>    # Normalize abbreviations<br>    s = re.sub(r&quot;\bst\b&quot;, &quot;street&quot;, s)<br>    s = re.sub(r&quot;\bave\b&quot;, &quot;avenue&quot;, s)<br>    s = re.sub(r&quot;\bapt\b|\bapartment\b|#&quot;, &quot;apt&quot;, s)<br><br>    return re.sub(r&quot;\s+&quot;, &quot; &quot;,</pre><p>This single step dramatically improves ranking quality.</p><p><strong>Step 2: Generating Address Embeddings</strong></p><p>We use a lightweight sentence embedding model:</p><p>SentenceTransformer(“all-MiniLM-L6-v2”)</p><p>Why it works:</p><ul><li>Handles short text well</li><li>Robust to noise</li><li>Fast inference</li><li>Produces 384-dim vectors</li></ul><p>Each address becomes a <strong>semantic fingerprint</strong>.</p><p><strong>Step 3: Storing Risky Addresses in Milvus</strong></p><p><strong>Schema</strong></p><p>id → primary key</p><p>address_text → canonicalized address</p><p>embedding → vector representation</p><p><strong>Index Choice</strong></p><ul><li><strong>HNSW</strong> (Hierarchical Navigable Small World)</li><li><strong>Cosine similarity</strong></li></ul><p>This gives:</p><ul><li>Sub-millisecond top-K retrieval</li><li>Excellent recall under noise</li></ul><p><strong>Step 4: Querying During Transactions</strong></p><p>For each transaction address:</p><pre>query_vec = model.encode([canon_addr(tx_address)])<br>results = collection.search(<br>data=query_vec,<br>anns_field=&quot;embedding&quot;,<br>metric_type=&quot;COSINE&quot;,<br>limit=5<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJr56Bfz4tbJ8hKl4Ukoww.png" /></figure><p>· Even heavily obfuscated inputs still retrieve the correct address.</p><p><strong>Why Ranking Sometimes Looks “Wrong”</strong></p><p>You may see:</p><ul><li>Same street &amp; city outranking exact house/unit matches</li></ul><p>Why?</p><ul><li>Embeddings prioritize <strong>semantic overlap</strong></li><li>Street + city dominates similarity space</li></ul><p><strong>Solution: Hybrid Scoring</strong></p><p>Vector DBs are for <strong>retrieval</strong>, not final decisioning.</p><p>Final score should combine:</p><p>final_score = vector_similarity + house_number_match + unit_match + zip_match</p><p><strong>Fraud Signals You Can Build</strong></p><ul><li>max_similarity_to_risky_address</li><li>count_above_similarity_threshold</li><li>shipping_vs_billing_similarity</li><li>device_vs_shipping_similarity</li></ul><p>These features plug directly into:</p><ul><li>Fraud ML models</li><li>Rule engines</li><li>Risk scoring pipelines</li></ul><p><strong>Final Working Solution</strong></p><p><strong>1.</strong> <strong>Local Setup (Milvus Using Docker)</strong></p><p>To test locally, Milvus is deployed as a standalone Docker service.</p><p>Steps followed:</p><p>· Run Milvus using Docker Compose</p><p>· Expose ports for PyMilvus client access</p><p>· Verify health before ingestion</p><p>Resources:</p><p>· Milvus installation video walkthrough (<a href="https://www.youtube.com/watch?v=K0ZayH0n7sI&amp;t=431s">Docker</a>)</p><p>· Official <a href="https://www.youtube.com/redirect?event=video_description&amp;redir_token=QUFFLUhqbmJZdVlUT2JnRGtVZW5vb2tjblp5RnVFd1VoUXxBQ3Jtc0trMXgzWXduZXVWY2xyTjVqNHk5Nl9Db0wwb3dxeUFVTG5yNlhTQW1jcC11cU1EVTVPTG1QanJuTkd4ZTNZWEFESEdISGVKM1pMaTZZUU51aEx3UGxyRm9XWjJKN1NjenVNLU9RQ0pQZHJjNlUwQkxyaw&amp;q=https%3A%2F%2Fmilvus.io%2Fdocs%2Fv2.0.x%2Finstall_standalone-docker.md&amp;v=K0ZayH0n7sI">Milvus</a> documentation</p><p>· PyMilvus client for Python integration</p><p>This setup closely mirrors a real production deployment.</p><p>2. <strong>Code</strong></p><p>milvus.py</p><pre>from pymilvus import connections, FieldSchema, CollectionSchema, DataType, Collection, utility<br>from sentence_transformers import SentenceTransformer<br>import numpy as np<br><br>import re, unicodedata<br>from difflib import get_close_matches<br><br>STREET_SYNONYMS = {<br>    r&quot;\bave\b&quot;: &quot;avenue&quot;, r&quot;\bblvd\b&quot;: &quot;boulevard&quot;, r&quot;\brd\b&quot;: &quot;road&quot;, r&quot;\bst\b&quot;: &quot;street&quot;<br>}<br>UNIT_SYNONYMS = {<br>    r&quot;#&quot;: &quot; apt &quot;, r&quot;\bapt\.?\b&quot;: &quot; apt &quot;, r&quot;\bapartment\b&quot;: &quot; apt &quot;,<br>    r&quot;\bunit\b&quot;: &quot; apt &quot;, r&quot;\bste\.?\b&quot;: &quot; suite &quot;, r&quot;\bsuite\b&quot;: &quot; suite &quot;<br>}<br><br># characters we want to glue-through inside a token<br>_INTRA_TOKEN_DELIMS = r&quot;[\/\.\-\_-–—\u00A0\u200B\u200C\u200D]+&quot;  # slash, dot, dashes, NBSP, zero-widths<br><br>def canon_addr(s: str) -&gt; str:<br>    s = unicodedata.normalize(&quot;NFKC&quot;, s or &quot;&quot;).lower().strip()<br><br>    # # 1) glue only punctuation-like delimiters *inside* tokens (keep real spaces!)<br>    s = re.sub(r&quot;(?&lt;=[a-z0-9])[\/\.\-\_]+(?=[a-z0-9])&quot;, &quot;&quot;, s)<br><br>    # 2) normalize dots/commas and other non-alnum (not spaces) to space<br>    s = re.sub(r&quot;[^\w\s]&quot;, &quot; &quot;, s)          # keep letters/digits/underscore/space<br>    s = re.sub(r&quot;_&quot;, &quot; &quot;, s)                # drop underscores to space<br><br>    # 3) apply synonyms<br>    for pat, rep in STREET_SYNONYMS.items():<br>        s = re.sub(pat, rep, s)<br>    for pat, rep in UNIT_SYNONYMS.items():<br>        s = re.sub(pat, rep, s)<br><br>    # 4) collapse spaces<br>    s = re.sub(r&quot;\s+&quot;, &quot; &quot;, s).strip()<br>    return s<br><br>def correct_tokens_to_vocab(text: str, vocab: set, cutoff=0.8):<br>    toks, fixed = text.split(), []<br>    for t in toks:<br>        cand = get_close_matches(t, vocab, n=1, cutoff=cutoff)<br>        fixed.append(cand[0] if cand else t)<br>    return &quot; &quot;.join(fixed)<br><br><br>connections.connect(&#39;default&#39;, host=&#39;127.0.0.1&#39;, port=19530)<br>if utility.has_collection(&quot;risky_addresses&quot;):<br>    utility.drop_collection(&quot;risky_addresses&quot;)<br><br>print(&#39;connection to milvus db successful&#39;)<br><br># 2️⃣ Define schema for risky addresses<br># -----------------------------------------------------<br>fields = [<br>    FieldSchema(name=&quot;id&quot;, dtype=DataType.INT64, is_primary=True, auto_id=True),<br>    FieldSchema(name=&quot;address_text&quot;, dtype=DataType.VARCHAR, max_length=256),<br>    FieldSchema(name=&quot;embedding&quot;, dtype=DataType.FLOAT_VECTOR, dim=384),<br>]<br><br>schema = CollectionSchema(fields, description=&quot;Known risky addresses&quot;)<br>collection = Collection(name=&quot;risky_addresses&quot;, schema=schema)<br>print(&quot; schema definition is successfully imported&quot;)<br><br># 3️⃣ Create index for fast ANN search<br># -----------------------------------------------------<br>index_params = {<br>    &quot;metric_type&quot;: &quot;COSINE&quot;,<br>    &quot;index_type&quot;: &quot;HNSW&quot;,<br>    &quot;params&quot;: {&quot;M&quot;: 16, &quot;efConstruction&quot;: 200}<br>}<br>collection.create_index(field_name=&quot;embedding&quot;, index_params=index_params)<br>print(&#39;index creation is successful&#39;)<br><br># -----------------------------------------------------<br># 4️⃣ Load embedding model<br># -----------------------------------------------------<br>model = SentenceTransformer(&quot;all-MiniLM-L6-v2&quot;)<br>print(&#39;sentence transformer model loading is successful&#39;)<br><br># 5️⃣ Insert a few risky addresses<br># -----------------------------------------------------<br>risky_addresses = [<br>  &quot;456 Juniper Street Apt 20, Houston, TX 72715&quot;,<br> &quot;456 Juniper Street Apt 20, Houston, TX 72715&quot;,<br><br>&quot;187 Juniper St, Houston, TX 72718&quot;,<br>  &quot;1100 SWModern Street, Bentonville , Ar 72713&quot;,<br>  &quot;PO Box 900, Fayetbille, AR 72720&quot;,<br>  &quot;12C Juniper Avenue, Bentonville , Ar 72713&quot;,<br>]<br><br># When inserting risky addresses<br>risky_addresses_clean = [canon_addr(a) for a in risky_addresses]<br>print(risky_addresses_clean)<br>embeddings = model.encode(risky_addresses_clean).tolist()<br>collection.insert([risky_addresses_clean, embeddings])<br><br>collection.flush()<br>collection.load()  # load into memory for search<br>print(&#39;Risky address embeddings collection loading into the milvus db is successful&#39;)<br><br><br># -----------------------------------------------------<br># 6️⃣ Query a new address (e.g., from current transaction)<br># -----------------------------------------------------<br><br>query_addr_1 = &quot;456 Jniper St apartment #20, Houston, TX 72715&quot;<br><br>query_addr_2 = &quot;456 Juniper Street apt #20, Houston, TX 72715&quot;<br><br>query_addr_3 = &quot;456 Jper Ave apt #20, Hou-Ston, TX 72715&quot;<br>query_addr_4 = &quot; Juniper Ave 456 #20, Hstn, tx 72715&quot;<br><br>query_addr_5 = &quot; J//p//r Av//e 45//8 //26, H.o.u.s.t.o.n, tx 72715&quot;<br><br>query_addr_6 = &quot; jUnIp//r Av//E 45//8 //26, H0uston, Tx 72715&quot;<br><br>from difflib import SequenceMatcher<br>def token_sort_ratio(a,b):<br>    return SequenceMatcher(None, &quot; &quot;.join(sorted(a.split())), &quot; &quot;.join(sorted(b.split()))).ratio()<br><br>def extract_house(text):<br>    m = re.search(r&quot;\b\d+\b&quot;, text); return m.group(0) if m else &quot;&quot;<br>def extract_zip(text):<br>    m = re.search(r&quot;\b\d{5}\b&quot;, text); return m.group(0) if m else &quot;&quot;<br><br><br><br><br>for query_addr in [query_addr_1, query_addr_2, query_addr_3, query_addr_4, query_addr_5, query_addr_6]:<br>    print(&#39;Get the closest addresses to {} \n\n&#39;.format(query_addr))<br>    query_norm = canon_addr(query_addr)<br>    print(query_norm)<br>    query_vec = model.encode([query_norm])<br><br>    search_params = {&quot;metric_type&quot;: &quot;COSINE&quot;, &quot;params&quot;: {&quot;ef&quot;: 64}}<br>    results = collection.search(<br>        data=query_vec,<br>        anns_field=&quot;embedding&quot;,<br>        param=search_params,<br>        limit=5,<br>        output_fields=[&quot;address_text&quot;]<br>    )<br><br><br>    # -----------------------------------------------------<br>    # 7️⃣ Display top matches<br>    # -----------------------------------------------------<br>    # for hits in results:<br>    #     for rank, hit in enumerate(hits):<br>    #         print(f&quot;Rank {rank+1}: {hit.entity.get(&#39;address_text&#39;)} (score={hit.distance:.4f})&quot;)<br><br>    q_house, q_zip = extract_house(query_norm), extract_zip(query_norm)<br>    for hits in results:<br>        reranked = sorted(<br>            hits,<br>            key=lambda h: (<br>                    0.78 * float(h.distance) +<br>                    0.18 * token_sort_ratio(query_norm, h.entity.get(&quot;address_text&quot;, &quot;&quot;)) +<br>                    (0.03 if extract_house(h.entity.get(&quot;address_text&quot;, &quot;&quot;)) == q_house else 0.0) +<br>                    (0.01 if extract_zip(h.entity.get(&quot;address_text&quot;, &quot;&quot;)) == q_zip else 0.0)<br>            ),<br>            reverse=True<br>        )<br><br>    for rank, hit in enumerate(reranked):<br>        print(f&quot;Rank {rank + 1}: {hit.entity.get(&#39;address_text&#39;)} (score={hit.distance:.4f})&quot;)</pre><p>The script:</p><p>· Creates the Milvus collection</p><p>· Applies HNSW indexing</p><p>· Inserts canonicalized risky addresses</p><p>· Performs similarity search and hybrid re-ranking</p><p><strong>Key Takeaways</strong></p><p>· Address manipulation is fundamentally a semantic problem</p><p>· Vector databases enable fast, scalable near-duplicate detection</p><p>· Canonicalization is as important as embeddings</p><p>· Hybrid scoring delivers production-grade precision</p><p>Follow me <a href="https://medium.com/@sivaramakrishnaganta1234">here</a> and on <a href="https://www.linkedin.com/in/siva-rama-krishna-ganta-5204ba125/">LinkedIn</a> if you’d like to learn more about building ML for fraud prevention in the real world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=818976c40edd" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/detecting-address-manipulation-fraud-using-vector-databases-milvus-embeddings-818976c40edd">Detecting Address Manipulation Fraud Using Vector Databases (Milvus + Embeddings)</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Real-Time Features for Fraud Detection at Scale]]></title>
            <link>https://pub.towardsai.net/designing-real-time-features-for-fraud-detection-at-scale-490afd927152?source=rss-97a8b112b94a------2</link>
            <guid isPermaLink="false">https://medium.com/p/490afd927152</guid>
            <category><![CDATA[cassandra]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Siva Ganta]]></dc:creator>
            <pubDate>Fri, 03 Oct 2025 22:10:16 GMT</pubDate>
            <atom:updated>2026-01-30T04:06:31.111Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>In fraud prevention, <strong>features are the lifeblood of machine learning models</strong>. While algorithm choice matters, in practice, the <strong>speed and accuracy of feature computation</strong> often determines how effective your system will be in stopping fraud.</p><p>Fraudsters adapt quickly: some attacks play out over minutes, others over months. To stay ahead, fraud prevention systems must combine <strong>near real-time features (minute/hour)</strong> with <strong>batch-based daily features</strong> and serve them seamlessly into models running at scale.</p><p>In this article, I’ll explain:</p><ul><li>Types of features used in fraud prevention.</li><li>How <strong>minute/hour features</strong> are computed in real time.</li><li>How <strong>daily features</strong> are prepared via batch pipelines.</li><li>The <strong>combined architecture</strong> that powers these systems in production.</li></ul><p><strong>Types of Features in Fraud Prevention</strong></p><p>1. <strong>Batch Features</strong></p><p>o Aggregated over long-term time windows (days to months).</p><p>o Capture steady behavioral trends.</p><p>2. <strong>Direct Features</strong></p><p>o Attributes directly available from a transaction (amount, card type, device, etc.).</p><p>3. <strong>External Features</strong></p><p>o Provided by third-party systems (device fingerprinting, geolocation APIs, blacklists).</p><p>The real power comes from blending <strong>short-window (minute/hour)</strong> with <strong>long-window (daily)</strong> features in one pipeline.</p><p><strong>Minute/Hour Features (Near Real-Time)</strong></p><p>These are <strong>short-window velocity features</strong>, such as:</p><ul><li>Number of transactions in the last 10 minutes, 30 minutes, 1 hour.</li><li>Number of login attempts (success/fail) in the past 5 hours.</li><li>Number of unique devices used in the last 24 hours.</li></ul><p><strong>How it works in production:</strong></p><ul><li>Event sources (transactions, logins, devices, IPs) stream into <strong>Kafka / Pub-Sub</strong>.</li><li>A <strong>feature updater service</strong> (Kafka consumer or part of the inference app) writes entity-level raw data or counters into <strong>Dynamo</strong> db/<strong>Cassandra/mysql/Hbase etc</strong></li><li>At inference, the scoring API queries(range queries etc) Cassandra using <strong>entity IDs (member_id, device_id, payment_id)</strong> as partition keys and <strong>timestamps</strong> as clustering keys</li></ul><p><strong>Tech stack:</strong> Python/Flask, Kafka, Cassandra/Dynamo db, Docker/Kubernetes, Grafana/Splunk.</p><p><strong>Daily Features (Batch Aggregations)</strong></p><p>Daily features capture <strong>longer-term trends</strong> such as:</p><ul><li>Transactions per entity in last 7/30/90/180/360 days.</li><li>Refund attempts in the last year.</li><li>Unique geolocations used over 6 months.</li></ul><p><strong>How it works in production:</strong></p><ul><li><strong>Airflow</strong> orchestrates <strong>Spark (PySpark)</strong> jobs each night.</li><li>Aggregations are stored in <strong>Hive / BigQuery/Red shift </strong>for long-term training (multi-year history).</li><li>Recent daily aggregates (e.g., last 5 days) are pushed into <strong>Cassandra</strong> for real-time inference.</li></ul><p>This ensures <strong>one feature pipeline supports both training and inference</strong>, minimizing train/serve skew.</p><p><strong>Tech stack:</strong> Spark/PySpark, Airflow, Hive/BigQuery, Cassandra/Dynamo db.</p><p><strong>Combined Architecture</strong></p><p>The figure below shows a <strong>generic fraud ML system architecture</strong> that integrates both <strong>real-time and batch features</strong> into a single scoring path:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D7mVus7Nk9ouCmeTCna4HQ.png" /></figure><p><strong>Flow:</strong></p><p>1. <strong>Data Sources</strong> (logins, transactions, devices, locations) → <strong>Streaming Ingest (Kafka)</strong>.</p><p>2. <strong>Feature Pipelines</strong> calculate:</p><p>o Real-time features (minute/hour) → Cassandra.</p><p>o Batch daily features (7–360 days) → Hive/BigQuery → Cassandra (short-term).</p><p>3. <strong>Feature Store</strong> (Cassandra/Dynamo db+ Hive/BigQuery) serves both training and inference.</p><p>4. <strong>Model Training Pipeline</strong> prepares features, tunes hyperparameters, evaluates, and stores models in a <strong>Model Registry (MLflow)</strong>.</p><p>5. <strong>Inference Service</strong> (Flask/FastAPI) fetches features from Cassandra and returns predictions.</p><p>6. <strong>Decisioning Layer</strong> applies thresholds to Accept, Review, or Reject.</p><p>7. <strong>Monitoring</strong> tracks latency, drift, and errors with Grafana/Splunk.</p><p><strong>Best Practices</strong></p><p>✅ <strong>Schema Design:</strong> Use entity IDs as partition keys and timestamps as clustering keys in Cassandra.<br> ✅ <strong>Freshness vs Cost:</strong> Keep only high-value features real time; aggregate others daily.<br> ✅ <strong>Consistency:</strong> Use the same pipelines for training and inference to prevent skew.<br> ✅ <strong>Latency Budgets:</strong> Keep feature fetch + model scoring &lt; 200 ms for real-time transactions.<br> ✅ <strong>Monitoring Drift:</strong> Apply KS test, PSI, and summary stats (mean/median) to detect data drift early.</p><p><strong>Closing thought:</strong></p><p>Real-time fraud prevention is as much <strong>data engineering</strong> as it is machine learning. The key lies in balancing <strong>fresh, streaming features</strong> with <strong>stable batch features</strong> — and making them both available in a low-latency serving environment.</p><p>In my next article, I’ll explore <strong>complete ML system design for fraud detection</strong> using distributed machine learning frameworks.</p><p>Follow me <a href="https://medium.com/@sivaramakrishnaganta1234">here</a> and on <a href="https://www.linkedin.com/in/siva-rama-krishna-ganta-5204ba125/">LinkedIn</a> if you’d like to learn more about building ML for fraud prevention in the real world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=490afd927152" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/designing-real-time-features-for-fraud-detection-at-scale-490afd927152">Designing Real-Time Features for Fraud Detection at Scale</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Stacking for Fraud Detection: Long-Term vs. Short-Term Models]]></title>
            <link>https://pub.towardsai.net/model-stacking-for-fraud-detection-long-term-vs-short-term-models-c388347eba99?source=rss-97a8b112b94a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c388347eba99</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[model-stacking]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <category><![CDATA[fraud-detection]]></category>
            <dc:creator><![CDATA[Siva Ganta]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 20:13:55 GMT</pubDate>
            <atom:updated>2026-01-30T04:06:27.178Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7HrwQyXx58pBxX1GUIURg.png" /></figure><p>Fraud in digital commerce evolves quickly. Some patterns persist for years, while new tactics emerge every few weeks. Relying on a single machine learning model is often not enough.</p><p>One powerful approach is <strong>model stacking</strong> — combining models trained on different time horizons and with different strengths. In this article, I’ll walk through how stacking long-term and short-term fraud models works, why it’s effective, and three practical ways to implement it. A runnable notebook and a diagram are linked at the end.</p><p><strong>Long-Term vs. Short-Term Models</strong></p><p><strong>Long-Term Model</strong></p><ul><li>Trained on <strong>1.5–2 years</strong> of historical data</li><li>Captures <strong>established fraud patterns</strong></li><li>Retrained less often (e.g., quarterly/bi-annually)</li><li>Pros: stable, robust coverage; Cons: slower to adapt</li></ul><p><strong>Short-Term Model</strong></p><ul><li>Trained on <strong>3–6 months</strong> of recent data</li><li>Captures <strong>emerging/seasonal patterns</strong></li><li>Retrained frequently (e.g., monthly)</li><li>Pros: agile to new attacks; Cons: less historical context</li></ul><p><strong>Why stack them?</strong> You get the <strong>stability</strong> of the long-term model and the <strong>agility</strong> of the short-term model in one decisioning layer.</p><p><strong>Advantages of Stacking</strong></p><ol><li><strong>Comprehensive coverage</strong> of both established and emerging fraud.</li><li><strong>Faster ramp-up</strong> — adapt quickly without retraining big models.</li><li><strong>Efficiency</strong> — reduce cost by training large models less often.</li><li><strong>Better decisioning</strong> — improve capture while controlling false positives.</li></ol><p><strong>Methods of Stacking</strong></p><p><strong>1) Recommendation Stacking</strong></p><p>Each model outputs a recommendation:</p><ul><li>Accept → <strong>0</strong></li><li>Manual Review → <strong>1</strong></li><li>Reject → <strong>2</strong></li></ul><p>Sum the two model recommendations to get a <strong>stacked score (0–4)</strong>, then apply thresholds for final action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*l7eR9UufRh39JnHH0F_0AA.png" /></figure><p><strong>When to use:</strong> operational simplicity; easy to explain to risk ops.</p><p><strong>2) Average-Score Stacking</strong></p><ul><li>Standardize each model’s probability to a <strong>0–1000</strong> score.</li><li>Take the <strong>average</strong> and apply thresholds for Accept/Review/Reject.</li></ul><p><strong>When to use:</strong> one model excels at high-dollar fraud while the other excels at low-dollar fraud — you want both strengths.</p><p><strong>3) Meta-Model Stacking</strong></p><ul><li>Use the two model outputs (probabilities or logits) as <strong>features</strong>.</li><li>Train a small <strong>meta-model</strong> (e.g., logistic regression, gradient boosting) to produce the final decision.</li></ul><p><strong>When to use:</strong> you can support a small extra model and want the best lift.</p><h3>Closing Thought</h3><p>Fraudsters evolve constantly, and relying on a single model is like locking just one door in a house with many entry points. By stacking <strong>long-term and short-term models</strong>, we create a layered defense that is both stable and adaptive.</p><p>In practice, I’ve seen stacking approaches significantly improve fraud capture rates while reducing false positives — protecting businesses and enhancing customer experience.</p><p><strong>Try It Yourself (Notebook)</strong></p><p>I’ve published a notebook that simulates an imbalanced, time-ordered dataset; trains a long-term and short-term model; and demonstrates all three stacking methods:</p><ul><li>Notebook:</li></ul><pre>#%% md<br><br># Model Stacking for Fraud Detection: Long‑Term vs. Short‑Term Models<br><br>This notebook simulates two fraud models trained on different time horizons and shows three stacking strategies:<br><br>1. **Recommendation stacking** (Accept/Review/Reject → score 0–4)  <br>2. **Average‑score stacking** (standardize to 0–1000, then average)  <br>3. **Meta‑model stacking** (use model outputs as features for a logistic regression)<br><br>&gt; **Note:** This is a synthetic, educational demo. Replace the data generation with your dataset and keep your company’s confidential details out of any public derivative.<br><br>#%%<br><br># If needed, install packages (uncomment when running locally)<br># !pip install xgboost scikit-learn pandas numpy matplotlib<br><br>#%%<br><br>import numpy as np, pandas as pd<br>from sklearn.datasets import make_classification<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import roc_auc_score, precision_recall_fscore_support<br>from sklearn.linear_model import LogisticRegression<br>from xgboost import XGBClassifier  # swap for LightGBM if preferred<br><br>RANDOM_STATE = 42<br>np.random.seed(RANDOM_STATE)<br><br>#%% md<br>## 1) Simulate an imbalanced, time‑ordered fraud dataset<br>#%%<br><br># 50k samples, highly imbalanced (0.8% fraud)<br>X, y = make_classification(<br>    n_samples=50000, n_features=40, n_informative=15, n_redundant=5,<br>    weights=[0.992, 0.008], flip_y=0.001, random_state=RANDOM_STATE<br>)<br>df = pd.DataFrame(X)<br>df[&quot;label&quot;] = y<br>df[&quot;t&quot;] = np.arange(len(df))  # chronological index<br><br># Train/test split by time (not random shuffle)<br>cut = int(0.8 * len(df))<br>train_df = df.iloc[:cut].copy()<br>test_df  = df.iloc[cut:].copy()<br><br># Within train, define long-term (older ~18 months) vs short-term (recent ~3-6 months) windows<br>lt_cut = int(0.85 * len(train_df))<br>long_train = train_df.iloc[:lt_cut]<br>short_train = train_df.iloc[lt_cut:]<br><br>X_long, y_long = long_train.drop(columns=[&quot;label&quot;,&quot;t&quot;]).values, long_train[&quot;label&quot;].values<br>X_short, y_short = short_train.drop(columns=[&quot;label&quot;,&quot;t&quot;]).values, short_train[&quot;label&quot;].values<br>X_test, y_test   = test_df.drop(columns=[&quot;label&quot;,&quot;t&quot;]).values, test_df[&quot;label&quot;].values<br><br>X_long.shape, X_short.shape, X_test.shape<br><br>#%% md<br>## 2) Train long‑term &amp; short‑term models<br>#%%<br><br># Long‑term model: larger window, retrained less frequently<br>long_model = XGBClassifier(<br>    n_estimators=400, max_depth=6, learning_rate=0.05,<br>    subsample=0.9, colsample_bytree=0.9, reg_lambda=1.0,<br>    random_state=RANDOM_STATE, n_jobs=-1, scale_pos_weight=(1/0.008 - 1)<br>)<br>long_model.fit(X_long, y_long)<br><br># Short‑term model: recent window, adapts faster<br>short_model = XGBClassifier(<br>    n_estimators=250, max_depth=5, learning_rate=0.07,<br>    subsample=0.9, colsample_bytree=0.9, reg_lambda=1.0,<br>    random_state=RANDOM_STATE+1, n_jobs=-1, scale_pos_weight=(1/0.008 - 1)<br>)<br>short_model.fit(X_short, y_short)<br><br># Predictions on test<br>p_long  = long_model.predict_proba(X_test)[:, 1]<br>p_short = short_model.predict_proba(X_test)[:, 1]<br><br>#%% md<br>## 3) Baseline metrics<br>#%%<br><br>def summarize(y_true, scores, name, thr=0.5):<br>    auc = roc_auc_score(y_true, scores)<br>    y_pred = (scores &gt;= thr).astype(int)<br>    p, r, f1, _ = precision_recall_fscore_support(y_true, y_pred, average=&quot;binary&quot;, zero_division=0)<br>    return {&quot;model&quot;: name, &quot;AUC&quot;: auc, &quot;precision&quot;: p, &quot;recall&quot;: r, &quot;f1&quot;: f1}<br><br>metrics = []<br>metrics.append(summarize(y_test, p_long,  &quot;Long‑term&quot;))<br>metrics.append(summarize(y_test, p_short, &quot;Short‑term&quot;))<br>pd.DataFrame(metrics).round(4)<br><br>#%% md<br>## 4) Stacking methods<br>#%%<br><br># (A) Recommendation stacking<br>def label_from_prob(p, t_accept=0.2, t_reject=0.8):<br>    # &lt;0.2 -&gt; accept(0), 0.2–0.8 -&gt; review(1), &gt;=0.8 -&gt; reject(2)<br>    return np.where(p &gt;= t_reject, 2, np.where(p &lt; t_accept, 0, 1))<br><br>lt_rec = label_from_prob(p_long)<br>st_rec = label_from_prob(p_short)<br>stack_score_rec = lt_rec + st_rec  # 0..4<br><br># Convert back to a score for AUC (scale 0..1) and a binary decision for P/R/F1<br>auc_rec = roc_auc_score(y_test, stack_score_rec / 4.0)<br>y_pred_rec = (stack_score_rec &gt;= 3).astype(int)  # threshold example<br>p, r, f1, _ = precision_recall_fscore_support(y_test, y_pred_rec, average=&quot;binary&quot;, zero_division=0)<br>rec_metrics = {&quot;model&quot;: &quot;Stacking: recommendation&quot;, &quot;AUC&quot;: auc_rec, &quot;precision&quot;: p, &quot;recall&quot;: r, &quot;f1&quot;: f1}<br><br># (B) Average‑score stacking<br>s_long  = (p_long  * 1000.0)<br>s_short = (p_short * 1000.0)<br>s_avg   = (s_long + s_short) / 2.0<br><br>auc_avg = roc_auc_score(y_test, s_avg / 1000.0)<br>y_pred_avg = (s_avg &gt;= 700).astype(int)  # threshold example<br>p, r, f1, _ = precision_recall_fscore_support(y_test, y_pred_avg, average=&quot;binary&quot;, zero_division=0)<br>avg_metrics = {&quot;model&quot;: &quot;Stacking: average score&quot;, &quot;AUC&quot;: auc_avg, &quot;precision&quot;: p, &quot;recall&quot;: r, &quot;f1&quot;: f1}<br><br># (C) Meta‑model stacking<br>meta_X = np.c_[p_long, p_short]<br>X_tr, X_va, y_tr, y_va = train_test_split(meta_X, y_test, test_size=0.5, random_state=RANDOM_STATE)<br>meta = LogisticRegression(max_iter=200)<br>meta.fit(X_tr, y_tr)<br>p_meta = meta.predict_proba(meta_X)[:, 1]<br>meta_metrics = summarize(y_test, p_meta, &quot;Stacking: meta‑model&quot;, thr=0.5)<br><br>pd.DataFrame([rec_metrics, avg_metrics, meta_metrics]).round(4)<br><br>#%% md<br>## 5) Compare all approaches<br>#%%<br><br>import pandas as pd<br>all_metrics = pd.DataFrame([<br>    summarize(y_test, p_long,  &quot;Long‑term&quot;),<br>    summarize(y_test, p_short, &quot;Short‑term&quot;),<br>    rec_metrics, avg_metrics, meta_metrics<br>]).round(4)<br>all_metrics.sort_values(&quot;AUC&quot;, ascending=False).reset_index(drop=True)</pre><p>Follow me <a href="https://medium.com/@sivaramakrishnaganta1234">here</a> and on <a href="https://www.linkedin.com/in/siva-rama-krishna-ganta-5204ba125/">LinkedIn</a> if you’d like to learn more about building ML for fraud prevention in the real world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c388347eba99" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/model-stacking-for-fraud-detection-long-term-vs-short-term-models-c388347eba99">Model Stacking for Fraud Detection: Long-Term vs. Short-Term Models</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Machine Learning Features for Fraud Detection at Scale]]></title>
            <link>https://medium.com/@sivaramakrishnaganta1234/designing-machine-learning-features-for-fraud-detection-at-scale-eb96540687dc?source=rss-97a8b112b94a------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb96540687dc</guid>
            <category><![CDATA[ml-in-production]]></category>
            <category><![CDATA[online-fraud-detection]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[fraud-detection]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Siva Ganta]]></dc:creator>
            <pubDate>Sat, 20 Sep 2025 23:39:50 GMT</pubDate>
            <atom:updated>2025-09-28T19:56:10.805Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*adGkTTODKgD3R6uIhZk7kA.png" /></figure><p>Fraud detection is often framed as a modeling problem. We debate whether to use XGBoost, LightGBM, neural networks, or deep ensembles. But in practice, the biggest gains I’ve seen in real-world fraud prevention don’t come from the algorithm, they come from <strong>the features we design.</strong></p><p>When fraudsters evolve their tactics, it’s not your model architecture that fails first. It’s the signals. Strong features make your models resilient. Weak features make even the best algorithms blind.</p><p>In this article, I’ll share a framework for thinking about <strong>feature design at scale</strong> in fraud detection, drawn from my experience building systems that have prevented over $200M in fraud losses annually.</p><p>Note: In any digital payment systems, firstly, understand the journey of a customer from login to payment to checkout etc. So, you will understand what all data points we can collect and create features.</p><p><strong>Categories of Fraud Features</strong></p><p><strong>1.</strong> <strong>Behavioral Features</strong></p><p>Fraudsters behave differently from genuine customers. Instead of asking “what happened once,” good features ask, “how is this user behaving over time?”</p><p>Examples :</p><ul><li>Average purchase size in the last x hours vs. last y days for x in [1, 2, 12, 24] and for y in [15, 30, 90, 180, 360]</li><li>Member login behavior over the time range</li><li>Login success/fail</li><li>Devices used -new/existing</li><li>Location — new/existing</li><li>Password change/reset</li><li>Number of unique devices used per user id, payment id, location and vice versa in a short time window and longtime windows</li></ul><p>These capture intent, not just isolated actions.</p><p><strong>2.</strong> <strong>Velocity Features</strong></p><p>Fraud is often about speed and bursts of activity. Genuine customers act at human pace. Fraud rings don’t.</p><p>Examples:</p><ul><li>Transactions per minute/hour/day</li><li>Successful/Failed login attempts per account or device</li><li>Gift card redemption velocity</li><li>Unique devices/payments per minute/hour/day</li><li>Failed payments — cvv fails, avs fails</li><li>String matching features — billing addr, shipping addr fuzzy match score, mbr name, email fuzzy match etc, account email, billing email, shipping email etc</li></ul><p>Velocity features expose automation(bots) and high-pressure attempts.</p><p>3. <strong>Cross-Entity Features</strong></p><p>Fraud rarely happens in isolation. Fraudsters reuse data points across accounts.</p><p>Examples:</p><ul><li>Same billing/shipping/customer address tied to multiple accounts</li><li>Phone numbers/emails linked to dozens of credit cards</li><li>One device being used to log into many members accounts.</li></ul><p>Cross-entity linking often uncovers hidden fraud networks.</p><p>size etc.</p><p><strong>4. Network features:</strong></p><p>Here’s a <strong>visual example of how cross-entity features can be turned into a fraud network graph</strong>:</p><p>Each node represents an <strong>entity</strong> (account ID, phone, email, address, credit card).</p><p>Edges connect entities that were linked in the same transaction.</p><p>Clusters (connected components) can reveal <strong>fraud rings</strong> when multiple accounts share the same identifiers (like phone numbers, addresses, or cards).</p><p>In the sample diagram above, you can already see clusters forming:</p><p>a. <strong>Phone P1</strong> connects Account A1 and Account A2 → possible collusion.</p><p>b. <strong>Address AD1</strong> links Account A1 and Account A3.</p><p>c. <strong>Card C1</strong> connects Account A1 and Account A4.</p><p>d. This kind of network can be used to:</p><p>e. Identify <strong>connected components</strong> → groups of entities forming suspicious clusters.</p><p>f. Calculate <strong>component size</strong> → larger clusters are more likely to be fraud rings.</p><p>g. Generate <strong>network features</strong> like degree centrality (how many accounts a card is linked to) or clustering coefficient (tightness of a fraud group).</p><p>5. <strong>Aggregate and Time-Decayed Features</strong></p><p>Static counts are weak; <strong>decay functions</strong> add nuance.</p><ul><li>Weighted averages that emphasize recent behavior</li><li>Transaction frequency with recency bias</li><li>Suspicious signals that fade if not repeated</li></ul><p>Fraud changes quickly — features need to recognize when “old behavior” is no longer relevant.</p><p>6. <strong>Risk-Based Features</strong></p><p>Some attributes are inherently riskier than others.</p><ul><li>High-risk IP ranges</li><li>Disposable emails or unverified phone numbers</li><li>Large dollar amount variance compared to a member’s baseline</li><li>Fraud stats</li><li>Email, ip, phone, credit card, account, addresses linked to frauds</li></ul><p>These features serve as multipliers in your fraud model’s risk scoring.</p><p><strong>Real-World Challenges</strong></p><ul><li><strong>Feature Drift</strong></li><li>Fraud evolves, and yesterday’s strong feature may weaken tomorrow.</li><li>Continuous monitoring (e.g., KS test, median/mean shifts) is essential.</li><li><strong>Data Imbalance</strong></li><li>Fraud data is typically &lt;1% positive.</li><li>Without careful design, noisy features may overwhelm signal.</li><li><strong>Latency Constraints</strong></li><li>Real-time fraud detection means features must be fast to compute.</li><li>Batch features work in notebooks; production needs Kafka streams and efficient pipelines.</li></ul><p><strong>Best Practices</strong></p><ul><li><strong>Design around behavior, not raw values</strong><br> Fraudsters copy good customers on simple signals. Behavior over time is harder to fake.</li><li><strong>Keep features explainable</strong><br> Fraud models often feed into risk review teams. Transparent features help humans understand why a transaction was flagged.</li><li><strong>Focus on quality, not quantity</strong><br> Five strong features can outperform 500 weak ones. Each feature should have a clear purpose.</li><li><strong>Invest in monitoring and retraining<br> </strong>The life of a feature doesn’t end at deployment. Tracking drift and scheduling retrains are critical to long-term accuracy.</li></ul><p><strong>Closing Thought</strong></p><p>Fraud detection features are the <strong>DNA of machine learning models</strong> in this space. By carefully designing features that reflect real behavior, velocity, and relationships, you create models that are not only more accurate but also more resilient to evolving fraud tactics.</p><p>In the coming weeks, I’ll share more on:</p><ul><li>Model stacking techniques for fraud</li><li>Designing real-time feature pipelines</li><li>Complete ML system design for fraud detection at scale etc</li></ul><p>Follow me <a href="https://medium.com/@sivaramakrishnaganta1234">here</a> and on <a href="https://www.linkedin.com/in/siva-rama-krishna-ganta-5204ba125/">LinkedIn</a> if you’d like to learn more about building ML for fraud prevention in the real world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb96540687dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>