<?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"><channel><title><![CDATA[Shittu Olumide]]></title><description><![CDATA[Shittu Olumide blog on Data science, Javascript, Blockchain, Web 3.0, python, and How-to articles and tutorials.]]></description><link>https://shittuolumide.hashnode.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1650387333885/nUJ0H3wR8.png</url><title>Shittu Olumide</title><link>https://shittuolumide.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Tue, 10 Nov 2026 05:31:38 GMT</lastBuildDate><atom:link href="https://shittuolumide.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Everything to Know About Loop Engineering]]></title><description><![CDATA[Learn all there is to know about loop engineering, with practical examples with real use cases.]]></description><link>https://shittuolumide.hashnode.dev/everything-to-know-about-loop-engineering</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/everything-to-know-about-loop-engineering</guid><category><![CDATA[Artificial Intelligence]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[loop-engineering]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Mon, 27 Jul 2026 11:48:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/5fa932a1fc2ed04a63dd7cb7/83d7e6fd-89e7-4d05-8101-2a89f0209a72.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A developer named <a href="https://jarredsumner.com/">Jarred Sumner</a> spent less than two weeks watching Claude Code turn a million lines of the Bun runtime from Zig into Rust. He didn’t sit there typing prompt after prompt for fourteen straight days. He wrote a 576-line rulebook once, kicked off a process, and let a system built around the model do the repeating. When it was done, the entire existing test suite passed in CI before anything merged, and only nineteen regressions turned up afterwards across a million lines of translated code, all of which got fixed (<a href="https://claude.com/blog/ai-code-migration">Anthropic, July 2026</a>).</p>
<p>That is not a story about a smarter model. <a href="https://jarredsumner.com/">Sumner</a> and <a href="https://www.linkedin.com/in/mikekrieger">Mike Krieger</a>, who separately turned a Python codebase into 165,000 lines of TypeScript over a single weekend, were both running a process that decided what to try next, checked its own output, and kept going without either of them holding the model’s hand through every step.</p>
<p>That process now has a name. People are calling it <strong>loop engineering</strong>, and depending on who you ask, it’s either the most useful shift in how engineers work with AI since the chat interface itself, or a rebrand of a bash script a hobbyist was running a year earlier. Both of those things are a little bit true, and untangling them is the point of this article.</p>
<h1><strong>What loop engineering actually is</strong></h1>
<p>Strip away the branding and the definition is simple. <strong>Loop engineering</strong> is the practice of designing the system that prompts an AI agent, checks its work, and decides what to do next, instead of a person doing all three of those things by hand, one message at a time.</p>
<p>The old way of working with a coding agent was a straight line. You typed an instruction, you read what came back, you typed the next instruction. The agent did real work in between, but you were the one holding it the whole time, the same way you’d hold a steering wheel that needs correcting every few seconds. Loop engineering replaces that line with a closed cycle: the agent takes an action, gets feedback from the actual environment it’s working in, uses that feedback to decide what happens next, and keeps going on its own until something you defined in advance is genuinely true.</p>
<p>The cleanest way to hold this in your head is what people are calling a recursive goal. Instead of typing each next step yourself, you state a purpose, something like “<em>get every test in the auth module passing</em>,” and the agent iterates toward that purpose without you sitting there directing traffic. It inspects the code, changes something, runs a check, reads what happened, and decides the next move, on repeat, until the goal is met or it genuinely can’t go any further.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5fa932a1fc2ed04a63dd7cb7/fcdb574f-2451-4191-85b0-93bfb5a8c82d.png" alt="The old way vs The loop" style="display:block;margin:0 auto" />

<h1><strong>Where the term came from</strong></h1>
<p>The story behind the name matters here because the speed at which it spread is itself evidence of how much the underlying capability had already changed.</p>
<p>On June 7, 2026, developer Peter Steinberger, known for building the OpenClaw agent project, posted a two-sentence message on X arguing that developers should stop prompting coding agents directly and start designing the loops that prompt agents for them.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5fa932a1fc2ed04a63dd7cb7/5cb94008-b28e-452c-9d31-096b39a1d253.png" alt="" style="display:block;margin:0 auto" />

<p>Days earlier, on June 2, Boris Cherny, who leads Claude Code at Anthropic, said something similar on stage at the WorkOS Acquired Unplugged event: that he no longer prompts Claude directly, and that his actual job had become writing the loops that prompt it for him. Then, on June 8, engineer and author Addy Osmani published <a href="https://addyosmani.com/blog/loop-engineering/">an essay simply titled “Loop Engineering”</a> that gave the idea an actual shape: five building blocks plus a sixth piece underneath them all. That essay is what turned a viral opinion into a vocabulary other people could build on and argue with.</p>
<p>It’s worth naming the lineage too, because none of this appeared out of nowhere. The direct practical ancestor is a method called <a href="https://ghuntley.com/ralph/">Ralph</a>, a plain bash loop that developer Geoffrey Huntley described in July 2025, months before the term existed, built around the simple idea of running an agent repeatedly against the same goal until it stuck. The academic ancestor goes back further still, to the <a href="https://arxiv.org/abs/2210.03629">ReAct pattern</a> from Yao and colleagues in 2022, which interleaved reasoning and acting inside a single loop, and to <a href="https://arxiv.org/abs/2303.11366">Reflexion</a> from Shinn and colleagues in 2023, which added memory and self-critique on top of that. The June 2026 moment didn’t invent any of this. It gave ordinary developers, not just researchers, a reason and a shared vocabulary to start building loops on purpose.</p>
<p>And the term is still moving. On July 18, 2026, Steinberger posted again, this time suggesting the loop era was already giving way to something he’s calling <a href="https://eu.36kr.com/en/p/3904771418867330">graph engineering</a>, where instead of one loop, teams wire several interconnected loops together with actual dependencies between them.</p>
<h1><strong>How this fits next to prompt, context, and harness engineering</strong></h1>
<p>Loop engineering didn’t replace anything that came before it. It’s the newest layer in a progression that’s been building since 2022, and each layer wraps the one underneath it rather than making it obsolete.</p>
<ol>
<li><p><strong>Prompt engineering,</strong> roughly 2022 through 2024, was about wording: giving a model a role, breaking a task into steps, providing examples. It optimized what you said, and its ceiling was real, because even a perfectly worded prompt can’t hand a model facts it was never given.</p>
</li>
<li><p><strong>Context engineering</strong>, which picked up through 2025, shifted the focus from the words themselves to everything the model actually sees at the moment it responds: conversation history, retrieved documents, tool output. Anthropic formalized this in September 2025 as <a href="https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents">curating and maintaining the optimal set of tokens available during inference</a>, and prompting effectively became one ingredient inside a bigger discipline rather than a separate one.</p>
</li>
<li><p><strong>Harness engineering</strong> showed up in early 2026 as agents started handling longer, more autonomous work in real production settings. The harness is the whole environment around an agent: the scaffolding, the tools, the constraints, the feedback loops that catch its mistakes.</p>
</li>
</ol>
<p>Loop engineering sits on top of all three. Where harness engineering asks what environment an agent needs, loop engineering asks a narrower, more operational question: <em>what cycle keeps the agent moving toward the goal, and exactly when does that cycle stop?</em>. You still write prompts. You still curate context. You still build a harness. The loop is simply where all of that gets set in motion and given a rhythm.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5fa932a1fc2ed04a63dd7cb7/4a2f402d-7d03-4979-8453-9a48e68bd67b.png" alt="Evolutiom of Building with LLMs." style="display:block;margin:0 auto" />

<h1><strong>The three things that make or break a loop</strong></h1>
<p>Every serious account of this, from Anthropic’s own team to IBM’s explainer to the practitioners already running loops in production, converges on the same three hard problems. Get any one of them wrong, and a loop stops being useful, sometimes quietly.</p>
<ol>
<li><p><strong>Context management</strong> comes first. A context window is an agent’s working memory, and it has a hard limit. Every step of a long loop adds more to that record: more reasoning, more tool output, more errors, and left unmanaged, that record either overflows outright or degrades in quality as it grows, a problem people have started calling context rot, where the model attends less reliably to what actually matters buried inside an increasingly long transcript. The fix is compacting old steps into shorter summaries, pruning stale output, and giving sub-agents their own clean context window for side tasks so they only report back a conclusion.</p>
</li>
<li><p><strong>Termination</strong> comes second, and getting it wrong is probably the single most expensive mistake in loop design. A loop needs several independent exits stacked on top of each other: a verifier confirming the actual goal was met, a hard ceiling on iterations, a token or time budget, and a subtler one, no-progress detection, which catches the case where the last few steps produced the same error or left the state functionally unchanged. Without that layered set of exits, a loop either runs forever or stops arbitrarily on a guess, and neither is acceptable in something meant to run while you’re asleep. This is not a hypothetical risk either. Uber reportedly capped its engineers at <a href="https://ai.gopubby.com/you-shouldnt-be-prompting-ai-anymore-you-should-be-designing-loops-5f26de35b84c">$1,500 per person per AI coding tool per month</a> after the company burned through its annual AI budget in four months, and unbounded loops without real termination logic are a large part of why that kind of billing surprise happens.</p>
</li>
<li><p><strong>Verification</strong> comes third, and it’s really a question of trust. The gold standard is deterministic verification: tests, type checkers, compilers, linters, because these return an objective pass or fail the model can’t argue its way around. A model acting as its own judge is more flexible and genuinely necessary for anything that can’t be mechanically checked, but it’s also more gameable, and a model grading work it produced itself is a structurally weak check by design. The strongest loops lean on a deterministic verifier wherever one exists at all, and save model judgment specifically for the parts of a task that truly can’t be measured any other way.</p>
</li>
</ol>
<h1><strong>Tutorial: Building a small working loop</strong></h1>
<p>Everything above is easier to hold onto once you’ve actually built one, so this section walks through a real, small, low-stakes loop from start to finish. The task: <em><strong>a nightly pass that lints one directory in a repository, fixes what it safely can, and leaves a written trail of what happened</strong></em>. Nothing fancy, on purpose. The value of loop engineering isn’t in the size of what you automate first; it’s in confirming the pieces actually hold together before you point them at anything that matters.</p>
<h3><strong>Step 1: pick a goal with a real stopping condition</strong></h3>
<p>“Clean up the code” is not a goal an agent, or a human, can check against. “Every file in <code>/src/utils</code> passes <code>eslint</code> with zero errors, and no existing test in that directory starts failing" is. The difference between those two sentences is the entire discipline in miniature.</p>
<h3><strong>Step 2: write the verifier before you write anything else</strong></h3>
<p>The verifier is what makes “done” mean something instead of being a model’s opinion of its own work. For this loop, it’s two commands: the linter, and the existing test suite scoped to the directory being touched. If both come back clean, the loop is allowed to stop. If either fails, the loop keeps going or escalates.</p>
<p>Step 3: write the loop itself Here’s the skeleton underneath nearly every production loop in use today.</p>
<pre><code class="language-python"># state holds the goal, plus a running scratchpad of what's been
# tried so far. this is what gets fed back to the model on every
# pass through the loop, and it's also what gets written to disk
# so a human (or tomorrow's run) can see what happened.
state = init_state(
    goal="lint /src/utils clean, don't break existing tests",
    max_steps=8,
)
</code></pre>
<pre><code class="language-python">for step in range(state.max_steps):
    # reason before acting: look at the current state and figure
    # out what the single next move should be
    thought = model.reason(state)
    # commit to one concrete, tool-backed action rather than a
    # vague intention. this is what actually touches the repo.
    action = model.choose_action(state, thought)
    # execute against the real environment, not a simulation.
    # this might run eslint, apply a fix, or run the test suite.
    result = tools.execute(action)
    # fold the outcome back into state, then compact it so the
    # context window doesn't fill up with every raw log line
    # from every step
    state = update(state, thought, action, result)
    state = compact(state)
    # a deterministic check, not the model's self-report, decides
    # whether the loop is actually finished
    if verifier.passes(state):
        write_log(state, outcome="success")
        return success(state)
    # catch the case where the last few steps produced the same
    # error or changed nothing at all, so the loop doesn't spin
    if no_progress(state):
        write_log(state, outcome="escalated: no progress")
        return escalate_to_human(state)
# ran out of steps without a clean pass. hand back rather than
# silently declaring victory
write_log(state, outcome="escalated: max steps reached")
return escalate_to_human(state)
</code></pre>
<p><strong>What’s actually happening here</strong>: the loop never trusts the model’s own claim that it’s finished. verifier.passes(state) runs the real linter and the real test suite and checks their actual exit codes, so "done" means something a human could independently confirm. The no_progress check exists specifically because agents left alone will sometimes retry a broken approach without varying it, and catching that early is cheaper than discovering it after burning through the entire step budget. And every exit path, success or escalation, writes to a log before it returns, which matters more than it looks like it should, because that log is the loop's memory across runs.</p>
<h2>Step 4: give it a real trigger</h2>
<p>A loop that only runs when you remember to run it isn’t really a loop yet. Here’s a GitHub Actions workflow that fires the lint pass every night.</p>
<pre><code class="language-python"># .github/workflows/nightly-lint-loop.yml
name: Nightly lint loop
</code></pre>
<pre><code class="language-python">on:
  schedule:
    # runs at 02:00 UTC every day. cron syntax is minute, hour,
    # day-of-month, month, day-of-week, with * meaning "any"
    - cron: '0 2 * * *'
  workflow_dispatch:
    # lets you trigger it manually from the Actions tab too,
    # useful while you're still testing the loop
jobs:
  lint-loop:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Set up Node
        uses: actions/setup-node@v4
        with:
          node-version: '20'
      - name: Install dependencies
        run: npm ci
      - name: Run the lint loop
        run: python scripts/lint_loop.py
        env:
          # keep the model's step budget in an env var so you can
          # tune it without touching the loop code itself
          MAX_STEPS: 8
      - name: Upload run log as an artifact
        uses: actions/upload-artifact@v4
        if: always()
        with:
          name: lint-loop-log
          path: state/lint-loop-log.md
</code></pre>
<p>The <code>schedule</code> block is what makes this an actual loop instead of a one-time script; it fires without anyone opening a laptop. The <code>workflow_dispatch</code> trigger is there purely so you can run it on demand while you're still confirming it behaves the way you expect, before you trust the schedule alone. And uploading the log as an artifact on every run, including failed ones (<code>if: always()</code>), is what turns this from a black box into something you can actually audit later.</p>
<h2>Step 5: read the state file after a few runs</h2>
<p>This is the part that’s easy to skip and shouldn’t be. After a handful of runs, the log should read like a short diary, not a wall of raw output.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5fa932a1fc2ed04a63dd7cb7/12f0e238-7824-41cc-a5c0-35be0817a64e.png" alt="" style="display:block;margin:0 auto" />

<p>If that file is readable at a glance, the loop is doing its job. If it’s a dense wall of tool output nobody would ever actually read, the compact step needs more work before this loop is trustworthy enough to leave unattended on anything bigger.</p>
<h1><strong>Loop engineering in a real production example</strong></h1>
<p>The Bun migration mentioned at the top of this article is worth returning to in more detail, because it’s one of the clearest documented cases of loop engineering running at real scale rather than on a toy task.</p>
<p>Jarred Sumner didn’t hand Claude Code a single prompt asking it to translate Bun’s Zig codebase into Rust. According to <a href="https://claude.com/blog/ai-code-migration">Anthropic’s own account of the project</a>, the actual starting point was a 576-line rulebook, a document laying out conventions, edge cases, and the specific things that shouldn’t be translated literally, plus one short kickoff instruction.</p>
<p>From there, the loop took over: translate a section, run the existing test suite against it, check the result, fix what failed, move to the next section, repeat. A little over a million lines of code came out the other side in under two weeks, with the entirety of Bun’s pre-existing test suite passing in CI before any of it merged. Nineteen regressions were found after the merge, and every one of them was tracked down and fixed, a small number relative to the size of what got translated, and a realistic one, since the point of loop engineering was never to promise zero mistakes, only a system reliable enough to make finding and fixing them the exception rather than the constant condition of the work.</p>
<p>Mike Krieger’s separate migration, turning a Python codebase into 165,000 lines of TypeScript over a single weekend, used a similar shape but leaned harder on parallel structure: hundreds of agents working through eight phase gates and three rounds of adversarial review, with a final parity check that compared the output of every command against the original Python version to catch anything that had quietly drifted. That adversarial review step is the maker-checker split from earlier in this article, showing up at production scale, a separate reviewing agent catching what the translating agent talked itself into.</p>
<p>Neither of these was a person prompting an agent turn by turn for two weeks straight. Both were a person designing the rulebook, the verifier, and the escalation path once, and then letting the loop run.</p>
<h1><strong>A smaller, everyday sample of loop engineering in action</strong></h1>
<p>Production migrations are the headline case, but most people’s first real loop looks a lot closer to the tutorial above than to a million-line codebase translation. A realistic small-team version might look like this: <strong>an automation runs every morning against a repository, calling a skill that reads the previous day’s CI failures, the open issues, and recent commits, and writes what it finds into a shared markdown file.</strong> For anything worth acting on, the loop opens an isolated worktree, sends one sub-agent to draft a fix, and sends a second sub-agent to review that draft against the project’s existing skills and tests. A connector opens the pull request and updates the tracking board automatically. Anything the loop genuinely can’t resolve lands in a triage inbox for a person to look at over coffee.</p>
<p>Nobody prompted any individual step of that. Someone designed it once, and the design is the actual engineering.</p>
<h1><strong>What loop engineering doesn’t solve</strong></h1>
<p>None of this is an argument that the discipline is a on size fit all, and it’s worth saying that plainly rather than as an afterthought.</p>
<p>A loop that runs unattended is also a loop that can make mistakes unattended, which is exactly why the maker-checker split exists in the first place. Even with a verifier in place, “<strong>done</strong>” is still a claim, not a proof, and someone has to actually trust the check before they trust what it approved.</p>
<p>The faster a loop ships code nobody read closely, the wider the gap grows between what exists in the repository and what the team actually understands about it, a problem people are calling comprehension debt. And there’s a subtler risk sitting right next to it: it’s genuinely tempting, once a loop is running smoothly, to stop having an opinion about its output and just accept whatever comes back, a pattern sometimes called cognitive surrender. Designing a loop with real judgment behind it is the antidote to both of these. Designing one specifically to avoid thinking about the problem is the accelerant. Same action, opposite result, and the loop itself has no way of telling you which one you’re doing.</p>
<h1><strong>Where humans still belong in the loop</strong></h1>
<p>None of this argues for removing people from the process, and the useful checkpoints show up at every level of a loop, not just at the very end of it.</p>
<p>In the base loop, that means requiring explicit approval before a genuinely sensitive action, a financial transaction, a production database write, something a deterministic test can’t fully vouch for. In the verification layer, it can mean a person acting as the actual grader for work where the stakes are too high to trust a rubric alone. Further out, it can mean a person reviewing a proposed change to the loop itself, its rulebook, its verifier, its escalation thresholds, before that change ships and starts shaping every run after it. None of these is an exotic addition. They’re a deliberate design choice, exactly like every other piece of the loop.</p>
<h1><strong>Conclusion</strong></h1>
<p>The honest starting point is smaller than most of what’s been described here. Pick one task where you’re currently the bottleneck, something recurring and genuinely low stakes, a nightly report, a lint pass, a triage summary. Write a goal specific enough that a machine could check it. Wire up one real verifier, not a model’s opinion of its own work. Give it exactly one escalation path for when it gets stuck. Run it for a couple of weeks and actually read the log before you let it touch anything bigger.</p>
<p>The skill underneath all of this was never really about writing a clever prompt. It’s about designing a cycle you trust enough to walk away from, and then actually checking, every so often, that the trust is still earned.</p>
<p>Let’s connect: <a href="https://www.linkedin.com/in/olumide-shittu">LinkedIn</a>, <a href="https://www.youtube.com/channel/UCNhFxpk6hGt5uMCKXq0Jl8A">YouTube</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Here’s how I would learn AI Agents as a total beginner]]></title><description><![CDATA[This guide provides a comprehensive and practical roadmap for beginners to bridge the gap between prompting and building.]]></description><link>https://shittuolumide.hashnode.dev/here-s-how-i-would-learn-ai-agents-as-a-total-beginner</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/here-s-how-i-would-learn-ai-agents-as-a-total-beginner</guid><category><![CDATA[AI]]></category><category><![CDATA[agents]]></category><category><![CDATA[aiagents]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Mon, 30 Mar 2026 09:35:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/5fa932a1fc2ed04a63dd7cb7/ba59e4b5-0d7f-4087-9a17-6769969b52d8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most people still use AI as a high-tech typewriter. They ask for an email draft or a summary of a meeting and call it a day. That approach is already becoming obsolete. We have moved past the point where AI just talks. Now, we are in the phase where AI acts.</p>
<p><a href="https://www.salesmate.io/blog/ai-agents-adoption-statistics/">Gartner</a> predicts that <strong>40%</strong> of enterprise software will have task-specific agents built into them by the end of 2026. To put that in perspective, that number was below <strong>5%</strong> in 2024. This isn’t just a small update to how software works. It is a fundamental change in how we get work done.</p>
<p>An agent is different because it doesn’t just give you a response. It thinks through a goal, finds the tools it needs, and stays on the job until the task is complete. If I were starting today, I would not waste time on complex prompt engineering tricks. Instead, I would focus on the architecture of autonomy. This is the path I would take to go from zero to building agents that actually deliver value.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5fa932a1fc2ed04a63dd7cb7/2f4c4aa8-1f34-4b43-82d2-2700f0046629.png" alt="" style="display:block;margin:0 auto" />

<p><a href="https://bayelsawatch.com/agentic-ai-market-to-exceed-usd-196-6-billion/">The market for this technology is expected to cross <strong>$196.6 billion</strong> in the coming years</a>. The demand for people who can build these systems is far outstripping the number of people who actually understand how they work. Learning this now puts you ahead of the curve before the field becomes crowded.</p>
<h2><strong>1. Defining the “Agent” (It isn’t just a GPT with a fancy name)</strong></h2>
<p>Before you write a single line of code, you have to understand the difference between a Large <strong>Language Model (LLM</strong>) and an <strong>Agent</strong>. It is easy to confuse the two because agents rely on LLMs to function. However, the distinction is critical. An LLM is essentially a brain in a jar. It is brilliant, well-read, and capable of complex reasoning, but it cannot move or interact with the world on its own. It sits there waiting for you to ask it a question so it can provide a text-based answer.</p>
<blockquote>
<p>“ An Agent is that same brain but with hands and a memory ”</p>
</blockquote>
<p>In technical terms, an agent is a system that uses an LLM as its reasoning engine to achieve a specific goal. Instead of just answering a prompt, the agent looks at the goal, breaks it down into smaller steps, and chooses the right tools to execute those steps. If a chatbot is a librarian who tells you where the books are, an agent is the researcher who goes to the shelves, reads the books, and writes the report for you.</p>
<p>The shift toward this “agentic” workflow is driving massive efficiency gains. Organizations that have moved from simple chatbots to autonomous agents are seeing a <a href="https://www.salesmate.io/blog/ai-agents-adoption-statistics/"><strong>20% to 30% reduction</strong> in operational friction and support costs</a>. This happens because the agent handles the “doing” part of the job, which previously required a human to copy and paste data between different tabs and applications.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5fa932a1fc2ed04a63dd7cb7/3859ec1f-97fd-4b6a-b505-9b3ac079af9e.png" alt="Structural components of an AI Agent" style="display:block;margin:0 auto" />

<p>When you build an agent, you are essentially creating a loop. The system “<strong>thinks</strong>” about the next step, “<strong>acts</strong>” by using a tool, “<strong>observes</strong>” the result of that action, and then starts the cycle again until the task is finished. This autonomy is what makes it an agent. If the system stops and waits for you to tell it what to do at every single step, it is just a complicated script, not an agent.</p>
<h2><strong>2. The Starter Pack: Three Foundations You Actually Need</strong></h2>
<p>You do not need a degree in advanced mathematics or a background in computer science to build an AI agent. Many people get intimidated by the “<strong>AI</strong>” label and assume they need to understand neural network weights or backpropagation. In reality, building agents is much more about logic and orchestration than it is about calculus.</p>
<p>If you are starting from zero, you only need to focus on three specific areas to get your first agent running.</p>
<h3><strong>Python: The Language of Automation</strong></h3>
<p>Python is the undisputed king of the AI world. As of 2026, it remains the most popular language for developers, <a href="https://www.tiobe.com/tiobe-index/">holding a <strong>29% share</strong> of the global programming market</a>. You do not need to be an expert, but you must be comfortable with the basics:</p>
<ul>
<li><p><strong>Functions and Loops:</strong> This is how you tell the agent to repeat a task until it succeeds.</p>
</li>
<li><p><strong>JSON Handling:</strong> This is the most important part. AI models communicate in a format called JSON. You need to know how to “<strong>parse</strong>” this data so your agent can read information from a weather API or a database and then use it.</p>
</li>
</ul>
<h3><strong>The API Mental Model</strong></h3>
<p>An agent is only as good as the tools it can access. You need to understand how to use an API (Application Programming Interface), which is essentially a digital handshake between two programs. When you want your agent to send an email or check a stock price, it sends a request to an API and gets a response back.</p>
<p>Most beginners start with the OpenAI or Anthropic APIs. You will need to learn how to manage “<strong>API Keys</strong>” safely. Think of an API key like a credit card: if you leak it, anyone can use your account to run expensive AI models.</p>
<h3><strong>The Reasoning Loop: Think, Act, Observe</strong></h3>
<p>This is the “<strong>logic</strong>” foundation. Every agent follows a cycle often called the “<strong>ReAct</strong>” pattern. It is the same process a human uses to solve a problem:</p>
<ul>
<li><p><strong>Think:</strong> The agent looks at the user’s request and decides what it needs to do.</p>
</li>
<li><p><strong>Act:</strong> The agent uses a tool, like a calculator or a web search.</p>
</li>
<li><p><strong>Observe:</strong> The agent looks at the result of that action and asks, “Did this solve the problem?”</p>
</li>
</ul>
<p>If the answer is no, the loop starts over. Understanding this flow is more important than memorizing code because it helps you debug why an agent is getting “stuck” in a loop or failing to complete a task.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5fa932a1fc2ed04a63dd7cb7/d63bb924-b88a-4208-bb1d-d2319a683327.png" alt="A flowchart showing a user request entering a Python Script" style="display:block;margin:0 auto" />

<p>By focusing only on these three foundations, you avoid the “tutorial hell” of learning things you will never use. Once you can write a basic Python script that talks to an API, you are already ahead of most people just playing with chat interfaces.</p>
<h2><strong>3. Phase One: The Single-Tool Agent</strong></h2>
<p>The most common mistake beginners make is trying to build a complex, multi-agent system on day one. Instead, you should start with a “<strong>Single-Tool Agent</strong>.” This is an AI that has one job and one specific tool to help it do that job. <a href="https://www.merge.dev/blog/ai-agent-statistics">As of 2026, <strong>81% of companies</strong> are taking this exact approach, using agents primarily for targeted lookups in third party software before moving on to more complex workflows</a>.</p>
<p>The magic happens when you move from a simple prompt to a “<strong>ReAct</strong>” (Reason + Act) loop. In a standard chatbot, the AI just guesses the answer. In a ReAct loop, the AI evaluates if it has enough information. If it doesn’t, it pauses its text generation, calls a tool, and then uses the new data to finish the task. This pattern is highly effective. <a href="https://www.merge.dev/blog/ai-agent-statistics">Data from early 2026 shows that single-tool agents handling tasks like travel planning or vendor comparisons achieve a <strong>completion success rate of 87%</strong></a>.</p>
<p>To build this, you don’t need a massive framework. You can see the logic in a few lines of Python. Below is a simplified example of how an agent “<strong>decides</strong>” to use a search tool.</p>
<p><strong>Python:</strong></p>
<pre><code class="language-python"># A simple representation of an agent reasoning loop
def simple_agent(user_query):
    # The 'Reasoning' step: The AI thinks about what it needs
    print(f"Thinking: I need to find the current price of {user_query}")
    
    # The 'Action' step: The AI chooses to call a specific tool
    # In a real setup, this would be an API call to Google or a Database
    raw_data = call_search_tool(user_query)

    # The 'Observation' step: The AI looks at the tool output
    print(f"Observing: The tool returned {raw_data}")

    # Final step: The AI provides the answer based on the new data
    return f"The current price of {user_query} is {raw_data}."

# This function simulates an external tool (like a web search)
def call_search_tool(query):
    # Simple mock data to represent a real API response
    return "$65,000"
# Running our beginner agent
print(simple_agent("Bitcoin"))
</code></pre>
<p><strong>Code explanation</strong>:</p>
<p>In this script, the <code>simple_agent</code> function mimics the brain of the agent. Instead of just returning a hardcoded string, it follows a sequence. First, it identifies a gap in its knowledge. Second, it calls the <code>call_search_tool</code> function, which represents an external API. Finally, it takes that "<strong>observation</strong>" and incorporates it into the final response. This shift from "<strong>generating</strong> <strong>text</strong>" to "managing a process" is the core skill you are trying to learn.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5fa932a1fc2ed04a63dd7cb7/d23524ba-6f88-41bc-b510-2bd8654cca3b.png" alt="A vertical flowchart showing three main boxes" style="display:block;margin:0 auto" />

<p>Mastering this single-tool loop is your first milestone. Once you can consistently get an AI to use one tool correctly without getting confused, you have unlocked the foundation of autonomous AI. The goal here isn’t to build something fancy but to ensure your “<strong>handshake</strong>” between the AI and the external world is solid.</p>
<h2><strong>4. Phase Two: Give Your Agent a Memory</strong></h2>
<p>A large context window is often marketed as the solution to AI memory, but in a production environment, it is a trap. Just because a model can “read” a million tokens at once does not mean it remembers who you are when you come back two weeks later. A context window is like a whiteboard. It is great for the task happening right now, but once the session ends, the board is wiped clean. To build a serious agent, you need a filing cabinet.</p>
<p>This filing cabinet is what we call persistent memory. As of 2026, <a href="https://www.landbase.com/blog/agentic-ai-statistics">research shows that companies deploying agents with robust memory layers see a <strong>30% reduction</strong> in operational costs</a> because the AI doesn’t have to re-learn user preferences or project details every single session.</p>
<h3><strong>The Two Layers of Memory</strong></h3>
<p>If you want your agent to feel intelligent, you have to manage two distinct types of storage.</p>
<ul>
<li><p><strong>Short-term Memory:</strong> This is the immediate conversation history. It allows the agent to understand that when you say “Do it again,” you are referring to the last task it performed.</p>
</li>
<li><p><strong>Long-term Memory:</strong> This is where you store facts that should last forever. If a user says they prefer Rust over Python, that should be moved from the whiteboard to the filing cabinet.</p>
</li>
</ul>
<p>The most common way to handle long-term memory is through Retrieval-Augmented Generation (RAG). This technique currently dominates <a href="https://www.marketsandmarkets.com/Market-Reports/vector-database-market-112683895.html"><strong>51% of all enterprise AI implementations</strong></a>. RAG allows the agent to search through a massive database of past interactions or uploaded documents and pull only the relevant “memories” into the current conversation.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5fa932a1fc2ed04a63dd7cb7/062d93c5-d3ba-4e71-8384-fc451e95069d.png" alt="A central AI Agent icon is positioned between two storage types" style="display:block;margin:0 auto" />

