<?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 Emma Yasenchak on Medium]]></title>
        <description><![CDATA[Stories by Emma Yasenchak on Medium]]></description>
        <link>https://medium.com/@emyasenc?source=rss-1313f6dd7649------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zRqwcVedPuSvvicD4Irz6Q.png</url>
            <title>Stories by Emma Yasenchak on Medium</title>
            <link>https://medium.com/@emyasenc?source=rss-1313f6dd7649------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:21:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emyasenc/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[Stop Writing API Docs — Let FastAPI Do It For You (Full Guide)]]></title>
            <link>https://medium.com/@emyasenc/stop-writing-api-docs-let-fastapi-do-it-for-you-full-guide-0e3b2030802e?source=rss-1313f6dd7649------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e3b2030802e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Emma Yasenchak]]></dc:creator>
            <pubDate>Fri, 01 May 2026 15:21:39 GMT</pubDate>
            <atom:updated>2026-05-01T15:21:39.860Z</atom:updated>
            <content:encoded><![CDATA[<p>How to use Swagger UI, OpenAPI, and auto‑generated docs to save hours of work</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hOEsW1MOw0WQ-s_x2LYeDg.jpeg" /></figure><p>You’ve built a great API. But without documentation, nobody will use it.</p><p>Writing docs by hand is tedious. Keeping them updated is worse. And when you change your API, your docs almost always fall out of sync.</p><p>FastAPI solves this — automatically.</p><p>In this tutorial, I’ll show you how to leverage auto‑generated Swagger UI, customise OpenAPI, and use the spec to list your API on marketplaces like RapidAPI.</p><p>By the end, you’ll never write API documentation by hand again.</p><h3>What You’ll Learn</h3><ul><li>✅ How FastAPI gives you /docs and /openapi.json for free</li><li>✅ How to add descriptions, examples, and response schemas (small effort, huge win)</li><li>✅ How to export OpenAPI for Postman, RapidAPI, and client SDKs</li><li>✅ How to customise the spec for production (remove internal endpoints, add live server URLs)</li></ul><p>All with copy‑paste code examples from a real production API.</p><h3>Step 1: What You Get for Free (Zero Code)</h3><p>Run your FastAPI app:</p><pre>uvicorn main:app --reload</pre><p>Now open http://localhost:8000/docs in your browser.</p><p>You’ll see:</p><ul><li>Every endpoint listed automatically</li><li>Request parameters with types</li><li>Response schemas</li><li>A “Try it out” button to test live requests</li></ul><p>This alone saves hours of manual documentation.</p><p>No markdown files. No readthedocs. No out‑of‑date screenshots.</p><h3>Step 2: Add Descriptions and Examples (Small Effort, Big Win)</h3><p>Your auto‑generated docs are good. But you can make them great with just a few lines of code.</p><p>python</p><pre>from fastapi import FastAPI, Query<br><br>app = FastAPI(title=&quot;Phone Validation API&quot;, version=&quot;2.0.0&quot;)<br>@app.get(&quot;/validate&quot;)<br>def validate_phone(<br>    phone: str = Query(<br>        ...,<br>        description=&quot;Phone number with country code (e.g., +14155552671)&quot;,<br>        example=&quot;+14155552671&quot;<br>    ),<br>    include_carrier: bool = Query(True, description=&quot;Return carrier name (e.g., AT&amp;T)&quot;),<br>    include_location: bool = Query(True, description=&quot;Return city, state, and country&quot;)<br>):<br>    &quot;&quot;&quot;Validate a phone number and return carrier, timezone, and location data.&quot;&quot;&quot;<br>    # your validation logic here<br>    return {&quot;phone&quot;: phone, &quot;valid&quot;: True}</pre><p>Now your /docs page has clear, helpful descriptions and clickable examples – without maintaining a separate documentation site.</p><h3>Step 3: Add Response Schemas (So Users Know What They’ll Get)</h3><p>Define what your API returns using Pydantic models. FastAPI will automatically render the schema in /docs.</p><pre>from pydantic import BaseModel<br>from typing import Optional, List<br><br>class ValidationResponse(BaseModel):<br>    phone: str<br>    valid: bool<br>    carrier: Optional[str] = None<br>    location: Optional[str] = None<br>    timezone: Optional[List[str]] = None<br>    formatted_number: Optional[str] = None<br>@app.get(&quot;/validate&quot;, response_model=ValidationResponse)<br>def validate_phone(phone: str):<br>    # your logic here<br>    return {&quot;phone&quot;: phone, &quot;valid&quot;: True}</pre><p>Users see exactly what fields they’ll receive — no guesswork, no extra documentation to write.</p><h3>Step 4: Export OpenAPI (For RapidAPI, Postman, and Client SDKs)</h3><p>Your API already has an OpenAPI specification at /openapi.json. Grab it:</p><pre>curl http://localhost:8000/openapi.json &gt; openapi.json</pre><p>You can now use this file to:</p><ul><li>Import into Postman — generates a complete API collection automatically</li><li>Import into RapidAPI — when listing your API for monetisation</li><li>Generate client SDKs — Python, JavaScript, TypeScript, Go, etc. (using tools like openapi-generator)</li></ul><p>This is the secret step that most developers miss.</p><h3>Step 5: Customise OpenAPI for Production</h3><p>Before sharing your OpenAPI spec, clean it up and add your production server URL.</p><pre>from fastapi.openapi.utils import get_openapi<br><br>def custom_openapi():<br>    if app.openapi_schema:<br>        return app.openapi_schema<br>    openapi_schema = get_openapi(<br>        title=&quot;Phone Validation API&quot;,<br>        version=&quot;2.0.0&quot;,<br>        description=&quot;Validate phone numbers worldwide – carrier, timezone, and location.&quot;,<br>        routes=app.routes,<br>    )<br>    # Add your production server (not localhost)<br>    openapi_schema[&quot;servers&quot;] = [<br>        {&quot;url&quot;: &quot;https://yasen-alpha-phone-validator.p.rapidapi.com&quot;, &quot;description&quot;: &quot;Production (RapidAPI)&quot;},<br>        {&quot;url&quot;: &quot;https://phone-validation-api.onrender.com&quot;, &quot;description&quot;: &quot;Direct deployment&quot;}<br>    ]<br>    app.openapi_schema = openapi_schema<br>    return app.openapi_schema<br>app.openapi = custom_openapi</pre><p>Now your exported OpenAPI file points to your live URL — not localhost. Anyone who downloads it can immediately call your real API.</p><h3>Step 6: Real‑World Example — My Phone Validation API</h3><p>I use all these techniques in my live Phone Validation API:</p><ul><li>📚 /docs page with descriptions, examples, and schemas</li><li>📄 OpenAPI spec exported and imported into RapidAPI</li><li>🔗 Automatic client generation for users</li></ul><p>👉 <a href="https://rapidapi.com/emyasenc/api/yasen-alpha-phone-validator">See the live API docs on RapidAPI</a></p><p>👉 <a href="https://github.com/emyasenc/phone-validation-api">Explore the source code on GitHub</a></p><h3>What You’ve Learned</h3><p>FeatureWhat FastAPI Gives YouInteractive docs/docs – zero codeOpenAPI specification/openapi.json – zero codeRequest examplesAdd example= to Query parametersResponse schemasUse response_model with PydanticProduction‑ready specCustomise with custom_openapi()</p><p>You never need to write API documentation by hand again.</p><h3>Next Steps</h3><ul><li>Add authentication to your docs (API key header)</li><li>Generate a Python client from your OpenAPI spec using openapi-python-client</li><li>Host your OpenAPI spec on GitHub for external linking</li><li>List your API on RapidAPI using the OpenAPI import feature</li></ul><h3>Resources</h3><ul><li>🔗 <a href="https://fastapi.tiangolo.com/tutorial/metadata/">FastAPI Documentation — Metadata</a></li><li>🔗 <a href="https://fastapi.tiangolo.com/tutorial/response-model/">FastAPI Documentation — Response Model</a></li><li>🔗 <a href="https://swagger.io/specification/">OpenAPI Specification</a></li><li>🔗 <a href="https://github.com/emyasenc/phone-validation-api">My Phone Validation API (GitHub)</a></li><li>🔗 <a href="https://rapidapi.com/emyasenc/api/yasen-alpha-phone-validator">My Live API on RapidAPI</a></li></ul><p>If you found this useful, follow me for more production‑API tips.</p><p><em>Stop writing docs. Start shipping.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e3b2030802e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Jupyter Notebook to Production API in 30 Minutes (FastAPI + Render)]]></title>
            <link>https://medium.com/@emyasenc/from-jupyter-notebook-to-production-api-in-30-minutes-fastapi-render-0b148fcf1945?source=rss-1313f6dd7649------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b148fcf1945</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Emma Yasenchak]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 22:03:44 GMT</pubDate>
            <atom:updated>2026-04-29T22:37:32.535Z</atom:updated>
            <content:encoded><![CDATA[<p>Stop keeping your models in notebooks. Deploy them as real APIs that anyone can call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zKMX-9hjn1zJILcPFmACPQ.jpeg" /></figure><p>You’ve trained a model. It works in your Jupyter Notebook. Now what?</p><p>If you’re like most data scientists, the model sits on your laptop, collecting dust.</p><p>In this tutorial, I’ll show you how to turn any ML model into a production API — in 30 minutes, for free.</p><p>We’ll use:</p><ul><li>A real example (phone number validation — no ML required, so anyone can follow)</li><li>FastAPI to build the API</li><li>Render to deploy it (free tier)</li></ul><p>By the end, you’ll have a live API that anyone can call. And you’ll know exactly how to do it for your own models.</p><h3>What You’ll Build</h3><p>A Phone Validation API that:</p><ul><li>Validates phone numbers from 200+ countries</li><li>Returns carrier, timezone, and location data</li><li>Handles single requests and batch validation</li><li>Is live on the internet, ready to use</li></ul><p>No cloud bills. No complex DevOps. Just code.</p><h3>Why This Works for Any ML Model</h3><p>The same steps apply whether you’re using:</p><ul><li>scikit‑learn (logistic regression, random forest)</li><li>XGBoost / LightGBM</li><li>A simple rule‑based system (like our phone validator)</li></ul><p>You’ll learn a workflow you can reuse for every model you build.</p><h3>Step 1: The Model (Already in a Notebook, Now in a Script)</h3><p>Let’s pretend we have a simple function inside a Jupyter notebook that validates phone numbers.</p><pre># In your Jupyter notebook<br>import phonenumbers<br><br>def validate_phone(phone: str) -&gt; dict:<br>    parsed = phonenumbers.parse(phone, None)<br>    is_valid = phonenumbers.is_valid_number(parsed)<br>    return {&quot;phone&quot;: phone, &quot;valid&quot;: is_valid}</pre><p>Now we’ll take this exact logic and move it into a FastAPI application.</p><h3>Step 2: Create a FastAPI Project (2 Minutes)</h3><p>Open your terminal and run:</p><pre>mkdir phone-api<br>cd phone-api<br>python -m venv venv<br>source venv/bin/activate<br>pip install fastapi uvicorn phonenumbers</pre><p>Create main.py and paste the code below:</p><pre>from fastapi import FastAPI, Query<br>import phonenumbers<br><br>app = FastAPI(title=&quot;Phone Validation API&quot;)<br>def validate_phone_logic(phone: str) -&gt; dict:<br>    parsed = phonenumbers.parse(phone, None)<br>    is_valid = phonenumbers.is_valid_number(parsed)<br>    return {&quot;phone&quot;: phone, &quot;valid&quot;: is_valid}<br>@app.get(&quot;/validate&quot;)<br>def validate(phone: str = Query(..., description=&quot;Phone with country code&quot;)):<br>    result = validate_phone_logic(phone)<br>    return result</pre><p>Run it locally:</p><pre>uvicorn main:app --reload</pre><p>Test it:</p><pre>curl &quot;http://localhost:8000/validate?phone=%2B14155552671&quot;</pre><p>That’s it — your model is now an API.</p><h3>Step 3: Add Features (No Notebook Jupyter Required)</h3><p>Your notebook might have had more advanced logic. Let’s add carrier and location.</p><p>Update main.py:</p><pre>from phonenumbers import carrier, geocoder<br><br>def validate_phone_logic(phone: str) -&gt; dict:<br>    parsed = phonenumbers.parse(phone, None)<br>    is_valid = phonenumbers.is_valid_number(parsed)<br>    result = {&quot;phone&quot;: phone, &quot;valid&quot;: is_valid}<br>    if is_valid:<br>        result[&quot;carrier&quot;] = carrier.name_for_number(parsed, &quot;en&quot;) or &quot;Unknown&quot;<br>        result[&quot;location&quot;] = geocoder.description_for_number(parsed, &quot;en&quot;) or &quot;Unknown&quot;<br>    return result</pre><p>Test again:</p><pre>curl &quot;http://localhost:8000/validate?phone=%2B14155552671&quot;</pre><p>Now you get carrier and location data. This is exactly how my production Phone Validation API works — but you could replace validate_phone_logic with any ML model (logistic regression, XGBoost, etc.).</p><h3>Step 4: Batch Endpoint (Handle Multiple Predictions)</h3><p>Real‑world users rarely predict one item at a time. Add a batch endpoint.</p><pre>from typing import List<br><br>@app.post(&quot;/validate/batch&quot;)<br>def validate_batch(phones: List[str]):<br>    results = [validate_phone_logic(p) for p in phones]<br>    return {&quot;total&quot;: len(results), &quot;results&quot;: results}</pre><p>Test it:</p><pre>curl -X POST &quot;http://localhost:8000/validate/batch&quot; \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;[&quot;+14155552671&quot;, &quot;+380671234567&quot;]</pre><p>This is the same pattern you’d use for batch inference with any ML model.</p><h3>Step 5: Add Documentation (Free, Auto‑Generated)</h3><p>FastAPI gives you interactive API docs at /docs – no extra code.</p><p>Visit http://localhost:8000/docs. You&#39;ll see a Swagger UI where anyone can test your API.</p><p>This is a huge advantage over Jupyter notebooks. Non‑technical stakeholders can try the model immediately.</p><h3>Step 6: Deploy to Production (Free Tier)</h3><h3>6.1 Push to GitHub</h3><p>Create a GitHub repository and push your code:</p><pre>git init<br>git add .<br>git commit -m &quot;Initial commit&quot;<br>git remote add origin https://github.com/yourusername/phone-api.git<br>git push -u origin main</pre><h3>6.2 Deploy on Render</h3><ol><li>Go to <a href="https://render.com/">render.com</a> and sign up with GitHub.</li><li>Click “New +” → “Web Service”.</li><li>Connect your GitHub repo.</li><li>Use these settings:</li></ol><ul><li>Build Command: pip install -r requirements.txt</li><li>Start Command: uvicorn main:app --host 0.0.0.0 --port 10000</li></ul><p>5. Click “Create Web Service”.</p><p>In 2–3 minutes, your API is live at a URL like <a href="https://your-app.onrender.com./">https://your-app.onrender.com.</a></p><h3>6.3 Test the Live API</h3><pre>curl &quot;https://your-app.onrender.com/validate?phone=%2B14155552671&quot;</pre><p>Your model is now a production API, accessible from anywhere.</p><h3>Step 7: Monetise (Optional — Add to RapidAPI)</h3><p>You can list your API on <a href="https://rapidapi.com/">RapidAPI</a> and charge for it.</p><ul><li>Set a free tier (e.g., 1,500 requests/month)</li><li>Add paid tiers for higher usage</li><li>Developers discover your API through RapidAPI’s marketplace</li></ul><p>This is exactly what I did with my Phone Validation API — it’s live, used by real developers, and costs me less than $7/month to host.</p><h3>What You’ve Learned</h3><ul><li>How to take code from a Jupyter notebook and turn it into a FastAPI application</li><li>How to add single and batch endpoints</li><li>How to auto‑generate documentation</li><li>How to deploy for free on Render</li><li>How to monetise on RapidAPI</li></ul><p>You can apply this same workflow to any ML model — scikit‑learn, XGBoost, TensorFlow, PyTorch, or a simple heuristic.</p><h3>See It Live — My Production API</h3><p>I built a full production version of this API with caching, rate limiting, webhooks, and batch validation.</p><p>👉 <a href="https://rapidapi.com/emyasenc/api/yasen-alpha-phone-validator">Test it free on RapidAPI</a></p><p>👉 <a href="https://github.com/emyasenc/phone-validation-api">Explore the source code on GitHub</a></p><h3>Next Steps</h3><ul><li>Replace the validation logic with your own ML model (logistic regression, random forest, etc.)</li><li>Add caching (lru_cache) to speed up repeated predictions</li><li>Add rate limiting to prevent abuse</li><li>Add webhooks to notify other services when a prediction is made</li></ul><h3>Resources</h3><ul><li>🔗 <a href="https://fastapi.tiangolo.com/">FastAPI Documentation</a></li><li>🔗 <a href="https://render.com/">Render Free Tier</a></li><li>🔗 <a href="https://rapidapi.com/">RapidAPI Marketplace</a></li><li>🔗 <a href="https://rapidapi.com/emyasenc/api/yasen-alpha-phone-validator">My Live Phone Validation API</a></li></ul><p><em>Stop leaving your models in notebooks. Ship them.</em></p><p>Follow me for more tutorials on deploying ML to production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b148fcf1945" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Choose the Right Deployment Platform for Your API or SaaS (2026 Guide)]]></title>
            <link>https://medium.com/@emyasenc/how-to-choose-the-right-deployment-platform-for-your-api-or-saas-2026-guide-74fc142b0768?source=rss-1313f6dd7649------2</link>
            <guid isPermaLink="false">https://medium.com/p/74fc142b0768</guid>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[render]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Emma Yasenchak]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 22:09:01 GMT</pubDate>
            <atom:updated>2026-04-28T22:09:01.256Z</atom:updated>
            <content:encoded><![CDATA[<p>AWS vs Render vs Heroku vs Railway vs Azure — pricing, ease of use, scalability, and when to use each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r5-2kaqYfrzZSYFpf-XrgQ.jpeg" /></figure><p>You’ve built your API. It works perfectly on your laptop. Now you need to put it online.</p><p>But AWS, Azure, Render, Heroku, Railway… which one do you choose?</p><p>I’ve been there. Confused. Overwhelmed. Afraid of picking the “wrong” platform.</p><p>After deploying multiple production APIs (phone validation, job scam detection, and more), I’ve learned what actually matters — and what doesn’t.</p><p>This guide is not sponsored. I’m not affiliated with any platform. This is just honest advice from someone who has shipped real code.</p><p>Let’s cut through the noise.</p><h3>What Actually Matters (Most Developers Get This Wrong)</h3><p>Before comparing platforms, here’s what you should care about:</p><p>Pricing — Is there a free tier? Pay-as-you-go or predictable monthly cost?</p><p>Ease of use — Can you deploy in 5 minutes or 5 hours?</p><p>Scalability — Will it handle 100 users? 10,000?</p><p>Vendor lock‑in — Can you leave without rewriting everything?</p><p>Database &amp; add‑ons — Does it support PostgreSQL, Redis, background jobs?</p><p>The #1 mistake developers make: They choose AWS for a small startup project because “that’s what big companies use.” Then they spend weeks configuring IAM roles, VPCs, and load balancers.</p><p>Don’t do that.</p><h3>Platform‑by‑Platform Breakdown (Honest, No Sponsorship)</h3><p>I’ve used Render, Heroku, and Railway for real projects. For AWS and Azure, I’ve learned from painful migrations and from talking to developers who use them daily.</p><p><strong>Render</strong> — Best for solo developers, startups, and APIs. Free tier available, then $7–20/month. Very easy to use. Scales well. Low vendor lock‑in.</p><p><strong>Heroku</strong> — Best for legacy apps and simple deploys. No free tier (expensive). Easy to use. Scales well. Medium vendor lock‑in.</p><p><strong>Railway</strong> — Best for hobbyists and prototypes. Free tier available, simple pricing. Very easy to use. Scales moderately. Low vendor lock‑in.</p><p><strong>AWS</strong> — Best for enterprises and huge scale. Pay‑as‑you‑go (complex). Hard to learn. Excellent scalability. High vendor lock‑in.</p><p><strong>Azure</strong> — Best for Microsoft‑focused teams. Pay‑as‑you‑go (complex). Hard to learn. Excellent scalability. High vendor lock‑in.</p><p><strong>Fly.io </strong>— Best for global apps needing low latency. Fair pricing. Medium ease of use. Scales well. Low vendor lock‑in.</p><h3>Deep Dive: When to Choose Each Platform</h3><h3>Render — The Sweet Spot for Solo Developers and Startups</h3><p>I deployed my Phone Validation API on Render. Here’s why:</p><ul><li>Free tier for testing</li><li>GitHub integration (push → auto‑deploy)</li><li>Start command: python main.py (no complicated config)</li><li>$7/month starter plan for production</li><li>Built‑in environment variables, logging, and SSL</li></ul><p>It took me 5 minutes to go from GitHub to live URL.</p><p>👉 <em>If you’re a solo developer or a small startup, start with Render.</em></p><h3>Railway — Great for Hobby Projects</h3><p>Railway has a beautifully simple UI and transparent pricing. It’s perfect for prototypes, side projects, or learning.</p><p>Downside: Less community resources than Render or AWS. But for hobby work, it’s fantastic.</p><h3>Heroku — The Veteran (But Dated)</h3><p>Heroku was the gold standard for years. Then Salesforce removed the free tier, and pricing became expensive for what you get.</p><p>Still useful for: Legacy apps, teams already familiar with Heroku, or apps that rely on Heroku’s extensive add‑on marketplace.</p><p>But for new projects? There are better, cheaper options.</p><h3>AWS — When You Absolutely Need Enterprise Scale</h3><p>AWS is incredibly powerful. It can handle millions of users. But with that power comes complexity.</p><p>You’ll need to learn:</p><ul><li>EC2 vs ECS vs Lambda</li><li>IAM roles and policies</li><li>VPCs and subnets</li><li>Load balancers and auto‑scaling groups</li></ul><p>Only choose AWS if:</p><ul><li>You’re serving enterprise customers who demand AWS</li><li>You need HIPAA, SOC2, or other compliance certifications</li><li>You have a dedicated DevOps person (or team)</li></ul><p>For most solo developers and startups, AWS is overkill.</p><h3>Azure — Best for Microsoft‑Focused Teams</h3><p>Same complexity as AWS. Choose Azure only if your company already uses .NET, Active Directory, or other Microsoft services extensively.</p><h3>Fly.io — Interesting Alternative for Global Apps</h3><p>Fly.io makes deploying apps close to users around the world easy. Great pricing, solid documentation. Less beginner‑friendly than Render, but worth exploring for latency‑sensitive applications.</p><h3>Decision Framework (Follow Along)</h3><p>Use this simple flow to find your answer:</p><ul><li>Do you need global scale (millions of users)? → AWS / Azure</li><li>Are you a solo developer or small startup? → Render</li><li>Do you want to deploy in &lt;5 minutes? → Render / Railway / Fly.io</li><li>Is this a hobby or learning project? → Railway or Render free tier</li><li>Do you need enterprise compliance (HIPAA, SOC2)? → AWS / Azure</li><li>Are you stuck with a legacy Heroku app? → Migrate to Render (it’s easy)</li></ul><p>For 80% of readers of this article, the answer is Render.</p><h3>Real‑World Examples (From My Own Projects)</h3><p>I’m not theorising. I’ve actually deployed production APIs on Render.</p><p><strong>Phone Validation API</strong> — Validates carrier, timezone, location, and 200+ countries. Deployed on Render because of the free tier for testing, $7/month for production, GitHub integration, and zero downtime deploys.</p><p><strong>Job Scam Detector API </strong>— 98.8% accuracy, 1.2% false positives. Deployed on Render for the same reasons — predictable cost, no surprise bills.</p><p>Both are live on RapidAPI, used by developers, and cost me less than $15/month total.</p><p>👉 <a href="https://rapidapi.com/emyasenc/api/yasen-alpha-phone-validator">Phone Validation API — Free Tier</a></p><p>👉 <a href="https://rapidapi.com/emyasenc/api/yasen-alpha-job-scam-detector1">Job Scam Detector API — Free Tier</a></p><h3>How to Move Platforms (When You Must)</h3><p>Don’t be afraid of lock‑in. Moving is easier than most people think.</p><p>From Render to Railway — Easy (both are container‑based).</p><p>From Heroku to Render — Very easy (Render has a Heroku import tool).</p><p>From Railway to Render — Easy.</p><p>From any platform to AWS — Hard. Avoid unless necessary.</p><p>Start simple. You can always migrate later.</p><h3>The Bottom Line (One‑Sentence Recommendation)</h3><p>If you’re a solo developer or a small startup — Start with Render (free tier, then $7/month).</p><p>If you’re a hobbyist with tiny projects — Start with Railway or Render’s free tier.</p><p>If you’re an enterprise with millions of users — Start with AWS or Azure.</p><p>If you’re unsure — Start with Render. You can’t go wrong.</p><p>For 90% of people reading this, Render is the right choice. It was for me.</p><h3>What Platform Did I Miss?</h3><p>I’d love to hear your experience.</p><ul><li>Are you using Fly.io? Koyeb? DigitalOcean App Platform?</li><li>What’s your favourite deployment platform and why?</li></ul><p>Drop a comment below. Let’s help the community make better decisions.</p><h3>Resources</h3><ul><li>🔗 My Phone Validation API (Live on Render) — <a href="https://rapidapi.com/emyasenc/api/yasen-alpha-phone-validator">Free Tier on RapidAPI</a></li><li>🔗 My Job Scam Detector API (Live on Render) — <a href="https://rapidapi.com/emyasenc/api/yasen-alpha-job-scam-detector1">Free Tier on RapidAPI</a></li><li>🔗 Deploy on Render documentation — <a href="https://render.com/docs">render.com/docs</a></li></ul><p><em>I wrote this because I spent too many hours being confused by deployment platforms. Hope it saves you that time.</em></p><p>Follow me for more practical tutorials on building, deploying, and monetizing APIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74fc142b0768" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a FastAPI Phone Validation API with Carrier, Timezone & Location Data]]></title>
            <link>https://medium.com/@emyasenc/build-a-fastapi-phone-validation-api-with-carrier-timezone-location-data-9b94fe2073e6?source=rss-1313f6dd7649------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b94fe2073e6</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Emma Yasenchak]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 21:43:27 GMT</pubDate>
            <atom:updated>2026-04-28T21:43:27.379Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6F10l88dvyorSiz6_rcTw.jpeg" /></figure><p>If you’ve ever built an API that worked perfectly on your laptop but crashed mysteriously after deployment, this tutorial is for you.</p><p>I’ll show you how to build, optimize, cache, document, deploy, and monetize a real, production‑grade phone validation API using FastAPI and Python.</p><p>Along the way, you’ll learn:</p><ul><li>✅ Build a complete FastAPI application — from a single endpoint to batch processing, caching, and webhooks</li><li>✅ Add professional touches: request validation, error handling, and automatic Swagger documentation</li><li>✅ Deploy for free on Render and list on RapidAPI</li><li>✅ Avoid the 10 most common “works on my machine” traps</li></ul><p>And yes — you can use the live API for free at the end of this tutorial.</p><p>📌 The complete source code is on GitHub — link at the bottom.</p><h3>What We’re Building</h3><p>A Phone Validation API that:</p><ul><li>Validates phone numbers in 200+ countries</li><li>Returns carrier, timezone, and location data</li><li>Supports single requests, batch validation (up to 100 numbers), and CSV bulk upload</li><li>Includes caching, rate limiting, and webhooks for invalid numbers</li><li>Is ready to be sold on RapidAPI</li></ul><p>This is not a toy example. This is the same API I built and deployed for my own projects — and it’s working in production right now.</p><h3>Why Phone Validation?</h3><p>Every app that collects user phone numbers faces the same problem: invalid numbers cause failed deliveries, wasted SMS credits, and frustrated users.</p><p>Most developers don’t want to build phone validation from scratch. They want a reliable API that just works.</p><p>That’s why I built this.</p><h3>1. Project Setup</h3><p>First, create a project folder and virtual environment.</p><pre>mkdir phone-validation-api<br>cd phone-validation-api<br>python3.11 -m venv venv<br>source venv/bin/activate  # On Windows: venv\Scripts\activate</pre><p>Create requirements.txt:</p><pre>fastapi==0.104.1<br>uvicorn==0.24.0<br>phonenumbers==8.13.18<br>python-multipart==0.0.6<br>httpx==0.25.0</pre><p>Install everything:</p><pre>pip install -r requirements.txt</pre><h3>2. Core Validation Logic</h3><p>We’ll use Google’s phonenumbers library — the same library that powers Android phones.</p><p>Inside main.py, add the helper functions:</p><pre>import re<br>import phonenumbers<br>from phonenumbers import carrier, timezone, geocoder<br>from phonenumbers.phonenumberutil import NumberParseException<br><br>def clean_phone_number(phone: str) -&gt; str:<br>    return re.sub(r&#39;[^\d+]&#39;, &#39;&#39;, phone)<br>def validate_phone_logic(phone: str, include_carrier: bool,<br>                         include_timezone: bool,<br>                         include_location: bool) -&gt; dict:<br>    cleaned = clean_phone_number(phone)<br>    parsed = phonenumbers.parse(cleaned, None)<br>    is_valid = phonenumbers.is_valid_number(parsed)<br>    is_possible = phonenumbers.is_possible_number(parsed)<br>    response = {<br>        &quot;phone&quot;: phone,<br>        &quot;valid&quot;: is_valid,<br>        &quot;possible&quot;: is_possible,<br>        &quot;formatted_number&quot;: phonenumbers.format_number(<br>            parsed, phonenumbers.PhoneNumberFormat.E164<br>        ),<br>        &quot;country_code&quot;: parsed.country_code,<br>        &quot;national_number&quot;: str(parsed.national_number),<br>        &quot;source&quot;: &quot;YASEN-ALPHA&quot;<br>    }<br>    if include_carrier and is_valid:<br>        try:<br>            response[&quot;carrier&quot;] = carrier.name_for_number(parsed, &quot;en&quot;) or &quot;Unknown&quot;<br>        except:<br>            response[&quot;carrier&quot;] = None<br>    if include_timezone and is_valid:<br>        try:<br>            tz_set = timezone.time_zones_for_number(parsed)<br>            response[&quot;timezone&quot;] = list(tz_set) if tz_set else None<br>        except:<br>            response[&quot;timezone&quot;] = None<br>    if include_location and is_valid:<br>        try:<br>            response[&quot;location&quot;] = geocoder.description_for_number(parsed, &quot;en&quot;) or &quot;Unknown&quot;<br>        except:<br>            response[&quot;location&quot;] = None<br>    return response</pre><p>This function will be reused in every endpoint.</p><h3>3. First Endpoint — /validate</h3><p>Add caching to speed up repeated requests.</p><pre>from fastapi import FastAPI, Query, HTTPException, status<br>from fastapi.responses import JSONResponse<br>from functools import lru_cache<br>import asyncio<br>from concurrent.futures import ThreadPoolExecutor<br><br>app = FastAPI(title=&quot;Phone Validation API&quot;, version=&quot;2.0.0&quot;)<br>executor = ThreadPoolExecutor(max_workers=4)<br>@lru_cache(maxsize=1000)<br>def cached_validate_phone(phone: str, include_carrier: bool,<br>                          include_timezone: bool,<br>                          include_location: bool) -&gt; str:<br>    # Full implementation in the GitHub repo<br>    import json<br>    try:<br>        # ... validation logic ...<br>        return json.dumps(response)<br>    except NumberParseException as e:<br>        error_response = {<br>            &quot;phone&quot;: phone,<br>            &quot;valid&quot;: False,<br>            &quot;error&quot;: str(e),<br>            &quot;example&quot;: &quot;+14155552671&quot;<br>        }<br>        return json.dumps(error_response)<br>@app.get(&quot;/validate&quot;)<br>async def validate_phone(<br>    phone: str = Query(..., description=&quot;Number with country code, e.g., +14155552671&quot;),<br>    include_carrier: bool = True,<br>    include_timezone: bool = True,<br>    include_location: bool = True<br>):<br>    if not phone or len(phone) &lt; 2:<br>        raise HTTPException(<br>            status_code=status.HTTP_400_BAD_REQUEST,<br>            detail={&quot;error&quot;: &quot;INVALID_PHONE_FORMAT&quot;,<br>                    &quot;message&quot;: &quot;Phone number is too short&quot;,<br>                    &quot;example&quot;: &quot;+14155552671&quot;}<br>        )<br>    loop = asyncio.get_event_loop()<br>    result = await loop.run_in_executor(<br>        executor,<br>        validate_phone_logic,<br>        phone, include_carrier, include_timezone, include_location<br>    )<br>    return JSONResponse(content=result)</pre><p>Test it locally:</p><pre>uvicorn main:app --reload --port 8005</pre><pre>curl &quot;http://localhost:8005/validate?phone=%2B14155552671&quot;</pre><p>Expected output:</p><pre>{<br>  &quot;phone&quot;: &quot;+14155552671&quot;,<br>  &quot;valid&quot;: true,<br>  &quot;carrier&quot;: &quot;AT&amp;T Mobility&quot;,<br>  &quot;timezone&quot;: [&quot;America/Los_Angeles&quot;],<br>  &quot;location&quot;: &quot;San Francisco, CA&quot;<br>}</pre><p>Notice that FastAPI automatically gives you interactive API docs at /docs.</p><h3>4. Batch Endpoint — /validate/batch</h3><p>A real API must handle many items at once. Here we validate up to 100 numbers in parallel.</p><pre>@app.post(&quot;/validate/batch&quot;)<br>async def validate_batch(<br>    phones: List[str],<br>    include_carrier: bool = True,<br>    include_timezone: bool = True,<br>    include_location: bool = True<br>):<br>    if len(phones) &gt; 100:<br>        raise HTTPException(<br>            status_code=status.HTTP_400_BAD_REQUEST,<br>            detail=&quot;Maximum 100 phone numbers per batch request&quot;<br>        )<br><br>  async def validate_one(phone):<br>          try:<br>              cleaned = clean_phone_number(phone)<br>              parsed = phonenumbers.parse(cleaned, None)<br>              is_valid = phonenumbers.is_valid_number(parsed)<br>              result = {<br>                  &quot;phone&quot;: phone,<br>                  &quot;valid&quot;: is_valid,<br>                  &quot;formatted_number&quot;: phonenumbers.format_number(<br>                      parsed, phonenumbers.PhoneNumberFormat.E164<br>                  )<br>              }<br>              if include_carrier and is_valid:<br>                  result[&quot;carrier&quot;] = carrier.name_for_number(parsed, &quot;en&quot;) or &quot;Unknown&quot;<br>              if include_timezone and is_valid:<br>                  tz_set = timezone.time_zones_for_number(parsed)<br>                  result[&quot;timezone&quot;] = list(tz_set) if tz_set else None<br>              if include_location and is_valid:<br>                  result[&quot;location&quot;] = geocoder.description_for_number(parsed, &quot;en&quot;) or &quot;Unknown&quot;<br>              return result, is_valid<br>          except NumberParseException as e:<br>              return {&quot;phone&quot;: phone, &quot;valid&quot;: False, &quot;error&quot;: str(e)}, False<br>      tasks = [validate_one(p) for p in phones]<br>      results_data = await asyncio.gather(*tasks)<br>      results = []<br>      valid_count = 0<br>      for r, is_valid in results_data:<br>          results.append(r)<br>          if is_valid:<br>              valid_count += 1<br>      return {<br>          &quot;total&quot;: len(results),<br>          &quot;valid_count&quot;: valid_count,<br>          &quot;results&quot;: results,<br>          &quot;batch_id&quot;: datetime.utcnow().strftime(&quot;%Y%m%d%H%M%S&quot;)<br>      }</pre><p>This endpoint already gives you batch processing that many commercial APIs charge extra for.</p><h3>5. Error Handling for Production</h3><p>A production API must be predictable. Always return JSON errors with the correct HTTP status codes.</p><pre>except NumberParseException as e:<br>    raise HTTPException(<br>        status_code=status.HTTP_400_BAD_REQUEST,<br>        detail={&quot;error&quot;: &quot;INVALID_PHONE_FORMAT&quot;,<br>                &quot;message&quot;: str(e),<br>                &quot;example&quot;: &quot;+14155552671&quot;}<br>    )</pre><p>Now a malformed request returns a clean, helpful error:</p><pre>{<br>  &quot;detail&quot;: {<br>    &quot;error&quot;: &quot;INVALID_PHONE_FORMAT&quot;,<br>    &quot;message&quot;: &quot;Missing or invalid default region.&quot;,<br>    &quot;example&quot;: &quot;+14155552671&quot;<br>  }<br>}</pre><h3>6. Documentation &amp; Root Endpoint</h3><p>FastAPI gives you a free interactive Swagger UI at /docs.</p><p>Add a root endpoint that explains pricing and features:</p><pre>@app.get(&quot;/&quot;)<br>def root():<br>    return {<br>        &quot;service&quot;: &quot;Phone Validation API&quot;,<br>        &quot;version&quot;: &quot;2.0.0&quot;,<br>        &quot;pricing&quot;: {<br>            &quot;free&quot;: &quot;1,500 requests/day&quot;,<br>            &quot;pro&quot;: &quot;$19/month for 15,000 requests&quot;,<br>            &quot;ultra&quot;: &quot;$49/month for 75,000 requests&quot;<br>        },<br>        &quot;features&quot;: [<br>            &quot;200+ countries&quot;,<br>            &quot;Carrier detection&quot;,<br>            &quot;Timezone &amp; location&quot;,<br>            &quot;Batch validation&quot;,<br>            &quot;Bulk CSV upload&quot;,<br>            &quot;Webhooks&quot;<br>        ]<br>    }</pre><h3>7. Deployment — Render + RapidAPI</h3><h3>Deploy on Render (Free Tier)</h3><ol><li>Push your code to a GitHub repository</li><li>On <a href="https://render.com/">Render.com</a>, click New + → Web Service</li><li>Connect your GitHub repo and use:</li></ol><ul><li>Build Command: pip install -r requirements.txt</li><li>Start Command: python main.py</li><li>Environment Variable: ENVIRONMENT=production</li></ul><p>4. Click Create Web Service — in 2 minutes your API is live</p><h3>List on RapidAPI</h3><ol><li>Go to <a href="https://rapidapi.com/">RapidAPI</a> → Add New API</li><li>Provide your Render URL as the Base URL</li><li>Import the OpenAPI spec (auto‑generated at /openapi.json)</li><li>Set your pricing: free tier + $19/month + $49/month</li><li>Publish — your API is now ready for the world</li></ol><h3>8. See It Live — Free Tier Available</h3><p>I already deployed the full production version of this API. It includes everything we just built plus:</p><ul><li>✅ LRU caching (reduces latency)</li><li>✅ Rate limiting</li><li>✅ Webhooks (notify your server when an invalid number is detected)</li><li>✅ Bulk CSV upload</li><li>✅ Open‑source code on GitHub</li></ul><p>👉 Test it for free: <a href="https://rapidapi.com/emyasenc/api/yasen-alpha-phone-validator">Phone Validation API on RapidAPI</a></p><p>👉 Vote for it on Product Hunt: <a href="https://www.producthunt.com/products/yasen-alpha-phone-validation-api">YASEN-ALPHA Phone Validation API — Live on Product Hunt</a></p><pre>curl --request GET \<br>  --url &#39;https://yasen-alpha-phone-validator.p.rapidapi.com/validate?phone=%2B14155552671&#39; \<br>  --header &#39;X-RapidAPI-Key: YOUR_API_KEY&#39; \<br>  --header &#39;X-RapidAPI-Host: yasen-alpha-phone-validator.p.rapidapi.com&#39;</pre><p>No credit card required — 1,500 free requests per month.</p><h3>9. What You Learned</h3><ul><li>How to structure a production‑ready FastAPI project</li><li>How to add batch endpoints and parallel processing with asyncio</li><li>How to cache expensive operations with lru_cache</li><li>How to handle errors gracefully and return proper HTTP status codes</li><li>How to deploy on Render and monetize via RapidAPI</li></ul><h3>10. Next Steps</h3><ul><li>Add authentication (API keys)</li><li>Implement per‑user rate limiting</li><li>Add more endpoints (e.g., CSV history)</li></ul><p>If you found this tutorial useful, follow me for more “build &amp; deploy” articles — no fluff, just code that runs in production.</p><h3>Resources</h3><ul><li>🔗 Live API — Free Tier: <a href="https://rapidapi.com/emyasenc/api/yasen-alpha-phone-validator">RapidAPI Listing</a></li><li>🚀 Product Hunt Launch: <a href="https://www.producthunt.com/products/yasen-alpha-phone-validation-api">Vote Here</a></li><li>📦 GitHub Repository: <a href="https://github.com/emyasenc/phone-validation-api">github.com/emyasenc/phone-validation-api</a></li><li>📚 FastAPI Documentation: <a href="https://fastapi.tiangolo.com/">fastapi.tiangolo.com</a></li></ul><p><em>I built this API because I needed reliable phone validation for my own projects. Hope it helps you too.</em></p><p>Follow for more tutorials on building, deploying, and monetizing APIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b94fe2073e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Chatbots with Rasa: A Detailed Guide for Advanced Chatbots]]></title>
            <link>https://medium.com/@emyasenc/building-chatbots-with-rasa-a-detailed-guide-for-advanced-chatbots-e5126dc1de80?source=rss-1313f6dd7649------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5126dc1de80</guid>
            <category><![CDATA[chatbot-design]]></category>
            <category><![CDATA[chatbot-development]]></category>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[rasa-framework]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Emma Yasenchak]]></dc:creator>
            <pubDate>Sat, 14 Dec 2024 21:34:33 GMT</pubDate>
            <atom:updated>2024-12-14T21:34:33.907Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9ZTimCn5ZjCHjrzX7Y-EQ.png" /></figure><p>Building a chatbot can seem daunting, but with the <strong>Rasa framework</strong>, it’s easier than ever to create a powerful, intelligent conversational assistant. In this detailed tutorial, we’ll walk through the entire process of building an advanced chatbot with Rasa. You’ll learn how to integrate <strong>Natural Language Understanding (NLU)</strong>, design <strong>dialogue management</strong> flows, implement <strong>custom actions</strong>, and connect your chatbot to external APIs to increase its capabilities. By the end of this guide, you’ll be ready to build robust chatbots for real-world applications.</p><p><strong>Before diving into the tutorial, it’s important to understand what makes Rasa a great choice for building chatbots.</strong></p><h3>What is Rasa?</h3><p>Rasa is an open-source machine learning framework that specializes in building contextual and flexible AI chatbots. Unlike rule-based systems, Rasa is powered by <strong>machine learning (ML)</strong> techniques, making it highly capable of understanding complex language nuances and managing dynamic conversations.</p><p>Rasa provides two main components:</p><ol><li><strong>Rasa NLU (Natural Language Understanding)</strong>: Handles the process of interpreting the user’s input, detecting user intents, and extracting key information (entities).</li><li><strong>Rasa Core (Dialogue Management)</strong>: Determines the appropriate responses and actions based on conversation history and user input, enabling context-driven dialogue.</li></ol><p>Rasa employs various AI techniques to process natural language and provide intelligent responses. Some of these methods include:</p><ul><li><strong>Intent Classification</strong>: A supervised learning approach used to categorize user input into pre-defined intents (e.g., greeting, booking a flight, asking about weather).</li><li><strong>Entity Recognition</strong>: A named entity recognition (NER) method used to extract relevant information, like locations or dates, from the user input.</li><li><strong>Reinforcement Learning (RL)</strong>: Used in Rasa Core for dialogue management, RL helps the bot “learn” optimal conversation flows from training data by rewarding or punishing actions based on the outcomes of the dialogue.</li><li><strong>Transformer models</strong>: Rasa supports transformer-based models (e.g., BERT, GPT-3) for more accurate language understanding, handling complex utterances.</li></ul><p>Rasa integrates seamlessly with external APIs and platforms, allowing developers to build sophisticated, scalable, and customizable chatbots.</p><h3>Table of Contents:</h3><ol><li><a href="#1-introduction-to-rasa">Introduction to Rasa</a></li><li><a href="#2-setting-up-your-rasa-project">Setting Up Your Rasa Project</a></li><li><a href="#3-natural-language-understanding-nlu">Natural Language Understanding (NLU)</a></li><li><a href="#4-dialogue-management-and-stories">Dialogue Management and Stories</a></li><li><a href="#5-custom-actions">Custom Actions</a></li><li><a href="#6-integrating-external-apis">Integrating External APIs</a></li><li><a href="#7-running-your-chatbot">Running Your Chatbot</a></li><li><a href="#8-conclusion">Conclusion</a></li></ol><h3>1. Introduction to Rasa</h3><p><strong>Rasa</strong> is an open-source conversational AI framework designed to make the process of creating chatbots and virtual assistants easier and more efficient. What makes Rasa powerful is its reliance on <strong>machine learning models</strong> for <strong>natural language understanding (NLU)</strong> and <strong>dialogue management</strong>, which gives it the flexibility to handle varied conversations.</p><h3>Key Features of Rasa:</h3><ul><li><strong>NLU</strong>: Rasa’s NLU pipeline uses various algorithms, including <strong>tokenizers</strong>, <strong>intent classification</strong>, and <strong>entity extraction</strong>, to understand user input.</li><li><strong>Dialogue Management</strong>: Rasa allows you to handle complex multi-turn conversations and provides tools to define <strong>conversation states</strong>, which help the bot keep track of interactions.</li><li><strong>Custom Actions</strong>: Rasa offers the ability to define custom Python actions that enable bots to interact with databases, access external APIs, or handle dynamic responses.</li><li><strong>Open Source and Extensible</strong>: Rasa’s flexibility makes it an excellent tool for integrating machine learning models, external services, and third-party APIs.</li></ul><p>In this tutorial, we will walk you through the process of building an advanced chatbot with Rasa, using its machine learning techniques to create an intelligent assistant that responds to user inputs contextually.</p><h3>2. Setting Up Your Rasa Project</h3><p>Before diving into Rasa’s core capabilities, you first need to install the framework and set up your project.</p><h3>Install Rasa</h3><p>First, you need to install Rasa. You can install it via pip:</p><pre>pip install rasa</pre><h3>Create a New Rasa Project</h3><p>After installing Rasa, create a new project:</p><pre>rasa init</pre><p>This command initializes a new Rasa project, setting up the necessary directories and sample files like domain.yml, nlu.yml, and stories.yml.</p><h3>Project Structure</h3><p>A basic Rasa project includes the following folders and files:</p><ul><li><strong>nlu.yml</strong>: Contains the NLU training data for detecting intents and extracting entities.</li><li><strong>stories.yml</strong>: Defines user-bot interactions (the flow of conversation).</li><li><strong>domain.yml</strong>: This file specifies how the bot should respond in various situations.</li><li><strong>actions.py</strong>: Where custom actions are implemented (e.g., calling external APIs).</li><li><strong>config.yml</strong>: Contains settings to configure your Rasa pipeline (the sequence of operations for NLU and dialogue management).</li></ul><p>Once your project is set up, you’re ready to start building your chatbot!</p><h3>3. Natural Language Understanding (NLU)</h3><p>Rasa uses machine learning to handle <strong>Natural Language Understanding (NLU)</strong>, which involves two major tasks:</p><ul><li><strong>Intent recognition</strong>: Determining the purpose of the user’s message.</li><li><strong>Entity extraction</strong>: Identifying important pieces of data in the user’s message (e.g., dates, locations, numbers).</li></ul><h3>Define Intents and Entities</h3><p>In Rasa, intents and entities are defined in the nlu.yml file. For example:</p><pre>nlu:<br>  - intent: greet<br>    examples: |<br>      - Hello!<br>      - Hi!<br>      - Good morning!<br>  <br>  - intent: book_flight<br>    examples: |<br>      - I need a flight from New York to Boston<br>      - Book a flight for tomorrow</pre><h3>Training the NLU Model</h3><p>You can train the NLU model to understand these intents and entities by running:</p><pre>rasa train nlu</pre><p>This process uses your defined examples to train a machine learning model, so the bot will be able to classify the intent and recognize the entities from any new user input.</p><h3>4. Dialogue Management and Stories</h3><p><strong>Rasa Core</strong> is responsible for managing the conversation and deciding what action to take next. It learns from <strong>stories</strong>, which define how the conversation should flow in different scenarios.</p><h3>Define Stories</h3><p>In the stories.yml file, you describe various possible user-bot interactions as &quot;stories.&quot; Here’s an example:</p><pre>stories:<br>  - story: greet and book flight<br>    steps:<br>      - intent: greet<br>      - action: utter_greet<br>      - intent: book_flight<br>      - action: action_book_flight</pre><h3>Responses and Actions</h3><p>In domain.yml, you define how the bot will respond to user inputs. For example:</p><pre>responses:<br>  utter_greet:<br>    - text: &quot;Hello! How can I assist you today?&quot;<br><br>actions:<br>  - action_book_flight</pre><h3>Dialogue Policies</h3><p>Rasa allows you to configure dialogue policies using the <strong>config.yml</strong> file, where you define the rules and machine learning models Rasa will use to predict the next action based on the conversation history.</p><h3>5. Custom Actions</h3><p>Rasa allows you to extend the bot’s capabilities by defining <strong>custom actions</strong> in the actions.py file. This is where you can integrate advanced features, such as querying a database or calling an external API.</p><p>Here’s an example of a custom action that books a flight by interacting with an external API:</p><pre>import requests<br>from rasa_sdk import Action<br>from rasa_sdk.executor import CollectingDispatcher<br><br>class ActionBookFlight(Action):<br>    <br>    def name(self):<br>        return &quot;action_book_flight&quot;<br>    <br>    def run(self, dispatcher, tracker, domain):<br>        destination = next(tracker.get_latest_entity_values(&quot;location&quot;), None)<br>        response = requests.post(&quot;https://api.example.com/book_flight&quot;, data={&quot;destination&quot;: destination})<br>        flight_confirmation = response.json()<br>        <br>        dispatcher.utter_message(f&quot;Your flight to {destination} has been booked. Confirmation number: {flight_confirmation[&#39;confirmation_code&#39;]}&quot;)<br>        return []</pre><h3>Registering Custom Actions</h3><p>You must also register your custom actions in the domain.yml file:</p><pre>actions:<br>  - action_book_flight</pre><h3>6. Integrating External APIs</h3><p>Your Rasa bot can become even more powerful by integrating with external APIs to provide dynamic data and services, such as weather, product recommendations, or flight bookings.</p><p>For example, you might integrate a weather API to respond with current weather information based on the user’s location:</p><pre>import requests<br>from rasa_sdk import Action<br>from rasa_sdk.executor import CollectingDispatcher<br><br>class ActionGetWeather(Action):<br>    <br>    def name(self):<br>        return &quot;action_get_weather&quot;<br>    <br>    def run(self, dispatcher, tracker, domain):<br>        location = next(tracker.get_latest_entity_values(&quot;location&quot;), None)<br>        response = requests.get(f&quot;https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&amp;q={location}&quot;)<br>        weather = response.json()<br>        dispatcher.utter_message(f&quot;The weather in {location} is {weather[&#39;current&#39;][&#39;temp_c&#39;]}°C.&quot;)<br>        return []</pre><h3>7. Running Your Chatbot</h3><p>Once everything is configured, you’re ready to run the Rasa chatbot.</p><p>To start your bot server, use:</p><pre>rasa run</pre><p>For interactive testing, launch the Rasa shell:</p><pre>rasa shell</pre><p>Test your bot by typing messages directly into the terminal.</p><h3>8. Conclusion</h3><p>In this guide, we’ve covered the entire process of building a chatbot with the <strong>Rasa framework</strong>, including:</p><ul><li>Setting up your project and installing Rasa</li><li>Training the bot to understand <strong>natural language</strong> using <strong>NLU</strong></li><li>Managing conversations with <strong>dialogue management</strong> and <strong>stories</strong></li><li>Enhancing chatbot capabilities with <strong>custom actions</strong> and integrating external APIs</li></ul><p>By leveraging machine learning, particularly intent recognition, entity extraction, and reinforcement learning, Rasa allows you to create chatbots that handle dynamic, intelligent conversations. Whether you’re building an assistant for customer support, booking systems, or other interactive applications, Rasa is a powerful framework that helps you scale and customize your chatbot effortlessly.</p><p>Happy coding, and enjoy building with Rasa!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5126dc1de80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Large Datasets and Big Data Tools: A Guide to PySpark]]></title>
            <link>https://medium.com/@emyasenc/working-with-large-datasets-and-big-data-tools-a-guide-to-pyspark-e6ab85a6f52c?source=rss-1313f6dd7649------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6ab85a6f52c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[scalable-machine-learning]]></category>
            <dc:creator><![CDATA[Emma Yasenchak]]></dc:creator>
            <pubDate>Sat, 14 Dec 2024 21:18:52 GMT</pubDate>
            <atom:updated>2026-06-22T21:36:43.715Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmMIAq54IBRSqY1IPODMdg.png" /></figure><p>Handling large datasets efficiently is one of the biggest challenges in data science and analytics. Whether it’s terabytes of logs, sensor data, or user interactions, traditional tools like pandas can hit performance bottlenecks when the data doesn’t fit into memory. This is where distributed data processing frameworks like <strong>Apache Spark</strong> come into play, allowing data science workflows to scale across multiple machines or clusters.</p><p>In this blog post, we’ll dive into <strong>PySpark</strong>, the Python API for Apache Spark, to demonstrate how to work with large datasets, perform parallel processing, and use Spark’s built-in capabilities for scalable machine learning. We’ll cover fundamental concepts, basic operations, and walk you through real-world examples to help you get up to speed.</p><h3>What is PySpark?</h3><p><strong>PySpark</strong> is the Python API for <strong>Apache Spark</strong>, a powerful, open-source distributed computing framework used for big data processing. Spark provides an interface for programming entire clusters with implicit data parallelism and fault tolerance. While Spark is traditionally written in <strong>Scala</strong>, PySpark allows data scientists and analysts who are familiar with Python to harness its distributed computing power.</p><p>PySpark operates with <strong>Resilient Distributed Datasets (RDDs)</strong> or <strong>Data Frames</strong> (which are more user-friendly and optimized for large-scale data processing). With PySpark, you can distribute your data processing tasks over a cluster of machines, thus significantly speeding up the computation.</p><h3>Setting up PySpark</h3><p>Before we start, let’s ensure we have the necessary tools and libraries set up. You’ll need to install PySpark on your local machine or a cluster.</p><h3>Installing PySpark</h3><p>Install PySpark with pip:</p><pre>pip install pyspark</pre><p>If you’re planning to work with a cluster of machines, ensure you’ve set up Apache Spark in your environment. The local machine installation is also sufficient for many tasks and tests.</p><p>Once installed, you’ll need to initialize the Spark session. This is the entry point for working with Spark, providing a unified interface to interact with Spark’s capabilities.</p><h3>Starting a Spark Session</h3><pre>from pyspark.sql import SparkSession<br><br># Initialize Spark session<br>spark = SparkSession.builder \<br>    .appName(&#39;Large Dataset Example&#39;) \<br>    .getOrCreate()</pre><h3>Reading Large Datasets into PySpark</h3><h3>Working with CSV Files</h3><p>In Spark, you can read data from many formats like CSV, JSON, Parquet, and more. Below is an example of loading a large CSV file and showing a preview of the first few rows.</p><pre># Load CSV data into a Spark DataFrame<br>df = spark.read.csv(&#39;path/to/large-dataset.csv&#39;, header=True, inferSchema=True)<br><br># Show the first few rows of the DataFrame<br>df.show(5)</pre><p>With <strong>PySpark DataFrame</strong>, you get parallel processing by default, where Spark automatically handles breaking up tasks, so the operations are scalable.</p><h3>Reading from Multiple Files</h3><p>PySpark allows you to process multiple files simultaneously. This is especially useful when dealing with datasets stored across different locations. You can also provide file paths with wildcards.</p><pre># Read multiple files using wildcards<br>df = spark.read.csv(&#39;path/to/dataset/*.csv&#39;, header=True, inferSchema=True)<br>df.show(5)</pre><h3>Performing Operations on Large Datasets</h3><p>Once the dataset is loaded, you can use standard DataFrame operations like filtering, grouping, and aggregation, similar to pandas, but <strong>distributed across nodes</strong>.</p><h3>Filter Data</h3><pre># Filter rows where the value of the column &#39;age&#39; is greater than 30<br>df_filtered = df.filter(df[&#39;age&#39;] &gt; 30)<br>df_filtered.show(5)</pre><h3>Group By and Aggregate</h3><pre># Group by &#39;category&#39; column and get the average &#39;value&#39; for each group<br>df_grouped = df.groupBy(&#39;category&#39;).agg({&#39;value&#39;: &#39;avg&#39;})<br>df_grouped.show(5)</pre><h3>Join Data Frames</h3><p>PySpark allows you to join multiple Data Frames efficiently, which can be a huge advantage when working with big data.</p><pre># Load another DataFrame<br>df2 = spark.read.csv(&#39;path/to/other-dataset.csv&#39;, header=True, inferSchema=True)<br><br># Perform a join on &#39;id&#39; column<br>df_joined = df.join(df2, on=&#39;id&#39;, how=&#39;inner&#39;)<br>df_joined.show(5)</pre><h3>Using PySpark for Scalable Machine Learning</h3><p>PySpark comes with a <strong>MLlib</strong> library for scalable machine learning. Here, we’ll walk through an example of training a logistic regression model for classification on a large dataset.</p><h3>Preparing the Data</h3><p>Before training a machine learning model, we often need to transform the raw data. PySpark includes functionality to <strong>assemble features</strong>, <strong>encode labels</strong>, and handle missing values.</p><pre>from pyspark.ml.feature import VectorAssembler<br>from pyspark.ml.classification import LogisticRegression<br>from pyspark.ml import Pipeline<br><br># Select feature columns and label column<br>feature_columns = [&#39;feature1&#39;, &#39;feature2&#39;, &#39;feature3&#39;]<br>assembler = VectorAssembler(inputCols=feature_columns, outputCol=&#39;features&#39;)<br>df_transformed = assembler.transform(df)<br><br># Prepare the data for ML (split into training and test sets)<br>train_data, test_data = df_transformed.randomSplit([0.8, 0.2], seed=1234)</pre><h3>Training the Model</h3><p>We can now use MLlib to train a logistic regression model on this data. This model can be run across a cluster of machines, so it’s scalable to large datasets.</p><pre># Instantiate and train the Logistic Regression model<br>lr = LogisticRegression(featuresCol=&#39;features&#39;, labelCol=&#39;label&#39;)<br>model = lr.fit(train_data)<br><br># Make predictions on test data<br>predictions = model.transform(test_data)<br>predictions.show(5)</pre><h3>Optimizing and Tuning PySpark</h3><p>When working with large datasets, optimization can make a big difference in performance. Here are a few tips to optimize PySpark tasks:</p><h3>Cache Data Frames</h3><p>When you need to reuse a DataFrame multiple times, caching it can save computation time by avoiding recalculating the same result.</p><pre>df_cache = df.cache()</pre><h3>Avoid Shuffling Data</h3><p>Shuffling is an expensive operation in Spark, so minimizing shuffle operations when processing data is critical. Try to use <strong>partitioning</strong> and <strong>broadcast joins</strong> when possible.</p><pre># Example of a broadcast join to minimize shuffling<br>from pyspark.sql.functions import broadcast<br>df_joined = df.join(broadcast(df2), on=&#39;id&#39;, how=&#39;inner&#39;)</pre><h3>Use the Efficient Parquet Format</h3><p>While CSV is easy to use, <strong>Parquet</strong> is a columnar format designed for efficient querying and can greatly speed up data processing tasks in Spark.</p><pre># Read and write data in Parquet format<br>df.write.parquet(&#39;path/to/output&#39;)<br>df_parquet = spark.read.parquet(&#39;path/to/output&#39;)</pre><h3>Conclusion</h3><p>In this tutorial, we’ve explored how to efficiently work with large datasets using PySpark. We covered reading datasets into Spark, processing data in parallel, and performing scalable machine learning tasks. PySpark provides the tools necessary to take on datasets that are too large for traditional tools like pandas, and with the distributed power of Spark, these operations can be spread across many machines, allowing for faster and more efficient analysis.</p><h3>🚀 From PySpark to Production API</h3><p>Working with big data is one thing — deploying it as a production API is another.</p><p>If you’re building data pipelines and want to serve predictions via FastAPI, you’ll run into the same problems I did: error handling, rate limiting, and consistent JSON responses.</p><p>I built a library that solves it:</p><ul><li>✅ raise_400() to raise_500() helper functions</li><li>✅ Global exception handler (catches everything)</li><li>✅ Validation error formatter (field-level details)</li><li>✅ Rate limiting built-in</li><li>✅ Used in production APIs on RapidAPI (8.6 popularity)</li></ul><p>Time saved: 2–3 hours per project</p><p>👉 <a href="https://emyasenc.gumroad.com/l/fastapi-error-handler?_gl=1*slonqs*_ga*ODkwNjU0MjU2LjE3ODIxNTg1Nzk.*_ga_6LJN6D94N6*czE3ODIxNTg1NzgkbzEkZzEkdDE3ODIxNTg3NDEkajYwJGwwJGgw">FastAPI Error Handler Library — $39</a></p><p>Buy once. Use forever. Commercial license included.</p><h3>📦 Resources</h3><ul><li>📘 <a href="https://emyasenc.gumroad.com/l/fastapi-error-handler?_gl=1*slonqs*_ga*ODkwNjU0MjU2LjE3ODIxNTg1Nzk.*_ga_6LJN6D94N6*czE3ODIxNTg1NzgkbzEkZzEkdDE3ODIxNTg3NDEkajYwJGwwJGgw">FastAPI Error Handler Library — $39</a></li><li>📞 <a href="https://rapidapi.com/emyasenc/api/yasen-alpha-phone-validator">Phone Validation API — Free Tier</a></li><li>🐙 <a href="https://github.com/emyasenc">GitHub — emyasenc</a></li></ul><h3>Key takeaways:</h3><ul><li>PySpark helps you handle large datasets using <strong>distributed processing</strong>.</li><li>The <strong>Spark DataFrame</strong> API is easy to use and automatically distributes your computation.</li><li>You can perform powerful machine learning tasks at scale using <strong>MLlib</strong>.</li><li>Optimization techniques like caching and using Parquet files are key for improving performance.</li></ul><p>By mastering tools like PySpark, data scientists can overcome the challenges of working with massive datasets, opening the door to more sophisticated, large-scale data analysis and machine learning workflows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6ab85a6f52c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Scraping for Beginners: Building Datasets with Python]]></title>
            <link>https://medium.com/@emyasenc/web-scraping-for-beginners-building-datasets-with-python-a916cb46929d?source=rss-1313f6dd7649------2</link>
            <guid isPermaLink="false">https://medium.com/p/a916cb46929d</guid>
            <category><![CDATA[scrapy]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[tutorial-for-beginners]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <dc:creator><![CDATA[Emma Yasenchak]]></dc:creator>
            <pubDate>Sat, 14 Dec 2024 21:02:50 GMT</pubDate>
            <atom:updated>2024-12-14T21:03:51.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48nx3iIsbzzs75LXFKSy7w.png" /></figure><p>Web scraping is a powerful technique to collect data from websites when APIs or pre-built datasets aren’t available. This skill is indispensable for data science, machine learning, and analysis projects.</p><p>In this guide, we’ll explore how to scrape data using Python libraries like <strong>Beautiful Soup</strong> and <strong>Scrapy</strong>. You’ll learn practical techniques to create your own datasets, along with essential ethical considerations and best practices.</p><h3>What Is Web Scraping?</h3><p><strong>Web scraping</strong> refers to programmatically extracting data from web pages. Use cases include:</p><ul><li><strong>Custom Datasets</strong>: Collect information from niche websites not providing easy downloads.</li><li><strong>Real-Time Updates</strong>: Fetch changing data such as sports scores, product prices, or social trends.</li><li><strong>Automation</strong>: Save time by automating repetitive data-gathering tasks.</li></ul><h3>Tools Needed</h3><p>We’ll use two Python tools in this tutorial:</p><ol><li><strong>BeautifulSoup</strong>: Simplifies parsing HTML.</li><li><strong>Scrapy</strong>: A framework tailored for scalable, efficient scraping projects.</li></ol><h4>Install the Libraries:</h4><p>Run the following commands in your terminal or IDE:</p><pre>pip install beautifulsoup4 requests scrapy pandas</pre><p>Ensure Python version 3.x is installed.</p><h3>Ethical Guidelines for Scraping</h3><p>Before scraping, always ensure compliance with the following rules:</p><ol><li><strong>Check Website’s Terms of Service</strong>: Many websites discourage or restrict web scraping.</li><li><strong>Respect Robots.txt</strong>: Use http://example.com/robots.txt to understand scraping permissions.</li><li><strong>Rate Limiting</strong>: Avoid overloading websites by adding delays between requests.</li><li><strong>Avoid Sensitive Data</strong>: Respect user privacy and legal regulations like GDPR.</li></ol><h3>Part 1: Scraping with BeautifulSoup</h3><p>Let’s scrape quotes, authors, and tags from <a href="http://quotes.toscrape.com/">Quotes to Scrape</a>, a beginner-friendly practice website.</p><h4>Step 1: Import Required Libraries</h4><pre>import requests<br>from bs4 import BeautifulSoup<br>import pandas as pd</pre><p>These modules handle HTTP requests, HTML parsing, and exporting data.</p><h4>Step 2: Send an HTTP GET Request</h4><p>Fetch the webpage’s HTML content using requests:</p><pre>url = &quot;http://quotes.toscrape.com/&quot;<br>response = requests.get(url)<br><br>if response.status_code == 200:<br>    print(&quot;Successfully fetched the page!&quot;)<br>else:<br>    print(f&quot;Failed to fetch the page. Status code: {response.status_code}&quot;)</pre><h4>Step 3: Parse the HTML Content</h4><p>Load the fetched content into BeautifulSoup:</p><pre>soup = BeautifulSoup(response.text, &quot;html.parser&quot;)</pre><p>BeautifulSoup transforms raw HTML into an easy-to-navigate structure.</p><h4>Step 4: Extract Quotes, Authors, and Tags</h4><p>Locate elements with CSS selectors and iterate to extract meaningful data:</p><pre>quotes = soup.select(&quot;.quote&quot;)<br>data = []</pre><pre>for quote in quotes:<br>    text = quote.select_one(&quot;.text&quot;).get_text(strip=True)<br>    author = quote.select_one(&quot;.author&quot;).get_text(strip=True)<br>    tags = [tag.get_text(strip=True) for tag in quote.select(&quot;.tags .tag&quot;)]</pre><pre>    data.append({<br>        &quot;Quote&quot;: text,<br>        &quot;Author&quot;: author,<br>        &quot;Tags&quot;: &quot;, &quot;.join(tags)<br>    })</pre><p>Explanation:</p><ul><li>.select(): Finds all HTML elements matching the selector.</li><li>.select_one(): Extracts the first matching element.</li><li>.get_text(strip=True): Fetches element text without leading/trailing whitespace.</li></ul><h4>Step 5: Save Data to a CSV File</h4><p>Finally, store the scraped data in a CSV using Pandas:</p><pre>df = pd.DataFrame(data)<br>df.to_csv(&quot;quotes.csv&quot;, index=False)<br>print(&quot;Data saved to quotes.csv!&quot;)</pre><p>Your data is now saved for further analysis or modeling!</p><h3>Part 2: Scalable Scraping with Scrapy</h3><p>While BeautifulSoup works well for simpler tasks, Scrapy excels at large-scale or multi-page scraping. Let’s scrape all quotes across multiple pages of the same website.</p><h4>Step 1: Set Up a Scrapy Project</h4><p>In your terminal, create a new Scrapy project:</p><pre>scrapy startproject quote_scraper</pre><p>This command creates a folder structure, including settings and scripts, to streamline your scraping tasks.</p><p>Navigate into the project:</p><pre>cd quote_scraper</pre><h4>Step 2: Write a Spider</h4><p>A <strong>Spider</strong> in Scrapy defines how to navigate the website and extract information. Create spiders/quotes_spider.py and add the following:</p><pre>import scrapy<br><br>class QuotesSpider(scrapy.Spider):<br>    name = &quot;quotes&quot;<br>    start_urls = [&quot;http://quotes.toscrape.com/&quot;]<br><br>def parse(self, response):<br>        for quote in response.css(&quot;.quote&quot;):<br>            yield {<br>                &quot;Quote&quot;: quote.css(&quot;.text::text&quot;).get(),<br>                &quot;Author&quot;: quote.css(&quot;.author::text&quot;).get(),<br>                &quot;Tags&quot;: quote.css(&quot;.tags .tag::text&quot;).getall(),<br>            }<br><br>        # Follow pagination links<br>        next_page = response.css(&quot;li.next a::attr(href)&quot;).get()<br>        if next_page:<br>            yield response.follow(next_page, self.parse)</pre><p>Explanation:</p><ul><li><strong>response.css()</strong>: Uses CSS selectors to locate elements.</li><li><strong>.get() and </strong><strong>.getall()</strong>: Extracts single/multiple elements respectively.</li><li><strong>response.follow()</strong>: Automates navigation to the next page.</li></ul><h4>Step 3: Run the Spider</h4><p>Run the Spider in your terminal to scrape all pages and save the data:</p><pre>scrapy crawl quotes -o quotes.json</pre><p>The data is saved in quotes.json in JSON format.</p><h4>Step 4: Analyze the Scraped Data</h4><p>Use Pandas to load and analyze the JSON data:</p><pre>import pandas as pd<br><br>data = pd.read_json(&quot;quotes.json&quot;)<br>print(data.head())</pre><h3>Best Practices for Web Scraping</h3><p>Follow these guidelines to ensure successful, ethical, and efficient scraping:</p><ol><li><strong>Start Small</strong>: Use BeautifulSoup for single-page scraping.</li><li><strong>Scale Smartly</strong>: Use Scrapy for pagination or dynamic websites.</li><li><strong>Delay Requests</strong>: Introduce delays with Scrapy’s DOWNLOAD_DELAY setting.</li><li><strong>Handle Errors</strong>: Log failed requests and handle missing fields.</li><li><strong>Test Regularly</strong>: Websites often change, breaking older scrapers. Automate tests if possible.</li></ol><h3>Conclusion</h3><p>With Python and its versatile libraries, web scraping becomes a powerful tool for collecting and customizing datasets. We:</p><ul><li>Scraped single pages with BeautifulSoup.</li><li>Built scalable scrapers with Scrapy.</li></ul><p>You’re now ready to apply these techniques in your data projects! Test this guide on practice sites or real-world applications, and enjoy the rewarding process of crafting your own datasets.</p><p>Have questions or ideas? Let me know in the comments below!</p><p>Happy scraping! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a916cb46929d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Machine Learning Models with Flask, FastAPI, or Streamlit: An In-Depth Guide]]></title>
            <link>https://medium.com/@emyasenc/deploying-machine-learning-models-with-flask-fastapi-or-streamlit-an-in-depth-guide-30c2e1f2ee44?source=rss-1313f6dd7649------2</link>
            <guid isPermaLink="false">https://medium.com/p/30c2e1f2ee44</guid>
            <category><![CDATA[real-time-predictions]]></category>
            <category><![CDATA[ml-model-deployment]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Emma Yasenchak]]></dc:creator>
            <pubDate>Fri, 29 Nov 2024 15:45:47 GMT</pubDate>
            <atom:updated>2026-06-22T21:22:52.073Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WaKVue0zYHUuL5QCMREiSw.png" /></figure><p>Deploying machine learning models enables your applications to make real-time predictions and decisions. This tutorial shows how to deploy machine learning models with <strong>Flask</strong>, <strong>FastAPI</strong>, and <strong>Streamlit</strong> using unique and realistic examples. Each framework is useful for different scenarios: Flask and FastAPI are well-suited for backend applications, while Streamlit is excellent for creating interactive user interfaces.</p><h3>Step 1: Prepare Your Machine Learning Model</h3><p>Before deploying, we need a trained model. In this example, let’s use a <strong>predictive maintenance model</strong> for a manufacturing company. The goal is to predict when machinery will break down so that preventative maintenance can be performed.</p><p>Imagine a company has sensor data from machines (e.g., temperature, vibration, pressure, etc.). We’ll use this data to predict when a machine is likely to fail, and deploy the model using Flask, FastAPI, and Streamlit.</p><p>Here’s how you can train a simple predictive maintenance model using scikit-learn and save it for deployment.</p><h3>Train the Predictive Maintenance Model</h3><pre>import pickle<br>import pandas as pd<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.model_selection import train_test_split<br><br># Load some sample data (simulated maintenance data)<br>data = pd.read_csv(&quot;machine_data.csv&quot;)<br><br># Example features: sensor readings for a machine (e.g., temperature, vibration, pressure)<br>X = data[[&#39;temperature&#39;, &#39;vibration&#39;, &#39;pressure&#39;]]<br>y = data[&#39;failure&#39;]  # Binary: 1 = failure, 0 = no failure<br><br># Split the data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># Train the model<br>model = RandomForestClassifier()<br>model.fit(X_train, y_train)<br><br># Save the trained model<br>with open(&quot;predictive_maintenance_model.pkl&quot;, &quot;wb&quot;) as f:<br>    pickle.dump(model, f)</pre><h3>Step 2: Deploy with Flask</h3><p>Flask is a lightweight framework for building web APIs. It’s perfect for serving a machine learning model through an API endpoint.</p><h3>Install Flask</h3><pre># Install using your CLI<br>pip install flask </pre><h3>Create the Flask Application</h3><p>Here’s how to deploy the predictive maintenance model using Flask:</p><pre>from flask import Flask, request, jsonify<br>import pickle<br>import numpy as np<br><br># Load the model<br>with open(&quot;predictive_maintenance_model.pkl&quot;, &quot;rb&quot;) as f:<br>    model = pickle.load(f)<br><br># Initialize Flask app<br>app = Flask(__name__)<br>@app.route(&quot;/predict&quot;, methods=[&quot;POST&quot;])<br>def predict():<br>    try:<br>        # Parse the input data (sensor readings)<br>        data = request.get_json()<br>        features = np.array(data[&quot;features&quot;]).reshape(1, -1)<br><br>        # Make predictions<br>        prediction = model.predict(features)<br>        result = &quot;Failure predicted&quot; if prediction[0] == 1 else &quot;No failure predicted&quot;<br>        return jsonify({&quot;prediction&quot;: result})<br>    except Exception as e:<br>        return jsonify({&quot;error&quot;: str(e)}), 400<br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(debug=True)</pre><h3>Testing the Flask API</h3><p>Save the file as app.py and run it:</p><pre>python app.py</pre><p>Send a POST request to http://127.0.0.1:5000/predict with the machine sensor data:</p><pre>curl -X POST -H &quot;Content-Type: application/json&quot; \<br>-d &#39;{&quot;features&quot;: [75.5, 0.7, 25.4]}&#39; \<br>http://127.0.0.1:5000/predict</pre><p>This will output:</p><pre>{<br>  &quot;prediction&quot;: &quot;No failure predicted&quot;<br>}</pre><h3>Step 3: Deploy with FastAPI</h3><p>FastAPI is another great option for serving machine learning models. It’s fast, has built-in validation, and auto-generates documentation.</p><h3>Install FastAPI and Uvicorn</h3><pre>pip install fastapi uvicorn</pre><h3>Create the FastAPI Application</h3><p>Here’s how to deploy the predictive maintenance model using FastAPI:</p><pre>from fastapi import FastAPI, HTTPException<br>from pydantic import BaseModel<br>import pickle<br>import numpy as np<br><br># Load the model<br>with open(&quot;predictive_maintenance_model.pkl&quot;, &quot;rb&quot;) as f:<br>    model = pickle.load(f)<br><br># Initialize FastAPI app<br>app = FastAPI()<br><br># Define input data schema<br>class Features(BaseModel):<br>    features: list[float]<br><br>@app.post(&quot;/predict&quot;)<br>def predict(features: Features):<br>    try:<br>        # Convert features to a numpy array<br>        data = np.array(features.features).reshape(1, -1)<br><br>        # Make predictions<br>        prediction = model.predict(data)<br>        result = &quot;Failure predicted&quot; if prediction[0] == 1 else &quot;No failure predicted&quot;<br>        return {&quot;prediction&quot;: result}<br>    except Exception as e:<br>        raise HTTPException(status_code=400, detail=str(e))</pre><h3>Testing and Documentation</h3><p>Save as main.py and run it:</p><pre>uvicorn main:app --reload</pre><p>Access the <strong>Swagger UI</strong> at http://127.0.0.1:8000/docs to test the /predict endpoint interactively.</p><h3>Step 4: Deploy with Streamlit</h3><p>Streamlit is ideal for creating interactive apps for non-technical users. Let’s create an easy-to-use dashboard where users can input sensor readings and get predictions.</p><h3>Install Streamlit</h3><pre>pip install streamlit</pre><h3>Create the Streamlit Application</h3><p>Here’s how to create an interactive user interface for the predictive maintenance model using Streamlit:</p><pre>import streamlit as st<br>import pickle<br>import numpy as np<br><br># Load the model<br>with open(&quot;predictive_maintenance_model.pkl&quot;, &quot;rb&quot;) as f:<br>    model = pickle.load(f)<br><br># Streamlit app<br>st.title(&quot;Predictive Maintenance Dashboard&quot;)<br>st.write(&quot;Enter the machine sensor readings to predict failures:&quot;)<br><br># Input fields for sensor data<br>temperature = st.number_input(&quot;Temperature&quot;, value=75.5)<br>vibration = st.number_input(&quot;Vibration&quot;, value=0.7)<br>pressure = st.number_input(&quot;Pressure&quot;, value=25.4)<br><br># Make prediction when button is clicked<br>if st.button(&quot;Predict&quot;):<br>    features = np.array([temperature, vibration, pressure]).reshape(1, -1)<br>    prediction = model.predict(features)<br>    result = &quot;Failure predicted&quot; if prediction[0] == 1 else &quot;No failure predicted&quot;<br>    st.write(result)</pre><h3>Running the Streamlit App</h3><p>Save as app.py and run it:</p><pre>streamlit run app.py</pre><p>This will launch an interactive web app where users can input sensor data and see predictions in real time.</p><h3>Step 5: Real-World Considerations</h3><p><strong>Flask vs FastAPI vs Streamlit</strong>:</p><ul><li><strong>Flask</strong>: Best for backend APIs that will be consumed by other services or systems.</li><li><strong>FastAPI</strong>: Ideal for high-performance APIs with automatic validation and documentation.</li><li><strong>Streamlit</strong>: Perfect for quick interactive web applications and dashboards where stakeholders can visualize data and predictions.</li><li><strong>Model Retraining</strong>: In production, periodically retrain models with fresh data to ensure predictions remain accurate.</li><li><strong>Security</strong>: For Flask and FastAPI applications, add authentication mechanisms (e.g., OAuth, API keys) to protect endpoints.</li><li><strong>Model Versioning</strong>: Use version control for your models and deploy new versions seamlessly without disrupting existing services.</li></ul><h3>Validating User Input in Production</h3><p>When you deploy an ML app that collects user phone numbers — for signup, SMS alerts, or fraud detection — you’ll eventually need to validate them. Invalid numbers cause failed deliveries and poor user experience.</p><p>Here’s a simple solution I built for my own projects.</p><p><strong>What it does</strong><br>- Checks if a phone number is real (200+ countries)<br>- Returns carrier, timezone, and location<br>- Supports batch validation (up to 100 numbers at once)</p><p><strong>Pricing</strong><br>- <em>Free:</em> 1,500 requests/month (no credit card)<br>- <em>Pro:</em> $19 for 15,000 requests<br>- <em>Ultra:</em> $49 for 75,000 requests</p><p><strong>Try it</strong><br>👉 <a href="https://rapidapi.com/emyasenc/api/yasen-alpha-phone-validator">[Phone Validation API — Free Tier]</a></p><p>Open source. No hype.</p><p><em>I needed this for my own deployed apps. Thought others might find it useful too.</em></p><h3>🛠️ Stop Writing Error Handlers From Scratch</h3><p>If you’re building FastAPI apps, you’re probably tired of writing the same error responses over and over.</p><p>I built a library that handles it all:<br>- ✅ `raise_400()` to `raise_500()` helpers<br>- ✅ Global exception handler<br>- ✅ Validation error formatting<br>- ✅ Rate limiting</p><p><em>Used in my production APIs on RapidAPI (8.6 popularity).</em></p><p>👉 <a href="https://emyasenc.gumroad.com/l/fastapi-error-handler?_gl=1*slonqs*_ga*ODkwNjU0MjU2LjE3ODIxNTg1Nzk.*_ga_6LJN6D94N6*czE3ODIxNTg1NzgkbzEkZzEkdDE3ODIxNTg3NDEkajYwJGwwJGgw">[FastAPI Error Handler Library — $39]</a></p><p>Saves 2–3 hours per project. Commercial license included.</p><h3>Conclusion</h3><p>By deploying machine learning models using frameworks like Flask, FastAPI, and Streamlit, you enable users to interact with your models in real-time. Flask and FastAPI are perfect for backend services, while Streamlit provides an easy interface for non-technical users. By choosing the appropriate tool, you can make your machine learning models accessible and impactful in real-world applications like predictive maintenance in manufacturing.</p><h3>📦 Resources</h3><p>- 📞 <a href="https://rapidapi.com/emyasenc/api/yasen-alpha-phone-validator">[Phone Validation API — Free Tier]</a><br>- 📘 <a href="https://emyasenc.gumroad.com/l/fastapi-error-handler?_gl=1*slonqs*_ga*ODkwNjU0MjU2LjE3ODIxNTg1Nzk.*_ga_6LJN6D94N6*czE3ODIxNTg1NzgkbzEkZzEkdDE3ODIxNTg3NDEkajYwJGwwJGgw">[FastAPI Error Handler Library — $39]</a><br>- 🐙 <a href="https://github.com/emyasenc">[GitHub — emyasenc]</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30c2e1f2ee44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Choose the Right Machine Learning Model for Your Project]]></title>
            <link>https://medium.com/@emyasenc/how-to-choose-the-right-machine-learning-model-for-your-project-15ba97ec9503?source=rss-1313f6dd7649------2</link>
            <guid isPermaLink="false">https://medium.com/p/15ba97ec9503</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[real-world-application]]></category>
            <category><![CDATA[model-selection]]></category>
            <category><![CDATA[model-comparison]]></category>
            <category><![CDATA[beginners-tips]]></category>
            <dc:creator><![CDATA[Emma Yasenchak]]></dc:creator>
            <pubDate>Fri, 29 Nov 2024 15:25:32 GMT</pubDate>
            <atom:updated>2024-11-29T15:25:32.705Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zoV-NU_zrhGgjR_rOL3S4A.png" /></figure><p>Choosing the right machine learning (ML) model can feel overwhelming, especially for beginners. With so many algorithms available, understanding their strengths, weaknesses, and practical applications is key to success. This step-by-step guide will help you evaluate and select the best model for your project, with detailed explanations and real-world examples.</p><h3>Step 1: Define the Problem Clearly</h3><p>Before choosing a model, you need to understand your problem. Ask yourself:</p><ol><li><strong>What is the goal?</strong> Predict values, classify data, detect anomalies, or group similar data?</li><li><strong>What type of data do you have?</strong> Structured (e.g., tabular), unstructured (e.g., text, images), or time series?</li></ol><h4>Real-World Examples:</h4><ul><li><strong>Predicting house prices</strong> (Regression): You want to predict the price of a house based on features like size, location, and number of bedrooms.</li><li><strong>Spam detection</strong> (Classification): You aim to classify emails as spam or not spam.</li><li><strong>Customer segmentation</strong> (Clustering): You want to group customers by purchasing behavior for targeted marketing.</li></ul><h3>Step 2: Understand Your Data</h3><p>The nature of your data heavily influences your choice of model. Key factors include:</p><ol><li><strong>Size of the dataset:</strong> Some models work well with small datasets (e.g., Logistic Regression), while others require large datasets (e.g., Neural Networks).</li><li><strong>Data type:</strong> Text, images, numerical, or categorical?</li><li><strong>Missing or imbalanced data:</strong> Some models (e.g., Tree-based models) handle missing data better than others.</li></ol><h4>Example:</h4><ul><li><strong>Predicting loan defaults</strong>: You have a mix of numerical (income, loan amount) and categorical (job type, education) data, with some missing values. Decision Trees or Gradient Boosting (e.g., XGBoost) would handle this well.</li></ul><h3>Step 3: Choose the Right Model Based on Problem Type</h3><h4>1. Regression (Predicting continuous values)</h4><p>Use regression models when your target variable is continuous (e.g., house prices, stock values).</p><p><strong>Popular Models:</strong></p><ul><li><strong>Linear Regression</strong>: Simple, interpretable, works well with linearly separable data.</li><li><strong>Polynomial Regression</strong>: Better for non-linear relationships.</li><li><strong>Random Forest Regressor</strong>: Handles non-linear relationships, robust to outliers.</li></ul><p><strong>Example:</strong> Predicting energy consumption in a building. Use Random Forest if the relationship is complex and involves weather conditions, occupancy, and time of day.</p><h4>2. Classification (Categorizing data)</h4><p>For discrete target variables (e.g., spam detection, medical diagnosis), classification models are ideal.</p><p><strong>Popular Models:</strong></p><ul><li><strong>Logistic Regression</strong>: Works well for binary classification problems.</li><li><strong>Support Vector Machines (SVMs)</strong>: Effective for high-dimensional data.</li><li><strong>Neural Networks</strong>: Best for large, complex datasets like image classification.</li><li><strong>XGBoost</strong>: Excellent for tabular data with categorical and numerical features.</li></ul><p><strong>Example:</strong> Detecting credit card fraud:</p><ul><li>Start with Logistic Regression for baseline accuracy.</li><li>Progress to XGBoost for better handling of imbalanced data and feature importance.</li></ul><h4>3. Clustering (Grouping data)</h4><p>Clustering models group similar data points together. Use them when labels aren’t available.</p><p><strong>Popular Models:</strong></p><ul><li><strong>K-Means</strong>: Simple, scalable, works well with spherical clusters.</li><li><strong>DBSCAN</strong>: Handles noise and works well with non-spherical clusters.</li></ul><p><strong>Example:</strong> Grouping patients based on symptoms for personalized treatments.</p><ul><li>Use DBSCAN if patient data is noisy and clusters vary in density.</li></ul><h4>4. Time Series Forecasting</h4><p>When data is time-dependent (e.g., stock prices, weather), specialized models are required.</p><p><strong>Popular Models:</strong></p><ul><li><strong>ARIMA</strong>: Best for univariate time series.</li><li><strong>LSTM (Long Short-Term Memory Networks)</strong>: Effective for multivariate or non-linear time series.</li></ul><p><strong>Example:</strong> Predicting sales for a retail store:</p><ul><li>Start with ARIMA for simple seasonality.</li><li>Use LSTM if the data involves complex patterns, such as promotions or holidays.</li></ul><h3>Step 4: Balance Accuracy, Interpretability, and Complexity</h3><h4>1. Accuracy</h4><p>Choose models like Gradient Boosting or Neural Networks for high accuracy in complex problems.</p><p><strong>Example:</strong> Predicting disease outcomes in healthcare: Prioritize accuracy over interpretability, as the stakes are high.</p><h4>2. Interpretability</h4><p>In applications like finance or healthcare, simpler models like Linear Regression or Decision Trees are preferred for explainability.</p><p><strong>Example:</strong> Loan approval: Banks need interpretable models to justify decisions to regulators and customers.</p><h4>3. Complexity and Resources</h4><p>Consider computational resources. Neural Networks require significant processing power, while simpler models like Logistic Regression are lightweight.</p><p><strong>Example:</strong> On-device AI for mobile apps: Use lightweight models like SVMs or decision trees to conserve battery and memory.</p><h3>Step 5: Evaluate Models with Metrics</h3><ul><li><strong>Regression</strong>: Use Mean Absolute Error (MAE) or Root Mean Squared Error (RMSE).</li><li><strong>Classification</strong>: Evaluate with Precision, Recall, F1-score, or ROC-AUC.</li><li><strong>Clustering</strong>: Use Silhouette Score or Davies-Bouldin Index.</li><li><strong>Time Series</strong>: Measure accuracy with Mean Absolute Percentage Error (MAPE).</li></ul><h3>Step 6: Test and Iterate</h3><p>Always experiment with multiple models and hyperparameters. Use tools like GridSearchCV or Optuna for tuning.</p><p><strong>Example:</strong><br>For a customer churn prediction project:</p><ol><li>Start with Logistic Regression.</li><li>Evaluate performance.</li><li>Progress to Gradient Boosting (e.g., LightGBM) for better results.</li></ol><h3>Conclusion</h3><p>Choosing the right ML model is both an art and a science. It requires a clear understanding of the problem, data, and trade-offs between accuracy, interpretability, and complexity. By following these steps, you’ll be well-equipped to make informed decisions and deliver impactful results in real-world projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15ba97ec9503" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to Data Engineering Pipelines: Building Effective train_pipeline.py]]></title>
            <link>https://medium.com/@emyasenc/a-beginners-guide-to-data-engineering-pipelines-building-effective-train-pipeline-py-c008b078ee03?source=rss-1313f6dd7649------2</link>
            <guid isPermaLink="false">https://medium.com/p/c008b078ee03</guid>
            <category><![CDATA[automating-workflows]]></category>
            <category><![CDATA[real-world-application]]></category>
            <category><![CDATA[data-engineering-skills]]></category>
            <category><![CDATA[machine-learning-pipeline]]></category>
            <category><![CDATA[python-for-data-science]]></category>
            <dc:creator><![CDATA[Emma Yasenchak]]></dc:creator>
            <pubDate>Fri, 29 Nov 2024 15:13:15 GMT</pubDate>
            <atom:updated>2024-11-29T15:13:15.843Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Beginner’s Guide to Data Engineering Pipelines: Building Effective train_pipeline.py and predict_pipeline.py</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ooSADBk1PrBOlrToadewlQ.png" /></figure><h3>Introduction</h3><p>Data pipelines are at the core of any machine learning project, ensuring the smooth flow of data from ingestion to prediction. In this blog, we’ll explore how to design and implement robust pipelines, focusing on train_pipeline.py for model training and predict_pipeline.py for making predictions. Using an example inspired by a fraud detection project, I’ll break down each step to help you build effective, reusable pipelines for real-world applications.</p><h3>Why Data Pipelines Matter</h3><p>Data engineering pipelines:</p><ul><li><strong>Automate processes</strong>: Save time and effort.</li><li><strong>Ensure consistency</strong>: Standardize data handling.</li><li><strong>Enhance scalability</strong>: Adapt to large datasets and complex workflows.</li></ul><p>The two core components we’ll discuss:</p><ol><li><strong>train_pipeline.py</strong>: Handles data ingestion, transformation, training, and evaluation.</li><li><strong>predict_pipeline.py</strong>: Transforms input data and generates predictions using a trained model.</li></ol><h3>Step-by-Step Guide to train_pipeline.py</h3><p>The training pipeline automates the entire model training lifecycle. Let’s break it down:</p><h4>1. Data Ingestion</h4><p>This step collects raw data and splits it into training and testing datasets.<br> The DataIngestion component might include:</p><ul><li><strong>Reading from a database or file system</strong>.</li><li><strong>Splitting into train/test sets</strong>.</li></ul><p>Example snippet:</p><pre># Data Ingestion<br>logging.info(&quot;Starting data ingestion process...&quot;)<br>data_ingestion = DataIngestion()<br>train_data_path, test_data_path = data_ingestion.initiate_data_ingestion()</pre><h4>2. Data Transformation</h4><p>Preprocess the data to make it suitable for modeling. The DataTransformation component:</p><ul><li>Encodes categorical variables.</li><li>Scales numerical features.</li><li>Combines preprocessed data into arrays.</li></ul><p>Example snippet:</p><pre># Data Transformation<br>logging.info(&quot;Starting data transformation process...&quot;)<br>data_transformation = DataTransformation()<br>train_arr, test_arr, _ = data_transformation.initiate_data_transformation(train_data_path, test_data_path)</pre><h4>3. Model Training</h4><p>This step trains multiple models and selects the best one. The ModelTrainer component:</p><ul><li>Trains various models (e.g., Random Forest, XGBoost).</li><li>Evaluates performance on test data.</li><li>Stores the best-performing model.</li></ul><p>Example snippet:</p><pre># Model Training<br>logging.info(&quot;Starting model training process...&quot;)<br>model_trainer = ModelTrainer()<br>model_report = model_trainer.initiate_model_trainer(train_arr, test_arr)</pre><h4>4. Model Evaluation</h4><p>Evaluate model performance using metrics like accuracy, precision, recall, F1-score, and ROC-AUC.</p><p>Example snippet:</p><pre># Model Evaluation<br>logging.info(&quot;Evaluating models...&quot;)<br>for model_name, model_info in model_report.items():<br>    model = model_info[&#39;best_model&#39;]<br>    X_train, y_train, X_test, y_test = (<br>        train_arr[:, :-1],<br>        train_arr[:, -1],<br>        test_arr[:, :-1],<br>        test_arr[:, -1]<br>    )<br>    y_test_pred = model.predict(X_test)<br>    metrics = {<br>        &quot;accuracy&quot;: accuracy_score(y_test, y_test_pred),<br>        &quot;precision&quot;: precision_score(y_test, y_test_pred),<br>        &quot;recall&quot;: recall_score(y_test, y_test_pred),<br>        &quot;f1_score&quot;: f1_score(y_test, y_test_pred),<br>        &quot;roc_auc_score&quot;: roc_auc_score(y_test, y_test_pred)<br>    }<br>    logging.info(f&quot;Metrics for {model_name}: {metrics}&quot;)</pre><h3>Step-by-Step Guide to predict_pipeline.py</h3><p>The prediction pipeline processes user-provided input data and generates predictions.</p><h4>1. Defining Features</h4><p>Start by defining the structure of your dataset. Split features into:</p><ul><li><strong>Numerical features</strong>: e.g., lat, long, amt.</li><li><strong>Categorical features</strong>: e.g., gender, city, category.</li></ul><p>Example:</p><pre>numerical_columns = [&quot;lat&quot;, &quot;long&quot;, &quot;amt&quot;, &quot;distance_to_merchant&quot;, &quot;age&quot;]<br>categorical_columns = [&quot;gender&quot;, &quot;city&quot;, &quot;category&quot;]<br>all_columns = numerical_columns + categorical_columns</pre><h4>2. Loading the Model and Preprocessor</h4><p>Load the trained model and the preprocessor (e.g., scaler or encoder).</p><p>Example:</p><pre>model_path = os.path.join(&quot;artifact&quot;, &quot;best_model.pkl&quot;)<br>preprocessor_path = os.path.join(&quot;artifact&quot;, &quot;preprocessor.pkl&quot;)<br>model = load_object(file_path=model_path)<br>preprocessor = load_object(file_path=preprocessor_path)</pre><h4>3. Preprocessing Input Data</h4><p>Transform input data using the preprocessor. This ensures it matches the format used during training.</p><p>Example:</p><pre>data_scaled = preprocessor.transform(features)</pre><h4>4. Making Predictions</h4><p>Use the trained model to predict outcomes.</p><p>Example:</p><pre>preds = model.predict(data_scaled)</pre><h4>5. Custom Input Class</h4><p>Create a CustomData class to handle dynamic user inputs. This allows for flexibility when feeding new data to the pipeline.</p><p>Example:</p><pre>class CustomData:<br>    def __init__(self, gender, city, category, amt, distance_to_merchant, age):<br>        self.gender = gender<br>        self.city = city<br>        self.category = category<br>        self.amt = amt<br>        self.distance_to_merchant = distance_to_merchant<br>        self.age = age<br><br>def get_data_as_data_frame(self):<br>        try:<br>            return pd.DataFrame({<br>                &quot;gender&quot;: [self.gender],<br>                &quot;city&quot;: [self.city],<br>                &quot;category&quot;: [self.category],<br>                &quot;amt&quot;: [self.amt],<br>                &quot;distance_to_merchant&quot;: [self.distance_to_merchant],<br>                &quot;age&quot;: [self.age]<br>            })<br>        except Exception as e:<br>            raise CustomException(e, sys)</pre><h3>Key Takeaways for Building Effective Pipelines</h3><ol><li><strong>Modularity</strong>: Separate concerns into components like data ingestion, transformation, and training.</li><li><strong>Reusability</strong>: Design reusable classes and methods.</li><li><strong>Error Handling</strong>: Implement robust exception handling to catch issues early.</li><li><strong>Logging</strong>: Use detailed logs to track pipeline progress and debug issues.</li><li><strong>Scalability</strong>: Ensure the pipeline can handle large datasets and adapt to new requirements.</li></ol><h3>Conclusion</h3><p>Building effective data pipelines is essential for scalable and efficient machine learning projects. With train_pipeline.py and predict_pipeline.py, you can automate and streamline your workflow, from ingestion to prediction. By following this guide and adapting it to your specific use case, you’ll be better equipped to manage real-world data science projects with confidence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c008b078ee03" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>