<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by George Dekermenjian on Medium]]></title>
        <description><![CDATA[Stories by George Dekermenjian on Medium]]></description>
        <link>https://medium.com/@ged1182?source=rss-f035bb41d1d2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BGyJMbDeQm1Kdwq91OgTBg@2x.jpeg</url>
            <title>Stories by George Dekermenjian on Medium</title>
            <link>https://medium.com/@ged1182?source=rss-f035bb41d1d2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:58:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ged1182/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Human-in-the-Loop AI Agents in Python + NextJS]]></title>
            <link>https://medium.com/@ged1182/building-human-in-the-loop-ai-agents-in-python-nextjs-3ab362d3fcc1?source=rss-f035bb41d1d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ab362d3fcc1</guid>
            <category><![CDATA[pydantic-ai]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[vercel-ai-sdk]]></category>
            <category><![CDATA[llm-agent]]></category>
            <dc:creator><![CDATA[George Dekermenjian]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 21:20:12 GMT</pubDate>
            <atom:updated>2026-01-11T21:20:12.150Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>llmBuilding Human-in-the-Loop AI Agents in Python + NextJS</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezDqAVFCuGx1P7X2B-PJQA.png" /></figure><p>Last month, I watched an AI agent delete the wrong files because I forgot to add a confirmation step.</p><p>The agent was supposed to clean up temporary files in a project directory. Instead, it interpreted “clean up” a bit too liberally and removed some configuration files I actually needed. Nothing catastrophic — just an hour of reconstruction work and a valuable lesson.</p><p>I needed human-in-the-loop: a way for the agent to pause before dangerous actions and ask, “Are you sure about this?” Conceptually simple. Implementation? That’s where things got interesting.</p><p>We spent a week building manual protocol handlers, wrestling with Server-Sent Events, and debugging message format mismatches. Our “simple approval flow” grew to 120 lines of boilerplate.</p><p>Then we found pydantic-ai’s `VercelAIAdapter` and replaced it all with a single function call.</p><p>Here’s the journey.</p><p><strong>What Exactly Is Human-in-the-Loop?</strong></p><p>Human-in-the-loop (HITL) means inserting a human decision point into an automated workflow. For AI agents, it typically means: “Before you execute this potentially dangerous action, ask me first.”</p><p>This matters more than ever because AI agents are getting powerful. They can browse the web, execute code, modify databases, send emails, and interact with external services. With great power comes the need for guardrails.</p><p>HITL serves three purposes:</p><p>1. <strong>Safety</strong> — Preventing unintended destructive actions before they happen</p><p>2. <strong>Compliance</strong>— Creating audit trails that show human approval for sensitive operations</p><p>3. <strong>Trust</strong> — Giving users confidence that the AI won’t take irreversible actions without permission</p><p>The technical challenge is coordinating three moving parts:</p><ul><li>A backend agent that can <em>*pause*</em> mid-execution and wait for a decision</li><li>A streaming connection that delivers real-time updates to the frontend</li><li>A frontend that intercepts specific tool calls and presents an approval UI</li></ul><p>All three need to speak the same protocol. That’s where we ran into trouble.</p><p><strong>Our First Attempt: The Hard Way</strong></p><p>Our stack was straightforward: pydantic-ai for the Python backend, Vercel AI SDK for the React frontend. Both are excellent tools. The challenge was getting them to talk to each other.</p><p>The Vercel AI SDK’s `useChat` hook expects responses in a specific format called the “Data Stream Protocol” — a series of Server-Sent Events with particular message types like `text-delta`, `tool-input-available`, and `finish-step`.</p><p>Pydantic-ai, being a Python library, doesn’t natively speak this protocol. So we built a translation layer.</p><p>Here’s what that looked like:</p><pre># The old way - 120+ lines of manual protocol handling<br>async def stream_response(messages):<br>    msg_id = f&quot;msg_{uuid.uuid4().hex[:12]}&quot;<br><br>    async with agent.run_stream(user_message) as result:<br>        async for text in result.stream_text(delta=True):<br>            # Manually construct SSE events<br>            yield f&#39;data: {json.dumps({&quot;type&quot;: &quot;text-start&quot;, &quot;id&quot;: msg_id})}\n\n&#39;<br>            yield f&#39;data: {json.dumps({&quot;type&quot;: &quot;text-delta&quot;, &quot;id&quot;: msg_id, &quot;delta&quot;: text})}\n\n&#39;<br><br>        # Handle tool calls manually<br>        final_result = await result.get_output()<br>        if isinstance(final_result, DeferredToolRequests):<br>            for tool_call in final_result.approvals:<br>                yield f&#39;data: {json.dumps({&quot;type&quot;: &quot;tool-input-start&quot;, ...})}\n\n&#39;<br>                yield f&#39;data: {json.dumps({&quot;type&quot;: &quot;tool-input-available&quot;, ...})}\n\n&#39;<br><br>    yield &#39;data: [DONE]\n\n&#39;</pre><p>This was just the streaming part. We also needed code to:</p><ul><li>Parse incoming Vercel AI SDK message formats</li><li>Convert them to pydantic-ai’s internal representation</li><li>Handle the reverse transformation for responses</li><li>Deal with error cases and edge conditions</li><li>Manage conversation state across requests</li></ul><p>The codebase grew. We debugged SSE formatting issues. We fixed JSON serialization problems. We discovered that we’d misread the protocol spec and our `step-start` events were in the wrong order.</p><p>After a week, we had a working HITL flow. It was also 120+ lines of protocol-handling code that we’d need to maintain forever.</p><p>There had to be a better way.</p><p><strong>The Discovery: VercelAIAdapter</strong></p><p>The better way was hiding in the pydantic-ai documentation all along.</p><p>While debugging yet another message format issue, I stumbled across a docs page I’d somehow missed: [ai.pydantic.dev/ui/vercel-ai/](https://ai.pydantic.dev/ui/vercel-ai/). The title was “Vercel AI Adapter” and the first example made me do a double-take.</p><p>Pydantic-ai includes a `VercelAIAdapter` class that was <strong>**ported directly from Vercel AI SDK’s TypeScript implementation**</strong> (specifically version 5.0.59). This means it natively understands the exact message format and protocol that the frontend expects.</p><p>Here’s the magic one-liner that replaced all our manual code:</p><pre>from pydantic_ai.ui.vercel_ai import VercelAIAdapter<br><br>@app.post(&quot;/api/chat&quot;)<br>async def chat(request: Request) -&gt; Response:<br>    return await VercelAIAdapter.dispatch_request(request, agent=agent)</pre><p>That’s the entire endpoint. This single function call:</p><ul><li>Parses incoming Vercel AI SDK requests</li><li>Converts messages to pydantic-ai’s internal format</li><li>Runs the agent with streaming enabled</li><li>Emits SSE events in the correct Data Stream Protocol format</li><li>Handles tool calls and deferred approval flows</li><li>Sends the `[DONE]` sentinel when the stream completes</li></ul><p>We deleted 120 lines of code, replaced them with this one-liner, and our HITL flow worked immediately. Same functionality, no maintenance burden.</p><p>The lesson hit hard: sometimes the best code is code you don’t have to write.</p><p><strong>The Complete Backend: 45 Lines That Do Everything</strong></p><pre>import os<br>from fastapi import FastAPI<br>from fastapi.middleware.cors import CORSMiddleware<br>from starlette.requests import Request<br>from starlette.responses import Response<br>from pydantic_ai import Agent, DeferredToolRequests<br>from pydantic_ai.ui.vercel_ai import VercelAIAdapter<br><br>os.environ[&quot;OPENAI_API_KEY&quot;] = &quot;your-key-here&quot;<br><br>agent = Agent(<br>    &quot;openai:gpt-4o-mini&quot;,<br>    system_prompt=&quot;You are a helpful assistant that can delete files when asked.&quot;,<br>    output_type=[str, DeferredToolRequests],<br>)<br><br>@agent.tool(requires_approval=True)<br>async def delete_file(ctx, path: str) -&gt; str:<br>    &quot;&quot;&quot;Delete a file at the given path. Requires user approval.&quot;&quot;&quot;<br>    return f&quot;File &#39;{path}&#39; has been deleted.&quot;<br><br>app = FastAPI()<br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;http://localhost:3000&quot;],<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)<br><br>@app.post(&quot;/api/chat&quot;)<br>async def chat(request: Request) -&gt; Response:<br>    return await VercelAIAdapter.dispatch_request(request, agent=agent)</pre><p>Two things require explanation:</p><p><strong>`output_type=[str, DeferredToolRequests]`</strong> — This tells pydantic-ai that an agent run might end in two ways: with a normal string response, or with deferred tool calls awaiting approval. Without this, the agent won’t know how to handle the “paused, waiting for approval” state.</p><p><strong>`@agent.tool(requires_approval=True)`</strong> — This decorator marks the tool as requiring human approval. When the agent tries to call this tool, instead of executing immediately, the run ends with a `DeferredToolRequests` object. The frontend receives this, shows an approval UI, and sends the decision back. Then the agent continues.</p><p>The flow looks like:</p><ol><li>User: “Delete the file /tmp/test.txt”</li><li>Agent decides to call `delete_file` with path=”/tmp/test.txt”</li><li>Agent run ends with `DeferredToolRequests` (because `requires_approval=True`)</li><li>Frontend receives the tool call, shows “Approve / Deny” buttons</li><li>User clicks “Approve”</li><li>Frontend sends approval back, agent continues</li><li>Agent executes the tool and responds: “I’ve deleted the file.”</li></ol><p><strong>Frontend Integration: The Gotcha That Cost Us Hours</strong></p><p>The frontend uses Vercel AI SDK’s `useChat` hook. Here’s the setup:</p><pre>const { messages, sendMessage, addToolOutput, status } = useChat({<br>  api: &quot;/api/chat&quot;,<br>  onToolCall: async ({ toolCall }) =&gt; {<br>    // Intercept tools that need approval<br>    setPendingApprovals((prev) =&gt; [...prev, {<br>      id: toolCall.toolCallId,<br>      toolName: toolCall.toolName,<br>      args: toolCall.args,<br>    }]);<br>    return undefined; // Don&#39;t auto-execute<br>  },<br>});</pre><p>The `onToolCall` callback fires whenever the agent calls any tool. By returning `undefined`, we tell the SDK not to auto-execute the tool. Instead, we add it to our pending approvals state and render an approval UI.</p><p>Here’s where we made a critical mistake that cost us hours of debugging.</p><p>When the user clicks “Approve,” we initially tried this:</p><pre>// WRONG - causes &quot;tool_calls must be followed by tool messages&quot; error<br>sendMessage({ text: `[APPROVED] Tool call ${toolCallId} approved` });</pre><p>This breaks the conversation. The LLM expects tool results in a very specific format within the message history. When you call a tool, the next message must be the tool’s result, not a user text message. Sending text like “[APPROVED]” confuses the model and causes protocol errors.</p><p>The correct approach uses `addToolOutput`:</p><pre>const handleApprove = async (toolCallId: string) =&gt; {<br>  await addToolOutput({<br>    toolCallId,<br>    output: { approved: true },<br>  });<br>  sendMessage(); // Continue the conversation<br>};<br><br>const handleDeny = async (toolCallId: string) =&gt; {<br>  await addToolOutput({<br>    toolCallId,<br>    output: { approved: false, reason: &quot;User denied the action&quot; },<br>  });<br>  sendMessage();<br>};</pre><p>The `addToolOutput` function properly formats the tool result in the conversation history, maintaining the expected message structure. Then `sendMessage()` continues the agent run.</p><p>This distinction between “sending a message” and “providing a tool result” is subtle but essential. The SDK provides both mechanisms for a reason.</p><p><strong>The “Dumb Proxy” Surprise</strong></p><p>One pleasant discovery: the Next.js API route doesn’t need to do anything clever.</p><pre>export async function POST(req: Request) {<br>  const body = await req.text();<br>  const response = await fetch(&quot;http://localhost:8000/api/chat&quot;, {<br>    method: &quot;POST&quot;,<br>    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    body,<br>  });<br>  return new Response(response.body, {<br>    headers: {<br>      &quot;Content-Type&quot;: &quot;text/event-stream&quot;,<br>      &quot;Cache-Control&quot;: &quot;no-cache&quot;,<br>      &quot;Connection&quot;: &quot;keep-alive&quot;,<br>    },<br>  });<br>}</pre><p>No transformations. No parsing. No protocol handling. Just forward the request body to the Python backend and stream the response back.</p><p>This works because `VercelAIAdapter` handles all the protocol details. The proxy’s job is simply to bridge the network gap between the browser and the Python server. That’s clean separation of concerns.</p><p><strong>Lessons Learned</strong></p><p>After a week of doing it the hard way and an afternoon of doing it the right way, here’s what we took away:</p><p><strong>Read the docs before building.</strong> Pydantic-ai’s documentation explicitly shows the one-liner solution on its own dedicated page. We spent days on manual implementations before finding it. The cure for “I’ll figure it out myself” is sometimes just… reading.</p><p><strong>Trust the adapter.</strong> We kept trying to “help” the `VercelAIAdapter` by handling edge cases ourselves. It didn’t need our help. It handles message format conversion, SSE streaming, tool call serialization, error responses, and the `[DONE]` sentinel. Let it do its job.</p><p><strong>Tool results are not messages.</strong> Using `addToolOutput()` instead of `sendMessage()` for tool responses is critical. LLMs have specific expectations about conversation structure, and violating those expectations causes confusing errors.</p><p><strong>Simple architectures win.</strong> Our final system has three components: a 45-line backend, a 21-line proxy, and a React component with an approval modal. No message buses, no complex state machines, no custom protocols. Sometimes boring is beautiful.</p><p><strong>Try It Yourself</strong></p><p>Human-in-the-loop doesn’t have to be complicated. With the right tools, it’s just a decorator on the backend and a callback on the frontend.</p><p>The stack:</p><ul><li><strong>Backend</strong>: FastAPI + pydantic-ai with `VercelAIAdapter`</li><li><strong>Frontend:</strong> Next.js + Vercel AI SDK with `useChat`</li><li><strong>The key</strong>: `requires_approval=True` and `addToolOutput()`</li></ul><p>Setup is straightforward:</p><pre># Add your OpenAI key to .env.local<br>make install  # Install dependencies<br>make dev      # Run both services</pre><p>Then open localhost:3000, ask the agent to delete a file, and watch the approval flow in action.</p><p><strong>Resources</strong></p><ul><li><a href="https://ai.pydantic.dev/ui/vercel-ai/">Pydantic AI Vercel AI Adapter Docs</a></li><li><a href="https://ai.pydantic.dev/deferred-tools/">Pydantic AI Deferred Tools</a></li><li><a href="https://ai-sdk.dev/docs/reference/ai-sdk-ui/use-chat">Vercel AI SDK useChat Reference</a></li><li><a href="https://ai-sdk.dev/cookbook/next/human-in-the-loop">Vercel AI SDK Human-in-the-Loop Cookbook</a></li><li><a href="https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol">Vercel AI Data Stream Protocol</a></li></ul><p><em>Have you built something similar, or run into your own protocol translation nightmares? I’d love to hear about it in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ab362d3fcc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Probability Distributions Using SciPy]]></title>
            <link>https://levelup.gitconnected.com/probability-distributions-using-scipy-58fdab53d7ac?source=rss-f035bb41d1d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/58fdab53d7ac</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[George Dekermenjian]]></dc:creator>
            <pubDate>Wed, 12 Feb 2020 17:35:03 GMT</pubDate>
            <atom:updated>2020-03-20T14:39:54.763Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post I’m going to show you how to work with probability distributions using SciPy. We will start by importing the relevant packages.</p><pre>import scipy.stats as stats<br>import numpy as np<br>%matplotlib inline<br>import matplotlib.pyplot as plt</pre><p>The stats module of sciPy offers many distributions so you are bound to find what you’re looking for. They are organized into three categories: Continuous, Discrete and Multivariate. Here is the <a href="https://docs.scipy.org/doc/scipy/reference/stats.html">complete list</a>. In this blog post, we will focus on (two) continuous distribution and (two) discrete distributions.</p><h4>Continuous Distributions</h4><p>We will start with the arguably the most famous distribution: Normal (Gaussian) distribution.</p><p>We start with creating an instance of the stats.norm class and initialize this object to have mean 100 and standard deviation 15:</p><p>normal=stats.norm(loc=100, scale=15)</p><p>Next, we can generate a random sample by calling the method .rvs(size=10) on this object to generate 10 random numbers.</p><pre>normal.rvs(size=10,random_state=143)<br>&gt;&gt; array([ 87.50268488, 118.56536514,  62.86403442,  84.42053641,<br>       114.91967271, 102.67337385,  92.6638058 ,  93.36867073,<br>        96.22587266,  92.97029531])</pre><p>random_state=143 is just so that the results are reproducible. If you include this, this result will always be the same. If you want to repeat and get different results, just omit this so that your code reads normal.rvs(size=10).</p><p>That was easy! Now lest generate 1000 random numbers from this distribution and make a histogram.</p><pre>normal_sample = normal.rvs(size=1000,random_state=123)<br>plt.hist(normal_sample,density=True,label=&quot;Sample&quot;)<br>plt.title(&quot;Normal Distribution&quot;)<br>plt.ylabel(&quot;Density&quot;)<br>plt.legend()<br>plt.show()</pre><p>Here is the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*A6SPXvyfXElqvHU81uYz6Q.png" /><figcaption>A histogram of 1000 random numbers generate from a normal distribution.</figcaption></figure><p>Now let’s focus on the PDF, the probability density function. Using the same (distribution) object we created, we can access the PDF via the method .pdf . The first argument can be a scalar of an array of values.</p><pre>print(normal.pdf(120))<br>print(normal.pdf([120,130,140]))<br>&gt;&gt; 0.010934004978399577<br>&gt;&gt; [0.010934   0.0035994  0.00075973]</pre><p>Next, let’s see how to plot the PDF. First create some values for the horizontal axis. We will use np.linspace(start,stop,num) to generate equally num spaced numbers between start and end. The relevant values for our case seem to be between 50 and 150: t.np.linspace(50,150,100). These will serve as the horizontal (x) values for the plot.</p><p>To get the vertical (y) values, we can compute the PDF on these values: normal.pdf(t). Below we have the code that puts all this together and gives us a plot of the normal PDF.</p><pre>t = np.linspace(50,150,100)<br>plt.plot(t,normal.pdf(t),label=&quot;PDF&quot;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*TlmOzs9lOmZbTfJ93fvwvA.png" /><figcaption>A plot of a normal PDF</figcaption></figure><p>Finally, we can overlay this on top of the histogram to see how well the random number generator did!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*YnH42aVnUIYOPgjhqYOJWg.png" /><figcaption>Histogram of a sample from the normal distribution and the corresponding plot of the PDF</figcaption></figure><p>That looks pretty good!</p><p>Another popular distribution is the Beta distribution. This one is also a continuous distribution and is used to model random variables between 0 and 1. So for instance, if the random variable is the probability of success, then this might be a good distribution to use. The Beta distribution takes two parameters, a and b. Therefore, to create a beta distribution object in scipy, we put beta=stats.beta(a=2,b=5). The code below generates a random sample from this distribution.</p><pre>beta=stats.beta(a=2,b=5)<br>beta.rvs(size=5,random_state=133)<br>&gt;&gt;array([0.13580999, 0.55628319, 0.39061464, 0.51549706, 0.3439727 ])</pre><p>As before, let’s get 1000 numbers from this distribution, make a histogram and overlay its PDF.</p><pre>beta_sample=beta.rvs(size=1000,random_state=133)<br>t=np.linspace(0,1,100)<br>plt.hist(beta_sample,density=True,label=&quot;Sample&quot;)<br>plt.plot(t,beta.pdf(t),label=&quot;PDF&quot;)<br>plt.legend()<br>plt.ylabel(&quot;Density&quot;)<br>plt.title(&quot;Beta Distribution&quot;)<br>plt.savefig(&quot;beta_hist_pdf.png&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*Mv_7K7ZuHAEfEDqfOfjikw.png" /><figcaption>Histogram of a sample from the beta distribution and the corresponding plot of the PDF</figcaption></figure><h4>Discrete Distributions</h4><p>Sometimes, we need to work with discrete distributions. We will demonstrate two: Binomial and Poisson. The binomial distribution is used to model the number of successes with repeated trial where each trial can either result in “success” or “failure”, the probability of success stays the same from one trial to another, the trials are independent of one another and finally the number of trials is fixed in advanced. A typical example is a fixed number of coin tosses. Here is how we get binomial distribution objects in scipy and generate some random numbers:</p><pre>binomial=stats.binom(n=10,p=0.4)<br>binomial.rvs(size=10,random_state=143)<br>&gt;&gt; array([5, 3, 4, 4, 4, 6, 1, 1, 3, 2])</pre><p>Remember the a discrete distribution doesn’t have a PDF. The corresponding function is a Probability Mass Function or PMF. In scipy we can access this function for a distribution objects as follows: binomial.pmf . Just like for the PDF, we can compute the PMF of a single number or for a list of numbers.</p><pre>binomial.pmf(2)<br>binomial.pmf([2,3,4])<br>&gt;&gt;&gt; 0.12093235199999994<br>&gt;&gt;&gt; [0.12093235 0.21499085 0.25082266]</pre><p>Next, let’s plot the PMF. Since it is discrete, we will use plt.scatter instead of plt.plot . Also, the PMF is zero except on the support of this distribution which happens to be 0, 1, 2, …, 10. Instead of np.linspace which is used to generate numbers from a continuous range, we will use np.arange(start,stop,step=1) to generate values to follow a discrete set. For us, this will be</p><pre>t=np.arange(0,11)<br>t<br>&gt;&gt; array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10])</pre><p>Notice how we have to put np.arange(0,11) instead of np.arange(0,10) as it doesn’t return the last number. Now, using these values, we can plot the PMF of our binomial distribution.</p><pre>plt.scatter(t,binomial.pmf(t),label=&quot;PMF&quot;,color=&quot;Orange&quot;)<br>plt.title(&quot;Binomial Distribution&quot;)<br>plt.ylabel(&quot;Density&quot;)<br>plt.legend()<br>plt.xticks(t)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*AJDYPUFLPhdnpwYvxXsXqw.png" /><figcaption>A plot of the PMF of a Binomial distribution.</figcaption></figure><p>Now we will generate 1000 random numbers from this distribution binomial_sample=binomial.rvs(size=1000,random_state=143)and create a histogram. Since we are dealing with discrete numbers, we have to add some options to control how the histogram is calculated:</p><ul><li>bins=11 to make sure we have 11 bins, one for each number 0,1,…,10</li><li>range=(0,11) to make sure the respective classes are [0,1), [1,2), …, [10,11)</li><li>align=&#39;left&#39; to make sure that the bar is aligned with the PMF (you’ll see why later when we overlay everything.</li><li>rwidth=0.75 so the bars of the histogram are 75% of the class width. This will make sure the bars don’t touch to communicate that we are working with discrete data.</li><li>alpha=0.75 so that the bars are semi-transparent to allow the overlay to look nice.</li></ul><p>Here is the full code.</p><pre>binomial_sample=binomial.rvs(size=1000,random_state=143)<br>plt.hist(binomial_sample,bins=11,range=(0,11),density=True,align=&#39;left&#39;,rwidth=0.75,label=&quot;Sample&quot;,alpha=0.75)<br>plt.title(&quot;Binomial Distribution&quot;)<br>plt.ylabel(&quot;Density&quot;)<br>plt.legend()<br>plt.xticks(t)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*puZiRgZgoqqbc2Rc6QVuZw.png" /><figcaption>A histogram of 1000 random numbers from the binomial distribution</figcaption></figure><p>Finally, here is the code that puts the PMF and the histogram together.</p><pre>binomial_sample=binomial.rvs(size=1000,random_state=143)<br>t = np.arange(0,11)<br>plt.hist(binomial_sample,bins=11,range=(0,11),density=True,align=&#39;left&#39;,rwidth=0.75,label=&quot;Sample&quot;,alpha=0.75)<br>plt.scatter(t,binomial.pmf(t),label=&quot;PMF&quot;,color=&quot;Orange&quot;)<br>plt.title(&quot;Binomial Distribution&quot;)<br>plt.ylabel(&quot;Density&quot;)<br>plt.legend()<br>plt.xticks(t)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*UQnU7hMztqQNADBOwE14pA.png" /><figcaption>Histogram of a random sample from the Binomial distribution and a plot of the associated PMF</figcaption></figure><p>The Poisson distribution is very commonly used in practice as well. It is used to model the number of events (say car accidents) occurs in a fixed duration of time (or space). The values this random variable can take are 0,1,2,… (it goes on forever). In scipy we can set up a Poisson distribution object by stats.poisson(mu=2) . Generating random numbers is just like the other distributions:</p><pre>poisson.rvs(size=10,random_state=143)<br>&gt;&gt; array([2, 3, 0, 1, 1, 0, 2, 2, 0, 1])</pre><p>Based on everything we have done above, we can generate 1000 random numbers from this distribution, plot the histogram, and the PMF together on the same plot. Try to do this on your own before looking at the code below. To encourage you, I will first show the end result and then the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*EzZVYV43iARfACHNdIPhRQ.png" /><figcaption>Histogram of a random sample from the Poisson distribution and a plot of the associated PMF</figcaption></figure><pre>poisson_sample = poisson.rvs(size=1000,random_state=143)<br>end = np.max(poisson_sample)+1<br>t=np.arange(0,end)<br>plt.hist(poisson_sample, bins=end,range=(0,end), density=True,align=&#39;left&#39;, rwidth=0.75,label=&quot;Sample&quot;, alpha=0.75)<br>plt.scatter(t,poisson.pmf(t),label=&quot;PMF&quot;,color=&quot;Orange&quot;)<br>plt.title(&quot;Poisson Distribution&quot;)<br>plt.ylabel(&quot;Density&quot;)<br>plt.legend()<br>plt.show()</pre><p>The one tricky part here is that since the support of a Poisson random variable has no end, we have to decide where to stop computing. For us, this will be the largest value of our sample data; therefore, we end=np.max(poisson_sample)+1 .</p><p>Here is a link to a <a href="https://gist.github.com/ged1182/81b39bf80e0a958ef53e5a6b4934dd8a">gist </a>containing all the code from this post.</p><p>I hope you enjoyed this post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58fdab53d7ac" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/probability-distributions-using-scipy-58fdab53d7ac">Probability Distributions Using SciPy</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-Means Step-by-Step]]></title>
            <link>https://levelup.gitconnected.com/k-means-manual-implementation-9f6fd9375b86?source=rss-f035bb41d1d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f6fd9375b86</guid>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <dc:creator><![CDATA[George Dekermenjian]]></dc:creator>
            <pubDate>Thu, 24 Jan 2019 17:25:44 GMT</pubDate>
            <atom:updated>2020-03-26T14:13:24.924Z</atom:updated>
            <content:encoded><![CDATA[<p>Clustering algorithms help group data into groups or clusters that are similar. There are a number of different approaches to clustering. In this post, we look at one of the most popular clustering algorithms: K-Means. The goal of this algorithm is to identify each cluster by its centroid. The motivation of what follows is to understand how the K-Means algorithm is implemented. The code contained is not meant to be used for production but rather to understand how the algorithm learns the clusters.</p><p>We start by importing the relevant libraries we will use.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.cluster import KMeans</pre><p>Every algorithm requires some sort of initialization. It turns out that K-Means is highly sensitive to the initialization of the centroids. There are a number of ways to initialize the centroids 𝜇_k. We implement what is called in the literature as <em>K-Means++</em> initialization. We initialize the first centroid 𝜇_1 by choosing a data point at random:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*4sUs2J0Rn9gql4yGaKBZjQ.png" /></figure><p>For each subsequent centroid, we want to choose a data point that is, with high probability, far away from the previous centroid. Suppose the first k-1 centroids have been chosen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*dx6_WKe8RmuH19YGu9ZKig.png" /></figure><p>We want to choose the next one so that it is far from the previous one with high probability. Each time we choose a centroid, we remove the respective data point from the original data set.</p><p>Consequently, we develop a distribution 𝜈 over the set {1,2,…,N-k}(where the data set has been re-indexed). The distribution is such that the probability of choosing the ith data point is proportional to the square distance between itself and the last chosen centroid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*OYR-6od-vjDUkmqlIGmttg.png" /></figure><pre>def initialize_centers(X,K):<br>    &#39;&#39;&#39;Implements K-Means++ initialization given the data matrix X and the number of cluster K<br>    Input:<br>        X - shape (N, D) - data matrix containing N examples of D-dimensional data<br>        K - a positive integer - the number of clusters<br>    <br>    Output:<br>        mu - shape(K,D) - K centroids each of which is a D-dimensional vector<br>    &#39;&#39;&#39;<br>    <br>    N,D = X.shape #find out the number of example and the dimesion of the data<br>    mu = np.zeros((K,D)) #initialize the variable that will store the K (D-dimensional) centroids<br>    idx = np.random.randint(0,X.shape[0]) #choose an index at random<br>    mu[0] = X[idx] #assign the respective data point as the first centroid<br>    X = np.delete(X,idx,axis=0) #remove the chosen data point from the data set.<br>    for k in range(1,K): #for each of the subsequent clusters<br>        #compute the square-norm of the different between each data point and the previous centroid<br>        nu = np.linalg.norm(X-mu[k-1],axis=1)**2 <br>        #divide these square-norms by their sum to get a distribution<br>        nu = nu / np.sum(nu)<br>        #choose an index at random from the distribution<br>        idx = np.random.choice(np.array(range(X.shape[0])),1,replace=False,p=nu)<br>        #assign the centroid of the k^th cluster as the respective data point<br>        mu[k] = X[idx]<br>        #remove the selected data point from the data matrix<br>        X = np.delete(X,idx,axis=0)<br>    #return the centroids<br>    return mu</pre><p>As you probably know, many machine learning algorithms work by optimizing some measure of ‘goodness’ (maximize) or ‘badness’ (minimize). In the K-Means algorithm, we define a loss function (‘badness’) that we want to minimize. What this function computes the ‘badness’ within each cluster. It does this by computing the square-distance between each data point assigned to a cluster and the centroid of that cluster. The distortion loss is then the sum of all these square distances. So, if a data point is not close enough to the centroid, it will contribute a large value to the loss.</p><pre>def distorsion_loss(X,mu, Z):<br>    &#39;&#39;&#39;Given the data matrix X, the current set of centroids mu<br>    and the assignment-matrix Z (also called a latent variable),<br>    computes the distrortion-loss<br>    <br>    Input:<br>        X - shape (N, D) - data matrix containing N examples of D-dimensional data<br>        mu - shape(K,D) - K centroids each of which is a D-dimensional vector<br>        Z - shape (N, K) - each element in the row contains exactly one 1 and the rest zero<br>            indicating the assignment of the respective data point to the cluster.<br>            For example Z_{53}=1 means that the 5th data point belongs to cluster 3 (4th cluster)<br>    &#39;&#39;&#39;<br>    K = mu.shape[0] #get the number of cluster by looking at how many centroids there are<br>    loss = 0 #initialize the loss to zero<br>    for k in range(K): #for each cluster<br>        #get the data points assigned to that cluster<br>        X_k = X[Z[:,k]==1]<br>        #compute the square-dstiance between each of these data points and the centroid<br>        D=np.linalg.norm(X_k-mu[k],axis = 1)**2<br>        #accumulate the loss<br>        loss += np.sum(D)<br>    #return<br>    return loss</pre><p>We are now ready train the K-Means algorithm. The training will proceed as follows:</p><ol><li>Initiliaze the centroids: mu_init = initialize_centers(X,K)</li><li>Update the assignment matrix. Each data point is assigned to the closest centroid.</li><li>Update the centroids. The new centroids are the average of the data points within their respective clusters.</li><li>Record the distorion_loss. If the change between the current loss and the previous loss is less than the tolerance or we have reached the maximum number of iterations, stop otherwise go to step 2.</li></ol><pre>def train_kmeans(X,K,mu_init,max_iter=10,tol=1e-4):<br>    &#39;&#39;&#39;Train the K-Means algorithm using the data matrix X, the number of clusters K,<br>    and the initial centroids mu_init<br>    <br>    Input:<br>        X - shape (N, D) - data matrix containing N examples of D-dimensional data<br>        K - a positive integer - the number of clusters<br>        mu_init - shape(K,D) - initial K centroids each of which is a D-dimensional vector<br>        max_iter - positive integer (default 10) the maximum number of iterations<br>        tol - positive number (default 1e-4) the tolerance which determines that<br>                the distorion_loss has converged.<br>    &#39;&#39;&#39;<br>    N = X.shape[0] #read in the number of data points<br>    mu = mu_init #initialize mu with mu_init<br>    loss_trace = [] #initalize an array to keep track of the losses<br>    mu_trace = [] #initialize an array to keep track of the centroids<br>    Z_trace = [] #initialize an array to keep track of the assignment matrices<br>    for it in range(max_iter): #for each iteration<br>        #Update cluster indicators<br>        Z = np.zeros((N,K)) #initialize the assignment matrix<br>        for i in range(N): #for each data point<br>            #compute the square distance between the datapoint and all the centroids<br>            d = np.linalg.norm(X[i]-mu,axis=1)**2<br>            #select the index of the smallest distance (corresponding to the closest centroid)<br>            j = np.argmin(d)<br>            #update the assingment matrix by assigning the i^th data point to the j^th cluster<br>            Z[i,j]=1<br><br>        #Update centroids<br>        N_k = np.sum(Z,axis=0) #count the number of data points in each cluster<br>        for j in range(K): #for each cluster<br>            #sum up the data points<br>            mu[j] = np.sum(X[Z[:,j]==1],axis=0)<br>            if N_k[j] &gt; 0: #if there is at least one data point in the cluster<br>                mu[j] = mu[j] / N_k[j] #divide to get the average, the centroid<br>        loss_ = distorsion_loss(X,mu,Z) #compute the loss<br>        loss_trace.append(loss_) #record the loss<br>        mu_trace.append(mu) #record the current value of mu<br>        Z_trace.append(Z) #record the current assignment matrix<br>        if len(loss_trace) &gt; 1: #if we have at least 2 iterations<br>            if abs(loss_trace[-2]-loss_trace[-1]) &lt; tol: #check convergence<br>                return mu, Z, loss_trace, mu_trace, Z_trace #return if loss has converged<br>    #return<br>    return mu, Z, loss_trace, mu_trace, Z_trace</pre><p>There we have it. The K-Means algorithm. Let’s generate some toy data to see how the K-Means does.</p><p>We will generate 3 clusters centered at the following points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*WCaPxwqezvBnpIgm2Y8N_A.png" /></figure><p>All data points around each of these centers will be distributed according to the multivariate normal distribution with unit (isotropic) covariance matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/1*KO131po4Wb16v4q7NmediA.png" /></figure><pre>#centroids<br>mu_1_actual = np.array([2,2])<br>mu_2_actual = np.array([-2,-2])<br>mu_3_actual = np.array([10,0])<br>#covariance matrix<br>sigma = np.eye(2)<br><br>#Clusters<br>X1 = np.random.multivariate_normal(mu_1_actual,sigma,100)<br>X2 = np.random.multivariate_normal(mu_2_actual,sigma,100)<br>X3 = np.random.multivariate_normal(mu_3_actual,sigma,100)<br><br>#Data matrix:<br>X = np.concatenate([X1,X2,X3],axis=0)</pre><pre>#Visualize the data and visualize the actual clusters.<br><br>fig = plt.figure(figsize=(20,5))<br>plt.subplot(121)<br>plt.scatter(X[:,0],X[:,1])<br>plt.subplot(122)<br>plt.scatter(X1[:,0],X1[:,1],c=&#39;r&#39;)<br>plt.scatter(X2[:,0],X2[:,1],c=&#39;g&#39;)<br>plt.scatter(X3[:,0],X3[:,1],c=&#39;b&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*MJ0Txx9D_d5IfG1ZRB_P_A.png" /></figure><pre>mu_init = initialize_centers(X,3)<br>mu,Z,loss_trace, mu_trace, Z_trace =train_kmeans(X,3,mu_init,max_iter=300,tol=1e-4)</pre><pre>fig = plt.figure(figsize=(20,5))<br>plt.subplot(121)<br>plt.scatter((X[Z[:,0]==1])[:,0],(X[Z[:,0]==1])[:,1],color=&#39;r&#39;)<br>plt.scatter((X[Z[:,1]==1])[:,0],(X[Z[:,1]==1])[:,1],color=&#39;g&#39;)<br>plt.scatter((X[Z[:,2]==1])[:,0],(X[Z[:,2]==1])[:,1],color=&#39;b&#39;)<br>plt.scatter(mu[:,0],mu[:,1],color=&#39;black&#39;,marker=&#39;o&#39;,s=200,alpha=0.75)<br>plt.title(&#39;K-Means with K=3&#39;)<br>plt.xlabel(&#39;x_1&#39;)<br>plt.ylabel(&#39;x_2&#39;)<br>plt.subplot(122)<br>plt.plot(range(len(loss_trace)),loss_trace)<br>plt.title(&#39;Distorion Loss&#39;)<br>plt.xlabel(&#39;Iteration&#39;)<br>plt.ylabel(&#39;Loss&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*eRSPKQMr0hgya4ud2rARrQ.png" /></figure><p>Not bad. It looks like the algorithm converged a few iterations.</p><pre>fig = plt.figure(figsize=(20,25))<br>for i in range(len(loss_trace)):<br>    plt.subplot(521+i)<br>    Z_i = Z_trace[i]<br>    mu_i = mu_trace[i]<br>    plt.scatter((X[Z_i[:,0]==1])[:,0],(X[Z_i[:,0]==1])[:,1],color=&#39;r&#39;)<br>    plt.scatter((X[Z_i[:,1]==1])[:,0],(X[Z_i[:,1]==1])[:,1],color=&#39;g&#39;)<br>    plt.scatter((X[Z_i[:,2]==1])[:,0],(X[Z_i[:,2]==1])[:,1],color=&#39;b&#39;)<br>    plt.scatter(mu_i[:,0],mu_i[:,1],color=&#39;black&#39;,marker=&#39;o&#39;,s=200, alpha=0.75)<br>    plt.title(&#39;Iteration:&#39; + str(i+1) +&#39;\nLoss:&#39;+str(round(100*loss_trace[i])/100))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*TwCdmtxDGrRNBAYurUP-XA.png" /></figure><p>Now things may not be as nice as this. K-Means is very sensitive to initialization. As a matter of fact if we run this again, with different initial centroides, it may not look this pretty.</p><pre>mu_init2 = initialize_centers(X,3)<br>mu2,Z2,loss_trace2, mu_trace2, Z_trace2 =train_kmeans(X,3,mu_init2,max_iter=300,tol=1e-4)</pre><pre>fig = plt.figure(figsize=(20,5))<br>plt.subplot(121)<br>plt.scatter((X[Z2[:,0]==1])[:,0],(X[Z2[:,0]==1])[:,1],color=&#39;r&#39;)<br>plt.scatter((X[Z2[:,1]==1])[:,0],(X[Z2[:,1]==1])[:,1],color=&#39;g&#39;)<br>plt.scatter((X[Z2[:,2]==1])[:,0],(X[Z2[:,2]==1])[:,1],color=&#39;b&#39;)<br>plt.scatter(mu2[:,0],mu2[:,1],color=&#39;black&#39;,marker=&#39;o&#39;,s=200,alpha=0.75)<br>plt.title(&#39;K-Means with K=3&#39;)<br>plt.xlabel(&#39;x_1&#39;)<br>plt.ylabel(&#39;x_2&#39;)<br>plt.subplot(122)<br>plt.plot(range(len(loss_trace2)),loss_trace2)<br>plt.title(&#39;Distorion Loss&#39;)<br>plt.xlabel(&#39;Iteration&#39;)<br>plt.ylabel(&#39;Loss&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*cfvl4M34X5O8V4HNsrGI2A.png" /></figure><p>Notice how the algorithm converged to a higher loss value and the clusters are not what we intended them to be. Now in practice, we don’t know how the clusters should look, that’s why we run this algorithm in the first place. So how do we overcome this obstacle. What is actually happening is that the distortion_loss function has many local minima. Furthermore, the K-Means algorithm isn’t guaranteed to converge to the global minimum. Therefore, in practice, we would run K-Means several times with different initial values and choose the result that has the lowest convergence of the loss. As you can see above, the loss converged at around 587 whereas in the the second run it converged around 2200.</p><h4>K-Means Using Sci-Kit Learn</h4><p>For comparison, let’s use the SciKit-Learn package, which is the gold standard in machine learning, to run K-Means algorithm. This actually does what we need. It will run K-Means several times, which different initial values each time and then choose the best result.</p><pre>kmeans = KMeans(n_clusters=3, random_state=0,verbose=0).fit(X)</pre><pre>clusters=kmeans.predict(X)<br>cluster_centers = kmeans.cluster_centers_<br>Z_sklearn = np.zeros((X.shape[0],3))<br>for i in range(X.shape[0]):<br>    Z_sklearn[i,clusters[i]]=1</pre><pre>plt.scatter((X[Z_sklearn[:,0]==1])[:,0],(X[Z_sklearn[:,0]==1])[:,1],color=&#39;r&#39;)<br>plt.scatter((X[Z_sklearn[:,1]==1])[:,0],(X[Z_sklearn[:,1]==1])[:,1],color=&#39;g&#39;)<br>plt.scatter((X[Z_sklearn[:,2]==1])[:,0],(X[Z_sklearn[:,2]==1])[:,1],color=&#39;b&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*dUWUoB6gS8hKskwWCmObFQ.png" /></figure><p>By the way, there is a much easier way to color the clusters..</p><pre>plt.scatter(X[:,0],X[:,1],c=clusters)<br>plt.scatter(cluster_centers[:,0],cluster_centers[:,1],color=&#39;black&#39;,marker=&#39;o&#39;,s=200,alpha=0.75)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*l6btJA3BKBSSvOHDFqNvkg.png" /></figure><h4>Comparing the Results…</h4><pre>#converged loss from sklearn<br>distorsion_loss(X,cluster_centers,Z_sklearn)</pre><pre>586.9973311742276</pre><pre>#converged loss from our good result</pre><pre>distorsion_loss(X,mu,Z)</pre><pre>586.9973311742275</pre><pre>#difference between our centroids and the ones found by sklearn<br>np.linalg.norm(np.sort(mu,axis=0)-np.sort(cluster_centers,axis=0),axis=1)</pre><pre>array([1.25607397e-15, 5.20417043e-18, 1.83102672e-15])</pre><p>All almost zero.</p><p>I hope this post sheds some light on K-Means, one of the most popular clustering algorithms used in unsupervised learning today. In my next post, we will consider a soft clustering algorithm using Gaussian Mixtures.</p><p>Here is the full <a href="https://gist.github.com/ged1182/ffbaf92ed595af3c4e3cd57792cfa517">jupyter notebook.</a></p><p>If you enjoyed this post please take a moment and give me some claps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f6fd9375b86" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/k-means-manual-implementation-9f6fd9375b86">K-Means Step-by-Step</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>