<p>You can start practising this by creating a simple “profile” system. Instead of just sending a prompt, you send the prompt along with a small snippet of data about the user.</p>
<p><strong>Python:</strong></p>
<pre><code class="language-python"># A simple way to simulate long-term memory
user_memory = {
"user_123": {
        "preferred_language": "Rust",
        "experience_level": "Beginner"
    }
}

def personalized_agent(user_id, task): 
    # Retrieve the 'memory' for this specific user
    memory = user_memory.get(user_id, {})
    language = memory.get("preferred_language", "Python")

    # The agent uses the memory to change its behavior
    print(f"Memory Check: User prefers {language}.")

    # Logic to execute the task based on memory
    return f"I am writing your {task} code in {language}."

# The agent now 'remembers' the user preference across different calls
print(personalized_agent("user_123", "web scraper"))
</code></pre>
<p><strong>Code Explanation:</strong></p>
<p>In this example, the user_memory dictionary acts as a mock database. When the personalized_agent function is called, the first thing it does is a "Memory Check." It looks up the user ID to see if there are any saved preferences. Because it finds that the user prefers Rust, it automatically adjusts its output without the user needing to specify the language again. In a real application, you would replace this dictionary with a vector database like Pinecone or Weaviate, but the logic remains exactly the same.</p>
<p>By implementing this, you move away from building a generic tool and start building a personalized assistant. This is the difference between a toy and a system that provides a <strong>171%</strong> average ROI for businesses.</p>
<h2><strong>5. Phase Three: The Multi-Agent Leap</strong></h2>
<p>In the real world, a single person rarely handles an entire project from strategy to execution. You have managers, researchers, and writers. AI development is moving in the same direction. We have realized that asking one large model to do everything often leads to “cognitive overload,” where the AI starts losing track of instructions or hallucinating details. Specialization is the fix.</p>
<p><a href="https://bayelsawatch.com/agentic-ai-market-to-exceed-usd-196-6-billion/">By the start of 2026, multi-agent orchestration captured a <strong>66% share</strong> of the global agentic AI market</a>. This shift happened because specialized teams of agents are more reliable than one “<strong>do-it-all</strong>” bot. When you break a task into parts, you can use smaller, faster models for simple steps and save the heavy, expensive models for high-level reasoning.</p>
<h3><strong>Choosing Your Framework: CrewAI vs. LangGraph</strong></h3>
<p>As you move into this phase, you will likely choose between two dominant tools.</p>
<ul>
<li><p><strong>CrewAI:</strong> This is the best choice if you want to get a project running quickly. It uses a “Role-Based” approach. You define an agent, give it a backstory, and assign it a task. It is intuitive because it mimics a human office. <a href="https://www.nxcode.io/resources/news/crewai-vs-langchain-ai-agent-framework-comparison-2026">Community benchmarks show that developers can move from an idea to a working multi-agent prototype <strong>40% faster</strong> using CrewAI compared to other frameworks</a>.</p>
</li>
<li><p><strong>LangGraph:</strong> If you need absolute control and “durable execution,” this is the industry standard. It models your agents as nodes in a graph. If an agent crashes halfway through a three-hour task, LangGraph can resume exactly where it left off. <a href="https://dev.to/pooyagolchian/ai-agents-in-2026-building-autonomous-workflows-with-local-llms-and-open-source-frameworks-36e4">In early 2026, LangGraph surpassed CrewAI in total GitHub stars, largely driven by enterprise teams who need this level of “checkpointing” for production apps</a>.</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/5fa932a1fc2ed04a63dd7cb7/fe8c36dc-6545-4e31-a8d2-0ba2432d2c7f.png" alt="Multi-Agent Collaboration Diagram" style="display:block;margin:0 auto" />

<h3><strong>Building a Collaborative Team</strong></h3>
<p>The core idea here is delegation. You write a script where one agent is responsible for the “<strong>What</strong>” and another is responsible for the “<strong>How</strong>.”</p>
<p><strong>Python:</strong></p>
<pre><code class="language-python"># A conceptual look at multi-agent delegation
class Agent:
    def __init__(self, role, task):
        self.role = role
        self.task = task
def execute(self, input_data=None):
    # Simulating the agent performing its specific role
    return f"[{self.role}] processed: {self.task} with {input_data}"
def run_multi_agent_flow(): 
    # Step 1: The Researcher finds the data
    researcher = Agent("Researcher", "Find latest AI trends")
    found_data = researcher.execute()

    # Step 2: The Manager reviews and delegates to the Writer
    manager_decision = "This looks good. Summarize this for a blog."

    # Step 3: The Writer takes the research and the manager's note
    writer = Agent("Writer", "Write a summary")
    final_output = writer.execute(input_data=f"{found_data} and {manager_decision}")

    return final_output
# Running the collaborative workflow
print(run_multi_agent_flow())
</code></pre>
<p><strong>Code Explanation:</strong></p>
<p>This code demonstrates a “<strong>Sequential</strong>” workflow. The <code>Agent</code> class is a template that can be customized with different roles. In the <code>run_multi_agent_flow</code> function, we create a researcher and a writer. The output of the researcher is passed directly to the writer. This "handoff" is the foundation of multi-agent systems. In a production setting, you would use a framework like CrewAI to handle these handoffs automatically, allowing agents to "talk" to each other until the manager agent is satisfied with the result.</p>
<h2><strong>6. Building the “Proof of Concept” Project</strong></h2>
<p>Theory is a comfortable place to stay, but it won’t teach you how to handle an agent that starts hallucinating or getting stuck in a logic loop. The fastest way to move from a beginner to someone who actually understands this tech is to build a project that solves a recurring problem. <a href="https://masterofcode.com/blog/ai-agent-statistics">Research shows that developers using AI agents to assist in their workflows can complete tasks <strong>126% faster</strong> than those working manually</a>.</p>
<p>For your first build, I recommend an <strong>Automated Newsletter Researcher</strong>. This is a project that actually saves you time. Instead of you spending thirty minutes every morning scouring the web for news, your agent does it for you.</p>
<h3><strong>The Tools of the Trade</strong></h3>
<p>You don’t need a heavy enterprise stack for this. Stick to the “minimalist” path to keep your code clean and easy to debug.</p>
<ul>
<li><p><strong>Python:</strong> The backbone of your script.</p>
</li>
<li><p><strong>OpenAI Agents SDK:</strong> This is a lightweight toolkit released recently that focuses on simple agent-to-agent handoffs and tool use without the bloat of larger frameworks. It is currently the production leader in terms of adoption because of its stability.</p>
</li>
<li><p><strong>Tavily:</strong> A search engine built specifically for AI agents that returns clean, LLM-ready content instead of messy HTML.</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/5fa932a1fc2ed04a63dd7cb7/085f472c-43b1-497b-a2e3-85ca2e2397e8.png" alt="Automated newsletter researcher workflow" style="display:block;margin:0 auto" />

<h3><strong>The Success Metric</strong></h3>
<p>Your project is “<strong>finished</strong>” when your agent can autonomously find three relevant articles on a specific topic, summarize them into three bullet points each, and save that summary to a local file without you touching your keyboard. This isn’t just a coding exercise. It is a functional piece of automation that delivers a measurable result. Early data from 2026 suggests that even simple personal automation projects like this can reclaim up to <a href="https://mitsloan.mit.edu/ideas-made-to-matter/agentic-ai-explained"><strong>20% of a professional’s daily schedule</strong></a>.</p>
<h3><strong>The Implementation</strong></h3>
<p>Here is a structured look at how you would set up the core logic for this researcher.</p>
<p><strong>Python:</strong></p>
<pre><code class="language-python">import os
# Assuming the use of a simplified Agents SDK pattern
from agents_sdk import Agent, Runner

# Step 1: Define the search tool
def search_the_web(query): 
    # This would typically call the Tavily API
    # For this example, we return a mock list of data
    return [
        {"title": "AI Agents in 2026", "content": "Agents are now 40% of apps."},
        {"title": "Python vs Rust", "content": "Rust is gaining ground in AI."},
        {"title": "OpenAI SDK", "content": "Minimalism is the new standard."}
    ]

# Step 2: Create the Researcher Agent
researcher = Agent(
    name="News Scout",
    instructions="Find the top 3 news stories about AI Agents and summarize them.",
    tools=[search_the_web]
)

# Step 3: Run the workflow
def main():
    # The runner manages the 'Think-Act-Observe' loop automatically
    runner = Runner()
    print("Starting the research process...")

    result = runner.run(
        agent=researcher,
        user_input="What are the biggest trends in AI Agents this week?"
    )

    # Step 4: Save the output to a file
    with open("newsletter_draft.txt", "w") as f:
        f.write(result.output)
    

    print("Newsletter draft saved successfully.")

if __name__ == "__main__":
    main()
</code></pre>
<p><strong>Code Explanation:</strong></p>
<p>In this setup, we use a <code>Runner</code> object to handle the heavy lifting of the reasoning loop. The <code>researcher</code> agent is given a specific identity and a single tool: the <code>search_the_web</code> function. When the <a href="http://runner.run"><code>runner.run</code></a><code>()</code> command is executed, the AI realizes it doesn't know the latest news. It triggers the search tool, observes the results we provided in the mock list, and then uses its internal logic to summarize those results. Finally, the script takes that summary and writes it to a physical file on your hard drive.</p>
<p>This project proves that you can bridge the gap between “<strong>chatting</strong>” and “<strong>doing</strong>.” Once you see that text file appear on your desktop, you have officially moved past the beginner phase.</p>
<h2><strong>Conclusion</strong></h2>
<p>The AI agent market is moving faster than the current talent pool can keep up. According to research from <a href="https://www.researchandmarkets.com/reports/6103459/ai-agents-market-report">Research and Markets</a>, the global AI agents market is expected to reach <strong>$12.06 billion</strong> by the end of 2026, representing a growth rate of 45.5% from the previous year. This growth is not just a theoretical spike. It is a direct result of companies moving away from simple chatbots toward autonomous systems that can actually finish complex work.</p>
<p>While roughly 62% of organizations are currently experimenting with these systems, <a href="https://azumo.com/artificial-intelligence/ai-insights/ai-agent-statistics">only about <strong>6%</strong> have managed to become “high performers”</a> who are effectively scaling agents across their business. This creates a massive opening for anyone who can move past the beginner stage. Most people are still stuck in the cycle of just asking an AI for summaries. By building the single-tool and multi-agent projects we covered in this guide, you are positioning yourself in that top 6% of the workforce.</p>
<p>The reality of 2026 is that proficiency in building autonomous workflows is becoming a baseline requirement. <a href="https://thoughtminds.ai/blog/10-gartner-prediction-for-enterprise-ai-adoption-trends">Gartner</a> suggests that by 2027, <strong>75% of all hiring processes</strong> will include some form of certification or testing for workplace AI proficiency. The goal for you right now should not be to just use an agent. Your goal should be to understand how to build, maintain, and orchestrate them.</p>
<p>Do not wait for a perfect certification or a formal university course to tell you that you are ready. The hands-on experience of building a proof of concept is worth more than any theory you could read. Tools like the <a href="https://developers.openai.com/api/docs/guides/agents-sdk">OpenAI SDK</a> and <a href="https://www.tavily.com/">Tavily</a> have made the entry barrier lower than ever. Start with one tool, one logic loop, and one goal. The market is waiting for the people who actually know how to build the “<strong>hands</strong>” for the brain.</p>
]]></content:encoded></item><item><title><![CDATA[Functional Programming in Python: Leveraging Lambda Functions and Higher-Order Functions]]></title><description><![CDATA[Use Python's functional programming with lambda and higher-order functions for modular, clean code—ideal for beginners boosting productivity]]></description><link>https://shittuolumide.hashnode.dev/functional-programming-in-python-leveraging-lambda-functions-and-higher-order-functions</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/functional-programming-in-python-leveraging-lambda-functions-and-higher-order-functions</guid><category><![CDATA[Python]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Python 3]]></category><category><![CDATA[Functional Programming]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Fri, 18 Apr 2025 12:54:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1744980630457/5f828518-9e9a-41f2-b394-cf22879a037f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Writing several lines of code for a computer program instructs the computer on how to solve a problem or achieve a particular task by executing the code. Without this instruction, the computer is clueless about how to solve the problem.</p>
<p>It’s relieving to know we can solve problems with a computer by writing several lines of code, sometimes hundreds. Now, imagine that you have been saddled with the responsibility of solving repetitive programming tasks several times a day.</p>
<p>Don’t tell me you intend to keep writing the several lines of code that make up the program every time to solve your tasks. Come on, be a smart programmer, modularize your code, and use functions!</p>
<blockquote>
<p><em>Functional programming is a programming paradigm that involves organizing your code into functions. When programs built with this paradigm run, they are treated as a chain or connection of several other functions.</em></p>
</blockquote>
<p>This programming paradigm treats functions as first-class citizens — this implies that functions can be passed as arguments, returned from other functions, and, lastly, assigned to a variable.</p>
<p>In this article, we’ll explore the principles of functional programming in Python, focusing on <strong>lambda functions</strong> and <strong>higher-order functions</strong> to simplify your code and boost productivity.</p>
<h2 id="heading-prerequisite"><strong>Prerequisite</strong></h2>
<p>This article is suitable for beginners in Python programming who have basic knowledge and wish to learn in-depth about functions.</p>
<h2 id="heading-what-are-functions"><strong>What are Functions</strong></h2>
<p>Functions in programming refer to a block of code that encapsulates or hides the inner implementation of the solution to a specific task or problem. A function is designed to solve a specific task; there is no one-size-fits-all approach. There has to be one function for a specific task.</p>
<p>A function takes in an argument, processes it, and may return a result or perform an action without returning any value. With that being said, let’s move on to the different types of functions available in Python.</p>
<h2 id="heading-types-of-functions-in-python"><strong>Types of Functions in Python</strong></h2>
<p>There are several types of functions in Python, but this article will focus on Lambda, user-defined, and higher-order functions.</p>
<ul>
<li><strong>User-defined functions</strong>: These are functions created by the programmer to perform a specific operation. They usually follow the standard function paradigm structure.</li>
</ul>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">say_hello</span>(<span class="hljs-params">name</span>):</span>
 <span class="hljs-keyword">return</span> <span class="hljs-string">f"Hello, <span class="hljs-subst">{name}</span>!, welcome."</span>
</code></pre>
<ul>
<li><p><strong>Built-in functions</strong>: They are functions that come with Python, you don’t have to define them because there is already an abstracted implementation. You just go ahead and use it in your code. Example: <strong><em>print(), len(), sum().</em></strong></p>
</li>
<li><p><strong>Special (Magic/Dunder) Functions</strong>: These are special functions that are built into Python; they have double underscores (__) in their names, and they are used in Python to perform special operations.</p>
</li>
<li><p><strong>Lambda functions</strong>: They are also known as anonymous functions. They are single-expression functions created using the <strong><em>lambda</em></strong> keyword. They are used for simple operations.</p>
</li>
<li><p>Higher-order functions: These are functions that take other functions as arguments or return other functions. Examples are: <strong><em>filter(), reduce(), and map().</em></strong></p>
</li>
</ul>
<h1 id="heading-anatomy-of-a-typical-python-function"><strong>Anatomy of a typical Python function</strong></h1>
<pre><code class="lang-python"><span class="hljs-string">"""
Module
Docstring
"""</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">function_name</span>(<span class="hljs-params">parameter</span>):</span>
    <span class="hljs-string">"""
    Function Docstring
    """</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">f"you passed <span class="hljs-subst">{parameter}</span>, this function is used for demonstration purposes."</span>
</code></pre>
<p>The code snippet above shows the various parts of a typical Python function; let’s go into every detail:</p>
<p><strong>1. Module Docstring</strong>: According to the <a target="_blank" href="https://peps.python.org/pep-0257/">PEP (Python Enhancement Proposals) 257,</a> a module docstring should be placed at the top of your Python file where your function is written. The module docstring should ideally contain information about the file’s contents. Always ensure that it is contained inside the multi-line quotes.</p>
<p><strong><em>2. def</em> Keyword</strong>: This keyword marks the beginning of the function being defined. It always precedes the function name.</p>
<p><strong><em>3. function_name:</em></strong> Python functions are named based on the task they perform. Appropriately naming your functions in your code helps ensure a readable code that some other programmer can easily make meaning from. The <strong><em>function_name</em></strong> comes after the <strong><em>def</em></strong> keyword and precedes a bracket.</p>
<p><strong><em>4. parameter:</em></strong> The <strong><em>parameter</em></strong> is a placeholder for the actual value or argument that will be passed to the function when it is called or used. Not all functions have a parameter; sometimes, it is just empty brackets after the <strong><em>function_name. Such</em></strong> functions don’t expect the user to pass any value to them; they perform the task they are defined for when called, regardless.</p>
<p><strong>5. Function Docstring</strong>: Slightly different from the Module Docstring, the Function Docstring contains precise information about the function and what it does, the type of arguments it receives, and the value it returns. Refer to <a target="_blank" href="https://peps.python.org/pep-0257/">PEP 257</a> for more details on how to use docstrings in Python.</p>
<p><strong><em>6. return</em> statement</strong>: The <strong><em>return</em></strong> statement in the Python function primarily sends the resultant value or values from the function to the caller. It marks the end of the function execution. From the code snippet above, the <strong><em>return</em></strong> statement sends the string in quotes from the function after replacing the right value for the <strong><em>parameter</em></strong>. Functions can still work without a <strong><em>return</em></strong> statement, but there wouldn’t be any value or values that can be collected and stored in a variable.</p>
<h1 id="heading-lets-look-deeper-into-lambda-and-higher-order-functions"><strong>Let’s look deeper into Lambda and Higher-Order functions</strong></h1>
<h2 id="heading-lambda-functions"><strong>Lambda functions:</strong></h2>
<p>Lambda functions, as previously discussed, are anonymous because they are not defined by a name like typical Python functions. See the code snippet below:</p>
<pre><code class="lang-python">answer = <span class="hljs-keyword">lambda</span> a, b: a + b
print(answer(<span class="hljs-number">3</span>, <span class="hljs-number">2</span>))
</code></pre>
<p>The variable <strong><em>answer</em></strong> is merely a reference to the function and not the name, a <strong><em>lambda</em></strong> function can still be written without any variable.</p>
<pre><code class="lang-python">print((<span class="hljs-keyword">lambda</span> a, b: a + b)(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)) <span class="hljs-comment"># outputs 5</span>
</code></pre>
<p>Now you see from the code snippet above that it is without any reference variable, but still works fine.</p>
<h2 id="heading-higher-order-functions"><strong>Higher-order functions:</strong></h2>
<p>Earlier, we discussed that Higher-Order Functions can:</p>
<ul>
<li><p>Take other function(s) as arguments</p>
</li>
<li><p>Return other functions.</p>
</li>
</ul>
<p>You will see this in action in a bit.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Function that takes another function as an argument</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">apply_function</span>(<span class="hljs-params">func, value</span>):</span>
 <span class="hljs-string">"""Applies the passed function to the given value."""</span>
 <span class="hljs-keyword">return</span> func(value)

<span class="hljs-comment"># Example function to pass</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">square</span>(<span class="hljs-params">x</span>):</span>
 <span class="hljs-keyword">return</span> x ** <span class="hljs-number">2</span>

<span class="hljs-comment"># Using the apply_function with the square function</span>
result = apply_function(square, <span class="hljs-number">5</span>)
print(result) <span class="hljs-comment"># Output: 25</span>
</code></pre>
<p>From the code snippet above, <strong><em>apply_function</em></strong> is the Higher-Order Function. It takes the <strong><em>square</em></strong> function as one of its arguments, uses it to perform the squaring operation, and finally returns the result.</p>
<p>One of the benefits of using Higher-Order Functions is that they promote code modularity; different functions handle the separation of logic. This is how to pass a function as an argument to a Higher-Order function.</p>
<p>Let’s now look at how to return functions from a Higher-Order Function.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Function that returns another function</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_multiplier</span>(<span class="hljs-params">multiplier_factor</span>):</span>
 <span class="hljs-string">""" Returns a function that multiplies its input by a given multiplier factor."""</span>
 <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">multiply_with_input</span>(<span class="hljs-params">number</span>):</span>
 <span class="hljs-keyword">return</span> number * multiplier_factor
 <span class="hljs-keyword">return</span> multiply_with_input

<span class="hljs-comment"># Using the function</span>
double_value = create_multiplier(<span class="hljs-number">2</span>) <span class="hljs-comment"># Returns a function that multiplies by 2</span>
triple_value = create_multiplier(<span class="hljs-number">3</span>) <span class="hljs-comment"># Returns a function that multiplies by 3</span>

<span class="hljs-comment"># Calling the returned functions</span>
print(double_value(<span class="hljs-number">5</span>)) <span class="hljs-comment"># Output: 10</span>
print(triple_value(<span class="hljs-number">5</span>)) <span class="hljs-comment"># Output: 15</span>
</code></pre>
<p>From the code shown above, the Higher-Order function is the <strong><em>create_multiplier</em></strong>, and the function defined inside it is the <strong><em>multiply_with_input</em></strong> function. If you look keenly, you will see that both functions take in arguments. How do we pass arguments on to the outer and inner functions during usage? You will see that in a bit.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Using the function</span>
double_value = create_multiplier(<span class="hljs-number">2</span>) <span class="hljs-comment"># Returns a function that multiplies by 2</span>

<span class="hljs-comment"># Calling the returned functions</span>
print(double_value(<span class="hljs-number">5</span>)) <span class="hljs-comment"># Output: 10</span>
</code></pre>
<p>From the example above, you can see that the <strong><em>create_multiplier</em></strong> is first called, and an argument is passed to it. The <strong><em>multiply_with_input</em></strong> function is returned to the <strong><em>double_value</em></strong> variable; it can now be accessed by passing an argument to it.</p>
<p>This is how a function can be returned from a Higher-Order Function.</p>
<h1 id="heading-conclusion"><strong>Conclusion</strong></h1>
<p>In this article, you have learned about functional programming and how we can leverage it for a cleaner and modular code; you also learned about Lambda and Higher-Order Functions — the <strong><em>lambda</em></strong> keyword enables creating functions using a single expression without giving it a name, making it suitable for handling simple operations even inside another function. Higher-order functions are a slightly advanced type of Python functions — they can take in functions(s) as arguments and can also return a function.</p>
<p>Note: Always ensure that no brackets are added to a higher-order function when passing a function as an argument. By adding the brackets to it, you are calling it already, which will result in an error. Passing the function without brackets, which is the right thing, implies that you are passing a reference to the function.</p>
]]></content:encoded></item><item><title><![CDATA[Overview of Statsmodels]]></title><description><![CDATA[Discover Statsmodels for statistical modeling in Python: tools, applications, and linear regression analysis]]></description><link>https://shittuolumide.hashnode.dev/overview-of-statsmodels</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/overview-of-statsmodels</guid><category><![CDATA[software development]]></category><category><![CDATA[Python]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Thu, 13 Mar 2025 16:23:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1741882521721/70249005-d900-48b0-b5a2-1c01fa5afd9c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Having data, no matter how quality it may be, without being able or knowing how to properly analyze and draw crucial statistical insights from it I am talking about key pointers and indicators that can help inform your next big business decision could be very frustrating, this is like having a gold mine but not having the capacity to tap into it, even though it can change your life tremendously, for the better.</p>
<p>Statistical modeling is a crucial framework used by statisticians, researchers, and data professionals to draw valuable insights from data. It largely involves the use of mathematical and statistical techniques and methodologies to analyze, represent, predict, and interpret data. It gives sufficient information that aids proper understanding of given data, leading to informed decision-making. It is to this end that different tools were developed for conducting statistical modeling. To name only a few tools used for this purpose, we have:</p>
<ul>
<li><p>Python libraries (statsmodel, sci-kit-learn, pandas).</p>
</li>
<li><p>R programming language (Specifically designed for scientific computing tasks).</p>
</li>
<li><p>SAS/SPSS (A commercial software for advanced statistical analysis).</p>
</li>
<li><p>Excel (Used for simple statistical modeling and visualization)</p>
</li>
</ul>
<p>In this article, we will be focusing on <strong><em>statsmodel</em></strong>; we will learn about its various tools and how it is used for statistical modeling with a simple code illustration.</p>
<h2 id="heading-prerequisites"><strong>Prerequisites</strong></h2>
<p>Prior knowledge of Python programming and statistical operations on datasets is useful, as it would ease the understanding of this article’s content.</p>
<h1 id="heading-what-is-statsmodel"><strong>What is statsmodel ?</strong></h1>
<p><strong><em>statsmodel</em></strong> contains methods and classes used for statistical modeling. According to the official <a target="_blank" href="https://www.statsmodels.org/stable/index.html">website</a> of <strong><em>statsmodel</em></strong>, “statsmodel is a Python module that provides classes and functions for the estimation of many different statistical models, as well as for conducting statistical tests and statistical data exploration.”</p>
<p>The ability of <strong><em>statsmodel</em></strong> to integrate easily with pandas and <strong><em>numpy</em></strong> libraries, which are very popular and commonly used tools for data operations, such as loading, exploring, and manipulating datasets, makes it favorable to Data Professionals.</p>
<p><strong><em>statsmodel</em></strong> contains various statistical tools often used by professionals to conduct statistical operations on data. Listed below are some of the predominantly used <strong><em>statsmodel</em></strong> tools for performing various tasks:</p>
<ul>
<li><p><strong>Time series-analysis</strong>: When performing time series tasks (analyzing and forecasting time series data) with <strong><em>statsmodel</em></strong>, ARIMA (AutoRegressive Integrated Moving Average) and SARIMAX (Seasonal AutoRegressive Integrated Moving Average with eXogenous variables) models are commonly used.</p>
</li>
<li><p><strong>Data Visualization</strong>: <strong><em>statsmodel</em></strong> contains plotting functions that can be used to create visual representations of statistical data and also visualize model diagnostics.</p>
</li>
<li><p><strong>Linear Regression Model</strong>: Ordinary Least Squares (OLS), Generalized Least Squares (GLS), and Weighted Least Squares (WLS) are all tools available in <strong><em>statsmodel,</em></strong> they are used for analyzing Linear Regression models. They all have their various use cases.</p>
</li>
<li><p><strong>Statistical Tests</strong>: <strong><em>statsmodel</em></strong> provides numerous testing frameworks for conducting statistical tests on data, these tools can be used for both hypothesis testing and diagnosis. Here are some of the tests that <strong><em>statsmodel</em></strong> provides: t-tests (used to compare the means of two distinct groups of data), chi-squared tests (Used for testing the relationships that exist between categorical data, that is, text data), ANOVA (Analysis of Variance), unlike the t-test that compares the means of two data groups, ANOVA is used to compare the mean of multiple data groups.</p>
</li>
<li><p><strong>Datasets</strong>: In-built datasets are available in <strong><em>statsmodel</em></strong> <em>and</em> can be used to practice and test operations.</p>
</li>
<li><p><strong>Nonparametric methods</strong>: These are tools provided by the <strong><em>statsmodel</em></strong> module for analyzing data without assuming a specific distribution. To achieve this, the Kernel Density Estimation (KDE) approach is predominantly used.</p>
</li>
</ul>
<h1 id="heading-applications-of-statsmodel"><strong>Applications of statsmodel</strong></h1>
<p><strong><em>statsmodel</em></strong> has numerous real-world applications, and it is used in various industries to carry out niche tasks.</p>
<p>Here are some key areas where <strong><em>statsmodel</em></strong> is utilized:</p>
<ul>
<li><p><strong>Finance</strong>: <strong><em>statsmodel</em></strong> is used in finance for forecasting and risk analysis. Time series can be used to monitor stock prices and returns.</p>
</li>
<li><p><strong>Econometrics</strong>: Economic data can be analyzed, and economic theories can be tested using the <strong><em>statsmodel.</em></strong></p>
</li>
<li><p><strong>Marketing</strong>: E-commerce companies use <strong><em>statsmodel</em></strong> to analyze and understand customer behavior while interacting with their business to predict demand and strategize for better profitability.</p>
</li>
<li><p><strong>Energy</strong>: In the energy sector, the <strong><em>statsmodel</em></strong> is used to forecast energy consumption and pricing at a given time for electricity and gas markets.</p>
</li>
<li><p><strong>Manufacturing</strong>: In the manufacturing industry, the <strong><em>statsmodel</em></strong> is used for predictive maintenance; it predicts potential failure from analyzing previous data.</p>
</li>
</ul>
<h1 id="heading-how-to-install-and-use-statsmodel"><strong>How to install and use statsmodel</strong></h1>
<p>So far in this article, we have learned a lot of theories about <strong><em>statsmodel,</em></strong> laying a good foundation for building more advanced knowledge. Let’s take it a little bit further to the coding side.</p>
<h2 id="heading-installing-statsmodel"><strong>Installing statsmodel</strong></h2>
<p>To install <strong><em>statsmodel</em></strong> on your machine, follow the steps below:</p>
<h2 id="heading-step-1"><strong>Step 1</strong></h2>
<ul>
<li>Create and activate a virtual environment.</li>
</ul>
<p>On Linux/Mac OS:</p>
<pre><code class="lang-python">python3 -m venv venv
source venv/bin/activate
</code></pre>
<p>On Windows OS:</p>
<pre><code class="lang-python">python -m venv venv
venv\scripts\activate
</code></pre>
<h2 id="heading-step-2"><strong>Step 2</strong></h2>
<ul>
<li>Install the <strong><em>statsmodel</em></strong> module on your machine by entering this code in your terminal window:</li>
</ul>
<pre><code class="lang-python">pip install statsmodels
</code></pre>
<h2 id="heading-step-3"><strong>Step 3</strong></h2>
<ul>
<li>Confirm the installation was successful. Create a new Python file, and write the following code inside it:</li>
</ul>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> statsmodels.api <span class="hljs-keyword">as</span> sm
print(sm.__version__)
</code></pre>
<p>After running this code, the version of <strong><em>statsmodel</em></strong> you installed should show on your terminal.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:1400/1*lujZxshEpft75KlZAmQ7xQ.png" alt /></p>
<p>We just finished installing <strong><em>statsmodel</em></strong>; now, let us do a Linear Regression Analysis using <strong><em>statsmodel.</em></strong> Before that, let us install a dependency that we will use in our code. Run this code in your terminal window:</p>
<pre><code class="lang-python">pip install pandas
</code></pre>
<p>This installs the <strong><em>pandas</em></strong> library into our created virtual environment, which is useful for loading and manipulating data.</p>
<p>In the Python file you created earlier, write the following code:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> statsmodels.api <span class="hljs-keyword">as</span> sm
<span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd

