<?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 Rahuul Siingh on Medium]]></title>
        <description><![CDATA[Stories by Rahuul Siingh on Medium]]></description>
        <link>https://medium.com/@rahul.singh.ds20?source=rss-f2193cb564b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nx1PFevCKaZbyKhvPXOvdg.jpeg</url>
            <title>Stories by Rahuul Siingh on Medium</title>
            <link>https://medium.com/@rahul.singh.ds20?source=rss-f2193cb564b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:33:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahul.singh.ds20/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[Claude Cowork Desktop Architecture]]></title>
            <link>https://medium.com/@rahul.singh.ds20/claude-cowork-desktop-architecture-1041a8ebcfa6?source=rss-f2193cb564b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1041a8ebcfa6</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[edge-ai]]></category>
            <category><![CDATA[claude-cowork]]></category>
            <dc:creator><![CDATA[Rahuul Siingh]]></dc:creator>
            <pubDate>Sun, 31 May 2026 08:29:10 GMT</pubDate>
            <atom:updated>2026-05-31T08:29:10.305Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*adSmpKCKWfrQbYR_Zz0j2g.png" /></figure><p><em>A Technical Reference &amp; Explainer</em></p><h3>1. Overview</h3><p>Claude Cowork is an agentic task-execution mode inside the Claude Desktop app. Rather than answering individual prompts, Claude plans and completes multi-step work on the user’s behalf, operating on a shared folder where it can read, edit, and create files to produce finished deliverables. It brings the same agentic foundations that power Claude Code into a desktop interface aimed at knowledge work that does not involve writing code.</p><p>The defining architectural decision is that Cowork does not treat “running on your machine” as a single trusted space. It splits work across two execution environments on the device, separated by privilege: a trusted native agent loop that touches your real disk and network, and an isolated virtual machine that contains anything risky. A permission system sits over the native loop, and admin controls let organizations narrow the whole thing on managed devices.</p><h3>Core design principles</h3><p>• <strong>Outcome-oriented execution-</strong> You describe a desired result; Claude determines the steps to reach it, rather than responding prompt-by-prompt.</p><p>• <strong>Persistent task planning-</strong> Once a task starts, Claude maintains context throughout, creating a plan and breaking work into subtasks without losing state.</p><p>• <strong>Reduced back-and-forth-</strong> Claude progresses independently across safe steps, surfacing decisions only where they matter.</p><p>• <strong>Transparency and steering-</strong> Claude surfaces its plan and progress while working, so you can monitor, clarify, or course-correct before significant actions.</p><h3>2. Architecture at a Glance</h3><p>Everything runs locally inside the Claude Desktop app, not on Anthropic’s servers. Within the device, work is divided as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*lxtZPbLP7pF1ZygN" /></figure><p><strong>Member device: </strong>Outer trust boundary. Hosts the Claude Desktop app on macOS or Windows; all execution happens here.</p><p><strong>Permission system: </strong>Application-layer gate over the native loop. Enforces connected-folder rules and organization network egress settings.</p><p><strong>Native agent loop: </strong>Trusted environment running on the host OS: reasoning, conversation, file reads/writes, web fetches, and local plugin MCP servers.</p><p><strong>Isolated VM: </strong>Untrusted, contained environment: shell commands and any code Claude writes run in a dedicated Linux guest, separated by the platform hypervisor.</p><p><strong>Connected folder: </strong>The only host resource deliberately exposed. Outputs land here; access is scoped to directories you explicitly grant.</p><p><strong>External integrations: </strong>Connectors, Claude in Chrome (browser access), and desktop extensions feed into the device, all subject to the gate.</p><p><strong>Admin controls: </strong>Org-wide toggle plus device-level MDM keys (Team/Enterprise) that restrict MCP servers and desktop extensions.</p><h3>3. The Two Execution Environments</h3><p>The split between the two environments is about privilege and reversibility. The native loop is trusted and has real access to your machine; the VM is treated as untrusted and is contained because arbitrary code is the highest-risk action an agent takes.</p><h3>3.1 The native agent loop</h3><p>Runs natively on the host OS, with no VM in between. It has four responsibilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*RWB1V4EXulqdui7g" /></figure><p>• <strong>Conversation &amp; reasoning-</strong> The model’s reasoning and tool-orchestration loop: interpreting the request, deciding the next tool call, and reading results back.</p><p>•<strong> File reads &amp; writes-</strong> File I/O happens here, not in the VM, because writing to your real disk requires real host access that an isolated guest does not have.</p><p>• <strong>Web fetches-</strong> Pulling content from URLs, governed by the application-layer egress policy.</p><p>• <strong>Local plugin MCP servers-</strong> Tool servers bundled with plugins or configured locally, run natively so they integrate with the desktop and connectors.</p><p>Why this matters: because file and web tools live outside the VM, they keep working even if the VM fails. This graceful degradation is direct evidence that the split is real, not cosmetic.</p><h3>3.2 The isolated VM</h3><p>Shell commands and any code Claude writes execute inside a dedicated Linux VM, isolated from the host operating system by the platform’s hypervisor — Apple Virtualization framework on macOS, Hyper-V on Windows. On top of the hypervisor boundary itself, the VM adds three internal hardening layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*hUKN2LxzFrdetI4J" /></figure><p><strong>Network egress filtering-</strong> Controls what executing code can reach online — independent from the native loop’s egress policy.</p><p><strong>Syscall restrictions-</strong> Limits which kernel operations the code may invoke.</p><p><strong>Per-session user isolation-</strong> Each session gets its own user account, so sessions cannot see each other.</p><p><strong>Trade-off:</strong> the same isolation that protects your host also blinds host-based security tooling. Endpoint detection (EDR) tools cannot inspect activity inside the VM by design — a point Anthropic flags explicitly for Enterprise admins whose compliance posture depends on endpoint visibility.</p><p><strong>Failure behavior: </strong>if a device cannot start the VM, Cowork continues running file and web tools while the VM is unavailable; shell commands and code execution report “workspace unavailable” until the VM recovers.</p><h3>4. The Permission System</h3><p>The application-layer permission system is what makes the trusted native loop safe. It performs two distinct jobs:</p><p>• <strong>Folder scoping-</strong> Claude can only touch directories you explicitly connect; it cannot see or modify files outside the permissions you grant. Access should be limited to only what the task requires.</p><p>• <strong>Network egress control-</strong> Governs where the native loop can reach online. Network access is restricted by default; if you extend it (for example through browser integration), you should limit it to trusted sources.</p><p>There are two independent egress filters in the architecture — one at this application layer for the native loop, and a separate one inside the VM for code execution. They are not the same control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*LIxar1ZXXljhLE2r" /></figure><h3>5. Output Delivery to the File System</h3><p>Output delivery runs through the native agent loop, not the VM. The write path is deliberately short: agent loop → permission gate → connected folder on disk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*EtKowENpQJKiHOQ0" /></figure><h3>How files are delivered</h3><p>• <strong>Direct local writes-</strong> Claude writes finished outputs straight into a directory you have already authorized — no upload/download step and no separate export.</p><p>• <strong>Finished deliverables- </strong>Outputs are polished artifacts, not raw text: structured documents, spreadsheets with working formulas, and formatted presentations.</p><p>• <strong>Folder-scoped-</strong> “Delivered to the file system” means delivered to the specific directories you connected — nothing lands elsewhere.</p><h3>The approval gate</h3><p>The gate has two checks. Folder scope decides where a file may land; the approval check decides whether a write proceeds when it is significant or potentially destructive. Routine, additive writes generally flow without interruption; destructive or hard-to-undo writes pause for your confirmation.</p><p>Likely to prompt for approval , Likely to flow without prompting, Overwriting an existing file</p><p>Creating a brand-new file in a connected folder</p><p>Deleting files</p><p>Producing fresh output that clobbers nothing</p><p>Mass rename / move of a large batch</p><p>Additive, low-risk operations</p><p>Replacing unrecoverable content</p><p>Reading or organizing without destructive change</p><p>Sourcing note: The specific operation-by-operation trigger for the approval gate is not enumerated in public documentation. The table above maps Anthropic’s stated principle (“significant or potentially destructive actions”) onto file writes; it is reasoned inference, not a published checklist. To know exactly where the gate fires in the current build, test directly in the app with a throwaway folder.</p><h3>6. The Task Lifecycle</h3><p>A single request flows through the architecture in five stages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*Cly6LZ0hSLmznU1-" /></figure><p><strong>Intent analysis: </strong>Claude analyzes the intended outcome rather than treating the request as a single prompt, identifying scope, required resources, and constraints based on the files and permissions provided.</p><p><strong>Planning &amp; decomposition:</strong> Claude creates a structured plan and breaks work into smaller subtasks, sequencing actions logically without losing context.</p><p><strong>Sub-agent execution:</strong> For heavier work, Claude coordinates multiple internal workstreams in parallel, using file and VM tools.</p><p><strong>Progress &amp; steering:</strong> Cowork surfaces what Claude is doing and why; you can monitor, clarify, or course-correct before significant actions.</p><p><strong>Output delivery:</strong> Claude writes the final outputs directly to the connected folder, ready for use.</p><h3>7. Mid-Task Steering</h3><p>Steering follows a “show your work, pause at the risky moments” model. You have three distinct levers operating at different moments:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*5Jsw17chZhMn9pwR" /></figure><p><strong>Plan approval</strong></p><p>Before execution begins. You review and approve Claude’s proposed approach — the broadest steering point, shaping the whole trajectory.</p><p><strong>Approval gate</strong></p><p>During execution, only at significant or destructive steps. Each time, you can approve or redirect. Safe steps in between run uninterrupted.</p><p><strong>Free-form intervention</strong></p><p>Anytime. Because progress stays visible, you can jump in to clarify or redirect at any point — not only when prompted.</p><p>The balance is deliberately tuned so Claude runs autonomously across the safe majority of work and only surfaces decisions at plan approval and before destructive actions. Underneath all of it: progress is visible throughout, and you remain responsible for every action you approve.</p><h3>8. External Integrations</h3><p>Three external channels connect into the device, all subject to the permission gate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*6vrHeMCTbiEFL5vj" /></figure><p>• <strong>Connectors:</strong> Give Claude access to outside data sources through the existing Claude connector ecosystem.</p><p>• <strong>Claude in Chrome:</strong> A separate browser channel — when paired, Cowork can perform tasks requiring browser access, with network permissions under user control. (Note: this also means the agent can browse with the user’s session cookies, which is relevant to the prompt-injection risk in Section 11.)</p><p>•<strong> Desktop extensions: </strong>Expand capability via MCPB/DXT extension servers, but also increase the attack surface; each should be evaluated carefully and granted only when necessary.</p><h3>9. Admin Controls (Team &amp; Enterprise)</h3><p>Cowork availability and scope are controlled at three levels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*FkAOvW2YzaQUFUca" /></figure><p><strong>Org-wide toggle-</strong> Organization settings &gt; Cowork (“Enable for your organization”) controls whether Cowork is available at all. The device-level controls only apply when Cowork is enabled.</p><p><strong>• Disable local MCP servers-</strong> Set isLocalDevMcpEnabled to false to disable plugin-bundled and locally configured MCP servers.</p><p><strong>• Disable desktop extensions-</strong> Set isDesktopExtensionEnabled to false to block MCPB and DXT extension servers from running.</p><p>Both MDM keys are device-level settings applied through your MDM solution, not from organization settings.</p><h3>10. Monitoring &amp; Observability</h3><p>This section covers material not raised earlier in the discussion. Cowork has a notable audit gap and a dedicated telemetry path that admins should understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*0eieXz_aBBxMJGOj" /></figure><h3>The audit gap</h3><p>Cowork activity is explicitly excluded from three places admins normally rely on: audit logs, the Compliance API, and data exports. The activity is not captured there at this time.</p><h3>OpenTelemetry — the current visibility tool</h3><p>To fill the gap, Anthropic provides OpenTelemetry (OTel) monitoring for Cowork on Team and Enterprise plans. When connected to an OTel collector, Cowork streams structured events that can be routed into existing SIEM and observability tools.</p><p>Events streamed include:</p><p>• User prompts. The full text of prompts submitted to Cowork.</p><p>• Tool &amp; MCP invocations. Every tool call, including MCP server name, tool name, parameters, success/failure, and execution time.</p><p>• File access. File paths Claude reads, modifies, or touches — including files accessed through MCPs and folder-scoped local files.</p><p>• Human approval decisions. The accept/reject decisions made at the approval gate.</p><p>• API request details. Including token usage and cost data.</p><p>Setup is admin-configured through the Cowork settings UI (no environment variables needed for the basic path) and requires Claude Desktop version 1.1.4173 or later. Cowork shares the same OTel event schema as Claude Code via the Claude Agent SDK; the two can be distinguished by a terminal.type attribute (cowork vs cli).</p><p>Sourcing note: A privacy caveat worth flagging: prompt content is included in Cowork OTel events by default, and tool-execution events carry file paths, URLs, and arguments. Teams that handle sensitive values should configure their collector to filter or redact these before ingestion. The OTEL_LOG_USER_PROMPTS variable used for Claude Code has no effect on Cowork.</p><h3>11. Security Considerations</h3><p>This section also covers material not raised earlier. Cowork’s agentic nature shifts real responsibility onto the user and the deploying organization.</p><p>• Prompt injection is the headline risk. An autonomous agent that reads files, browses the web with the user’s session, and runs code is exposed to instructions hidden in the content it processes. Security practitioners treat this as the primary threat to plan for.</p><p>• User responsibility. You remain responsible for all actions Claude performs on your behalf, including file changes, data access, and interactions with external systems. Reviewing plans before approval is essential.</p><p>• Extension attack surface. Each desktop extension or MCP server widens what Claude can do and what an attacker could reach. Grant only what a task needs.</p><p>• Network discipline. Keep extended network access limited to trusted sources, since egress is what turns a local compromise into data exfiltration.</p><h3>12. Limitations &amp; Evolution</h3><p>Currency caveat. Cowork launched as a research preview on January 12, 2026 (initially macOS-only, Max-plan-only, no session persistence, no cross-device sync). Anthropic has since migrated to the newer two-environment architecture described in this document and expanded availability, including Windows support. Organizations that began during the research preview are migrated separately and notified before the switch.</p><p>Known characteristics of the preview-era build (some may have since changed):</p><p>• No memory across sessions — each task starts with a clean state.</p><p>• No cross-device sync of tasks or outputs.</p><p>• The desktop app must remain open during execution; closing it or sleeping the system ends the session.</p><p>• Cowork tasks consume more usage than regular chat because of planning, sub-task coordination, and long-running execution.</p><h3>13. Design Rationale — The Reason and the How</h3><p>This section gives the reason each architectural choice exists and how it is enforced, working through every major list in this document. Throughout, the organizing logic is the same: match privilege to risk — give each function exactly the access it needs, and contain the thing most likely to go wrong.</p><p>Sourcing note: The principles and structure below are documented. Several exact mechanisms — the precise approval threshold, the VM’s internal configuration, and the rationale for the audit exclusion — live in Anthropic’s non-public Trust Center document. Those are presented here as reasoned inference from the stated principles, and are marked where they appear.</p><h3>13.1 Why the two environments sit where they do</h3><p>Native agent loop — trusted</p><p>Reason — Its jobs require real host access. Reasoning needs the model and your context; file writes need your actual disk; web fetches need a real network; local MCP servers need to integrate with the desktop. None of these can be done from inside an isolated guest.</p><p>How — Runs natively on the host OS with no VM in between, gated by the application-layer permission system rather than by isolation. Containment for this side is permission-based, not boundary-based — because you cannot isolate file I/O in a guest and still have it write to your real folders.</p><p>Isolated VM — untrusted</p><p>Reason — Arbitrary code and shell commands are the highest-risk action an agent takes — the thing a mistake or an attacker could weaponize. So it is contained rather than trusted.</p><p>How — A dedicated Linux guest separated from the host by the platform hypervisor (Apple Virtualization.framework on macOS, Hyper-V on Windows). The hypervisor is a hardware-backed boundary the guest cannot reach across.</p><p>Why the split is real, not cosmetic</p><p>Reason — If the two environments were not genuinely separate, a VM failure would take everything down. Instead, file and web tools keep working when the VM is unavailable; only code execution reports “workspace unavailable.”</p><p>How — The environments are separate execution boundaries, so one can fail independently of the other. This graceful degradation is the observable proof of the separation.</p><h3>13.2 Why the VM has three hardening layers on top of the hypervisor</h3><p>The hypervisor stops the guest from touching the host, but code inside the guest can still misbehave within it. Each layer closes a different residual gap — defense in depth, so one boundary failing does not mean total compromise.</p><p>Network egress filtering</p><p>Reason — Isolation from the host does not stop code from reaching the internet — and exfiltration or command-and-control happens over the network, not the host filesystem.</p><p>How — The VM enforces its own egress rules, independent of the native loop’s egress policy, so even code running freely inside cannot freely call out.</p><p>Syscall restrictions</p><p>Reason — A VM-escape or privilege-escalation attempt typically goes through unusual kernel calls.</p><p>How — The VM limits which kernel operations code may invoke, shrinking the attack surface against the hypervisor boundary itself.</p><p>Per-session user isolation</p><p>Reason — One session’s code should not be able to read or interfere with another session’s data.</p><p>How — Each session gets its own user account inside the VM, walling sessions off from each other even within the same guest.</p><h3>13.3 Why the permission system does two jobs</h3><p>The native loop is trusted, so something must bound what “trusted” may touch. The gate answers two separate questions, which is why it has two mechanisms — and why there are two egress filters in the system overall.</p><p>Folder scoping — “where may Claude act?”</p><p>Reason — A trusted process with unrestricted disk access is a liability, so access is reduced to only what the task requires.</p><p>How — You explicitly connect directories; Claude cannot see or modify anything outside them.</p><p>Network egress control — “where may it reach online?”</p><p>Reason — Web access is the path by which a local problem becomes a data leak.</p><p>How — Network access is restricted by default; you opt into extending it (e.g. for browser integration), ideally to trusted sources only.</p><p>Why two egress filters, not one</p><p>Reason — The native loop and the VM have different threat profiles, so a single shared policy would be wrong for at least one of them.</p><p>How — Each environment governs its own egress independently — one at the application layer, one inside the VM.</p><h3>13.4 Why the output write path takes its exact route</h3><p>The path is agent loop → permission gate → connected folder, and each hop has a reason.</p><p>• Starts in the native loop because writing to your real disk needs host access the VM does not have.</p><p>• Passes through the gate because a trusted writer still should not land files anywhere or destroy content silently.</p><p>• Ends in the connected folder because that is the single host resource deliberately exposed — outputs go where you authorized, nowhere else.</p><p>• Degrades gracefully because the write path never touches the VM, so file delivery survives a VM failure.</p><h3>13.5 Why there are three steering levers</h3><p>One lever cannot cover the whole task, because steering is needed at different scopes and moments. Splitting it three ways lets autonomy and control coexist.</p><p>Plan approval</p><p>Reason — Lets you shape the whole trajectory cheaply, before any action runs — the highest-leverage, lowest-cost intervention point.</p><p>How — You review and approve the proposed approach before execution begins.</p><p>Approval gate</p><p>Reason — Keeps the irreversible individual steps under your control without stopping everything else.</p><p>How — Fires only at significant or destructive steps during execution; each time you approve or redirect, and safe steps between run uninterrupted.</p><p>Free-form intervention</p><p>Reason — Not every needed correction lines up with a prompt — you might spot drift mid-stream.</p><p>How — Because progress stays visible throughout, you can jump in at any point, not only when asked.</p><p>Why this balance: it lets Claude run autonomously across the safe majority of work (useful for long tasks) while surfacing decisions only at plan-time and before destructive actions (so you are not micromanaging). The constant underneath: you remain responsible for everything you approve.</p><h3>13.6 Why each external channel exists and how it is bounded</h3><p>Connectors</p><p>Reason — Let Claude use outside data sources without manual copying.</p><p>How — Feed into the device through the existing connector ecosystem, still subject to the permission gate.</p><p>Claude in Chrome</p><p>Reason — Some tasks genuinely need a browser.</p><p>How — Runs with the user’s session, network permissions under user control — which is also why it carries injection risk (see 13.9).</p><p>Desktop extensions</p><p>Reason — Expand capability beyond the built-in tools.</p><p>How — Each is an added MCPB/DXT server you evaluate and grant individually, because each one widens the attack surface.</p><h3>13.7 Why admin controls are layered</h3><p>Organizations need both a master switch and fine-grained scope, so control is layered.</p><p>• Org-wide toggle — decides whether Cowork runs at all. How: set in Organization settings &gt; Cowork.</p><p>• Disable local MCP servers — cuts off plugin/local tool servers. How: isLocalDevMcpEnabled = false.</p><p>• Disable desktop extensions — blocks extension servers specifically. How: isDesktopExtensionEnabled = false.</p><p>Why the latter two are device-level MDM keys: they enforce on the endpoint itself, so they hold even outside the org’s app-level controls.</p><h3>13.8 Why each security consideration is real</h3><p>Prompt injection (the headline risk)</p><p>Reason — Cowork reads files, browses with your session, and runs code — so a hostile instruction hidden in any content it processes can hijack a capable agent.</p><p>How — Mitigated by scoping, egress limits, and the approval gate; not eliminated. Treated by practitioners as the primary threat to plan for.</p><p>User responsibility</p><p>Reason — You are accountable for every action Claude takes on your behalf.</p><p>How — The approval points exist precisely so that accountability is exercisable — review plans before approving.</p><p>Extension attack surface</p><p>Reason — Each added server is one more thing an attacker could reach through.</p><p>How — Grant only what a task needs; admins can disable extensions entirely via MDM.</p><p>Network discipline</p><p>Reason — Egress is what converts a local compromise into actual data exfiltration.</p><p>How — Keep extended network access limited to trusted sources to cap the blast radius.</p><h3>13.9 Why the monitoring gap exists and how it is filled</h3><p>The audit gap</p><p>Reason — Cowork is excluded from audit logs, the Compliance API, and data exports. The explicit rationale is not public, but it follows from Cowork being a newer local-agent surface the existing server-side audit pipeline does not capture (inference).</p><p>How — Filled with OpenTelemetry — a standard, real-time event stream security teams already ingest.</p><p>OpenTelemetry as the fill</p><p>Reason — It is the established way to get structured, real-time agent telemetry into a SIEM.</p><p>How — An admin configures an OTLP endpoint in Cowork settings; Cowork streams prompts, tool/MCP calls, file access, approval decisions, and cost. Privacy caveat: prompt content and file paths are included by default, so sensitive deployments must filter or redact at the collector.</p><p><a href="https://www.linkedin.com/search/results/all/?keywords=%23ai&amp;origin=HASH_TAG_FROM_FEED">#AI</a> <a href="https://www.linkedin.com/search/results/all/?keywords=%23agenticai&amp;origin=HASH_TAG_FROM_FEED">#AgenticAI</a> <a href="https://www.linkedin.com/search/results/all/?keywords=%23claude&amp;origin=HASH_TAG_FROM_FEED">#Claude</a> <a href="https://www.linkedin.com/search/results/all/?keywords=%23architecture&amp;origin=HASH_TAG_FROM_FEED">#Architecture</a> <a href="https://www.linkedin.com/search/results/all/?keywords=%23cybersecurity&amp;origin=HASH_TAG_FROM_FEED">#CyberSecurity</a> <a href="https://www.linkedin.com/search/results/all/?keywords=%23enterpriseai&amp;origin=HASH_TAG_FROM_FEED">#EnterpriseAI</a> <a href="https://www.linkedin.com/search/results/all/?keywords=%23desktopai&amp;origin=HASH_TAG_FROM_FEED">#DesktopAI</a> <a href="https://www.linkedin.com/search/results/all/?keywords=%23aiengineering&amp;origin=HASH_TAG_FROM_FEED">#AIEngineering</a> <a href="https://www.linkedin.com/search/results/all/?keywords=%23opentelemetry&amp;origin=HASH_TAG_FROM_FEED">#OpenTelemetry</a> <a href="https://www.linkedin.com/search/results/all/?keywords=%23aiagents&amp;origin=HASH_TAG_FROM_FEED">#AIAgents</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1041a8ebcfa6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google is Back : Google Cloud Launches New AI Models, Opens Generative AI Studio]]></title>
            <link>https://medium.com/@rahul.singh.ds20/google-is-back-google-cloud-launches-new-ai-models-opens-generative-ai-studio-7017d3431c6f?source=rss-f2193cb564b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7017d3431c6f</guid>
            <category><![CDATA[latest-news]]></category>
            <category><![CDATA[bard-ai]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[google-bard]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Rahuul Siingh]]></dc:creator>
            <pubDate>Sat, 13 May 2023 09:56:39 GMT</pubDate>
            <atom:updated>2023-05-13T09:56:39.528Z</atom:updated>
            <content:encoded><![CDATA[<h3>Google is Back : Google Cloud Launches New AI Models, Opens Generative AI Studio</h3><p>Author: Rahul Singh</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ilc6Fv0GZT7tk_cTH3j_kw.png" /><figcaption>By: Author</figcaption></figure><p>Google Cloud has launched new AI models and opened Generative AI Studio, a new tool that makes it easier for developers to build and deploy generative AI applications.</p><p>Generative AI is a type of artificial intelligence that can create new data, such as text, images, and audio. It is used in a variety of applications, including natural language processing, image generation, and speech synthesis.</p><p>The new AI models that Google Cloud has launched include:</p><ul><li>Bard: Bard is a large language model that can generate text, translate languages, write different kinds of creative content, and answer your questions in an informative way.</li><li>PaLM 2: PaLM 2 is a next-generation language model with improved multilingual, reasoning, and coding capabilities.</li><li>Turing: Turing is a text-to-code model that can generate code in a variety of programming languages.</li><li>DALL-E 2: DALL-E 2 is an image generation model that can create realistic images from text descriptions.</li><li>Chinchilla: Chinchilla is an audio generation model that can create realistic audio from text descriptions.</li></ul><p>Generative AI Studio is a new tool that makes it easier for developers to build and deploy generative AI applications. It provides a simple UI for creating and managing generative AI models, as well as a variety of tools for tuning and evaluating models.</p><p>To use Generative AI Studio, developers first need to create a model. This can be done by uploading a pre-trained model or by training a new model from scratch. Once a model is created, it can be tuned using a variety of parameters, such as the size of the model, the number of training steps, and the type of loss function.</p><p>After a model is tuned, it can be deployed to a production environment. Generative AI Studio provides a variety of deployment options, including serving models through a REST API or embedding models in web applications.</p><p>Generative AI is a powerful tool that can be used to create a variety of applications. Google Cloud’s new AI models and Generative AI Studio make it easier for developers to build and deploy generative AI applications.</p><h3>Diagram of the Generative AI Studio workflow</h3><p>The following diagram shows the workflow for creating and deploying a generative AI model using Generative AI Studio:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Df7hGJdwzX7i5Y1sWnY7pA.png" /><figcaption>By: Author</figcaption></figure><ol><li>Create a model: The first step is to create a model. This can be done by uploading a pre-trained model or by training a new model from scratch.</li><li>Tune the model: Once a model is created, it can be tuned using a variety of parameters, such as the size of the model, the number of training steps, and the type of loss function.</li><li>Deploy the model: Once a model is tuned, it can be deployed to a production environment. Generative AI Studio provides a variety of deployment options, including serving models through a REST API or embedding models in web applications.</li></ol><h3>Use cases for generative AI</h3><p>Generative AI can be used to create a variety of applications, including:</p><ul><li>Natural language processing: Generative AI can be used to create natural language processing applications, such as chatbots, question-answering systems, and machine translation systems.</li><li>Image generation: Generative AI can be used to create image generation applications, such as photorealistic image generation and image editing applications.</li><li>Speech synthesis: Generative AI can be used to create speech synthesis applications, such as text-to-speech systems and virtual assistants.</li></ul><h3>Benefits of using generative AI</h3><p>Generative AI has a number of benefits, including:</p><ul><li>Increased productivity: Generative AI can help developers to be more productive by automating tasks that are currently done manually.</li><li>Improved accuracy: Generative AI can improve the accuracy of applications by providing more realistic and accurate results.</li><li>New possibilities: Generative AI opens up new possibilities for creating applications that were not possible before.</li></ul><h3>Challenges of using generative AI</h3><p>Generative AI also has a number of challenges, including:</p><ul><li>Bias: Generative AI models can be biased, which can lead to inaccurate or unfair results.</li><li>Security: Generative AI models can be used to create malicious content, such as deepfakes or spam.</li><li>Regulation: Generative AI is a new technology, and there is currently little regulation governing its use.</li></ul><h3>Conclusion</h3><p>Generative AI is a powerful tool that can be used to create a variety of applications. Google Cloud’s new AI models and Generative AI Studio make it easier for developers to build and deploy generative AI applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7017d3431c6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Engineering-The New Buzz: Enhancing Interactions with ChatGPT as a Developer]]></title>
            <link>https://medium.com/@rahul.singh.ds20/prompt-engineering-the-new-buzz-enhancing-interactions-with-chatgpt-as-a-developer-b5f7dcadc251?source=rss-f2193cb564b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5f7dcadc251</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[prompt]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[Rahuul Siingh]]></dc:creator>
            <pubDate>Sat, 06 May 2023 12:43:27 GMT</pubDate>
            <atom:updated>2023-05-06T12:54:50.732Z</atom:updated>
            <content:encoded><![CDATA[<p>Author: Rahul Singh</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_9tulADXMrUsQMaZx5ZGog.png" /><figcaption>By: Author</figcaption></figure><p>ChatGPT, powered by OpenAI’s GPT-3.5 model, is a versatile natural language processing (NLP) model that can be interacted with by providing prompts. Prompt engineering involves carefully constructing prompts to improve the quality and specificity of the model’s responses. In this article, we will explore the principles of prompt engineering and discuss various tactics to optimize interactions with ChatGPT. We will also address model limitations and demonstrate how to use the ChatGPT API to interact with the model. Additionally, we will cover iterative prompt development and explore ways to transform text using ChatGPT’s capabilities.</p><p><strong>Prompting Principles:</strong></p><p><strong>Principle 1: Write Clear and Specific Instructions:</strong></p><p>To ensure clear and accurate responses from ChatGPT, we can follow several tactics:</p><p>Tactic 1: Use delimiters to indicate distinct parts of the input: Delimiters such as , “””, &lt; &gt;, &lt;tag&gt; &lt;/tag&gt;, or : can be used to clearly separate different sections of the prompt. This helps the model understand the intended structure and respond accordingly.</p><pre># Example using delimiters<br>prompt = &#39;&#39;&#39;<br>Question: What is the capital of France?<br>Answer: The capital of France is &lt;answer&gt;.<br>&#39;&#39;&#39;</pre><p>Tactic 2: Ask for a structured output: By requesting structured outputs like JSON or HTML, we can specify the format in which we want the model to provide information, making it easier to parse and utilize the responses.</p><pre># Example prompting for structured output<br>prompt = &#39;&#39;&#39;<br>Question: Provide information about the product in JSON format.<br>&#39;&#39;&#39;</pre><p>Tactic 3: Ask the model to check conditions: We can instruct ChatGPT to verify whether specific conditions are satisfied, helping us obtain responses that align with our requirements.</p><pre># Example asking the model to check conditions<br>prompt = &#39;&#39;&#39;<br>Question: Is the number &lt;input_number&gt; divisible by 3?<br>&#39;&#39;&#39;</pre><p>Tactic 4: “Few-shot” prompting: By providing a few examples or demonstrations, we can help ChatGPT understand a specific task or context, enabling it to generate more accurate responses.</p><pre># Example of few-shot prompting<br>prompt = &#39;&#39;&#39;<br>Context: Customer reviews of the product.<br>Review 1: This product is &lt;sentiment&gt;.<br>Review 2: The quality of this product is &lt;sentiment&gt;.<br>&#39;&#39;&#39;</pre><p><strong>Principle 2: Give the Model Time to “Think”:</strong></p><p>To allow ChatGPT to generate more thoughtful responses, we can employ the following tactics:</p><p>Tactic 1: Specify the steps required to complete a task: By breaking down a complex task into individual steps and asking the model to perform each step sequentially, we can guide it toward a more accurate and comprehensive response.</p><pre># Example specifying steps<br>prompt = &#39;&#39;&#39;<br>Task: Please outline the steps required to &lt;task&gt;.<br>&#39;&#39;&#39;</pre><p>Tactic 2: Instruct the model to work out its own solution: Rather than rushing the model into providing an immediate response, we can explicitly ask it to think through the problem and generate a solution on its own.</p><pre># Example instructing the model to think<br>prompt = &#39;&#39;&#39;<br>Question: Take your time and think about the possible solutions to &lt;problem&gt;.<br>&#39;&#39;&#39;</pre><p><strong>Model Limitations: Hallucinations:</strong></p><p>While ChatGPT is a powerful model, it may occasionally generate responses that are not based on factual information. To mitigate this issue, it is essential to carefully review and validate the generated content to ensure its accuracy and reliability.</p><p><strong>Iterative Prompt Development:</strong></p><p>To improve prompt quality, we can iterate and refine our prompts based on specific challenges or issues. Let’s address three common issues and propose solutions:</p><p>Issue 1: The text is too long: When dealing with lengthy inputs, it is beneficial to limit the number of words, sentences, or characters to ensure concise and focused responses.</p><pre># Example limiting the number of words<br>prompt = &#39;&#39;&#39;<br>Text: &lt;input_text&gt;<br>Limit: 50 words<br>&#39;&#39;&#39;</pre><p>Issue 2: Text focuses on the wrong details: To guide ChatGPT towards relevant information, we can explicitly ask it to prioritize specific aspects that are more valuable or meaningful to the intended audience.</p><pre># Example directing the focus<br>prompt = &#39;&#39;&#39;<br>Text: &lt;input_text&gt;<br>Focus: Extract key details about &lt;topic&gt;.<br>&#39;&#39;&#39;</pre><p>Issue 3: Description needs a table of dimensions: In scenarios where structured information is required, we can instruct the model to extract and organize relevant information into a table format.</p><pre># Example prompting for table creation<br>prompt = &#39;&#39;&#39;<br>Text: &lt;input_text&gt;<br>Task: Extract dimensions and create a table.<br>&#39;&#39;&#39;</pre><p><strong>Utilizing ChatGPT for NLP Tasks:</strong></p><p>Beyond prompt engineering, ChatGPT can be leveraged to perform various NLP tasks. Let’s explore some examples:</p><p><strong>Summarization with a focus on specific topics:</strong> By specifying the desired topic or theme, we can use ChatGPT to generate summaries that emphasize the requested aspects.</p><pre># Example of summarization with topic focus<br>prompt = &#39;&#39;&#39;<br>Text: &lt;input_text&gt;<br>Topic: &lt;topic&gt;<br>Task: Generate a summary with emphasis on the &lt;topic&gt;.<br>&#39;&#39;&#39;</pre><p><strong>Inferring, Sentiment Analysis, and Emotional Analysis:</strong> ChatGPT can assist in inferring information, analyzing sentiment (positive/negative), and identifying types of emotions from text.</p><pre># Example of inferring and sentiment analysis<br>prompt = &#39;&#39;&#39;<br>Text: &lt;input_text&gt;<br>Task 1: Infer information or fill in missing details.<br>Task 2: Analyze sentiment and classify it as positive or negative.<br>&#39;&#39;&#39;</pre><p><strong>Extracting Product and Company Names from Customer Reviews:</strong> We can utilize ChatGPT to extract specific entities like product names and company names from customer reviews.</p><pre># Example of entity extraction<br>prompt = &#39;&#39;&#39;<br>Text: &lt;input_text&gt;<br>Task: Extract product and company names mentioned in the text.<br>&#39;&#39;&#39;</pre><p><strong>Creating News Alerts for Specific Topics:</strong> ChatGPT can help generate news alerts based on specified topics, allowing users to stay updated on their areas of interest.</p><pre># Example of news alert generation<br>prompt = &#39;&#39;&#39;<br>Topic: &lt;topic&gt;<br>Task: Create a news alert for the latest developments on &lt;topic&gt;.<br>&#39;&#39;&#39;</pre><p><strong>Transforming Text with ChatGPT:</strong></p><p>In addition to NLP tasks, ChatGPT can be used to transform text in various ways. Let’s explore some transformation examples:</p><p><strong>Translation:</strong> ChatGPT can serve as a translation tool by utilizing its training with multiple languages. We can leverage this capability to translate text between different languages.</p><pre># Example of translation<br>prompt = &#39;&#39;&#39;<br>Source Language: &lt;source_language&gt;<br>Target Language: &lt;target_language&gt;<br>Text: &lt;input_text&gt;<br>Task: Translate the text from &lt;source_language&gt; to &lt;target_language&gt;.<br>&#39;&#39;&#39;</pre><p>Using ChatGPT as a universal translator, we can create a prompt that accepts text in any language and provides a translation in a specified language.</p><pre># Example of universal translation<br>prompt = &#39;&#39;&#39;<br>Source Language: Any<br>Target Language: &lt;target_language&gt;<br>Text: &lt;input_text&gt;<br>Task: Translate the text to &lt;target_language&gt;.<br>&#39;&#39;&#39;</pre><p><strong>Tone Transformation:</strong> ChatGPT can be used to transform the tone or style of a given text. By providing instructions on the desired tone, we can receive a revised version of the text with the specified tone.</p><pre># Example of tone transformation<br>prompt = &#39;&#39;&#39;<br>Text: &lt;input_text&gt;<br>Tone: &lt;desired_tone&gt;<br>Task: Transform the text to match the &lt;desired_tone&gt;.<br>&#39;&#39;&#39;</pre><p><strong>Format Conversion:</strong> ChatGPT can assist in converting text between different formats. By describing the input and output formats, we can prompt the model to perform the necessary format conversion.</p><pre># Example of format conversion<br>prompt = &#39;&#39;&#39;<br>Input Format: &lt;input_format&gt;<br>Output Format: &lt;output_format&gt;<br>Input Text: &lt;input_text&gt;<br>Task: Convert the text from &lt;input_format&gt; to &lt;output_format&gt;.<br>&#39;&#39;&#39;</pre><p><strong>Spellcheck/Grammar Check:</strong> With ChatGPT’s language understanding capabilities, we can prompt it to perform spellchecking and grammar checking tasks.</p><pre># Example of spellcheck/grammar check<br>prompt = &#39;&#39;&#39;<br>Text: &lt;input_text&gt;<br>Task: Check the text for spelling and grammar errors, and provide corrections.<br>&#39;&#39;&#39;</pre><p><strong>Expanding Automated Customer Email Replies:</strong> By customizing the automated replies to customer emails, ChatGPT can assist in generating more detailed and personalized responses.</p><pre># Example of expanding automated customer email replies<br>prompt = &#39;&#39;&#39;<br>Email: &lt;customer_email&gt;<br>Task: Expand the automated reply for the customer&#39;s email, providing a detailed response.<br>&#39;&#39;&#39;</pre><p><strong>Interacting with ChatGPT API:</strong></p><p>To interact with ChatGPT via the API, we can use the following Python code snippet:</p><pre>import openai<br><br># Set up OpenAI API credentials<br>openai.api_key = &#39;YOUR_API_KEY&#39;<br><br># Define the completion prompt<br>prompt = &#39;&#39;&#39;<br>Text: &lt;input_text&gt;<br>Task: &lt;task&gt;<br>&#39;&#39;&#39;<br><br># Generate a response from ChatGPT<br>response = openai.Completion.create(<br>  engine=&#39;text-davinci-003&#39;,<br>  prompt=prompt,<br>  max_tokens=100,<br>  n=1,<br>  stop=None,<br>  temperature=0.7,<br>  top_p=1.0,<br>  frequency_penalty=0.0,<br>  presence_penalty=0.0<br>)<br><br># Extract the generated text from the response<br>generated_text = response.choices[0].text.strip()<br><br># Print the generated response<br>print(generated_text)</pre><p>In this code snippet, we set up the OpenAI API credentials, define the completion prompt, and generate a response from ChatGPT using the openai.Completion.create() method. We can adjust parameters like max_tokens, temperature, and top_p to control the length and creativity of the generated response.</p><p><strong>Conclusion:</strong></p><p>Prompt engineering plays a crucial role in optimizing interactions with ChatGPT. By following the principles of clear and specific instructions, allowing the model time to “think,” and iteratively refining prompts, we can enhance the quality and relevance of responses. Furthermore, ChatGPT’s capabilities in NLP tasks and text transformation offer numerous possibilities for applications in various domains. By leveraging the ChatGPT API, developers can seamlessly integrate ChatGPT into their applications and workflows, unlocking the potential of conversational AI.</p><p>Remember, prompt engineering is an iterative process that requires experimentation, feedback, and continuous improvement to achieve desired results. With thoughtful prompt design and strategic utilization of ChatGPT’s capabilities, we can unlock new possibilities in natural language processing and empower intelligent conversations.</p><p>As you explore prompt engineering and interact with ChatGPT, keep in mind the model’s limitations, such as the potential for hallucinations. It is essential to review and validate the generated content for accuracy before relying on it in critical applications.</p><p>In conclusion, prompt engineering allows us to harness the power of ChatGPT and create meaningful and productive interactions. By understanding the principles, applying tactics, and leveraging the model’s capabilities, we can unlock the potential of conversational AI for a wide range of tasks. So, let’s dive into prompt engineering, experiment with various prompts, and witness the incredible potential of ChatGPT in transforming the way we interact with language and technology.</p><p>Happy prompting and exploring the vast possibilities of ChatGPT!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5f7dcadc251" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM: The Evolution of Language Models-GPT’s]]></title>
            <link>https://medium.com/@rahul.singh.ds20/llm-the-evolution-of-language-models-gpts-780284622a3e?source=rss-f2193cb564b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/780284622a3e</guid>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Rahuul Siingh]]></dc:creator>
            <pubDate>Sat, 06 May 2023 08:00:35 GMT</pubDate>
            <atom:updated>2023-05-06T08:00:35.829Z</atom:updated>
            <content:encoded><![CDATA[<p>Author: Rahul Singh</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_vFD6ro4HazA_cTVmY2gOg.png" /><figcaption>By: Author</figcaption></figure><p>Language models have played a pivotal role in shaping natural language processing and understanding. Over the years, we have witnessed remarkable advancements in the field, with each generation of models building upon the achievements of its predecessors. In this article, we will take you on a journey through the timeline of language model growth, starting from the early days of contextual word embeddings to the anticipation surrounding future models.</p><p><strong>ELMo (Embeddings from Language Models):</strong> In 2010, the concept of contextual word embeddings took shape with the introduction of ELMo. This model aimed to capture word meaning based on sentence context. By utilizing code snippets like the following:</p><pre>from allennlp.modules.elmo import Elmo<br>elmo = Elmo(options_file, weight_file)<br>embeddings = elmo(input_sentences)</pre><p>ELMo pioneered the idea of contextual embeddings, paving the way for more advanced models.</p><p><strong>CoVe (Contextualized Word Vectors):</strong> In 2017, the CoVe model emerged, incorporating machine translation techniques to enhance language understanding. By using snippets such as:</p><pre>import torch<br>from torch.nn import LSTM<br>lstm = LSTM(input_size, hidden_size, num_layers)<br>cove_embeddings = lstm(input_sentences)</pre><p>CoVe brought machine translation techniques into the mix, improving the model’s ability to grasp contextual nuances.</p><p><strong>ULMFiT (Universal Language Model Fine-tuning):</strong> The year 2017 witnessed a significant breakthrough with the advent of ULMFiT. This model focused on fine-tuning pre-trained language models for specific tasks. Through the following code snippet:</p><pre>from fastai.text import *<br>learn = language_model_learner(data_lm, AWD_LSTM)<br>learn.fine_tune()</pre><p>ULMFiT demonstrated the effectiveness of fine-tuning, empowering models to excel at specialized tasks.</p><p><strong>GPT-1 (Generative Pre-trained Transformer):</strong> June 2018 marked a monumental milestone with the arrival of GPT-1. It introduced the GPT series, revolutionizing language generation using pre-trained models. Developers leveraged code snippets like:</p><pre>from transformers import GPTTokenizer, GPTModel<br>tokenizer = GPTTokenizer.from_pretrained(&#39;gpt1&#39;)<br>model = GPTModel.from_pretrained(&#39;gpt1&#39;)<br>outputs = model(input_ids)</pre><p>GPT-1 kickstarted a new era of generative language models, captivating the world with its capabilities.</p><p><strong>GPT-2: Improved Text Generation:</strong> February 2019 witnessed an evolution in text generation with GPT-2. This model showcased improved performance by leveraging a larger parameter count. By utilizing the following code:</p><pre>from transformers import GPT2Tokenizer, GPT2LMHeadModel<br>tokenizer = GPT2Tokenizer.from_pretrained(&#39;gpt2&#39;)<br>model = GPT2LMHeadModel.from_pretrained(&#39;gpt2&#39;)<br>outputs = model.generate(input_ids)</pre><p>GPT-2 pushed the boundaries of text generation, thanks to its increased parameter count of 1.5 billion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zhGEB44zkQ64bGd_g8IL-g.png" /><figcaption>By: Author</figcaption></figure><p><strong>GPT-3: Advanced Language Understanding:</strong> In June 2020, GPT-3 made waves with its unparalleled language understanding and reasoning capabilities. By incorporating code snippets like:</p><pre>import torch<br>from transformers import GPT3Tokenizer, GPT3Model<br>tokenizer = GPT3Tokenizer.from_pretrained(&#39;gpt3&#39;)<br>model = GPT3Model.from_pretrained(&#39;gpt3&#39;)<br>outputs = model(input_ids)</pre><p>GPT-3’s significant parameter increase to 175 billion elevated the model’s ability to comprehend and respond to complex language structures.</p><p><strong>GPT-3.5: </strong>Fine-tuning and Enhancements In mid-2021, the language model landscape witnessed the introduction of GPT-3.5. This iteration focused on fine-tuning the model and implementing improvements across various tasks. Through snippets like:</p><pre>import torch<br>from transformers import GPT3ForSequenceClassification<br>tokenizer = GPT3Tokenizer.from_pretrained(&#39;gpt3.5&#39;)<br>model = GPT3ForSequenceClassification.from_pretrained(&#39;gpt3.5&#39;)<br>outputs = model(input_ids)</pre><p>GPT-3.5 showcased refinements in fine-tuning techniques and enhancements, making it even more adept at handling diverse language-based tasks.</p><p><strong>GPT-4:</strong> GPT-4 and Beyond Looking ahead, we anticipate the arrival of GPT-4 and beyond, which are introducing groundbreaking advancements in architecture and capabilities. While the specifics of these models remain unknown, the continuous evolution suggests that future models will push the boundaries of natural language understanding, generation, and reasoning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*Ag89rlkM_EC8HcKFYoYJGA.png" /><figcaption>By: Author</figcaption></figure><p>The growth of language models, from the early contextual embeddings to the powerful GPT-3, has revolutionized natural language processing. Each model has built upon the achievements of its predecessors, introducing novel techniques and improvements. GPT-4 and beyond, we can only imagine the remarkable strides these future models will bring to the field of language understanding and generation. The journey of language model growth is far from over, promising exciting possibilities for the future of human-machine interaction and communication.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=780284622a3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unified governance for data, analytics and AI: Unity Catalog-DataBricks]]></title>
            <link>https://medium.com/@rahul.singh.ds20/unified-governance-for-data-analytics-and-ai-unity-catalog-databricks-7b09d80e573f?source=rss-f2193cb564b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b09d80e573f</guid>
            <dc:creator><![CDATA[Rahuul Siingh]]></dc:creator>
            <pubDate>Fri, 05 May 2023 17:58:27 GMT</pubDate>
            <atom:updated>2023-05-05T18:07:53.425Z</atom:updated>
            <content:encoded><![CDATA[<p>Author: Rahul Singh &amp; Divyesh Bhisikar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YVjUIftMTCTGUYUUfYMplg.png" /><figcaption>By Author</figcaption></figure><p>Unity Catalog is a metadata management platform offered by Databricks that enables organizations to store, discover, and manage data assets across various systems, including data lakes, data warehouses, and databases. In this article, we will take a closer look at Unity Catalog, its features, and how it can help organizations with their metadata management needs.</p><p>Unity Catalog provides a centralized metadata repository that allows organizations to create, store, and manage metadata across various data sources. The platform is designed to address the challenges of metadata management, such as data discovery, data lineage, and data governance, by providing a unified view of data assets across the organization.</p><p>Features</p><p>Unity Catalog offers several features that make it a powerful metadata management platform. Some of the key features include:</p><ol><li>Unified Metadata Repository: Unity Catalog provides a centralized metadata repository that allows organizations to store metadata from various data sources. This unified repository enables organizations to have a single source of truth for their data assets, reducing the risk of data inconsistencies and errors.</li><li>Data Discovery: Unity Catalog enables organizations to discover data assets across their entire data ecosystem. The platform provides a search interface that allows users to search for data assets by name, keyword, or tag. Additionally, Unity Catalog can automatically discover new data assets as they are added to the data ecosystem.</li><li>Data Lineage: Unity Catalog provides data lineage capabilities that enable organizations to trace the origin and movement of data across various data sources. This capability is critical for organizations that need to comply with data governance regulations or need to troubleshoot data quality issues.</li><li>Data Governance: Unity Catalog enables organizations to implement data governance policies that ensure data quality, security, and compliance. The platform provides tools for data stewards to define and enforce policies around data access, data quality, and data usage.</li><li>Integration with Databricks: Unity Catalog integrates seamlessly with Databricks, enabling organizations to leverage Databricks for data processing and analysis. The integration allows organizations to leverage Databricks for data preparation, data transformation, and machine learning, while Unity Catalog provides a centralized view of data assets across the organization.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*508uMMmBaOCpYyveC9PlWQ.gif" /><figcaption><a href="https://medium.com/u/5ae67e7eecef">Databricks</a></figcaption></figure><p>Benefits</p><p>Unity Catalog offers several benefits for organizations that need to manage their data assets effectively. Some of the key benefits include:</p><ol><li>Improved Data Quality: Unity Catalog enables organizations to implement data governance policies that ensure data quality, reducing the risk of data errors and inconsistencies.</li><li>Better Data Discovery: Unity Catalog provides a search interface that enables users to discover data assets across the entire data ecosystem, reducing the time and effort required to find relevant data.</li><li>Enhanced Data Lineage: Unity Catalog provides data lineage capabilities that enable organizations to trace the origin and movement of data across various data sources, reducing the risk of data inconsistencies and errors.</li><li>Greater Data Collaboration: Unity Catalog enables organizations to share data assets across teams, improving collaboration and reducing the duplication of effort.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*p8O7y0el4d2NNJIgDUVL6w.png" /><figcaption><a href="https://medium.com/u/5ae67e7eecef">Databricks</a></figcaption></figure><p>Conclusion</p><p>Unity Catalog is a powerful metadata management platform that enables organizations to store, discover, and manage data assets across various systems. The platform offers several features, including a unified metadata repository, data discovery, data lineage, and data governance, that make it an ideal solution for organizations that need to manage their data assets effectively. With Unity Catalog, organizations can improve data quality, enhance data discovery and lineage, and foster greater collaboration across teams.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b09d80e573f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineering: Zero ETL Past, LLM new future of Data Engineering]]></title>
            <link>https://medium.com/@rahul.singh.ds20/data-engineering-zero-etl-past-llm-new-future-of-data-engineering-fa9c6160f4fe?source=rss-f2193cb564b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa9c6160f4fe</guid>
            <dc:creator><![CDATA[Rahuul Siingh]]></dc:creator>
            <pubDate>Fri, 05 May 2023 08:15:00 GMT</pubDate>
            <atom:updated>2023-05-05T08:15:00.059Z</atom:updated>
            <content:encoded><![CDATA[<p>Author: Rahul Singh</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qMijOeKxvVvcGfi35voAwg.png" /><figcaption>By Author</figcaption></figure><p>If you’re averse to change, data engineering may not be the right field for you. It seems that almost everything in this space is subject to reinvention.</p><p>Some of the most significant recent examples of this are Snowflake and Databricks, which have disrupted the traditional database concept and ushered in the modern data stack era. FiveTran and dbt have fundamentally altered the data pipeline, shifting it from ETL to ELT, as part of this trend.</p><p>Meanwhile, Monte Carlo has disrupted the traditional method of manually coding unit tests by advocating for automated testing to ensure data quality.</p><p>As data engineers continue to scale the modern data stack slope of enlightenment, they are trampling hard-coded pipelines and on-premises servers in their wake. The inevitable consolidation and trough of disillusionment are visible on the horizon, though they remain at a safe distance.</p><p>However, new ideas are already emerging to disrupt the disruptors. Zero-ETL is taking aim at data ingestion, while AI and large language models have the potential to transform transformation. Data product containers are also vying for the position of the core building block of data.</p><p>Given that the body of the Hadoop era is not even cold yet, it may seem unfair that we will have to rebuild our data systems yet again. However, the reality is that we will likely need to rebuild our data systems several times throughout our careers. The real questions we should be asking are why, when, and how we will need to do this.</p><p>While I don’t claim to have all the answers or a crystal ball, this article will closely examine some of the most significant near-future ideas that may become part of the post-modern data stack and their potential impact on data engineering.</p><p>The rise of the modern data stack was not solely due to its superior performance compared to its predecessor. There are real trade-offs involved. While data is now bigger and faster, it is also messier and less governed, and the cost efficiency is still a subject of debate.</p><p>However, the modern data stack is considered supreme because it enables use cases and unlocks value from data in ways that were previously challenging, if not impossible. Machine learning, for example, has evolved from a buzzword to a revenue generator. Analytics and experimentation can delve deeper to support more significant decisions.</p><p>The same will apply to the trends mentioned below. There will be advantages and disadvantages to each, but what will drive adoption is their ability, or the potential of the dark horse idea that hasn’t been discovered yet, to unlock new ways of leveraging data. Let’s take a closer look at each trend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N7gKfwp88moi19fYwsNu-Q.png" /><figcaption>By Author</figcaption></figure><p>The term “Zero-ETL” is somewhat misleading since the data pipeline still exists in this approach. However, the process has been modified to allow for the transactional database to do data cleaning and normalization before automatically loading the data into the analytical data warehouse. This integration is possible because most zero-ETL architectures require both the transactional database and data warehouse to be from the same cloud provider.</p><p>With Zero-ETL, the data is in a relatively raw state, and there is less ability to customize how the data is treated during the ingestion phase. However, this approach has its advantages, including reduced latency, no duplicate data storage, and one less source for failure. On the downside, there is less visibility and accountability of software engineers toward the data their services produce, which may result in unexpected schema changes that can crash the entire operation.</p><p>AWS is the main driver behind Zero-ETL, but GCP and Snowflake offer similar capabilities. Additionally, Snowflake and Databricks are pursuing “no copy data sharing,” which provides expanded access to the data where it’s stored without the need for ETL.</p><p>While Zero-ETL may simplify infrastructure, data teams may prefer to decouple their operational and analytical databases to avoid unexpected schema changes. The primary business driver for this innovation is likely infrastructure simplification, and no copy data sharing may remove obstacles to lengthy security reviews, resulting in greater adoption in the long run.</p><p>The first trend discussed is the use of large language models, such as GPT-4, to automate the process of querying data in natural language. This would simplify self-service analytics and democratize data, but it may be difficult to implement for more advanced analytics due to the complexity of data pipelines. One potential solution is the use of a “one big table” (OBT) strategy, where all the raw data is placed into one table. This strategy has both proponents and detractors, but leveraging large language models may overcome some of its challenges, such as discovery and pattern recognition. Super early startups such as Delphi and GetDot.AI, as well as more established players such as AWS QuickSite, Tableau Ask Data, and ThoughtSpot, are driving this trend.</p><p>The second trend discussed is the use of data product containers, which are containers for data tables. This concept is similar to containerization in software engineering and may make data more reliable and governable by better surfacing information such as semantic definition, data lineage, and quality metrics. However, it may be unclear whether this concept will make it easier or more difficult for organizations to scale their data products, and whether the byproducts of data pipelines (code, data, metadata) contain value worth preserving.</p><p>I can suggest some resources and best practices for building or improving data reliability:</p><ol><li>Establish clear data governance policies and procedures to ensure data quality and consistency across the organization.</li><li>Implement data validation and verification processes to catch errors and inconsistencies early in the pipeline.</li><li>Use data profiling and data quality tools to monitor and report on data health and integrity.</li><li>Build data lineage and documentation to track the lifecycle of data and its transformations.</li><li>Invest in data visualization and reporting tools to make data more accessible and understandable to all stakeholders.</li><li>Train and educate your data team on best practices for data management and quality assurance.</li><li>Establish a culture of data ownership and accountability across the organization.</li><li>Consider using cloud-based data platforms and services that offer built-in data quality and reliability features.</li></ol><p>By implementing these best practices and leveraging the latest technologies and tools, organizations can improve the reliability and trustworthiness of their data, and ultimately drive better business outcomes</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa9c6160f4fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualization: Plots to tell story with python]]></title>
            <link>https://medium.com/@rahul.singh.ds20/visualization-plots-to-tell-story-with-python-d2ac03f62d5a?source=rss-f2193cb564b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2ac03f62d5a</guid>
            <dc:creator><![CDATA[Rahuul Siingh]]></dc:creator>
            <pubDate>Thu, 09 Feb 2023 14:56:30 GMT</pubDate>
            <atom:updated>2023-02-09T14:56:30.959Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Tell story with plots according to datatypes in python</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_0G7-VdcrBtF72kbmbDq-Q.png" /></figure><p>Data visualization is a crucial aspect of data analysis as it helps to understand and communicate insights in a clear and concise manner. There are various types of charts available that can be used to visualize different types of data, and each chart has its unique advantages and disadvantages. In this article, we will discuss the most common types of charts and provide code snippets for each in Python.</p><p>Bar Charts: Bar charts are used to represent categorical data and are used to compare the values of different categories. They are used to visualize the distribution of data and are particularly useful when dealing with nominal or ordinal data. The height of each bar represents the value of each category, and the width represents the size of the category.</p><pre>import matplotlib.pyplot as plt<br><br>categories = [&quot;Category 1&quot;, &quot;Category 2&quot;, &quot;Category 3&quot;]<br>values = [10, 20, 30]<br><br>plt.bar(categories, values)<br>plt.xlabel(&quot;Categories&quot;)<br>plt.ylabel(&quot;Values&quot;)<br>plt.title(&quot;Bar Chart Example&quot;)<br>plt.show()</pre><p>Line Charts: Line charts are used to visualize data over a continuous interval or time. They are used to show trends and patterns in data and are particularly useful when dealing with continuous or numerical data. Line charts can also be used to compare multiple variables.</p><pre>import matplotlib.pyplot as plt<br><br>time = [1, 2, 3, 4, 5]<br>value1 = [10, 20, 30, 40, 50]<br>value2 = [15, 25, 35, 45, 55]<br><br>plt.plot(time, value1, label=&quot;Value 1&quot;)<br>plt.plot(time, value2, label=&quot;Value 2&quot;)<br>plt.xlabel(&quot;Time&quot;)<br>plt.ylabel(&quot;Values&quot;)<br>plt.title(&quot;Line Chart Example&quot;)<br>plt.legend()<br>plt.show()</pre><p>Scatter Plots: Scatter plots are used to visualize the relationship between two variables. They are used to show the distribution of data and to identify any patterns or trends in the data. Scatter plots can also be used to compare multiple variables.</p><pre>import matplotlib.pyplot as plt<br><br>x = [1, 2, 3, 4, 5]<br>y = [10, 20, 30, 40, 50]<br><br>plt.scatter(x, y)<br>plt.xlabel(&quot;X Axis&quot;)<br>plt.ylabel(&quot;Y Axis&quot;)<br>plt.title(&quot;Scatter Plot Example&quot;)<br>plt.show()</pre><p>Pie Charts: Pie charts are used to represent the proportion of different categories in a whole. They are used to visualize the distribution of data and are particularly useful when dealing with nominal or ordinal data. Pie charts are best used when there are few categories and the data is categorical.</p><pre>import matplotlib.pyplot as plt<br><br>categories = [&quot;Category 1&quot;, &quot;Category 2&quot;, &quot;Category 3&quot;]<br>values = [10, 20, 30]<br><br>plt.pie(values, labels=categories)<br>plt.title(&quot;Pie Chart Example&quot;)<br>plt.show()</pre><p>Histograms: Histograms are used to visualize the distribution of continuous or numerical data. They are used to show the frequency of data within a range of values and are particularly useful when dealing with large datasets. The X-axis represents the range of values, and the Y-axis represents the frequency of those values.</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br><br>data = np.random.normal(100, 20, 1000)<br><br>plt.hist(data, bins=20, edgecolor=&quot;black&quot;)<br>plt.xlabel(&quot;Range of Values&quot;)<br>plt.ylabel(&quot;Frequency&quot;)<br>plt.title(&quot;Histogram Example&quot;)<br>plt.show()</pre><p>Box Plots: Box plots are used to visualize the distribution of numerical data. They are used to show the minimum, first quartile, median, third quartile, and maximum of the data. Box plots are particularly useful when dealing with large datasets and identifying outliers in the data.</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br><br>data = np.random.normal(100, 20, 1000)<br><br>plt.boxplot(data)<br>plt.xlabel(&quot;Data&quot;)<br>plt.ylabel(&quot;Values&quot;)<br>plt.title(&quot;Box Plot Example&quot;)<br>plt.show()</pre><p>Heat Maps: Heat maps are used to visualize the relationship between two variables and are particularly useful when dealing with large datasets. They use colors to represent the values, with warm colors representing high values and cool colors representing low values. Heat maps can be used to identify patterns and trends in data and are often used in finance, biology, and sports.</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br><br>data = np.random.rand(10, 10)<br><br>plt.imshow(data, cmap=&quot;hot&quot;)<br>plt.xlabel(&quot;X Axis&quot;)<br>plt.ylabel(&quot;Y Axis&quot;)<br>plt.title(&quot;Heat Map Example&quot;)<br>plt.colorbar()<br>plt.show()</pre><p>Violin Plots: Violin plots are used to visualize the distribution of numerical data and are similar to box plots. However, violin plots show the entire distribution of the data and are particularly useful when dealing with large datasets and multiple variables. The shape of the violin plot represents the density of the data, with wider areas representing higher density and narrower areas representing lower density.</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>import seaborn as sns<br><br>data = np.random.normal(100, 20, 1000)<br><br>sns.violinplot(data)<br>plt.xlabel(&quot;Data&quot;)<br>plt.ylabel(&quot;Values&quot;)<br>plt.title(&quot;Violin Plot Example&quot;)<br>plt.show()</pre><p>Radar Charts: Radar charts are used to visualize multivariate data and are particularly useful when dealing with data with multiple variables. They are often used in sports, market research, and psychology. The shape of the chart represents the distribution of the data, with longer lines representing higher values and shorter lines representing lower values.</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br><br>data = np.array([[10, 20, 30, 40, 50],<br>                 [15, 25, 35, 45, 55],<br>                 [5, 10, 15, 20, 25]])<br><br>angles = np.linspace(0, 2 * np.pi, data.shape[1], endpoint=False)<br>data = np.concatenate((data, [data[0]]))<br>angles = np.concatenate((angles, [angles[0]]))<br><br>plt.polar(angles, data)<br>plt.title(&quot;Radar Chart Example&quot;plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMmf43vh1YQfA5A1oRwgQg.jpeg" /></figure><p>Note: This is not an exhaustive list, there are many other types of charts available for data visualization, each with its unique advantages and disadvantages. The selection of the chart depends on the type of data you are working with and the insights you want to communicate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2ac03f62d5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Synthetic Data: Future of Data]]></title>
            <link>https://medium.com/@rahul.singh.ds20/synthetic-data-future-of-data-6efd0b06a8ad?source=rss-f2193cb564b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6efd0b06a8ad</guid>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[synthetic-data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Rahuul Siingh]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 13:01:07 GMT</pubDate>
            <atom:updated>2023-02-07T13:02:17.790Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s2zWFJWS3VDMJdUJhb2bgQ.png" /></figure><p>Synthetic data generation is the process of creating artificial data that resembles real-world data. Synthetic data can be used for various purposes such as testing, training, and experimentation. In this article, we will discuss the basics of synthetic data generation and how to generate synthetic data in Python.</p><h3>Why Use Synthetic Data?</h3><p>There are several reasons why synthetic data is used:</p><p>Privacy Concerns: In some cases, real-world data may contain sensitive information that cannot be shared publicly. Synthetic data allows data scientists to perform their experiments and analysis without accessing real-world data.</p><p>Data Scarcity: In some cases, there may not be enough real-world data to perform a certain analysis or experiment. Synthetic data can be used to supplement the real-world data.</p><p>Model Validation: Synthetic data can be used to test and validate machine learning models before deploying them on real-world data.</p><h3>Types of Synthetic Data Generation</h3><p>There are several techniques used to generate synthetic data:</p><ol><li>Random Sampling: Generating data randomly using numpy’s random functions.</li><li>Sampling from Probability Distributions: Sampling data from a predefined probability distribution such as normal distribution.</li><li>Generative Adversarial Networks (GANs): Using deep learning models to generate synthetic data.</li></ol><h3>Generating Synthetic Data in Python</h3><p>Here, we will discuss how to generate synthetic data in Python using random sampling. To generate synthetic data, we will use the numpy library.</p><pre>import numpy as np<br><br># Generating synthetic data<br>synthetic_data = np.random.rand(1000, 5)</pre><p>The above code generates 1000 rows and 5 columns of synthetic data. The values in the synthetic data are generated randomly using the rand function from the numpy library.</p><p>Similarly, we can generate synthetic data from other probability distributions such as normal distribution. Here’s an example:</p><pre># Generating synthetic data from normal distribution<br>synthetic_data = np.random.normal(0, 1, (1000, 5))</pre><p>In the above example, the mean of the normal distribution is 0 and the standard deviation is 1. The normal function from the numpy library is used to generate 1000 rows and 5 columns of synthetic data from a normal distribution.</p><p><strong>Advanced techniques</strong> to generate synthetic data can produce more realistic and complex data compared to traditional methods. Here are a few of the most commonly used advanced techniques:</p><p><strong><em>Generative Adversarial Networks (GANs):</em></strong><em> </em>GANs are a type of deep neural network that can be used to generate synthetic data. GANs consist of two components: a generator and a discriminator. The generator produces synthetic data, while the discriminator tries to distinguish between real data and synthetic data. The generator and discriminator are trained simultaneously, and the generator learns to produce synthetic data that the discriminator cannot distinguish from real data.</p><p>Here’s an example of how to implement a GAN in Python using the Keras library:</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from keras.layers import Input, Dense, Reshape, Flatten, BatchNormalization<br>from keras.layers.advanced_activations import LeakyReLU<br>from keras.models import Sequential, Model<br><br># Load the real-world data<br>data = np.loadtxt(&#39;real_data.csv&#39;, delimiter=&#39;,&#39;)<br><br># Define the generator<br>generator = Sequential()<br>generator.add(Dense(128, input_dim=100))<br>generator.add(LeakyReLU(0.2))<br>generator.add(BatchNormalization(momentum=0.8))<br>generator.add(Dense(256))<br>generator.add(LeakyReLU(0.2))<br>generator.add(BatchNormalization(momentum=0.8))<br>generator.add(Dense(512))<br>generator.add(LeakyReLU(0.2))<br>generator.add(BatchNormalization(momentum=0.8))<br>generator.add(Dense(1024))<br>generator.add(LeakyReLU(0.2))<br>generator.add(BatchNormalization(momentum=0.8))<br>generator.add(Dense(np.prod(data.shape[1:]), activation=&#39;tanh&#39;))<br>generator.add(Reshape(data.shape[1:]))<br>generator.compile(loss=&#39;binary_crossentropy&#39;, optimizer=&#39;adam&#39;)<br><br># Define the discriminator<br>discriminator = Sequential()<br>discriminator.add(Flatten(input_shape=data.shape[1:]))<br>discriminator.add(Dense(512))<br>discriminator.add(LeakyReLU(0.2))<br>discriminator.add(Dense(256))<br>discriminator.add(LeakyReLU(0.2))<br>discriminator.add(Dense(1, activation=&#39;sigmoid&#39;))<br>discriminator.compile(loss=&#39;binary_crossentropy&#39;, optimizer=&#39;adam&#39;)<br><br># Combine the generator and the discriminator into a GAN<br>gan_input = Input(shape=(100,))<br>generated_data = generator(gan_input)<br>gan_output = discriminator(generated_data)<br>gan = Model(gan_input, gan_output)<br>gan.compile(loss=&#39;binary_crossentropy&#39;, optimizer=&#39;adam&#39;)<br><br># Train the GAN<br>for epoch in range(100):<br>    # Generate synthetic data<br>    noise = np.random.normal(0, 1, (len(data), 100))<br>    synthetic_data = generator.predict(noise)<br>    <br>    # Train the discriminator on real and synthetic data<br>    real_data_labels = np.ones(len(data))<br>    synthetic_data_labels = np.zeros(len(data))<br>    d_loss_real = discriminator.train_on_batch(data, real_data_labels)<br>    d_loss_synthetic = discriminator.train_on_batch(synthetic_data, synthetic_data_labels)<br>    d_loss = 0.5 * np.add(d_loss_real, d_loss_synthetic)<br>    <br>    # Train the generator to fool the discriminator<br>    g_loss = gan.train_on_batch(noise, real_data_labels)<br>    <br>    # Print the losses<br>    if epoch % 10 == 0:<br>        print(f&#39;Epoch: {epoch}, D loss: {d_loss}, G loss: {g_loss}&#39;)<br><br># Extract the synthetic data from the GAN<br>noise = np.random.normal(0, 1, (len(data), 100))<br>synthetic_data = generator.predict(noise)<br><br># Plot the real-world data and the synthetic data<br>plt.hist(data, bins=50, alpha=0.5, label=&#39;Real data&#39;)<br>plt.hist(synthetic_data, bins=50, alpha=0.5, label=&#39;Synthetic data&#39;)<br>plt.legend()<br>plt.show()</pre><p><strong><em>Variational Autoencoders (VAEs)</em></strong> are generative models that can be used to generate synthetic data. VAEs consist of two neural networks: an encoder network and a decoder network. The encoder network encodes real-world data into a lower-dimensional latent space, and the decoder network decodes the latent representation into synthetic data that resembles the original data. The two networks are trained together to minimize a reconstruction loss, which measures the difference between the real-world data and the synthetic data generated by the decoder network.</p><p>Here’s an example of how to implement a VAE in Python using the TensorFlow library:</p><pre>import tensorflow as tf<br><br># Define the encoder network<br>def encoder():<br>    model = tf.keras.Sequential()<br>    model.add(tf.keras.layers.Dense(64, activation=&#39;relu&#39;, input_dim=1024))<br>    model.add(tf.keras.layers.Dense(32, activation=&#39;relu&#39;))<br>    model.add(tf.keras.layers.Dense(16, activation=&#39;relu&#39;))<br>    model.add(tf.keras.layers.Dense(8, activation=&#39;relu&#39;))<br>    model.add(tf.keras.layers.Dense(4, activation=&#39;relu&#39;))<br>    model.add(tf.keras.layers.Dense(2, activation=&#39;relu&#39;))<br>    return model<br><br># Define the decoder network<br>def decoder():<br>    model = tf.keras.Sequential()<br>    model.add(tf.keras.layers.Dense(4, activation=&#39;relu&#39;, input_dim=2))<br>    model.add(tf.keras.layers.Dense(8, activation=&#39;relu&#39;))<br>    model.add(tf.keras.layers.Dense(16, activation=&#39;relu&#39;))<br>    model.add(tf.keras.layers.Dense(32, activation=&#39;relu&#39;))<br>    model.add(tf.keras.layers.Dense(64, activation=&#39;relu&#39;))<br>    model.add(tf.keras.layers.Dense(1024, activation=&#39;sigmoid&#39;))<br>    return model<br><br># Compile the networks<br>encoder = encoder()<br>decoder = decoder()<br><br># Define the VAE model<br>inputs = tf.keras.layers.Input(shape=(1024,))<br>latent_representation = encoder(inputs)<br>reconstructed_data = decoder(latent_representation)<br><br># Compile the VAE model<br>vae = tf.keras.Model(inputs, reconstructed_data)<br>vae.compile(loss=&#39;binary_crossentropy&#39;, optimizer=&#39;adam&#39;)</pre><p><strong><em>Monte Carlo Simulation: </em></strong>Monte Carlo simulation is a method of using random sampling to simulate real-world phenomena. It can be used to generate synthetic data by sampling from the distribution of the real-world data. For example, if you have a dataset that represents the height of individuals in a population, you can use Monte Carlo simulation to generate a synthetic dataset of heights that resembles the distribution of the real-world data.</p><p>Here’s an example of how to implement Monte Carlo simulation in Python:</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Load the real-world data<br>data = np.loadtxt(&#39;real_data.csv&#39;, delimiter=&#39;,&#39;)<br><br># Fit a probability distribution to the real-world data<br>mu, sigma = np.mean(data), np.std(data)<br>distribution = np.random.normal(mu, sigma, 1000)<br><br># Generate synthetic data using Monte Carlo simulation<br>synthetic_data = np.random.choice(distribution, size=100)<br><br># Plot the real-world data and the synthetic data<br>plt.hist(data, bins=50, alpha=0.5, label=&#39;Real data&#39;)<br>plt.hist(synthetic_data, bins=50, alpha=0.5, label=&#39;Synthetic data&#39;)<br>plt.legend()<br>plt.show()</pre><p><strong><em>Bayesian Networks:</em></strong> Bayesian networks are probabilistic graphical models that can be used to generate synthetic data. Bayesian networks consist of nodes that represent variables and directed edges that represent the relationships between variables. The probabilities of the variables in a Bayesian network are determined by a set of conditional probability distributions.</p><p>Here’s an example of how to implement a Bayesian network in Python using the pgmpy library:</p><pre>from pgmpy.models import BayesianModel<br>from pgmpy.factors.discrete import TabularCPD<br><br># Define the variables in the Bayesian network<br>variables = [&#39;Variable1&#39;, &#39;Variable2&#39;, &#39;Variable3&#39;]<br><br># Define the relationships between the variables<br>relationships = [(&#39;Variable1&#39;, &#39;Variable2&#39;),<br>                 (&#39;Variable2&#39;, &#39;Variable3&#39;)]<br><br># Create the Bayesian network<br>model = BayesianModel(relationships)<br><br># Define the conditional probability distributions<br>cpd_1 = TabularCPD(variable=&#39;Variable1&#39;, variable_card=2,<br>                   values=[[0.5, 0.5]])<br>cpd_2 = TabularCPD(variable=&#39;Variable2&#39;, variable_card=2,<br>                   values=[[0.7, 0.3],<br>                          [0.4, 0.6]],<br>                   evidence=[&#39;Variable1&#39;],<br>                   evidence_card=[2])<br>cpd_3 = TabularCPD(variable=&#39;Variable3&#39;, variable_card=2,<br>                   values=[[0.6, 0.4],<br>                          [0.3, 0.7]],<br>                   evidence=[&#39;Variable2&#39;],<br>                   evidence_card=[2])<br><br># Add the conditional probability distributions to the Bayesian network<br>model.add_cpds(cpd_1, cpd_2, cpd_3)<br><br># Generate synthetic data using the Bayesian network<br>synthetic_data = model.sample(1000)</pre><p><strong><em>Markov Chain Monte Carlo (MCMC):</em></strong> MCMC is a family of algorithms that can be used to generate synthetic data by sampling from complex probability distributions. MCMC algorithms work by constructing a Markov chain that converges to the desired distribution over time. The samples generated by the chain can be used as synthetic data.</p><p>Here’s an example of how to implement MCMC in Python using the PyMC3 library:</p><pre>import pymc3 as pm<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Load the real-world data<br>data = np.loadtxt(&#39;real_data.csv&#39;, delimiter=&#39;,&#39;)<br><br># Define the model and the priors<br>with pm.Model() as model:<br>    mu = pm.Normal(&#39;mu&#39;, mu=0, sigma=10)<br>    sigma = pm.HalfNormal(&#39;sigma&#39;, sigma=1)<br>    likelihood = pm.Normal(&#39;likelihood&#39;, mu=mu, sigma=sigma, observed=data)<br><br># Sample from the posterior using MCMC<br>with model:<br>    trace = pm.sample(1000, tune=1000)<br><br># Extract the synthetic data from the MCMC samples<br>synthetic_data = trace[&#39;likelihood&#39;]<br><br># Plot the real-world data and the synthetic data<br>plt.hist(data, bins=50, alpha=0.5, label=&#39;Real data&#39;)<br>plt.hist(synthetic_data, bins=50, alpha=0.5, label=&#39;Synthetic data&#39;)<br>plt.legend()<br>plt.show()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6efd0b06a8ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka with Azure for live streaming data]]></title>
            <link>https://medium.com/@rahul.singh.ds20/kafka-with-azure-for-live-streaming-data-9de4b05db8f8?source=rss-f2193cb564b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9de4b05db8f8</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Rahuul Siingh]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 03:08:37 GMT</pubDate>
            <atom:updated>2023-01-27T03:08:37.770Z</atom:updated>
            <content:encoded><![CDATA[<p>Apache Kafka is an open-source, distributed streaming platform that is often used to build real-time data pipelines and streaming applications. Azure is a cloud computing platform and service created by Microsoft that provides a wide range of services, including data storage, analytics, and machine learning. Together, these two technologies can be used to create a dashboard for live streaming data.</p><p>To start, you will need to set up an Azure Kafka cluster. This can be done using the Azure portal, or by using the Azure CLI. Once the cluster is set up, you can use the Kafka APIs to produce and consume messages.</p><p>One way to create a dashboard for live streaming data is to use the Kafka Connect API to connect to an external data source, such as a database or a message queue. The data from the external source can then be consumed by a Kafka consumer and used to update the dashboard in real-time.</p><p>Here is an example of how to set up a Kafka Connector to a database using the Kafka Connect API:</p><p>This code creates a new Kafka Connector that connects to a SQL Server database hosted on Azure, and reads data from a table called &quot;my_table&quot;. The data is then written to a Kafka topic with the prefix &quot;my-topic-&quot;.</p><p>Once the data is in a Kafka topic, it can be consumed by a Kafka consumer and used to update the dashboard in real-time.</p><p>To create a dashboard, you can use a visualization tool such as Power BI, which can connect to Kafka topic via a Kafka-PowerBI connector and visualize the data in real-time. Here is an example of how to create a Kafka-PowerBI connector:</p><p>This code creates a new Power BI connection, and a new dataset called &quot;Kafka&quot;. It then adds the data from the Kafka topic &quot;my-topic&quot; to the dataset, and starts streaming the data to Power BI in real-time.</p><p>In this way, you can create a dashboard for live streaming data using Apache Kafka and Azure. With integration of different tools you can create interactive and real-time dashboards to visualize the streaming data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9de4b05db8f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Drifting]]></title>
            <link>https://medium.com/@rahul.singh.ds20/data-drifting-829910a158ec?source=rss-f2193cb564b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/829910a158ec</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-drift]]></category>
            <dc:creator><![CDATA[Rahuul Siingh]]></dc:creator>
            <pubDate>Wed, 25 Jan 2023 12:10:54 GMT</pubDate>
            <atom:updated>2023-01-25T12:10:54.359Z</atom:updated>
            <content:encoded><![CDATA[<p>Data drifting, also known as concept drift, is a phenomenon that occurs when the underlying distribution of a dataset changes over time. This can lead to models trained on the original data becoming less accurate when applied to new data. In this article, we will explore some techniques for detecting and mitigating data drifting in machine learning models.</p><p>One common method for detecting data drifting is to use statistical tests, such as the Kolmogorov-Smirnov test or the Cramer-Von Mises test, to compare the distribution of new data to that of the original training data. For example, in Python, you can use the scipy.stats library to perform the Kolmogorov-Smirnov test:</p><p>If the p-value of the test is less than a pre-determined significance level, it suggests that the new data is significantly different from the original training data.</p><p>Another method for detecting data drifting is to use a sliding window approach, where the model’s performance is evaluated on a fixed-size window of the most recent data. For example, in Python:</p><pre>import numpy as np<br><br># Generate new data<br>new_data = ...<br><br># Set the window size<br>window_size = 1000<br><br># Initialize an empty list to store the model&#39;s performance<br>performance_scores = []<br><br># Iterate through the new data<br>for i in range(len(new_data) - window_size):<br>    # Get the window of data<br>    window = new_data[i:i+window_size]<br><br>    # Evaluate the model&#39;s performance on the window of data<br>    performance_score = model.evaluate(window)<br><br>    # Append the performance score to the list<br>    performance_scores.append(performance_score)<br><br># Plot the performance scores over time<br>plt.plot(performance_scores)<br>plt.show()<br><br></pre><p>If the performance scores start to decline over time, it suggests that the model is experiencing data drifting.</p><p>Once data drifting has been detected, there are several techniques that can be used to mitigate its effects. One approach is to retrain the model periodically using a combination of the original training data and the new data. Another approach is to use techniques such as transfer learning, where a pre-trained model is fine-tuned on the new data.</p><pre># Use pre-trained model<br>model = keras.applications.VGG16(weights=&#39;imagenet&#39;, include_top=False, input_shape=(224, 224, 3))<br># Freeze the layers<br>for layer in model.layers:<br>    layer.trainable = False<br># Add custom layers<br>x = model.output<br>x = keras.layers.Flatten()(x)<br>x = keras.layers.Dense(1024, activation=&quot;relu&quot;)(x)<br>x = keras.layers.Dropout(dropout rate)(x)<br>x = keras.layers.Dense(256, activation=&quot;relu&quot;)(x)<br>predictions = keras.layers.Dense(num_classes, activation=&quot;softmax&quot;)(x)<br><br><br>#Create the final model<br><br>model = keras.Model(inputs=model.input, outputs=predictions)<br><br>#Train the model<br><br>model.compile(optimizer=&#39;adam&#39;, loss=&#39;categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br>model.fit(new_data, labels, epochs=10, batch_size=32)<br><br><br><br></pre><pre>from sklearn.ensemble import RandomForestClassifier<br><br># Train a random forest classifier<br>clf = RandomForestClassifier(n_estimators=100)<br>clf.fit(original_data, labels)<br><br></pre><p>Another technique that can be used to mitigate data drifting is to use ensemble methods, such as bagging or boosting, which combine multiple models to improve performance. For example, in Python, you can use the `RandomForestClassifier` from the `sklearn` library to train an ensemble of decision trees:</p><pre>from sklearn.ensemble import RandomForestClassifier<br><br># Train a random forest classifier<br>clf = RandomForestClassifier(n_estimators=100)<br>clf.fit(original_data, labels)<br><br></pre><p>Data drifting is a common problem in machine learning, and it&#39;s important to have methods in place to detect and mitigate its effects. By using techniques such as statistical tests, sliding window approach, retraining, transfer learning, fine-tuning and ensemble methods, you can help ensure that your models continue to perform well even as the underlying data distribution changes over time.</p><p>It is worth noting that the above examples are just a reference and the solution must be tailored to the specific problem and dataset. It is important to evaluate the performance of the different approach and pick the one that works best for your dataset</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=829910a158ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>