<?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 Taeef Najib on Medium]]></title>
        <description><![CDATA[Stories by Taeef Najib on Medium]]></description>
        <link>https://medium.com/@taeefnajib?source=rss-ef79c46616b3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uvL1rMQAlqGe0K_YU51pJQ.jpeg</url>
            <title>Stories by Taeef Najib on Medium</title>
            <link>https://medium.com/@taeefnajib?source=rss-ef79c46616b3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:28:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@taeefnajib/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[The AI Job Panic Has a Second Act, and Nobody Is Talking About It]]></title>
            <link>https://medium.com/@taeefnajib/the-ai-job-panic-has-a-second-act-and-nobody-is-talking-about-it-0b13f1ae0961?source=rss-ef79c46616b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b13f1ae0961</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[layoffs]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[jobs]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Taeef Najib]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 05:56:23 GMT</pubDate>
            <atom:updated>2026-11-01T05:56:23.934Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Companies are betting that replacing people with AI is the cheaper path. Here is why that bet may not pay off, and what comes after.</em></p><p>Every week brings a new headline about a company replacing people with AI. The story usually ends there: people lose jobs, machines win, the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-8jB6iQkODkdSo1ZsXb9Hg.png" /><figcaption>Generated by <a href="https://chatgpt.com/s/m_6ae6d2ea734c8191a191570a14054b7f">ChatGPT</a></figcaption></figure><p>But stories like this rarely end where the headlines stop. Every big technological shift has had a second act, and that second act usually belongs to people, not machines.</p><p>Here is my prediction of how the “AI is taking our jobs” story plays out, in five stages.</p><h3>Stage 1: The Rush</h3><p>We are in this stage right now, and the numbers are hard to ignore.</p><p>By mid-July 2026, one tracker had recorded 302 layoff events affecting more than 200,000 workers, roughly 1,024 job losses per day, nearly double the daily rate of 2025. More than half of those events named AI, automation, or machine learning as a contributing factor.</p><p>The logic seems simple. An AI agent doesn’t take sick leave, doesn’t ask for a raise, and works around the clock. On a spreadsheet, it beats a human every time.</p><p>There is a twist, though. Some of this is hype. Nearly six in ten companies admit they frame layoffs or hiring slowdowns as AI-driven when the real reason is financial. Analysts have even coined a term for it: “AI-washing,” meaning layoffs blamed on AI without clear evidence that AI actually replaced those workers.</p><p>Hype or not, the jobs are still gone. And that is where the trouble starts.</p><h3>Stage 2: The Human Cost</h3><p>The usual answer to job losses is “people will retrain and move on.” Some will. Many won’t.</p><p>Not everyone is built for every kind of work. A 50-year-old customer service agent cannot become a machine learning engineer in six months, no matter how many online courses exist.</p><p>The optimistic forecasts admit this gap. The World Economic Forum projects that 170 million new roles will be created and 92 million displaced by 2030. That sounds like good news, but the same report says 59% of the global workforce will need reskilling or upskilling by 2030 to stay competitive. New jobs don’t help people who can’t reach them.</p><p>When large numbers of people lose income with nowhere to go, financial stress turns into social stress. That is not a moral judgement. It is a pattern history has shown many times.</p><h3>Stage 3: The Backlash</h3><p>Public anger is already building, and it has found a visible target: data centres.</p><p>A Gallup poll published in May 2026 found that 71% of Americans oppose building an AI data centre in their local area. In the first quarter of 2026 alone, public backlash delayed or blocked at least 75 data centre projects in the US, worth around $130 billion combined. In July, opponents organised protests in at least 125 locations across the United States, the first coordinated national effort against the AI infrastructure build-out.</p><p>The job question sits at the centre of it. A Reuters/Ipsos poll found that half of Americans fear AI could put them or someone in their household out of work.</p><p>I expect this to grow into boycotts of companies seen as “AI-first, people-last.” Some of it may turn ugly. Reports already note that the wave of anger has brought protests, swayed election results, and led to isolated acts of violence.</p><h3>Stage 4: The Bill Comes Due</h3><p>Here is the part the spreadsheet misses. Workers are also customers.</p><p>When a company replaces its people with AI, it also risks losing the trust of the people who buy from it. Boycotts cut revenue. Falling revenue makes those “savings” on labour look a lot less impressive.</p><p>We have already seen a preview. In 2024, Klarna claimed AI could do the work of 700 customer service agents and was handling 75% of customer chats within a month of launch. Then the CEO changed course. He told Bloomberg that while AI chatbots are cheaper than human workers, they deliver lower-quality service. The company is now hiring humans again.</p><h3>The “cheap AI” price tag may not last</h3><p>There is another assumption hiding in the spreadsheet: that AI will stay as cheap as it is today.</p><p>Right now, much of it is sold at a discount. Reports suggest that even after price cuts, OpenAI and Anthropic are still losing money, and that a complex query can cost the AI lab more to serve than it earns. It is a familiar Silicon Valley playbook: price below cost to win market share, then raise prices once customers are locked in.</p><p>The cracks are already showing. GitHub moved its Copilot coding assistant from flat subscription pricing to usage-based pricing in June 2026. Uber’s chief technology officer told staff the company had used up its entire 2026 AI budget in just four months.</p><p>To be fair, AI can also get cheaper. The cost of generating text has dropped, partly thanks to big efficiency gains in how models run. But the price is not fixed. It depends on chips, power, and supply chains, and those can change quickly. AI demand is already causing a historic shortage of memory chips. One report suggests memory makers may meet only 60% of demand by 2027, with SK Hynix, Samsung, and Micron producing over 90% of the world’s supply.</p><p>Concentrated supply means fragile supply. A factory shutdown, a trade dispute, or a shipping disruption could push costs up overnight. A company that fired half its workforce based on today’s AI price may find itself paying tomorrow’s, with no easy way to bring those people back.</p><p>Investors notice these things. If AI-heavy companies face boycotts, blocked infrastructure, rising AI bills, and weaker customer loyalty, the growth story that props up their valuations starts to wobble. And when the stock price falls, boardroom priorities change quickly.</p><h3>Stage 5: The Correction</h3><p>This is where I expect the pendulum to swing back.</p><h3>The safety net has a hole in it</h3><p>Before any correction comes, governments will face a problem of their own.</p><p>People who lose their jobs to AI will turn to the government for support to get by. At the same time, companies hurt by boycotts and falling revenue will ask for incentives and relief to cover their losses. Both groups will be knocking on the same door.</p><p>The catch is that government money comes largely from people who earn and spend. Fewer workers means less income tax. Less spending means less sales and consumption tax. So just as more people need help, there is less money to provide it. Welfare systems were built on the assumption that most people are working and paying in, and only some are drawing out at any given time. Flip that ratio, and governments may simply not be able to support everyone the way they do today.</p><p>That pressure, more than anything, is what will force them to act.</p><h3>How the correction plays out</h3><p><strong>From industry:</strong> Companies will start setting internal standards, a certain share of work that must stay with humans, partly for quality and partly for reputation.</p><p><strong>From governments:</strong> Leaders will not sit still while unemployment and crime rise. Regulation is already moving at the infrastructure level: fourteen US states have considered or are considering moratoriums on new data centre projects. I expect rules on the balance between AI and human labour to follow.</p><p><strong>From the market:</strong> “Made by humans” will become a premium label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lLBTMz6YfkPcIX-EfNwdhg.png" /><figcaption>Generated by <a href="https://chatgpt.com/s/m_6ae6d296f5b48191a7ace773a65b4f85">ChatGPT</a></figcaption></figure><p>That last one has happened before. When machines took over production during the Industrial Revolution, handmade goods didn’t disappear. They became valuable. The Arts and Crafts movement of the late 1800s turned human craftsmanship into a mark of quality, and “handmade” still commands a higher price today.</p><p>The same thing is already starting with AI. BBC News counted at least eight separate initiatives competing to create a label with the kind of global recognition the Fair Trade logo has for ethically made products. Labels like “Proudly Human,” “Human-made,” and “AI-free” are appearing on films, marketing, books, and websites.</p><h3>So, Will Humans Get Their Jobs Back?</h3><p>Yes, but not all of them, and not the same jobs.</p><p>The people who come out ahead will be the ones who work <em>with</em> AI rather than compete against it. The evidence already points this way: research has found that the companies seeing the most gains were using AI as a collaboration tool to make workers more productive, not to replace them.</p><p>That is the real lesson. The question was never “humans or AI.” It was always “humans who use AI or humans who don’t.”</p><p>Every industrial revolution has forced people to adapt, and every time, the ones who adapted shaped what came next. This one is no different. It is not the end of human work. It is the next stage of human evolution.</p><p>The second act is coming. The only question is which side of it you will be standing on.</p><p><em>If this made you think, I’d love to hear your take. Do you see the pendulum swinging back, or are we headed somewhere else entirely?</em></p><p>If you like this article, please be kind to clap, comment and share.</p><h3>Sources</h3><ul><li><a href="https://rentierdigital.xyz/blog/ai-layoffs-2026-not-replacement">The 2026 AI layoffs nobody frames right (Rentier Digital)</a></li><li><a href="https://founderreports.com/?p=3976">AI Layoffs by Company tracker (Founder Reports)</a></li><li><a href="https://thenextweb.com/news/the-people-we-left-behind-tech-layoffs-ai-hype-and-a-misplaced-future">The people we left behind (The Next Web)</a></li><li><a href="https://www.weforum.org/press/2025/01/future-of-jobs-report-2025-78-million-new-job-opportunities-by-2030-but-urgent-upskilling-needed-to-prepare-workforces/">Future of Jobs Report 2025 (World Economic Forum)</a></li><li><a href="https://www.thealgorithmicbridge.com/p/how-america-turned-against-ai-according">How America Turned Against AI (The Algorithmic Bridge)</a></li><li><a href="https://fortune.com/2026/06/22/data-center-opposition-goes-national-despite-only-8-percent-living-near-one/">Data center opposition goes national (Fortune)</a></li><li><a href="https://www.staradvertiser.com/2026/07/18/breaking-news/u-s-data-center-protests-go-national-as-backlash-grows/">U.S. data center protests go national (Reuters via Honolulu Star-Advertiser)</a></li><li><a href="https://allwork.space/2026/06/ai-data-center-boom-faces-public-backlash-as-77-fear-higher-electricity-bills/">AI data center boom faces public backlash (Reuters via Allwork.Space)</a></li><li><a href="https://www.entrepreneur.com/business-news/klarna-ceo-reverses-course-by-hiring-more-humans-not-ai/491396">Klarna is hiring customer service agents again (Entrepreneur)</a></li><li><a href="https://siliconcanals.com/?p=63576">Klarna U-turns on AI (Silicon Canals)</a></li><li><a href="https://axios.com/2026/03/12/ai-models-costs-ipo-pricing">Don’t get used to cheap AI (Axios)</a></li><li><a href="https://www.iads.org/member/articles-reports/ai-is-currently-priced-below-cost-that-won-t-last">AI is currently priced below cost. That won’t last. (IADS)</a></li><li><a href="https://drezzed.clownfishtv.com/p/the-ai-industry-has-spent-14-trillion">The AI industry’s spending and pricing (Clownfish TV)</a></li><li><a href="https://www.bloomberg.com/graphics/2026-ai-boom-memory-chip-shortage/">The 2026 AI boom memory chip shortage (Bloomberg)</a></li><li><a href="https://respawn.outlookindia.com/amp/story/gaming/gaming-news/ai-memory-shortage-could-push-ram-crunch-to-2030">AI Memory Shortage Could Push RAM Crunch to 2030 (Outlook Respawn)</a></li><li><a href="https://rightstech.com/2026/03/is-this-product-human-made-the-race-to-establish-an-ai-free-logo/">Is this product ‘human-made’? (BBC via Rights Tech)</a></li><li><a href="https://www.blackenterprise.com/?p=1188479">AI layoffs surge, research shows automation not paying off (Black Enterprise)</a></li><li><a href="https://www.thelowdownblog.com/2026/05/americans-anti-ai-rebellion-becomes.html?m=1">Americans’ anti-AI rebellion (Jonathan Low)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b13f1ae0961" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon’s Answer to OpenAI: Meet Nova, the Future of Foundation Models]]></title>
            <link>https://medium.com/@taeefnajib/amazons-answer-to-openai-meet-nova-the-future-of-foundation-models-a2a9a09ccae9?source=rss-ef79c46616b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2a9a09ccae9</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[nova]]></category>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[multimodal-ai]]></category>
            <dc:creator><![CDATA[Taeef Najib]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 05:41:24 GMT</pubDate>
            <atom:updated>2024-12-04T05:41:24.257Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Amazon Nova</strong> is the newest innovation in generative AI, offering a suite of state-of-the-art foundation models designed for unparalleled intelligence, cost efficiency, and multimodal capabilities. Announced at AWS re:Invent 2024, these models promise to transform industries, making generative AI accessible, customizable, and scalable for a wide range of applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*ho-C6uJKqseE7opdhZcblg.jpeg" /><figcaption>Image Generated by Amazon Nova</figcaption></figure><p>Let’s dive into how Amazon Nova models are setting a new standard in AI and why they matter for enterprises, creators, and developers.</p><h3>Why Amazon Nova?</h3><p>The generative AI landscape is evolving rapidly, with major players racing to outpace each other. Amazon Nova stands out by combining <strong>frontier intelligence</strong> with <strong>industry-leading price-performance</strong>, delivering solutions tailored to real-world challenges.</p><p>With a score of 75, Nova Pro ranks higher than GPT-4o (November release), Mistral Large 2 and Llama 3.1 405B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mR-NG90bwYpOvYmhzsk6hQ.jpeg" /><figcaption>Fig 1: Image Posted on X by <a href="https://x.com/ArtificialAnlys/status/1864023052818030814">Artificial Analysis</a></figcaption></figure><h3>Key Features of Amazon Nova:</h3><ul><li><strong>Multimodal capabilities:</strong> Process text, images, and video for understanding and creative generation tasks.</li><li><strong>Customization:</strong> Fine-tune models to align with proprietary data and brand-specific needs.</li><li><strong>Cost-effectiveness:</strong> Up to <strong>75% cheaper</strong> than other leading models in similar categories.</li><li><strong>Responsible AI:</strong> Integrated safety measures, content moderation, and watermarking.</li></ul><p>Here’s an image generated with this prompt: <em>“A dinosaur sitting in a tea cup”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*jV4ZbZvlIXu57d_gbmtslQ.png" /><figcaption>Image Generated by Amazon Nova</figcaption></figure><h3>Amazon’s Edge</h3><p>With AWS’s global infrastructure and investments in custom AI chips like <strong>Trainium 2</strong> and <strong>Inferentia</strong>, Amazon Nova models are faster, more reliable, and better integrated into existing enterprise ecosystems.</p><h3>Amazon Nova Models at a Glance</h3><p>Amazon Nova introduces six models split into two categories: <strong>Understanding Models</strong> and <strong>Creative Content Generation Models</strong>.</p><h3>Understanding Models</h3><ol><li><strong>Amazon Nova Micro</strong></li></ol><ul><li><strong>Focus:</strong> Text-only tasks with lightning-fast, cost-effective responses.</li><li><strong>Key Applications:</strong> Summarization, translation, coding, and chatbots.</li><li><strong>Specs:</strong> Supports 128K tokens.</li></ul><ol><li><strong>Amazon Nova Lite</strong></li></ol><ul><li><strong>Focus:</strong> Multimodal processing of text, images, and videos.</li><li><strong>Key Applications:</strong> Document analysis, customer support, and visual Q&amp;A.</li><li><strong>Specs:</strong> Handles up to 300K tokens and 30-minute video inputs.</li></ul><ol><li><strong>Amazon Nova Pro</strong></li></ol><ul><li><strong>Focus:</strong> Advanced multimodal understanding with agentic capabilities.</li><li><strong>Key Applications:</strong> Complex workflows, financial analysis, and video summarization.</li><li><strong>Specs:</strong> Processes 300K tokens and 15,000+ lines of code.</li></ul><ol><li><strong>Amazon Nova Premier</strong> <em>(Coming early 2025)</em></li></ol><ul><li><strong>Focus:</strong> Complex reasoning tasks.</li><li><strong>Applications:</strong> Training smaller, efficient models using teacher-student distillation.</li></ul><h3>Creative Content Generation Models</h3><ol><li><strong>Amazon Nova Canvas</strong></li></ol><ul><li><strong>Focus:</strong> Image generation with studio-quality outputs.</li><li><strong>Features:</strong> Inpainting, outpainting, and background removal for precise content editing.</li></ul><ol><li><strong>Amazon Nova Reel</strong></li></ol><ul><li><strong>Focus:</strong> Video generation with text and image prompts.</li><li><strong>Features:</strong> Control over visual style, camera actions, and pacing for professional-quality video content.</li></ul><h3>Use Cases: Where Amazon Nova Shines</h3><h3>1. Document Analysis with Amazon Nova Pro</h3><p>Upload complex PDFs and generate summaries or decision trees in seconds. For example, a legal firm can use this model to analyze lengthy contracts, extracting key clauses and creating action plans.</p><h3>2. Video Understanding for Sports Analytics</h3><p>Amazon Nova Pro can describe video content in detail, enabling applications like sports analytics:</p><p><strong><em>Video Prompt:</em></strong><em> “Describe this video.”<br></em><strong><em>Output:</em></strong><em> “The video depicts a football game where the quarterback throws a pass to a receiver, culminating in a tackle by the opposing team.”</em></p><h3>3. Marketing Creativity with Amazon Nova Canvas and Reel</h3><p>Create dynamic advertisements like a whimsical “Pasta City” where buildings are made of cannelloni and streets flow with marinara sauce. Amazon Nova empowers brands to scale their creative campaigns effortlessly.</p><h3>Built for Enterprises: Integration with Amazon Bedrock</h3><p>Amazon Nova models are seamlessly integrated into <strong>Amazon Bedrock</strong>, enabling enterprises to:</p><ul><li>Fine-tune models with proprietary data for higher accuracy.</li><li>Deploy Retrieval-Augmented Generation (RAG) for grounded and accurate responses.</li><li>Scale globally with support for 200+ languages.</li></ul><h3>Customization at Its Core</h3><p>Amazon Nova supports <strong>fine-tuning</strong> and <strong>distillation</strong>, allowing businesses to adapt models to specific industries like finance, healthcare, and retail. For example, a retail company can train Nova models to align with their catalog, enhancing product recommendations.</p><h3>The Future of Amazon Nova</h3><p>Amazon’s commitment to AI innovation doesn’t stop here. In 2025, the company plans to release:</p><ul><li><strong>Speech-to-Speech Models:</strong> For real-time, human-like verbal interactions.</li><li><strong>Multimodal-to-Multimodal Models:</strong> Capable of handling any input and output combination across text, audio, images, and video.</li></ul><p>These developments will pave the way for applications like interactive AI agents that understand tone, translate across modalities, and adapt to user preferences seamlessly.</p><h3>Responsible AI: A Priority</h3><p>Amazon Nova models are designed with safety and transparency at their core. Features include:</p><ul><li><strong>Watermarking:</strong> To prevent misuse of creative outputs.</li><li><strong>Content Moderation:</strong> To ensure ethical AI usage.</li><li><strong>AWS AI Service Cards:</strong> Detailed documentation on use cases and limitations.</li></ul><h3>Get Started with Amazon Nova</h3><p>Amazon Nova models are available now on <strong>Amazon Bedrock</strong>, with support in multiple AWS regions. Whether you’re a developer, marketer, or enterprise leader, Amazon Nova offers the tools you need to build the future of AI-driven applications.</p><p>👉 <a href="https://aws.amazon.com/de/ai/generative-ai/nova/"><strong>Try Amazon Nova today</strong></a> and let us know what you create!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2a9a09ccae9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Stressing Over Tackling Class Imbalance]]></title>
            <link>https://medium.com/@taeefnajib/stop-stressing-over-tackling-class-imbalance-8f823b18ac0b?source=rss-ef79c46616b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f823b18ac0b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[class-imbalance]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Taeef Najib]]></dc:creator>
            <pubDate>Fri, 15 Nov 2024 00:04:12 GMT</pubDate>
            <atom:updated>2025-04-01T16:47:06.388Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Stressing Over Class Imbalance</h3><h4>Techniques With Code Examples (Python)</h4><p>Class imbalance is a common problem in machine learning. It occurs when the number of samples in one class significantly outweighs the number of samples in other classes. This can lead to biased models that perform poorly on the minority class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BeOHC0YV3Y_tz9tBlRpSrA.jpeg" /><figcaption>Credit: <a href="https://www.pexels.com/photo/photo-of-two-gold-colored-and-silver-colored-coins-standing-on-floor-1055081/">Pexel</a> (Mateusz Dach)</figcaption></figure><p>To read the full article for free, click <a href="https://medium.com/@taeefnajib/stop-stressing-over-tackling-class-imbalance-8f823b18ac0b?source=friends_link&amp;sk=977c02f63eee06c6cddb85fec5dbad47"><strong>here</strong></a></p><h3>The Dataset</h3><p>We create a fake dataset of 1000 sample with 20 features and 2 imbalanced target classes (90:10)</p><pre>from sklearn.datasets import make_classification<br>import pandas as pd<br># Create an imbalanced dataset<br>X, y = make_classification(n_samples=1000, n_features=20, weights=[0.9, 0.1], random_state=42)<br>print(&quot;Shape of X:&quot;, X.shape)<br>print(&quot;Shape of y:&quot;, y.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*2Bxvxh-czLhnI_yeKisZSw.png" /></figure><p>Here are some effective techniques to handle class imbalance, along with Python code examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0VXygC1V3XGrP2S6YQoZg.png" /><figcaption>Different Class Imbalance Handling Techniques</figcaption></figure><h3>Different Techniques:</h3><h4><strong>1. Data-Level Techniques:</strong></h4><h4><strong>Oversampling:</strong></h4><ul><li><strong>Random Oversampling:</strong> This duplicates samples from the minority class until it matches the majority class. If one class is significantly underrepresented compared to others, random oversampling can help balance the dataset, enabling the model to learn the minority class patterns better. It’s often the right approach if the dataset is too small to train a model effectively.</li></ul><pre>from imblearn.over_sampling import RandomOverSampler<br>ros = RandomOverSampler(random_state=42)<br>X_resampled, y_resampled = ros.fit_resample(X, y)<br>print(&quot;Original dataset shape:&quot;, {0: sum(y == 0), 1: sum(y == 1)})<br>print(&quot;Resampled dataset shape:&quot;, {0: sum(y_resampled == 0), 1: sum(y_resampled == 1)})</pre><p><em>Explanation: Random oversampling duplicates minority class samples, which can help balance the dataset but may lead to overfitting.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*t8YxBspbM3gezpRr-onVhQ.png" /></figure><ul><li><strong>SMOTE (Synthetic Minority Over-sampling Technique):</strong> SMOTE creates synthetic samples by interpolating between existing minority class samples.</li></ul><pre>from imblearn.over_sampling import SMOTE<br>smote = SMOTE(random_state=42)<br>X_smote, y_smote = smote.fit_resample(X, y)<br>print(&quot;Original dataset shape:&quot;, {0: sum(y == 0), 1: sum(y == 1)})<br>print(&quot;SMOTE dataset shape:&quot;, {0: sum(y_smote == 0), 1: sum(y_smote == 1)})</pre><p><em>Explanation: SMOTE addresses overfitting by creating new samples instead of duplicating. However, it may create synthetic samples that aren’t representative of real data.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*c8g3trsHe0WGCgXi7Io0WA.png" /></figure><h4><strong>Undersampling:</strong></h4><ul><li><strong>Random Undersampling:</strong> Randomly removes samples from the majority class.</li></ul><pre>from imblearn.under_sampling import RandomUnderSampler<br>rus = RandomUnderSampler(random_state=42)<br>X_resampled, y_resampled = rus.fit_resample(X, y)<br>print(&quot;Original dataset shape:&quot;, {0: sum(y == 0), 1: sum(y == 1)})<br>print(&quot;Under-sampled dataset shape:&quot;, {0: sum(y_resampled == 0), 1: sum(y_resampled == 1)})</pre><p><em>Explanation: Random undersampling reduces dataset size and may remove useful information, impacting model performance.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*TWIkXBgszM-Hp6b04nZvZg.png" /></figure><ul><li><strong>Cluster Centroids:</strong> Selects representative samples by clustering the majority class.</li></ul><pre>from imblearn.under_sampling import ClusterCentroids<br>cc = ClusterCentroids(random_state=42)<br>X_centroids, y_centroids = cc.fit_resample(X, y)<br>print(&quot;Cluster Centroids dataset shape:&quot;, {0: sum(y_centroids == 0), 1: sum(y_centroids == 1)})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*CZOINqc05MUpF-jvH4_f-g.png" /></figure><ul><li><strong>Class Weighting:</strong> Assigns higher weights to minority class samples during training.</li></ul><pre>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import classification_report<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)<br>model = LogisticRegression(class_weight=&#39;balanced&#39;)<br>model.fit(X_train, y_train)<br>y_pred = model.predict(X_test)<br>print(classification_report(y_test, y_pred))</pre><p><em>Explanation: Class weighting adjusts the algorithm to focus more on the minority class by assigning it a higher weight in the cost function.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*9QDEvIlszer0vhXHWel7xw.png" /></figure><h4>2. Algorithm-Level Techniques:</h4><ul><li><strong>Cost-Sensitive Learning:</strong> This approach also assigns a higher penalty to misclassifications of the minority class, but it’s more flexible and model-specific.</li></ul><pre>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import classification_report<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)<br>model = LogisticRegression(class_weight={0: 1, 1: 10}) # Heavier weight for the minority class<br>model.fit(X_train, y_train)<br>y_pred = model.predict(X_test)<br>print(classification_report(y_test, y_pred))</pre><p><em>Explanation: Adjusting class weights in cost-sensitive learning helps direct the model’s focus towards the minority class.</em></p><ul><li><strong>Ensemble Methods:</strong></li><li><strong>SMOTEBoost:</strong> Uses SMOTE with boosting, a technique where SMOTE-generated samples are used to train each new classifier in a boosting ensemble.</li><li><strong>One-Class Classification:</strong> Useful when the minority class represents anomalies.</li></ul><pre>from sklearn.svm import OneClassSVM<br># Assume majority class is normal (0) and minority is anomaly (1)<br>X_normal = X[y == 0]<br>one_class_model = OneClassSVM(gamma=&#39;auto&#39;).fit(X_normal)<br># Predict on the test set<br>y_pred = one_class_model.predict(X_test)<br>y_pred = [0 if i == 1 else 1 for i in y_pred] # Map SVM output to original labels</pre><p><em>Explanation: One-Class Classification focuses on detecting outliers, which can be effective if the minority class samples are indeed anomalies.</em></p><h3>Evaluation Metrics:</h3><ul><li><strong>Confusion Matrix: </strong>Shows the performance of the model on both classes.</li></ul><pre>from sklearn.metrics import confusion_matrix, classification_report<br>print(confusion_matrix(y_test, y_pred))<br>print(classification_report(y_test, y_pred))</pre><ul><li><strong>ROC Curve and AUC-ROC:</strong></li></ul><pre>from sklearn.metrics import roc_auc_score, roc_curve<br>import matplotlib.pyplot as plt<br>y_proba = model.predict_proba(X_test)[:, 1]<br>fpr, tpr, _ = roc_curve(y_test, y_proba)<br>auc = roc_auc_score(y_test, y_proba)<br>plt.plot(fpr, tpr, label=f&quot;AUC = {auc:.2f}&quot;)<br>plt.xlabel(&quot;False Positive Rate&quot;)<br>plt.ylabel(&quot;True Positive Rate&quot;)<br>plt.legend()<br>plt.show()</pre><p><em>Explanation: AUC-ROC provides a single score to evaluate model performance across both classes, with higher values indicating better performance on the minority class.</em></p><p>— -</p><h3>Key Takeaway:</h3><ul><li><strong>Data-level approaches</strong> are often more flexible and adaptable across classifiers. Oversampling, in particular, is straightforward but may cause overfitting.</li><li><strong>Algorithm-level techniques</strong> may be powerful but are often model-specific and harder to generalize across different classifiers.</li></ul><p>By understanding the techniques and trying different methods, you can address class imbalance effectively and improve model performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f823b18ac0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effortless ML Experimentation]]></title>
            <link>https://blog.devgenius.io/effortless-ml-experimentation-4d415b23950c?source=rss-ef79c46616b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d415b23950c</guid>
            <category><![CDATA[model-registry]]></category>
            <category><![CDATA[experiment-tracking]]></category>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Taeef Najib]]></dc:creator>
            <pubDate>Wed, 22 May 2024 21:00:02 GMT</pubDate>
            <atom:updated>2025-04-01T16:46:27.767Z</atom:updated>
            <content:encoded><![CDATA[<h3>Effortless ML Experimentation: A Beginner’s Guide to MLFlow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*zN08Qo8qin02DoHLoiauNA.jpeg" /><figcaption>Generated at playground.com (model: Juggernaut XL)</figcaption></figure><p>MLOps is revolutionizing the field of machine learning by combining the power of AI with the principles of software development. Machine learning model registry and experimentation management are key components of MLOps. Minor changes in parameters can significantly impact the model’s performance. Therefore, a machine learning engineer almost always needs to keep track of parameters, models, and their performance evaluation metrics.</p><p>To read the full article for free, click <a href="https://blog.devgenius.io/effortless-ml-experimentation-4d415b23950c?source=friends_link&amp;sk=bb2754d0c9d08d8109fe4bacfad0ff57"><strong>here</strong></a></p><h3>🤔 What is MLFlow</h3><p>MLFlow is an open-source platform designed to manage the ML lifecycle, including experiment management, reproducibility, deployment consistency, model management, and library agnosticism.</p><p>In this tutorial, we’ll walk you through the basics of MLFlow through an example project.</p><h3>⚙️ Installation</h3><p>Let’s start by installing MLFlow using pip</p><pre>pip install mlflow</pre><h3>📘 Basic Usage</h3><p>To get started, let’s create a simple Python script (script.py) to demonstrate how to log parameters and metrics with MLFlow.</p><pre>import mlflow<br><br>def my_function(param1, param2):<br>    result = param1 + param2<br>    return result<br><br>if __name__ == &quot;__main__&quot;:<br>    param1 = 2<br>    param2 = 6<br>    metric = function(param1, param2)<br>    mlflow.log_param(&quot;param1&quot;, param1)<br>    mlflow.log_param(&quot;param2&quot;, param2)<br>    mlflow.log_metric(&quot;metric&quot;, metric)</pre><p>As you can see, this script has a simple function my_function that takes two parameters- param1 and param2, adds them, and returns the result. Run python script.py and it will create a folder mlruns inside which there will be the first experiment 0 (experiment id). Inside this folder, you’ll see a run folder with the name containing a unique ID. In this run folder, you can find the metrics where the result is stored, and the params where the parameters are stored, associated with this run. There’d be nothing inside artifacts folder since we are not saving any model.</p><p>Every time you run script.py with different parameters, MLFlow will create a new run folder inside mlruns &gt; 0.</p><h3>💻 MLFlow UI</h3><p>MLFlow comes with a handy UI for visualizing your experiments. To launch the UI, run:</p><pre>mlflow ui</pre><p>This will open a web interface at <a href="http://127.0.0.1:5000/">http://127.0.0.1:5000</a> where you can see all the details of the experiments you’ve run, including parameters and metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJBCJrCgBARJl7N8pIkyFA.png" /><figcaption>MLFlow UI</figcaption></figure><h3>📊 Tracking a Machine Learning Model with MLFlow</h3><p>Next, let’s create a simple machine learning model and track its parameters and metrics using MLFlow.</p><h3>👣 Steps to Create and Track a Model</h3><p><strong>1. Create a Virtual Environment</strong></p><p>It’s a good practice to create a virtual environment for your project:</p><pre>python -m venv myenv<br>source myenv/bin/activate  # On Windows use `myenv\Scripts\activate`</pre><p><strong>2. Install Dependencies</strong></p><p>Install the necessary dependencies, including MLFlow and Scikit-Learn:</p><pre>pip install mlflow scikit-learn pandas numpy</pre><p><strong>3. Create </strong><strong>model.py</strong></p><p>Create a new Python file named model.py and add the following code:</p><pre># Importing the required libraries<br>import argparse<br>import pandas as pd<br>import numpy as np<br>from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score<br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import ElasticNet<br>import mlflow<br>import mlflow.sklearn<br>from mlflow.models import infer_signature<br><br># Get the data<br>def get_data():<br>    URL = &quot;http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv&quot;<br>    try:<br>        df = pd.read_csv(URL, sep=&quot;;&quot;)<br>        return df<br>    except Exception as e:<br>        raise e<br><br># Evaluate the model<br>def evaluate(actual, pred):<br>    rmse = np.sqrt(mean_squared_error(actual, pred))<br>    mae = mean_absolute_error(actual, pred)<br>    r2 = r2_score(actual, pred)<br>    return rmse, mae, r2<br><br># Train the model<br>def main(alpha, l1_ratio):<br>    df = get_data()<br>    train, test = train_test_split(df, test_size=0.2, random_state=42)<br>    train_x = train.drop([&quot;quality&quot;], axis=1)<br>    test_x = test.drop([&quot;quality&quot;], axis=1)<br>    train_y = train[&quot;quality&quot;]<br>    test_y = test[&quot;quality&quot;]<br><br>    with mlflow.start_run():<br>        lr = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, random_state=42)<br>        lr.fit(train_x, train_y)<br>        pred = lr.predict(test_x)<br>        signature = infer_signature(test_x, pred)<br><br>        rmse, mae, r2 = evaluate(test_y, pred)<br>        print(f&quot;Elastic Net params: alpha={alpha}, l1_ratio={l1_ratio}&quot;)<br>        print(f&quot;Elastic Net metrics: rmse={rmse}, mae={mae}, r2={r2}&quot;)<br><br>        # Logging parameters and metrics<br>        mlflow.log_param(&quot;alpha&quot;, alpha)<br>        mlflow.log_param(&quot;l1_ratio&quot;, l1_ratio)<br>        mlflow.log_metric(&quot;rmse&quot;, rmse)<br>        mlflow.log_metric(&quot;mae&quot;, mae)<br>        mlflow.log_metric(&quot;r2&quot;, r2)<br><br>        # Log the sklearn model and register as version 1<br>        mlflow.sklearn.log_model(<br>            sk_model=lr,<br>            artifact_path=&quot;sklearn-model&quot;,<br>            signature=signature,<br>            registered_model_name=&quot;sk-learn-elasticnet-reg-model&quot;,<br>        )<br><br><br># Entry point for the script<br>if __name__ == &quot;__main__&quot;:<br>    parser = argparse.ArgumentParser()<br>    parser.add_argument(&quot;--alpha&quot;, &quot;-a&quot;, type=float, default=0.5)<br>    parser.add_argument(&quot;--l1_ratio&quot;, &quot;-l1&quot;, type=float, default=0.5)<br>    args = parser.parse_args()<br>    main(alpha=args.alpha, l1_ratio=args.l1_ratio)</pre><p>This script trains and evaluates an ElasticNet regression model on the Wine Quality dataset.</p><ol><li>At first, we import all dependencies.</li><li>Then we define a function get_data that collects wine quality dataset from an URL, creates a pandas dataframe, and return the dataframe.</li><li>We define another function evaluate() that takes the actual target of the test dataset, and the prediction of ElasticNet regression model on the train dataset. Then it calculates and returns the evaluation metrics- Root Mean Squared Error (RMSE), Mean Absolute Error (MAE), and R-squared (R2).</li><li>Then we define the most important function main() whoch takes two parameters- alpha and l1_ratio. It creates the dataframe df using get_data() function, splits the dataset into train and test datasets, starts an MLflow run to log experiment details, creates an ElasticNet model with specified alpha and l1_ratio, fits the model to the training data, predicts target values for the test data, evaluates the model using evaluate() function and finally logs the models, parameters and metrics to MLflow.</li><li>We set up argument parsing to accept alpha and l1_ratio from the command line and parse the command line arguments. Then we call the main function with the parsed values.</li></ol><p><strong>4. Run the Model</strong></p><p>Execute your script with different parameters to track multiple experiments:</p><pre>python model.py --alpha 0.5 --l1_ratio 0.5<br>python model.py --alpha 0.1 --l1_ratio 0.9</pre><p>Each run will log the model, parameters, and metrics to MLFlow.</p><h3>🎁 Wrapping Up</h3><p>In this tutorial, we’ve covered only the basics of using MLFlow to track machine learning experiments. By following these steps, you can easily log parameters and metrics, visualize your experiments using the MLFlow UI, and manage your machine learning lifecycle more effectively. Happy experimenting!</p><h3>👤 About Me</h3><p>I’m Taeef Najib, a Software Development Engineer at Sidetrek, specializing in data science, machine learning, data engineering, and data analytics. With a passion for transforming data into actionable insights, I excel in creating innovative solutions that drive business success.</p><p>➡️ Connect with me at <a href="https://www.linkedin.com/in/taeefnajib/">https://www.linkedin.com/in/taeefnajib/</a></p><p>If you liked this article, please clap 👏👏👏👏👏 for better visibility/reach. Also, leave a comment to let me know your thoughts, feedback, and input.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d415b23950c" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/effortless-ml-experimentation-4d415b23950c">Effortless ML Experimentation</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fundamentals of Unit Testing]]></title>
            <link>https://medium.com/@taeefnajib/writing-unit-tests-for-your-data-science-projects-c3d46e98beb2?source=rss-ef79c46616b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3d46e98beb2</guid>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[unit-testing-tools]]></category>
            <dc:creator><![CDATA[Taeef Najib]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 00:30:06 GMT</pubDate>
            <atom:updated>2025-04-01T16:41:29.183Z</atom:updated>
            <content:encoded><![CDATA[<h4>With Pytest, A Python Testing Framework</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lleOBQ_cSdi1aUrSIhq17A.jpeg" /><figcaption>Stock Photo by <a href="https://www.pexels.com/photo/photo-of-person-taking-down-notes-7319070/">Pexel</a></figcaption></figure><p>Testing is a Software Engineering concept. It is a broad topic under the umbrella of continuous integration and continuous delivery (CI/CD) pipeline. Among all different types of tests, unit tests are the fastest to run and the least expensive. All the benefits of unit testing apply to Data Science just as much to Software Engineering. So when should Data Scientists start testing the code? The answer is: right after performing the exploratory data analysis. Especially when code is used in production, writing unit tests is a crucial step and definitely a good practice that is often overlooked by many. In this article, we are going to focus only on Unit Tests.</p><p>To read the full article for free click <a href="https://medium.com/@taeefnajib/writing-unit-tests-for-your-data-science-projects-c3d46e98beb2?source=friends_link&amp;sk=9483610ba83f9fba455fec5a5de6c912"><strong>here</strong></a></p><h3>Types of Software Testings</h3><h4>Unit Test</h4><p>Unit Testing is the first step of testing and is usually done by developers. It means testing individual parts of the code to check whether they work.</p><h4>Integration Test</h4><p>Integration Testing is done after Unit Testing. In this phase, individual modules or components are combined and tested as a group. Integration Testing is conducted to evaluate the compliance of a system or component with specified functional requirements.</p><h4>System Testing</h4><p>After Integration Testing is done, the complete and fully integrated software product needs to be tested. This is called System Testing. It is Black-box testing, meaning that the tester does not see what is going on inside. whereas in Unit Testing and Integration Testing, we use White-box Testing.</p><p>Alongside, there are many other tests, such as Usability Testing, Load Testing, Regression Testing, Recovery Testing, Migration Testing, Functional Testing, Hardware/Software Testing, Security Testing and so on and so forth.</p><h3>What is Unit Testing</h3><p>Unit testing is a step of software development life-cycle where the smallest testable parts of an application, termed as units, are individually tested. It is a well-known topic among Software developers and QA engineers. But it is also important for Data Scientists to write unit tests. The goal of unit testing is to separate small parts of written code to check if they work as intended.</p><p>If done correctly, they can benefit data science projects as much as they benefit the software development process. Speaking of benefits, here are the main benefits of writing unit tests.</p><h3>Benefits of Unit Testing</h3><ul><li>Find bugs earlier: These tests detect early flaws in code which may be more challenging to find in later testing stages. Fixing bugs at an early stage is usually much cheaper than fixing them later in the production phase.</li><li>Helps detect edge cases: Edge cases are easily overlooked. However, unit tests can detect edge cases for very complex code.</li><li>Iterate faster: Writing unit tests helps detect the part of your code that breaks. Therefore, it helps you make changes safely and refactor your code easily without breaking anything.</li><li>Acts as documentation: By testing each small part of your code individually, you know what each function does and how it works. This serves as the documentation for the users of the code.</li><li>Debug more easily: Unit testing also helps debug more easily.</li><li>Design better code: Writing unit tests forces you to plan ahead, organize your code, and follow production-ready coding conventions, making you create better designs.</li></ul><h3>How to Perform Unit Testing</h3><h4>Pytest Framework:</h4><p>Pytest is a testing framework that allows you to write small, readable tests in Python, and can scale to support complex functional testing for applications and libraries.</p><p>In order to use pytest, we need to install it first with the following command:</p><pre>pip install -U pytest</pre><p>Now let’s understand how to perform unit testing in pytest. Before that, we have to understand the 3 As of unit testing:</p><ul><li><strong>Arrange:</strong> Prepare arguments to pass into the function being tested.</li><li><strong>Act:</strong> Call the function being tested.</li><li><strong>Assert:</strong> Compare actual vs. expected</li></ul><p>Let’s consider a function in a file called main.py:</p><pre>def add_numbers(first_number, second_number):<br>	return first_number + second_number</pre><p>To test the function add_numbers(), we have to first import the function and also import pytest in a file called test.py</p><pre>from main import add_numbers<br>import pytest</pre><p>In [test_add_numbers.py](&lt;http://test.py&gt;) we have to create a test function in the following pattern- test_*()</p><pre>def test_add_numbers():<br>    # Arrange<br>    first_number, second_number = 6, 3   <br>    # Act<br>    result = add_numbers (first_number, second_number)<br>    # Assert<br>    assert result == 9</pre><p>In your terminal, run the following command:</p><pre>pytest</pre><p>This will automatically find all files of the form test_*.py or *_test.py in the current directory and its sub-directories, and find all test functions. You’ll see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*c4tc6tU7ZkDdwmOeGHoCGg.png" /></figure><h4>Testing Multiple Functions</h4><p>What if you want to test multiple functions at once? Let’s take these two functions as examples:</p><pre>def add_numbers(first_number, second_number):<br>	return first_number + second_number</pre><pre>def substract_numbers(first_number, second_number):<br>	return first_number - second_number</pre><p>To test them together, you need to create a class. Prefix your class with Test otherwise the class will be skipped. Let’s create a new file test_multiple_functions.py</p><pre>class TestClass:<br>    def test_add_numbers(self):<br>	    # Arrange<br>	    first_number, second_number = 6, 3   <br>	    # Act<br>	    result = add_numbers (first_number, second_number)<br>	    # Assert<br>	    assert result == 9<br>    def test_substract_numbers(self):<br>	    # Arrange<br>	    first_number, second_number = 6, 3   <br>	    # Act<br>	    result = substract_numbers (first_number, second_number)<br>	    # Assert<br>	    assert result == 9</pre><p>In order to test the functions or classes of a specific file, you can use the following command:</p><pre>pytest test_multiple_functions.py</pre><p>Please note that the first function should return Passed and the second one should return Failed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*dcxg5Nl5pzcYXsaGrinX7Q.png" /></figure><p>Pytest uses different decorators to facilitate testing. Two important concepts should be introduced at this point:</p><ul><li>Fixtures</li><li>Parameterization</li></ul><h4>Pytest Fixtures</h4><p>Fixtures in pytest provide a way to set up and manage resources that your tests might require, such as database connections, temporary files, configuration settings, or any other kind of state. Fixtures help you avoid duplicating code and make your tests more organized, maintainable, and efficient. To use Fixtures, you need to use @pytest.fixture decorator. Let’s say, we have this code in dataframe.py:</p><pre>import pandas as pd</pre><pre>df = pd.read_csv(&quot;raw/data.csv&quot;)</pre><pre>def show_columns(df):<br>	return df.columns</pre><pre>def check_nan(df, col):<br>	return df[col].isna().any().any()</pre><p>To test the functions show_cols() and check_nan(), we’ll use the following code in test_dataframe.py:</p><pre>from dataframe import show_columns, check_nan<br>import pytest<br>import pandas as pd</pre><pre>@pytest.fixture<br>def create_dataframe():<br>    return pd.read_csv(&quot;raw/data.csv&quot;)</pre><pre>class TestClass:<br>    def test_show_columns(self, create_dataframe):<br>        cols = show_columns(df=create_dataframe)<br>        expected_cols = [&#39;date&#39;, &#39;reg&#39;, &#39;name&#39;, &#39;prod&#39;, &#39;qty&#39;, &#39;price&#39;, &#39;total_price&#39;]<br>        assert cols.tolist() == expected_cols<br>    <br>    def test_check_nan(self, create_dataframe):<br>        has_nan = check_nan(df=create_dataframe, col=&quot;name&quot;)<br>        assert not has_nan</pre><p>We can see that both tests are passed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*n6mIEgoh9YpsuKc0EtcvNg.png" /></figure><h4>Parameterization</h4><p>The objective of writing unit tests is not just testing one output with one input. We should test multiple sets of inputs and expected outputs. In pytest, we can use parameterized tests to test different sets of actual and expected outputs using the <strong>@pytest.mark.parametrize</strong> decorator. This allows us to write a single test function that takes multiple sets of inputs and expected outputs. Pytest automatically generates separate test cases for each combination.</p><p>Let’s consider another example. This is our code in [main.py](&lt;http://main.py&gt;) file:</p><pre>def multiply_numbers(first_number, second_number):<br>	return first_number * second_number</pre><p>We create a file called test_multiply_numbers.py file:</p><pre>from main import multiply_numbers<br>import pytest</pre><pre>@pytest.mark.parametrize(&quot;first_number, second_number, expected_output&quot;, [<br>    (0, 0, 0),<br>    (0, 1, 0),<br>    (1, 0, 0),<br>    (1, 1, 1),<br>    (-1, -1, 1),<br>    (-1, 1, -1),<br>    (1, -1, -1)<br>])</pre><pre>def test_multiply_numbers(first_number, second_number, expected_output):<br>    result = multiply_numbers (first_number, second_number)<br>    # Assert<br>    assert result == expected_output</pre><p>If we run pytest test_multply_numbers.py, we can see that pytest has created 7 tests with 7 different sets of actual and expected outcomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*11LVagyR3XJFDrq06NqbQg.png" /></figure><h4>Multiple Asserts</h4><p>It is generally a good idea to use a single assert statement in a test function. But we can also use multiple assert statements. Take this code in multiple_asserts.py file for example:</p><pre>import pytest</pre><pre>def test_multiple_asserts():<br>    value1 = 10<br>    value2 = 15<br>    <br>    assert value1 &lt; value2<br>    assert value2 &gt; 0<br>    assert value1 + value2 == 30</pre><p>Even though the first and the second assert statement should pass, the third one should fail. When we run pytest multiple_asserts.py, we can see that there is only 1 test that failed and it also shows where it failed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*Si0DTHYQjvOfk9fh-Vx2UA.png" /></figure><h3>Final Words</h3><p>Here are some extra tips for you!</p><h4>Scopes</h4><p>Fixtures are usually time-expensive. By default, a fixture is invoked once per test function. But we can control how long these resources are available and shared among test functions. the <strong>scope</strong> parameter for fixtures determines the lifetime and scope of the fixture instances. We can create a fixture for function, class, module, package or session. This is how to use different scopes for fixtures:</p><pre>@pytest.fixture(scope=&quot;function&quot;)<br>@pytest.fixture(scope=&quot;class&quot;)<br>@pytest.fixture(scope=&quot;module&quot;)<br>@pytest.fixture(scope=&quot;session&quot;)</pre><h4>Testing A Specific Function</h4><p>If you want to test a specific test function in a specific test file, you can use this command:</p><pre>pytest testfile.py -k test_function</pre><p>or</p><pre>pytest testfile.py::test_function</pre><p>All the files can be found on this GitHub repository: <a href="https://github.com/taeefnajib/Unit-Testing-using-Pytest">https://github.com/taeefnajib/Unit-Testing-using-Pytest</a></p><p>Embracing unit testing is a good practice for both Data Scientists and Software Engineers. With its ability to detect bugs early, test elusive edge cases, and facilitate rapid iterations, unit testing makes the development process more efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3d46e98beb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hyperparameter Tuning Using Optuna]]></title>
            <link>https://medium.com/@taeefnajib/hyperparameter-tuning-using-optuna-c46d7b29a3e?source=rss-ef79c46616b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c46d7b29a3e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[optuna]]></category>
            <category><![CDATA[bayesian-optimization]]></category>
            <category><![CDATA[model-performance]]></category>
            <category><![CDATA[optimization-techniques]]></category>
            <dc:creator><![CDATA[Taeef Najib]]></dc:creator>
            <pubDate>Fri, 11 Aug 2023 00:41:35 GMT</pubDate>
            <atom:updated>2025-04-01T16:42:33.462Z</atom:updated>
            <content:encoded><![CDATA[<h4>Use the Power of Bayesian Optimization</h4><p>Hyperparameter tuning is one of the most important steps in the ML workflow. It is the process of selecting a set of optimal hyperparameters that can improve the performance of a model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DEgSn-9ZqoamYXNjd3cLRw.jpeg" /><figcaption>Stock photo from <a href="https://www.pexels.com/photo/macro-shot-audio-equalizer-744318/">Pexels</a></figcaption></figure><p>To read the full article for free, click <a href="https://medium.com/@taeefnajib/hyperparameter-tuning-using-optuna-c46d7b29a3e?source=friends_link&amp;sk=721a63588137b26d3980592ffdb13702"><strong>here.</strong></a></p><h3><strong>What are Hyperparameters?</strong></h3><p>Hyperparameters are parameters that are set before the model training begins. They are not learned by the model during the training process.</p><p><strong>Methods of Hyperparameter Tuning</strong></p><p>There are three methods worth talking about:</p><ol><li><em>Grid search,</em></li><li><em>Random search, and</em></li><li><em>Bayesian optimization.</em></li></ol><p>In this article, we are going to talk about Bayesian Optimization. A popular open-source framework for Bayesian Optimization is Optuna. We’ll also talk about Optuna. Before that, let’s learn a bit about the Bayesian Optimization technique.</p><p><strong>What is Bayesian Optimization</strong></p><p>Grid search and Random search are widely used in the Data Science community. But they have some limitations. For instance, Grid search is both time-consuming and resource-hungry. Random search is better in terms of speed and complexity. However, it does not imply using any specific algorithm. It selects hyperparameters at random within a range. Both of these techniques have a common drawback- they don’t take the previous iterations into consideration while searching for the optimal hyperparameters. This is where Bayesian optimization kicks in. It finds relatively good hyperparameter combinations in relatively few iterations as it uses a probabilistic function considering the previous evaluation results.</p><h3><strong>What is Optuna</strong></h3><p>Optuna is a free, powerful, and open-source framework for hyperparameter optimization. It automates the tuning process using a combination of Bayesian optimization and helping algorithms to efficiently and effectively search the optimal set of hyperparameters.</p><p>This framework is pretty simple and it can easily be integrated with the most popular ML libraries including TensorFlow, Scikit-learn, XGBoost, LightGBM, PyTorch, and so on and so forth.</p><h3><strong>How to Use Optuna</strong></h3><p>To use Optuna for hyperparameter tuning, you need to define an objective function. Inside the objective function, suggest hyperparameter values using trial. In the same function, declare the model, which is SVC in this example. Finally, create a study object and invoke the optimize function over 100 trials.</p><p>Here is an example code:</p><pre>import optuna<br>from sklearn.datasets import load_iris<br>from sklearn.svm import SVC<br>from sklearn.model_selection import cross_val_score<br><br>iris = load_iris()<br>X, y = iris.data, iris.target<br><br># Define the objective function and suggest hyperparameters values<br>def objective(trial):<br>    svc_c = trial.suggest_loguniform(&#39;C&#39;, 1e-10, 1e10)<br>    svc_gamma = trial.suggest_loguniform(&#39;gamma&#39;, 1e-10, 1e10)<br>    clf = SVC(C=svc_c, gamma=svc_gamma)<br>    return cross_val_score(clf, X, y, n_jobs=-1, cv=3).mean()<br><br># Create a study object and optimize the objective function<br>study = optuna.create_study(direction=&#39;maximize&#39;)<br>study.optimize(objective, n_trials=100)<br><br># Print the best set of hyperparameters<br>print(&#39;Best hyperparameters: &#39;, study.best_params)<br># Print the corresponding performance<br>print(&#39;Best performance: &#39;, study.best_value)</pre><p>Optuna is a useful and open-source hyperparameter optimization framework that automates the search for optimal hyperparameters. It can efficiently search large spaces and prune unpromising trials for faster results. To learn more, you can explore the <a href="https://optuna.org/">official docs</a> of Optuna.</p><p>***If you like this article, please <strong>clap,</strong> and <strong>share,</strong> to make it more visible. ***Follow me for more articles. I usually follow back.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c46d7b29a3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerization for Your Next Data Science Projects]]></title>
            <link>https://medium.com/@taeefnajib/dockerization-for-your-next-data-science-projects-c5f2f06b70c4?source=rss-ef79c46616b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5f2f06b70c4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[dockerization]]></category>
            <category><![CDATA[reproducibility]]></category>
            <dc:creator><![CDATA[Taeef Najib]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 17:42:46 GMT</pubDate>
            <atom:updated>2025-04-01T16:44:36.993Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dockerization for Next Your Data Science Project</h3><h4>An Absolutely Basic Tutorial on Docker For Data Scientists</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jJFrUxXB-ixi3vQj" /><figcaption>Photo by <a href="https://unsplash.com/@ventiviews?utm_source=medium&amp;utm_medium=referral">Venti Views</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The concept of <em>Environment </em>is one of the most important factors to be considered in Data Science, which is often overlooked by many. With the help of package managers, such as pip or conda it is possible to install a bunch of dependencies on your local machine. But Data Science projects are often meant to be collaborative, which means others, such as your colleagues, clients, supervisors, and other stakeholders may also be involved. Different people use different types of machines with different Operating Systems. Often, incompatibility issues and conflicts raise when a project runs on another person’s machine, even if it runs smoothly on yours. Docker solves this pain point by bundling up everything so the app runs on other machines as smoothly as it runs on your machine.</p><p>To read the full article for free, click <a href="https://medium.com/@taeefnajib/dockerization-for-your-next-data-science-projects-c5f2f06b70c4?source=friends_link&amp;sk=21800ecb6938d053d9e78fa283b3292a"><strong>here</strong></a></p><h3>What Docker Really is 🤔</h3><p>When you, as a developer, work on a project, the project runs smoothly on your machine. However, a common problem every developer faces is that- a project that runs on the developer’s machine, does not run on another person’s machine as soon as it is shipped to another machine. This other person may be a co-developer, a client, a cloud server, or a project manager. Even if it runs, the same performance may not be found in another person’s machine.</p><p>This classic problem is stated as <strong>“It works on my machine…!!”</strong></p><p>This happens often due to infrastructure issues, for example, a dependency that is installed in one machine and not installed in the other may arise an error. Also, the two developers may be using completely different Operating Systems, which may cause the errors.</p><p>To address this issue, you can either ask the other person to create a virtual machine. This is not only time-consuming but also resource-consuming. There comes docker to save the day!</p><p>Docker packages all the components of an application and makes a Docker container, which can easily run on another machine. On the new machine, Docker, when it is run, creates a virtual environment inside which the application runs.</p><p>Using docker, you can not only ship your project to another person’s machine but also share the image socially where any person can use the image to create a container. Isn’t that handy?</p><h3>How it Works ⚙️</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJwtSd7OFMBaLVXmNu5uHA.png" /><figcaption>Image by Author</figcaption></figure><p>There are three elements that you need to know, in order to work with Docker:</p><ol><li><strong>A Dockerfile</strong> is a text document that contains all the commands a user could call on the command line to assemble an image. You are going to add a dockerfile to your project folder for others to reproduce your project.</li><li><strong>A Docker Image</strong> is a read-only file with a bunch of instructions. When these instructions are executed, it creates a Docker container.</li><li><strong>A Docker Container</strong> is a software package that has all the dependencies required to run an application. It contains your code, dependencies, configuration, process, some functionalities of an OS, and more.</li></ol><h3>Two Parts of Docker</h3><p>There are two integral parts of Docker:</p><ol><li>Docker Engine</li><li>Docker Hub</li></ol><p>Now let’s get started with Docker. Our first step is to download and install the Docker Desktop App.</p><h3>Download and Install Docker 🚢</h3><p>Go to the official website of Docker and signup. If you have an account already, sign in. Then download Docker Desktop App for your OS. Once downloaded and installed, go to your terminal and run docker. If docker is installed in your system, you’re going to see a whole bunch of things on the terminal. Otherwise, you’ll see messages like <strong>“docker: command not found”</strong></p><p>Once you install the app, run it and log in. On a mac, I didn’t face any issues, but on <strong>Ubuntu 22.04.1 LTS,</strong> I got an error regarding pass for which you can find a solution here: <a href="https://github.com/docker/docker-credential-helpers/issues/102#issuecomment-388634452">https://github.com/docker/docker-credential-helpers/issues/102#issuecomment-388634452</a></p><p>Let’s test docker by running docker run hello-world It should return something like this on the terminal:</p><pre>Hello from Docker!<br>This message shows that your installation appears to be working correctly.<br><br>To generate this message, Docker took the following steps:<br> 1. The Docker client contacted the Docker daemon.<br> 2. The Docker daemon pulled the &quot;hello-world&quot; image from the Docker Hub.<br>    (amd64)<br> 3. The Docker daemon created a new container from that image which runs the<br>    executable that produces the output you are currently reading.<br> 4. The Docker daemon streamed that output to the Docker client, which sent it<br>    to your terminal.<br><br>To try something more ambitious, you can run an Ubuntu container with:<br> $ docker run -it ubuntu bash<br><br>Share images, automate workflows, and more with a free Docker ID:<br> https://hub.docker.com/<br><br>For more examples and ideas, visit:<br> https://docs.docker.com/get-started/</pre><p>However, on <strong>Ubuntu 22.04.1 LTS,</strong> I received an error:</p><pre>Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.39/containers/json: dial unix /var/run/docker.sock: connect: permission denied</pre><p><a href="https://linuxhandbook.com/docker-permission-denied/">Here</a> is a solution to this issue. The next step is to create the dockerfile in your project directory.</p><h3>How to Write a Dockerfile 📄</h3><p>Dockerfile is a text file that has instructions for Docker on how to build the image. To create adockerfile, you first need to go to your project directory and create a new file called “Dockerfile”. Please note that the file name will not have any extension. It will be simply called “Dockerfile” and that’s how Docker will recognize it.</p><p>Once it is created, open the file using your favorite IDE, such as VSCode. It will be a blank file, but you need to write commands for Docker in this file. The most common syntaxes are explained for you below. After we explain all these commands, we are going to merge some of them to write our dockerfile.</p><ol><li><strong>FROM</strong></li></ol><p>A valid dockerfile should start with FROM syntax. It sets the Base Image. The Image can be simply an OS, such as Ubuntu or Alpine. Or, it can be a technology used in your project. It can be pulled from <a href="https://hub.docker.com/">Dockerhub</a>, a listing of all public repositories of pre-built applications, ready to be used. You can choose a technology that you used, such as Python, Java, Node, Rupy, etc.</p><p>The following structure should be maintained while declaring FROM syntax in your dockerfile:</p><pre>FROM python:3</pre><p>You can use python:&lt;version&gt; which is the default syntax if you are unsure about what your needs are. You can also use other image variants, such as python:&lt;version&gt;-slim or python:&lt;version&gt;-alpine, and so on.</p><p>You can see the tags here: <a href="https://hub.docker.com/_/python">https://hub.docker.com/_/python</a></p><p><strong>2. WORKDIR</strong></p><p>In this command, you are going to declare the working directory of your docker container that will be created from the image. Let’s name our project folder app, so the working directory would be /app</p><pre>WORKDIR /app</pre><p><strong>3. EXPOSE</strong></p><p>This command is used to declare the port through which the local machine can access the container. It’s called the container port.</p><pre>EXPOSE 5000</pre><p><strong>4. COPY</strong></p><p>This command is used to copy files and directories from your container to the local machine. It is declared in this way COPY &lt;src-path&gt; &lt;destination-path&gt; In our example dockerfile, we can use it in the following way. By . we mean the current folder. So, we are copying everything from the current directory to the root of our container.</p><pre>COPY . .</pre><p><strong>5. RUN</strong></p><p>RUN command sets the actions to be taken during building the image from dockerfile. CMD also sets the actions, but CMD sets only the action that needs to be taken after the container is instantiated. CMD states the action of the container. RUN states only the actions that need to take place while building the image. It is possible to have multiple RUN commands in a dockerfile. But you may want to pass multiple actions to a single RUN command, instead, since every time you call the RUN command, you add a new layer to the image, increasing the size of your docker image. RUN declares actions like unzipping a zipped file, installing dependencies, etc.</p><pre>RUN pip install -r requirements.txt</pre><p><strong>6. CMD</strong></p><p>There can only be one CMD command in a dockerfile, unlike RUN. If you provide multiple CMD commands, only the last one will be executed. For our example, we have an <a href="http://app.py/">app.py</a> file that needs to be run in order for the Flask application to run. As we normally use python app.py to run the app, we can pass the same into the CMD command as an array:</p><pre>CMD [&quot;python&quot;, &quot;./app.py&quot;]</pre><h3>.dockerignore File</h3><p>Before docker sends all the files to the docker daemon, it looks for a file called .dockerignore. If it exists, docker reads the names of files and directories in this file and excludes them. This helps you prevent unimportant, large, and sensitive files to be included in your image. Here’s an example code:</p><pre># This is how you write a comment. It will be ignored.<br># Any folder or file that starts with the word `temp` inside any folder<br># It could be a folder called temp or a file called temporary.yaml, etc.<br>*/temp* <br># Any folder or file that starts with the word `temp` inside any folder,<br># sub-folder, or sub-folder inside any number of sub-folder.<br>**/temp*<br># Any file that has .md extension<br>*.md<br># ! is used to create an exception<br>!README.md</pre><h3>How to Build a Docker Image 🖼️</h3><p>Now that you have your dockerfile ready to be used. While you are inside the directory, run this code in your terminal to build a docker image with the dockerfile:</p><pre>docker build -t &lt;your-image-name&gt; .</pre><p>docker build command takes instructions from your dockerfile and builds an image. -t flag simply tags your image, meaning that you’ll receive a human-readable tag for the image that you can use to call your image while creating the container. However, we add a name in the command, so we can directly call the image with its name, too! The . at the end tells docker to look for dockerfile in the current directory.</p><h3>How to Create a New Container 📦</h3><p>run the command docker images to verify that your image is built. If it is successfully built, you can start creating a container with the image. Use the command in the terminal:</p><pre>docker run -p 5000:8000 &lt;your-image-name&gt;</pre><p>The command docker run creates a container using the docker image &lt;your-image-name&gt; and starts it at port 8000. -p flag creates the mapping between the host’s port 8000 to the container’s port 5000.</p><p>There you go! You now have a basic understanding of docker, its functionalities, and how to use it to make your data science project reproducible.</p><p>If you have any questions, you can ask me in the <strong>comment</strong> section.</p><p><strong>Find me on:</strong></p><ul><li>LinkedIn at<em> </em><a href="https://www.linkedin.com/in/taeefnajib/"><em>https://www.linkedin.com/in/taeefnajib</em></a></li><li>Twitter at <a href="https://twitter.com/IAmTaeefNajib"><em>https://twitter.com/IAmTaeefNajib</em></a></li><li>GitHub at <a href="https://github.com/taeefnajib"><em>https://github.com/taeefnajib</em></a></li></ul><p>If you liked this article, please give me a <strong>clap </strong>👏👏👏 and if you think it is useful, please <strong>share</strong> <strong>it</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5f2f06b70c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turn Your ML Project into a Web App]]></title>
            <link>https://medium.com/@taeefnajib/turn-your-ml-project-into-a-web-app-211cacfa7b44?source=rss-ef79c46616b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/211cacfa7b44</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[web-applications]]></category>
            <dc:creator><![CDATA[Taeef Najib]]></dc:creator>
            <pubDate>Sat, 25 Feb 2023 13:45:02 GMT</pubDate>
            <atom:updated>2025-04-01T16:43:44.449Z</atom:updated>
            <content:encoded><![CDATA[<h3>Turn Your ML Project into a Web App Using Flask and Render</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PBre3FtG6XibYmbb4Ee2EQ.png" /><figcaption><em>Image by Author [Generated by Stable Diffusion: “Robotic hand holding robotic brain”]</em></figcaption></figure><p>Your portfolio projects can make or break your employability! This is more true for aspiring Data Scientists since Data Science is not just theoretical-gibberish, but rather a mixture of both theory and practical implementation. When we talk about a Data Science project, do we really mean a Jupyter Notebook uploaded on GitHub, or do we also want to see the implementation of the models using a nice Graphical User Interface (GUI)? I believe almost all of you would agree that both are true. When I was trying to showcase my work to the world, I faced almost every obstacle that a beginner may face during deployment. All the tutorials I found were talking about Heroku, but it was not free anymore at the time I was trying to deploy my project. So I thought of creating a tutorial solely on building and deploying a web app using a free alternative Render.</p><p>To read the full article for free, click <a href="https://medium.com/@taeefnajib/turn-your-ml-project-into-a-web-app-211cacfa7b44?source=friends_link&amp;sk=45e17601fe68838d7beadfe10d0067ee"><strong>here</strong></a></p><p>Before we even start, let’s set the expectations! This is not a tutorial on training a Machine Learning model. Rather, we’ll assume that you already trained a model and saved it using pickle. This tutorial will teach you how to create a web app that will use your trained model to predict an output/target based on the inputs/features provided by the users on a GUI. This tutorial will also teach you how to deploy the app on Render.</p><p>This is a simple form of deployment using Flask and Render, for absolute beginners.</p><h3>1.0 A Little Bit of Theory</h3><h4>1.1 What is Render</h4><p>Render is a cloud platform as a service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud. It supports many languages, such as Python, Ruby, Rust, Node.js, and more. For our purpose, we are going to use Python. Previously, Heroku was a popular platform for hobbyist engineers and students to deploy their apps for free. Since November 28, 2022, the company stopped offering free product plans. So users turned to other free alternatives, such as Render. As a pre-requisite, we would need a requirements.txt file. It is a file that contains the names of all the dependencies of the project. Render needs to install the dependencies before running the app.</p><h4>1.2 What is Flask</h4><p>Flask is a micro web framework, written in Python, and developed by Armin Ronacher. It provides libraries to build lightweight web applications. Flask is getting increasingly popular for being simple and lightweight, and also for having a small learning curve. It is suitable for both beginners and professionals.</p><p>Now that we have a theoretical understanding of this project, let’s get to work!</p><p>To give you a preview, the structure of our project folder would look like this:</p><pre>├── models<br>│   ├── model.pkl        &lt;- model saved after it is trained<br>├── requirements.txt     &lt;- required for deploying at Render<br>├── static<br>│   ├── image       <br>│   │   ├── img.jpg      &lt;- image to be used in your GUI<br>│   ├── style.css        &lt;- CSS stylesheet for your GUI<br>├── templates<br>│   ├── index.html       &lt;- HTML template for your GUI<br>├── app.py               &lt;- the main file containing the Flask app</pre><h3>2.0 About Our Project</h3><p>Here’s the web app we are going to build:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*ABRi7GjiPP3wZgvt74QsmA.png" /><figcaption>Screenshot of web UI. Image by Author</figcaption></figure><p>You can check the public repository here:</p><p><a href="https://github.com/taeefnajib/glass-type-prediction">GitHub - taeefnajib/glass-type-prediction: In this project, we are going to classify the type of a glass based on the elements used in the glass.</a></p><p>In this project, we used a <a href="https://www.kaggle.com/datasets/uciml/glass">dataset</a> posted on Kaggle by UCI Machine Learning. We’ll create a web app that will predict the type of glass based on the different chemical elements used in it. The chemical elements are:</p><ul><li>RI — Iridium</li><li>NA — Sodium</li><li>Mg — Magnesium</li><li>Al — Aluminium</li><li>Si — Silicon</li><li>K — Potassium</li><li>Ca — Calcium</li><li>Ba — Barium</li><li>Fe — Iron</li></ul><p><em>** Please ignore any other file or folder in the GitHub repository other than the files mentioned in the file structure above. We will only use the saved model and focus more on creating and deploying the app.</em></p><h3>3.0 Building A Flask App</h3><h4>3.1 Virtual Environment</h4><p>First and foremost, we need to create a virtual environment on our local machine. Let’s create an environment using venv or conda</p><pre>conda create --name glass-type-prediction python=3.10<br>conda activate glass-type-prediction</pre><h4>3.2 Model</h4><p>Our model will reside as a .pkl file inside the model folder. As previously stated, we assumed that we trained and saved the model using pickle Therefore, I intentionally excluded the training part to keep the actual tutorial simple and easy to understand. You can download the model.pkl file from GitHub.</p><h4>3.3 Install Dependencies</h4><p>requirements.txt file is required by Render in order for us to deploy our project on it. Create a new file in your directory and name it requirements.txt. Paste the following libraries in the file:</p><pre>click<br>flask<br>gunicorn<br>itsdangerous<br>jinja2<br>markupsafe<br>numpy<br>werkzeug</pre><p>Install the dependencies using pip by running the following command on your terminal:</p><pre>pip install -r requirements.txt</pre><p>This will install all the libraries that we’ll require to run a flask app.</p><p><em>** In my experience, it is better to keep only the name of the libraries in the file. I received a version conflict error when I used the specific version number for a number of libraries.</em></p><h4>3.4 Templates and index.html</h4><p>We need a folder that will hold the HTML file for our GUI. This folder needs to be named templates. If it is named anything else other than templates, you need to specify the other name while instantiating the app in <a href="http://app.py/">app.py</a> file:</p><pre>app = Flask(__name__, template_folder=&#39;something-else&#39;)</pre><p>Inside this folder, create a file called index.html which will contain the HTML code for the front-end of our project. Paste the following in the file:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>    &lt;head&gt;<br>        &lt;meta charset=&quot;utf-8&quot;&gt;<br>        &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;<br>        &lt;title&gt;Glass Type Prediction&lt;/title&gt;<br>        &lt;meta name=&quot;description&quot; content=&quot;&quot;&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>        &lt;link rel=&quot;stylesheet&quot; href=&quot;../static/style.css&quot;&gt;<br>        &lt;link rel=&quot;preconnect&quot; href=&quot;&lt;https://fonts.googleapis.com&gt;&quot;&gt;<br>        &lt;link rel=&quot;preconnect&quot; href=&quot;&lt;https://fonts.gstatic.com&gt;&quot; crossorigin&gt;<br>        &lt;link href=&quot;&lt;https://fonts.googleapis.com/css2?family=Noto+Sans:ital@0;1&amp;family=Source+Serif+Pro:wght@600&amp;display=swap&gt;&quot; rel=&quot;stylesheet&quot;&gt;<br>        &lt;script src=&quot;&lt;https://kit.fontawesome.com/c9c493ee57.js&gt;&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;div class=&quot;container&quot;&gt;<br>            &lt;div class=&quot;row heading&quot;&gt;<br>                &lt;h1 class=&quot;text-center&quot;&gt;Glass Type Prediction&lt;/h1&gt;<br>                &lt;br&gt;<br>                &lt;p class=&quot;text-center&quot;&gt;Insert the amount of chemical elements in a glass to find out the type of it.&lt;/p&gt;<br>                &lt;br&gt;<br>                &lt;p class=&quot;text-center&quot;&gt;For example, if you insert the values as follow:&lt;/p&gt;<br>                &lt;p class=&quot;text-center&quot;&gt;Iridium : 1.51730, Sodium : 12.35, Magnesium : 2.72, Aluminium : 1.63, &lt;br&gt;Silicon : 72.87,<br>                Potassium : 0.70, Calcium : 9.23, Barium : 0.00 and Iron :	0.00&lt;/p&gt;<br>                &lt;br&gt;<br>                &lt;p class=&quot;text-center&quot;&gt;It will return the type as &#39;build wind non-float&#39;&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;form action=&quot;{{ url_for(&#39;predict&#39;)}}&quot; method=&quot;post&quot; class=&quot;form&quot;&gt;<br>                &lt;div class=&quot;row&quot;&gt;<br>                    &lt;div class=&quot;col&quot;&gt;<br>                        &lt;label class=&quot;label&quot; for=&quot;Iridium&quot;&gt;Iridium&lt;/label&gt;<br>                        &lt;br&gt;<br>                        &lt;input type=&quot;text&quot; name=&quot;Iridium&quot; id=&quot;Iridium&quot; class=&quot;text-input&quot;/&gt;<br>                        &lt;br&gt;<br>                        &lt;label class=&quot;label&quot; for=&quot;Sodium&quot;&gt;Sodium&lt;/label&gt;<br>                        &lt;br&gt;<br>                        &lt;input type=&quot;text&quot; name=&quot;Sodium&quot; id=&quot;Sodium&quot; class=&quot;text-input&quot;/&gt;<br>                        &lt;br&gt;<br>                        &lt;label class=&quot;label&quot; for=&quot;Magnesium&quot;&gt;Magnesium&lt;/label&gt;<br>                        &lt;br&gt;<br>                        &lt;input type=&quot;text&quot; name=&quot;Magnesium&quot; id=&quot;Magnesium&quot; class=&quot;text-input&quot;/&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;col&quot;&gt;<br>                        &lt;label class=&quot;label&quot; for=&quot;Aluminium&quot;&gt;Aluminium&lt;/label&gt;<br>                        &lt;br&gt;<br>                        &lt;input type=&quot;text&quot; name=&quot;Aluminium&quot; id=&quot;Aluminium&quot; class=&quot;text-input&quot;/&gt;<br>                        &lt;br&gt;<br>                        &lt;label class=&quot;label&quot; for=&quot;Silicon&quot;&gt;Silicon&lt;/label&gt;<br>                        &lt;br&gt;<br>                        &lt;input type=&quot;text&quot; name=&quot;Silicon&quot; id=&quot;Silicon&quot; class=&quot;text-input&quot;/&gt;<br>                        &lt;br&gt;<br>                        &lt;label class=&quot;label&quot; for=&quot;Potassium&quot;&gt;Potassium&lt;/label&gt;<br>                        &lt;br&gt;<br>                        &lt;input type=&quot;text&quot; name=&quot;Potassium&quot; id=&quot;Potassium&quot; class=&quot;text-input&quot;/&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;col&quot;&gt;<br>                        &lt;label class=&quot;label&quot; for=&quot;Calcium&quot;&gt;Calcium&lt;/label&gt;<br>                        &lt;br&gt;<br>                        &lt;input type=&quot;text&quot; name=&quot;Calcium&quot; id=&quot;Calcium&quot; class=&quot;text-input&quot;/&gt;<br>                        &lt;br&gt;<br>                        &lt;label class=&quot;label&quot; for=&quot;Barium&quot;&gt;Barium&lt;/label&gt;<br>                        &lt;br&gt;<br>                        &lt;input type=&quot;text&quot; name=&quot;Barium&quot; id=&quot;Barium&quot; class=&quot;text-input&quot;/&gt;<br>                        &lt;br&gt;<br>                        &lt;label class=&quot;label&quot; for=&quot;Iron&quot;&gt;Iron&lt;/label&gt;<br>                        &lt;br&gt;<br>                        &lt;input type=&quot;text&quot; name=&quot;Iron&quot; id=&quot;Iron&quot; class=&quot;text-input&quot;/&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;row&quot;&gt;{{ prediction_text }}&lt;/div&gt;<br>                &lt;div class=&quot;row&quot;&gt;<br>                    &lt;button type=&quot;submit&quot; class=&quot;btn&quot;&gt;&lt;span&gt;Predict Type&lt;/span&gt;&lt;/button&gt;<br>                &lt;/div&gt;<br>            &lt;/form&gt;<br>            &lt;div class=&quot;row footer&quot;&gt;<br>                &lt;p&gt;Image Credit: &lt;a href=&quot;: &lt;https://www.pexels.com/photo/architect-architecture-beach-bridge-262347/&gt;&quot;&gt;Pixabay on pexels.com&lt;/a&gt; &lt;/p&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>This file can contain much more complex and sophisticated code. We tried to keep things simple for this example.</p><h4>3.5 Static Folder</h4><p>In our project, we need a folder named static inside which we need a file called style.css and a folder called image. The folder will have an image named as img.jpg You can download the image from <a href="https://www.pexels.com/photo/architect-architecture-beach-bridge-262347/">Pexel</a>.</p><h4>3.5.1 style.css</h4><p>This file will contain all our CSS codes. Let’s create a style.css file and put the following in the file:</p><pre>*  <br>    { <br>    margin: 0; <br>    padding: 0; <br>    border: 0; <br>}<br>body <br>    { <br>    background-color: #000000;     <br>    text-align:center; <br>} <br>.container<br>    {  <br>    width:990px;  <br>    text-align:left;   <br>    margin-left:auto;  <br>    margin-right:auto;  <br>    background-color: #1d1d1d; <br>    color: #ffffff;<br>    height: 100%;<br>    overflow: hidden;<br>}<br>.row {<br>    width: 100%;<br>    float: left;<br>    text-align: center; <br>    margin-top: 50px;<br>}<br>.col {<br>    width: 33%;<br>    float: left;<br>    margin-left:auto;  <br>    margin-right:auto; <br>}<br>.heading {<br>    background: linear-gradient(242deg, rgb(104 0 243 / 88%), rgb(0 0 0 / 69%)), url(https://medium.com/&quot;image/img.jpg&quot;);<br>    background-repeat: no-repeat;<br>    background-size: cover;<br>    height: auto;<br>    width: 100%;<br>    padding-top: 50px;<br>    padding-bottom: 50px;<br>    margin-top: 0px;<br>}<br>.form {<br>    margin: auto;<br>}<br>.label {<br>    line-height: 2.5;<br>    font-family: &#39;Noto Sans&#39;, sans-serif;<br>    font-weight: 400;<br>    font-size: 10pt;<br>}<br>.footer {<br>    margin-bottom: 20px;<br>}<br>.footer &gt; p {<br>    font-family: &#39;Noto Sans&#39;, sans-serif;<br>    font-style: italic;<br>    font-weight: 400;<br>    font-size: 10pt;<br>    color: #ffffff;<br>}<br>.footer &gt; p &gt; a {<br>    color: #ffffff<br>}<br>h1 {<br>    color: #ffffff;<br>    font-family: &#39;Source Serif Pro&#39;, serif;<br>    font-weight: 600;<br>    font-size: 28pt;<br>}<br>p {<br>    color: #ffffff;<br>    font-family: &#39;Noto Sans&#39;, sans-serif;<br>    font-weight: 400;<br>    font-style: italic;<br>    font-size: 12pt;<br>}<br>.btn &gt; span {<br>    font-family: &#39;Source Serif Pro&#39;, serif;<br>    font-weight: 600;<br>    font-size: 11pt;<br>    text-transform: uppercase;<br>}<br>.text-left {<br>    text-align: left;<br>}<br>.text-right {<br>    text-align: right;<br>}<br>.text-center {<br>    text-align: center;<br>}<br>.btn {<br>    background-color: #6f4cff;<br>    color: #ffffff;<br>    height: 50px;<br>    width: 250px;<br>    padding: 10px;<br>    transition: 0.3s;   <br>}<br>.btn:hover {<br>    background-color: #573cc2;<br>}<br>.text-input {<br>    height: 30px;<br>    margin-bottom: 30px;<br>    padding: 5px 10px;<br>}</pre><h4><a href="http://app.py/">3.6 app.py</a></h4><p>Inside your project folder, you need a file called app.py where you need to paste the following code:</p><pre># importing all dependencies<br>import numpy as np<br>from flask import Flask, request, render_template<br>import pickle<br><br># instantiating the app<br>app = Flask(__name__)<br><br># loading the model from the model.pkl file<br>model = pickle.load(open(&quot;models/model.pkl&quot;, &quot;rb&quot;))<br><br># this is the function that the app will run at http://127.0.0.1:8000<br>@app.route(&quot;/&quot;)<br>def home():<br>    return render_template(&quot;index.html&quot;)<br><br># this is the function that the button will run<br>@app.route(&quot;/predict&quot;, methods=[&quot;POST&quot;])<br>def predict():<br>    &quot;&quot;&quot;<br>    For rendering results on HTML GUI<br>    &quot;&quot;&quot;<br>    float_features = [float(x) for x in request.form.values()]<br>    final_features = [np.array(float_features)]<br>    prediction = model.predict(final_features)<br>    output = prediction[0]<br>    return render_template(<br>        &quot;index.html&quot;, prediction_text=&quot;Glass Type: {}&quot;.format(output)<br>    )<br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(debug=True, port=8000)</pre><p>Now run app.pyby running the code in your terminal:</p><pre>python app.py</pre><p>and it will show the following in your terminal:</p><pre>* Serving Flask app<br>* Running on &lt;http://127.0.0.1:8000&gt; (Press CTRL+C to quit)</pre><p>Open the URL in your browser or click on it by pressing ctrl/cmd, it will load the app on the browser that runs the template index.html. The template contains a form for entering user input. As soon as we press the PREDICT TYPE button, the form action in our index.html file runs the predict() function from our app.py file which then takes user input through the form, and returns a prediction on the same HTML file.</p><p>With the last step, our app is ready to be deployed.</p><h3>4.0 Deployment</h3><h4>4.1 Push Your Project to GitHub</h4><p>After you test your app locally, you need to push the project to GitHub. See this article to learn how to add local files to GitHub:</p><p><a href="https://docs.github.com/en/get-started/importing-your-projects-to-github/importing-source-code-to-github/adding-locally-hosted-code-to-github">Adding locally hosted code to GitHub - GitHub Docs</a></p><h4>4.2 Deploy on Render</h4><p>Deploying on Render is not so complex. It’s a 4-step process. If you need to learn more, you can check Render’s documentation for Python: <a href="https://render.com/docs/deploy-flask">https://render.com/docs/deploy-flask</a></p><p><strong>Step 1: Create an account on Render and sign in</strong></p><p>Visit <a href="https://render.com/">https://render.com</a> and click on “Get Started for Free” to signup for a new account if you do not already have an account. If you have an account, sign in.</p><p><strong>Step 2: Create a new application</strong></p><p>Once, logged in, you’ll be taken to the dashboard (<a href="https://dashboard.render.com/">https://dashboard.render.com</a>) If this is your first time on Render, under the section “Get started in minutes”, click on <strong>New Web Service</strong>, and you’ll be taken to the page where you can connect your GitHub account to select the repository for the project. Click on <strong>+Connect Account</strong> and select all the repositories or only the repository for this project. Click on <strong>Install.</strong> You’ll be asked to confirm your password on GitHub.</p><p><strong>Step 3: Connect Your Repository</strong></p><p>You’ll be redirected to the page where you were before. But this time you’ll see your repositories in the list with the button <strong>“Connect”</strong> on the right side of them. Click on <strong>Connect</strong> beside your project and you’ll be taken to a project details page. The page will ask for the following information:</p><ol><li><em>Name: Put a relevant name for your project.</em></li><li><em>Region: Try to select the region closest to your location.</em></li><li><em>Branch: Usually Master, but you can select any other brand if you have to.</em></li><li><em>Root Directory (Optional): By default, it picks the repository’s root directory. You can leave it blank.</em></li><li><em>Environment: Choose Python 3 for this project.</em></li><li><em>Build Command: By default, it is </em><em>pip install -r requirements.txt if your requirements.txt file is named differently, you can edit the command.</em></li><li><em>Start Command: Put </em><em>gunicorn app:app Render uses </em><em>gunicorn to start the server and </em><em>app is the file name of your flask app.</em></li></ol><p>You can also choose your Instance Type for Render. Let’s pick the <strong>Free plan.</strong></p><p>Now, click on <strong>Create Web Service</strong></p><p><strong>Step 4: Deploy!</strong></p><p>You’ll be taken to a new page where you’ll see the status of your deployment. Render will install all the dependencies, generate a container image and start your web application. If there is any issue, the status will be failed otherwise, it would be <strong>OK.</strong> If a deployment fails, fix the errors, and commit the changes to the GitHub repository. Then click on <strong>Manual Deploy</strong> and select <strong>Deploy latest commit</strong> Once the status is OK, you can go to the sub-domain provided by Render at the top-left of the page, and see your newly deployed web application.</p><p>My app is running at <a href="https://glass-type-prediction.onrender.com/">https://glass-type-prediction.onrender.com</a></p><h3>5.0 Conclusion</h3><p>I hope you, now have an understanding of showcasing your Machine Learning project as a web app. If you have never deployed an app before, you’ll get comfortable with the concepts and the steps. Once that happens, you can build a more sophisticated web app by exploring more about Flask and Render. If you have any questions, please feel free to leave a comment, so I can respond quickly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=211cacfa7b44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Structure Your Data Science Projects]]></title>
            <link>https://medium.com/@taeefnajib/how-to-structure-your-data-science-projects-5d4e471970f5?source=rss-ef79c46616b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d4e471970f5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cookie-cutters]]></category>
            <category><![CDATA[project-structure]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[template]]></category>
            <dc:creator><![CDATA[Taeef Najib]]></dc:creator>
            <pubDate>Thu, 12 Jan 2023 19:55:01 GMT</pubDate>
            <atom:updated>2025-04-01T16:45:44.945Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Structure Your Data Science Projects Using Cookiecutter Templates</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-kx_cmTqr8925v3tSFdkKw.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@anete-lusina/">Anete Lusina</a> on <a href="https://www.pexels.com/photo/opened-folder-for-documents-on-table-4792288">Pexel</a></figcaption></figure><p>Data Science projects don’t have to be messy! While it takes a lot of tiresome legwork to structure your projects, it is also a part of the process that you cannot skip. Organizing your files and folders inside the project folder is probably one of the most important things you should consider even before you start working on the project. It is more true for Data Science projects. While there is no hard and fast rule for structuring your projects, many Data Scientists, Researchers and Software Engineers use the Cookiecutter Templates to cut out the templating tasks.</p><blockquote>“The golden rule is that there are no golden rules.” — George Bernard Shaw</blockquote><p>To read the full article for free, click <a href="https://medium.com/@taeefnajib/how-to-structure-your-data-science-projects-5d4e471970f5?source=friends_link&amp;sk=7df633428510c7d232c295c3f8164a51"><strong>here</strong></a></p><h4>What is Cookiecutter?</h4><p><a href="https://www.cookiecutter.io/">Cookiecutter</a> is an open source cross-platform (runs on Windows, Mac or Linux) library for building coding project templates. It takes a source directory tree and copies it into your new project. This templating library creates a skeleton or boilerplate for you, so you do not need to waste time in planning the structure of your project and doing the tidius legwork. It can generate boilerplate for any programming language or markup format: Python, JavaScript, Ruby, CoffeeScript, RST, Markdown, CSS, HTML and more.</p><h4>How to Use Cookiecutter</h4><p>First of all, you need to have <a href="https://www.python.org/">Python</a> installed in your system as it is a Python package that can be installed using pip, conda or any other package manager.</p><p>For our purpose, we are going to use pip to install Cookiecutter.</p><ol><li>Make sure you have <a href="https://pypi.org/project/pip">pip</a> installed in your system</li><li>In your terminal, run the following code:</li></ol><pre>pip install cookiecutter</pre><p>3. To use Cookiecutter, you need to pick one of its templates from the <a href="https://www.cookiecutter.io/templates">Template Library</a> or create your own template. Since this article is all about Data Science, we are going to use the <a href="https://github.com/drivendata/cookiecutter-data-science">Data Science template.</a></p><p>In your terminal, run the following command:</p><pre>cookiecutter -c v1 https://github.com/drivendata/cookiecutter-data-science</pre><p>We’re going to be asked a few questions, such as project_name, repo_name, author_name, description, etc. Give an appropriate project name, repository name, author’s name, short description. Choose which open source license you want to use. Let’s choose <a href="https://opensource.org/licenses/MIT">MIT</a>. s3_bucket is optional. Select python interpreter that you want to use. For our example, let’s choose python3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wdpu_g_iPTwRukp9SuaUig.png" /></figure><p>Once you enter all information, the project structure is going to look like this:</p><pre>├── LICENSE<br>├── Makefile           &lt;- Makefile with commands like `make data` or `make train`<br>├── README.md          &lt;- The top-level README for developers using this project.<br>├── data<br>│   ├── external       &lt;- Data from third party sources.<br>│   ├── interim        &lt;- Intermediate data that has been transformed.<br>│   ├── processed      &lt;- The final, canonical data sets for modeling.<br>│   └── raw            &lt;- The original, immutable data dump.<br>│<br>├── docs               &lt;- A default Sphinx project; see sphinx-doc.org for details<br>│<br>├── models             &lt;- Trained and serialized models, model predictions, or model summaries<br>│<br>├── notebooks          &lt;- Jupyter notebooks. Naming convention is a number (for ordering),<br>│                         the creator&#39;s initials, and a short `-` delimited description, e.g.<br>│                         `1.0-jqp-initial-data-exploration`.<br>│<br>├── references         &lt;- Data dictionaries, manuals, and all other explanatory materials.<br>│<br>├── reports            &lt;- Generated analysis as HTML, PDF, LaTeX, etc.<br>│   └── figures        &lt;- Generated graphics and figures to be used in reporting<br>│<br>├── requirements.txt   &lt;- The requirements file for reproducing the analysis environment, e.g.<br>│                         generated with `pip freeze &gt; requirements.txt`<br>│<br>├── setup.py           &lt;- makes project pip installable (pip install -e .) so src can be imported<br>├── src                &lt;- Source code for use in this project.<br>│   ├── __init__.py    &lt;- Makes src a Python module<br>│   │<br>│   ├── data           &lt;- Scripts to download or generate data<br>│   │   └── make_dataset.py<br>│   │<br>│   ├── features       &lt;- Scripts to turn raw data into features for modeling<br>│   │   └── build_features.py<br>│   │<br>│   ├── models         &lt;- Scripts to train models and then use trained models to make<br>│   │   │                 predictions<br>│   │   ├── predict_model.py<br>│   │   └── train_model.py<br>│   │<br>│   └── visualization  &lt;- Scripts to create exploratory and results oriented visualizations<br>│       └── visualize.py<br>│<br>└── tox.ini            &lt;- tox file with settings for running tox; see tox.readthedocs.io</pre><p>you, now have a nice and simple boilerplate to start working on your project with.</p><h4>Using Custom Templates</h4><p>You can customize your project structure based on your needs or create your own structure which requires a bit more know-how. You can, of course, start creating your template from scratch. But it is more convenient to use a template and edit it. For this, you need to clone a repo, such as <a href="https://github.com/audreyfeldroy/cookiecutter-pypackage">this</a> and run the following command in your terminal:</p><pre>git clone git@github.com:audreyr/cookiecutter-pypackage.git</pre><p>Once the repo is cloned, you can change the key/value pairs in the cookiecutter.json file to change the template as per your preferences.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d4e471970f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>