<span class="hljs-comment"># Example dataset</span>
data = sm.datasets.get_rdataset(<span class="hljs-string">"mtcars"</span>).data

<span class="hljs-comment"># Define variables</span>
X = data[[<span class="hljs-string">'hp'</span>, <span class="hljs-string">'wt'</span>]] <span class="hljs-comment"># Independent variables</span>
X = sm.add_constant(X) <span class="hljs-comment"># Add intercept</span>
y = data[<span class="hljs-string">'mpg'</span>] <span class="hljs-comment"># Dependent variable</span>

<span class="hljs-comment"># Fit the model</span>
model = sm.OLS(y, X)
results = model.fit()

<span class="hljs-comment"># Print the summary</span>
print(results.summary())
</code></pre>
<ul>
<li><p>In this code snippet, the <strong><em>statsmodel.api</em></strong> module was imported, which happens to be the main module that provides tools for statistical modeling. The <strong><em>pandas</em></strong> library was also imported to handle the data frame data type returned from the <strong><em>mtcars</em></strong> dataset.</p>
</li>
<li><p>The dataset is stored as a <strong><em>pandas</em></strong> data frame in the <strong><em>data</em></strong> variable.</p>
</li>
<li><p>The dependent and independent variables were extracted and stored in the y and X variables, respectively.</p>
</li>
<li><p>The OLS (Ordinary Least Square) method was used to create an OLS regression model.</p>
</li>
<li><p>The model was fitted to the data.</p>
</li>
<li><p>Lastly, the summary of the model was printed, which shows a detailed overview of the regression results.</p>
</li>
</ul>
<p>When you run this code, you should get an output similar to what is shown in the image below.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:1400/1*ExQGarZGPnnX1aqicck96g.png" alt /></p>
<h1 id="heading-conclusion"><strong>Conclusion</strong></h1>
<p>In this article, we’ve explored the power of <strong><em>statsmodel</em></strong> and its role in statistical modeling and conducted linear regression analysis. <strong><em>statsmodel</em></strong> provides a comprehensive collection of tools for data professionals, researchers, and analysts.</p>
<p>By integrating seamlessly with <strong><em>pandas</em></strong> and <strong><em>numpy</em></strong>, <strong><em>statsmodel</em></strong> makes statistical modeling in Python intuitive and accessible. Whether you’re working in <strong>finance, healthcare, manufacturing, or marketing</strong>, this library offers powerful capabilities for extracting meaningful insights from data.</p>
<p>As you’ve seen from our example, installing and using <strong>statsmodel</strong> is straightforward, and with a solid grasp of its tools, you can unlock new possibilities in data analysis. I recommend that you dive even deeper — experiment with other datasets and explore more advanced statistical models- to cement what you are learning and grow your expertise even more.</p>
]]></content:encoded></item><item><title><![CDATA[Let’s Build a RAG-Powered Research Paper Assistant]]></title><description><![CDATA[Build a RAG-powered assistant using OpenAI, Pinecone, and LangChain for enhanced research retrieval and synthesis]]></description><link>https://shittuolumide.hashnode.dev/lets-build-a-rag-powered-research-paper-assistant</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/lets-build-a-rag-powered-research-paper-assistant</guid><category><![CDATA[Artificial Intelligence]]></category><category><![CDATA[llm]]></category><category><![CDATA[RAG ]]></category><category><![CDATA[Developer]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Tue, 11 Mar 2025 11:34:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1741692988567/5784306e-6291-430e-927a-7aec0dafb76b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Have you ever spent hours sifting through academic papers only to feel overwhelmed by the sheer amount of information? Finding, analyzing, and synthesizing relevant research can be daunting. But what if there was a tool that could do the heavy lifting for you?</p>
<p><strong>Retrieval-Augmented Generation</strong>, a state-of-the-art <strong>AI framework</strong> that puts together the accuracy of retrieval systems with the creative problem-solving capabilities of Large Language Models. In this article, we will explain <strong>RAG</strong> in detail, show how it works, and take you through a step-by-step process to build a research assistant powered by OpenAI.</p>
<h1 id="heading-why-does-it-matter"><strong>Why Does It Matter?</strong></h1>
<p><strong>Let’s break it down before we get too technical:</strong></p>
<ul>
<li><p><strong>Retrieval:</strong> This part retrieves the most relevant documents from a large dataset, such as academic papers or books, based on a user’s query.</p>
</li>
<li><p><strong>Generation:</strong> It takes that information and synthesizes it with the knowledge to generate responses through a language model, such as <strong>OpenAI’s GPT-4</strong>.</p>
</li>
</ul>
<p>By combining these two capabilities, <strong>RAG</strong> generates highly accurate and contextually rich outputs. It’s like having an AI librarian who will not only recommend the best books but also summarize and explain them to you.</p>
<h1 id="heading-what-will-you-build"><strong>What Will You Build?</strong></h1>
<p>In this tutorial, we’ll create a <strong>RAG</strong>-powered Research Paper Assistant capable of searching a database of academic papers, summarizing key points from relevant studies, and answering user queries with accurate, well-cited information.</p>
<p><strong>We will be using:</strong></p>
<ol>
<li><p><strong>OpenAI GPT-4</strong> to generate the text.</p>
</li>
<li><p><strong>Pinecone</strong> or <strong>Weaviate</strong> for vector search.</p>
</li>
<li><p><strong>LangChain</strong> to orchestrate the RAG pipeline.</p>
</li>
</ol>
<h1 id="heading-step-1-setup-your-environment"><strong>Step 1: Setup Your Environment</strong></h1>
<p>Okay, first things first: prepare the tools and libraries that will be used for this project.</p>
<h1 id="heading-prerequisites"><strong>Prerequisites:</strong></h1>
<ol>
<li><p>Basic programming skills in any language. In this case, <strong>Python</strong> will be used.</p>
</li>
<li><p>Research paper dataset <a target="_blank" href="https://www.kaggle.com/Cornell-University/arxiv"><strong>Arxiv Open Access</strong></a> or Semantic Scholar</p>
</li>
<li><p>OpenAI API key</p>
</li>
<li><p><strong>Environment Setup</strong>: You can run this application locally on your system or in a cloud-based Jupyter Notebook environment like <a target="_blank" href="https://colab.google/">Google Colab</a>, which is beginner-friendly and free for basic usage.</p>
</li>
</ol>
<h2 id="heading-accessing-openai-for-free"><strong>Accessing OpenAI for Free</strong></h2>
<p>If you don’t already have an OpenAI account, follow these steps to get started:</p>
<ol>
<li><p><strong>Sign Up</strong>: Visit <a target="_blank" href="https://platform.openai.com/">OpenAI’s website</a> and sign up for an account.</p>
</li>
<li><p><strong>Free Credits</strong>: New users receive free credits, which you can use to practice along with this tutorial.</p>
</li>
<li><p><strong>Educational Discounts</strong>: If you’re a student, check for OpenAI’s educational programs or grants to access additional credits.</p>
</li>
</ol>
<p><strong>Installation of Required Libraries</strong></p>
<p>The following are the commands to install our required libraries:</p>
<pre><code class="lang-python">pip install openai langchain pinecone-client sentence-transformers
</code></pre>
<p><strong>Note:</strong> If using <strong>Google Colab</strong>, add the ! prefix before each command to execute it in the notebook.</p>
<h1 id="heading-step-2-prepare-the-data"><strong>Step 2: Prepare the Data</strong></h1>
<p>A good assistant requires a well-prepared dataset. The preparation of your dataset can be done through the following steps:</p>
<h1 id="heading-1-gather-your-data"><strong>1. Gather Your Data</strong></h1>
<p>Download a dataset of research papers or use APIs like Semantic Scholar to fetch the abstracts and metadata. <strong>Pro tip:</strong> Stick to domains you are interested in unless you want to start analyzing the migratory patterns of penguins when your interests actually lie in studying neural networks.</p>
<p>In this tutorial, we will make use of the <a target="_blank" href="https://www.kaggle.com/Cornell-University/arxiv">ArXiv Open Access Dataset</a> available in Kaggle. The following is how you can access and load it into your environment:</p>
<ol>
<li><p>Log in to Kaggle or sign up, then follow the below steps:</p>
</li>
<li><p>Follow the <a target="_blank" href="https://www.kaggle.com/Cornell-University/arxiv">dataset page</a>.</p>
</li>
<li><p>Download the dataset and upload the <strong>papers.csv</strong> file to your Google Colab or your local directory.</p>
</li>
<li><p>Use the following code snippet to load the file:</p>
</li>
</ol>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd

<span class="hljs-comment"># Load dataset</span>
<span class="hljs-keyword">from</span> google.colab <span class="hljs-keyword">import</span> files

<span class="hljs-comment"># Upload CSV</span>
uploaded = files.upload()  <span class="hljs-comment"># Select 'papers.csv'</span>

<span class="hljs-comment"># Load dataset into a DataFrame e.g (papers.csv)</span>
df = pd.read_csv(<span class="hljs-string">"papers.csv"</span>)
</code></pre>
<p>If running locally, ensure the papers.csv file is in the same directory as your script and load it as follows:</p>
<pre><code class="lang-python">df = pd.read_csv(<span class="hljs-string">"papers.csv"</span>)
</code></pre>
<h1 id="heading-2-preprocess-the-data"><strong>2. Preprocess the Data</strong></h1>
<p>We need to clean up the data by removing duplicates, irrelevant information, and formatting issues. Here’s how we’ll do it:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> sentence_transformers <span class="hljs-keyword">import</span> SentenceTransformer

<span class="hljs-comment"># Extract abstracts and titles</span>
data = df[[<span class="hljs-string">"title"</span>, <span class="hljs-string">"abstract"</span>]].dropna()

<span class="hljs-comment"># Generate embeddings</span>
model = SentenceTransformer(<span class="hljs-string">"all-MiniLM-L6-v2"</span>)
data[<span class="hljs-string">"embeddings"</span>] = data[<span class="hljs-string">"abstract"</span>].apply(<span class="hljs-keyword">lambda</span> x: model.encode(x).tolist())

<span class="hljs-comment"># Save preprocessed data</span>
data.to_json(<span class="hljs-string">"preprocessed_data.json"</span>, orient=<span class="hljs-string">"records"</span>)
</code></pre>
<h1 id="heading-step-3-set-up-vector-search"><strong>Step 3: Set Up Vector Search</strong></h1>
<p>A vector database enables fast and efficient retrieval. We’ll use <strong>Pinecone</strong> for this step.</p>
<h2 id="heading-create-a-pinecone-index"><strong>Create a Pinecone Index</strong></h2>
<p>Sign up at <a target="_blank" href="https://www.pinecone.io/">Pinecone.io</a> and create an index. Choose parameters like:</p>
<ul>
<li><p><strong>Metric</strong>: Cosine similarity.</p>
</li>
<li><p><strong>Dimension</strong>: Match the embedding size of your model (e.g., 384 for MiniLM).</p>
</li>
</ul>
<h2 id="heading-upload-data-to-pinecone"><strong>Upload Data to Pinecone</strong></h2>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pinecone

pinecone.init(api_key=<span class="hljs-string">"YOUR_API_KEY"</span>, environment=<span class="hljs-string">"us-west1-gcp"</span>)
index = pinecone.Index(<span class="hljs-string">"research-assistant"</span>)

<span class="hljs-comment"># Upload data</span>
<span class="hljs-keyword">for</span> idx, record <span class="hljs-keyword">in</span> data.iterrows():
    index.upsert([(str(idx), record[<span class="hljs-string">"embeddings"</span>])])
</code></pre>
<h1 id="heading-step-4-build-the-rag-pipeline"><strong>Step 4: Build the RAG Pipeline</strong></h1>
<p>Now comes the fun part: combining retrieval with generation.</p>
<h2 id="heading-define-the-retrieval-function"><strong>Define the Retrieval Function</strong></h2>
<p>This function queries the Pinecone index:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">retrieve_relevant_docs</span>(<span class="hljs-params">query, top_k=<span class="hljs-number">5</span></span>):</span>
    query_embedding = model.encode(query).tolist()
    results = index.query(query_embedding, top_k=top_k, include_metadata=<span class="hljs-literal">True</span>)
    <span class="hljs-keyword">return</span> [res[<span class="hljs-string">"metadata"</span>] <span class="hljs-keyword">for</span> res <span class="hljs-keyword">in</span> results[<span class="hljs-string">"matches"</span>]]
</code></pre>
<h2 id="heading-generate-responses"><strong>Generate Responses</strong></h2>
<p>Use OpenAI to synthesize responses:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> openai

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">generate_response</span>(<span class="hljs-params">query, documents</span>):</span>
    context = <span class="hljs-string">"\n"</span>.join([doc[<span class="hljs-string">"abstract"</span>] <span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> documents])
    prompt = <span class="hljs-string">f"Use the following context to answer the query:\n<span class="hljs-subst">{context}</span>\n\nQuery: <span class="hljs-subst">{query}</span>\nAnswer:"</span>

    response = openai.Completion.create(
        engine=<span class="hljs-string">"text-davinci-003"</span>,
        prompt=prompt,
        max_tokens=<span class="hljs-number">150</span>
   )
   <span class="hljs-keyword">return</span> response[<span class="hljs-string">"choices"</span>][<span class="hljs-number">0</span>][<span class="hljs-string">"text"</span>].strip()
</code></pre>
<h1 id="heading-step-5-create-the-interactive-assistant"><strong>Step 5: Create the Interactive Assistant</strong></h1>
<p>Let’s tie everything together with a simple interface.</p>
<h2 id="heading-basic-command-line-interface"><strong>Basic Command-Line Interface</strong></h2>
<pre><code class="lang-python"><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    print(<span class="hljs-string">"Welcome to the RAG-Powered Research Assistant!"</span>)
    <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
        query = input(<span class="hljs-string">"Enter your research question (or 'exit' to quit): "</span>)
        <span class="hljs-keyword">if</span> query.lower() == <span class="hljs-string">"exit"</span>:
            <span class="hljs-keyword">break</span>
        docs = retrieve_relevant_docs(query)
            <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> docs:
                print(<span class="hljs-string">"No relevant documents found."</span>)
            <span class="hljs-keyword">else</span>:
                answer = generate_response(query, docs)
                print(<span class="hljs-string">f"Answer: <span class="hljs-subst">{answer}</span>\n"</span>)
</code></pre>
<h1 id="heading-step-6-enhance-the-experience"><strong>Step 6: Enhance the Experience</strong></h1>
<p>To make your assistant even more powerful, add the following:</p>
<ol>
<li><p><strong>Add Citations</strong>: Add paper titles and authors to give credibility to the output.</p>
</li>
<li><p><strong>Web Interface</strong>: Provide a nice UI created in <strong>React</strong> or <strong>Next.js</strong>.</p>
</li>
<li><p><strong>Summarization:</strong> Allow summarizing of whole papers.</p>
</li>
</ol>
<h1 id="heading-advanced-features-for-your-rag-assistant"><strong>Advanced Features for Your RAG Assistant</strong></h1>
<p>To add more capabilities to your research assistant, the following capabilities can be implemented for it:</p>
<h2 id="heading-citation-generation"><strong>Citation Generation</strong></h2>
<p>The inclusion of citations or references for the retrieved research papers will make your assistant more reliable and useful for academic purposes. You can extract metadata such as authors, titles, and publication years to create properly formatted citations.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">format_citation</span>(<span class="hljs-params">doc</span>):</span>
   <span class="hljs-keyword">return</span> <span class="hljs-string">f"<span class="hljs-subst">{doc[<span class="hljs-string">'title'</span>]}</span> by <span class="hljs-subst">{doc[<span class="hljs-string">'authors'</span>]}</span> (<span class="hljs-subst">{doc[<span class="hljs-string">'year'</span>]}</span>)"</span>
</code></pre>
<h2 id="heading-overview-of-findings"><strong>Overview of Findings</strong></h2>
<p>Summarizing long documents or multiple papers into concise, digestible insights helps streamline the research process. Use OpenAI or specialized summarization models like <strong>bart-large-cnn</strong>.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">summarize_docs</span>(<span class="hljs-params">documents</span>):</span>
    summaries = [doc[<span class="hljs-string">"abstract"</span>][:<span class="hljs-number">500</span>] <span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> documents] <span class="hljs-comment"># Limit the text length</span>
    combined_summary = <span class="hljs-string">" "</span>.join(summaries)
    response = openai.Completion.create(
        engine=<span class="hljs-string">"text-davinci-003"</span>,
        prompt=<span class="hljs-string">f"Summarize the following research abstracts:\n<span class="hljs-subst">{combined_summary}</span>"</span>,
 max_tokens=<span class="hljs-number">200</span>
 )
   <span class="hljs-keyword">return</span> response[<span class="hljs-string">"choices"</span>][<span class="hljs-number">0</span>][<span class="hljs-string">"text"</span>].strip()
</code></pre>
<h2 id="heading-real-time-data-updates"><strong>Real-Time Data Updates</strong></h2>
<p>If your dataset is updated regularly, consider periodic updates with a scheduler to keep the assistant updated. This can be automated using <strong>cron</strong> jobs or <strong>Celery</strong>.</p>
<h2 id="heading-multilingual"><strong>Multilingual</strong></h2>
<p>If your audience includes researchers all over the world, include translation capabilities. Libraries like <strong>transformers</strong> with models like <strong>Helsinki-NLP</strong> can help.</p>
<h2 id="heading-deploying-your-assistant"><strong>Deploying Your Assistant</strong></h2>
<p>Once your RAG-powered assistant is built, deploy it to make it accessible. Here’s how:</p>
<ol>
<li><strong>API Deployment with Flask or FastAPI  
 </strong>Create an API endpoint to handle user queries and return results.</li>
</ol>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> fastapi <span class="hljs-keyword">import</span> FastAPI
app = FastAPI()

<span class="hljs-meta">@app.post("/query")</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">query_research_assistant</span>(<span class="hljs-params">query: str</span>):</span>
    docs = retrieve_relevant_docs(query)
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> docs:
    <span class="hljs-keyword">return</span> {<span class="hljs-string">"answer"</span>: <span class="hljs-string">"No relevant documents found."</span>}
    answer = generate_response(query, docs)
    <span class="hljs-keyword">return</span> {<span class="hljs-string">"answer"</span>: answer}
</code></pre>
<p>Run the API on the local system or deploy it to <strong>Heroku</strong>, <strong>AWS</strong>, <strong>Google Cloud</strong>, etc.</p>
<h1 id="heading-web-interface"><strong>Web Interface</strong></h1>
<p>Create a user-friendly interface using frameworks such as <strong>React</strong>, <strong>Vue.js</strong>, or even <strong>Streamlit</strong> for fast, interactive web application development.</p>
<h1 id="heading-dockerize-for-portability"><strong>Dockerize for Portability</strong></h1>
<p>Package your application in a Docker container for easy deployment across environments.</p>
<pre><code class="lang-python">FROM python:<span class="hljs-number">3.9</span>-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD [<span class="hljs-string">"uvicorn"</span>, <span class="hljs-string">"app:app"</span>, <span class="hljs-string">" - host"</span>, <span class="hljs-string">"0.0.0.0"</span>, <span class="hljs-string">" - port"</span>, <span class="hljs-string">"8000"</span>]
</code></pre>
<h2 id="heading-integration-with-slack-or-discord"><strong>Integration with Slack or Discord</strong></h2>
<p>Create bots that respond to user queries in Slack or Discord channels to make the assistant accessible in collaboration tools.</p>
<h2 id="heading-testing-and-iteration"><strong>Testing and Iteration</strong></h2>
<p>Prior to the release of your assistant, quality needs to be controlled:</p>
<ol>
<li><p><strong>Accuracy Testing:</strong> The accuracy of both retrieval and generation components should be tested. Test real-world queries and check response relevance.</p>
</li>
<li><p><strong>Performance Testing:</strong> Measure response times, especially when your assistant processes large amounts of data. If needed, improve the retrieval and generation steps.</p>
</li>
<li><p><strong>User Feedback:</strong> Ask researchers or target users for feedback and implement their suggestions to improve the user-friendliness and functionality of your assistant.</p>
</li>
</ol>
<h1 id="heading-future-possibilities-with-rag"><strong>Future Possibilities with RAG</strong></h1>
<p>Retrieval-augmented generation is not limited to research assistance alone. Here are a few other applications:</p>
<ol>
<li><p><strong>Legal Research</strong>: Quickly find and summarize legal documents or case law.</p>
</li>
<li><p><strong>Healthcare</strong>: Assist doctors by retrieving relevant medical studies and summarizing patient cases.</p>
</li>
<li><p><strong>E-commerce:</strong> Improve customer support by combining product information retrieval with personalized recommendations.</p>
</li>
</ol>
<h1 id="heading-conclusion"><strong>Conclusion</strong></h1>
<p>By building a RAG-powered research assistant, you will be entering the future of intelligent tools that mix precision with creativity. This will not only assist academic researchers in doing their work more effectively but also open doors to endless possibilities in other domains. With frameworks like <strong>LangChain</strong>, powerful language models like <strong>GPT-4</strong>, and scalable vector databases like Pinecone, creating your assistant has never been more accessible.</p>
<p>So, why wait? Dive in and change the way research is done in your field. The possibilities are endless, and your journey has just begun.</p>
<h1 id="heading-call-to-action"><strong>Call-to-Action</strong></h1>
<p>Want to build your <strong>RAG-powered assistant</strong>? Begin coding now and join the AI revolution in academic research. Share your experience and let us know how it transforms your workflow!</p>
<h1 id="heading-references"><strong>References</strong></h1>
<ol>
<li><p><strong>OpenAI API Documentation  
 </strong>Learn more about how to use the OpenAI API for text generation:<br /> <a target="_blank" href="https://platform.openai.com/docs/">https://platform.openai.com/docs/</a></p>
</li>
<li><p><strong>LangChain Documentation  
 </strong>Official guide to orchestrating RAG pipelines with LangChain:<br /> <a target="_blank" href="https://www.langchain.com/">https://www.langchain.com/</a></p>
</li>
<li><p><strong>Pinecone Documentation  
 </strong>A comprehensive resource for setting up and using Pinecone for vector search:<br /> <a target="_blank" href="https://docs.pinecone.io/">https://docs.pinecone.io/</a></p>
</li>
<li><p><strong>ArXiv Dataset on Kaggle  
 </strong>Access the ArXiv Open Access Dataset for research papers:<br /> <a target="_blank" href="https://www.kaggle.com/datasets/Cornell-University/arxiv">https://www.kaggle.com/datasets/Cornell-University/arxiv</a></p>
</li>
<li><p><strong>Sentence Transformers  
 </strong>Learn about the sentence-transformers library and its usage for embeddings:<br /> <a target="_blank" href="https://www.sbert.net/">https://www.sbert.net/</a></p>
</li>
<li><p><strong>Semantic Scholar API  
 </strong>Explore the Semantic Scholar API to fetch academic papers:<br /> <a target="_blank" href="https://www.semanticscholar.org/product/api">https://www.semanticscholar.org/product/api</a></p>
</li>
<li><p><strong>Pinecone Blog: Building with RAG  
 </strong>A detailed tutorial on Retrieval-Augmented Generation with Pinecone:<br /> <a target="_blank" href="https://www.pinecone.io/learn/rag/">https://www.pinecone.io/learn/rag/</a></p>
</li>
<li><p><strong>Google Colab Documentation  
 </strong>Beginner-friendly documentation to get started with Google Colab:<br /> <a target="_blank" href="https://colab.research.google.com/">https://colab.research.google.com/</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Prompt Engineering Patterns for Successful RAG Implementations]]></title><description><![CDATA[Explore essential prompt engineering patterns to enhance RAG implementations, ensuring accurate, context-aware AI responses in diverse applications]]></description><link>https://shittuolumide.hashnode.dev/prompt-engineering-patterns-for-successful-rag-implementations</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/prompt-engineering-patterns-for-successful-rag-implementations</guid><category><![CDATA[#PromptEngineering]]></category><category><![CDATA[llm]]></category><category><![CDATA[Artificial Intelligence]]></category><category><![CDATA[AI]]></category><category><![CDATA[RAG ]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Tue, 25 Feb 2025 14:31:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1740493398362/10b877f1-1f09-4456-8cff-93554ab568ba.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>RAG</strong> has been the magic sauce behind the scenes, empowering many AI-driven applications to transcend the divide from static knowledge toward dynamic and real-time information. But getting exactly the right responses- precise, relevant, and of high value- is both a science and an art. Herein comes your guide on implementing prompt engineering patterns to make any implementation of RAG more effective and efficient.</p>
<p><a target="_blank" href="https://imgflip.com/i/8mv2pm"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1740493451783/a689b41b-0947-4cfd-8105-b50a4cf6b13d.png" alt="Image source:Source: https://imgflip.com/i/8mv2pm" class="image--center mx-auto" /></a></p>
<h1 id="heading-why-prompt-engineering-matters-in-rag"><strong>Why Prompt Engineering Matters in RAG</strong></h1>
<p>Now, imagine setting a request to the AI assistant for today’s stock market trends, and it gives information from a finance book from ten years ago. This is what happens when your prompts are not clear, specified, or structured.</p>
<p><strong>RAG</strong> retrieves information from outside and builds informed responses, but its capability identifies highly with how the prompt is set. Well-structured and clearly defined prompts ensure the following:</p>
<ul>
<li><p>High retrieval accuracy</p>
</li>
<li><p>Less hallucination and misinformation</p>
</li>
<li><p>More context-aware responses</p>
</li>
</ul>
<h1 id="heading-prerequisites"><strong>Prerequisites</strong></h1>
<p>Before diving into the deep end, one should have:</p>
<ol>
<li><p>A high-level understanding of <strong>Large Language Models</strong> (LLMs)</p>
</li>
<li><p>Understanding of <strong>RAG</strong> architecture</p>
</li>
<li><p>Some Python experience (we are going to write a bit of code)</p>
</li>
<li><p>A sense of humor- Trust me, it helps.</p>
</li>
</ol>
<h1 id="heading-1-direct-retrieval-pattern"><strong>1. Direct Retrieval Pattern</strong></h1>
<p><strong>“Retrieve only, no guessing.”</strong></p>
<p>On questions requiring factual accuracy, forcing the model to rely on the retrieved documents minimizes hallucinations.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-python">prompt = <span class="hljs-string">"Using only the provided retrieved documents, answer the following question. Do not add any external knowledge."</span>
</code></pre>
<h2 id="heading-why-it-works"><strong>Why it works:</strong></h2>
<ul>
<li><p>Keeps answers grounded in retrieved data</p>
</li>
<li><p>Less speculation or incorrect responses</p>
</li>
</ul>
<h2 id="heading-pitfall"><strong>Pitfall:</strong></h2>
<ul>
<li>If too restrictive, the AI becomes overly cautious with many “I don’t know” responses.</li>
</ul>
<h1 id="heading-2-chain-of-thought-cot-prompting"><strong>2. Chain of Thought (CoT) Prompting</strong></h1>
<p><strong>“Think like a detective.”</strong></p>
<p>For complicated reasoning, the process of leading the AI through logical steps amplifies response quality.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-python">prompt = <span class="hljs-string">"Break down the following problem into logical steps and solve it step by step using the retrieved data."</span>
</code></pre>
<h2 id="heading-why-it-works-1"><strong>Why it works:</strong></h2>
<ul>
<li><p>Improves reasoning and transparency</p>
</li>
<li><p>Improves explainability in responses</p>
</li>
</ul>
<h2 id="heading-pitfall-1"><strong>Pitfall:</strong></h2>
<ul>
<li>Increases response time and token usage</li>
</ul>
<h1 id="heading-3-context-enrichment-pattern"><strong>3. Context Enrichment Pattern</strong></h1>
<p><strong>“More context, fewer errors.”</strong></p>
<p>Extra context in the prompt provides for more accurate responses.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-python">context = <span class="hljs-string">"You are a cybersecurity expert analyzing a recent data breach."</span>
prompt = <span class="hljs-string">f"<span class="hljs-subst">{context}</span> Based on the retrieved documents, explain the breach's impact and potential solutions."</span>
</code></pre>
<h2 id="heading-why-it-works-2"><strong>Why it works:</strong></h2>
<ul>
<li><p>Tailor responses to domain-specific needs</p>
</li>
<li><p>Reduces ambiguity in AI output</p>
</li>
</ul>
<h2 id="heading-pitfall-2"><strong>Pitfall:</strong></h2>
<ul>
<li>Too much context can overwhelm the model</li>
</ul>
<h1 id="heading-4-instruction-tuning-pattern"><strong>4. Instruction-Tuning Pattern</strong></h1>
<p><strong>“Be clear, be direct.”</strong></p>
<p>LLMs perform better when instructions are precise and structured.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-python">prompt = <span class="hljs-string">"Summarize the following document in three bullet points, each under 20 words."</span>
</code></pre>
<h2 id="heading-why-this-works"><strong>Why this works:</strong></h2>
<ul>
<li><p>Guides the model towards structured output</p>
</li>
<li><p>Avoids excessive verbosity</p>
</li>
</ul>
<h2 id="heading-pitfall-3"><strong>Pitfall:</strong></h2>
<ul>
<li>Rigid formats may limit nuanced responses</li>
</ul>
<h1 id="heading-5-persona-based-prompting"><strong>5. Persona-Based Prompting</strong></h1>
<p><strong>“Personalize responses for target groups.”</strong></p>
<p>If your RAG model serves heterogeneous end users, say <strong>novice vs. expert</strong>, response personalization will enrich participation.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-python">user_type = <span class="hljs-string">"Beginner"</span>
prompt = <span class="hljs-string">f"Explain blockchain technology as if I were a <span class="hljs-subst">{user_type}</span>, using simple language and real-world examples."</span>
</code></pre>
<h2 id="heading-why-it-works-3"><strong>Why it works:</strong></h2>
<ul>
<li><p>Increased accessibility</p>
</li>
<li><p>Enhances personalization</p>
</li>
</ul>
<h2 id="heading-common-mistake"><strong>Common mistake:</strong></h2>
<ul>
<li>Oversimplification could be missing information relevant to an expert</li>
</ul>
<h1 id="heading-6-error-handling-pattern"><strong>6. Error Handling Pattern</strong></h1>
<p><strong>“What if AI gets it wrong?”</strong></p>
<ul>
<li>Prompts have to include a reflection of the outcome so AI can flag any uncertainties.</li>
</ul>
<p><strong>Example:</strong></p>
<pre><code class="lang-python">prompt = <span class="hljs-string">"If your response contains conflicting information, state your confidence level and suggest areas for further research."</span>
</code></pre>
<h2 id="heading-why-it-works-4"><strong>Why it works:</strong></h2>
<ul>
<li><p>More transparent responses</p>
</li>
<li><p>Less risk of misinformation</p>
</li>
</ul>
<h2 id="heading-pitfall-4"><strong>Pitfall:</strong></h2>
<ul>
<li>AI may always give low-confidence answers, even when the answer is correct.</li>
</ul>
<h1 id="heading-7-multi-pass-query-refinement"><strong>7. Multi-Pass Query Refinement</strong></h1>
<p><strong>“Iterate until the answer is perfect.”</strong></p>
<p>Instead of providing a single-shot response, this approach iterates queries to refine accuracy.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-python">prompt = <span class="hljs-string">"Generate an initial answer, then refine it based on retrieved documents to improve accuracy."</span>
</code></pre>
<h2 id="heading-why-it-works-5"><strong>Why it works:</strong></h2>
<ul>
<li><p>Helps AI self-correct mistakes</p>
</li>
<li><p>Improves factual consistency</p>
</li>
</ul>
<h2 id="heading-pitfall-5"><strong>Pitfall:</strong></h2>
<ul>
<li>Requires more processing time</li>
</ul>
<h1 id="heading-8-hybrid-prompting-with-few-shot-examples"><strong>8. Hybrid Prompting with Few-Shot Examples</strong></h1>
<p><strong>“Show, don’t tell.”</strong></p>
<p>Few-shot learning reinforces the results in consistency, supported with examples.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-python">prompt = <span class="hljs-string">"Here are two examples of well-structured financial reports. Follow this pattern when summarizing the retrieved data."</span>
</code></pre>
<h2 id="heading-why-it-works-6"><strong>Why it works:</strong></h2>
<ul>
<li><p>Gives reference structure</p>
</li>
<li><p>Develops coherence and quality</p>
</li>
</ul>
<h2 id="heading-pitfall-6"><strong>Pitfall:</strong></h2>
<ul>
<li>Requires selected examples of curation</li>
</ul>
<h2 id="heading-implementing-rag-for-song-recommendations">Implementing <strong>RAG for Song Recommendations</strong></h2>
<pre><code class="lang-plaintext">import torch
from transformers import RagTokenizer, RagRetriever, RagSequenceForGeneration

