<?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 Rkhaghi on Medium]]></title>
        <description><![CDATA[Stories by Rkhaghi on Medium]]></description>
        <link>https://medium.com/@rkhaghi?source=rss-6ba70500a10------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*u-BYbKBc4xVC-YS8.jpg</url>
            <title>Stories by Rkhaghi on Medium</title>
            <link>https://medium.com/@rkhaghi?source=rss-6ba70500a10------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:28:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rkhaghi/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[From Satellite Images to Crop Stress Scores: Building an End-to-End ML Platform]]></title>
            <link>https://tierrainsights.buzz/building-a-production-style-crop-monitoring-platform-with-aws-and-machine-learning-31b11d6dc0ba?source=rss-6ba70500a10------2</link>
            <guid isPermaLink="false">https://medium.com/p/31b11d6dc0ba</guid>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sentinel]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rkhaghi]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 17:13:45 GMT</pubDate>
            <atom:updated>2026-08-10T17:38:33.584Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I fused satellite imagery, weather, and soil data into a serverless ML inference pipeline</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PhCoHIekU_t7IaTyuvMgGQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKLpPiFPzTJhSIdLKg3Ijw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eONI-1FGUWK2wX2a7wKN2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nw3B9zkXICHrBanPIplNMQ.png" /></figure><p>This article walks through how I built TerraSignal, an end-to-end crop stress prediction platform that fuses three geospatial data sources, runs inference on AWS Lambda, and surfaces results through a Streamlit dashboard. The full code is on <a href="https://github.com/rkhaghi/crop-stress-platform">GitHub</a>.</p><h3>Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-W6hUjmuNnZn1NyW7zfTQ.png" /></figure><p>The system has two flows:</p><ul><li>Inference path: User opens the Streamlit dashboard → enters coordinates and a date range → the dashboard calls an AWS Lambda function via HTTP → Lambda fetches satellite, weather, and soil data in real time → XGBoost predicts a stress index → results returned to the dashboard.</li><li>CI/CD path: A push to the development branch triggers GitHub Actions → builds a Docker image → pushes to ECR → Lambda runs the new image on the next invocation.</li></ul><h3>The Data Sources</h3><p>The model fuses three independent signals:</p><p>Sentinel-2 (via CDSE) provides multispectral bands every 5 days. From these I compute spectral indices — NDVI (vegetation health), NDWI (water content), NDRE (chlorophyll), EVI, and SAVI — then aggregate them spatially over the field boundary. I access Sentinel-2 through the Copernicus Data Space Ecosystem (CDSE) STAC API with S3-compatible access, which is free and doesn’t require Sentinel Hub credits.</p><p>Open-Meteo provides daily weather: precipitation, temperature, and ET₀ (evapotranspiration). The cumulative water deficit — ET₀ minus rainfall — is one of the strongest predictors of water stress.</p><p>SoilGrids provides soil properties (clay content, organic carbon, pH) that modulate how quickly fields dry out. Since the SoilGrids API can be unreliable, the pipeline continues gracefully if it’s unavailable</p><h3>Training the model</h3><p>The primary goal was to build a complete end-to-end pipeline, so I created a synthetic training dataset: 20 dummy field records with real UK coordinates and regions, but entirely fabricated dates, crop types, and stress indices (0–1 range). While not representative of real agronomic patterns, this dataset was sufficient to validate the full architecture — data ingestion, feature engineering, model loading, and inference.</p><p>The feature table unified Sentinel-2 spectral indices (NDVI, EVI, NDWI, NDRE, SAVI), weather aggregates, and soil properties. I trained an XGBoost regressor on these dummy labels, then stored the model in S3 for Lambda to load at runtime. The focus was engineering clarity and system reliability, not model accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AlAppO0hnY-Z8cT9OCNPmA.jpeg" /></figure><h3>Engineering Decisions</h3><h4>Container image + ECR + Lambda</h4><p>Geospatial dependencies (rasterio, GDAL, shapely) exceed Lambda’s 250MB zip limit. A Docker container image removes this constraint and runs natively on Lambda’s Python 3.11 base runtime. I chose ECR (Elastic Container Registry) over DockerHub because:</p><ul><li>Direct AWS integration — Lambda pulls from ECR without extra authentication</li><li>No rate limits for private images</li><li>No public image exposure for credentials</li></ul><h4>GitHub Actions → Docker → ECR → Lambda</h4><p>The CI/CD pipeline is simple and automatic:</p><pre># On push to development branch:<br>1. GitHub Actions builds the Docker image<br>2. Logs into ECR<br>3. Tags and pushes to 582367504589.dkr.ecr.eu-west-1.amazonaws.com/crop-stress:latest<br>4. Lambda automatically runs the new image on next invocation</pre><h4>API Gateway → Lambda Function URL</h4><p>I initially used API Gateway as the HTTP endpoint to Lambda. It worked, but had a fatal flaw: a hard 29-second timeout that cannot be overridden, regardless of Lambda’s configured timeout. A full inference run takes 60–120 seconds.</p><p>The fix: Lambda Function URL. This is a direct HTTPS endpoint attached to Lambda with no proxy layer and no timeout. Streamlit now calls this URL directly:</p><pre>resp = requests.post(<br>    &quot;https://???.lambda-url.eu-west-1.on.aws/&quot;,<br>    json={&quot;lat&quot;: 51.5, &quot;lon&quot;: -1.2, &quot;start_date&quot;: &quot;2024-04-01&quot;, &quot;end_date&quot;: &quot;2024-06-30&quot;},<br>    timeout=330<br>)</pre><h3>Streamlit dashboard as the UI</h3><p>Streamlit lets me build an interactive dashboard with zero frontend code. The dashboard:</p><ul><li>Reads the Lambda Function URL from .env (or lets users enter it at runtime)</li><li>Sends location + date range as JSON</li><li>Parses the response and renders charts (weather, soil, Sentinel scenes)</li><li>Adds a password gate for access control</li></ul><p>The full codebase, Dockerfile, and infrastructure templates are on <a href="https://github.com/rkhaghi/crop-stress-platform">GitHub</a>. To run it locally run:</p><pre>docker build -t crop-stress:latest .<br>docker run -p 9000:8080 crop-stress:latest</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31b11d6dc0ba" width="1" height="1" alt=""><hr><p><a href="https://tierrainsights.buzz/building-a-production-style-crop-monitoring-platform-with-aws-and-machine-learning-31b11d6dc0ba">From Satellite Images to Crop Stress Scores: Building an End-to-End ML Platform</a> was originally published in <a href="https://tierrainsights.buzz/">Tierra Insights</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an End-to-End Fraud Detection ML Pipeline on AWS]]></title>
            <link>https://aws.plainenglish.io/building-an-end-to-end-fraud-detection-ml-pipeline-on-aws-2f434108316b?source=rss-6ba70500a10------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f434108316b</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[aws-pipeline]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fraud-detection]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rkhaghi]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 14:09:00 GMT</pubDate>
            <atom:updated>2026-07-30T11:03:04.720Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/796/0*YOOJ7A19Zcwlqfdw" /></figure><h3>Introduction</h3><p><em>From raw transaction data to real-time scoring, model monitoring, and automated retraining : a complete MLOps walkthrough</em></p><p>I built a complete, production-grade fraud detection system on AWS to understand what it <em>actually</em> takes to go from a dataset to a live, monitored ML system. Not just training a model in a Jupyter notebook , but deploying it, serving it in real-time, detecting when it degrades, and automating the retraining cycle</p><p>This article walks through every step.</p><p>Raw CSV (S3)<br> ↓<br>Feature Engineering (SageMaker Processing)<br> ↓<br>XGBoost Training (SageMaker Training, spot instances)<br> ↓<br>Evaluation Gate (PR-AUC ≥ 0.85 threshold)<br> ↓<br>Model Registry (version control + approval gate)<br> ↓<br>Real-Time Endpoint (SageMaker, &lt;100ms)<br> ↓<br>Live Stream (SQS → Lambda → DynamoDB + SNS alerts)<br> ↓<br>Monitoring (Model Monitor + CloudWatch dashboard)<br> ↓<br>CI/CD (GitHub Actions → automated retraining)</p><h3>Section 1 : The Dataset</h3><h4>The Dataset</h4><p>I used a synthetic dataset of 500,000 card transactions across the UK, US, and India : representing 5,000 cardholders over 6 months.</p><p>Fraud rate: 0.42% , roughly 2,100 fraudulent transactions out of 500,000. This extreme imbalance is realistic and one of the core technical challenge</p><p><a href="https://www.kaggle.com/datasets/larangetiwari/synthetic-card-transactions-for-fraud-detection">Synthetic Card Transactions for Fraud Detection</a></p><h3>Section 2: Getting Data into S3</h3><p>Everything in SageMaker starts with S3. It’s not just storage, it’s the universal connector between every service. Your raw data lives there, your processed splits land there, your trained model gets packaged there, your monitoring logs go there, it acts as conveyor.</p><p>First of all, we need our raw data in S3.</p><p><strong>Uploading the Dataset</strong></p><p>The simplest approach , upload directly from your local machine using boto3 or the AWS CLI:</p><pre>import boto3<br><br>s3 = boto3.client(&quot;s3&quot;, region_name=&quot;us-east-1&quot;)<br>BUCKET = &quot;sagemaker-fraud-detection&quot;<br><br>s3.upload_file(<br>    &quot;Data/synthetic_transactions.csv&quot;,<br>    BUCKET,<br>    &quot;data/synthetic_transactions.csv&quot;<br>)<br>print(f&quot;Uploaded → s3://{BUCKET}/data/synthetic_transactions.csv&quot;)</pre><p>It’s worth thinking about folder structure upfront. We organised ours like this:</p><pre>s3://sagemaker-fraud-detection-rezaws/<br>│<br>├── data/<br>│   └── synthetic_transactions.csv       ← raw input data<br>│<br>├── code/<br>│   ├── sm_processing.py                <br>│   ├── sm_train.py<br>│   └── sm_evaluate.py<br>│<br>├── scripts/<br>│   └── engineering.py              <br>│<br>├── models/<br>│   └── model-clean.tar.gz               <br>│<br>└── monitoring/<br>    ├── data-capture/                   <br>    ├── baseline/                       <br>    └── reports/                         </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5aB1JSN90zQ-gv69TEewQ.jpeg" /></figure><h4><strong>How SageMaker Moves Your Data</strong></h4><p>Think of SageMaker as a delivery service for your code.</p><ol><li>S3 is the warehouse: Your data sits in the cloud, safe and permanent.</li><li>SageMaker is the delivery truck : When you start a job, it automatically downloads your data from S3 onto a temporary server</li><li>Your code is the recipient : Because the data was already delivered to that server’s local hard drive, your script just opens it like a normal file.</li></ol><pre>ProcessingInput(<br>    source=&quot;s3://bucket/data/&quot;,              # warehouse location<br>    destination=&quot;/opt/ml/processing/input/data&quot;  # delivery address<br>)<br><br># Then your script just reads normally:<br>df = pd.read_csv(&quot;/opt/ml/processing/input/data/transactions.csv&quot;)</pre><p>Here are all the standard “delivery addresses” SageMaker uses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*vw-kEjB_n5EBYrbNLjdlSw.jpeg" /></figure><p>In our project specifically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*8S15FEZemYWY-Lg1jIbcpg.jpeg" /></figure><p>Rule of thumb: Processing jobs always use /opt/ml/processing/. Training jobs use /opt/ml/. The channel names after that are yours to choose , just match them between your job config and your script.</p><h3>Section 3: Feature Engineering</h3><h4>Why Raw Data Isn’t Enough</h4><p>A raw transaction looks like this:</p><p>{<br> “transaction_id”: “TXN_001”,<br> “cardholder_id”: “CH_0042”,<br> “timestamp”: “2024–06–15 14:32:00”,<br> “merchant_name”: “Luxury Watches Ltd”,<br> “merchant_city”: “London”,<br> “merchant_country”: “GB”,<br> “merchant_category”: “jewellery”,<br> “amount”: 1250.00,<br> “currency”: “GBP”,<br> “is_online”: false,<br> “is_recurring”: false,<br> “is_international”: false,<br> “mcc”: 5944<br>}</p><p>Is this fraud? You can’t tell. £1,250 at a jewellery shop is suspicious , but maybe this cardholder buys expensive jewellery regularly. The raw amount alone means nothing without context.</p><p>Context is everything. The model needs to know:</p><ul><li>Is this unusual <em>for this specific cardholder</em>?</li><li>How many transactions has this cardholder made in the last hour?</li><li>How far did they travel between their last two transactions?</li><li>Are they suddenly spending online after never doing so before?</li></ul><p>This is what feature engineering answers.</p><p>1. time_since_last_txn_seconds : detects Card Testing</p><p>Card testers make many rapid transactions in quick succession to verify a stolen card works.</p><pre>df[&quot;time_since_last_txn_seconds&quot;] = (<br>    df.groupby(&quot;cardholder_id&quot;)[&quot;timestamp&quot;]<br>    .diff()<br>    .dt.total_seconds()<br>    .fillna(-1)   # -1 for the cardholder&#39;s very first transaction<br>)</pre><p>2. txn_count_last_1h / 6h / 24h : detects Card Testing &amp; Account Takeover</p><p>How many transactions did this cardholder make in the last hour? This requires a time-aware rolling window.</p><pre>df = df.set_index(&quot;timestamp&quot;)   # DatetimeIndex needed for time-based rolling<br><br>for window in (&quot;1h&quot;, &quot;6h&quot;, &quot;24h&quot;):<br>    df[f&quot;txn_count_last_{window}&quot;] = (<br>        df.groupby(&quot;cardholder_id&quot;)[&quot;amount&quot;]<br>        .transform(lambda x: x.rolling(window).count() - 1)<br>        # -1 excludes the current transaction from its own count<br>    )</pre><p>3. amount_vs_cardholder_avg : detects Account Takeover</p><p>A £1,250 transaction might be normal for a business traveller but extraordinary for a student. We need the ratio relative to each cardholder’s historical average.</p><pre>cardholder_avg = (<br>    df.groupby(&quot;cardholder_id&quot;)[&quot;amount&quot;]<br>    .transform(lambda x: x.expanding().mean().shift(1))<br>    # shift(1) excludes the current transaction from its own average<br>)<br>df[&quot;amount_vs_cardholder_avg&quot;] = df[&quot;amount&quot;] / cardholder_avg.fillna(df[&quot;amount&quot;])</pre><p>4. geo_velocity_kmhdetects Geographic Impossibility</p><pre>df[&quot;prev_lat&quot;] = df.groupby(&quot;cardholder_id&quot;)[&quot;lat&quot;].shift(1)<br>df[&quot;prev_lon&quot;] = df.groupby(&quot;cardholder_id&quot;)[&quot;lon&quot;].shift(1)<br>df[&quot;prev_time&quot;] = df.groupby(&quot;cardholder_id&quot;)[&quot;timestamp&quot;].shift(1)<br><br>def _velocity(row):<br>    dist_km = geodesic((row[&quot;lat&quot;], row[&quot;lon&quot;]), (row[&quot;prev_lat&quot;], row[&quot;prev_lon&quot;])).km<br>    hours = max((row[&quot;timestamp&quot;] - row[&quot;prev_time&quot;]).total_seconds() / 3600, 0.0167)<br>    return dist_km / hours<br><br>df[&quot;geo_velocity_kmh&quot;] = df.apply(_velocity, axis=1)</pre><p>5 &amp; 6. is_new_merchant / is_new_city: detects Account Takeover &amp; CNP</p><pre>df[&quot;merchant_cumcount&quot;] = df.groupby(<br>    [&quot;cardholder_id&quot;, &quot;merchant_name&quot;]<br>).cumcount()<br>df[&quot;is_new_merchant&quot;] = (df[&quot;merchant_cumcount&quot;] == 0).astype(int)</pre><p>7. online_ratio_last_7d : detects Card-Not-Present (CNP) Fraud</p><p>A sudden shift from in-store to online transactions (especially international online) is a strong CNP signal. Someone stole the card number but not the physical card.</p><pre>df[&quot;is_online_int&quot;] = df[&quot;is_online&quot;].astype(int)<br>df = df.set_index(&quot;timestamp&quot;)<br>df[&quot;online_ratio_last_7d&quot;] = (<br>    df.groupby(&quot;cardholder_id&quot;)[&quot;is_online_int&quot;]<br>    .transform(lambda x: x.rolling(&quot;7d&quot;).mean().shift(1))<br>    .fillna(0.0)<br>)</pre><p>8. spending_acceleration_7d : detects Bust-Out Fraud</p><p>Bust-out fraud involves a fraudster slowly building credit trust then maxing out the account. The signature is a gradual acceleration in spending.</p><pre>rolling_7d  = df.groupby(&quot;cardholder_id&quot;)[&quot;amount&quot;].transform(<br>    lambda x: x.rolling(&quot;7d&quot;).mean().shift(1)<br>)<br>rolling_14d = df.groupby(&quot;cardholder_id&quot;)[&quot;amount&quot;].transform(<br>    lambda x: x.rolling(&quot;14d&quot;).mean().shift(1)<br>)<br>df[&quot;spending_acceleration_7d&quot;] = rolling_7d / rolling_14d.replace(0, np.nan).fillna(1.0)</pre><p>The Complete Feature Engineering Code</p><pre>import pandas as pd<br>import numpy as np<br>from geopy.distance import geodesic<br><br># ---------------------------------------------------------------------------<br># City coordinates lookup<br># ---------------------------------------------------------------------------<br>CITY_COORDS = {<br>    &quot;London&quot;:        (51.5074,   -0.1278),<br>    &quot;Manchester&quot;:    (53.4808,   -2.2426),<br>  <br>    # ... 24 cities total across UK, US, India<br>}<br><br>def _add_recency_features(df):<br>    &quot;&quot;&quot;Time since the cardholder&#39;s previous transaction.&quot;&quot;&quot;<br>    df[&quot;time_since_last_txn_seconds&quot;] = (<br>        df.groupby(&quot;cardholder_id&quot;)[&quot;timestamp&quot;]<br>        .diff()<br>        .dt.total_seconds()<br>        .fillna(-1)  <br>    )<br>    return df<br><br>def _add_velocity_features(df):<br>    &quot;&quot;&quot;Transaction count in rolling time windows.&quot;&quot;&quot;<br>    df = df.set_index(&quot;timestamp&quot;)  <br>    for window in (&quot;1h&quot;, &quot;6h&quot;, &quot;24h&quot;):<br>        df[f&quot;txn_count_last_{window}&quot;] = (<br>            df.groupby(&quot;cardholder_id&quot;)[&quot;amount&quot;]<br>            .transform(lambda x: x.rolling(window).count() - 1)<br>        )<br>    return df.reset_index()<br><br>def _add_amount_features(df):<br>    &quot;&quot;&quot;Ratio of transaction to cardholder&#39;s historical average.&quot;&quot;&quot;<br>    hist_avg = (<br>        df.groupby(&quot;cardholder_id&quot;)[&quot;amount&quot;]<br>        .transform(lambda x: x.expanding().mean().shift(1))<br>    )<br>    df[&quot;amount_vs_cardholder_avg&quot;] = df[&quot;amount&quot;] / hist_avg.fillna(df[&quot;amount&quot;])<br>    return df<br><br>def _add_geo_features(df):<br>    &quot;&quot;&quot;Travel speed between consecutive transactions (km/h).&quot;&quot;&quot;<br>    df[&quot;lat&quot;] = df[&quot;merchant_city&quot;].map(lambda c: CITY_COORDS.get(c, (0.0, 0.0))[0])<br>    df[&quot;lon&quot;] = df[&quot;merchant_city&quot;].map(lambda c: CITY_COORDS.get(c, (0.0, 0.0))[1])<br>    df[&quot;prev_lat&quot;]  = df.groupby(&quot;cardholder_id&quot;)[&quot;lat&quot;].shift(1)<br>    df[&quot;prev_lon&quot;]  = df.groupby(&quot;cardholder_id&quot;)[&quot;lon&quot;].shift(1)<br>    df[&quot;prev_time&quot;] = df.groupby(&quot;cardholder_id&quot;)[&quot;timestamp&quot;].shift(1)<br><br>    def _velocity(row):<br>        if pd.isna(row[&quot;prev_lat&quot;]):<br>            return 0.0<br>        dist_km = geodesic(<br>            (row[&quot;lat&quot;], row[&quot;lon&quot;]),<br>            (row[&quot;prev_lat&quot;], row[&quot;prev_lon&quot;])<br>        ).km<br>        hours = max((row[&quot;timestamp&quot;] - row[&quot;prev_time&quot;]).total_seconds() / 3600, 0.0167)<br>        return dist_km / hours<br><br>    df[&quot;geo_velocity_kmh&quot;] = df.apply(_velocity, axis=1)<br>    df.drop(columns=[&quot;lat&quot;, &quot;lon&quot;, &quot;prev_lat&quot;, &quot;prev_lon&quot;, &quot;prev_time&quot;], inplace=True)<br>    return df<br><br>def _add_merchant_features(df):<br>    &quot;&quot;&quot;First-visit flags for merchant and city.&quot;&quot;&quot;<br>    df[&quot;is_new_merchant&quot;] = (<br>        df.groupby([&quot;cardholder_id&quot;, &quot;merchant_name&quot;]).cumcount() == 0<br>    ).astype(int)<br>    df[&quot;is_new_city&quot;] = (<br>        df.groupby([&quot;cardholder_id&quot;, &quot;merchant_city&quot;]).cumcount() == 0<br>    ).astype(int)<br>    return df<br><br>def _add_online_ratio_feature(df):<br>    &quot;&quot;&quot;Ratio of online transactions in the last 7 days.&quot;&quot;&quot;<br>    df[&quot;is_online_int&quot;] = df[&quot;is_online&quot;].astype(int)<br>    df = df.set_index(&quot;timestamp&quot;)<br>    df[&quot;online_ratio_last_7d&quot;] = (<br>        df.groupby(&quot;cardholder_id&quot;)[&quot;is_online_int&quot;]<br>        .transform(lambda x: x.rolling(&quot;7d&quot;).mean().shift(1))<br>        .fillna(0.0)<br>    )<br>    return df.reset_index().drop(columns=[&quot;is_online_int&quot;])<br><br>def _add_spending_acceleration(df):<br>    &quot;&quot;&quot;7-day spending acceleration (bust-out signal).&quot;&quot;&quot;<br>    df = df.set_index(&quot;timestamp&quot;)<br>    rolling_7d  = df.groupby(&quot;cardholder_id&quot;)[&quot;amount&quot;].transform(<br>        lambda x: x.rolling(&quot;7d&quot;).mean().shift(1)<br>    )<br>    rolling_14d = df.groupby(&quot;cardholder_id&quot;)[&quot;amount&quot;].transform(<br>        lambda x: x.rolling(&quot;14d&quot;).mean().shift(1)<br>    )<br>    df[&quot;spending_acceleration_7d&quot;] = (<br>        rolling_7d / rolling_14d.replace(0, np.nan).fillna(1.0)<br>    ).fillna(1.0)<br>    return df.reset_index()<br><br><br>def compute_features(df: pd.DataFrame) -&gt; pd.DataFrame:<br>    df = df.copy()<br>    df[&quot;timestamp&quot;] = pd.to_datetime(df[&quot;timestamp&quot;])<br>    df = df.sort_values([&quot;cardholder_id&quot;, &quot;timestamp&quot;]).reset_index(drop=True)<br><br>    df = _add_recency_features(df)<br>    df = _add_velocity_features(df)<br>    df = _add_amount_features(df)<br>    df = _add_geo_features(df)<br>    df = _add_merchant_features(df)<br>    df = _add_online_ratio_feature(df)<br>    df = _add_spending_acceleration(df)<br><br>    return df</pre><p>You’ll notice every helper function starts with an underscore: _add_recency_features, _add_geo_features, etc. This is a Python convention that means &quot;this is for internal use only. External code only calls compute_features().</p><h3>Section 4 : The SageMaker Pipeline</h3><h3>Why a Pipeline?</h3><p>A SageMaker Pipeline is a directed acyclic graph (DAG) of steps that runs on managed infrastructure, tracks every artifact, and enforces quality gates. Think of it as a repeatable factory for ML models.</p><p>S3 (raw data)<br> ↓<br> FeatureEngineering Processing Job (SKLearn container)<br> ↓<br>TrainXGBoost Training Job (XGBoost container, spot instances)<br> ↓<br>EvaluateModel Processing Job (XGBoost container)<br> ↓<br> CheckPRAUC Condition Step (PR-AUC ≥ 0.85?)<br> ↓<br>RegisterModel (if passed) or pipeline ends (if failed)</p><h3>The Pipeline Notebook</h3><p>The pipeline is defined and launched from a Jupyter notebook (pipeline.ipynb) running inside <strong>SageMaker Studio</strong> , AWS&#39;s built-in notebook environment. Studio comes pre-configured with the SageMaker SDK, AWS credentials, and IAM role access, so you can connect to AWS services without any setup.</p><p>The notebook is purely an <strong>orchestrator</strong> — it defines what should run, in what order, on what infrastructure, then hands everything off to SageMaker to execute on separate managed instances. Once you click run, you can close the notebook. The pipeline runs entirely on AWS regardless of whether Studio is open.</p><p>In production, CI/CD can trigger the same execution with a single API call:</p><pre>sm.start_pipeline_execution(PipelineName=&quot;fraud-detection-pipeline&quot;)</pre><h3>Step 1: Feature Engineering</h3><p>The processing script runs inside a managed SKLearn container on a remote ml.t3.medium instance. SageMaker mounts S3 data to a local path before the script runs and uploads outputs after it finishes.</p><p>below is the sm_processing.py file, as you can see engineering has imported from compute_features. It has one job: take the raw CSV and produce three clean, feature-engineered splits.</p><pre>pipeline_session = PipelineSession()   # captures args, doesn&#39;t execute yet<br><br>step_process = ProcessingStep(<br>    name=&quot;FeatureEngineering&quot;,<br>    step_args=sklearn_processor.run(<br>        code=&quot;sm_processing.py&quot;,<br>        inputs=[<br>            ProcessingInput(source=f&quot;s3://{BUCKET}/data/&quot;,<br>                            destination=&quot;/opt/ml/processing/input/data&quot;),<br>            ProcessingInput(source=f&quot;s3://{BUCKET}/scripts/engineering.py&quot;,<br>                            destination=&quot;/opt/ml/processing/input/scripts&quot;),<br>        ],<br>        outputs=[<br>            ProcessingOutput(output_name=&quot;train&quot;, source=&quot;/opt/ml/processing/output/train&quot;),<br>            ProcessingOutput(output_name=&quot;val&quot;,   source=&quot;/opt/ml/processing/output/val&quot;),<br>            ProcessingOutput(output_name=&quot;test&quot;,  source=&quot;/opt/ml/processing/output/test&quot;),<br>        ],<br>    ),<br>    cache_config=CacheConfig(enable_caching=True, expire_after=&quot;7d&quot;),<br>)</pre><p>Key: PipelineSession() — Using this instead of Session() tells SageMaker to capture the job definition rather than execute it immediately. The pipeline is a blueprint, not a live run.</p><p>Key: caching — With expire_after=”7d”, if you re-run the pipeline within 7 days with the same input data, SageMaker skips this step entirely. Feature engineering on 500K rows takes ~5 minutes — caching saves both time and money on every subsequent run.</p><p>Inside sm_processing.py, a time-based split (not random) is used:</p><pre>train = df[df[&quot;timestamp&quot;] &lt;= &quot;2024-04-30&quot;]<br>val   = df[(df[&quot;timestamp&quot;] &gt; &quot;2024-04-30&quot;) &amp; (df[&quot;timestamp&quot;] &lt;= &quot;2024-05-31&quot;)]<br>test  = df[df[&quot;timestamp&quot;] &gt; &quot;2024-05-31&quot;]</pre><h3>Step 2 : Training</h3><p>XGBoost training uses spot instances, unused AWS compute capacity at up to 70% discount:</p><pre>xgb_estimator = XGBoost(<br>    entry_point=&quot;sm_train.py&quot;,<br>    source_dir=SRC_DIR,<br>    framework_version=&quot;1.7-1&quot;,<br>    instance_type=&quot;ml.m5.large&quot;,<br>    use_spot_instances=True,<br>    max_run=3600,<br>    max_wait=7200,<br>    hyperparameters={<br>        &quot;n-estimators&quot;: 500,<br>        &quot;max-depth&quot;: 6,<br>        &quot;learning-rate&quot;: 0.05,<br>        &quot;subsample&quot;: 0.8,<br>        &quot;colsample-bytree&quot;: 0.8,<br>    },<br>    sagemaker_session=pipeline_session,<br>)<br><br>step_train = TrainingStep(<br>    name=&quot;TrainXGBoost&quot;,<br>    estimator=xgb_estimator,<br>    inputs={<br>        &quot;train&quot;: TrainingInput(<br>            step_process.properties.ProcessingOutputConfig.Outputs[&quot;train&quot;].S3Output.S3Uri<br>        ),<br>    },<br>)<br></pre><p>step_process.properties… is a lazy reference , SageMaker resolves it at execution time. The output path is auto-generated with a random ID on every run , you can’t hardcode it. This is what wires steps together into a proper DAG.</p><p><em>Handling Class Imbalance</em></p><p>With 0.42% fraud rate, the model would otherwise learn to always predict “not fraud” and be right 99.58% of the time. We fix this with:</p><pre>neg = (y_train == 0).sum()   # ~300,000<br>pos = (y_train == 1).sum()   # ~1,260<br>spw = round(neg / pos)       # ≈ 238<br><br>model = XGBClassifier(scale_pos_weight=spw, eval_metric=&quot;aucpr&quot;, ...)</pre><p>Another popular approach is SMOTE (Synthetic Minority Oversampling Technique). Instead of telling the model to weight fraud cases higher, SMOTE actually creates synthetic fraud examples to balance the dataset before training.</p><pre>from imblearn.over_sampling import SMOTE<br>sm = SMOTE(random_state=42)<br>X_train_resampled, y_train_resampled = sm.fit_resample(X_train, y_train)</pre><p>For imbalanced datasets, ROC-AUC is optimistic , it gives too much credit for correctly identifying the majority class. PR-AUC focuses specifically on the minority class performance. When fraud is 0.42% of data, PR-AUC tells you the truth.</p><p>The script saves three files to /opt/ml/model/, which SageMaker packages into model.tar.gz and uploads to S3:</p><pre>model.save_model(&quot;model.json&quot;)           # the XGBoost model<br>json.dump(metrics, &quot;metrics.json&quot;)       # val PR-AUC + threshold<br>json.dump(feature_cols, &quot;feature_columns.json&quot;)  # column order for inference</pre><h3>Step 3: Evaluation</h3><p>The evaluation script loads the model artifact, scores the held-out test set, and writes a structured report:</p><pre># Extract model.tar.gz (SageMaker packages training output automatically)<br>with tarfile.open(os.path.join(MODEL_DIR, &quot;model.tar.gz&quot;)) as tar:<br>    tar.extractall(MODEL_DIR)<br><br>model = XGBClassifier()<br>model.load_model(os.path.join(MODEL_DIR, &quot;model.json&quot;))<br><br># Load feature columns and reindex to match training exactly<br>feature_columns = json.load(open(os.path.join(MODEL_DIR, &quot;feature_columns.json&quot;)))<br>X_test = X_test.reindex(columns=feature_columns, fill_value=0)<br><br>y_prob = model.predict_proba(X_test)[:, 1]<br>pr_auc = average_precision_score(y_test, y_prob)<br><br># Write evaluation report in the exact format ConditionStep expects<br>evaluation = {<br>    &quot;binary_classification_metrics&quot;: {<br>        &quot;average_precision&quot;: {<br>            &quot;value&quot;: round(pr_auc, 4),<br>            &quot;standard_deviation&quot;: &quot;NaN&quot;,<br>        }<br>    }<br>}<br>json.dump(evaluation, open(os.path.join(OUTPUT_DIR, &quot;evaluation.json&quot;), &quot;w&quot;))</pre><p>The double-nested structure under binary_classification_metrics is not optional , it&#39;s the exact format SageMaker&#39;s ConditionStep requires to read the PR-AUC value via JsonGet.</p><h3>Step 4: The Quality Gate</h3><p>This is the most important step for production safety , and the one most projects skip.</p><pre>cond = ConditionGreaterThanOrEqualTo(<br>    left=JsonGet(<br>        step_name=step_evaluate.name,<br>        property_file=evaluation_report,<br>        json_path=&quot;binary_classification_metrics.average_precision.value&quot;,<br>    ),<br>    right=0.85,<br>)<br><br>step_condition = ConditionStep(<br>    name=&quot;CheckPRAUC&quot;,<br>    conditions=[cond],<br>    if_steps=[step_register],   # register if PR-AUC ≥ 0.85<br>    else_steps=[],              # end silently if below threshold<br>)</pre><p>If the model fails , maybe training data quality degraded, or a bug crept into feature engineering , the pipeline ends silently. No bad model ever reaches the registry.</p><h3>Section 5: Real-Time Serving</h3><h3>The Architecture</h3><p>Once a model is approved in the registry, we deploy it to a SageMaker endpoint and wire up a real-time processing stream:</p><pre>FEATURE_COLUMNS = [<br>    &quot;mcc&quot;, &quot;amount&quot;, &quot;is_online&quot;, &quot;is_recurring&quot;, &quot;is_international&quot;,<br>    &quot;time_since_last_txn_seconds&quot;,<br>    &quot;txn_count_last_1h&quot;, &quot;txn_count_last_6h&quot;, &quot;txn_count_last_24h&quot;,<br>    &quot;amount_vs_cardholder_avg&quot;, &quot;geo_velocity_kmh&quot;,<br>    &quot;is_new_merchant&quot;, &quot;is_new_city&quot;,<br>    &quot;online_ratio_last_7d&quot;, &quot;spending_acceleration_7d&quot;,<br>    &quot;merchant_category_coffee&quot;, &quot;merchant_category_grocery&quot;,<br>    # ... 15 total categories<br>    &quot;merchant_country_GB&quot;, &quot;merchant_country_IN&quot;, &quot;merchant_country_US&quot;,<br>    &quot;currency_GBP&quot;, &quot;currency_INR&quot;, &quot;currency_USD&quot;,<br>]<br><br>def build_feature_vector(txn: dict) -&gt; str:<br>    row = {}<br>    row[&quot;amount&quot;]    = float(txn.get(&quot;amount&quot;, 0))<br>    row[&quot;is_online&quot;] = int(str(txn.get(&quot;is_online&quot;, &quot;False&quot;)).lower() == &quot;true&quot;)<br><br>    # Behavioural features default to 0 — no Feature Store in this version<br>    row[&quot;txn_count_last_1h&quot;] = float(txn.get(&quot;txn_count_last_1h&quot;, 0))<br>    row[&quot;geo_velocity_kmh&quot;]  = float(txn.get(&quot;geo_velocity_kmh&quot;, 0))<br><br>    # One-hot encode categories manually<br>    category = str(txn.get(&quot;merchant_category&quot;, &quot;&quot;)).lower()<br>    for col in FEATURE_COLUMNS:<br>        if col.startswith(&quot;merchant_category_&quot;):<br>            row[col] = 1 if col == f&quot;merchant_category_{category}&quot; else 0<br><br>    values = [str(row.get(col, 0)) for col in FEATURE_COLUMNS]<br>    return &quot;,&quot;.join(values)</pre><p>FEATURE_COLUMNS is hardcoded in the exact order used during training. XGBoost uses positional indexing , wrong order means wrong predictions, with no error raised. This list is the contract between training and inference.</p><p><strong>Unknown categories default to all zeros</strong> , no crash, just a slightly less informed prediction. This is the standard industry approach</p><h3>The Lambda Handler</h3><pre>def handler(event, context):<br>    for record in event.get(&quot;Records&quot;, []):<br>        txn = json.loads(record[&quot;body&quot;])<br>        txn_id = txn.get(&quot;transaction_id&quot;)<br><br>        # Score<br>        csv_row = build_feature_vector(txn)<br>        response = runtime.invoke_endpoint(<br>            EndpointName=ENDPOINT_NAME,<br>            ContentType=&quot;text/csv&quot;,<br>            Body=csv_row,<br>        )<br>        score = float(response[&quot;Body&quot;].read().decode())<br><br>        # Store decision<br>        table.put_item(Item={<br>            &quot;transaction_id&quot;: txn_id,<br>            &quot;fraud_score&quot;: str(round(score, 4)),<br>            &quot;is_fraud_flag&quot;: str(score &gt;= FRAUD_THRESHOLD),<br>            &quot;processed_at&quot;: datetime.now(timezone.utc).isoformat(),<br>        })<br><br>        # Alert if fraud<br>        if score &gt;= FRAUD_THRESHOLD:<br>            sns.publish(<br>                TopicArn=SNS_TOPIC_ARN,<br>                Subject=&quot;Fraud Alert&quot;,<br>                Message=f&quot;Transaction {txn_id} flagged with score {score:.4f}&quot;,<br>            )<br><br>    return {&quot;statusCode&quot;: 200}</pre><p><strong>AWS clients are initialised outside the handler</strong> , they’re reused across invocations when Lambda keeps the container warm (cold start optimisation).</p><p><strong>Error re-raising: </strong>if an exception occurs, it’s re-raised so SQS retries the message automatically. No transaction is silently dropped.</p><h3>Section 6: Monitoring</h3><h3>Why Monitoring Matters</h3><p>A model that was excellent when deployed can degrade silently. Fraud patterns evolve, new merchant categories appear, spending behaviours shift. Without monitoring, you’d only discover degradation when fraud rates spike.</p><p>We set up three layers of monitoring:</p><h3>1. Data Capture</h3><p>Every inference request and response is logged to S3 automatically:</p><pre>DataCaptureConfig={<br>    &quot;EnableCapture&quot;: True,<br>    &quot;InitialSamplingPercentage&quot;: 100,<br>    &quot;DestinationS3Uri&quot;: f&quot;s3://{BUCKET}/monitoring/data-capture&quot;,<br>    &quot;CaptureOptions&quot;: [<br>        {&quot;CaptureMode&quot;: &quot;Input&quot;},<br>        {&quot;CaptureMode&quot;: &quot;Output&quot;},<br>    ],<br>}</pre><h3>2. Baseline + Model Monitor</h3><p>The baseline is a “fingerprint” of what normal training data looks like</p><pre>monitor.suggest_baseline(<br>    baseline_dataset=training_data_s3,<br>    dataset_format=DatasetFormat.csv(header=True),<br>    output_s3_uri=baseline_results_s3,<br>)<br># Produces: statistics.json + constraints.json</pre><p>A daily schedule then compares live traffic against this baseline:</p><pre>monitor.create_monitoring_schedule(<br>    monitor_schedule_name=&quot;fraud-detection-monitor-schedule&quot;,<br>    endpoint_input=ENDPOINT_NAME,<br>    schedule_cron_expression=CronExpressionGenerator.daily(),<br>)</pre><h3>3. CloudWatch Dashboard + Alarms</h3><p>A dashboard with 9 widgets covering endpoint latency, invocations, errors, Lambda performance, SQS queue depth, DynamoDB writes, and SNS alerts.</p><p>Four automated alarms, all routing to the SNS fraud-alerts topic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*Yek_4ChtQXTcEVwaDbKp0g.png" /></figure><p>A custom metric (FraudDetection/Custom &gt; FraudDetected) is published on every Lambda invocation , enabling fraud rate tracking over time and alarming if it spikes unexpectedly.</p><h3>Section 7: CI/CD</h3><h3>GitHub Actions Workflows</h3><p><strong>CI (</strong><strong>ci.yml)</strong> : runs on every push to the development branch:</p><pre>steps:<br>  - name: Install dependencies<br>    run: pip install -r requirements.txt -r requirements-dev.txt<br><br>  - name: Lint with ruff<br>    run: ruff check src/<br><br>  - name: Run tests<br>    run: pytest tests/ -v</pre><pre>steps:<br>  - name: Upload scripts to S3<br>    run: |<br>      aws s3 cp src/sm_processing.py s3://$BUCKET/code/<br>      aws s3 cp src/sm_train.py s3://$BUCKET/code/<br>      aws s3 cp src/sm_evaluate.py s3://$BUCKET/code/<br>      aws s3 cp src/engineering.py s3://$BUCKET/scripts/<br><br>  - name: Start pipeline execution<br>    run: python -c &quot;<br>      import boto3<br>      sm = boto3.client(&#39;sagemaker&#39;, region_name=&#39;us-east-1&#39;)<br>      sm.start_pipeline_execution(PipelineName=&#39;fraud-detection-pipeline&#39;)<br>    &quot;</pre><p>The full project is available on GitHub: <a href="https://github.com/rkhaghi/fraud-detection-pipeline">fraud-detection-pipeline</a></p><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f434108316b" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/building-an-end-to-end-fraud-detection-ml-pipeline-on-aws-2f434108316b">Building an End-to-End Fraud Detection ML Pipeline on AWS</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>