<?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 Prabhutells on Medium]]></title>
        <description><![CDATA[Stories by Prabhutells on Medium]]></description>
        <link>https://medium.com/@prabhutells143?source=rss-295db4e9811b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DEcg0TqxLcOjJNfR</url>
            <title>Stories by Prabhutells on Medium</title>
            <link>https://medium.com/@prabhutells143?source=rss-295db4e9811b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:06:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prabhutells143/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[Beyond the Grocery Aisle: Building a Supermarket Sales Predictor with ML and Hugging Face]]></title>
            <link>https://medium.com/@prabhutells143/beyond-the-grocery-aisle-building-a-supermarket-sales-predictor-with-ml-and-hugging-face-a0f6620ee440?source=rss-295db4e9811b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0f6620ee440</guid>
            <dc:creator><![CDATA[Prabhutells]]></dc:creator>
            <pubDate>Sat, 11 Apr 2026 10:42:14 GMT</pubDate>
            <atom:updated>2026-04-12T17:23:06.952Z</atom:updated>
            <content:encoded><![CDATA[<p>How a Saturday grocery run turned into an end-to-end ML forecasting solution</p><h3>The Spark Behind the Project</h3><p>Every weekend I push a cart through the aisles of my Grace local supermarket. Vegetables, dairy, snacks the usual routine. But since I started studying AI and Machine Learning, I can’t look at anything the same way. Shelves of products stopped being just shelves. They became datasets. Patterns. Signals waiting to be decoded.</p><p>One Saturday evening I noticed the store manager moving between aisles with a clipboard, muttering to himself, crossing things off. Curious, I asked what he was doing. His answer was disarmingly simple: <em>“Trying to figure out what we’ll need next month.”</em> He had a spreadsheet. Years of experience. And a healthy dose of intuition. But no predictive system. No model. No data-driven forecast.</p><p>That conversation stuck with me. And I thought this is a regression problem. I know how to solve this.</p><p>The result is <strong>SuperKart Sales Predictor</strong>: an end-to-end machine learning pipeline that forecasts product-level sales revenue for supermarkets, deployed live on Hugging Face Spaces.</p><p>This is how I built it.</p><h3>Problem Statement</h3><p><strong>SuperKart</strong> is a fictional retail chain operating supermarkets and food marts across tier 1, 2, and 3 cities in India. The business challenge was straightforward but high-stakes:</p><blockquote>Accurately forecast the quarterly sales revenue for each product in each store to support inventory management, supply chain planning, and regional strategy.</blockquote><p>A bad forecast in retail has real costs. Over-order and you have spoilage and tied-up capital. Under-order and you have empty shelves and lost revenue. Getting it right even approximately changes how a business operates.</p><p>This wasn’t just a modelling exercise. The goal was to also <strong>deploy the model</strong> so it could actually be used by non-technical stakeholders. A model that lives in a Jupyter notebook helps no one.</p><h3>The Solution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*xdh8r5BLQ-S6d1_ohw2ERg.png" /></figure><h3>Technical Architecture Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*VD6gxkbMHmB_8HiHMBbcBw.png" /></figure><h3>Layered Architecture Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*bXHnLPapn009OyG0zzg4Fg.png" /></figure><h3>The Dataset</h3><p>The dataset contains <strong>8,763 records</strong> across <strong>12 columns</strong>, capturing both product-level and store-level attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*TL-i7HB5I70ruTC-8VxjnA.png" /></figure><p>There were <strong>no missing values</strong> and <strong>no duplicate rows</strong> — an unusually clean dataset that let us focus on the modelling rather than data cleaning.</p><h3>Exploratory Data Analysis</h3><p>Before building any model, I spent time genuinely understanding the data. EDA isn’t just a step to tick off it’s where you find the story.</p><h3>Numerical Feature Insights</h3><p>Running descriptive statistics and plotting histograms + boxplots for the four numerical features revealed:</p><ul><li><strong>Product_Weight</strong> follows a fairly uniform distribution (range: 4–22 units), concentrated between 10–15. No strong outliers.</li><li><strong>Product_Allocated_Area</strong> is right-skewed — most products get a small shelf allocation, with a few products commanding disproportionately large space.</li><li><strong>Product_MRP</strong> is relatively uniformly distributed between ₹31 and ₹266, with a mean around ₹147.</li><li><strong>Product_Store_Sales_Total</strong> (our target) is also right-skewed — a minority of products drive outsized revenue. This is typical in retail: Pareto dynamics at play.</li></ul><h3>Categorical Feature Insights</h3><ul><li><strong>Product_Sugar_Content</strong>: ‘Low Sugar’ is by far the most common category (~56% of products).</li><li><strong>Product_Type</strong>: ‘Fruits and Vegetables’ leads in frequency, followed by Snack Foods and Household items.</li><li><strong>Store_Size</strong>: Medium-sized stores dominate the dataset.</li><li><strong>Store_Location_City_Type</strong>: Tier 2 cities have the most store locations.</li><li><strong>Store_Type</strong>: Supermarket Type2 is the most frequent, concentrated in OUT004.</li></ul><h3>Bivariate Analysis: What Drives Sales?</h3><p>This is where it got interesting.</p><p>The <strong>correlation heat map</strong> revealed that Product_MRP has the strongest positive correlation with Product_Store_Sales_Total. Higher-priced products generate more revenue which makes intuitive sense, but it&#39;s satisfying to see the data confirm it.</p><p>Box plots of categorical features vs. sales showed:</p><ul><li><strong>Store_Type</strong>: Supermarket Type1 and Type2 outperform Food Marts significantly.</li><li><strong>Store_Size</strong>: Medium and High-sized stores generate more sales than Small stores.</li><li><strong>Store_Location_City_Type</strong>: Tier 1 and Tier 2 cities drive stronger sales than Tier 3.</li><li><strong>Product_Sugar_Content</strong>: ‘Regular’ products show slightly higher median sales.</li></ul><h3>Data Preprocessing : -</h3><h3>Feature Engineering</h3><p>One of the most impactful preprocessing decisions was converting Store_Establishment_Year into Store_Age:</p><pre>dataset[&#39;Store_Age&#39;] = dataset[&#39;Store_Establishment_Year&#39;].apply(lambda year: 2024 - year)<br>dataset.drop(&#39;Store_Establishment_Year&#39;, axis=1, inplace=True)</pre><p>Why? A model can reason about “this store is 37 years old” far more naturally than “this store was established in 1987.” Age as a concept captures maturity, customer loyalty, and operational efficiency in a way the raw year does not.</p><p>I also dropped Product_Id and Store_Id — they are identifiers, not features. Including them would cause the model to memorise individual records rather than learn generalizable patterns.</p><h3>Train / Test Split</h3><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br># X_train: (7010, 9)  |  X_test: (1753, 9)</pre><p>An 80/20 split with random_state=42 for reproducibility. The test set is kept completely untouched until final evaluation.</p><h3>Preprocessing Pipeline</h3><p>To prevent data leakage (a common pitfall), I built a ColumnTransformer inside an sklearn Pipeline</p><pre>preprocessor = make_column_transformer(<br>    (OneHotEncoder(handle_unknown=&#39;ignore&#39;), categorical_features),<br>    (StandardScaler(), numerical_features),<br>    remainder=&#39;passthrough&#39;<br>)</pre><p>This ensures that:</p><ul><li>Categorical features are one-hot encoded (e.g., Store_Type → 4 binary columns)</li><li>Numerical features are standardized using statistics computed <strong>only</strong> on the training set</li><li>The same transformation is applied at inference time without re-fitting</li></ul><h3>Outlier Treatment: Why We Kept Them</h3><p>The IQR analysis identified about 81 outliers in Product_Allocated_Area (1.16%) and 95 in Product_Store_Sales_Total (1.36%). We deliberately chose not to remove or cap them, for three reasons:</p><ol><li><strong>Business validity</strong>: High sales events are real — promotions, festive seasons, viral products. They’re not noise; they’re signal.</li><li><strong>Model robustness</strong>: Tree-based models partition data by thresholds, making them naturally resistant to extreme values.</li><li><strong>Information value</strong>: Predicting high-sales scenarios is precisely what a store manager needs — those are the moments inventory planning matters most.</li></ol><h3>Model Building and Evaluation</h3><p>I trained three models, each building on the previous.</p><h3>Evaluation Metrics</h3><p>For regression problems, I used five metrics:</p><ul><li><strong>RMSE</strong> (Root Mean Squared Error): penalises large errors</li><li><strong>MAE</strong> (Mean Absolute Error): average magnitude of errors</li><li><strong>R²</strong> and <strong>Adjusted R²</strong>: proportion of variance explained</li><li><strong>MAPE</strong> (Mean Absolute Percentage Error): percentage-based intuition for business stakeholders</li></ul><h3>Model 1: Decision Tree Regressor</h3><pre>dt_pipeline = Pipeline([<br>    (&#39;preprocessor&#39;, preprocessor),<br>    (&#39;regressor&#39;, DecisionTreeRegressor(random_state=42))<br>])</pre><p>A textbook case of <strong>overfitting</strong>. The Decision Tree memorised every training example (R² = 1.0 on train), but struggled to generalise. It’s a useful baseline — it shows us what we’re trying to beat.</p><h3>Model 2: Random Forest Regressor (Untuned)</h3><p>Random Forests reduce variance by averaging predictions from many decorrelated trees — each trained on a random subset of data and features.</p><p>SetRMSEMAER²MAPETrain107.040.20.9901.5%Test283.6108.60.9303.9%</p><p>A dramatic improvement. Test R² jumps from 0.86 to 0.93. The training-test gap narrows — a sign of better generalisation. But there’s still some overfitting, and the default hyperparameters haven’t been optimised.</p><h3>Model 3: Tuned Random Forest (GridSearchCV)</h3><pre>param_grid = {<br>    &#39;regressor__n_estimators&#39;: [100, 200, 300],<br>    &#39;regressor__max_depth&#39;: [None, 10, 20],<br>    &#39;regressor__min_samples_leaf&#39;: [1, 2, 4]<br>}</pre><pre>grid_search_rf = GridSearchCV(<br>    rf_pipeline,<br>    param_grid,<br>    cv=5,<br>    scoring=&#39;neg_mean_squared_error&#39;,<br>    n_jobs=-1,<br>    verbose=2<br>)</pre><p>Best parameters found: n_estimators=300, max_depth=None, min_samples_leaf=2</p><p>SetRMSEMAER²MAPETrain171.560.00.9742.2%Test277.6104.3<strong>0.9323.7%</strong></p><p>The tuned model achieves the best test performance across all metrics. Crucially, the training-test gap is tighter than the untuned version — the regularisation from min_samples_leaf=2 prevents overfitting while maintaining predictive power.</p><p><strong>What does MAPE 3.7% mean in practice?</strong> If a product is expected to generate ₹10,000 in sales, the model’s prediction will be off by about ₹370 on average. For quarterly inventory planning, that’s a level of accuracy that can genuinely drive decisions.</p><h3>Model Comparison Summary</h3><p>ModelTest R²Test MAPEVerdictDecision Tree0.8594.9%Overfit — unusableRandom Forest (untuned)0.9303.9%Good baseline<strong>Random Forest (tuned)0.9323.7%</strong>✅ Best model</p><p>The tuned Random Forest was serialized using joblib and saved for deployment:</p><pre>joblib.dump(best_rf_model, &#39;backend_files/superkart_predictor_model.joblib&#39;)</pre><h3>Deployment Architecture</h3><p>A model in a notebook is a prototype. A model behind an API is a product. This is where most tutorials stop, and where I wanted to go further.</p><h3>Architecture Overview</h3><pre>User (Streamlit UI)<br>       ↓  HTTP request<br>Flask REST API (Docker container)<br>       ↓  loads model<br>superkart_predictor_model.joblib<br>       ↓  returns prediction<br>Streamlit UI displays result</pre><p>Both the backend and frontend are hosted as separate <strong>Hugging Face Spaces</strong> — one Docker space for the API, one Streamlit space for the UI.</p><h3>Backend: Flask REST API</h3><p>The Flask app exposes two endpoints:</p><p><strong>POST /v1/predict/single</strong> — takes a single JSON object and returns a predicted sales figure.</p><pre>@superkart_price_api.post(&#39;/v1/predict/single&#39;)<br>def predict_single_item_sales():<br>    superkart_data = request.get_json()<br>    input_data = pd.DataFrame([superkart_data], columns=feature_names)<br>    prediction = model.predict(input_data)<br>    return jsonify({&#39;predicted_sales&#39;: prediction.tolist()[0]})</pre><p><strong>POST /v1/predict/batch</strong> — accepts a CSV file upload and returns predictions for every row.</p><pre>@superkart_price_api.post(&#39;/v1/predict/batch&#39;)<br>def predict_batch_item_sales():<br>    file = request.files[&#39;file&#39;]<br>    input_data = pd.read_csv(file)<br>    predictions = model.predict(input_data[feature_names])<br>    input_data[&#39;predicted_sales&#39;] = predictions<br>    return jsonify({&#39;predictions&#39;: input_data.to_dict(orient=&#39;records&#39;)})</pre><p>The server runs with <strong>Gunicorn</strong> (4 workers) on port 7860 — suitable for concurrent requests in a production-like setup.</p><h3>Containerization with Docker</h3><pre>FROM python:3.9-slim<br>WORKDIR /app<br>COPY . .<br>RUN pip install --no-cache-dir --upgrade -r requirements.txt<br>CMD [&quot;gunicorn&quot;, &quot;-w&quot;, &quot;4&quot;, &quot;-b&quot;, &quot;0.0.0.0:7860&quot;, &quot;app:superkart_price_api&quot;]</pre><p>Using python:3.9-slim keeps the image small. The app starts with 4 Gunicorn workers to handle concurrent requests.</p><h3>Frontend: Streamlit UI</h3><p>The Streamlit app provides a clean interface for two use cases:</p><p><strong>Single prediction</strong>: A form with dropdowns and number inputs (product weight, MRP, sugar content, store type, city tier, etc.) that calls the Flask API and displays the predicted revenue.</p><p><strong>Batch prediction</strong>: A file uploader that accepts a CSV of multiple products, sends it to the /v1/predict/batch endpoint, displays the results table, and offers a download button for the predictions CSV.</p><pre>if submitted_single:<br>    response = requests.post(f&quot;{API_BASE_URL}/v1/predict/single&quot;, json=single_item_data)<br>    if response.status_code == 200:<br>        predicted_sales = response.json()[&#39;predicted_sales&#39;]<br>        st.success(f&quot;Predicted Sales: ₹{predicted_sales:,.2f}&quot;)</pre><h3>Uploading to Hugging Face Spaces</h3><p>Both apps were uploaded programmatically using the huggingface_hub library:</p><pre>from huggingface_hub import login, HfApi</pre><pre>login(token=access_key)<br>api = HfApi()</pre><pre>api.upload_folder(<br>    folder_path=&quot;/content/backend_files&quot;,<br>    repo_id=&quot;Prabhusanthanam/superkartsalesbackend&quot;,<br>    repo_type=&quot;space&quot;<br>)</pre><p>This means the entire deployment — from training to hosting — can be run from a single Colab notebook.</p><h3>Live Inference Test</h3><p>Here’s the model predicting sales for a real product:</p><pre>sample_data = {<br>    &quot;Product_Weight&quot;: 12.53,<br>    &quot;Product_Sugar_Content&quot;: &quot;Regular&quot;,<br>    &quot;Product_Allocated_Area&quot;: 0.066,<br>    &quot;Product_Type&quot;: &quot;Fruits and Vegetables&quot;,<br>    &quot;Product_MRP&quot;: 125.79,<br>    &quot;Store_Size&quot;: &quot;Medium&quot;,<br>    &quot;Store_Location_City_Type&quot;: &quot;Tier 2&quot;,<br>    &quot;Store_Type&quot;: &quot;Supermarket Type1&quot;,<br>    &quot;Store_Age&quot;: 15<br>}</pre><pre># Response: Predicted Sales for the single item: ₹2,904.24</pre><h3>Actionable Business Insights</h3><p>The model isn’t just a number generator — it surfaces real patterns in the data that store managers and strategists can act on.</p><h3>1. Price is the strongest lever</h3><p>Product_MRP is the most correlated feature with sales. SuperKart can use this to explore premium product introductions or targeted pricing strategies in high-performing store segments.</p><h3>2. Store type and size matter more than location tier</h3><p>Medium and High-sized Supermarket Type1 and Type2 stores significantly outperform smaller formats and Food Marts. Expansion strategy should prioritise these formats, particularly in Tier 2 cities where the data shows strong performance.</p><h3>3. Category mix is a multiplier</h3><p>‘Fruits and Vegetables’ and ‘Snack Foods’ are both high-frequency and high-revenue categories. Ensuring reliable stock and shelf prominence for these categories especially in high-performing stores — is a direct revenue lever.</p><h3>4. The forecasting model enables operational efficiency at scale</h3><ul><li><strong>Inventory management</strong>: Feed the model into procurement workflows to reduce stockouts and minimise overstocking waste</li><li><strong>Supply chain planning</strong>: Use quarterly forecasts to negotiate better supplier terms and plan logistics ahead of demand peaks</li><li><strong>Regional strategy</strong>: Give regional managers accurate, product-level forecasts to guide staffing, promotions, and store layout decisions</li></ul><h3>Reflections and What’s Next</h3><p>This project was built while learning. I won’t pretend it’s production-ready for a large retailer it isn’t. The dataset is simulated, the infrastructure is small-scale, and there are significant improvements that a real implementation would need:</p><ul><li><strong>Time-series modelling</strong>: Real sales data has temporal patterns seasonality, promotions, weather effects that this cross-sectional model doesn’t capture</li><li><strong>External data</strong>: Economic indicators, competitor pricing, local events</li><li><strong>Continuous retraining</strong>: Model drift is real; as the product mix and customer behaviour evolve, the model needs to evolve too</li><li><strong>Authentication and rate limiting</strong>: The current API is open — a production system needs proper access controls</li></ul><p>But none of that diminishes what this demonstrates: you can go from a business problem observed in a grocery aisle to a live, callable API with a working UI — using skills you can learn.</p><p>That’s the point. You don’t need to work at a large company or have years of experience to build something useful. You need curiosity, a dataset, and the willingness to see the process through from notebook to deployment.</p><h3>Technical Stack Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*UbDAmxt1ImdvRUOv8YVjcQ.png" /></figure><h3>Links</h3><ul><li>🚀 <strong>Live App</strong>: <a href="https://huggingface.co/spaces/Prabhusanthanam/superkart-sales-frontend">huggingface.co/spaces/Prabhusanthanam/superkart-sales-frontend</a></li><li>🔧 <strong>Backend API</strong>: <a href="https://huggingface.co/spaces/Prabhusanthanam/superkartsalesbackend">huggingface.co/spaces/Prabhusanthanam/superkartsalesbackend</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0f6620ee440" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Customer Churn with Machine Learning: From Model to Hugging Face Deployment]]></title>
            <link>https://medium.com/@prabhutells143/predicting-customer-churn-with-machine-learning-from-model-to-hugging-face-deployment-3d10e863b6ef?source=rss-295db4e9811b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d10e863b6ef</guid>
            <dc:creator><![CDATA[Prabhutells]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 18:36:39 GMT</pubDate>
            <atom:updated>2026-04-08T18:36:39.121Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s competitive telecom landscape, retaining customers is as critical as acquiring new ones. High churn rates directly impact revenue and long term growth. To tackle this, I built and deployed a <strong>Customer Churn Prediction App, </strong>a machine learning solution that predicts whether a customer is likely to leave, helping teams take proactive retention measures.</p><p>This blog walks through the entire process from data preparation to hosting the model on <strong>Hugging Face Spaces </strong>blending technical depth with business insight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*9mZk0yPx1Xhzh2zauOTfVQ.png" /></figure><h4>1. Install and Import Necessary Libraries</h4><p>We start by setting up the environment with essential Python libraries:</p><p><em>!pip install pandas==2.2.2 numpy==2.0.2 scikit-learn==1.6.1 xgboost==2.1.4 joblib==1.4.2 streamlit==1.43.2</em></p><p>These libraries handle everything from data manipulation (pandas, numpy) to model training (scikit-learn, xgboost) and deployment (streamlit, joblib).</p><h4>2. Data Loading and Overview</h4><p>The dataset, sourced from a telecom company, contains customer demographics, service details, and churn status. After loading it into a Pandas DataFrame, we explore its structure:</p><p><em>dataset = pd.read_csv(“telecom_churn.csv”)<br>dataset.shape # (5880, 12)</em></p><p>Each row represents a customer, with attributes like <strong>tenure</strong>, <strong>contract type</strong>, <strong>payment method</strong>, and <strong>monthly charges, </strong>all potential churn indicators.</p><h4>3. Exploratory Data Analysis (EDA)</h4><ul><li><em>Define the target variable for the classification task</em></li><li><em>List of numerical features in the dataset</em></li><li><em>List of categorical features in the dataset</em></li><li><em>Generate summary statistics for numerical features</em></li><li><em>Generate categorical insights</em></li><li><em>Compute the proportion of each class in the target variable</em></li></ul><p>EDA helps uncover patterns behind customer behavior.</p><ul><li><strong>Tenure:</strong> Customers range from 1 to 72 months, showing a mix of new and loyal users.</li><li><strong>Contract Type:</strong> Most are on month-to-month plans a known churn risk.</li><li><strong>Payment Method:</strong> Electronic checks correlate with higher churn.</li><li><strong>Churn Distribution:</strong> Roughly 49% of customers have churned, indicating a balanced dataset.</li></ul><p>These insights guide feature selection and model design.</p><h4>4. Model Training with Hyperparameter Tuning</h4><h4>Data Preprocessing</h4><p>We separate numerical and categorical features, applying scaling and one hot encoding:</p><p><em>numeric_features = [‘SeniorCitizen’, ‘tenure’, ‘MonthlyCharges’, ‘TotalCharges’]<br>categorical_features = [‘Partner’, ‘Dependents’, ‘PhoneService’, ‘InternetService’, ‘Contract’, ‘PaymentMethod’]</em></p><p>A ColumnTransformer ensures consistent preprocessing across feature types.</p><h4>Create Model Pipeline</h4><p>We build a pipeline combining preprocessing and model training:</p><p><em>from sklearn.pipeline import make_pipeline<br>from sklearn.compose import make_column_transformer<br>from xgboost import XGBClassifier</em></p><p><em>preprocessor = make_column_transformer(<br> (StandardScaler(), numeric_features),<br> (OneHotEncoder(), categorical_features)<br>)</em></p><p><em>pipeline = make_pipeline(preprocessor, XGBClassifier())</em></p><h4>Model Training</h4><p>The pipeline is trained on the dataset using a train(80%)-test(20%) split. This ensures the model learns patterns while being evaluated on unseen data.</p><h4>Hyperparameter Tuning</h4><p>We use GridSearchCV to optimize parameters like learning rate, max depth, and number of estimators, improving accuracy and generalization.</p><h4>Selecting the Best Model</h4><p>The best-performing model is selected based on validation accuracy and classification metrics. This ensures reliable predictions across diverse customer profiles.</p><h4>5. Model Serialization</h4><p>To reuse the trained model, we serialize it using joblib:</p><p><em>joblib.dump(best_model, “deployment_files/churn_prediction_model_v1_0.joblib”)</em></p><p>Serialization preserves preprocessing steps and learned parameters, enabling seamless deployment.</p><h4>6. Creating a Web App using Streamlit</h4><p>Streamlit transforms the model into an interactive web app. Users can input customer details and instantly view churn predictions.</p><p><em>import streamlit as st<br>import joblib<br>import pandas as pd</em></p><p><em>model = joblib.load(“churn_prediction_model_v1_0.joblib”)</em></p><p><em>st.title(“Customer Churn Prediction App”)<br>st.write(“Predict customer churn risk based on service details.”)</em></p><p>The app collects inputs via dropdowns and numeric fields, runs predictions, and displays churn probability — making machine learning accessible to non-technical users.</p><h4>7. Creating a Dependencies File <strong>— </strong>requirements.txt</h4><p>To ensure reproducibility, we list all dependencies:</p><p><em>pandas==2.2.2<br>numpy==2.0.2<br>scikit-learn==1.6.1<br>xgboost==2.1.4<br>joblib==1.4.2<br>streamlit==1.43.2</em></p><p>This file guarantees consistent environments across development and deployment.</p><h4>8. Created a Dockerfile</h4><p>Containerization ensures the app runs identically anywhere. The Dockerfile defines the environment and execution command:</p><p><em>FROM python:3.9-slim<br>WORKDIR /app<br>COPY . .<br>RUN pip install -r requirements.txt<br>CMD [“streamlit”, “run”, “app.py”, “ — server.port=8501”]</em></p><p>This lightweight setup makes deployment scalable and portable.</p><h4>9. Uploaded Files to Hugging Face Repository</h4><p>Using the huggingface_hub API, we authenticate and upload all deployment files:</p><p><em>from huggingface_hub import login, HfApi</em></p><p><em>login(token=”your_hf_token”)<br>api = HfApi()<br>api.upload_folder(folder_path=”/content/deployment_files”, repo_id=”your_repo_id”, repo_type=”space”)</em></p><p>Files like the model, app script, Dockerfile, and requirements are pushed to the Hugging Face Space — ready for public access.</p><h3>10. Browse the App in Hugging Face for Churn Predictive Insights</h3><p>Once deployed, the app is live on Hugging Face Spaces. Business teams can now input customer details and instantly see churn risk predictions enabling <strong>data-driven retention strategies</strong>.</p><p>This interactive tool bridges the gap between analytics and action, empowering decision-makers to focus on customers who matter most.</p><h3>Final Thoughts</h3><p>This project demonstrates how machine learning can be operationalized from raw data to a live predictive system. By combining <strong>XGBoost</strong>, <strong>Streamlit</strong>, <strong>Docker</strong>, and <strong>Hugging Face Spaces</strong>, we’ve built a scalable, interpretable, and accessible churn prediction solution.</p><p>Whether you’re a data scientist refining models or a business leader seeking actionable insights, this end-to-end workflow shows how AI can drive smarter customer retention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d10e863b6ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Dataiku Deployment: A GitLab-Powered CI/CD Workflow]]></title>
            <link>https://medium.com/@prabhutells143/automating-dataiku-deployment-a-gitlab-powered-ci-cd-workflow-ddeaf91965ef?source=rss-295db4e9811b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddeaf91965ef</guid>
            <dc:creator><![CDATA[Prabhutells]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 18:45:16 GMT</pubDate>
            <atom:updated>2025-06-30T18:45:16.793Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 Introduction</h3><p>In the fast-paced world of data science, getting from idea to impact is only half the story. The other half — often overlooked — is ensuring that those brilliant ideas make it safely and reliably into production. For many organizations, Dataiku has become the go-to platform for building and orchestrating data workflows. But once those models and pipelines are ready, a key question arises: <em>how do we deploy them efficiently and securely without disrupting production stability?</em></p><h3>🧩 Problem Statement</h3><p>At the heart of this story is a business team empowered with Dataiku — a powerful data science platform where they shape their goals into repeatable, workflow-driven solutions. These workflows interact with production-level databases, performing complex transformations and modeling tasks that drive critical decision-making.</p><p>With great power, however, comes the need for governance. To preserve stability, security, and compliance, the organization established guidelines to ensure that all production-bound code:</p><ul><li>Must be <strong>scanned for vulnerabilities</strong>.</li><li>Should be <strong>deployed through a controlled process to maintain consistency</strong>.</li><li>Comes from <strong>version-controlled sources</strong>, not manual uploads.</li></ul><p>However, this shift brought its own challenges:</p><ul><li>Manual deployments were time-consuming and error-prone.</li><li>Business teams are restricted with read-only access to the Automation Node, slowing down delivery.</li><li>Coordinating across Design and Automation Nodes while preserving stability became a significant overhead</li></ul><p>Enter a DevOps-driven solution — automated, secure, and scalable. With a sprinkle of Git hooks, the power of GitLab CI/CD, and the right packaging strategy, we transformed deployment into a smooth, hands-off experience. Let me walk you through how we built it.</p><h3>⚙️ Designing the Deployment Pipeline</h3><p>To tackle the challenges of stability, security, and restricted access, we implemented a fully automated CI/CD pipeline using GitLab. Once business teams commit and merge their feature branches to master in the Dataiku Design Node, a post-merge hook script kicks off the deployment sequence by triggering a GitLab pipeline via API. The pipeline orchestrates four distinct stages, each with a specific role in the delivery lifecycle:</p><h3>🔸 Stage 1: package_bundle</h3><p>his initial stage uses package_bundle.py, a Python script that:</p><ul><li>Leverages the <strong>Dataiku DSS Client</strong> to log into the Design Node.</li><li>Navigates to a predefined project and creates a <strong>deployment bundle</strong>.</li><li>Downloads the bundle to local space and stores it as a <strong>GitLab artifact</strong>.</li></ul><p>This stage encapsulates the project state, ensuring all necessary components are captured for downstream processes.</p><h3>🔸 Stage 2: Snapshot Creation &amp; Sandbox Scan</h3><p>In this job:</p><ul><li>The downloaded bundle is <strong>unzipped</strong> and all .ipynb notebooks are converted to .py scripts to make it eligible for scan.</li><li>A snapshot.zip archive is created from the converted files.</li><li>This archive is uploaded to <strong>JFrog Artifactory</strong>, then scanned for vulnerabilities via <strong>Veracode’s sandbox environment</strong>.</li></ul><p>This early scan stage surfaces potential security issues without blocking release.</p><h3>🔸 Stage 3: Release Build &amp; Static Analysis</h3><p>Mirroring Stage 2 with a production-ready intent:</p><ul><li>The same conversion process creates a release.zip archive.</li><li>This version undergoes a <strong>static analysis scan</strong> in Veracode, ensuring it’s safe for deployment.</li></ul><p>This step formalizes the readiness of the final artifact by applying stricter validation.</p><h3>🔸 Stage 4: Publish &amp; Deploy</h3><p>With the original bundle (from Stage 1) still available:</p><ul><li>It’s <strong>published to the Project Deployer</strong> within Dataiku design node.</li><li>The bundle is then deployed to the <strong>Automation Node</strong>, where production workflows operate.</li><li>Any existing deployments are <strong>updated seamlessly</strong>, preserving continuity while shipping new features.</li></ul><p>This final stage closes the loop by making business-developed workflows accessible in a governed, production-ready environment.</p><p>This pipeline bridges the gap between creative experimentation and reliable execution. Business users stay focused on data science, while DevOps ensures compliance, security, and delivery speed — without manual intervention.</p><h3>Visualization of the workflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sDbRd3PC4JMYphZXq5JTyg.png" /><figcaption>A fully automated CI/CD workflow, bridging Dataiku’s Design Node to the governed Automation Node — powered end-to-end by GitLab</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddeaf91965ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>