# Load the RAG model, tokenizer, and retriever
model_name = "facebook/rag-sequence-nq"
tokenizer = RagTokenizer.from_pretrained(model_name)
retriever = RagRetriever.from_pretrained(model_name)
model = RagSequenceForGeneration.from_pretrained(model_name, retriever=retriever)

# Define user input: Mood for song recommendation
user_mood = "I'm feeling happy and energetic. Recommend some songs to match my vibe."

# Tokenize the query
input_ids = tokenizer(user_mood, return_tensors="pt").input_ids

# Generate a response using RAG
with torch.no_grad():
 output_ids = model.generate(input_ids, max_length=100, num_return_sequences=1)

# Decode and print the response
recommendation = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
print("🎵 Song Recommendations:", recommendation[0])
</code></pre>
<h1 id="heading-additional-considerations"><strong>Additional Considerations</strong></h1>
<p>There are a few things you need to also consider, namely <strong>handling long queries</strong>, <strong>optimizing retrieval quality</strong>, and <strong>evaluate and refine prompts.</strong></p>
<h2 id="heading-handling-long-queries"><strong>Handling Long Queries</strong></h2>
<ul>
<li><p>Break complicated queries into subqueries.</p>
</li>
<li><p>Summarize inputs before giving them to the model.</p>
</li>
<li><p>Order retrievals based on keyword relevance.</p>
</li>
</ul>
<h2 id="heading-optimising-retrieval-quality"><strong>Optimising Retrieval Quality</strong></h2>
<ul>
<li><p>Use of embeddings for superior similarity search</p>
</li>
<li><p>Fine-tuning of retriever models on the domain-specific task</p>
</li>
<li><p>Hybrid search: experimentation with BM 25 + Embeddings.</p>
</li>
</ul>
<h2 id="heading-evaluate-and-refine-prompts"><strong>Evaluate and Refine Prompts</strong></h2>
<ul>
<li><p>Response quality could be monitored via human feedback.</p>
</li>
<li><p>A/B Testing of Prompts for their efficacy</p>
</li>
<li><p>Iteration on prompts will need to be modified based on various metrics.</p>
</li>
</ul>
<h1 id="heading-conclusion-how-to-master-prompt-engineering-in-rag"><strong>Conclusion: How to Master Prompt Engineering in RAG</strong></h1>
<p>Mastery of <strong>RAG</strong> requires not only a powerful <strong>LLM</strong> but also precision in crafting the prompt. The right patterns help considerably increase response accuracy, relevance to the context, and swiftness. Be it finance, healthcare, cybersecurity, or any other domain, structured prompt engineering will ensure your AI delivers value-driven insight.</p>
<p><strong>Final Tip:</strong> Iterate. The best prompts evolve, much like the finest AI applications. A well-engineered prompt today may need to be adjusted tomorrow as your use cases expand and AI capabilities improve. Stay adaptive, experiment, and refine for optimal performance.</p>
<h2 id="heading-references"><strong>References</strong></h2>
<ol>
<li><p>Lewis, P., et al. “Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks.” NeurIPS, 2020.</p>
</li>
<li><p>Brown, T., et al. “Language Models are Few-Shot Learners.” NeurIPS, 2020.</p>
</li>
<li><p>OpenAI. “GPT-4 Technical Report.” 2023.</p>
</li>
<li><p>Google AI. “Understanding Prompt Engineering for LLMs.” Blog post, 2023.</p>
</li>
<li><p>Borgeaud, S., et al. “Improving Language Models by Retrieving from Trillions of Tokens.” DeepMind, 2022.</p>
</li>
<li><p>Radford, A., et al. “Learning Transferable Visual Models From Natural Language Supervision.” OpenAI, 2021.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Machine Learning Basics: Building Your First Predictive Model in R]]></title><description><![CDATA[Learn to build your first predictive model in R, a powerful tool for machine learning and data analysis]]></description><link>https://shittuolumide.hashnode.dev/machine-learning-basics-building-your-first-predictive-model-in-r</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/machine-learning-basics-building-your-first-predictive-model-in-r</guid><category><![CDATA[Machine Learning]]></category><category><![CDATA[R Language]]></category><category><![CDATA[Data Science]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Wed, 11 Dec 2024 13:39:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1733751992262/6f54cc92-a04c-46fc-b972-dee08eb7d956.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Machine learning models used for prediction purposes have become one of the most adopted technologies by different organizations. These models are capable of predicting future occurrences/outcomes, giving valuable insights for making key decisions, hence leading to growth and increased productivity.</p>
<p>In light of this, the demand for professionals capable of building high-performance predictive models continues to soar at a rapid rate. This has seen myriads of people with transferable skill sets move towards becoming machine learning engineers; I am talking about data analysts conversant with R or even statisticians or other researchers alike who utilize R, as R is a powerful language for building machine learning models.</p>
<p>In the course of this article, you will learn how to build a predictive model using the R programming language.</p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>This tutorial is suitable for people familiar with the R programming language, Visual Studio Code (as a code editor), and who already know a thing or two about machine learning (just a little is enough).</p>
<h3 id="heading-objectives">Objectives</h3>
<p>By going through this article, you should be able to:</p>
<ul>
<li><p>Learn how to build a simple machine-learning model in R using the Logistic Regression algorithm.</p>
</li>
<li><p>Evaluate the performance of your model.</p>
</li>
</ul>
<p>Machine learning (ML) can be likened to teaching a computer to learn from experience instead of being explicitly programmed for every task. Imagine showing a kid hundreds of pictures of cats and dogs and asking them to identify which is which — they’ll eventually figure it out. That’s essentially how ML works but for computers.</p>
<p>It all started with the idea of creating systems that could mimic human intelligence. Over the years, it evolved from simple rule-based systems to sophisticated algorithms that can handle vast amounts of data. Today, ML powers everything from voice assistants like Siri to personalized recommendations on Netflix.</p>
<p>At its core, ML involves feeding data into algorithms, training them to recognize patterns, and making predictions or decisions without constant human guidance.</p>
<h3 id="heading-building-a-predictive-model-in-r">Building a Predictive Model in R</h3>
<ol>
<li><strong>Install and load the necessary packages</strong></li>
</ol>
<p>I assume you already have R set up on your computer. If you don’t, feel free to check out this <a target="_blank" href="https://cran.r-project.org/doc/manuals/r-release/R-admin.html">resource</a>. Install and load the necessary packages you will be using for training the model, as shown below.</p>
<pre><code class="lang-python">install.packages(<span class="hljs-string">"tidyverse"</span>)  <span class="hljs-comment"># For data manipulation and visualization</span>
install.packages(<span class="hljs-string">"caret"</span>)      <span class="hljs-comment"># For model training and evaluation</span>
library(tidyverse)             <span class="hljs-comment"># loading the tidyverse library</span>
library(caret)                 <span class="hljs-comment"># loading the caret library</span>
</code></pre>
<p>2. <strong>Load your preferred dataset</strong></p>
<p>In this step, you choose the dataset you will use to train your model. It can be an externally prepared dataset in CSV format or a built-in dataset. For this article, we will be using the built-in <code>mtcars</code> dataset.</p>
<pre><code class="lang-python">data &lt;- mtcars
</code></pre>
<p>3. <strong>Exploratory data analysis</strong></p>
<p>This step involves understanding the dataset you are working with and checking its suitability for use. It encompasses a series of processes, such as checking for null values in the dataset and filling them appropriately if there are.</p>
<p>View the dataset</p>
<pre><code class="lang-python">glimpse(data)
</code></pre>
<p>Check for missing values in the <code>mtcars</code> built-in dataset.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Check for missing values</span>
sum(<span class="hljs-keyword">is</span>. na(mtcars))
</code></pre>
<p>View the statistical summary of the dataset.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Summary statistics</span>
summary(mtcars)
</code></pre>
<p>4. <strong>Split the dataset for testing and training the model</strong></p>
<p>This involves splitting your dataset into a particular proportion. In this example, we are using the 80:20 proportion, that is, 80% for training and the remaining 20% for testing the model.</p>
<p>Ensure reproducibility and split the dataset</p>
<pre><code class="lang-python">set.seed(<span class="hljs-number">123</span>)  <span class="hljs-comment"># For reproducibility</span>

<span class="hljs-comment"># Split the data into 80% training and 20% testing</span>
train_index &lt;- createDataPartition(data$mpg, p = <span class="hljs-number">0.8</span>, list = FALSE)
train_data &lt;- data[train_index, ]
test_data &lt;- data[-train_index, ]
</code></pre>
<p>5. <strong>Build the Linear Regression model</strong></p>
<p>Use the<code>train()</code> function from the caret package to build your model</p>
<pre><code class="lang-python"> <span class="hljs-comment"># Train the model</span>
model &lt;- train(
  mpg ~ wt + hp,  <span class="hljs-comment"># Formula: mpg as a function of wt and hp</span>
  data = train_data,
  method = <span class="hljs-string">"lm"</span>,  <span class="hljs-comment"># Linear regression method</span>
  trControl = trainControl(method = <span class="hljs-string">"cv"</span>, number = <span class="hljs-number">5</span>)  <span class="hljs-comment"># 5-fold cross-validation</span>
)

<span class="hljs-comment"># View model summary</span>
print(model)
</code></pre>
<p>In this step, we have successfully built our linear regression model. The next step is to evaluate its performance using a suitable metric. For this article, we are going to use the RMSE metric.</p>
<p>6. <strong>Model evaluation</strong></p>
<p>Use the model you have built in the previous step to make predictions on the test dataset and evaluate the predicted values using the RMSE metric.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Make predictions</span>
predictions &lt;- predict(model, newdata = test_data)

<span class="hljs-comment"># Evaluate performance</span>
results &lt;- data.frame(
  Actual = test_data$mpg,
  Predicted = predictions
)

<span class="hljs-comment"># Calculate RMSE and R-squared</span>
rmse &lt;- sqrt(mean((results$Actual - results$Predicted)^<span class="hljs-number">2</span>))

print(paste(<span class="hljs-string">"RMSE:"</span>, rmse))
</code></pre>
<p>7. <strong>Model visualization</strong></p>
<p>This is an optional step as it seeks to provide a visual expression of the predicted values and the actual values, showing the accuracy of the model.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Plot actual vs predicted</span>
plot(test_data$mpg, predictions, main = <span class="hljs-string">"Actual vs Predicted"</span>,
     xlab = <span class="hljs-string">"Actual mpg"</span>, ylab = <span class="hljs-string">"Predicted mpg"</span>)
abline(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, col = <span class="hljs-string">"red"</span>)  <span class="hljs-comment"># Add diagonal line for reference</span>
</code></pre>
<p>Congrats on making it this far. We have successfully built a linear regression machine learning model using the R programming language.</p>
<p>Let’s combine all the code snippets for a better understanding.</p>
<pre><code class="lang-python">install.packages(<span class="hljs-string">"tidyverse"</span>)  <span class="hljs-comment"># For data manipulation and visualization</span>
install.packages(<span class="hljs-string">"caret"</span>)      <span class="hljs-comment"># For model training and evaluation</span>
library(tidyverse)             <span class="hljs-comment"># loading the tidyverse library</span>
library(caret) 

data &lt;- mtcars

glimpse(data)

<span class="hljs-comment"># Check for missing values</span>
sum(<span class="hljs-keyword">is</span>. na(mtcars))

<span class="hljs-comment"># Summary statistics</span>
summary(mtcars)

set.seed(<span class="hljs-number">123</span>)  <span class="hljs-comment"># For reproducibility</span>

<span class="hljs-comment"># Split the data into 80% training and 20% testing</span>
train_index &lt;- createDataPartition(data$mpg, p = <span class="hljs-number">0.8</span>, list = FALSE)
train_data &lt;- data[train_index, ]
test_data &lt;- data[-train_index, ]

 <span class="hljs-comment"># Train the model</span>
model &lt;- train(
  mpg ~ wt + hp,  <span class="hljs-comment"># Formula: mpg as a function of wt and hp</span>
  data = train_data,
  method = <span class="hljs-string">"lm"</span>,  <span class="hljs-comment"># Linear regression method</span>
  trControl = trainControl(method = <span class="hljs-string">"cv"</span>, number = <span class="hljs-number">5</span>)  <span class="hljs-comment"># 5-fold cross-validation</span>
)

<span class="hljs-comment"># View model summary</span>
print(model)

<span class="hljs-comment"># Make predictions</span>
predictions &lt;- predict(model, newdata = test_data)

<span class="hljs-comment"># Evaluate performance</span>
results &lt;- data.frame(
  Actual = test_data$mpg,
  Predicted = predictions
)

<span class="hljs-comment"># Calculate RMSE and R-squared</span>
rmse &lt;- sqrt(mean((results$Actual - results$Predicted)^<span class="hljs-number">2</span>))

print(paste(<span class="hljs-string">"RMSE:"</span>, rmse))

<span class="hljs-comment"># Plot actual vs predicted</span>
plot(test_data$mpg, predictions, main = <span class="hljs-string">"Actual vs Predicted"</span>,
     xlab = <span class="hljs-string">"Actual mpg"</span>, ylab = <span class="hljs-string">"Predicted mpg"</span>)
abline(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, col = <span class="hljs-string">"red"</span>)  <span class="hljs-comment"># Add diagonal line for reference</span>
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In this article, we have built a Machine Learning model using the built-in <code>mtcars</code> dataset and the linear regression algorithm. Still, for your implementation when working on projects, you can use any other external dataset and algorithm you deem fit for the particular task.</p>
<p>It is recommended that you conduct proper exploratory data analysis on your dataset and experiment with different algorithms before selecting the one that best suits the task.</p>
]]></content:encoded></item><item><title><![CDATA[How to Install PySpark on Your Local Machine]]></title><description><![CDATA[PySpark, is a game-changer for data analysis and processing. This article breaks down the process of installation on your local machine.]]></description><link>https://shittuolumide.hashnode.dev/how-to-install-pyspark-on-your-local-machine</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/how-to-install-pyspark-on-your-local-machine</guid><category><![CDATA[Python]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[PySpark]]></category><category><![CDATA[Installation]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Programming Tips]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Mon, 09 Dec 2024 12:25:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1733746532212/10782ebe-f866-4493-8b9b-344fd94f731a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you’re stepping into the world of Big Data, you have likely heard of <a target="_blank" href="https://spark.apache.org/">Apache Spark</a><a target="_blank" href="https://spark.apache.org/">,</a> a powerful distributed computing system. <a target="_blank" href="https://spark.apache.org/docs/latest/api/python/index.html">PySpark</a><a target="_blank" href="https://spark.apache.org/docs/latest/api/python/index.html">,</a> the Python library for Apache Spark, is a favorite among data enthusiasts for its combination of speed, scalability, and ease of use. But setting it up on your local machine can feel a bit intimidating at first.</p>
<p>Fear not — this article walks you through the entire process, addressing common questions and making the journey as straightforward as possible.</p>
<h1 id="heading-what-is-pyspark-and-why-should-you-care">What is PySpark, and Why Should You Care?</h1>
<p>Before going into installation, let’s understand what PySpark is. PySpark allows you to leverage the massive computational power of Apache Spark using Python. Whether you’re analyzing terabytes of data, building machine learning models, or running ETL (<strong>Extract, Transform, Load</strong>) pipelines, PySpark allows you to work with data more efficiently than ever.</p>
<p>Now that you understand PySpark, let’s go through the installation process.</p>
<h2 id="heading-step-1-ensure-your-system-meets-the-requirements">Step 1: Ensure Your System Meets the Requirements</h2>
<p>PySpark runs on various machines, including <em>Windows</em>, <em>macOS</em>, and <em>Linux</em>. Here’s what you need to install it successfully:</p>
<ul>
<li><p><strong>Java Development Kit (JDK):</strong> PySpark requires Java (version 8 or 11 is recommended).</p>
</li>
<li><p><strong>Python:</strong> Ensure you have <em>Python 3.6</em> or later.</p>
</li>
<li><p><strong>Apache Spark Binary:</strong> You’ll download this during the installation process.</p>
</li>
</ul>
<p>To check your system readiness:</p>
<ol>
<li><p>Open your <strong>terminal</strong> or <strong>command prompt</strong>.</p>
</li>
<li><p>Type <code>java -version</code>and <code>python — version</code>to confirm Java and Python installations.</p>
</li>
</ol>
<p>If you don’t have Java or Python installed, follow these steps:</p>
<ul>
<li><p>For <em>Java</em>: Download it from <a target="_blank" href="https://www.oracle.com/java/technologies/javase-downloads.html">Oracle’s official website</a>.</p>
</li>
<li><p>For <em>Python</em>: Visit <a target="_blank" href="https://www.python.org/downloads/">Python’s download page</a>.</p>
</li>
</ul>
<h2 id="heading-step-2-install-java">Step 2: Install Java</h2>
<p>Java is the backbone of <strong>Apache Spark</strong>. To install it:</p>
<ol>
<li><p><strong>Download Java:</strong> Visit the <a target="_blank" href="https://www.oracle.com/java/technologies/javase-downloads.html">Java SE Development Kit download page</a>. Choose the appropriate version for your operating system.</p>
</li>
<li><p><strong>Install Java:</strong> Run the installer and follow the prompts. On Windows, you’ll need to set the <code>JAVA_HOME</code> environment variable. To do this:</p>
</li>
</ol>
<ul>
<li>Copy the path variable, go to the <strong><em>local disk</em></strong> on your machine, select <strong><em>program files</em></strong>, look for the <strong><em>java</em></strong> folder open it you will see <strong><em>jdk-17</em></strong> (your own version may not be 17). Open it, and you will be able to see your path and copy like below</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733746783078/2b4f3408-0d02-42a6-885f-70e1074ed8f5.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>Search for <strong><em>Environment Variables</em></strong> in the Windows search bar.</p>
</li>
<li><p>Under <strong><em>System Variables</em></strong>, click <strong>New</strong> and set the variable name as <code>JAVA_HOME</code> and the value as your <strong>Java</strong> installation path you copied above <strong><em>(e.g., C:\Program Files\Java\jdk-17)</em></strong>.</p>
</li>
</ul>
<p>3<strong>. Verify Installation:</strong> Open a terminal or command prompt and type <code>java-version</code>.</p>
<h2 id="heading-step-3-install-apache-spark">Step <strong>3: Install Apache Spark</strong></h2>
<ol>
<li><p><strong>Download Spark:</strong> Visit <a target="_blank" href="https://spark.apache.org/downloads.html">Apache Spark’s website</a> and select the version compatible with your needs. Use the pre-built package for Hadoop (a common pairing with Spark).</p>
</li>
<li><p><strong>Extract the Files:</strong></p>
</li>
</ol>
<ul>
<li><p>On <strong><em>Windows</em></strong>, use a tool like WinRAR or 7-Zip to extract the file.</p>
</li>
<li><p>On <strong><em>macOS/Linux</em></strong>, use the command <code>tar -xvf spark-&lt;version&gt;.tgz</code></p>
</li>
</ul>
<ol start="3">
<li><p><strong>Set Environment Variables:</strong></p>
</li>
<li><p>For <strong><em>Windows</em></strong>: Add Spark’s bin directory to your system’s PATH variable.</p>
</li>
<li><p>For <strong><em>macOS/Linux</em></strong>: Add the following lines to your <code>.bashrc</code> or <code>.zshrc</code> file:</p>
</li>
</ol>
<pre><code class="lang-python">export SPARK_HOME=/path/to/spark
export PATH=$SPARK_HOME/bin:$PATH
</code></pre>
<ol start="4">
<li><strong>Verify Installation:</strong> Open a terminal and type <code>spark-shell</code>. You should see Spark’s interactive shell start.</li>
</ol>
<h2 id="heading-step-4-install-hadoop-optional-but-recommended">Step 4: Install Hadoop (Optional but Recommended)</h2>
<p>While Spark doesn’t strictly require <a target="_blank" href="https://hadoop.apache.org/">Hadoop</a>, many users install it for its HDFS (Hadoop Distributed File System) support. To install Hadoop:</p>
<ol>
<li><p>Download Hadoop binaries from <a target="_blank" href="https://hadoop.apache.org/releases.html">Apache Hadoop’s website</a>.</p>
</li>
<li><p>Extract the files and set up the <code>HADOOP_HOME</code> environment variable.</p>
</li>
</ol>
<h2 id="heading-step-5-install-pyspark-via-pip">Step 5: Install PySpark via pi<strong>p</strong></h2>
<p>Installing PySpark is a breeze with Python’s pip tool. Simply run:</p>
<pre><code class="lang-python">pip install pyspark
</code></pre>
<p>To verify, open a Python shell and type:</p>
<pre><code class="lang-python">pip install pysparkark.__version__)
</code></pre>
<p>If you see a version number, congratulations! PySpark is installed 🎉</p>
<h2 id="heading-step-6-test-your-pyspark-installation">Step 6: Test Your PySpark Installatio<strong>n</strong></h2>
<p>Here’s where the fun begins. Let’s ensure everything is working smoothly:</p>
<p><strong>Create a Simple Script:  
</strong>Open a text editor and paste the following code:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> pyspark.sql <span class="hljs-keyword">import</span> SparkSession
spark = SparkSession.builder.appName(<span class="hljs-string">"PySparkTest"</span>).getOrCreate()
data = [(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">25</span>), (<span class="hljs-string">"Bob"</span>, <span class="hljs-number">30</span>), (<span class="hljs-string">"Cathy"</span>, <span class="hljs-number">29</span>)]
columns = [<span class="hljs-string">"Name"</span>, <span class="hljs-string">"Age"</span>]
df = spark.createDataFrame(data, columns)
df.show()
</code></pre>
<p>Save it as <strong><em>test_pyspark.py</em></strong></p>
<p><strong>Run the Script:  
</strong>In your terminal, navigate to the script’s directory and type:</p>
<pre><code class="lang-python">python test_pyspark.py
</code></pre>
<p>You should see a neatly formatted table displaying the <strong>names</strong> and <strong>ages</strong>.</p>
<h2 id="heading-troubleshooting-common-issues">Troubleshooting Common Issues</h2>
<p>Even with the best instructions, hiccups happen. Here are some common problems and solutions:</p>
<ul>
<li><p><strong>Issue:</strong> <code>java.lang.NoClassDefFoundError</code><br />  <strong>Solution:</strong> Double-check your <code>JAVA_HOME</code>and PATH variables.</p>
</li>
<li><p><strong>Issue:</strong> PySpark installation succeeded, but the test script failed.<br />  <strong>Solution:</strong> Ensure you’re using the correct Python version. Sometimes, virtual environments can cause conflicts.</p>
</li>
<li><p><strong>Issue: The</strong> <code>spark-shell</code> command doesn’t work.<br />  <strong>Solution:</strong> Verify that the Spark directory is correctly added to your PATH.</p>
</li>
</ul>
<h2 id="heading-why-use-pyspark-locally">Why Use PySpark Locally?</h2>
<p>Many users wonder why they should bother installing PySpark on their local machine when it’s primarily used in distributed systems. Here’s why:</p>
<ul>
<li><p><strong>Learning:</strong> Experiment and learn Spark concepts without requiring a cluster.</p>
</li>
<li><p><strong>Prototyping:</strong> Test small data jobs locally before deploying them to a larger environment.</p>
</li>
<li><p><strong>Convenience:</strong> Debug issues and develop applications with ease.</p>
</li>
</ul>
<h2 id="heading-boost-your-pyspark-productivity">Boost Your PySpark Productivity</h2>
<p>To get the most out of PySpark, consider these tips:</p>
<ol>
<li><p><strong>Set Up a Virtual Environment:</strong> Use tools like <code>venv</code> or <code>conda</code> to isolate your PySpark installation.</p>
</li>
<li><p><strong>Integrate with IDEs:</strong> Tools like <strong>PyCharm</strong> and <strong>Jupyter Notebook</strong> make PySpark development more interactive.</p>
</li>
<li><p><strong>Leverage PySpark Documentation:</strong> Visit <a target="_blank" href="https://spark.apache.org/docs/latest/api/python/index.html">Apache Spark’s documentation</a> for in-depth guidance.</p>
</li>
</ol>
<h2 id="heading-engage-with-the-pyspark-community">Engage with the PySpark Community</h2>
<p>Getting stuck is normal, especially with a powerful tool like PySpark. Engage with the vibrant PySpark community for help:</p>
<ul>
<li><p><strong>Join Forums:</strong> Websites like Stack Overflow have dedicated Spark tags.</p>
</li>
<li><p><strong>Attend Meetups:</strong> Spark and Python communities often host events where you can learn and network.</p>
</li>
<li><p><strong>Follow Blogs:</strong> Many data professionals share their experiences and tutorials online.</p>
</li>
</ul>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Installing PySpark on your local machine may seem daunting at first, but following these steps makes it manageable and rewarding. Whether you’re just starting your data journey or sharpening your skills, PySpark equips you with the tools to tackle real-world data problems.</p>
<p>PySpark, the Python API for Apache Spark, is a game-changer for data analysis and processing. While its potential is immense, setting it up on your local machine can feel challenging. This article breaks down the process step-by-step, covering everything from installing Java and downloading Spark to testing your setup with a simple script.</p>
<p>With PySpark installed locally, you can prototype data workflows, learn Spark’s features, and test small-scale projects without needing a full cluster.</p>
]]></content:encoded></item><item><title><![CDATA[How to Use PySpark for Machine Learning]]></title><description><![CDATA[Learn how to use PySpark, a Python API for Apache Spark, to build a machine learning model using the Linear Regression algorithm]]></description><link>https://shittuolumide.hashnode.dev/how-to-use-pyspark-for-machine-learning</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/how-to-use-pyspark-for-machine-learning</guid><category><![CDATA[Machine Learning]]></category><category><![CDATA[Python]]></category><category><![CDATA[PySpark]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Wed, 04 Dec 2024 15:08:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1733324513866/a618eaa7-e03a-402a-ad66-c3e58d05d3e8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Since the release of Apache Spark (an open-source framework for processing Big Data), it has become one of the most widely used technologies for processing large amounts of data in parallel across multiple containers — it prides itself on efficiency and speed compared to similar software that existed before it.</p>
<p>Working with this amazing technology in Python is feasible through PySpark, a Python API that allows you to interact with and tap into ApacheSpark’s amazing potential using the Python programming language.</p>
<p>In this article, you will learn and get started with using PySpark to build a machine-learning model using the Linear Regression algorithm.</p>
<blockquote>
<p><strong><em>Note*</em></strong>: Having prior knowledge of Python, an IDE like VSCode, how to use a command prompt/terminal and familiarity with Machine Learning concepts is essential for proper understanding of the concepts contained in this article.*</p>
</blockquote>
<p>By going through this article, you should be able to:</p>
<ul>
<li><p>Understand what ApacheSpark is.</p>
</li>
<li><p>Learn about PySpark and how to use it for Machine Learning.</p>
</li>
</ul>
<h2 id="heading-whats-pyspark-all-about"><strong>What’s PySpark all about?</strong></h2>
<p>According to the Apache Spark official <a target="_blank" href="https://spark.apache.org/">website</a>, PySpark lets you utilize the combined strengths of ApacheSpark (simplicity, speed, scalability, versatility) and Python (rich ecosystem, matured libraries, simplicity) for “<strong><em>data engineering, data science, and machine learning on single-node machines or clusters</em></strong>.”</p>
<p><a target="_blank" href="https://www.databricks.com/glossary/pyspark"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733324594170/43f94c02-125a-402f-b2ee-3c3f57c7f8a9.png" alt="Image source" class="image--center mx-auto" /></a></p>
<p>PySpark is the Python API for ApacheSpark, which means it serves as an interface that lets your code written in Python communicate with the ApacheSpark technology written in Scala. This way, professionals already familiar with the Python ecosystem can quickly utilize the ApacheSpark technology. This also ensures that existing libraries used in Python remain relevant.</p>
<h1 id="heading-detailed-guide-on-how-to-use-pyspark-for-machine-learning"><strong>Detailed Guide on how to use PySpark for Machine Learning</strong></h1>
<p>In the ensuing steps, we will build a machine-learning model using the Linear Regression algorithm:</p>
<ol>
<li><strong>Install project dependencies:</strong> I’m assuming that you already have Python installed on your machine. If not, install it before moving to the next step. Open your terminal or command prompt and enter the code below to install the <code>PySpark library</code>.</li>
</ol>
<pre><code class="lang-python">pip install pyspark
</code></pre>
<p>You can install these additional Python libraries if you do not have them.</p>
<pre><code class="lang-python">pip install pandas numpy
</code></pre>
<p>2. <strong>Create a file and import the necessary libraries:</strong> Open VSCode, and in your chosen project directory, create a file for your project, e.g <code>pyspart_model.py</code>. Open the file and import the necessary libraries for the project.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> pyspark.sql <span class="hljs-keyword">import</span> SparkSession
<span class="hljs-keyword">from</span> pyspark.ml.feature <span class="hljs-keyword">import</span> VectorAssembler
<span class="hljs-keyword">from</span> pyspark.ml.classification <span class="hljs-keyword">import</span> LogisticRegression
<span class="hljs-keyword">from</span> pyspark.ml.evaluation <span class="hljs-keyword">import</span> BinaryClassificationEvaluator
<span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd
</code></pre>
<p>3. <strong>Create a spark session</strong>: Start a spark session for the project by entering this code under the imports.</p>
<pre><code class="lang-python">spark = SparkSession.builder.appName(<span class="hljs-string">"LogisticRegressionExample"</span>).getOrCreate()
</code></pre>
<p>4. <strong>Read the CSV file (the dataset you will be working with)</strong>: If you already have your dataset named <strong><em>data.csv</em></strong> in your project directory/folder, load it using the code below.</p>
<pre><code class="lang-python">data = spark.read.csv(<span class="hljs-string">"data.csv"</span>, header=<span class="hljs-literal">True</span>, inferSchema=<span class="hljs-literal">True</span>)
</code></pre>
<p>5. <strong>Exploratory data analysis</strong>: This step helps you understand the dataset you are working with. Check for null values and decide on the cleansing approach to use.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Display the schema my</span>
 data.printSchema() 
