<?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 Mert Şükrü Pehlivan on Medium]]></title>
        <description><![CDATA[Stories by Mert Şükrü Pehlivan on Medium]]></description>
        <link>https://medium.com/@mertsukrupehlivan?source=rss-ccac642510d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VVabH8-63otGC7m9jD23qQ.jpeg</url>
            <title>Stories by Mert Şükrü Pehlivan on Medium</title>
            <link>https://medium.com/@mertsukrupehlivan?source=rss-ccac642510d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 07:19:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mertsukrupehlivan/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[Parent-Child Chunking in RAG: Searching with Small Chunks, Answering with Larger Context]]></title>
            <link>https://medium.com/@mertsukrupehlivan/parent-child-chunking-in-rag-searching-with-small-chunks-answering-with-larger-context-cc0e32053e1e?source=rss-ccac642510d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc0e32053e1e</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Mert Şükrü Pehlivan]]></dc:creator>
            <pubDate>Sat, 02 May 2026 16:12:40 GMT</pubDate>
            <atom:updated>2026-05-02T16:12:40.797Z</atom:updated>
            <content:encoded><![CDATA[<p>In many Retrieval-Augmented Generation systems, the quality of the answer depends not only on the language model, but also on how well the documents are prepared before retrieval.</p><p>This preparation step is usually called <strong>chunking</strong>.</p><p>Chunking means splitting a long document into smaller pieces so that these pieces can be embedded, stored in a vector database, and retrieved later when a user asks a question.</p><p>At first, chunking may look like a simple preprocessing step. However, in real-world RAG systems, especially when working with PDFs, contracts, policies, technical documents, or regulatory guidelines, chunking becomes one of the most important design decisions.</p><p>A poor chunking strategy can cause the system to miss relevant information, retrieve incomplete context, or generate answers that sound confident but are not properly grounded in the source document.</p><p>One effective approach to this problem is <strong>parent-child chunking</strong>.</p><p>The main idea is simple:</p><p><em>Use small chunks for accurate search, but provide larger chunks to the language model for better context.</em></p><p>In this article, we will look at what parent-child chunking is, why it is useful, how it works, and when it should be used.</p><h3>Why Chunking Matters in RAG</h3><p>A typical RAG pipeline works like this:</p><pre>Document<br> ↓<br>Chunking<br> ↓<br>Embedding<br> ↓<br>Vector Database<br> ↓<br>User Query<br> ↓<br>Retrieval<br> ↓<br>LLM Answer</pre><p>The document is not usually passed directly to the language model. Instead, it is split into smaller parts. These parts are converted into embeddings and stored in a vector database.</p><p>When a user asks a question, the system searches for the most relevant chunks and sends them to the language model as context.</p><p>This means the model can only answer well if the retrieved chunks contain enough relevant information.</p><p>If the right information is not retrieved, even the best language model may fail.</p><p>This is why chunking is not just a technical detail. It directly affects answer quality.</p><h3>The Problem with Standard Chunking</h3><p>The most common chunking strategy is to split documents into fixed-size pieces.</p><p>For example:</p><blockquote>Chunk size: 500 tokens<br>Overlap: 100 tokens</blockquote><p>This approach is simple and often works well for basic use cases. Tools like RecursiveCharacterTextSplitter in LangChain are commonly used for this purpose.</p><p>However, standard chunking has two major problems.</p><h4>Problem 1: Small Chunks Can Lose Context</h4><p>Small chunks are good for search because they are focused. A short paragraph usually represents one specific idea, so its embedding can match a user query more accurately.</p><p>However, small chunks may not contain enough context.</p><p>For example, imagine this text is split into different chunks:</p><p>The following situations are excluded from the insurance coverage.</p><p>And the next chunk contains:</p><blockquote>Damage caused by intentional actions, illegal use, or failure to follow safety instructions will not be covered.Damage by intentional actions, illegal use, or failure to follow safety instructions will not be covere</blockquote><p>If the model only receives the first chunk, it knows that exclusions exist, but it does not know what they are.</p><p>If it only receives the second chunk, it may miss the fact that these are official exclusions from the policy.</p><p>In both cases, the model receives incomplete context.</p><h4>Problem 2: Large Chunks Can Reduce Retrieval Precision</h4><p>One solution might be to use larger chunks.</p><p>For example:</p><blockquote>Chunk size: 3000 tokens</blockquote><p>This gives the language model more context. But it creates another problem.</p><p>Large chunks often contain many different topics. A single large chunk may include definitions, conditions, exclusions, examples, limits, and exceptions.</p><p>When such a large chunk is embedded, the embedding becomes less focused. As a result, semantic search may become less precise.</p><p>The vector database may fail to retrieve the right section because the meaning of the large chunk is too broad.</p><p>So we face a trade-off:</p><blockquote>Small chunks → better search, weaker context<br>Large chunks → weaker search, better context</blockquote><p>Parent-child chunking is designed to solve this trade-off.</p><h3>What Is Parent-Child Chunking?</h3><p>Parent-child chunking is a two-level chunking strategy.</p><p>Instead of splitting a document into only one type of chunk, we create two types:</p><blockquote>Parent Chunk = Larger context block<br>Child Chunk = Smaller search block</blockquote><p>The child chunks are used for embedding and retrieval.</p><p>The parent chunks are used as the final context given to the language model.</p><p>In other words:</p><blockquote>Search with child chunks.<br>Answer with parent chunks.</blockquote><p>This gives us the best of both worlds.</p><p>Child chunks are small enough to improve retrieval precision. Parent chunks are large enough to preserve context.</p><h3>Parent Chunk vs Child Chunk</h3><p>A parent chunk is a larger section of text. It may contain multiple paragraphs or a complete subsection of a document.</p><p>A child chunk is a smaller piece created from the parent chunk.</p><p>Here is the difference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*5DjXARQu3BrGafGKehpPpA.png" /></figure><p>The relationship between them is tracked using metadata.</p><p>For example:</p><pre>{<br>    &quot;child_id&quot;: &quot;child_001&quot;,<br>    &quot;parent_id&quot;: &quot;parent_001&quot;,<br>    &quot;section&quot;: &quot;Coverage Exclusions&quot;,<br>    &quot;source&quot;: &quot;policy_document.pdf&quot;<br>}</pre><p>his metadata allows the system to retrieve a child chunk first and then find its related parent chunk.</p><h3>How Parent-Child Chunking Works</h3><p>The process can be explained step by step.</p><h3>Step 1: Split the Document into Parent Chunks</h3><p>First, the document is divided into larger meaningful sections.</p><p>For example:</p><blockquote>Parent 1: General Conditions<br>Parent 2: Coverage Details<br>Parent 3: Exclusions<br>Parent 4: Claim Process</blockquote><p>Ideally, parent chunks should follow the structure of the document.</p><p>For policy documents, this could mean section-based splitting.</p><p>For technical documents, it could mean heading-based splitting.</p><p>For academic papers, it could mean splitting by abstract, introduction, methodology, results, and conclusion.</p><p>The goal is to keep related information together.</p><h3>Step 2: Split Each Parent Chunk into Child Chunks</h3><p>Each parent chunk is then split into smaller child chunks.</p><p>For example:</p><p>Parent Chunk: Coverage Details</p><blockquote>Child 1: Basic coverage explanation<br> Child 2: Coverage limits<br> Child 3: Special conditions<br> Child 4: Exceptions</blockquote><p>The child chunks are smaller and more focused.</p><p>This makes them more suitable for semantic search.</p><h3>Step 3: Embed Only the Child Chunks</h3><p>In many parent-child chunking designs, only child chunks are embedded.</p><p>The vector database stores child chunks and their metadata.</p><p>Example metadata:</p><pre>{<br>    &quot;child_id&quot;: &quot;child_034&quot;,<br>    &quot;parent_id&quot;: &quot;parent_009&quot;,<br>    &quot;document_id&quot;: &quot;doc_001&quot;,<br>    &quot;section_title&quot;: &quot;Exclusions&quot;,<br>    &quot;page_number&quot;: 12,<br>    &quot;source_file&quot;: &quot;insurance_policy.pdf&quot;<br>}</pre><p>The most important field here is parent_id.</p><p>This field connects the child chunk back to its parent.</p><h3>Step 4: Retrieve Child Chunks Based on the User Query</h3><p>When the user asks a question, the system performs vector search over the child chunks.</p><p>For example, the user asks:</p><p>Is damage covered if the vehicle key is left inside the car?</p><p>The vector database may retrieve a child chunk like this:</p><blockquote>If the vehicle key is left inside the car or the doors are not locked, the insurer may reject the claim.</blockquote><p>This child chunk is highly relevant to the question.</p><h3>Step 5: Retrieve the Parent Chunk</h3><p>After finding the relevant child chunk, the system looks at its metadata and finds the related parent chunk.</p><p>For example:</p><pre>child_metadata[&quot;parent_id&quot;] = &quot;parent_009&quot;</pre><p>The system then retrieves parent_009.</p><p>This parent chunk may contain the full exclusion section, including definitions, conditions, and exceptions.</p><p>Finally, the parent chunk is sent to the language model.</p><h3>Step 6: Generate the Answer Using Parent Context</h3><p>The language model now receives a richer context.</p><p>Instead of seeing only one small sentence, it sees the broader section where that sentence belongs.</p><p>This helps the model produce a more accurate and grounded answer.</p><p>The pipeline looks like this:</p><pre>User Query<br>   ↓<br>Search child chunks<br>   ↓<br>Find top matching child chunks<br>   ↓<br>Get their parent_id values<br>   ↓<br>Retrieve unique parent chunks<br>   ↓<br>Send parent chunks to the LLM<br>   ↓<br>Generate final answer</pre><h3>A Simple Example</h3><p>Let’s use an insurance policy example.</p><p>Assume we have this parent chunk:</p><p>Theft coverage applies when the insured vehicle is stolen or when there is an attempted theft.</p><p>However, the claim may be rejected if the vehicle key is left inside the car, if the doors are not locked, or if the insured fails to take reasonable safety measures.</p><p>This parent chunk can be split into two child chunks:</p><blockquote>Child 1:<br>Theft coverage applies when the insured vehicle is stolen or when there is an attempted theft.</blockquote><blockquote>Child 2:<br>The claim may be rejected if the vehicle key is left inside the car, if the doors are not locked, or if reasonable safety measures are not taken.</blockquote><p>Now the user asks:</p><blockquote>Will the insurance pay if I leave the key inside the car?</blockquote><p>The vector search will probably retrieve <strong>Child 2</strong>, because it directly matches the question.</p><p>But instead of sending only Child 2 to the language model, the system retrieves the full parent chunk.</p><p>This allows the model to understand both the general coverage rule and the specific exclusion.</p><p>The answer becomes more reliable.</p><h3>Why Not Just Embed Parent Chunks?</h3><p>A natural question is:</p><blockquote><em>If the parent chunk contains more context, why not just embed the parent chunk?</em></blockquote><p>The reason is retrieval precision.</p><p>A large parent chunk may contain many different topics. Its embedding represents the overall meaning of the entire block, not one specific detail.</p><p>If the user asks about a very specific condition, the parent chunk may not rank highly enough in vector search.</p><p>Child chunks solve this problem because they are smaller and more focused.</p><p>They are better search targets.</p><h3>Why Not Just Send Child Chunks to the LLM?</h3><p>Another natural question is:</p><blockquote><em>If child chunks are good for search, why not send only child chunks to the LLM?</em></blockquote><p>The answer is context.</p><p>Child chunks may contain the answer, but they may not contain the full reasoning context.</p><p>For example, a child chunk might say:</p><p>This condition is excluded from coverage.</p><p>But what does “this condition” refer to?</p><p>The explanation may exist in the previous paragraph or in the section heading.</p><p>If the LLM receives only the child chunk, it may misunderstand the meaning.</p><p>Parent chunks reduce this risk.</p><h3>Choosing Parent and Child Chunk Sizes</h3><p>There is no perfect chunk size for every project. The best values depend on the document type, embedding model, language model context window, and use case.</p><p>However, a reasonable starting point could be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*psXOVpwaZO-Mkq8nJ8dpvg.png" /></figure><p>Parent overlap100–300 tokens</p><p>For long policy or legal documents, parent chunks should usually be large enough to include a complete section or subsection.</p><p>For technical documentation, parent chunks may follow headings.</p><p>For FAQ-style content, parent-child chunking may not even be necessary because the content is already short and self-contained.</p><p>The key point is this:</p><blockquote><em>Chunk size should be tested, not guessed.</em></blockquote><p>A good RAG system should be evaluated with real questions and expected answers.</p><h3>Metadata Is Critical</h3><p>Parent-child chunking depends heavily on metadata.</p><p>Without good metadata, the system cannot reliably connect child chunks to parent chunks.</p><p>Useful metadata fields include:</p><pre>{<br>    &quot;document_id&quot;: &quot;...&quot;,<br>    &quot;parent_id&quot;: &quot;...&quot;,<br>    &quot;child_id&quot;: &quot;...&quot;,<br>    &quot;section_title&quot;: &quot;...&quot;,<br>    &quot;page_number&quot;: &quot;...&quot;,<br>    &quot;source_file&quot;: &quot;...&quot;,<br>    &quot;chunk_index&quot;: ...<br>}</pre><p>This metadata is useful for several reasons.</p><p>First, it allows the system to retrieve the correct parent chunk.</p><p>Second, it helps remove duplicate parent chunks from the final context.</p><p>Third, it supports citation and source tracking.</p><p>Fourth, it makes debugging much easier.</p><p>When a RAG answer is wrong, you can inspect which child chunks were retrieved, which parent chunks were sent to the LLM, and whether the right context was available.</p><p>In production systems, this is extremely important.</p><h3>Avoiding Duplicate Parents</h3><p>One common issue is duplicate parent retrieval.</p><p>Suppose the top 10 retrieved child chunks include several children from the same parent.</p><p>If we blindly retrieve the parent for each child, the same parent may be added to the context multiple times.</p><p>This wastes tokens and may confuse the language model.</p><p>A better approach is:</p><blockquote>Retrieve top-k child chunks<br>Get parent_id values<br>Remove duplicate parent_id values<br>Retrieve unique parent chunks<br>Send only unique parents to the LLM</blockquote><p>Example configuration:</p><pre>TOP_K_CHILDREN = 10<br>MAX_UNIQUE_PARENTS = 3<br>SCORE_THRESHOLD = 0.75</pre><p>This keeps the context focused and prevents unnecessary repetition.</p><h3>Should We Add Neighbor Chunks?</h3><p>Sometimes, even parent-child chunking may not be enough.</p><p>In some cases, the relevant information is spread across nearby child chunks.</p><p>A possible improvement is to include neighboring child chunks:</p><pre>Child i-1<br>Child i<br>Child i+1</pre><p>This can help when the text has strong paragraph-to-paragraph dependency.</p><p>However, it should be used carefully.</p><p>Adding too many neighbor chunks increases context size and may introduce irrelevant information.</p><p>For many systems, parent chunks already solve most of the context problem. Neighbor chunks should be treated as an optional improvement, not a default requirement.</p><h3>Advantages of Parent-Child Chunking</h3><p>Parent-child chunking has several important advantages.</p><h3>Better Retrieval Accuracy</h3><p>Child chunks are small and focused, so they often match user queries better than large chunks.</p><h3>Better Context for the LLM</h3><p>Parent chunks give the model enough surrounding information to understand the retrieved content properly.</p><h3>Lower Risk of Hallucination</h3><p>When the model receives better context, it is less likely to fill gaps with unsupported assumptions.</p><h3>Better Performance on Long Documents</h3><p>This approach is especially useful for PDFs, contracts, policy documents, regulations, guidelines, and technical manuals.</p><h3>Better Explainability</h3><p>With proper metadata, it becomes easier to trace an answer back to its source document, section, page, and chunk.</p><h3>Disadvantages and Trade-Offs</h3><p>Parent-child chunking is powerful, but it is not free.</p><p>It adds complexity to the pipeline.</p><p>You need to manage parent IDs, child IDs, metadata, document stores, vector stores, and retrieval logic.</p><p>It can also increase context size if too many parent chunks are passed to the language model.</p><p>Another risk is creating parent chunks that are too large. If a parent chunk contains too many unrelated topics, the LLM may lose focus.</p><p>So parent-child chunking should be designed carefully.</p><p>The goal is not to send more context.</p><p>The goal is to send the right context.</p><h3>When Should You Use Parent-Child Chunking?</h3><p>Parent-child chunking is especially useful when documents are long, structured, and context-dependent.</p><p>Good use cases include:</p><pre>Insurance policies<br>Legal contracts<br>Compliance guidelines<br>Technical documentation<br>Regulatory documents<br>Academic papers<br>Financial reports<br>Internal company procedures</pre><p>It may not be necessary for:</p><pre>Short FAQ documents<br>Small knowledge bases<br>Simple product descriptions<br>Documents where each answer is contained in one short paragraph</pre><p>In simple use cases, standard chunking may be enough.</p><p>In complex document-heavy systems, parent-child chunking can significantly improve RAG quality.</p><h3>Common Mistakes</h3><p>One common mistake is using parent-child chunking without proper metadata. If the relationship between child and parent chunks is not reliable, the whole approach becomes fragile.</p><p>Another mistake is sending too many parent chunks to the language model. More context does not always mean better answers.</p><p>A third mistake is using fixed chunk sizes without testing. Different documents require different strategies.</p><p>A fourth mistake is relying only on vector similarity. In some systems, hybrid search, keyword filtering, metadata filtering, or section-based retrieval can improve results.</p><p>Finally, many teams forget to evaluate retrieval separately from answer generation. Before blaming the LLM, we should first check whether the correct context was retrieved.</p><h3>How to Evaluate Parent-Child Chunking</h3><p>A practical evaluation table can look like this:</p><pre>Question<br>Expected source section<br>Retrieved child chunks<br>Retrieved parent chunks<br>Final answer<br>Correct / Incorrect<br>Notes</pre><p>You can compare different chunking strategies:</p><pre>Standard chunking<br>Parent-child chunking<br>Parent-child chunking with metadata filtering<br>Parent-child chunking with hybrid search</pre><p>The most important questions are:</p><pre>Did the system retrieve the correct source?<br>Did the LLM receive enough context?<br>Was the answer grounded in the document?<br>Did the system avoid irrelevant context?</pre><p>This type of evaluation is more useful than only looking at similarity scores.</p><p>A high similarity score does not always mean the retrieved context is sufficient.</p><h3>Final Thoughts</h3><p>Parent-child chunking is one of the most useful strategies for improving RAG systems that work with long and complex documents.</p><p>The idea is simple but powerful:</p><blockquote><em>Retrieve small, focused child chunks.<br> Then give the language model larger parent chunks for context.</em></blockquote><p>This approach improves both search precision and answer quality.</p><p>It helps solve one of the main problems in RAG: small chunks are good for retrieval but weak for context, while large chunks are good for context but weak for retrieval.</p><p>Parent-child chunking connects these two needs.</p><p>For real-world RAG systems, especially in legal, insurance, compliance, and technical domains, this strategy can make the difference between a system that only looks impressive and a system that actually works reliably.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc0e32053e1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Will the AI Bubble Burst — or Is This Just the Beginning?]]></title>
            <link>https://medium.com/@mertsukrupehlivan/will-the-ai-bubble-burst-or-is-this-just-the-beginning-b964507e9737?source=rss-ccac642510d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b964507e9737</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[future-technology]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Mert Şükrü Pehlivan]]></dc:creator>
            <pubDate>Sun, 14 Dec 2025 11:52:06 GMT</pubDate>
            <atom:updated>2025-12-14T11:52:06.060Z</atom:updated>
            <content:encoded><![CDATA[<h3>Will the AI Bubble Burst — or Is This Just the Beginning?</h3><p>Over the past year, artificial intelligence has gone from a promising technology to the center of global capital flows. Trillions of dollars in market value, massive GPU orders, unprecedented energy demand, and nonstop headlines have pushed one question to the forefront: <strong>Is AI a once-in-a-generation technological revolution, or are we replaying the dot-com bubble?</strong></p><p>After analyzing recent discussions and perspectives, the answer seems less binary than many think. The financial world is currently split into three camps: pessimists, optimists, and those who view AI through the lens of historical technological cycles.</p><h3><strong>1. The Pessimistic View: The “Cisco Scenario” and Pulled-Forward Demand</strong></h3><p>Skeptics often compare today’s Nvidia dominance to <strong>Cisco Systems during the dot-com era</strong>.</p><p>In the late 1990s, companies believed internet traffic would grow exponentially forever. As a result, they placed <strong>three years’ worth of hardware orders in a single year</strong>. When demand normalized, warehouses were full, orders collapsed overnight, and Cisco lost nearly <strong>88% of its market value</strong>.</p><p>The argument today is similar:</p><ul><li>Big players like Meta, OpenAI, and hyperscalers are <strong>panic-buying GPUs</strong> due to supply fears</li><li>Once capacity catches up, orders may abruptly slow</li><li>If demand has merely been pulled forward, Nvidia and the broader AI hardware ecosystem could face a sharp correction</li></ul><p>From this perspective, the current boom is fragile — built on fear of scarcity rather than sustainable end-user demand.</p><h3><strong>2. The Optimistic View: “This Time Is Different”</strong></h3><p>Optimists argue that comparing AI to the dot-com bubble misses a key distinction.</p><p>In 2000, many of the largest internet companies:</p><ul><li>Had no profits</li><li>Had unclear business models</li><li>Were valued on clicks and promises</li></ul><p>Today’s AI buyers are fundamentally different:</p><ul><li><strong>Microsoft, Google, Meta, Amazon</strong> are among the most profitable companies in history</li><li>AI systems already produce real economic output: code generation, automation, analytics, productivity gains</li><li>The industry is still in a <strong>core infrastructure-building phase</strong>, similar to electrification or cloud computing</li></ul><p>From this angle, the current spending surge isn’t excess — it’s the cost of building the foundation for a long-term transformation.</p><h3>3. The Financial Math Problem: The Ouroboros Risk</h3><p>The most uncomfortable question is not technological — it’s financial.</p><p>Today:</p><ul><li><strong>$400–500 billion</strong> is spent annually on AI infrastructure (chips, data centers, energy)</li><li>For this to make economic sense, roughly <strong>$600 billion in recurring revenue</strong> is needed</li><li>Current AI-driven revenue is estimated at <strong>~$100 billion</strong></li></ul><p>Even more concerning is <em>where</em> that revenue comes from.</p><p>Much of it is <strong>circular</strong> — an “Ouroboros” effect:</p><ul><li>Microsoft invests in OpenAI → OpenAI spends heavily on Azure → revenue flows back to Microsoft</li><li>Nvidia invests in CoreWeave → CoreWeave buys Nvidia GPUs → Nvidia books revenue</li></ul><p>This is not organic demand from the broader economy yet. The baker, the factory owner, the logistics firm — most are still experimenting, not fully transformed.</p><p>If external, non-tech demand does not scale, financial pressure will eventually surface.</p><h3>4. Two Hard Limits: Energy and Data</h3><p>Even if capital keeps flowing, AI faces <strong>physical constraints</strong>.</p><h4>Energy</h4><ul><li>AI models consume enormous amounts of electricity</li><li>Data centers can be built in ~2 years</li><li>Power grid expansion takes <strong>5–10 years</strong></li><li>By 2026, we may face a scenario where <strong>models exist, but electricity doesn’t</strong></li></ul><h4>Data</h4><ul><li>High-quality, human-generated data is finite</li><li>Estimates suggest exhaustion between <strong>2026–2028</strong></li><li>Synthetic data (AI training on AI-generated content) risks degradation — like photocopying a photocopy</li><li>Creativity, signal quality, and reliability may decay over time</li></ul><p>These are not software problems. They are structural limits.</p><h3>5. The Middle Ground: Carlota Perez and the “Golden Age” Pattern</h3><p>Economist <strong>Carlota Perez</strong> offers a framework that neatly explains what we are seeing.</p><p>Technological revolutions typically move through four stages:</p><ol><li><strong>Emergence</strong> — The breakthrough appears (e.g., ChatGPT)</li><li><strong>Frenzy</strong> — Capital floods in, valuations detach from reality</li><li><strong>Crash / Turning Point</strong> — Excess collapses, weak players fail</li><li><strong>Golden Age</strong> — Infrastructure becomes cheap and widely usable</li></ol><p>If this pattern holds, we are currently deep in the <strong>frenzy phase</strong>.</p><p>A correction around <strong>2026</strong> wouldn’t mean AI failed. It would mean the hype burned off — leaving behind cheap compute, mature infrastructure, and space for real innovation to scale.</p><p>Just as railroads didn’t disappear after their bubble burst, AI won’t either.</p><h3>Final Thought</h3><p>The most likely outcome is not “AI saves everything” nor “AI collapses.”</p><p>It’s this:</p><ul><li>A painful but necessary correction</li><li>A reset of expectations</li><li>And a far more powerful second act, driven by accessibility rather than hype</li></ul><p><strong>If the AI bubble bursts, it won’t be the end.<br> It will be the moment AI truly begins.</strong></p><p><em>Curious where you stand:<br> Are you bearish, bullish, or somewhere in between?</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b964507e9737" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparing Chunking Strategies for RAG: From Naive Splits to Striding Windows]]></title>
            <link>https://medium.com/@mertsukrupehlivan/comparing-chunking-strategies-for-rag-from-naive-splits-to-striding-windows-26a75e8ee116?source=rss-ccac642510d------2</link>
            <guid isPermaLink="false">https://medium.com/p/26a75e8ee116</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Mert Şükrü Pehlivan]]></dc:creator>
            <pubDate>Sat, 27 Sep 2025 21:59:12 GMT</pubDate>
            <atom:updated>2025-09-27T22:14:54.118Z</atom:updated>
            <content:encoded><![CDATA[<h3>Contents</h3><ol><li><strong>Introduction</strong> — Why chunking matters in Retrieval-Augmented Generation (RAG)</li><li><strong>Setup</strong> — The sample text and code environment</li><li><strong>Chunking Methods</strong></li></ol><ul><li>Naive Split</li><li>Sentence Split</li><li>Paragraph Split</li><li>Hybrid Split</li><li>Stride Split</li><li>Semantic Split</li></ul><ol><li><strong>Results and Analysis</strong> — Pros and cons of each method</li><li><strong>Comparison Table</strong> — Side-by-side evaluation of all approaches</li><li><strong>Key Takeaways</strong> — What works best in practice</li><li><strong>Conclusion</strong> — Final thoughts on chunking strategies for RAG</li></ol><h3><strong>Introduction</strong></h3><p>When building <strong>Retrieval-Augmented Generation (RAG)</strong> applications, one of the most critical design choices is <strong>how you chunk your documents</strong>. Since large language models (LLMs) cannot process arbitrarily long documents due to token limits, we must split text into smaller, meaningful units.</p><p>But here’s the catch: <strong>how</strong> you split text drastically affects retrieval quality, accuracy, and hallucination risk. In this post, we’ll explore five chunking strategies with Python examples and compare their outputs.</p><h3>Setup</h3><p>We’ll use a sample document (in this case, a research-style article) and implement different splitting strategies:</p><ul><li><strong>Naive Split</strong> — fixed-length chunks</li><li><strong>Sentence Split</strong> — break by sentences</li><li><strong>Paragraph Split</strong> — break by paragraphs</li><li><strong>Hybrid Split</strong> — paragraph-based, with a max length fallback</li><li><strong>Stride Split</strong> — sliding window with overlap</li><li><strong>Semantic Split — </strong>combining sentence meaning + chunk length</li></ul><p>Here’s the code:</p><pre>import textwrap<br>import re<br><br># -------------------------------<br># CHUNK FUNCTIONS<br># -------------------------------<br><br># 1. Naive Split (fixed length)<br>def naive_split(text, chunk_size=500):<br>    return [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]<br><br># 2. Sentence Split<br>def sentence_split(text): <br>    sentences = re.split(r&#39;(?&lt;=[.!?])\s+&#39;, text.strip())<br>    return sentences<br><br># 3. Paragraph Split<br>def paragraph_split(text):<br>    return [p.strip() for p in text.split(&quot;\n\n&quot;) if p.strip()]<br><br># 4. Hybrid Split (paragraph + length limit)<br>def hybrid_split(text, max_len=500):<br>    paras = paragraph_split(text)<br>    hybrid_chunks = []<br>    for p in paras:<br>        if len(p) &lt;= max_len:<br>            hybrid_chunks.append(p)<br>        else:<br>            hybrid_chunks.extend(textwrap.wrap(p, max_len))<br>    return hybrid_chunks<br><br># 5. Stride Split (Sliding Window with overlap)<br>def stride_split(text, chunk_size=500, overlap=100):<br>    chunks, start = [], 0<br>    while start &lt; len(text):<br>        end = start + chunk_size<br>        chunks.append(text[start:end])<br>        start += chunk_size - overlap<br>    return chunks<br><br># 6. Semantic Split (split by meaning units using sentence length merging)<br>def semantic_split(text, max_len=500):<br>    sentences = re.split(r&#39;(?&lt;=[.!?])\s+&#39;, text.strip())<br>    chunks, current_chunk = [], &quot;&quot;<br><br>    for sent in sentences:<br>        if len(current_chunk) + len(sent) &lt;= max_len:<br>            current_chunk += &quot; &quot; + sent<br>        else:<br>            chunks.append(current_chunk.strip())<br>            current_chunk = sent<br>    if current_chunk:<br>        chunks.append(current_chunk.strip())<br>    return chunks<br><br># -------------------------------<br># APPLY CHUNKING<br># -------------------------------<br>naive_chunks = naive_split(doc)<br>sentence_chunks = sentence_split(doc)<br>paragraph_chunks = paragraph_split(doc)<br>hybrid_chunks = hybrid_split(doc)<br>stride_chunks = stride_split(doc)<br>semantic_chunks = semantic_split(doc, max_len=500)<br><br># -------------------------------<br># PRINT RESULTS<br># -------------------------------<br>def print_chunks(chunks, title, max_print=2):<br>    print(&quot;=&quot;*50)<br>    print(f&quot;{title} ({len(chunks)} chunks)&quot;)<br>    print(&quot;=&quot;*50)<br>    for i, ch in enumerate(chunks[:max_print], 1):<br>        print(f&quot;\n--- Chunk {i} ---\n{ch[:1000]}...\n&quot;)<br><br>print_chunks(naive_chunks, &quot;Naive Split&quot;)<br>print_chunks(sentence_chunks, &quot;Sentence Split&quot;)<br>print_chunks(paragraph_chunks, &quot;Paragraph Split&quot;)<br>print_chunks(hybrid_chunks, &quot;Hybrid Split&quot;)<br>print_chunks(stride_chunks, &quot;Stride Split&quot;)<br>rint_chunks(semantic_chunks, &quot;Semantic Split&quot;)</pre><h3>Results and Analysis</h3><h4>1. Naive Split</h4><ul><li>Chunks are divided every 500 characters, regardless of semantic boundaries.</li><li><strong>Pros:</strong> Very simple, ensures uniform size.</li><li><strong>Cons:</strong> Splits may cut sentences in half, making embeddings less meaningful.</li></ul><h4>2. Sentence Split</h4><ul><li>Uses regex to split text into individual sentences.</li><li><strong>Pros:</strong> Preserves semantic meaning of each sentence.</li><li><strong>Cons:</strong> Too granular. Each chunk may be too small to provide useful context during retrieval.</li></ul><h4>3. Paragraph Split</h4><ul><li>Breaks text based on paragraph separators (\n\n).</li><li><strong>Pros:</strong> Natural, often aligns with logical units of meaning.</li><li><strong>Cons:</strong> Paragraphs can be very long and exceed model limits.</li></ul><h4>4. Hybrid Split</h4><ul><li>Splits by paragraph first, then enforces a maximum length.</li><li><strong>Pros:</strong> Retains natural structure while guaranteeing size control.</li><li><strong>Cons:</strong> Some splitting still may cut sentences if paragraphs are very large.</li></ul><p>This method is often the <strong>most practical for real-world RAG systems</strong>.</p><h4>5. Stride Split</h4><ul><li>Uses fixed-length chunks but introduces <strong>overlap</strong> (e.g., 500 characters with 100-character overlap).</li><li><strong>Pros:</strong> Prevents important sentences from being cut in half, ensures continuity.</li><li><strong>Cons:</strong> Increases storage and embedding costs (since overlapping text is duplicated).</li></ul><h4>6. Semantic Split</h4><ul><li>First splits by sentences, then groups them together until a maximum length is reached.</li><li><strong>Pros:</strong> Keeps chunks semantically meaningful while avoiding overly small pieces. Great balance between precision and recall.</li><li><strong>Cons:</strong> Slightly more complex implementation than naive methods; may produce variable-length chunks.</li></ul><h3>Comparison Table of Chunking Methods</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*9wIEhiPKxYpH_yPWE1ga3w.png" /></figure><h3>Key Takeaways</h3><ul><li><strong>Naive splitting</strong> is too simplistic for production.</li><li><strong>Sentence splitting</strong> is precise but impractical (too many tiny chunks).</li><li><strong>Paragraph splitting</strong> works if paragraphs are short.</li><li><strong>Hybrid splitting</strong> is usually the best balance for RAG.</li><li><strong>Stride splitting</strong> is most robust but can be costly.</li></ul><h3>Conclusion</h3><p>Chunking is not just a preprocessing detail — it’s the foundation of any <strong>retrieval-augmented generation</strong> pipeline.</p><ul><li>Bad chunking → poor retrieval → hallucinations.</li><li>Good chunking → relevant context → accurate answers.</li></ul><p>Choosing the right strategy depends on your <strong>use case, cost constraints, and document structure</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26a75e8ee116" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Sentiment Analysis Web App with Streamlit and OpenAI]]></title>
            <link>https://medium.com/@mertsukrupehlivan/build-a-sentiment-analysis-web-app-with-streamlit-and-openai-410b9fa6464c?source=rss-ccac642510d------2</link>
            <guid isPermaLink="false">https://medium.com/p/410b9fa6464c</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Mert Şükrü Pehlivan]]></dc:creator>
            <pubDate>Sat, 05 Jul 2025 17:11:03 GMT</pubDate>
            <atom:updated>2025-09-01T08:54:50.579Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/683/0*ckaP1-nNVCWeTn41.jpg" /></figure><p>Sentiment analysis is one of the most popular applications of Natural Language Processing (NLP). In this blog post, I’ll explain how to build a web app that can analyze sentiments both from a single sentence input and from entire Excel files containing multiple rows of text.</p><p>I used <strong>Streamlit</strong> for the frontend and <strong>OpenAI’s GPT model</strong> for the sentiment classification. This project is ideal for anyone looking to combine language models with an interactive Python application.</p><h3>What We’ll Build</h3><p>The application will have:</p><ul><li><strong>Two modes</strong>:</li></ul><p>Analyze a single sentence typed by the user.</p><p>Analyze all rows in an uploaded Excel file.</p><ul><li>Support for <strong>English and Turkish language options</strong>.</li><li>The ability to <strong>download results</strong> as a processed Excel file.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j92XpnW_9-6NZ46R" /></figure><h3><strong>Prerequisites</strong></h3><p>Make sure you have:</p><ul><li>An OpenAI API key.</li><li>Python 3.8+ installed.</li><li>The following packages installed:</li></ul><pre>pip install streamlit openai pandas python-dotenv openpyxl</pre><p>Create a .env file in your project folder and add your API key:</p><pre>OPENAI_API_KEY=your_openai_api_key_here</pre><h3>Code Overview</h3><h4>Environment and Initialization</h4><pre>import os<br>import streamlit as st<br>from dotenv import load_dotenv<br>from openai import OpenAI<br>import pandas as pd<br>import time<br><br># Load .env file<br>load_dotenv()<br><br># Initialize OpenAI client<br>client = OpenAI(api_key=os.getenv(&quot;OPENAI_API_KEY&quot;))</pre><p><strong>Explanation</strong>:</p><ul><li>Using dotenv to keep API keys safe</li><li>OpenAI client is created to handle all our completions.</li><li>pandas will handle data manipulation.</li></ul><h4>Streamlit Layout and Tabs</h4><pre>st.title(&quot;Sentiment Analysis Tool&quot;)<br><br>st.write(<br>    &quot;&quot;&quot;<br>    This application works in two ways:<br>    - You can analyze a single sentence.<br>    - You can upload an Excel file for batch analysis.<br>    &quot;&quot;&quot;<br>)<br><br>tab1, tab2 = st.tabs([&#39;Single Sentence Analysis&#39;, &#39;Excel File Sentiment Analysis&#39;])</pre><p><strong>Explanation</strong>:</p><ul><li>Setting a title and description.</li><li>Creating two tabs for different use cases.</li></ul><h4>Single Sentence Analysis</h4><pre>with tab1:<br>    language_selection = st.selectbox(<br>        &quot;Select a language&quot;,<br>        [&quot;English&quot;, &quot;Turkish&quot;]<br>    )<br><br>    if language_selection == &quot;Turkish&quot;:<br>        user_input = st.text_area(&quot;Please enter the text to analyze:&quot;)<br>    else:<br>        user_input = st.text_area(&quot;Please enter the text to analyze:&quot;)<br><br>    if st.button(&quot;Analyze&quot;, key=&quot;single_analysis_button&quot;):<br>        if not user_input.strip():<br>            st.warning(&quot;Please enter some text.&quot;)<br>        else:<br>            # Build prompt<br>            if language_selection == &quot;Turkish&quot;:<br>                prompt_instruction = (<br>                    &quot;Determine the sentiment of the following text and provide a confidence score.\n&quot;<br>                    &quot;Reply only in this format:\n&quot;<br>                    &quot;Sentiment: (Positive/Negative/Neutral)\n&quot;<br>                    &quot;Score: (0-100 integer)\n\n&quot;<br>                    f&quot;Text: {user_input}\n\n&quot;<br>                    &quot;Answer:&quot;<br>                )<br>                sentiment_prefix = &quot;Sentiment:&quot;<br>                score_prefix = &quot;Score:&quot;<br>            else:<br>                prompt_instruction = (<br>                    &quot;Determine the sentiment of the following text and provide a confidence score.\n&quot;<br>                    &quot;Reply only in this format:\n&quot;<br>                    &quot;Sentiment: (Positive/Negative/Neutral)\n&quot;<br>                    &quot;Score: (0-100 integer)\n\n&quot;<br>                    f&quot;Text: {user_input}\n\n&quot;<br>                    &quot;Answer:&quot;<br>                )<br>                sentiment_prefix = &quot;Sentiment:&quot;<br>                score_prefix = &quot;Score:&quot;<br><br>            prompt_text = prompt_instruction<br><br>            try:<br>                completion = client.chat.completions.create(<br>                    model=&quot;gpt-4o-mini&quot;,<br>                    messages=[<br>                        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a professional sentiment analysis expert.&quot;},<br>                        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt_text}<br>                    ],<br>                    temperature=0<br>                )<br><br>                response_text = completion.choices[0].message.content.strip()<br><br>                # Parse response<br>                lines = response_text.split(&quot;\n&quot;)<br>                sentiment_line = next(line for line in lines if line.startswith(sentiment_prefix))<br>                score_line = next(line for line in lines if line.startswith(score_prefix))<br><br>                sentiment = sentiment_line.replace(sentiment_prefix, &quot;&quot;).strip()<br>                score = score_line.replace(score_prefix, &quot;&quot;).strip()<br><br>                st.success(f&quot;Sentiment: {sentiment}&quot;)<br>                st.info(f&quot;Confidence Score: {score}/100&quot;)<br><br>            except Exception as e:<br>                st.error(f&quot;Failed to parse response. Raw response: {response_text}&quot;)</pre><p><strong>Explanation</strong>:</p><ul><li>The prompt clearly instructs GPT to answer in a strict format.</li><li>After the response, I split by lines and extract sentiment and score.</li><li>Results were displayed in the UI.</li></ul><h4>Excel File Batch Analysis</h4><pre>with tab2:<br>    uploaded_file = st.file_uploader(&quot;Upload your Excel file&quot;, type=[&quot;xlsx&quot;])<br><br>    if uploaded_file is not None:<br>        df = pd.read_excel(uploaded_file)<br><br>        st.write(&quot;Uploaded File:&quot;)<br>        st.dataframe(df.head())<br><br>        column_name = st.selectbox(<br>            &quot;Select the column to analyze&quot;,<br>            df.columns<br>        )<br><br>        if st.button(&quot;Analyze all rows&quot;):<br>            texts = df[column_name].fillna(&quot;&quot;).astype(str).tolist()<br>            sentiments = []<br>            scores = []<br><br>            progress_bar = st.progress(0)<br>            status_text = st.empty()<br><br>            for idx, text in enumerate(texts):<br>                prompt_text = (<br>                    &quot;Determine the sentiment of the following text and provide a confidence score.\n&quot;<br>                    &quot;Reply only in this format:\n&quot;<br>                    &quot;Sentiment: (Positive/Negative/Neutral)\n&quot;<br>                    &quot;Score: (0-100 integer)\n\n&quot;<br>                    f&quot;Text: {text}\n\n&quot;<br>                    &quot;Answer:&quot;<br>                )<br><br>                try:<br>                    completion = client.chat.completions.create(<br>                        model=&quot;gpt-4o-mini&quot;,<br>                        messages=[<br>                            {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a professional sentiment analysis expert.&quot;},<br>                            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt_text}<br>                        ],<br>                        temperature=0<br>                    )<br><br>                    response_text = completion.choices[0].message.content.strip()<br><br>                    lines = response_text.split(&quot;\n&quot;)<br>                    sentiment_line = next(line for line in lines if line.startswith(&quot;Sentiment:&quot;))<br>                    score_line = next(line for line in lines if line.startswith(&quot;Score:&quot;))<br><br>                    sentiment = sentiment_line.replace(&quot;Sentiment:&quot;, &quot;&quot;).strip()<br>                    score = score_line.replace(&quot;Score:&quot;, &quot;&quot;).strip()<br><br>                except Exception as e:<br>                    sentiment = &quot;Error&quot;<br>                    score = &quot;Error&quot;<br>                    st.error(f&quot;Error on row {idx+1}: {e}&quot;)<br><br>                sentiments.append(sentiment)<br>                scores.append(score)<br><br>                progress_bar.progress((idx + 1) / len(texts))<br>                status_text.text(f&quot;Analyzed {idx + 1}/{len(texts)} rows.&quot;)<br>                time.sleep(0.2)<br><br>            df[&#39;Sentiment&#39;] = sentiments<br>            df[&#39;Score&#39;] = scores<br><br>            st.success(&quot;Batch analysis completed.&quot;)<br>            st.dataframe(df)<br><br>            # Download button<br>            from io import BytesIO<br>            buffer = BytesIO()<br>            df.to_excel(buffer, index=False, engine=&quot;openpyxl&quot;)<br>            buffer.seek(0)<br><br>            st.download_button(<br>                label=&quot;Download results as Excel&quot;,<br>                data=buffer,<br>                file_name=&quot;sentiment_analysis_results.xlsx&quot;,<br>                mime=&quot;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&quot;<br>            )</pre><p><strong>Explanation</strong>:</p><ul><li>Users upload an Excel file and pick the text column.</li><li>Each row is sent to the model individually.</li><li>Results are appended to the DataFrame.</li><li>A progress bar shows real-time status.</li><li>Users can download the final Excel report.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*UJCyegojHthAzfCdI0NPkg.png" /></figure><h3>Final Thoughts</h3><p>This project is a great example of how you can combine <strong>Streamlit</strong> and <strong>OpenAI’s GPT models</strong> to create a practical, user-friendly application. Even with just a few hundred lines of Python, you can build a powerful tool that helps you understand the emotional tone of any text — whether it’s a short message or an entire dataset.</p><p>Here are some things to keep in mind as you experiment further:</p><ul><li><strong>Start Small</strong><br> Always test your app with a few sentences to make sure your prompts and parsing logic work correctly.</li><li><strong>Keep Prompts Simple</strong><br> Clear and consistent instructions to the model are essential. If your output format changes unexpectedly, adjust the prompt wording or add stricter parsing.</li><li><strong>Watch Your Usage</strong><br> Processing many rows in a file will make many API calls. Keep an eye on your OpenAI usage to avoid surprises on your bill.</li><li><strong>Customize and Expand</strong><br> You could easily extend this app to detect other attributes — like language detection, text summarization, or topic classification — by updating the prompt and column names.</li><li><strong>Make It Your Own</strong><br> Streamlit makes it easy to customize the interface. Try adding colors, charts, or additional output columns to make your results more visually appealing.</li></ul><p><strong>Tip</strong>: Always monitor your OpenAI API usage carefully, especially when processing large datasets.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=410b9fa6464c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-World Data Science vs. Kaggle: Bridging the Expectation Gap]]></title>
            <link>https://medium.com/@mertsukrupehlivan/real-world-data-science-vs-kaggle-bridging-the-expectation-gap-4b6cb5a7ce29?source=rss-ccac642510d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b6cb5a7ce29</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Mert Şükrü Pehlivan]]></dc:creator>
            <pubDate>Sun, 08 Jun 2025 16:46:15 GMT</pubDate>
            <atom:updated>2025-06-08T16:46:15.672Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>If you’ve ever participated in a Kaggle competition and then transitioned into a data science role in the real world, you probably felt the jarring difference between the two. Kaggle is a fantastic platform to hone your machine learning skills, but it doesn’t reflect the full complexity of working with data in industry. This article explores the key differences between Kaggle and real-world data science — and what skills you truly need to thrive as a professional.</p><h3>🤔 1. The Dataset is (Almost) Never Clean</h3><p><strong>Kaggle</strong>: Datasets are typically clean and ready for modeling. Columns are neatly named, missing values are rare, and data leakage is avoided.</p><p><strong>Real World</strong>:</p><ul><li>You may have missing, inconsistent, or duplicated records.</li><li>Feature names can be cryptic or poorly documented.</li><li>Labels may be incomplete, delayed, or wrong.</li></ul><blockquote><strong><em>Visual Suggestion</em></strong><em>: Side-by-side screenshot of a Kaggle dataset and a real-world dataset with missing values and inconsistent formats.</em></blockquote><blockquote><strong><em>Real-world skill</em></strong><em>: Mastering data cleaning, validation, and robust preprocessing pipelines.</em></blockquote><h3>🔍 2. The Problem is Not Well-Defined</h3><p><strong>Kaggle</strong>: You know exactly what you’re optimizing for — be it RMSE, AUC, or F1-score.</p><p><strong>Real World</strong>:</p><ul><li>Business goals may be ambiguous or evolving.</li><li>You may have to define the target variable.</li><li>Metrics may differ based on constraints.</li></ul><blockquote><strong><em>Visual Suggestion</em></strong><em>: Flowchart showing transition from vague business goal to a concrete ML objective.</em></blockquote><blockquote><strong><em>Real-world skill</em></strong><em>: Translating business goals into data problems and selecting the right metrics.</em></blockquote><h3>📈 3. There’s No Leaderboard in Real Life</h3><p><strong>Kaggle</strong>: Leaderboards give instant feedback.</p><p><strong>Real World</strong>:</p><ul><li>Ground truth might arrive months later.</li><li>A/B tests are needed to validate models.</li><li>Small gains can have big impacts.</li></ul><blockquote><strong><em>Visual Suggestion</em></strong><em>: Comparison of Kaggle leaderboard vs. business KPI dashboard.</em></blockquote><blockquote><strong><em>Real-world skill</em></strong><em>: Experimentation and dealing with uncertainty.</em></blockquote><h3>🧩 4. Feature Engineering &gt; Model Tuning</h3><p><strong>Kaggle</strong>: Intricate model tuning (XGBoost, LightGBM).</p><p><strong>Real World</strong>:</p><ul><li>Meaningful features &gt; complex models.</li><li>Domain expertise trumps brute force.</li></ul><blockquote><strong><em>Visual Suggestion</em></strong><em>: Bar chart comparing model performance with vs. without manual feature engineering.</em></blockquote><blockquote><strong><em>Real-world skill</em></strong><em>: Understanding domain context and crafting quality features.</em></blockquote><h3>🛠️ 5. Deployment is a First-Class Citizen</h3><p><strong>Kaggle</strong>: Job ends after model submission.</p><p><strong>Real World</strong>:</p><ul><li>Model versioning and monitoring matter.</li><li>Deployment must be scalable and reliable.</li><li>Integration with APIs/databases is key.</li></ul><blockquote><strong><em>Visual Suggestion</em></strong><em>: Diagram of a basic MLOps pipeline (training → deployment → monitoring).</em></blockquote><blockquote><strong><em>Real-world skill</em></strong><em>: MLOps, reproducibility, and system design.</em></blockquote><h3>💬 6. Collaboration and Communication Are Key</h3><p><strong>Kaggle</strong>: Mostly solo efforts.</p><p><strong>Real World</strong>:</p><ul><li>Teams include engineers, PMs, and stakeholders.</li><li>Communication is as important as modeling.</li></ul><blockquote><strong><em>Visual Suggestion</em></strong><em>: Org chart showing cross-functional data team.</em></blockquote><blockquote><strong><em>Real-world skill</em></strong><em>: Documentation, stakeholder alignment, and teamwork.</em></blockquote><h3>📊 Conclusion</h3><p>Kaggle is a great sandbox for technical skill development. But real-world data science is a multidisciplinary, messy, and iterative process that requires not just modeling skills, but also communication, problem definition, and deployment know-how. Embrace the chaos — because that’s where the real impact happens.</p><h3>📍 Call to Action</h3><p>If you’re transitioning from Kaggle to a data science job, start focusing on the bigger picture. Get familiar with messy data, unclear objectives, and cross-functional dynamics. And remember: solving <em>real</em> problems is always more rewarding than climbing a leaderboard.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b6cb5a7ce29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protecting Sensitive Data with Microsoft Presidio]]></title>
            <link>https://medium.com/@mertsukrupehlivan/protecting-sensitive-data-with-microsoft-presidio-84760d0b9274?source=rss-ccac642510d------2</link>
            <guid isPermaLink="false">https://medium.com/p/84760d0b9274</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[data-protection]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Mert Şükrü Pehlivan]]></dc:creator>
            <pubDate>Mon, 03 Mar 2025 18:35:41 GMT</pubDate>
            <atom:updated>2025-03-03T18:35:41.459Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s world, where data privacy and security are critical, organizations must ensure that personally identifiable information (PII) is protected. Microsoft Presidio is an <strong>open-source privacy-preserving text analysis and anonymization tool</strong> designed to identify and mask sensitive data, such as names, phone numbers, emails, and addresses.</p><p>Presidio is particularly useful in industries like <strong>healthcare, finance, and customer support</strong>, where handling sensitive data is unavoidable. By automating the detection and anonymization of PII, Presidio helps organizations comply with <strong>GDPR, CCPA, and other data protection regulations</strong>.</p><h3>How Microsoft Presidio Works</h3><p>Microsoft Presidio consists of two main components:</p><ol><li><strong>Presidio Analyzer</strong>: Identifies sensitive information in unstructured text using NLP models.</li><li><strong>Presidio Anonymizer</strong>: Replaces or masks the identified PII with placeholders, ensuring data privacy.</li></ol><h3>Key Features:</h3><ul><li>Prebuilt NLP models for detecting common PII entities like names, locations, phone numbers, and emails.</li><li>Custom recognizers to detect domain-specific sensitive information.</li><li>Supports multiple languages.</li><li>Flexible anonymization techniques, including redaction, replacement, and hashing.</li></ul><h3>Hands-On with Presidio</h3><p>Let’s walk through a simple Python script that detects and anonymizes PII in a given text using <strong>Presidio Analyzer and Anonymizer</strong>.</p><h3>Installation</h3><pre>pip install presidio-analyzer presidio-anonymizer</pre><h3>Python Code for PII Detection and Anonymization</h3><pre>from presidio_analyzer import AnalyzerEngine<br>from presidio_anonymizer import AnonymizerEngine<br>import warnings<br>import logging<br><br>warnings.filterwarnings(&#39;ignore&#39;)<br>logging.getLogger(&quot;presidio-analyzer&quot;).setLevel(logging.ERROR)<br><br>text = &quot;My name is John Doe, and I live in New York. I work at OpenAI as a research scientist. &quot; \<br>       &quot;You can contact me via email at john.doe@example.com or call me at 212-555-5555. &quot; \<br>       &quot;I was born on January 15, 1985, in Los Angeles, but I moved to New York in 2010.&quot;<br><br># Set up the engine<br>analyzer = AnalyzerEngine()<br><br># Analyze text for sensitive information<br>results = analyzer.analyze(text=text,<br>                           entities=[&quot;PHONE_NUMBER&quot;, &quot;PERSON&quot;, &quot;LOCATION&quot;, &quot;EMAIL_ADDRESS&quot;],<br>                           language=&#39;en&#39;)<br><br># Initialize anonymizer<br>anonymizer = AnonymizerEngine()<br>anonymized_text = anonymizer.anonymize(text=text, analyzer_results=results)<br><br># Generate text with entity labels (e.g., John Doe&lt;PERSON&gt;)<br>text_with_labels = text<br>for res in sorted(results, key=lambda x: x.start, reverse=True):<br>    text_with_labels = (text_with_labels[:res.end] + f&quot;&lt;{res.entity_type}&gt;&quot; +<br>                        text_with_labels[res.end:])<br><br># Print outputs<br>print(&quot;Detected Entities:&quot;, results)<br>print(&quot;Anonymized Text:&quot;, anonymized_text.text)<br>print(&quot;Text with Entity Labels:&quot;, text_with_labels)<br>print(&quot;Anonymized Items:&quot;, anonymized_text.items)</pre><h3>Output</h3><h4>Detected Entities:</h4><pre>[type: EMAIL_ADDRESS, start: 118, end: 138, score: 1.0]<br>[type: PERSON, start: 11, end: 19, score: 0.85]<br>[type: LOCATION, start: 35, end: 43, score: 0.85]<br>[type: LOCATION, start: 201, end: 212, score: 0.85]<br>[type: LOCATION, start: 229, end: 237, score: 0.85]<br>[type: PHONE_NUMBER, start: 153, end: 165, score: 0.4]</pre><h4>Anonymized Text:</h4><pre>My name is &lt;PERSON&gt;, and I live in &lt;LOCATION&gt;. I work at OpenAI as a research scientist.<br>You can contact me via email at &lt;EMAIL_ADDRESS&gt; or call me at &lt;PHONE_NUMBER&gt;.<br>I was born on January 15, 1985, in &lt;LOCATION&gt;, but I moved to &lt;LOCATION&gt; in 2010.</pre><h4>Text with Entity Labels:</h4><pre>My name is John Doe&lt;PERSON&gt;, and I live in New York&lt;LOCATION&gt;.<br>I work at OpenAI as a research scientist.<br>You can contact me via email at john.doe@example.com&lt;EMAIL_ADDRESS&gt; or call me at 212-555-5555&lt;PHONE_NUMBER&gt;.<br>I was born on January 15, 1985, in Los Angeles&lt;LOCATION&gt;, but I moved to New York&lt;LOCATION&gt; in 2010.</pre><h4>Anonymized Items:</h4><pre>[<br>    {&#39;start&#39;: 227, &#39;end&#39;: 237, &#39;entity_type&#39;: &#39;LOCATION&#39;, &#39;text&#39;: &#39;&lt;LOCATION&gt;&#39;, &#39;operator&#39;: &#39;replace&#39;},<br>    {&#39;start&#39;: 200, &#39;end&#39;: 210, &#39;entity_type&#39;: &#39;LOCATION&#39;, &#39;text&#39;: &#39;&lt;LOCATION&gt;&#39;, &#39;operator&#39;: &#39;replace&#39;},<br>    {&#39;start&#39;: 150, &#39;end&#39;: 164, &#39;entity_type&#39;: &#39;PHONE_NUMBER&#39;, &#39;text&#39;: &#39;&lt;PHONE_NUMBER&gt;&#39;, &#39;operator&#39;: &#39;replace&#39;},<br>    {&#39;start&#39;: 120, &#39;end&#39;: 135, &#39;entity_type&#39;: &#39;EMAIL_ADDRESS&#39;, &#39;text&#39;: &#39;&lt;EMAIL_ADDRESS&gt;&#39;, &#39;operator&#39;: &#39;replace&#39;},<br>    {&#39;start&#39;: 35, &#39;end&#39;: 45, &#39;entity_type&#39;: &#39;LOCATION&#39;, &#39;text&#39;: &#39;&lt;LOCATION&gt;&#39;, &#39;operator&#39;: &#39;replace&#39;},<br>    {&#39;start&#39;: 11, &#39;end&#39;: 19, &#39;entity_type&#39;: &#39;PERSON&#39;, &#39;text&#39;: &#39;&lt;PERSON&gt;&#39;, &#39;operator&#39;: &#39;replace&#39;}<br>]</pre><h3>Using Presidio with a NER Model</h3><p>Presidio allows integration with <strong>custom Named Entity Recognition (NER) models</strong> for more advanced entity detection. Below is an example of using <strong>spaCy</strong> as a custom NER model with Presidio.</p><h3>Installation</h3><pre>pip install spacy<br>python -m spacy download en_core_web_sm</pre><h3>Python Code with spaCy NER</h3><pre>from presidio_analyzer.nlp_engine import SpacyNlpEngine<br>from presidio_analyzer import AnalyzerEngine<br><br># Set up spaCy NLP engine<br>nlp_engine = SpacyNlpEngine(models={&#39;en&#39;: &#39;en_core_web_sm&#39;})<br>analyzer = AnalyzerEngine(nlp_engine=nlp_engine, supported_languages=[&quot;en&quot;])<br><br># Analyze text with spaCy-based Presidio<br>results = analyzer.analyze(text=text, language=&#39;en&#39;)<br><br>print(&quot;Detected Entities:&quot;, results)</pre><h3>Using Presidio with a BERT-based NER Model</h3><p>Presidio allows integration with <strong>custom Named Entity Recognition (NER) models</strong> such as <strong>BERT</strong> for more accurate and domain-specific entity detection. Below is an example using a pre-trained <strong>Hugging Face BERT model</strong> to detect PII before anonymization.</p><pre>pip install transformers torch presidio-analyzer presidio-anonymizer</pre><h3>Python Code for BERT-based PII Detection</h3><pre>from transformers import pipeline<br>from presidio_analyzer import AnalyzerEngine, RecognizerResult, EntityRecognizer<br><br># Load a pre-trained BERT NER model from Hugging Face<br>ner_pipeline = pipeline(&quot;ner&quot;, model=&quot;dbmdz/bert-large-cased-finetuned-conll03-english&quot;, aggregation_strategy=&quot;simple&quot;)<br><br>def custom_ner_recognizer(text):<br>    entities = []<br>    for entity in ner_pipeline(text):<br>        entities.append(<br>            RecognizerResult(entity_type=entity[&quot;entity_group&quot;],<br>                             start=entity[&quot;start&quot;],<br>                             end=entity[&quot;end&quot;],<br>                             score=entity[&quot;score&quot;])<br>        )<br>    return entities<br><br># Initialize Presidio Analyzer<br>analyzer = AnalyzerEngine()<br><br># Custom NER-based entity detection<br>text = &quot;My name is Alice Johnson, and I live in San Francisco. My email is alice.j@example.com.&quot;<br>results = custom_ner_recognizer(text)<br><br>print(&quot;Detected Entities:&quot;, results)</pre><h3>Output</h3><pre>Detected Entities: [<br>    RecognizerResult(entity_type=&#39;PER&#39;, start=11, end=24, score=0.99),<br>    RecognizerResult(entity_type=&#39;LOC&#39;, start=42, end=55, score=0.98),<br>    RecognizerResult(entity_type=&#39;EMAIL_ADDRESS&#39;, start=67, end=89, score=1.00)<br>]</pre><h3>Adding Custom Recognizers in Presidio</h3><p>Microsoft Presidio allows users to add custom entity recognizers to detect domain-specific PII. This can be useful for detecting sensitive terms that are not covered by default recognizers.</p><h3>Example of Adding a Custom Recognizer</h3><pre>from presidio_analyzer import Pattern, PatternRecognizer<br><br># Define a custom recognizer for detecting Employee IDs<br>employee_id_recognizer = PatternRecognizer(supported_entity=&quot;EMPLOYEE_ID&quot;,<br>                                           patterns=[Pattern(&quot;\bEMP[0-9]{4}\b&quot;, score=0.9)])<br><br># Add the custom recognizer to the analyzer<br>analyzer.registry.add_recognizer(employee_id_recognizer)</pre><p>This allows Presidio to detect and anonymize custom-defined sensitive entities, improving flexibility for various use cases.</p><h3>Conclusion</h3><p>Microsoft Presidio is a robust tool for detecting and anonymizing sensitive information, making it invaluable for organizations dealing with PII. By integrating it with custom recognizers and advanced NER models like BERT, users can achieve even greater accuracy in entity detection. Whether used standalone or with deep learning models, Presidio helps ensure <strong>data privacy, regulatory compliance, and secure data handling</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84760d0b9274" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Imbalanced Datasets in Machine Learning]]></title>
            <link>https://medium.com/@mertsukrupehlivan/handling-imbalanced-datasets-in-machine-learning-9763e8fb0ccb?source=rss-ccac642510d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9763e8fb0ccb</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Mert Şükrü Pehlivan]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 23:17:37 GMT</pubDate>
            <atom:updated>2024-12-23T23:17:37.008Z</atom:updated>
            <content:encoded><![CDATA[<p>Imbalanced datasets are a common challenge in machine learning, particularly in classification tasks where the distribution of classes is highly skewed. For instance, in fraud detection, the number of fraudulent transactions is often much smaller than non-fraudulent ones. This article will explore strategies to handle imbalanced datasets effectively, using Python code to illustrate key techniques.</p><h3>Understanding the Problem</h3><p>An imbalanced dataset occurs when one class significantly outnumbers the other(s). This imbalance can lead to biased models that perform well on the majority class while neglecting the minority class. A model trained on such data might achieve high overall accuracy but fail to correctly classify minority class instances, which are often the most critical.</p><h3>Techniques to Handle Imbalanced Datasets</h3><h4>1. Resampling Methods</h4><ul><li><strong>Oversampling the Minority Class</strong>: Adds more instances to the minority class.</li><li><strong>Undersampling the Majority Class</strong>: Removes instances from the majority class.</li></ul><p><em>Code Example: Oversampling with SMOTE</em></p><pre>from imblearn.over_sampling import SMOTE<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import classification_report<br><br># Example Dataset<br>X, y = load_data()  # Replace with your dataset<br># Split the dataset<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)<br># Apply SMOTE<br>smote = SMOTE(random_state=42)<br>X_train_resampled, y_train_resampled = smote.fit_resample(X_train, y_train)<br># Train the model<br>clf = RandomForestClassifier(random_state=42)<br>clf.fit(X_train_resampled, y_train_resampled)<br># Evaluate<br>predictions = clf.predict(X_test)<br>print(classification_report(y_test, predictions))</pre><h4>2. Class Weighting</h4><p>Many machine learning algorithms, like logistic regression or tree-based models, allow you to specify class weights to penalize misclassification of minority classes more heavily.</p><p><em>Code Example: Using Class Weights in Scikit-Learn</em></p><pre>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import classification_report<br><br>#Train with class weights<br>clf = RandomForestClassifier(class_weight={0: 1, 1: 10}, random_state=42)  # Adjust weights as needed<br>clf.fit(X_train, y_train)<br># Evaluate<br>predictions = clf.predict(X_test)<br>print(classification_report(y_test, predictions))</pre><h4>3. Evaluation Metrics</h4><p>Accuracy is not a reliable metric for imbalanced datasets. Instead, consider:</p><ul><li>Precision, Recall, and F1-Score</li><li>Area Under the Precision-Recall Curve (PR AUC)</li><li>Matthews Correlation Coefficient (MCC)</li></ul><p><em>Code Example: Evaluating Metrics</em></p><pre>from sklearn.metrics import precision_recall_curve, roc_auc_score, f1_score<br><br># Evaluate metrics<br>precision, recall, _ = precision_recall_curve(y_test, predictions)<br>auc = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1])<br>f1 = f1_score(y_test, predictions, average=&#39;weighted&#39;)<br>print(f&quot;Precision-Recall AUC: {auc}&quot;)<br>print(f&quot;F1 Score: {f1}&quot;)</pre><h4>4. Using Tree-Based Algorithms</h4><p>Tree-based algorithms, like XGBoost or LightGBM, handle imbalanced datasets well by allowing for customized loss functions or built-in options to adjust class weights.</p><p><em>Code Example: XGBoost</em></p><pre>from xgboost import XGBClassifier<br># Train XGBoost with scale_pos_weight<br>clf = XGBClassifier(scale_pos_weight=10, random_state=42)  # Adjust scale_pos_weight based on class distribution<br>clf.fit(X_train, y_train)<br># Evaluate<br>predictions = clf.predict(X_test)<br>print(classification_report(y_test, predictions))</pre><h3>Best Practices</h3><ul><li><strong>Understand the Dataset</strong>: Explore the class distribution and domain-specific importance of classes.</li><li><strong>Experiment with Multiple Techniques</strong>: No single method works best for all scenarios.</li><li><strong>Combine Methods</strong>: For example, use SMOTE with class-weighted models.</li><li><strong>Use Robust Metrics</strong>: Ensure you’re optimizing for metrics that reflect the problem’s objectives.</li></ul><p>Handling imbalanced datasets requires a thoughtful approach. By applying these techniques and evaluating the model’s performance with appropriate metrics, you can create robust models that perform well across all classes.</p><p>Feel free to adapt the code and techniques based on your specific dataset and problem!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9763e8fb0ccb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Principal Component Analysis in Machine Learning: A Comprehensive Guide]]></title>
            <link>https://medium.com/@mertsukrupehlivan/principal-component-analysis-in-machine-learning-a-comprehensive-guide-7872f4756261?source=rss-ccac642510d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7872f4756261</guid>
            <category><![CDATA[pca-analysis]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Mert Şükrü Pehlivan]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 23:14:02 GMT</pubDate>
            <atom:updated>2024-10-28T23:14:02.650Z</atom:updated>
            <content:encoded><![CDATA[<p>Principal Component Analysis (PCA) is a powerful technique in the field of machine learning and data science. It’s widely used for dimensionality reduction, data compression, and feature extraction. In this comprehensive guide, we’ll dive deep into the theory behind PCA, its mathematical foundations, and provide a step-by-step implementation in Python.</p><h3>Table of Contents</h3><ol><li>Introduction to PCA</li><li>Mathematical Foundations</li><li>The PCA Algorithm</li><li>Implementing PCA in Python</li><li>Practical Examples</li><li>Advantages and Limitations of PCA</li><li>Conclusion</li></ol><h3>1. Introduction to PCA</h3><p>Principal Component Analysis (PCA) is an unsupervised learning algorithm that aims to reduce the dimensionality of a dataset while retaining as much of the original variability as possible. It does this by identifying the principal components — the directions in the feature space along which the data varies the most.</p><p>The primary goals of PCA are:</p><ul><li>Dimensionality reduction</li><li>Feature extraction</li><li>Data visualization</li><li>Noise reduction</li></ul><h3>2. Mathematical Foundations</h3><p>To understand PCA, we need to grasp a few key mathematical concepts:</p><h4>2.1 Variance and Covariance</h4><p>Variance measures the spread of a single variable, while covariance measures the relationship between two variables.</p><p>For a dataset X with n features, the covariance matrix C is defined as:</p><p>C = (1 / (n-1)) * (X — μ)^T * (X — μ)</p><p>Where μ is the mean vector of X.</p><h4>2.2 Eigenvectors and Eigenvalues</h4><p>For a square matrix A, if there exists a vector v and a scalar λ such that:</p><p>Av = λv</p><p>Then v is called an eigenvector of A, and λ is the corresponding eigenvalue.</p><h4>2.3 Singular Value Decomposition (SVD)</h4><p>SVD is a matrix factorization method that decomposes a matrix X into three matrices:</p><p>X = UΣV^T</p><p>Where U and V are orthogonal matrices, and Σ is a diagonal matrix of singular values.</p><h3>3. The PCA Algorithm</h3><p>The PCA algorithm can be broken down into the following steps:</p><ol><li>Standardize the dataset</li><li>Compute the covariance matrix</li><li>Calculate the eigenvectors and eigenvalues of the covariance matrix</li><li>Sort the eigenvectors by decreasing eigenvalues</li><li>Choose k eigenvectors as the new features</li><li>Transform the original dataset</li></ol><h3>4. Implementing PCA in Python</h3><p>Let’s implement PCA from scratch in Python, and then compare it with scikit-learn’s implementation.</p><h4>4.1 PCA from Scratch</h4><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.datasets import load_iris<br><br>def pca_from_scratch(X, n_components):<br>    # Step 1: Standardize the dataset<br>    X_std = (X - np.mean(X, axis=0)) / np.std(X, axis=0)<br>    <br>    # Step 2: Compute the covariance matrix<br>    cov_matrix = np.cov(X_std.T)<br>    <br>    # Step 3: Calculate eigenvectors and eigenvalues<br>    eigenvalues, eigenvectors = np.linalg.eig(cov_matrix)<br>    <br>    # Step 4: Sort eigenvectors by decreasing eigenvalues<br>    idx = eigenvalues.argsort()[::-1]<br>    eigenvalues = eigenvalues[idx]<br>    eigenvectors = eigenvectors[:, idx]<br>    <br>    # Step 5: Choose k eigenvectors as the new features<br>    k_eigenvectors = eigenvectors[:, :n_components]<br>    <br>    # Step 6: Transform the original dataset<br>    return np.dot(X_std, k_eigenvectors)<br><br># Load the Iris dataset<br>iris = load_iris()<br>X = iris.data<br>y = iris.target<br><br># Apply PCA<br>X_pca = pca_from_scratch(X, n_components=2)<br><br># Plot the results<br>plt.figure(figsize=(8, 6))<br>scatter = plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y, cmap=&#39;viridis&#39;)<br>plt.colorbar(scatter)<br>plt.xlabel(&#39;First Principal Component&#39;)<br>plt.ylabel(&#39;Second Principal Component&#39;)<br>plt.title(&#39;PCA of Iris Dataset&#39;)<br>plt.show()</pre><h4>4.2 PCA using scikit-learn</h4><p>Now, let’s use scikit-learn’s implementation for comparison:</p><pre>from sklearn.decomposition import PCA<br>from sklearn.preprocessing import StandardScaler<br><br># Standardize the data<br>scaler = StandardScaler()<br>X_std = scaler.fit_transform(X)<br><br># Apply PCA<br>pca = PCA(n_components=2)<br>X_pca_sklearn = pca.fit_transform(X_std)<br><br># Plot the results<br>plt.figure(figsize=(8, 6))<br>scatter = plt.scatter(X_pca_sklearn[:, 0], X_pca_sklearn[:, 1], c=y, cmap=&#39;viridis&#39;)<br>plt.colorbar(scatter)<br>plt.xlabel(&#39;First Principal Component&#39;)<br>plt.ylabel(&#39;Second Principal Component&#39;)<br>plt.title(&#39;PCA of Iris Dataset (scikit-learn)&#39;)<br>plt.show()<br><br># Print the explained variance ratio<br>print(&quot;Explained Variance Ratio:&quot;, pca.explained_variance_ratio_)</pre><h3>5. Practical Examples</h3><p>Let’s explore some practical applications of PCA:</p><h4>5.1 Dimensionality Reduction for Visualization</h4><p>We’ve already seen how PCA can be used to visualize high-dimensional data in 2D or 3D space. This is particularly useful for exploratory data analysis.</p><h4>5.2 Feature Selection</h4><p>PCA can be used to identify the most important features in a dataset:</p><pre># Load a high-dimensional dataset<br>from sklearn.datasets import load_digits<br>digits = load_digits()<br>X = digits.data<br><br># Apply PCA<br>pca = PCA().fit(X)<br><br># Plot cumulative explained variance ratio<br>plt.figure(figsize=(10, 6))<br>plt.plot(np.cumsum(pca.explained_variance_ratio_))<br>plt.xlabel(&#39;Number of Components&#39;)<br>plt.ylabel(&#39;Cumulative Explained Variance Ratio&#39;)<br>plt.title(&#39;Explained Variance Ratio vs. Number of Components&#39;)<br>plt.show()</pre><h4>5.3 Noise Reduction</h4><p>PCA can be used to remove noise from data by reconstructing it using only the top k principal components:</p><pre>def denoise_image(image, n_components):<br>    pca = PCA(n_components=n_components)<br>    denoised = pca.inverse_transform(pca.fit_transform(image))<br>    return denoised<br><br># Load and denoise an image<br>from sklearn.datasets import load_digits<br>digits = load_digits()<br>image = digits.images[0]<br><br>plt.figure(figsize=(12, 4))<br>for i, n in enumerate([10, 20, 30, 64]):<br>    denoised = denoise_image(image.reshape(1, -1), n).reshape(8, 8)<br>    plt.subplot(1, 4, i+1)<br>    plt.imshow(denoised, cmap=&#39;gray&#39;)<br>    plt.title(f&#39;{n} components&#39;)<br>plt.show()</pre><h3>6. Advantages and Limitations of PCA</h3><h4>Advantages:</h4><ul><li>Reduces dimensionality of the data</li><li>Removes correlated features</li><li>Improves algorithm performance</li><li>Helpful for data visualization</li></ul><h4>Limitations:</h4><ul><li>Assumes linearity</li><li>Sensitive to feature scaling</li><li>May lose some interpretability</li><li>Not suitable for all types of data</li></ul><h3>7. Conclusion</h3><p>Principal Component Analysis is a powerful technique in the machine learning toolkit. It offers a way to reduce the dimensionality of data while preserving its essential characteristics. By understanding the mathematical foundations and implementing PCA from scratch, we gain deeper insights into how it works and when to apply it.</p><p>As with any technique, it’s important to understand both its strengths and limitations. PCA is particularly useful for exploratory data analysis, dimensionality reduction, and as a preprocessing step for many machine learning algorithms. However, it may not be suitable for all types of data, especially when the relationships between variables are non-linear.</p><p>By mastering PCA, data scientists and machine learning practitioners can more effectively handle high-dimensional datasets, reduce noise, and extract meaningful features from their data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7872f4756261" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Scratch to Optimized: Unraveling Bubble Sort with Python]]></title>
            <link>https://medium.com/@mertsukrupehlivan/from-scratch-to-optimized-unraveling-bubble-sort-with-python-daa51f023072?source=rss-ccac642510d------2</link>
            <guid isPermaLink="false">https://medium.com/p/daa51f023072</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <dc:creator><![CDATA[Mert Şükrü Pehlivan]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 22:13:08 GMT</pubDate>
            <atom:updated>2024-09-27T22:13:08.474Z</atom:updated>
            <content:encoded><![CDATA[<p>Sorting algorithms are an integral part of computer science and are widely used in various applications. One of the simplest yet fundamental sorting algorithms is <strong>Bubble Sort</strong>. While it’s not the most efficient algorithm, understanding it provides a foundation for more complex algorithms. In this post, we’ll delve into Bubble Sort, demonstrate a manual run-through, provide Python code for its implementation and optimization, and discuss its time complexity.</p><h3>What is Bubble Sort?</h3><p>Bubble Sort is a comparison-based sorting algorithm. It repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process repeats until the list is sorted. The largest element “bubbles up” to the end of the list after each pass, which is where the algorithm gets its name.</p><h3>Manual Run Through</h3><p>Let’s take an unsorted array:<br>arr = [5, 1, 4, 2, 8]</p><p>Here’s a step-by-step breakdown of how Bubble Sort works:</p><p><strong>Initial array:</strong> [5, 1, 4, 2, 8]</p><p><strong>Pass 1:</strong></p><ol><li>Compare 5 and 1. Since 5 &gt; 1, swap them. Array becomes [1, 5, 4, 2, 8].</li><li>Compare 5 and 4. Since 5 &gt; 4, swap them. Array becomes [1, 4, 5, 2, 8].</li><li>Compare 5 and 2. Since 5 &gt; 2, swap them. Array becomes [1, 4, 2, 5, 8].</li><li>Compare 5 and 8. No swap is needed since 5 &lt; 8.</li></ol><p>At the end of Pass 1, the largest element 8 has “bubbled” to its correct position at the end.</p><p><strong>Pass 2:</strong></p><ol><li>Compare 1 and 4. No swap is needed.</li><li>Compare 4 and 2. Since 4 &gt; 2, swap them. Array becomes [1, 2, 4, 5, 8].</li><li>Compare 4 and 5. No swap is needed.</li></ol><p>At the end of Pass 2, the second-largest element 5 is in place.</p><p><strong>Pass 3:</strong></p><ol><li>Compare 1 and 2. No swap is needed.</li><li>Compare 2 and 4. No swap is needed.</li></ol><p>Since no swaps occurred during Pass 3, the array is now sorted.</p><p>Final sorted array: [1, 2, 4, 5, 8]</p><h3>Bubble Sort Implementation in Python</h3><p>Here’s how to implement Bubble Sort in Python:</p><pre>def bubble_sort(arr):<br>    n = len(arr)<br>    # Traverse through all elements in the array<br>    for i in range(n-1):<br>        # Last i elements are already sorted, so we skip them<br>        for j in range(0, n-i-1):<br>            # Swap if the element found is greater than the next element<br>            if arr[j] &gt; arr[j+1]:<br>                arr[j], arr[j+1] = arr[j+1], arr[j]<br><br># Example usage:<br>arr = [5, 1, 4, 2, 8]<br>bubble_sort(arr)<br>print(&quot;Sorted array:&quot;, arr)</pre><p><strong>Output:</strong></p><pre>Sorted array: [1, 2, 4, 5, 8]</pre><h3>Improving Bubble Sort</h3><p>One of the major drawbacks of the basic Bubble Sort algorithm is that it continues to iterate even if the array is already sorted. We can optimize it by introducing a <strong>flag</strong> to check if any swaps were made in the previous pass. If no swaps were made, the array is already sorted, and we can break out of the loop early.</p><p>Here’s an optimized version of Bubble Sort:</p><pre>def optimized_bubble_sort(arr):<br>    n = len(arr)<br>    for i in range(n-1):<br>        swapped = False<br>        # Traverse the array as usual<br>        for j in range(0, n-i-1):<br>            if arr[j] &gt; arr[j+1]:<br>                arr[j], arr[j+1] = arr[j+1], arr[j]<br>                swapped = True<br>        # If no two elements were swapped, the array is sorted<br>        if not swapped:<br>            break<br><br># Example:<br>arr = [5, 1, 4, 2, 8]<br>optimized_bubble_sort(arr)<br>print(&quot;Optimized sorted array:&quot;, arr)</pre><p>In this version, the algorithm checks if any swaps were made. If no swaps occurred, the array is already sorted, and the algorithm stops, reducing unnecessary iterations.</p><h3>Understanding the Time Complexity of Bubble Sort</h3><p>The Bubble Sort algorithm sorts an array by repeatedly traversing through it and comparing adjacent elements, swapping them if the left element is larger than the right. As the algorithm progresses, the largest unsorted element “bubbles up” to the correct position, and the unsorted portion of the array becomes smaller with each pass. In the worst-case scenario, Bubble Sort will go through an array of size n exactly n-1 times.</p><h4>Breakdown of Bubble Sort Operations</h4><p>When Bubble Sort runs through the array, every element is compared to the next. For each comparison, if the element on the left is larger than the one on the right, they are swapped. After each complete pass through the array, the largest unsorted element is in its correct position, and the next pass deals with one fewer element.</p><p>On average, the algorithm makes about n^2 comparisons and swaps, since each element must be compared to every other element (at least in the worst case).</p><p>Operations=(n−1)⋅2n​=2n2​−2n​</p><h4>Simplifying for Large Data Sets</h4><p>When analyzing time complexity, we focus on how the algorithm performs as the size of the dataset (n) grows very large. For large n, the term n^2 becomes significantly larger than the term n. So large, in fact, that we can approximate the number of operations by ignoring the n/2 term.</p><p>Operations=2n2​−2n​≈2n2​</p><p>When considering time complexity in terms of <strong>Big O</strong> notation, constants are disregarded. Therefore, the factor 1/2 can be omitted, simplifying the time complexity of Bubble Sort to:</p><p>O(n22)=O(n2)O\left(\frac{n²}{2}\right) = O(n²)O(2n2​)=O(n2)</p><h3>Conclusion</h3><p>Bubble Sort is a simple yet fundamental algorithm that introduces key concepts in sorting. Although its inefficiency makes it less practical for large datasets, understanding it builds a strong foundation for learning more advanced sorting techniques like Merge Sort or Quick Sort. By optimizing Bubble Sort, we can reduce unnecessary comparisons when the array is already sorted, improving its best-case performance.</p><p>Whether you’re a beginner or revisiting sorting algorithms, Bubble Sort is an excellent entry point to deepen your understanding of algorithm design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daa51f023072" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to SQL: Unveiling the Basics with Code]]></title>
            <link>https://medium.com/@mertsukrupehlivan/a-beginners-guide-to-sql-unveiling-the-basics-with-code-ce7b00b6ed3a?source=rss-ccac642510d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce7b00b6ed3a</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Mert Şükrü Pehlivan]]></dc:creator>
            <pubDate>Sun, 04 Feb 2024 11:51:31 GMT</pubDate>
            <atom:updated>2024-02-04T11:51:31.419Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><p>Structured Query Language (SQL) is a powerful tool for managing and manipulating relational databases. Whether you’re a budding data analyst, a software developer, or someone looking to dip their toes into the vast ocean of database management, understanding the basics of SQL is essential. In this comprehensive guide, we’ll unravel the fundamental concepts of SQL and provide hands-on examples to help you get started.</p><h3>Chapter 1: Getting Started with SQL</h3><h3>1.1 What is SQL?</h3><p>SQL, or Structured Query Language, is a domain-specific language designed for managing and manipulating relational databases. It provides a standardized way to interact with databases, enabling users to retrieve, insert, update, and delete data.</p><h3>1.2 Setting Up Your Environment</h3><p>Before diving into SQL, you need a database to work with. Popular relational database management systems (RDBMS) include MySQL, PostgreSQL, SQLite, and Microsoft SQL Server. Choose one that suits your needs and install it on your machine. Once installed, you can access the database using a command-line interface, graphical user interface, or an integrated development environment (IDE).</p><h3>Chapter 2: Basic SQL Commands</h3><h4>2.1 SELECT Statement</h4><p>The SELECT statement is the most fundamental SQL command, used for retrieving data from a database table.</p><pre>-- Selecting all columns from a table<br>SELECT * FROM employees;<br><br>-- Selecting specific columns<br>SELECT first_name, last_name, job_title FROM employees;</pre><h4>2.2 WHERE Clause</h4><p>The WHERE clause filters the results based on a specified condition.</p><pre>-- Selecting employees with a specific job title<br>SELECT * FROM employees WHERE job_title = &#39;Data Analyst&#39;;</pre><h4>2.3 INSERT Statement</h4><p>The INSERT statement is used to add new records to a table.</p><pre>-- Inserting a new employee<br>INSERT INTO employees (first_name, last_name, job_title) VALUES (&#39;John&#39;, &#39;Doe&#39;, &#39;Software Engineer&#39;)</pre><h4>2.4 UPDATE Statement</h4><p>The UPDATE statement modifies existing records in a table.</p><pre>-- Updating job title for a specific employee<br>UPDATE employees SET job_title = &#39;Senior Software Engineer&#39; WHERE employee_id = 10</pre><h4>2.5 DELETE Statement</h4><p>The DELETE statement removes records from a table based on a condition.</p><pre>-- Deleting an employee<br>DELETE FROM employees WHERE employee_id = 102;</pre><h3>Chapter 3: Sorting and Filtering</h3><h4>3.1 ORDER BY Clause</h4><p>The ORDER BY clause is used to sort the result set.</p><pre>-- Sorting employees by last name<br>SELECT * FROM employees ORDER BY last_name;</pre><h4>3.2 LIMIT Clause</h4><p>The LIMIT clause restricts the number of rows returned.</p><pre>-- Retrieving the first 5 employees<br>SELECT * FROM employees LIMIT 5;</pre><h3>Chapter 4: Grouping and Aggregation</h3><h4>4.1 GROUP BY Clause</h4><p>The GROUP BY clause groups rows based on specified columns.</p><pre>-- Counting employees in each department<br>SELECT department, COUNT(*) FROM employees GROUP BY department;</pre><h4>4.2 Aggregate Functions</h4><p>Aggregate functions perform calculations on a set of values.</p><pre>-- Calculating average salary<br>SELECT AVG(salary) FROM employees;</pre><h3>Conclusion:</h3><p>Mastering the basics of SQL opens the door to effective database management. In this blog post, we covered the essential SQL commands, including SELECT, INSERT, UPDATE, and DELETE, along with filtering, sorting, grouping, and aggregation techniques. Armed with this knowledge, you&#39;re well on your way to becoming proficient in SQL. Happy querying!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce7b00b6ed3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>