<span class="hljs-comment"># Show the first ten rows </span>
data.show(<span class="hljs-number">10</span>)
<span class="hljs-comment"># Count null values in each column</span>
missing_values = df.select(
    [count(when(isnull(c), c)).alias(c) <span class="hljs-keyword">for</span> c <span class="hljs-keyword">in</span> df.columns]
)

<span class="hljs-comment"># Show the result</span>
missing_values.show()
</code></pre>
<p>Optionally, if you are working with a small dataset, you can convert it to a Python data frame and directory and use Python to check for missing values.</p>
<pre><code class="lang-python">pandas_df = data.toPandas()
<span class="hljs-comment"># Use Pandas to check missing values</span>
print(pandas_df.isna().sum())
</code></pre>
<p>6. <strong>Data preprocessing</strong>: This step involves converting the columns/features in the dataset into a format that PySpark’s machine-learning library can easily understand or is compatible with.</p>
<p>Use <strong><em>VectorAssembler</em></strong> to combine all features into a single vector column.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Combine feature columns into a single vector column</span>
feature_columns = [col <span class="hljs-keyword">for</span> col <span class="hljs-keyword">in</span> data.columns <span class="hljs-keyword">if</span> col != <span class="hljs-string">"label"</span>]
assembler = VectorAssembler(inputCols=feature_columns, outputCol=<span class="hljs-string">"features"</span>)

<span class="hljs-comment"># Transform the data</span>
data = assembler.transform(data)

<span class="hljs-comment"># Select only the 'features' and 'label' columns for training</span>
final_data = data.select(<span class="hljs-string">"features"</span>, <span class="hljs-string">"label"</span>)

<span class="hljs-comment"># Show the transformed data</span>
final_data.show(<span class="hljs-number">5</span>)
</code></pre>
<p>7. <strong>Split the dataset</strong>: Split the dataset in a proportion that is convenient for you. Here, we are using 70% to 30%: 70% for training and 30% for testing the model.</p>
<pre><code class="lang-python">train_data, test_data = final_data.randomSplit([<span class="hljs-number">0.7</span>, <span class="hljs-number">0.3</span>], seed=<span class="hljs-number">42</span>)
</code></pre>
<p>8. <strong>Train your model:</strong> We are using the Logistic Regression algorithm for training our model.</p>
<p>Create an instance of the LogisticRegression class and fit the model.</p>
<pre><code class="lang-python">lr = LogisticRegression(featuresCol=<span class="hljs-string">"features"</span>, labelCol=<span class="hljs-string">"label"</span>)

<span class="hljs-comment"># Train the model</span>
lr_model = lr.fit(train_data)
</code></pre>
<p>9. <strong>Make predictions with your trained model:</strong> Use the model we have trained in the previous step to make predictions</p>
<pre><code class="lang-python">predictions = lr_model.transform(test_data)
<span class="hljs-comment"># Show predictions</span>
predictions.select(<span class="hljs-string">"features"</span>, <span class="hljs-string">"label"</span>, <span class="hljs-string">"prediction"</span>, <span class="hljs-string">"probability"</span>).show(<span class="hljs-number">5</span>)
</code></pre>
<p>10. <strong>Model Evaluation</strong>: Here, the model is being evaluated to determine its predictive performance or its level of correctness. We achieve this by using a suitable evaluation metric.</p>
<p>Evaluate the model using the AUC metric</p>
<pre><code class="lang-python">evaluator = BinaryClassificationEvaluator(rawPredictionCol=<span class="hljs-string">"rawPrediction"</span>, labelCol=<span class="hljs-string">"label"</span>, metricName=<span class="hljs-string">"areaUnderROC"</span>)

<span class="hljs-comment"># Compute the AUC</span>
auc = evaluator.evaluate(predictions)
print(<span class="hljs-string">f"Area Under ROC: <span class="hljs-subst">{auc}</span>"</span>)
</code></pre>
<p>The end-to-end code used for this article is shown below:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> pyspark.sql <span class="hljs-keyword">import</span> SparkSession
<span class="hljs-keyword">from</span> pyspark.ml.feature <span class="hljs-keyword">import</span> VectorAssembler
<span class="hljs-keyword">from</span> pyspark.ml.classification <span class="hljs-keyword">import</span> LogisticRegression
<span class="hljs-keyword">from</span> pyspark.ml.evaluation <span class="hljs-keyword">import</span> BinaryClassificationEvaluator

<span class="hljs-comment"># Start Spark session</span>
spark = SparkSession.builder.appName(<span class="hljs-string">"LogisticRegressionExample"</span>).getOrCreate()

<span class="hljs-comment"># Load and preprocess data</span>
data = spark.read.csv(<span class="hljs-string">"data.csv"</span>, header=<span class="hljs-literal">True</span>, inferSchema=<span class="hljs-literal">True</span>)
assembler = VectorAssembler(inputCols=[col <span class="hljs-keyword">for</span> col <span class="hljs-keyword">in</span> data.columns <span class="hljs-keyword">if</span> col != <span class="hljs-string">"label"</span>], outputCol=<span class="hljs-string">"features"</span>)
data = assembler.transform(data).select(<span class="hljs-string">"features"</span>, <span class="hljs-string">"label"</span>)

<span class="hljs-comment"># Split the data</span>
train_data, test_data = data.randomSplit([<span class="hljs-number">0.7</span>, <span class="hljs-number">0.3</span>], seed=<span class="hljs-number">42</span>)

<span class="hljs-comment"># Train the model</span>
lr = LogisticRegression(featuresCol=<span class="hljs-string">"features"</span>, labelCol=<span class="hljs-string">"label"</span>)
lr_model = lr.fit(train_data)

<span class="hljs-comment"># Make predictions</span>
predictions = lr_model.transform(test_data)
predictions.select(<span class="hljs-string">"features"</span>, <span class="hljs-string">"label"</span>, <span class="hljs-string">"prediction"</span>, <span class="hljs-string">"probability"</span>).show(<span class="hljs-number">5</span>)

<span class="hljs-comment"># Evaluate the model</span>
evaluator = BinaryClassificationEvaluator(rawPredictionCol=<span class="hljs-string">"rawPrediction"</span>, labelCol=<span class="hljs-string">"label"</span>, metricName=<span class="hljs-string">"areaUnderROC"</span>)
auc = evaluator.evaluate(predictions)
print(<span class="hljs-string">f"Area Under ROC: <span class="hljs-subst">{auc}</span>"</span>)
</code></pre>
<h2 id="heading-next-steps"><strong>Next steps 🤔</strong></h2>
<p>We have reached the end of this article. By following the steps above, you have built your machine-learning model using PySpark.</p>
<p>Always ensure that your dataset is clean and free of null values before proceeding to the next steps. Lastly, make sure your features all contain numerical values before going ahead to train your model.</p>
]]></content:encoded></item><item><title><![CDATA[Building a PDF Summarizer with LangChain]]></title><description><![CDATA[Building a PDF Summarizer with LangChain]]></description><link>https://shittuolumide.hashnode.dev/building-a-pdf-summarizer-with-langchain</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/building-a-pdf-summarizer-with-langchain</guid><category><![CDATA[AI]]></category><category><![CDATA[Python]]></category><category><![CDATA[llm]]></category><category><![CDATA[langchain]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Tue, 12 Dec 2023 00:00:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1702338229844/76d863d5-911c-4a7f-8db2-9404957a635e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We are in an era inundated with information, and the ability to distill complex documents into concise, digestible summaries is a skill in high demand. Imagine a world where lengthy PDFs, often dense with data, could be swiftly summarized with precision. </p>
<p>There are many paid and free tools that can help summarize documents such as PDFs out there, but you can build your custom PDF summarizer tailored to your taste using tools powered by LLMs.</p>
<p>In this article, you will learn how to build a PDF summarizer using LangChain, Gradio and you will be able to see your project live, so you if are looking to get started with LangChain or build an LLM-powered application for your portfolio, this tutorial is for you. </p>
<h4 id="heading-prerequisites">Prerequisites</h4>
<ul>
<li><strong>LangChain</strong>: This is one of the most useful libraries to help developers build apps powered by LLMs.<br />  LangChain enables LLM models to generate responses based on the most up-to-date information available online and also simplifies the process of organizing large volumes of data so that it can be easily accessed by LLMs.</li>
</ul>
<p>Installation using <code>pip</code> .</p>
<pre><code class="lang-python">pip install langchain
</code></pre>
<ul>
<li><strong>Gradio</strong>: Gradio is the fastest way to demo your machine learning model with a friendly web interface so that anyone can use it, anywhere!</li>
</ul>
<p>Installation using <code>pip</code>.</p>
<pre><code class="lang-python">pip install gradio
</code></pre>
<p>To build this LLM-powered application, we will break it down into three simple and easy steps.</p>
<h4 id="heading-step-1">Step 1:</h4>
<p>Import the important libraries, for this tutorial we will import LangChain and Gradio. </p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> langchain.document_loaders <span class="hljs-keyword">import</span> PyPDFLoader
<span class="hljs-keyword">import</span> gradio <span class="hljs-keyword">as</span> gr
loader = PyPDFLoader(<span class="hljs-string">"whitepaper.pdf"</span>) 
documents = loader.load()
</code></pre>
<p>From the code above: </p>
<ul>
<li><p><code>from langchain.document_loaders import PyPDFLoader</code>: Imports the PyPDFLoader module from LangChain, enabling PDF document loading (“<strong>whitepaper.pdf</strong>”) which is in the same directory as our Python script.</p>
</li>
<li><p><code>import gradio as gr</code>: Imports Gradio, a Python library for creating customizable UI components for machine learning models and functions.</p>
</li>
</ul>
<h4 id="heading-step-2">Step 2:</h4>
<p>Create a summarize function to make the summarization. This function will define the PDF file path and an optional custom prompt as input.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">summarize_pdf</span> (<span class="hljs-params">pdf_file_path, custom_prompt=<span class="hljs-string">""</span></span>):</span>
    loader = PyPDFLoader(pdf_file_path)
    docs = loader.load_and_split()
    chain = load_summarize_chain(llm, chain_type=<span class="hljs-string">"map_reduce"</span>)
    summary = chain.run(docs)

    <span class="hljs-keyword">return</span> summary
</code></pre>
<ul>
<li><p>We define a function named <code>summarize_pdf</code> that takes a PDF file path and an optional custom prompt.</p>
</li>
<li><p>Then we use the PyPDFLoader to load and split the PDF document into separate sections.</p>
</li>
<li><p>Utilizing the LangChain’s summarization capabilities through the <code>load_summarize_chain</code> function to generate a summary based on the loaded document.</p>
</li>
<li><p>Return the generated summary.</p>
</li>
</ul>
<h4 id="heading-step-3">Step 3:</h4>
<p>This is the step where we need to set the Gradio Interface. </p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    input_pdf_path = gr.inputs.Textbox(label=<span class="hljs-string">"Enter the PDF file path"</span>)
    output_summary = gr.outputs.Textbox(label=<span class="hljs-string">"Summary"</span>)

    interface = gr.Interface(
        fn = summarize_pdf,
        inputs = input_pdf_path,
        outputs = output_summary,
        title = <span class="hljs-string">"PDF Summarizer"</span>,
        description = <span class="hljs-string">"This app allows you to summarize your PDF files."</span>,
    ).launch(share=<span class="hljs-literal">True</span>)
</code></pre>
<ul>
<li><p>Sets up Gradio UI components for user interaction.</p>
</li>
<li><p>We define an input field (<code>input_pdf_path</code>) for users to enter the PDF file path.</p>
</li>
<li><p>Then we specify an output field (<code>output_summary</code>) to display the summarized text.</p>
</li>
<li><p>We create a Gradio interface (<code>interface</code>) that utilizes the <code>summarize_pdf</code> function as the core functionality.</p>
</li>
<li><p>Finally, we configure the interface with a title, description, input/output components, and launch the UI for user interaction.</p>
</li>
</ul>
<h4 id="heading-launch-testing">Launch/ Testing</h4>
<p>We can now call the <code>main()</code> function to run the application. </p>
<pre><code class="lang-python">main()
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702338685893/a6650b6d-adc3-4f5a-9309-46f21ab41563.png" alt class="image--center mx-auto" /></p>
<p>From the screenshot, you will see that Gradio launched the application on a public and private URL. </p>
<p>Here is what the finished project looks like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702338796633/2723c356-1fdd-4942-ac0e-dfbf94f41c21.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>By harnessing LangChain’s capabilities alongside Gradio’s intuitive interface, we’ve demystified the process of converting lengthy PDF documents into concise, informative summaries.</p>
<p>This isn’t just about building a tool; it’s about embracing the potential of technology to enhance information accessibility. Through this article, we’ve bridged the gap between complex data and user-friendly insights, empowering individuals to navigate through vast volumes of information effortlessly.</p>
<p>Happy summarizing! 😎 </p>
<h4 id="heading-resources">Resources</h4>
<p>Full GitHub code:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/zenUnicorn/PDF-Summarizer-Using-LangChain">https://github.com/zenUnicorn/PDF-Summarizer-Using-LangChain</a></div>
<p> </p>
<p>LangChain documentation:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://python.langchain.com/docs/get_started/introduction">https://python.langchain.com/docs/get_started/introduction</a></div>
]]></content:encoded></item><item><title><![CDATA[Your LLM hallucinates, Why?]]></title><description><![CDATA[Your LLM hallucinates, Why?]]></description><link>https://shittuolumide.hashnode.dev/your-llm-hallucinates-why</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/your-llm-hallucinates-why</guid><category><![CDATA[AI]]></category><category><![CDATA[llm]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Wed, 29 Nov 2023 14:43:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1701268731849/f4bfa775-4d3a-4111-b96e-dec001430845.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>It is a fact that large language models (LLMs) have really made life easier for the whole world, and there has really been a huge adoption of AI in all areas of life. But as much as this new trend is interesting and helpful, it also has its limitations.</p>
<p>One of the limitations of LLM is “<strong><em>hallucination</em></strong>”, others include:</p>
<ol>
<li><p>Contextual understanding</p>
</li>
<li><p>Domain-Specific Knowledge</p>
</li>
<li><p>Lack of Common Sense Reasoning</p>
</li>
<li><p>Continual learning constraints.</p>
</li>
</ol>
<h2 id="heading-what-does-it-really-mean-for-an-llm-to-hallucinate"><strong>What does it really mean for an LLM to hallucinate?</strong></h2>
<p>Hallucination refers to instances where the model generates information or outputs that are factually incorrect, nonsensical, or not grounded in the provided context.</p>
<p>We can also say:</p>
<p>A hallucination occurs when the model generates text or responses that seem plausible on the surface but lack factual accuracy or logical consistency.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1701268772699/ea62c434-72fd-4bb8-a122-39544e5724b4.jpeg" alt class="image--center mx-auto" /></p>
<p>Things to consider if your model is hallucinating:</p>
<h3 id="heading-token-limit">- Token Limit</h3>
<p>The token limit is the maximum number of tokens or words, that the model can process in a single sequence. Tokens can include words, subwords, or characters, each represented as a unit in the model’s input.</p>
<p>This limit is imposed due to computational constraints and memory limitations within the model architecture. It affects both the input and output of the model. When the input text exceeds this limit, the model cannot process the entire sequence at once, potentially leading to truncation, where only a portion of the input is considered. Similarly, for text generation tasks, the output length is also capped by this token limit.</p>
<p>The token window limit is how many words an LLM can absorb while generating an answer. Your LLM (e.g. <strong>ChatGPT</strong>) is a sponge — what does this mean?<br />Too much much water (words) = no more absorption.</p>
<ul>
<li><p><code>GPT — 3</code> has a limit of <strong>2048</strong> tokens (<a target="_blank" href="https://platform.openai.com/docs/models/gpt-3-5">gpt-3.5-turbo has up 16,385 tokens</a>).</p>
</li>
<li><p><code>GPT—4</code> has a token limit of <strong>128,000</strong> tokens.</p>
</li>
</ul>
<p><a target="_blank" href="https://platform.openai.com/docs/models/gpt-3-5"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1701350993095/59d2925e-fd8a-4ac5-8eeb-ab16c689f304.png" alt class="image--center mx-auto" /></a></p>
<p>For instance, if an LLM has a token limit of 2048 tokens, any input longer than that would need to be split into smaller segments for processing, potentially affecting the context and coherence of the information being processed.</p>
<p>This token limit poses challenges when dealing with lengthy texts, complex documents, or tasks that require processing a large amount of information in a single sequence and this can lead to model hallucinations.</p>
<h3 id="heading-token-isnt-everything">- Token isn’t everything</h3>
<p><code>Claude 2.1</code> now has a 200,000 token limit and you might think it must be the best LLM yet. Well, not really. An academic paper shows the opposite, they tested <code>Cluade 2.1</code> and <code>GPT-4</code>. They performed a “<strong><em>needle in a haystack</em></strong>” scenario and both LLM had to find the information. The longer the text, the harder. Makes sense?<br />The study also shows other factors:</p>
<ul>
<li><p>How attentive to details the LLM is.</p>
</li>
<li><p>It’s ability to discern relevance.</p>
</li>
</ul>
<p>So bigger does not necessarily mean better, it challenges the notion that a larger token limit in LLMs = better performance.</p>
<h3 id="heading-the-data-training-bias">- The data training bias</h3>
<p>What you feed the LLM = the quality of the LLM, so this means that the quality of the training matters. When the training data is bad, there can be a biased data reflection, potentially perpetuating or amplifying societal biases.</p>
<h2 id="heading-wrap-up"><strong>Wrap up</strong></h2>
<p>Recognizing these limitations helps in using LLMs effectively while considering their strengths and weaknesses. Addressing and minimizing hallucination in LLMs involves ongoing research and development to enhance the model’s contextual understanding, improve fact-checking capabilities, and refine its ability to generate accurate and contextually appropriate responses.</p>
]]></content:encoded></item><item><title><![CDATA[Synergy in AI: Bridging the Gap Between Data Science and Business]]></title><description><![CDATA[A 2023 report by McKinsey & Company found that companies that are data-driven are more likely to outperform their peers by up to 5%. In 2021, a study by…]]></description><link>https://shittuolumide.hashnode.dev/synergy-in-ai-bridging-the-gap-between-data-science-and-business</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/synergy-in-ai-bridging-the-gap-between-data-science-and-business</guid><category><![CDATA[AI]]></category><category><![CDATA[Data Science]]></category><category><![CDATA[business]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Tue, 24 Oct 2023 09:31:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1698139524887/c4f5211e-eec2-40e4-8b94-18d4bd389b90.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A 2023 report by <a target="_blank" href="https://www.mckinsey.com/capabilities/mckinsey-digital/our-insights/new-years-resolutions-for-tech-in-2023">McKinsey &amp; Company</a> found that companies that are data-driven are more likely to outperform their peers by up to 5%. In 2021, a study by <a target="_blank" href="https://hbr.org/2019/01/data-science-and-the-art-of-persuasion">Havard Business</a> Review found that companies that have a strong data culture are more likely to be innovative and successful.</p>
<p>These statistics show that data science is becoming increasingly important for businesses of all sizes. However, there is still a gap between data scientists and business users. This gap can lead to a number of problems, such as:</p>
<ul>
<li><p>Data scientists not understanding the needs of the business.</p>
</li>
<li><p>Business users not understanding the technical capabilities of data science.</p>
</li>
<li><p>Data science projects not being aligned with business goals.</p>
</li>
<li><p>Data science insights not being used to make business decisions.</p>
</li>
</ul>
<p>At its core, synergy in AI represents the harmonious integration of data science and business operations. It’s the science of combining data-driven insights with strategic decision-making, creating a dynamic partnership that enhances the overall performance and competitiveness of an organization. In essence, it’s about leveraging the incredible potential of AI and data analytics to fuel business growth, improve efficiency, and stay ahead in an increasingly data-centric world.</p>
<h2 id="heading-real-world-examples-of-successful-synergy"><strong>Real-world examples of successful synergy</strong></h2>
<p>The concept of synergy between data science and business is not theoretical; it has already yielded remarkable results in real-world scenarios. Several organizations have harnessed the power of this synergy to achieve outstanding outcomes:</p>
<ul>
<li><p><strong>Netflix</strong>: The streaming giant employs data science to understand user preferences, recommend content, and personalize the user experience. By seamlessly integrating data science into their business model, Netflix has become a content powerhouse, creating hit shows and retaining millions of subscribers worldwide.</p>
</li>
<li><p><strong>Amazon</strong>: Amazon’s recommendation engine, powered by advanced data analytics, has significantly boosted its sales. This collaborative approach between data scientists and business teams enables them to offer personalized product suggestions, improving customer satisfaction and driving revenue.</p>
</li>
<li><p><strong>Uber</strong>: Uber utilizes data science not only for optimizing ride routes but also for surge pricing, matching drivers with riders, and predicting demand patterns. This collaborative approach has not only made ride-sharing convenient for customers but also enhanced drivers’ earnings and the company’s overall profitability.</p>
</li>
</ul>
<h2 id="heading-why-bridge-the-gap"><strong>Why bridge the gap?</strong></h2>
<p>Why is bridging the gap between data science and business so crucial in today’s landscape? The answer lies in the transformative power of data. Data has evolved from being merely a byproduct of business operations to a strategic asset that, when harnessed effectively, can unlock a world of possibilities.</p>
<p>On one side of the spectrum, data scientists possess the expertise to mine, analyze, and derive insights from vast datasets. On the other side, business leaders have the vision and acumen to steer their organizations toward success. The synergy between these two worlds not only bridges the gap but also unlocks the full potential of data, transforming it into actionable intelligence that drives innovation and growth.</p>
<p>Here are some other reasons why there is a need to bridge the gap:</p>
<h3 id="heading-breaking-down-silos">Breaking down silos</h3>
<p>One of the most pressing needs is to break down the silos that traditionally separate these two domains. Silos often develop when data scientists and business professionals work in isolation, each with their own set of objectives, tools, and language. These silos can lead to inefficiencies, miscommunication, and missed opportunities.</p>
<p>Breaking down silos means fostering a culture of collaboration and communication between data science and business teams. It involves creating an environment where data scientists and business professionals can interact seamlessly, share insights, and align their efforts towards common goals. When silos are dismantled, data scientists gain a deeper understanding of business needs, and business professionals become more data-savvy, resulting in a powerful synergy that drives innovation and growth.</p>
<h3 id="heading-collaborative-approaches">Collaborative approaches</h3>
<p>Synergy in AI is not merely about coexistence; it’s about active collaboration. Collaborative approaches entail bringing data scientists and business professionals together as equal partners in the decision-making process. By involving data scientists early on in business discussions and vice versa, organizations can ensure that data-driven insights are integrated into strategic planning and day-to-day operations.</p>
<p>Collaboration also means fostering cross-functional teams where individuals with diverse skills and expertise work together to solve complex problems. Data scientists and business experts can combine their strengths to formulate hypotheses, analyze data, and develop actionable strategies. This collaborative spirit encourages creativity, adaptability, and a holistic perspective, all of which are vital in navigating the data-driven landscape.</p>
<h2 id="heading-bridging-the-gap"><strong>Bridging the gap</strong></h2>
<p>To bridge the gap between these two domains effectively, organizations must employ a multi-faceted approach that encompasses cross-training and education, integrated teams, and the utilization of cutting-edge tools and technologies for collaboration.</p>
<h3 id="heading-cross-training-and-education">Cross-training and education</h3>
<p>To foster collaboration and understanding between data scientists and business professionals, organizations should invest in cross-training and education initiatives. This approach involves:</p>
<ul>
<li><p><strong>Educational workshops</strong>: Conduct workshops and training programs that help data scientists grasp the intricacies of business operations and enable business professionals to understand the fundamentals of data science. These sessions should be interactive and encourage knowledge sharing.</p>
</li>
<li><p><strong>Interdisciplinary courses</strong>: Encourage employees to pursue interdisciplinary courses or certifications that combine data science and business topics. This not only enhances their skill sets but also breaks down barriers between departments.</p>
</li>
<li><p><strong>Mentorship programs</strong>: Implement mentorship programs where experienced data scientists mentor business professionals (and vice versa). This one-on-one guidance fosters a deeper understanding of each other’s roles and responsibilities.</p>
</li>
</ul>
<h3 id="heading-integrated-teams">Integrated teams</h3>
<p>Breaking down the silos between data science and business departments is paramount for achieving synergy. Building integrated teams involves:</p>
<ul>
<li><p><strong>Cross-functional teams:</strong> Form cross-functional teams that comprise data scientists, business analysts, marketing experts, and other relevant roles. These teams work together on projects, bringing diverse perspectives to the table.</p>
</li>
<li><p><strong>Shared goals:</strong> Define shared objectives that encourage collaboration. When teams have common goals and KPIs, they are more likely to work together seamlessly to achieve them.</p>
</li>
<li><p><strong>Regular meetings:</strong> Hold regular meetings where both data science and business professionals come together to discuss progress, challenges, and insights. These meetings promote open communication and knowledge exchange.</p>
</li>
</ul>
<h2 id="heading-tools-and-technologies-for-collaboration"><strong>Tools and technologies for collaboration</strong></h2>
<p>To enable effective collaboration, organizations should leverage tools and technologies tailored to the needs of both data science and business teams:</p>
<ul>
<li><p><strong>Data visualization tools</strong>: Invest in data visualization platforms that allow business professionals to easily interpret complex data and gain actionable insights. These tools bridge the gap between raw data and decision-making.</p>
</li>
<li><p><strong>Collaborative analytics platforms</strong>: Implement collaborative analytics platforms that facilitate real-time collaboration between data scientists and business analysts. These platforms enable joint data exploration and modeling.</p>
</li>
<li><p><strong>Communication and documentation tools</strong>: Use communication and documentation tools that ensure all team members have access to project updates, data sources, and analysis documentation. Transparency is key to successful collaboration.</p>
</li>
</ul>
<h2 id="heading-benefits-of-synergy-in-ai"><strong>Benefits of Synergy in AI</strong></h2>
<p>In this section, we explore the benefits of this synergy in AI in depth:</p>
<h3 id="heading-enhanced-decision-making">Enhanced Decision-Making</h3>
<ul>
<li><p><strong>Data-driven insights*</strong>:* Synergy in AI ensures that business decisions are grounded in data-backed insights. Data scientists can analyze vast datasets, identify patterns, and provide actionable recommendations to inform strategic choices.</p>
</li>
<li><p><strong>Predictive analytics*</strong>:* By leveraging AI and machine learning models, businesses can predict future trends, customer behavior, and market dynamics. This foresight empowers organizations to make proactive decisions and stay ahead of the competition.</p>
</li>
</ul>
<h3 id="heading-improved-efficiency-and-productivity">Improved Efficiency and Productivity</h3>
<ul>
<li><p><strong>Automation*</strong>:* AI-powered tools and algorithms can automate repetitive tasks, reducing manual workloads and allowing employees to focus on higher-value tasks. This leads to increased productivity and cost savings.</p>
</li>
<li><p><strong>Optimized operations*</strong>:* Data-driven insights can help streamline processes and optimize resource allocation, ensuring that businesses operate more efficiently and effectively.</p>
</li>
</ul>
<h3 id="heading-innovation-and-competitive-advantage">Innovation and Competitive Advantage</h3>
<ul>
<li><p><strong>Market responsiveness*</strong>:* Synergy in AI enables organizations to adapt swiftly to changing market conditions. They can respond to customer preferences and market shifts in real-time, gaining a competitive edge.</p>
</li>
<li><p><strong>New revenue streams*</strong>:* Collaborative AI initiatives often lead to the development of innovative products or services, opening up new revenue streams and business opportunities.</p>
</li>
</ul>
<h3 id="heading-customer-centric-strategies">Customer-Centric Strategies</h3>
<ul>
<li><p><strong>Personalization*</strong>:* AI-driven customer segmentation and personalization strategies allow businesses to tailor their offerings to individual customer preferences. This leads to higher customer satisfaction and loyalty.</p>
</li>
<li><p><strong>Enhanced customer experience*</strong>:* With AI-powered chatbots, recommendation engines, and sentiment analysis, organizations can deliver exceptional customer experiences, leading to increased customer retention.</p>
</li>
</ul>
<h3 id="heading-risk-mitigation">Risk Mitigation</h3>
<ul>
<li><p><strong>Anomaly detection*</strong>:* AI models can identify unusual patterns or outliers in data, helping organizations detect fraud, security breaches, or operational anomalies early, and minimizing potential risks.</p>
</li>
<li><p><strong>Compliance and regulation*</strong>:* By using AI to ensure data compliance and monitor regulatory changes, businesses can avoid legal and financial penalties.</p>
</li>
</ul>
<h3 id="heading-data-monetization">Data Monetization</h3>
<ul>
<li><p><strong>Data-driven products*</strong>:* Synergy between data science and business can lead to the creation of data-driven products or services that can be monetized, diversifying revenue streams.</p>
</li>
<li><p><strong>Partnerships and collaborations:</strong> Organizations can leverage their data assets to establish partnerships or collaborations with other businesses, expanding their market reach.</p>
</li>
</ul>
<h3 id="heading-measurable-roi">Measurable ROI</h3>
<ul>
<li><strong>Quantifiable outcomes*</strong>:* Synergy in AI often yields measurable results, making it easier to calculate the return on investment (ROI) of data science initiatives and justifying ongoing investments.</li>
</ul>
<h3 id="heading-employee-satisfaction-and-development">Employee Satisfaction and Development</h3>
<ul>
<li><strong>Cross-training*</strong>:* Encouraging collaboration between data scientists and business teams fosters a culture of continuous learning and skill development. Employees become more versatile and adaptable in their roles.</li>
</ul>
<h2 id="heading-wrap-up"><strong>Wrap up</strong></h2>
<p>Throughout this article, we’ve emphasized the critical importance of synergy between data science and business. As we look ahead, businesses are encouraged to proactively foster collaboration between their data science and business teams. Breaking down the silos that have traditionally separated these two domains is not just a strategic advantage; it’s a necessity in today’s data-driven era. Encouraging cross-training, investing in integrated technologies, and cultivating a culture of cooperation will be essential steps toward realizing the full potential of synergy in AI.</p>
<p><strong>References:</strong></p>
<ul>
<li><p>McKinsey &amp; Company: The Value of Data: <a target="_blank" href="https://www.mckinsey.com/capabilities/mckinsey-digital/our-insights/new-years-resolutions-for-tech-in-2023">https://www.mckinsey.com/capabilities/mckinsey-digital/our-insights/new-years-resolutions-for-tech-in-2023</a></p>
</li>
<li><p>Harvard Business Review: Why Data Science Is More Important Than Ever: <a target="_blank" href="https://hbr.org/2019/01/data-science-and-the-art-of-persuasion">https://hbr.org/2019/01/data-science-and-the-art-of-persuasion</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Memory Management using PYTORCH_CUDA_ALLOC_CONF]]></title><description><![CDATA[Memory Management using PYTORCH_CUDA_ALLOC_CONF]]></description><link>https://shittuolumide.hashnode.dev/memory-management-using-pytorchcudaallocconf</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/memory-management-using-pytorchcudaallocconf</guid><category><![CDATA[Python]]></category><category><![CDATA[Deep Learning]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[pytorch]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Sat, 24 Jun 2023 09:56:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1687600407351/4e0d46ad-6b68-4fb7-b195-9b12cd7efe5e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Like an orchestra conductor carefully allocating resources to each musician, memory management is the hidden maestro that orchestrates the performance of software applications. It is the art and science of efficiently organizing and utilizing a computer’s memory to optimize performance, enhance security, and unleash the full potential of our programs.</p>
<p>In deep learning, where models are becoming increasingly complex and datasets larger than ever, efficient memory management is crucial in achieving optimal performance. The memory requirements of deep learning models can be immense, often surpassing the capabilities of the available hardware, which is why in this article, we explore a powerful tool called <strong>PYTORCH_CUDA_ALLOC_CONF</strong> that addresses these memory management challenges when using PyTorch and CUDA.</p>
<p>PyTorch, a popular deep learning framework, and CUDA, a parallel computing platform, provide developers with the tools to leverage the power of GPUs for accelerated training and inference. However, managing GPU memory efficiently is essential for preventing out-of-memory errors, maximizing hardware utilization, and achieving faster computation times.</p>
<h1 id="heading-overview-of-pytorchcudaallocconf"><strong>Overview of PYTORCH_CUDA_ALLOC_CONF</strong></h1>
<p><strong>PYTORCH_CUDA_ALLOC_CONF</strong> is a configuration option introduced in PyTorch to enhance memory management and allocation for deep learning applications utilizing CUDA. It is designed to optimize GPU memory allocation and improve performance during training and inference processes.</p>
<p>It enables users to fine-tune the memory management behavior by configuring various aspects of CUDA memory allocation. By adjusting these configurations, developers can optimize memory utilization and minimize unnecessary memory transfers, improving training and inference efficiency.</p>
<p>The configuration options provided by <strong>PYTORCH_CUDA_ALLOC_CONF</strong> allow users to control parameters such as the caching algorithm, the maximum GPU memory capacity, the allocation granularity, and the memory pool management strategy. These configurations can be adjusted based on the specific requirements of the deep learning model and the available GPU resources.</p>
<p>One key advantage of <strong>PYTORCH_CUDA_ALLOC_CONF</strong> is its ability to dynamically allocate and manage memory based on memory usage patterns during runtime. It supports dynamic memory allocation, allowing the framework to allocate memory on-demand and release it when it is no longer needed. This dynamic allocation approach helps avoid unnecessary memory waste and efficiently utilizes GPU resources.</p>
<p>Similarly, <strong>PYTORCH_CUDA_ALLOC_CONF</strong> incorporates memory recycling techniques, where memory blocks no longer in use can be recycled and reused for subsequent computations. Reusing memory reduces the frequency of memory allocations and deallocations, which can be time-consuming. This recycling mechanism further enhances memory management efficiency and contributes to improved performance.</p>
<h1 id="heading-how-does-pytorchcudaallocconf-work"><strong>How does PYTORCH_CUDA_ALLOC_CONF work?</strong></h1>
<p>As discussed earlier, PYTORCH_CUDA_ALLOC_CONF is a PyTorch environment variable that allows us to configure memory allocation behavior for CUDA tensors. It controls memory allocation strategies, enabling users to optimize memory usage and improve performance in deep learning tasks. When set, PYTORCH_CUDA_ALLOC_CONF overrides the default memory allocator in PyTorch and introduces more efficient memory management techniques.</p>
<p>PYTORCH_CUDA_ALLOC_CONF operates by utilizing different memory allocation algorithms and strategies. It provides several configuration options, including:</p>
<ol>
<li><p><code>heuristic</code>: This option enables PyTorch to automatically select the best memory allocation strategy based on heuristics and runtime conditions. It dynamically adjusts memory allocation parameters to optimize performance for different scenarios.</p>
</li>
<li><p><code>nmalloc</code>: This option specifies the number of memory allocation attempts before an out-of-memory error is raised. It allows users to control the number of attempts made by PyTorch to allocate memory.</p>
</li>
<li><p><code>caching_allocator</code>: This option enables a caching memory allocator, which improves performance by reusing previously allocated memory blocks. It reduces the overhead of memory allocation and deallocation operations.</p>
</li>
<li><p><code>pooled</code>: This option activates pooled memory allocation, which allocates memory in fixed-size blocks or pools. It improves memory utilization by reducing fragmentation and overhead associated with variable-sized memory allocations.</p>
</li>
</ol>
<h1 id="heading-implementation"><strong>Implementation</strong></h1>
<p>In this section, we will look at how we use <strong>PYTORCH_CUDA_ALLOC_CONF</strong> for memory management in PyTorch.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">import</span> os

<span class="hljs-comment"># Set PYTORCH_CUDA_ALLOC_CONF environment variable</span>
os.environ[<span class="hljs-string">"PYTORCH_CUDA_ALLOC_CONF"</span>] = <span class="hljs-string">"caching_allocator"</span>

<span class="hljs-comment"># Explanation: By setting PYTORCH_CUDA_ALLOC_CONF to "caching_allocator",</span>
<span class="hljs-comment"># we enable the caching memory allocator, which improves memory management efficiency.</span>

<span class="hljs-comment"># Create a CUDA tensor</span>
x = torch.randn(<span class="hljs-number">1000</span>, <span class="hljs-number">1000</span>).cuda()

<span class="hljs-comment"># Explanation: Here, we create a CUDA tensor using the torch.randn() function.</span>
<span class="hljs-comment"># Since PYTORCH_CUDA_ALLOC_CONF is set, the tensor will be allocated using the caching allocator.</span>

<span class="hljs-comment"># Perform some computations</span>
y = x + x.t()
z = torch.matmul(y, y)

<span class="hljs-comment"># Explanation: We perform some computations on the CUDA tensor.</span>
<span class="hljs-comment"># The caching allocator manages the memory allocation and reuse efficiently,</span>
<span class="hljs-comment"># reducing the overhead of memory allocation and deallocation operations.</span>

<span class="hljs-comment"># Clear memory explicitly (optional)</span>
<span class="hljs-keyword">del</span> x, y, z

<span class="hljs-comment"># Explanation: Clearing the variables is optional, but it can help release GPU memory</span>
<span class="hljs-comment"># before subsequent operations to avoid excessive memory usage.</span>

<span class="hljs-comment"># Reset PYTORCH_CUDA_ALLOC_CONF environment variable (optional)</span>
os.environ[<span class="hljs-string">"PYTORCH_CUDA_ALLOC_CONF"</span>] = <span class="hljs-string">""</span>

<span class="hljs-comment"># Explanation: Resetting PYTORCH_CUDA_ALLOC_CONF to an empty string restores</span>
<span class="hljs-comment"># the default memory allocator behavior in PyTorch.</span>

<span class="hljs-comment"># Continue with other operations</span>
</code></pre>
<p><strong>Explanation</strong>:</p>
<ol>
<li><p>The code sets the environment variable <code>PYTORCH_CUDA_ALLOC_CONF</code> to <code>"caching_allocator"</code>. This activates the caching memory allocator, which improves memory management efficiency by reusing previously allocated memory blocks.</p>
</li>
<li><p>A CUDA tensor <code>x</code> of size 1000x1000 is created using <code>torch.randn()</code>. Since <code>PYTORCH_CUDA_ALLOC_CONF</code> is set, the tensor will be allocated using the caching allocator.</p>
</li>
<li><p>Computation operations (<code>y = x + x.t()</code> and <code>z = torch.matmul(y, y)</code>) are performed on the CUDA tensor. The caching allocator manages memory allocation and reuse efficiently, reducing the overhead of memory allocation and deallocation operations.</p>
</li>
<li><p>The <code>del</code> statement is used to explicitly clear the variables <code>x</code>, <code>y</code>, and <code>z</code>. This step is optional but can help release GPU memory before subsequent operations to avoid excessive memory usage.</p>
</li>
<li><p>The <code>PYTORCH_CUDA_ALLOC_CONF</code> environment variable is reset to an empty string if desired. This restores the default memory allocator behavior in PyTorch.</p>
</li>
<li><p>Further operations can be performed using PyTorch as needed.</p>
</li>
</ol>
<h1 id="heading-advantages-and-benefits-of-using-pytorchcudaallocconf"><strong>Advantages and benefits of using PYTORCH_CUDA_ALLOC_CONF:</strong></h1>
<ol>
<li><p><strong>Improved performance</strong>: PYTORCH_CUDA_ALLOC_CONF offers various memory allocation strategies to significantly enhance performance in deep learning tasks. By optimizing memory usage, it reduces memory fragmentation and improves overall memory management efficiency. This, in turn, leads to faster computation and better utilization of GPU resources.</p>
</li>
<li><p><strong>Reduced memory:</strong> fragmentation occurs when memory blocks become scattered and inefficiently utilized, leading to wasted memory. PYTORCH_CUDA_ALLOC_CONF helps mitigate fragmentation by implementing pooling and caching strategies. This ensures more effective memory reuse and reduces the likelihood of memory fragmentation, resulting in better memory utilization.</p>
</li>
<li><p><strong>Customizable allocation behavior</strong>: PYTORCH_CUDA_ALLOC_CONF allows users to customize memory allocation behavior according to their specific requirements. Users can adapt memory allocation strategies to their particular models, data sizes, and hardware configurations by choosing different options and configurations, leading to optimal performance.</p>
</li>
<li><p><strong>Error control</strong>: The <code>nmalloc</code> option in PYTORCH_CUDA_ALLOC_CONF allows users to set the maximum number of memory allocation attempts. This feature can prevent excessive memory allocation attempts and prevent the program from getting stuck in an allocation loop. It provides control and error handling when dealing with memory allocation issues.</p>
</li>
<li><p><strong>Compatibility and ease of use</strong>: PYTORCH_CUDA_ALLOC_CONF seamlessly integrates with PyTorch, a widely used deep learning framework. It can be easily set as an environment variable, allowing users to enable and configure memory allocation behavior without complex code modifications. This ensures compatibility across different PyTorch versions and simplifies the implementation of memory management optimizations.</p>
</li>
</ol>
<h1 id="heading-conclusion"><strong>Conclusion</strong></h1>
<p>In summary, PYTORCH_CUDA_ALLOC_CONF provides a valuable tool for developers working with PyTorch and CUDA, offering a range of configuration options to optimize memory allocation and utilization. By leveraging this feature, deep learning practitioners can effectively manage memory resources, reduce memory-related bottlenecks, and ultimately improve the efficiency and performance of their models.</p>
]]></content:encoded></item><item><title><![CDATA[How can I set max_split_size_mb to avoid fragmentation in Pytorch?]]></title><description><![CDATA[PyTorch, a popular deep learning framework, has revolutionized the field of artificial intelligence by providing a flexible and efficient platform for…]]></description><link>https://shittuolumide.hashnode.dev/how-can-i-set-maxsplitsizemb-to-avoid-fragmentation-in-pytorch</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/how-can-i-set-maxsplitsizemb-to-avoid-fragmentation-in-pytorch</guid><category><![CDATA[Machine Learning]]></category><category><![CDATA[Python]]></category><category><![CDATA[pytorch]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Fri, 23 Jun 2023 12:36:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1687523625776/1826368c-264f-4cac-ab83-2ae6347058da.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a target="_blank" href="https://pytorch.org/">PyTorch</a>, a popular deep learning framework, has revolutionized the field of artificial intelligence by providing a flexible and efficient platform for developing cutting-edge models. However, memory management becomes a critical concern as models become increasingly complex and datasets grow. One specific challenge is memory fragmentation, which can significantly impact PyTorch’s performance and limit its ability to handle larger models and datasets.</p>
<p>Memory fragmentation occurs when memory is allocated and deallocated in a way that leaves small, unusable gaps between allocated blocks. These fragmented memory blocks can hinder the efficient allocation of large tensors, leading to increased memory consumption, slower training times, and even out-of-memory errors. To address this issue, PyTorch provides a configurable parameter called “<strong>max_split_size_mb</strong>” that helps control memory fragmentation.</p>
<p>This article aims to provide a comprehensive understanding of memory fragmentation in PyTorch and guide you in setting an appropriate value for <strong>max_split_size_mb</strong>. We will delve into the causes and consequences of fragmentation, explore strategies to avoid it and present best practices for monitoring and diagnosing fragmentation issues. By the end of this article, you will have the knowledge and tools necessary to optimize memory management in PyTorch and achieve better performance and scalability for their deep learning projects.</p>
<h1 id="heading-what-causes-memory-fragmentation"><strong>What causes memory fragmentation?</strong></h1>
<p>In PyTorch, memory fragmentation can occur due to several factors and operations. Here are some common causes of fragmentation in PyTorch:</p>
<ol>
<li><p><strong>Dynamic memory allocation:</strong> PyTorch dynamically allocates memory for tensors and computational operations during runtime. This dynamic allocation can lead to memory fragmentation if the allocated memory blocks are not contiguous or if there are frequent allocations and deallocations.</p>
</li>
<li><p><strong>Variable tensor sizes</strong>: It supports tensors with variable sizes, allowing flexibility in defining models and processing variable-sized inputs. However, when tensors of different sizes are allocated and deallocated frequently, it can result in fragmented memory blocks.</p>
</li>
<li><p><strong>In-place operations</strong>: PyTorch allows in-place operations, where the output of an operation is stored in the memory of one of the input tensors. While this can save memory, it can also lead to fragmentation if the resulting tensor size differs significantly from the original.</p>
</li>
<li><p><strong>Model complexity and layer sizes</strong>: Deep learning models with complex architectures and large layer sizes require significant memory resources. If the available memory is not efficiently managed, fragmentation can occur as the memory is allocated and deallocated during training or inference.</p>
</li>
<li><p><strong>Batch size variations</strong>: When working with varying batch sizes, memory fragmentation can occur if the allocated memory for larger batches cannot be efficiently utilized for smaller batches. This issue becomes more prominent when the batch sizes change frequently or significantly differ.</p>
</li>
<li><p><strong>GPU memory constraints</strong>: If the available GPU memory is limited, PyTorch must manage memory allocation carefully. Fragmentation can occur when the memory is not effectively utilized or when tensors cannot be allocated contiguously due to insufficient memory.</p>
</li>
</ol>
<p>With the understanding of what causes fragmentation, let’s look at its consequences. The consequences of fragmentation in PyTorch can significantly impact the performance and efficiency of your machine learning workflow. Here are some key consequences to be aware of:</p>
<ol>
<li><p><strong>Increased memory usage</strong>: Fragmentation can lead to inefficient memory allocation and utilization. As memory becomes fragmented, smaller free memory blocks are scattered throughout, making it challenging to allocate contiguous memory for larger tensors. This can increase overall memory usage, as the memory allocator needs to reserve extra space to accommodate fragmented memory blocks.</p>
</li>
<li><p><strong>Performance degradation</strong>: Fragmentation can cause performance degradation in PyTorch applications. When memory becomes fragmented, it may require more frequent memory allocations and deallocations, leading to increased overhead and slower execution times. This can negatively impact the overall throughput and efficiency of your training or inference process.</p>
</li>
<li><p><strong>Out-of-Memory errors</strong>: Inadequate management of memory fragmentation can result in out-of-memory errors. As memory becomes fragmented, it may limit the availability of contiguous memory blocks, causing memory allocation failures when allocating large tensors or intermediate computational buffers. These errors can interrupt the execution of your code and prevent it from running to completion.</p>
</li>
<li><p><strong>Increased garbage collection overhead</strong>: Fragmentation can lead to increased garbage collection (GC) overhead. When memory becomes fragmented, the garbage collector must traverse and deallocate smaller memory blocks more frequently, increasing the time spent on garbage collection. This can introduce additional computational overhead and slow down the execution of your PyTorch code.</p>
</li>
</ol>
<h1 id="heading-implementation"><strong>Implementation</strong></h1>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> torch

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">set_max_split_size_mb</span>(<span class="hljs-params">model, max_split_size_mb</span>):</span>
    <span class="hljs-string">"""
    Set the max_split_size_mb parameter in PyTorch to avoid fragmentation.

    Args:
        model (torch.nn.Module): The PyTorch model.
        max_split_size_mb (int): The desired value for max_split_size_mb in megabytes.
    """</span>
    <span class="hljs-keyword">for</span> param <span class="hljs-keyword">in</span> model.parameters():
        param.requires_grad = <span class="hljs-literal">False</span>  <span class="hljs-comment"># Disable gradient calculation to prevent unnecessary memory allocations</span>

    <span class="hljs-comment"># Dummy forward pass to initialize the memory allocator</span>
    dummy_input = torch.randn(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>)
    model(dummy_input)

    <span class="hljs-comment"># Get the current memory allocator state</span>
    allocator = torch.cuda.memory._get_memory_allocator()

    <span class="hljs-comment"># Update max_split_size_mb in the memory allocator</span>
    allocator.set_max_split_size(max_split_size_mb * <span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>)

    <span class="hljs-keyword">for</span> param <span class="hljs-keyword">in</span> model.parameters():
        param.requires_grad = <span class="hljs-literal">True</span>  <span class="hljs-comment"># Re-enable gradient calculation for training</span>

<span class="hljs-comment"># Example usage</span>
<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    <span class="hljs-comment"># Create your PyTorch model</span>
    model = torch.nn.Linear(<span class="hljs-number">10</span>, <span class="hljs-number">5</span>)

    <span class="hljs-comment"># Set the desired max_split_size_mb value (e.g., 200 MB)</span>
    max_split_size_mb = <span class="hljs-number">200</span>

    <span class="hljs-comment"># Call the function to set max_split_size_mb</span>
    set_max_split_size_mb(model, max_split_size_mb)
</code></pre>
<p><strong>Explanation</strong>:</p>
<ul>
<li><p>The <code>set_max_split_size_mb</code> function takes two parameters: <code>model</code> (a PyTorch model) and <code>max_split_size_mb</code> (the desired value for <code>max_split_size_mb</code> in megabytes).</p>
</li>
<li><p>The function begins by disabling gradient calculation for all parameters in the model using <code>param.requires_grad = False</code>. This prevents unnecessary memory allocations during the initialization process.</p>
</li>
<li><p>To initialize the memory allocator, a dummy input tensor is created (<code>dummy_input</code>) and passed through the model's forward pass (<code>model(dummy_input)</code>). This allows the memory allocator to allocate memory and establish its initial state.</p>
</li>
<li><p>Next, the function retrieves the memory allocator using <code>torch.cuda.memory._get_memory_allocator()</code>. This gives access to the allocator's methods and properties.</p>
</li>
<li><p>The <code>set_max_split_size</code> method of the memory allocator is called to update the <code>max_split_size_mb</code> value. The provided <code>max_split_size_mb</code> is multiplied by <code>1024 * 1024</code> to convert it from megabytes to bytes.</p>
</li>
<li><p>Finally, gradient calculation is re-enabled for all parameters in the model using <code>param.requires_grad = True</code>, allowing the model to be trained normally.</p>
</li>
<li><p>In the example usage section, a PyTorch model (<code>torch.nn.Linear</code>) is created, and the desired <code>max_split_size_mb</code> value (e.g., 200 MB) is set. The <code>set_max_split_size_mb</code> function is then called with the model and the desired value.</p>
</li>
</ul>
<p>By setting <code>max_split_size_mb</code> appropriately, you can control the memory fragmentation in PyTorch and optimize the memory usage during training or inference.</p>
<h1 id="heading-best-practices-for-monitoring-and-diagnosing-fragmentation-issues"><strong>Best practices for monitoring and diagnosing fragmentation issues</strong></h1>
<p>Monitoring and diagnosing memory fragmentation issues in PyTorch involves a combination of observation, measurement, and analysis. Here are some best practices to help you effectively monitor and diagnose memory fragmentation problems:</p>
<ol>
<li><p><strong>Observe memory allocation errors</strong>: Keep an eye out for out-of-memory (OOM) errors or other memory-related exceptions during your training or inference processes. These errors can indicate that memory fragmentation is occurring.</p>
</li>
<li><p><strong>Use memory profiling tools</strong>: PyTorch provides a built-in memory profiler that allows you to track memory allocation and deallocation. Use the profiler to identify memory usage patterns and potential sources of fragmentation. You can enable it using the <code>torch.autograd.profiler.profile</code> context manager or the <code>torch.cuda.profiler.profile</code> function.</p>
</li>
<li><p><strong>Monitor GPU memory utilization</strong>: Use GPU memory utilization tools like NVIDIA’s <code>nvidia-smi</code> or PyTorch's <code>torch.cuda.memory_allocated()</code> and <code>torch.cuda.memory_cached()</code> functions to monitor the memory consumption of your application. Monitor these metrics during training or inference to identify any abnormal memory growth or caching patterns.</p>
</li>
<li><p><strong>Optimize data loading and batching</strong>: Inefficient data loading and batching can contribute to memory fragmentation. Optimize your data loading pipeline by utilizing techniques such as prefetching, parallel loading, or using data loaders with appropriate batch sizes to minimize memory fragmentation.</p>
</li>
<li><p><strong>Experiment with different configurations</strong>: Vary the <code>max_split_size_mb</code> parameter and observe its impact on memory fragmentation. Experiment with different values and measure the memory usage and performance to find an optimal setting for your specific use case.</p>
</li>
</ol>
<h1 id="heading-conclusion"><strong>Conclusion</strong></h1>
<p>In conclusion, setting the <strong>max_split_size_mb</strong> parameter appropriately in PyTorch is crucial for avoiding memory fragmentation and optimizing performance. Fragmentation can negatively impact the efficiency of your PyTorch models, leading to memory allocation errors and performance degradation over time. By understanding the concept of memory fragmentation and its implications, you can take proactive measures to mitigate these issues.</p>
]]></content:encoded></item><item><title><![CDATA[Copy.deepcopy() vs clone() in Pytorch]]></title><description><![CDATA[PyTorch has become a popular deep learning framework in the machine learning community. Creating duplicates of items is a common requirement for developers…]]></description><link>https://shittuolumide.hashnode.dev/copydeepcopy-vs-clone-in-pytorch</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/copydeepcopy-vs-clone-in-pytorch</guid><category><![CDATA[Machine Learning]]></category><category><![CDATA[Deep Learning]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Wed, 21 Jun 2023 22:47:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1687387685639/6a16309f-e857-4545-a144-52751e26dd54.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>PyTorch has become a popular deep learning framework in the machine learning community. Creating duplicates of items is a common requirement for developers and researchers using PyTorch. Understanding the distinctions between the copies is essential for retaining a model’s state, providing data augmentation, or enabling parallel processing. It is essential to use the <code>copy.deepcopy()</code> and <code>clone()</code> methods.</p>
<p>In this article, we examine the nuances of various object copying methods in PyTorch and their applications, performance issues, and best practices for selecting the appropriate method.</p>
<h1 id="heading-understanding-copydeepcopy"><strong>Understanding Copy.deepcopy()</strong></h1>
<p>In PyTorch, the <code>copy.deepcopy()</code> function is a powerful tool for creating deep copies of objects, including tensors and other PyTorch-specific objects. It belongs to the <code>copy</code> module in the Python standard library. It allows us to create independent copies of objects, ensuring that any modifications made to the original object do not affect the copied one.</p>
<p>To understand <code>copy.deepcopy()</code> in PyTorch, let's explore its working mechanism and the benefits it offers:</p>
<ol>
<li><p><strong>Recursive copying</strong>: <code>copy.deepcopy()</code> operates by recursively traversing the object hierarchy and creating a copy of each object encountered. This means that the top-level object and all its nested objects are duplicated.</p>
</li>
<li><p><strong>Independent memory allocation</strong>: When <code>copy.deepcopy()</code> It creates a copy of an object and allocates new memory for the copied object. This ensures that the original and copied objects have separate memory spaces and are entirely independent.</p>
</li>
<li><p><strong>Handling complex structures</strong>: One of the key advantages of <code>copy.deepcopy()</code> is its ability to handle complex nested structures. This is particularly useful when working with PyTorch models, which consist of layers, parameters, gradients, and other interconnected components. <code>copy.deepcopy()</code> ensures that every element within the model is correctly replicated without any reference sharing, preserving the original structure's integrity.</p>
</li>
<li><p><strong>Immutable and mutable objects</strong>: <code>copy.deepcopy()</code> is suitable for both immutable and mutable objects. Immutable objects, such as tensors, require deep copying to maintain integrity. On the other hand, mutable objects, like lists or dictionaries, benefit from deep copying to avoid unintended modifications.</p>
</li>
<li><p><strong>Use Cases</strong>: <code>copy.deepcopy()</code> finds application in various scenarios. For instance, when training deep learning models, we may need to create copies of the model at different stages to compare training progress or perform model ensembling. Additionally, when working with complex data structures or preserving object states during program execution, <code>copy.deepcopy()</code> ensures that we have independent copies to work with.</p>
</li>
</ol>
<p>It’s important to note that while <code>copy.deepcopy()</code> provides a comprehensive and independent copy of objects, it can be computationally expensive and memory-intensive. Traversing and duplicating large object hierarchies can increase execution times and memory usage. Therefore, evaluating the trade-offs between accuracy, performance, and memory consumption is essential when deciding to use <code>copy.deepcopy()</code> in PyTorch.</p>
<h2 id="heading-implementation"><strong>Implementation</strong></h2>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">import</span> copy
</code></pre>
<p>First, we import the required libraries, including PyTorch and the <code>copy</code> module for using <code>deepcopy()</code>.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Creating a sample PyTorch tensor</span>
tensor = torch.tensor([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
</code></pre>
<p>We start by creating a sample PyTorch tensor. This tensor will serve as an example object that we want to copy using <code>deepcopy()</code>.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Creating a deepcopy of the tensor</span>
tensor_copy = copy.deepcopy(tensor)
</code></pre>
<p>Next, we use <code>copy.deepcopy()</code> to create a deep copy of the <code>tensor</code> object. We assign the copied tensor to <code>tensor_copy</code>.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Modifying the original tensor</span>
tensor[<span class="hljs-number">0</span>] = <span class="hljs-number">10</span>
</code></pre>
<p>Here, we modify the original <code>tensor</code> object by changing the value of its first element to 10.</p>
<pre><code class="lang-python">print(tensor)
<span class="hljs-comment"># Output: tensor([10,  2,  3])</span>
</code></pre>
<p>Printing the original <code>tensor</code> confirms that the modification was successful, and the first element is now 10.</p>
<pre><code class="lang-python">print(tensor_copy)
<span class="hljs-comment"># Output: tensor([1, 2, 3])</span>
</code></pre>
<p>However, when we print the <code>tensor_copy</code>, we can observe that it remains unchanged. This behavior demonstrates the effectiveness of <code>copy.deepcopy()</code>. It creates a completely independent copy of the original object, ensuring that modifications to the original object do not affect the copied one.</p>
<p>The <code>copy.deepcopy()</code> function in this example performs a recursive traversal of the tensor object, copying each element and its underlying memory allocation. This process ensures that any modifications to the original tensor are not propagated to the copied tensor.</p>
<p>By utilizing <code>copy.deepcopy()</code> in PyTorch, we can create fully independent copies of complex objects such as neural network models, enabling us to preserve their state, perform experiments, or compare different versions without any unintended side effects.</p>
<h1 id="heading-exploring-clone-in-pytorch"><strong>Exploring clone() in PyTorch</strong></h1>
<p>In PyTorch, the <code>clone()</code> method creates a shallow copy of an object. Unlike <code>copy.deepcopy()</code>, which creates an independent copy of the entire object hierarchy, <code>clone()</code> primarily operates on the top-level object and shallowly clones any nested objects within that hierarchy. The key distinction lies in the level of object hierarchy they copy.</p>
<p>When we call <code>clone()</code> on a PyTorch object, it creates a new object that shares the underlying memory with the original object. However, the memory content is duplicated, ensuring that the cloned object maintains independence from the original. This means that modifications to the cloned object do not affect the original, and vice versa.</p>
<p>The shallow copying nature of <code>clone()</code> makes it more memory-efficient and faster than <code>copy.deepcopy()</code> when dealing with large objects or scenarios where a complete deep copy is not necessary. Instead of traversing the entire object hierarchy, <code>clone()</code> focuses on duplicating the top-level attributes and references any nested objects, maintaining memory sharing.</p>
<p>One important thing to note is that <code>clone()</code> is designed to work specifically with PyTorch tensors and objects. It ensures that tensor memory is shared while creating independent instances of the tensor, allowing efficient computation and memory utilization. This behavior is <code>clone()</code> particularly useful when working with PyTorch models, as it avoids redundant memory allocation and copying operations.</p>
<p>However, it’s important to understand the limitations of <code>clone()</code>. Since it performs shallow copying, any changes made to the shared underlying memory in one object will be reflected in the other objects that share that memory. Therefore, it is crucial to use <code>clone()</code> carefully and consider the mutability of the objects being copied. In cases where a complete independent copy is required, <code>copy.deepcopy()</code> remains the safer option.</p>
<h2 id="heading-implementation-1"><strong>Implementation</strong></h2>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> torch

<span class="hljs-comment"># Create a PyTorch tensor</span>
original_tensor = torch.tensor([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>])

<span class="hljs-comment"># Clone the tensor using the clone() method</span>
cloned_tensor = original_tensor.clone()

<span class="hljs-comment"># Modify the cloned tensor</span>
cloned_tensor[<span class="hljs-number">0</span>] = <span class="hljs-number">10</span>

<span class="hljs-comment"># Print the original and cloned tensors</span>
print(<span class="hljs-string">"Original tensor:"</span>, original_tensor)
print(<span class="hljs-string">"Cloned tensor:"</span>, cloned_tensor)
</code></pre>
<p><strong>Explanation</strong>:</p>
<ol>
<li><p>We start by importing the necessary PyTorch library using <code>import torch</code>.</p>
</li>
<li><p>Next, we create a PyTorch tensor named <code>original_tensor</code> using the <code>torch.tensor()</code> method. In this example, we initialize it with the values [1, 2, 3, 4, 5].</p>
</li>
<li><p>To create a clone of the <code>original_tensor</code>, we use the <code>clone()</code> method and assign it to the <code>cloned_tensor</code> variable. This will create a shallow copy of the tensor, meaning the underlying memory will be shared between the original and cloned tensors.</p>
</li>
<li><p>We modify the first element of the <code>cloned_tensor</code> by assigning the value 10 to <code>cloned_tensor[0]</code>.</p>
</li>
<li><p>Finally, we print both the original and cloned tensors to observe the differences.</p>
</li>
</ol>
<p><strong>Output</strong>:</p>
<pre><code class="lang-python">Original tensor: tensor([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>])
Cloned tensor: tensor([<span class="hljs-number">10</span>,  <span class="hljs-number">2</span>,  <span class="hljs-number">3</span>,  <span class="hljs-number">4</span>,  <span class="hljs-number">5</span>])
</code></pre>
<p>The output shows that the modification made to the cloned tensor (changing the first element to 10) did not affect the original tensor. This demonstrates that the <code>clone()</code> method creates an independent copy of the top-level object (tensor) while sharing the underlying memory.</p>
<p>It’s important to note that <code>clone()</code> can be applied to various PyTorch objects, including tensors, models, and other complex structures. The behavior remains the same: creating a shallow copy of the object while maintaining memory sharing.</p>
<h1 id="heading-best-practices-for-selecting-the-appropriate-method"><strong>Best practices for selecting the appropriate method.</strong></h1>
<p>When selecting the appropriate method between <code>clone()</code> and <code>copy.deepcopy()</code> in PyTorch, it is essential to consider the following best practices:</p>
<ol>
<li><p><strong>Understand the object hierarchy</strong>: Analyze the structure and complexity of the object we want to copy. If the object hierarchy is simple and shallow, <code>clone()</code> might suffice. However, if the hierarchy is complex with nested objects and interdependencies, <code>copy.deepcopy()</code> is better suited to ensure a completely independent copy.</p>
</li>
<li><p><strong>Consider memory usage</strong>: Evaluate the memory consumption of our application. If memory is a concern and we have large objects, <code>clone()</code> is generally more memory-efficient since it avoids duplicating memory for the entire object hierarchy. However, remember that memory sharing can introduce dependencies and requires caution when modifying shared data.</p>
</li>
<li><p><strong>Assess performance requirements</strong>: Take into account the performance requirements of our application. Working with large objects or computationally intensive tasks <code>clone()</code> is usually faster due to its shallow copying nature. On the other hand, <code>copy.deepcopy()</code> can be slower due to its recursive traversal of the entire object hierarchy.</p>
</li>
<li><p><strong>Evaluate object mutability</strong>: Consider the mutability of the objects we work with. If the object is mutable, and subsequent modifications should not affect the original, <code>copy.deepcopy()</code> is the safer option. <code>clone()</code> is more suitable for immutable objects or situations where shared memory is acceptable.</p>
</li>
<li><p><strong>Measure and compare</strong>: Benchmark and profile our code to measure each method's performance and memory impact in our specific use case. This empirical data can help guide our decision and identify the most efficient approach.</p>
</li>
<li><p><strong>Leverage PyTorch’s specialized methods</strong>: Keep in mind that PyTorch provides additional specialized methods, such as <code>tensor.clone()</code> and <code>tensor.detach()</code>, which offer more specific ways to create copies based on different requirements. Consider whether these specialized methods align better with our needs.</p>
</li>
</ol>
<h1 id="heading-conclusion"><strong>Conclusion</strong></h1>
<p>In conclusion, the <code>copy.deepcopy()</code> and <code>clone()</code> PyTorch's techniques are useful for creating copies of objects, but they have key differences.</p>
<p>The <code>copy.deepcopy()</code> function is a general-purpose method available in Python’s “<strong>copy</strong>” module. It creates a deep copy of an object, including all nested objects, by recursively copying every element. This technique is suitable when you need an independent copy of an object and its associated data. However, it can be slower and consume more memory than other techniques.</p>
<p>On the other hand, the “clone()” method is specific to PyTorch and is designed to create a shallow copy of a tensor or a module. It creates a new tensor or module with the same data references as the original object. This technique is efficient regarding memory usage and can be faster than <code>copy.deepcopy()</code> since it avoids the recursive copying of nested objects. It is particularly useful when creating a lightweight copy or dealing with large tensors or complex models.</p>
<p>And by the best practices in this article, we can make an informed decision and select the most appropriate method, either <code>clone()</code> or <code>copy.deepcopy()</code>, based on the specific requirements of our PyTorch application.</p>
]]></content:encoded></item><item><title><![CDATA[Python Mini Projects]]></title><description><![CDATA[Learning programming can be challenging, especially for beginners diving into the vast world of coding. The syntax, logic, and problem-solving aspects can…]]></description><link>https://shittuolumide.hashnode.dev/python-mini-projects</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/python-mini-projects</guid><category><![CDATA[Python]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Mon, 22 May 2023 14:53:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684766124492/ea685085-814b-4221-a792-5fe8ccb54f10.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Learning programming can be challenging, especially for beginners diving into the vast world of coding. The syntax, logic, and problem-solving aspects can sometimes feel overwhelming, leading many aspiring developers to question their abilities.</p>
<p>However, a proven method for overcoming these hurdles and accelerating your learning curve is through practical application and hands-on projects. With its simplicity and versatility, Python offers an excellent platform for embarking on these mini projects that reinforce your understanding and provide a tangible sense of accomplishment.</p>
<p>In this article, we will explore some mini Python projects that you can follow up on and build in this article. These projects can help solidify your understanding of fundamental concepts, enhance your problem-solving skills, and foster a deep sense of creativity and innovation. Whether you're a beginner aiming to build a solid foundation or an intermediate learner seeking to expand your Python proficiency, embracing mini projects can be a transformative step in your programming journey.</p>
<h1 id="heading-file-encryption-and-decryption"><strong>File encryption and decryption</strong></h1>
<p>In terms of file encryption, encrypting a message so that only the intended audience can view it. We encrypt data to safeguard data security because we don't want anyone to access it.</p>
<p>It would be difficult to encrypt (and decode) files by hand, but we can do so using Python's "cryptography" module.</p>
<h3 id="heading-code-example">Code example:</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">encrypt</span>(<span class="hljs-params">message, key</span>):</span>
    encrypted_message = <span class="hljs-string">""</span>
    <span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> message:
        <span class="hljs-keyword">if</span> char.isalpha():  <span class="hljs-comment"># Check if the character is a letter</span>
            ascii_offset = ord(<span class="hljs-string">'A'</span>) <span class="hljs-keyword">if</span> char.isupper() <span class="hljs-keyword">else</span> ord(<span class="hljs-string">'a'</span>)
            shifted = (ord(char) - ascii_offset + key) % <span class="hljs-number">26</span> + ascii_offset
            encrypted_message += chr(shifted)
        <span class="hljs-keyword">else</span>:
            encrypted_message += char  <span class="hljs-comment"># Keep non-alphabetic characters as is</span>
    <span class="hljs-keyword">return</span> encrypted_message

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decrypt</span>(<span class="hljs-params">encrypted_message, key</span>):</span>
    decrypted_message = <span class="hljs-string">""</span>
    <span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> encrypted_message:
        <span class="hljs-keyword">if</span> char.isalpha():  <span class="hljs-comment"># Check if the character is a letter</span>
            ascii_offset = ord(<span class="hljs-string">'A'</span>) <span class="hljs-keyword">if</span> char.isupper() <span class="hljs-keyword">else</span> ord(<span class="hljs-string">'a'</span>)
            shifted = (ord(char) - ascii_offset - key) % <span class="hljs-number">26</span> + ascii_offset
            decrypted_message += chr(shifted)
        <span class="hljs-keyword">else</span>:
            decrypted_message += char  <span class="hljs-comment"># Keep non-alphabetic characters as is</span>
    <span class="hljs-keyword">return</span> decrypted_message

<span class="hljs-comment"># Example usage</span>
message = <span class="hljs-string">"Hello, World!"</span>
key = <span class="hljs-number">3</span>

<span class="hljs-comment"># Encryption</span>
encrypted = encrypt(message, key)
print(<span class="hljs-string">"Encrypted message:"</span>, encrypted)

<span class="hljs-comment"># Decryption</span>
decrypted = decrypt(encrypted, key)
print(<span class="hljs-string">"Decrypted message:"</span>, decrypted)
</code></pre>
<h3 id="heading-explanation-of-the-code">Explanation of the code:</h3>
<ul>
<li><p>We define two functions: <code>encrypt</code> and <code>decrypt</code>, which take a message and a key as input parameters.</p>
</li>
<li><p>The <code>encrypt</code> function iterates over each character in the message using a <code>for</code> loop.</p>
</li>
<li><p>Inside the loop, we check if the character is alphabetic using the <code>isalpha()</code> method.</p>
</li>
<li><p>We determine the ASCII offset based on the case of the letter (<code>A</code> or <code>a</code>).</p>
</li>
<li><p>The character is then shifted by the key value using the formula <code>shifted = (ord(char) - ascii_offset + key) % 26 + ascii_offset</code>. This formula wraps the shifted value around within the range of alphabetic characters (26 characters in total).</p>
</li>
<li><p>The shifted character is converted back to its ASCII representation using <code>chr()</code> and added to the <code>encrypted_message</code> string.</p>
</li>
<li><p>Non-alphabetic characters are simply added to the <code>encrypted_message</code> without modification.</p>
</li>
<li><p>The <code>encrypt</code> function returns the encrypted message.</p>
</li>
<li><p>The <code>decrypt</code> function follows a similar logic to the <code>encrypt</code> function, but the shift is done in the opposite direction (subtracting the key value).</p>
</li>
<li><p>Example usage demonstrates how to encrypt and decrypt a message.</p>
</li>
<li><p>The encrypted message is printed.</p>
</li>
<li><p>The decrypted message is printed.</p>
</li>
</ul>
<h1 id="heading-photo-background-remover"><strong>Photo background remover</strong></h1>
<p>To remove the background from your photos, various internet tools and software are accessible. However, I personally find it difficult to trust these programs since I'm not sure where my photos are kept when they are used with third-party software. Building your own background removal tool would thus be a fantastic idea.</p>
<pre><code class="lang-python">!pip install rembg
<span class="hljs-keyword">from</span> google.colab <span class="hljs-keyword">import</span> files
uploaded = files.upload()

<span class="hljs-comment">## https://pixabay.com/photos/animal-mammal-fallow-deer-stag-984573/</span>
<span class="hljs-keyword">from</span> rembg <span class="hljs-keyword">import</span> remove 
<span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image

input_img = <span class="hljs-string">'deer.jpg'</span>
output_img = <span class="hljs-string">'deer_rmbg.png'</span>

inp = Image.open(input_img)
output = remove(inp)

output.save(output_img)
files.download(output_img)
</code></pre>
<p>If you run this code, you will get this output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684764243562/e8e1beab-1963-48f6-8afd-1e8a6c70650c.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-make-your-own-animations"><strong>Make your own animations</strong></h1>
<p>To turn your picture into animations, you can use the algorithm called <a target="_blank" href="https://tachibanayoshino.github.io/AnimeGANv2/">AnimeGANv2</a>, a deep learning algorithm that transforms real-world scenes into anime-style images. The technical nitty-gritty is beyond the scope of this blog, but if you’d like to learn more, feel free to check out <a target="_blank" href="https://github.com/TachibanaYoshino/AnimeGANv2">this GitHub</a>.</p>
<p>To turn our pictures into works of art, we will call the pre-trained models from the <a target="_blank" href="https://pytorch.org/hub/">PyToch hub</a>.</p>
<pre><code class="lang-python">rom PIL <span class="hljs-keyword">import</span> Image
<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">import</span> IPython
<span class="hljs-keyword">from</span> IPython.display <span class="hljs-keyword">import</span> display
<span class="hljs-comment"># upload images</span>
<span class="hljs-keyword">from</span> google.colab <span class="hljs-keyword">import</span> files
uploaded = files.upload()

<span class="hljs-comment"># https://github.com/bryandlee/animegan2-pytorch</span>
<span class="hljs-comment"># load models and face2paint utility function</span>
model_facev2 = torch.hub.load(<span class="hljs-string">"bryandlee/animegan2-pytorch:main"</span>, <span class="hljs-string">"generator"</span>, pretrained=<span class="hljs-string">"face_paint_512_v2"</span>)
face2paint = torch.hub.load(<span class="hljs-string">"bryandlee/animegan2-pytorch:main"</span>, <span class="hljs-string">"face2paint"</span>, size=<span class="hljs-number">512</span>)

<span class="hljs-keyword">for</span> INPUT_IMG <span class="hljs-keyword">in</span> [<span class="hljs-string">'KatLi.JPG'</span>]:  
  img = Image.open(INPUT_IMG).convert(<span class="hljs-string">"RGB"</span>)
  out_facev2 = face2paint(model_facev2, img)

  <span class="hljs-comment"># display images</span>
  display(img)
  display(out_facev2)
</code></pre>
<p>In this code, we first upload some images, then we load the models using the <code>torch.hub.load()</code> and call the <code>face2paint</code> function.</p>
<p>Viola! we have the animation, and the most fun part is that you can add more photos of your family and friends to create animations in batches to share with them!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684764543307/197c8540-e67a-4afc-ae63-88a391ac37a0.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-youtube-video-downloader"><strong>YouTube video downloader</strong></h1>
<p>Sometimes you watch a video on YouTube, Which can be a tutorial, a comedy, or even a documentary, and you want to have it downloaded on your computer. Here is where the Python module <code>{pytube}</code> comes in handy.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> pytube <span class="hljs-keyword">import</span> YouTube

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">DownloadYT</span>(<span class="hljs-params">url</span>):</span>
    youtubeObject = YouTube(url)
    youtubeObject = youtubeObject.streams.get_highest_resolution()
    <span class="hljs-keyword">try</span>:
      youtubeObject.download()
      print(<span class="hljs-string">"Title:"</span>, youtubeObject.title)
      print(<span class="hljs-string">"=== Download is completed successfully ===\n"</span>)
    <span class="hljs-keyword">except</span>:
        print(<span class="hljs-string">"An error has occurred"</span>) 

urls = [<span class="hljs-string">'https://www.youtube.com/watch?v=ZnrjyEuBJcg&amp;t=14s'</span>, 
        <span class="hljs-string">'https://www.youtube.com/watch?v=e_B0vt-eWPw&amp;t=158s'</span>]

<span class="hljs-keyword">for</span> url <span class="hljs-keyword">in</span> urls:
  DownloadYT(url)
</code></pre>
<p>As you can see, to download the video in its best quality, all we need is to specify the <code>get_highest_resolution()</code> function and call <code>download()</code>.</p>
<p>So with these four mini projects, you should clearly understand the structure and how to build some projects with Python.</p>
]]></content:encoded></item><item><title><![CDATA[Build your first Data science project from your Netflix data]]></title><description><![CDATA[Use your own Netflix data to build your first data science project, analyse and visualize using Python.]]></description><link>https://shittuolumide.hashnode.dev/build-your-first-data-science-project-from-your-netflix-data</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/build-your-first-data-science-project-from-your-netflix-data</guid><category><![CDATA[Python]]></category><category><![CDATA[Data Science]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Tue, 21 Mar 2023 11:48:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1679394724370/1dcd7378-a65b-4f11-9a8f-dfe9df59dafb.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Are you new to Data science? are you still trying to get your first project up and running? if this is you, you are in the right place.</p>
<p>In this article, we will build a data science project together, or should I say you will build your first data science project using your own Netflix data. It is not always easy getting the right dataset for a data science project, so why go through that stress when you can easily get your own data from Netflix, and convert it into a dataset since Netflix allows you to download your complete watching history which you can actually use to build cool data science projects.</p>
<p>We will make use of some Python libraries (<strong>Pandas</strong> and <strong>Matplotlib</strong>) and at the end of this article, you should have a project that can be added to your portfolio.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li><p>Basic knowledge of Python, Pandas and Matplotlib.</p>
</li>
<li><p>Pandas and Matplotlib installed on your computer but if you don't have them installed already <code>pip install pandas</code> &amp; <code>pip install matplotlib</code> to install them.</p>
</li>
<li><p>A Netflix account.</p>
</li>
</ul>
<h2 id="heading-get-the-raw-data">🎯 Get the raw data</h2>
<p>For us to be able to build this project, we will need data. We can get the raw data by following these steps:</p>
<ul>
<li><p>Login to your <a target="_blank" href="https://www.netflix.com/">Netflix</a> account.</p>
</li>
<li><p>Navigate to the <a target="_blank" href="https://www.netflix.com/account/getmyinfo">Get my info page</a> and request your data.</p>
</li>
<li><p>A confirmation email will be sent to you, make sure to confirm it.</p>
</li>
<li><p>An email will be sent to you that your download is ready.<br />  <strong><em>Note*</em></strong>: this might take a while to come.*</p>
</li>
<li><p>After you download the zip file, you should see these directories.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679395385840/fb05dd58-4e31-4f68-96e4-227d551ec117.png" alt="Directories in the zip file." class="image--center mx-auto" /></p>
<ul>
<li>Click on the <strong><em>CONTENT_INTERACTION</em></strong> folder and open the <strong><em>ViewingActivity.csv</em></strong> file<strong><em>,</em></strong> this contains your full watching history.</li>
</ul>
<h2 id="heading-lets-examine-the-data">🎯 Let’s examine the data</h2>
<p>We will use our knowledge of Pandas to examine the data and see what we have. But first, let's import the <strong><em>ViewingActivity.csv</em></strong> file into our notebook and read it as a Pandas dataframe.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd
df = pd.read_csv(<span class="hljs-string">'ViewingActivity.csv'</span>)
</code></pre>
<p>Let’s have a look at the first set of rows that we have.</p>
<pre><code class="lang-python">df.head()
</code></pre>
<p>Let’s see the number of rows and columns that we are working with.</p>
<pre><code class="lang-python">df.shape

<span class="hljs-comment">#output: (9273, 10)</span>
</code></pre>
<p>From the dataset, we have 10 columns.</p>
<ul>
<li><p><strong><em>Profile Name</em></strong> — This shows the profiles of people sharing a Netflix account.</p>
</li>
<li><p><strong>Title</strong> — This column contains the names of the series a particular user is watching.</p>
</li>
<li><p><strong><em>Start Time &amp; Duration</em></strong> — This shows us when and also for how long did a user on the profile watch a movie.</p>
</li>
<li><p><strong><em>Device Type*</em></strong>—* This contains the different devices used to watch these movies. </p>
</li>
<li><p><strong><em>Country</em></strong> — The location(Country) where the particular profile is watching from.</p>
</li>
</ul>
<p>You can check out the remaining columns.</p>
<p>Before we can work with the data in more detail, we need to understand the underlying data types.</p>
<pre><code class="lang-python">df.dtypes
</code></pre>
<p>From the result, we see that all the columns store the data in the <strong><em>object</em></strong> data type.</p>
<h2 id="heading-getting-the-number-of-users-on-the-netflix-account">🎯 Getting the number of users on the Netflix account</h2>
<p>We can get the number of people that we share the same Netflix account with, all we have to do is find the unique users within the <strong><em>Profile Name</em></strong> column.</p>
<pre><code class="lang-python">df[<span class="hljs-string">"Profile Name"</span>].unique()
</code></pre>
<h2 id="heading-getting-the-number-of-devices-watching-on-the-netflix-account">🎯 Getting the number of devices watching on the Netflix account</h2>
<p>In the same way we found the number of users on the Netflix account, we can also find the number of unique devices watching movies on the account.</p>
<pre><code class="lang-python">df[<span class="hljs-string">"Device Type"</span>].unique()
</code></pre>
<h2 id="heading-getting-the-profile-with-the-most-viewing-and-activities">🎯 Getting the profile with the most viewing and activities</h2>
<p>We can find out which of the users is interacting and watching the most amongst the whole users on the Netflix account. We will use the <code>DataFrame.value_counts()</code> method to count the number of row occurrences </p>
<pre><code class="lang-python">df[<span class="hljs-string">'Profile Name'</span>].value_counts()
</code></pre>
<p>Using Matplotlib, we can easily visualize this.</p>
<pre><code class="lang-python">%matplotlib inline
<span class="hljs-keyword">import</span> matplotlib
<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt
df[<span class="hljs-string">'Profile Name'</span>].value_counts().plot(kind=<span class="hljs-string">'bar'</span>)
plt.show()
</code></pre>
<p>The output looks like this:</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*O4KJ-NxF690xRY1ZvQDDDg.png" alt="The profile with the most viewing and activities." /></p>
<h2 id="heading-getting-the-profile-with-the-most-watched-time">🎯 Getting the profile with the most-watched time</h2>
<p>In order to get the user that watched movies the most, we have to go through several steps. </p>
<p>The first thing to do is to transform the <strong><em>Start Time</em></strong> and <strong><em>Duration</em></strong> columns into a <strong>DateTime</strong> format.</p>
<pre><code class="lang-python">df[<span class="hljs-string">'Start Time'</span>] = pd.to_datetime(df[<span class="hljs-string">'Start Time'</span>], utc=<span class="hljs-literal">True</span>)
df[<span class="hljs-string">'Duration'</span>] = pd.to_timedelta(df[<span class="hljs-string">'Duration'</span>])
</code></pre>
<p>The next thing is to check the overall viewing duration for all profiles.</p>
<pre><code class="lang-python">df[<span class="hljs-string">'Duration'</span>].sum()
</code></pre>
<p>Let’s find the viewing duration for each profile.</p>
<pre><code class="lang-python">df.loc[df[<span class="hljs-string">'Profile Name'</span>]==<span class="hljs-string">'Add your profile name'</span>,<span class="hljs-string">'Duration'</span>].sum()
</code></pre>
<p>From the result, we will notice that we have the same order as the profile with the most activities. So that means that the profile with the most activities also has a higher watch time. </p>
<p>The visualization is not that easy, because a <strong>Timedelta</strong> is nothing that can be plotted using <strong>Matplotlib</strong>. So we have to perform another Transformation with NumPy’s astype method.</p>
<pre><code class="lang-python">df.loc[df[<span class="hljs-string">'Profile Name'</span>]==<span class="hljs-string">'Your profile name'</span>,<span class="hljs-string">'Duration'</span>].astype(<span class="hljs-string">'timedelta64[s]'</span>).sum()
</code></pre>
<p>So we can now create a dictionary to store the overall watch time per user in seconds.</p>
<pre><code class="lang-python">watchTime = {}
watchTime.update({<span class="hljs-string">"First Profile"</span>: df.loc[df[<span class="hljs-string">'Profile Name'</span>]==<span class="hljs-string">'First Profile'</span>,<span class="hljs-string">'Duration'</span>].astype(<span class="hljs-string">'timedelta64[s]'</span>).sum()})
watchTime.update({<span class="hljs-string">"Second Profile"</span>: df.loc[df[<span class="hljs-string">'Profile Name'</span>]==<span class="hljs-string">'Second Profile'</span>,<span class="hljs-string">'Duration'</span>].astype(<span class="hljs-string">'timedelta64[s]'</span>).sum()})
watchTime.update({<span class="hljs-string">"Third Profile"</span>: df.loc[df[<span class="hljs-string">'Profile Name'</span>]==<span class="hljs-string">'Third Profile'</span>,<span class="hljs-string">'Duration'</span>].astype(<span class="hljs-string">'timedelta64[s]'</span>).sum()})
</code></pre>
<p>The dictionary looks like this:</p>
<pre><code class="lang-python">{<span class="hljs-string">'First Profile'</span>: <span class="hljs-number">4138000.0</span>, <span class="hljs-string">'Second Profile'</span>: <span class="hljs-number">1411573.0</span>, <span class="hljs-string">'Third Profile'</span>: <span class="hljs-number">2050125.0</span>,}
</code></pre>
<p>So we can now plot the bar chart.</p>
<pre><code class="lang-python">%matplotlib inline
<span class="hljs-keyword">import</span> matplotlib
<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt
plt.bar(*zip(*watchTime.items()))
plt.show()
</code></pre>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*dkKzcoN4piL2KEDNRMe2OQ.png" alt="The profile with the most-watched time." /></p>
<h2 id="heading-getting-the-devices-used-by-a-user-and-which-device-is-used-the-most">🎯 Getting the devices used by a user, and which device is used the most</h2>
<p>We will first have a look at the <strong><em>Device Type</em></strong> column and see the devices used by each user, they are actually plenty (some were even used just once while some were used frequently).</p>
<pre><code class="lang-python">df[<span class="hljs-string">'Device Type'</span>].value_counts()
</code></pre>
<p>We can again quickly plot this in a bar chart.</p>
<pre><code class="lang-python">df[<span class="hljs-string">'Device Type'</span>].value_counts().plot(kind=<span class="hljs-string">'bar'</span>)
plt.show()
</code></pre>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*tTjmF1VHYA3qF_eLBSV8mA.png" alt="The device used the most" /></p>
<p>We can now filter them based on each user(just in case you want to know how many devices you used)</p>
<pre><code class="lang-python">df_device = df.loc[df[<span class="hljs-string">'Profile Name'</span>] == <span class="hljs-string">'Your profile name'</span>]
df_device[<span class="hljs-string">'Device Type'</span>].value_counts()
</code></pre>
<p>We will see the see device name and the number of times it was used by that particular user. So we can plot the bar chart now.</p>
<pre><code class="lang-python">df_device[<span class="hljs-string">'Device Type'</span>].value_counts().plot(kind=<span class="hljs-string">'bar'</span>)
plt.show()
</code></pre>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*Al2fi3a65l9t68I60kKO9A.png" alt="Getting the devices used by a user." /></p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In this article, we were able to cover a simple data science project, download raw data from Netflix, analyse and visualize the data. As you can also see that we answered a number of questions using the dataset and trust me more questions can still be explored. I am curious to know know what project ideas you get from this article and what you build.</p>
<p>In the meantime, how about you answer these questions with the dataset:</p>
<ul>
<li><p>The most popular/watched title.</p>
</li>
<li><p>A movie watched by all users.</p>
</li>
<li><p>Recommend a movie for one user based on the common watching history of other users.</p>
</li>
</ul>
<p>Let’s connect on <a target="_blank" href="https://www.twitter.com/Shittu_Olumide_">Twitter</a> and on <a target="_blank" href="https://www.linkedin.com/in/olumide-shittu">LinkedIn</a>. You can also subscribe to my <a target="_blank" href="https://www.youtube.com/channel/UCNhFxpk6hGt5uMCKXq0Jl8A">YouTube</a> channel.</p>
<p><strong>Happy Coding!</strong></p>
]]></content:encoded></item><item><title><![CDATA[Understanding Python Metaclasses]]></title><description><![CDATA[Overview of metaclasses in Python and best practices when using it.]]></description><link>https://shittuolumide.hashnode.dev/understanding-python-metaclasses</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/understanding-python-metaclasses</guid><category><![CDATA[Python]]></category><category><![CDATA[python beginner]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Tue, 14 Mar 2023 13:46:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1678798659391/c5c0bbf6-dbdf-4e3f-b34e-fa157c993a0e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In Python, a metaclass is a class that defines the behavior of other classes. Specifically, a metaclass is a class that is used to create and customize other classes.</p>
<p>When you define a class in Python, Python automatically creates the class using a built-in metaclass called <code>type</code>. However, you can create your own custom metaclasses by defining a new class that inherits from <code>type</code>.</p>
<p>Metaclasses are used to modify the behavior of classes in various ways. For example, you can use a metaclass to:</p>
<ul>
<li><p>Modify the attributes of a class when it is created.</p>
</li>
<li><p>Automatically add new methods or attributes to a class.</p>
</li>
<li><p>Enforce coding standards or conventions for classes.</p>
</li>
<li><p>Implement custom behavior for classes.</p>
</li>
</ul>
<p>To define a metaclass in Python, you create a new class that inherits from <code>type</code>. For example:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyMeta</span>(<span class="hljs-params">type</span>):</span>
    <span class="hljs-keyword">pass</span>
</code></pre>
<p>In this example, we define a new metaclass called <code>MyMeta</code> that inherits from <code>type</code>. We can now use <code>MyMeta</code> as the metaclass for other classes by setting the <code>metaclass</code> attribute of those classes to <code>MyMeta</code>. For example:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span>(<span class="hljs-params">metaclass=MyMeta</span>):</span>
    <span class="hljs-keyword">pass</span>
</code></pre>
<p>In this example, we define a new class called <code>MyClass</code> and set its metaclass to <code>MyMeta</code>. When <code>MyClass</code> is created, Python will use <code>MyMeta</code> as the metaclass, and the behaviour of <code>MyClass</code> will be determined by the behaviour of <code>MyMeta</code>.</p>
<h2 id="heading-create-your-first-metaclass">Create your first Metaclass</h2>
<p>Here's an example of how to define a simple metaclass in Python:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyMeta</span>(<span class="hljs-params">type</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__new__</span>(<span class="hljs-params">cls, name, bases, attrs</span>):</span>
        print(<span class="hljs-string">"Creating class"</span>, name)
        <span class="hljs-keyword">return</span> super().__new__(cls, name, bases, attrs)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span>(<span class="hljs-params">metaclass=MyMeta</span>):</span>
    x = <span class="hljs-number">1</span>
</code></pre>
<p>In this example, we define a new metaclass called <code>MyMeta</code>. The <code>__new__</code> method of this metaclass is called when a new class is created. The <code>__new__</code> method takes four arguments:</p>
<ul>
<li><p><code>cls</code>: the metaclass itself.</p>
</li>
<li><p><code>name</code>: the name of the class being created.</p>
</li>
<li><p><code>bases</code>: a tuple of base classes for the new class.</p>
</li>
<li><p><code>attrs</code>: a dictionary of class attributes</p>
</li>
</ul>
<p>In this example, we simply print a message when a new class is created.</p>
<p>We then define a new class called <code>MyClass</code>, and set its metaclass to <code>MyMeta</code>. This means that when <code>MyClass</code> is created, the <code>__new__</code> method of <code>MyMeta</code> is called.</p>
<p>When we run this code, we get the following output:</p>
<pre><code class="lang-python">Creating <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span></span>
</code></pre>
<p>This shows that the <code>__new__</code> method of <code>MyMeta</code> is called when <code>MyClass</code> is created.</p>
<hr />
<p>Let's also look at an example of how to add custom behaviors to a class using metaclasses such as adding methods or modifying instance creation.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">InteractiveMeta</span>(<span class="hljs-params">type</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__new__</span>(<span class="hljs-params">cls, name, bases, attrs</span>):</span>
        print(<span class="hljs-string">f"Creating class '<span class="hljs-subst">{name}</span>'"</span>)
        new_class = super().__new__(cls, name, bases, attrs)
        new_class.say_hello = <span class="hljs-keyword">lambda</span> self: print(<span class="hljs-string">f"Hello from <span class="hljs-subst">{self.__class__.__name__}</span>!"</span>)
        <span class="hljs-keyword">return</span> new_class

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span>(<span class="hljs-params">cls, *args, **kwargs</span>):</span>
        print(<span class="hljs-string">f"Creating instance of '<span class="hljs-subst">{cls.__name__}</span>'"</span>)
        instance = super().__call__(*args, **kwargs)
        instance.say_hello()
        <span class="hljs-keyword">return</span> instance


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span>(<span class="hljs-params">metaclass=InteractiveMeta</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name</span>):</span>
        self.name = name
</code></pre>
<p>In the code above, we define an interactive metaclass called <code>InteractiveMeta</code> that has two functions: <code>__new__</code> and <code>__call__</code>.</p>
<p>The <code>__new__</code> function is called when a new class is created, and it takes four arguments: <code>cls</code>, <code>name</code>, <code>bases</code>, and <code>attrs</code>. In this function, we first print a message indicating that a new class is being created. We then create the new class using the <code>super().__new__()</code> function, and add a new method called <code>say_hello</code> to the class using a lambda function. Finally, we return the new class.</p>
<p>The <code>__call__</code> function is called when an instance of the class is created, and it takes <code>cls</code>, <code>*args</code>, and <code>**kwargs</code> as arguments. In this function, we print a message indicating that a new instance of the class is being created. We then create the instance using the <code>super().__call__()</code> function, call the <code>say_hello()</code> method on the instance, and return the instance.</p>
<p>We then define a new class called <code>MyClass</code> and set its metaclass to <code>InteractiveMeta</code>. When <code>MyClass</code> is created, the <code>__new__</code> function of <code>InteractiveMeta</code> is called to create the class, and the <code>__call__</code> function is called to create an instance of the class.</p>
<p>Finally, we create an instance of <code>MyClass</code> and pass it a name argument. When the instance is created, the <code>__call__</code> function of <code>InteractiveMeta</code> is called to create the instance, and the <code>say_hello()</code> method of the instance is called to print a message.</p>
<h2 id="heading-python-metaclass-best-practices">Python metaclass best practices</h2>
<p>Here are some best practices to follow when working with metaclasses:</p>
<ol>
<li><p><strong>Keep it simple</strong>: Avoid using metaclasses unless they are necessary for your use case. Overusing metaclasses can make your code difficult to read and maintain.</p>
</li>
<li><p><strong>Document your code</strong>: When using a metaclass, make sure to document its purpose and behaviour so that other developers can understand what your code is doing.</p>
</li>
<li><p><strong>Use descriptive names</strong>: When defining a metaclass, use a descriptive name that reflects its purpose and behaviour. This will make it easier for other developers to understand what your code is doing.</p>
</li>
<li><p><strong>Test thoroughly</strong>: Metaclasses can be difficult to debug, so make sure to thoroughly test your code to ensure that it behaves correctly.</p>
</li>
<li><p><strong>Use inheritance sparingly</strong>: Inheritance can be a useful tool for defining metaclasses, but it can also make your code more complex. Try to use inheritance sparingly and only when it makes sense for your use case.</p>
</li>
<li><p><strong>Follow PEP 3115</strong>: If you're defining a metaclass in Python 3, follow the guidelines set out in PEP 3115. This will ensure that your metaclass is compatible with the latest version of Python and will make it easier for other developers to understand your code.</p>
</li>
<li><p><strong>Keep performance in mind</strong>: Metaclasses can have a significant impact on performance, especially when used in large projects. Make sure to test the performance of your code and optimize it as necessary.</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Metaclasses can be powerful tools for customizing the behavior of classes in Python, but they can also be complex and difficult to understand. It's generally recommended to use metaclasses sparingly and only when necessary and to thoroughly test any code that uses metaclasses to ensure that it behaves correctly.</p>
<p>Here are some resources online where you can learn more about metaclasses in Python:</p>
<ol>
<li><p>Python documentation - Metaclasses: <a target="_blank" href="https://docs.python.org/3/reference/datamodel.html#metaclasses"><strong>https://docs.python.org/3/reference/datamodel.html#metaclasses</strong></a></p>
</li>
<li><p>Real Python - Understanding Python Metaclasses: <a target="_blank" href="https://realpython.com/python-metaclasses/"><strong>https://realpython.com/python-metaclasses/</strong></a></p>
</li>
<li><p>GeeksforGeeks - Metaclasses in Python: <a target="_blank" href="https://www.geeksforgeeks.org/metaclasses-in-python/"><strong>https://www.geeksforgeeks.org/metaclasses-in-python/</strong></a></p>
</li>
</ol>
<p>Let's connect on <a target="_blank" href="https://www.twitter.com/Shittu_Olumide_">Twitter</a> and on <a target="_blank" href="https://www.linkedin.com/in/olumide-shittu">LinkedIn</a>. You can also subscribe to my <a target="_blank" href="https://www.youtube.com/channel/UCNhFxpk6hGt5uMCKXq0Jl8A">YouTube</a> channel.</p>
<p>Happy Coding!</p>
]]></content:encoded></item><item><title><![CDATA[Python hashing and salting]]></title><description><![CDATA[Learn everything about salting, the reasons for salting, and learn everything about hashing, and hashing technologies in this article.]]></description><link>https://shittuolumide.hashnode.dev/python-hashing-and-salting</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/python-hashing-and-salting</guid><category><![CDATA[Python]]></category><category><![CDATA[Python 3]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[data structures]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Sun, 05 Mar 2023 15:21:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677965574467/01cdd695-309b-47cc-a49c-a6e80a795e9d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, we will learn about hashing in python, hashing algorithms - MD5 (Message-Digest algorithm 5), SHA-1 (Secure Hash Algorithm 1), SHA-256 (Secure Hash Algorithm 256), SHA-512 (Secure Hash Algorithm 512), and the most recent &amp; recommended hashing technologies for password storage is <strong>bcrypt</strong>, <strong>scrypt</strong>,and <strong>Argon2.</strong></p>
<p>We will also look into what salting is all about, this is definitely going to be a very interesting article so let's dive right in.</p>
<h1 id="heading-what-is-salting">What is Salting?</h1>
<p>Cybercrime has increased in frequency over recent years, to gain access to passwords, user information, and other sensitive data, hackers are coming up with a variety of strategies. As a result, it is imperative that developers implement security measures to safeguard the data of their users. Salting passwords is one of these safeguards.</p>
<p>Salting is a security measure that prevents hackers from quickly cracking user passwords. Before hashing a user's password, it adds a random string of characters to it, salt is the name for the arbitrary string. The password and salt are combined, after which the resulting string is hashed. Password cracking techniques like <strong>dictionary</strong> <strong>attacks</strong>, <strong>brute force attacks</strong>, and <strong>rainbow table attacks</strong> are made more challenging by this process.</p>
<h2 id="heading-reasons-for-salting">Reasons for Salting</h2>
<p>There are several reasons why you should use salt when hashing passwords. Some of these reasons include:</p>
<ul>
<li><p><strong>Protection against insider attacks</strong>: Salting makes it harder for insiders to steal passwords since they won't be able to crack them easily.</p>
</li>
<li><p><strong>Preventing brute force attacks</strong>: Brute force attacks involve trying all possible combinations of characters until the correct password is found. With salting, even if a hacker manages to crack one password, it won't work for other users with similar passwords.</p>
</li>
<li><p><strong>Preventing dictionary attacks</strong>: With salting, even if the same password is used by multiple users, they will end up with different hashes. This makes it harder for hackers to use pre-computed tables like rainbow tables to crack passwords.</p>
</li>
<li><p><strong>Compliance with regulations</strong>: Many data protection regulations require that passwords be stored securely. Salting passwords is a good way to ensure that you are compliant with these regulations.</p>
</li>
</ul>
<p>In Python, salting can be done using the built-in <code>hashlib</code> module. Here is an example of how to salt a password in Python:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> hashlib
<span class="hljs-keyword">import</span> os

password = <span class="hljs-string">'1234!3#'</span>
salt = os.urandom(<span class="hljs-number">32</span>)
hashed_password = hashlib.pbkdf2_hmac(<span class="hljs-string">'sha256'</span>, password.encode(<span class="hljs-string">'utf-8'</span>), salt, <span class="hljs-number">100000</span>)
</code></pre>
<p>In the example above, we first generate a random salt using the <code>os.urandom()</code> method. We then use the <code>hashlib.pbkdf2_hmac()</code> method to hash the password with the salt. The <code>pbkdf2_hmac()</code> method is a key derivation function that is commonly used for password hashing. It takes four arguments:</p>
<ul>
<li><p>The hash algorithm to use (in this case, <strong>SHA-256</strong>).</p>
</li>
<li><p>The password to hash (encoded as <strong>bytes</strong>).</p>
</li>
<li><p>The salt to use (also encoded as <strong>bytes</strong>).</p>
</li>
<li><p>The number of iterations to use (<strong>100000</strong> in this case).</p>
</li>
</ul>
<p>The output of the <code>pbkdf2_hmac()</code> method is the hashed password, which can be stored in a database or used for authentication.</p>
<p>With that understanding, let's hop on to learn about hashing.</p>
<h1 id="heading-what-is-hashing">What is Hashing</h1>
<p>Hashing in Python is the process of converting an input into a fixed-length sequence of bytes, called a hash or message digest. The hash is generated using a mathematical function that maps the input data to a fixed-size array of bytes. This process is irreversible, meaning that it is impossible to reconstruct the input data from the hash.</p>
<h2 id="heading-hashing-applications">Hashing applications</h2>
<p>Hashing has various applications including:</p>
<ul>
<li><p><strong>Data Integrity</strong>: Hashing can be used to ensure the integrity of data by generating a hash of the data and comparing it with the hash of the original data. If the hashes match, it indicates that the data has not been tampered with.</p>
</li>
<li><p><strong>Password Storage</strong>: Hashing is commonly used to store passwords in a secure way. When a user creates a password, it is hashed and stored in a database. When the user logs in, the password they enter is hashed and compared with the stored hash. If the hashes match, the user is authenticated.</p>
</li>
<li><p><strong>Indexing and Searching</strong>: Hashing can be used to create indexes for searching and retrieving data quickly. Hash tables are commonly used in computer science to implement this functionality.</p>
</li>
<li><p><strong>Digital Signatures</strong>: Hashing can be used to create digital signatures, which can be used to verify the authenticity of digital documents. A digital signature is created by hashing the document and then encrypting the hash with the private key of the signer. The recipient can then use the signer's public key to decrypt the hash and compare it with the hash of the original document.</p>
</li>
</ul>
<h2 id="heading-hashing-algorithms">Hashing algorithms</h2>
<p>Although there are several hashing algorithms in Python, we will only examine a few in this section.</p>
<ul>
<li><p><strong>MD5 (Message-Digest algorithm 5)</strong></p>
<pre><code class="lang-python">  <span class="hljs-keyword">import</span> hashlib

  <span class="hljs-comment"># Create a hash object using MD5 algorithm</span>
  hash_object = hashlib.md5()

  <span class="hljs-comment"># Update the hash object with a message</span>
  hash_object.update(<span class="hljs-string">b"Hello, world!"</span>)

  <span class="hljs-comment"># Get the hexadecimal digest of the hash</span>
  hex_dig = hash_object.hexdigest()

  print(hex_dig)
</code></pre>
<p>  This code creates an instance of the <code>hashlib.md5()</code> class, updates it with the message "<strong>Hello, world!</strong>", and gets the hexadecimal digest of the hash. <strong>MD5</strong> is a widely-used hash function, but it has some weaknesses and should not be used for cryptographic purposes.</p>
</li>
<li><p><strong>SHA-1 (Secure Hash Algorithm 1)</strong></p>
<pre><code class="lang-python">  <span class="hljs-keyword">import</span> hashlib

  <span class="hljs-comment"># Create a hash object using SHA-1 algorithm</span>
  hash_object = hashlib.sha1()

  <span class="hljs-comment"># Update the hash object with a message</span>
  hash_object.update(<span class="hljs-string">b"Hello, world!"</span>)

  <span class="hljs-comment"># Get the hexadecimal digest of the hash</span>
  hex_dig = hash_object.hexdigest()

  print(hex_dig)
</code></pre>
<p>  This code creates an instance of the <code>hashlib.sha1()</code> class, updates it with the message "<strong>Hello, world!</strong>", and gets the hexadecimal digest of the hash. <strong>SHA-1</strong> is also widely used, but it has been found to have some weaknesses and should be used with caution.</p>
</li>
<li><p><strong>SHA-256 (Secure Hash Algorithm 256)</strong></p>
<pre><code class="lang-python">  <span class="hljs-keyword">import</span> hashlib

  <span class="hljs-comment"># Create a hash object using SHA-256 algorithm</span>
  hash_object = hashlib.sha256()

  <span class="hljs-comment"># Update the hash object with a message</span>
  hash_object.update(<span class="hljs-string">b"Hello, world!"</span>)

  <span class="hljs-comment"># Get the hexadecimal digest of the hash</span>
  hex_dig = hash_object.hexdigest()

  print(hex_dig)
</code></pre>
<p>  This code creates an instance of the <code>hashlib.sha256()</code> class, updates it with the message "<strong>Hello, world!</strong>", and gets the hexadecimal digest of the hash. <strong>SHA-256</strong> is a more secure hash function than <strong>MD5</strong> or <strong>SHA-1</strong>, and is commonly used in cryptography.</p>
</li>
<li><p><strong>SHA-512 (Secure Hash Algorithm 512)</strong>  </p>
<pre><code class="lang-python">  <span class="hljs-keyword">import</span> hashlib

  <span class="hljs-comment"># Create a hash object using SHA-512 algorithm</span>
  hash_object = hashlib.sha512()

  <span class="hljs-comment"># Update the hash object with a message</span>
  hash_object.update(<span class="hljs-string">b"Hello, world!"</span>)

  <span class="hljs-comment"># Get the hexadecimal digest of the hash</span>
  hex_dig = hash_object.hexdigest()

  print(hex_dig)
</code></pre>
<p>  This code creates an instance of the <code>hashlib.sha512()</code> class, updates it with the message "Hello, world!", and gets the hexadecimal digest of the hash. <strong>SHA-512</strong> is an even more secure hash function than <strong>SHA-256</strong>, but it is also slower and may not be necessary for all applications.</p>
</li>
</ul>
<h2 id="heading-python-hashing-technologies">Python hashing Technologies</h2>
<ul>
<li><p><strong>Scrypt</strong>: is a password-based key derivation function that is designed to be expensive to compute and hence difficult to attack via brute force methods. It is commonly used for password storage and authentication purposes. The <strong>scrypt</strong> algorithm is similar to <strong>bcrypt</strong> but is designed to be more memory-hard, making it more difficult to create specialized hardware for cracking <strong>scrypt</strong> hashes.  </p>
<p>  Let's see how it can be implemented.</p>
</li>
</ul>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> scrypt

<span class="hljs-comment"># Hash a password</span>
password = <span class="hljs-string">b"password1234#$"</span>
salt = scrypt.gensalt()
hashed_password = scrypt.hash(password, salt)

<span class="hljs-comment"># Verify a password</span>
password_to_verify = <span class="hljs-string">b"password1234#$"</span>
<span class="hljs-keyword">if</span> scrypt.verify(password_to_verify, hashed_password):
    print(<span class="hljs-string">"Password is correct"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"Invalid password"</span>)
</code></pre>
<ul>
<li><p><strong>Bcrypt:</strong> is a popular password-hashing library used for secure password storage. It uses the Blowfish algorithm to perform the hash function, making it one of the most secure and slowest password-hashing functions available.  </p>
<p>  Let's see how it can be implemented.</p>
</li>
</ul>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> bcrypt

<span class="hljs-comment"># Hash a password</span>
password = <span class="hljs-string">b"password1234#$"</span>.encode()
salt = bcrypt.gensalt()
hashed_password = bcrypt.hashpw(password, salt)

<span class="hljs-comment"># Verify a password</span>
password_to_verify = <span class="hljs-string">b"password1234#$"</span>.encode()
<span class="hljs-keyword">if</span> bcrypt.checkpw(password_to_verify, hashed_password):
    print(<span class="hljs-string">"Password is correct"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"Invalid password"</span>)
</code></pre>
<ul>
<li><p><strong>Argon2:</strong> is a newer password hashing algorithm that is currently considered to be one of the strongest and most secure hashing algorithms available. It was the winner of the Password Hashing Competition in 2015 and is now widely used for password storage in many modern applications.  </p>
<p>  Here's an example of how to use the <strong>Argon2</strong> algorithm in Python using the <code>argon2</code> library:</p>
</li>
</ul>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> argon2

<span class="hljs-comment"># Define the password to be hashed</span>
password = <span class="hljs-string">b'password1234#$'</span>

<span class="hljs-comment"># Hash the password using Argon2</span>
hasher = argon2.PasswordHasher()
hashed_password = hasher.hash(password)

<span class="hljs-comment"># Print the hashed password</span>
print(hashed_password)

<span class="hljs-comment"># Verify a password against a hashed password</span>
<span class="hljs-comment"># Note that this will return True if the password matches the hash</span>
<span class="hljs-comment"># and False if it does not.</span>
new_password = <span class="hljs-string">b'password1234#$'</span>
<span class="hljs-keyword">try</span>:
    hasher.verify(hashed_password, new_password)
    print(<span class="hljs-string">"Password is valid."</span>)
<span class="hljs-keyword">except</span> argon2.exceptions.VerifyMismatchError:
    print(<span class="hljs-string">"Password is incorrect."</span>)
</code></pre>
<p>In this example, we first define the password that we want to hash. We then create an instance of the <code>argon2.PasswordHasher()</code> class and use it to hash the password. The resulting hashed password is stored in the <code>hashed_password</code> variable.</p>
<p>We can then verify a password against the hashed password using the <code>verify()</code> method of the <code>argon2.PasswordHasher()</code> class. If the password matches the hash, the method will return <code>True</code>. If the password does not match the hash, the method will raise a <code>argon2.exceptions.VerifyMismatchError</code>.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Wrapping up, hashing and salting are important techniques used in enhancing the security of passwords and sensitive data in Python. Hashing enables the creation of a fixed size, unique, and irreversible representation of data while salting adds an extra layer of security by adding random strings to the data before hashing. We have discussed the popular hashing algorithms used in Python, including <strong>SHA-256</strong>, <strong>bcrypt</strong>, <strong>scrypt</strong>, and <strong>Argon2</strong>, with code examples and explanations for each. It is important to choose the right algorithm based on your specific security requirements.</p>
<p>Let's connect on <a target="_blank" href="https://www.twitter.com/Shittu_Olumide_"><strong>Twitter</strong></a> and on <a target="_blank" href="https://www.linkedin.com/in/olumide-shittu"><strong>LinkedIn</strong></a>. You can also subscribe to my <a target="_blank" href="https://www.youtube.com/channel/UCNhFxpk6hGt5uMCKXq0Jl8A"><strong>YouTube</strong></a> channel.</p>
<p><strong>Happy Coding!</strong></p>
]]></content:encoded></item><item><title><![CDATA[Extract Tables From Images in Python]]></title><description><![CDATA[In this article, we will explore how to extract tables from images using Python. We will cover a library called the img2table in Python.]]></description><link>https://shittuolumide.hashnode.dev/extract-tables-from-images-in-python</link><guid isPermaLink="true">https://shittuolumide.hashnode.dev/extract-tables-from-images-in-python</guid><category><![CDATA[Python]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Productivity]]></category><category><![CDATA[Python 3]]></category><dc:creator><![CDATA[Shittu Olumide Ayodeji]]></dc:creator><pubDate>Mon, 27 Feb 2023 11:17:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677489347951/841def9d-c79e-4447-ad0e-0cbb36c744b6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Extracting tables from images can be a tedious and time-consuming task, especially if you have a large number of images to process. However, with the right tools and techniques, you can automate this process and extract tables from images quickly and easily.</p>
<p>In this article, we will explore how to extract tables from images using Python. We will cover a library(<strong>img2table</strong>) that can be used to identify and extract tables from images, along with sample code and explanations. Whether you are working with scanned documents, photos, or other types of images, this article will provide you with the tools and knowledge you need to extract tables efficiently and accurately.</p>
<h1 id="heading-what-is-img2table">What is img2table?</h1>
<p><a target="_blank" href="https://github.com/xavctn/img2table"><strong>Img2Table</strong></a> is a straightforward, user-friendly Python library for table extraction and identification that is based on OpenCV image processing and supports PDF files in addition to the majority of popular image file formats.</p>
<p>Due to its design, it offers a useful and less heavy alternative to solutions based on neural networks, especially for CPU usage.</p>
<p>It supports the following file formats:</p>
<ul>
<li><p>JPEG files - <em>.jpeg,</em> .jpg, *.jpe</p>
</li>
<li><p>Portable Network Graphics - *.png</p>
</li>
<li><p>JPEG 2000 files - *.jp2</p>
</li>
</ul>
<ul>
<li><p>Windows bitmaps - <em>.bmp,</em> .dib</p>
</li>
<li><p>WebP - *.webp</p>
</li>
<li><p>Portable image format - <em>.pbm,</em> .pgm, <em>.ppm</em> .pxm, *.pnm</p>
</li>
<li><p>PFM files - *.pfm</p>
</li>
<li><p>OpenEXR Image files - *.exr</p>
</li>
</ul>
<h2 id="heading-img2table-features">img2table Features</h2>
<ul>
<li><p>Table cell-level bounding boxes and table identification for images and PDF files.</p>
</li>
<li><p>Dealing with intricate table structures, like merged cells.</p>
</li>
<li><p>Extraction of table titles.</p>
</li>
<li><p>Extracting table content while supporting OCR tools and services.</p>
</li>
<li><p>A Pandas DataFrame representation and a simple object representing the extracted tables are returned.</p>
</li>
<li><p>Preserve the original structure of extracted tables by exporting them to an Excel file.</p>
</li>
</ul>
<p>The package is simple (in comparison to deep learning solutions) and needs little or no training. There are still some limitations though since borderless tables' more complicated identification is not yet supported and may call for CNN-based approaches.</p>
<h1 id="heading-implementation">Implementation</h1>
<h3 id="heading-installation">Installation</h3>
<p>Just like every other Python package, img2table can be installed via <code>pip</code> .</p>
<pre><code class="lang-python">pip install img2table
</code></pre>
<h3 id="heading-working-with-images">Working with Images</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> img2table.document <span class="hljs-keyword">import</span> Image

image = Image(src,dpi=<span class="hljs-number">200</span>, detect_rotation=<span class="hljs-literal">False</span>)
</code></pre>
<p>We instantiate <code>Image</code> , where src is the path to the image (<strong>it is required</strong>), <code>dpi</code> is used to adapt OpenCV algorithm parameters, it's optional with an <code>int</code> type (<strong>default is 200</strong>), <code>detect_rotation</code> detects and corrects skew or rotation of the image, it is a boolean type and by default <code>False</code>.</p>
<p>Let's have an example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> img2table.document <span class="hljs-keyword">import</span> Image

<span class="hljs-comment"># Instantiation of the image</span>
img = Image(src=<span class="hljs-string">"image.jpg"</span>)

<span class="hljs-comment"># Table identification</span>
imgage_tables = img.extract_tables()

<span class="hljs-comment"># Result of table identification</span>
imgage_tables

<span class="hljs-comment">#output</span>
[ExtractedTable(title=<span class="hljs-literal">None</span>, bbox=(<span class="hljs-number">10</span>, <span class="hljs-number">8</span>, <span class="hljs-number">745</span>, <span class="hljs-number">314</span>),shape=(<span class="hljs-number">6</span>, <span class="hljs-number">3</span>)),
 ExtractedTable(title=<span class="hljs-literal">None</span>, bbox=(<span class="hljs-number">936</span>, <span class="hljs-number">9</span>, <span class="hljs-number">1129</span>, <span class="hljs-number">111</span>),shape=(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>))]
</code></pre>
<h3 id="heading-working-with-pdf">Working with PDF</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> img2table.document <span class="hljs-keyword">import</span> PDF

pdf = PDF(src, dpi=<span class="hljs-number">200</span>, pages=[<span class="hljs-number">0</span>, <span class="hljs-number">2</span>])
</code></pre>
<p>It is the same as the way we work with images, just that we have a new parameter <code>pages</code>, which is a list of PDF page indexes to be processed. But if there are no specified indexes in the <code>pages</code> list, all the pages are processed.</p>
<h3 id="heading-working-with-ocr">Working with OCR</h3>
<p>To parse the content of tables, <code>img2table</code> offers an interface for various OCR tools and services.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> img2table.ocr <span class="hljs-keyword">import</span> TesseractOCR

ocr = TesseractOCR(n_threads=<span class="hljs-number">1</span>, lang=<span class="hljs-string">"eng"</span>, tessdata_dir=<span class="hljs-string">"..."</span>)
</code></pre>
<p>Where <code>n_threads</code> is the number of concurrent threads used to call Tesseract with an <code>int</code> type and the default is <code>1</code>, <code>lang</code> is used in Tesseract for text extraction and it is optional, finally the <code>tessdata_dir</code> is the directory containing Tesseract traineddata files.</p>
<blockquote>
<p>Note: <em>Usage of</em> <a target="_blank" href="https://github.com/tesseract-ocr/tesseract"><em>Tesseract-OCR</em></a> <em>requires prior installation.</em></p>
</blockquote>
<p>Let's have a look at an example.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> img2table.document <span class="hljs-keyword">import</span> PDF
<span class="hljs-keyword">from</span> img2table.ocr <span class="hljs-keyword">import</span> TesseractOCR

<span class="hljs-comment"># Instantiation of the pdf</span>
pdf = PDF(src=<span class="hljs-string">"tablesfile.pdf"</span>)

<span class="hljs-comment"># Instantiation of the OCR, Tesseract, which requires prior installation</span>
ocr = TesseractOCR(lang=<span class="hljs-string">"eng"</span>)

<span class="hljs-comment"># Table identification and extraction</span>
pdf_tables = pdf.extract_tables(ocr=ocr)

<span class="hljs-comment"># We can also create an excel file with the tables</span>
pdf.to_xlsx(<span class="hljs-string">'tables.xlsx'</span>, ocr=ocr)
</code></pre>
<h3 id="heading-extracting-multiple-tables">Extracting Multiple tables</h3>
<p>The <code>extract_tables</code> method of a document allows multiple tables to be extracted simultaneously from a PDF page or an image.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> img2table.ocr <span class="hljs-keyword">import</span> TesseractOCR
<span class="hljs-keyword">from</span> img2table.document <span class="hljs-keyword">import</span> Image

<span class="hljs-comment"># Instantiation of OCR</span>
ocr = TesseractOCR(n_threads=<span class="hljs-number">1</span>, lang=<span class="hljs-string">"eng"</span>)

<span class="hljs-comment"># Instantiation of document, either an image or a PDF</span>
doc = Image(src, dpi=<span class="hljs-number">200</span>)

<span class="hljs-comment"># Table extraction</span>
extracted_tables = doc.extract_tables(ocr=ocr,
                                      implicit_rows=<span class="hljs-literal">True</span>,
                                      borderless_tables=<span class="hljs-literal">False</span>,
                                      min_confidence=<span class="hljs-number">50</span>)
</code></pre>
<p>Most of the parameters have been discussed earlier when working with images and PDF, but there are new parameters. <code>ocr</code> is the instance used to parse document text, <code>implicit_rows</code> is a Boolean type indicating if implicit rows should be identified, <code>borderless_tables</code> indicates if borderless tables are extracted, and lastly, <code>min_confidence</code> is the minimum confidence level from OCR in order to process text from 0(the worst) to 99(the best).</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>The <strong>OpenCV-python</strong> library and <strong>OpenCV</strong> are both used for all of the image processing. The <strong>Hough Transform</strong>, which recognizes lines in an image, serves as the algorithm's foundation. It enables us to recognize the image's horizontal and vertical lines. The library really doesn't have much more to it because the intention was to keep it as straightforward as possible in order to avoid any potential complications that might arise from using other approaches.</p>
<p>View the project's documentation on <a target="_blank" href="https://github.com/xavctn/img2table">GitHub</a>.</p>
<p>Let's connect on <a target="_blank" href="https://www.twitter.com/Shittu_Olumide_">Twitter</a> and on <a target="_blank" href="https://www.linkedin.com/in/olumide-shittu">LinkedIn</a>. You can also subscribe to my <a target="_blank" href="https://www.youtube.com/channel/UCNhFxpk6hGt5uMCKXq0Jl8A">YouTube</a> channel.</p>
<p><strong>Happy Coding!</strong></p>
]]></content:encoded></item></channel></rss>