<?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 Adithya Nanduri on Medium]]></title>
        <description><![CDATA[Stories by Adithya Nanduri on Medium]]></description>
        <link>https://medium.com/@adithya.nanduri?source=rss-198ccd09af11------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pt_uj22sW4Hifq9c</url>
            <title>Stories by Adithya Nanduri on Medium</title>
            <link>https://medium.com/@adithya.nanduri?source=rss-198ccd09af11------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 19:23:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adithya.nanduri/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[Onboard Databricks Genie Like Your Best Analyst]]></title>
            <link>https://medium.com/@adithya.nanduri/onboard-databricks-genie-like-your-best-analyst-6fed6d456105?source=rss-198ccd09af11------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fed6d456105</guid>
            <dc:creator><![CDATA[Adithya Nanduri]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 21:26:10 GMT</pubDate>
            <atom:updated>2026-10-26T18:24:26.970Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Field notes from a solutions architect on taking Databricks AI/BI Genie from a demo to answers people can trust.</em></blockquote><h3>Introduction</h3><p>When a BI rollout stalls, the first conversation is usually about the tool. I start by asking a different question: have we given it enough context to do the job?</p><p>On a call last month, a team described how they had connected Genie to thirty raw tables, tested a set of questions, demonstrated it to executives, and gone live. Two weeks later, an SVP made a staffing decision using a number produced by a query with an incorrect join. Testing had not caught the error, and the answer gave the user no reason to question it.</p><p>That’s the failure that hurts: the answer is wrong, but it looks right. By the time someone checks the SQL, the decision has already been made.</p><p>Genie is Databricks’ conversational analytics experience. Users ask questions in natural language and receive answers based on their organization’s data, governed by Unity Catalog. But access to data is only the beginning. You would not give a new analyst thirty tables and expect them to know which admission definition the operations team uses or which joins inflate a total. You would explain the business, show them the trusted sources, and review their work. Genie needs that onboarding too.</p><p>These are the six stages I use to get there. Across the teams I have worked with, this approach has typically improved Genie benchmark scores from around 75% to above 90% within a few weeks. Most of these gains came from the semantic layer: clear metric definitions, context and semantics. The work is familiar to anyone who has built trusted BI: agree on the numbers, make the logic explicit, and test the questions people actually ask.</p><h3>You have probably seen one of these</h3><p>When I look at an early deployment, these are the problems I see most:</p><ul><li><strong>It demoed well, then a wrong number drove a decision.</strong> The answer looked reasonable. Nobody had checked the join.</li><li><strong>The numbers don’t hold up.</strong> A change in wording changes the calculation, or a total comes back quietly inflated.</li><li><strong>The instructions have become a rulebook.</strong> Paragraphs explain what a readmission means, leaving the agent to reconstruct the calculation each time.</li><li><strong>One agent is being asked to cover everything.</strong> Each new domain brings another definition of “active,” another date field, and another join path.</li><li><strong>It passed the tests and struggled in the first week.</strong> The prepared questions were clear. The real ones rarely are.</li></ul><p>Before blaming the model or adding more instructions, I review the data exposed to the agent, the metric definitions, and the test coverage. These are familiar BI concerns, and they account for many of the issues teams encounter with conversational analytics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*VJgIPJp7eQpqOZJkzd5puA.png" /></figure><h3>Stage 0: Define the charter</h3><p>The team in the opening story started with thirty tables. I would start with the staffing decision. Who needs the answer? Which number do they trust today? What would make the answer wrong?</p><p>This is the agent’s job description. Write it before selecting the data.</p><p><strong>Choose one domain.</strong> Patient throughput, readmissions, or bed capacity can each provide a manageable starting point. Look for a clear user group, established terminology, curated data, and an accountable business owner.</p><p><strong>Identify the users and their decisions.</strong> An operations lead planning staffing needs a different experience from an analyst investigating an unexpected trend. Even when they use the same data, their requirements for explanation, exploration, and review may differ.</p><p><strong>Collect real questions.</strong> Use existing dashboards, BI tickets, query history, and recurring spreadsheets to identify what people need to know. Preserve the wording from meetings and support requests, including questions that are incomplete or ambiguous.</p><p><strong>Set measurable acceptance criteria.</strong> For example, require approved results for at least 90% of priority questions, reconciliation of every certified metric to its authoritative report, no unauthorized rows in security tests, and clarification for at least 90% of deliberately ambiguous questions. List the questions that must pass before release. For a staffing use case, require reconciliation of the staffing metrics and assign a reviewer for decision inputs. An overall score of 90% does not excuse a known error in those answers.</p><p><strong>Agree on definitions with the business.</strong> A technically valid query can still answer the wrong business question. Clinical operations and the data team, for example, need to agree on what counts as an admission before certifying an admission metric.</p><p><strong>Done when:</strong> the domain is scoped, 30 to 50 real questions are prioritized, business and technical owners are named, and acceptance criteria are documented.</p><h3>Stage 1: Prepare the data</h3><p>With the job defined, show the agent where to find reliable answers. The SVP’s number came from an incorrect join, exactly the kind of mistake you would warn a new analyst about before their first assignment. Those warnings need to be visible in the data model.</p><p>Start with an inventory. For each candidate table, record its grain, keys, owner, freshness, and sensitive fields. Keep, simplify, or exclude it based on the questions in the charter. Most tables do not need to reach the first agent.</p><p><strong>Declare keys and document columns.</strong> Primary and foreign keys provide information about table relationships and reduce ambiguity when generating joins. Descriptions explain fields whose meaning would otherwise have to be inferred. A column such as los_days needs a business definition, units, and relevant aggregation guidance.</p><pre>-- Ensure primary key columns are NOT NULL before declaring the key.<br>ALTER TABLE analytics.patient<br>  ADD CONSTRAINT patient_pk PRIMARY KEY (patient_id);<br><br>ALTER TABLE analytics.encounter<br>  ADD CONSTRAINT encounter_patient_fk<br>  FOREIGN KEY (patient_id) REFERENCES analytics.patient(patient_id);<br>COMMENT ON COLUMN analytics.encounter.los_days IS<br>&#39;Length of stay in days. Additive across encounters. One decimal place.&#39;;</pre><p>Databricks does not enforce these keys, so validate uniqueness and referential integrity first, and keep checking as new data arrives. This matters even more if you enable RELY, which lets the optimizer trust the keys.</p><p><strong>Create simplifying views.</strong> Use recognizable column names, decode status codes into business terms, and prejoin related attributes where the join preserves the intended grain. Check for duplicate rows and inflated totals. Expose the curated view instead of providing a competing raw table path to the same metric.</p><p><strong>Document the metric contract.</strong> Agree on each metric’s definition, formula, grain, exclusions, authoritative report, and owner. Resolve disagreements before implementation. Be explicit about snapshot measures such as census and about terms such as “current” and “admitted.” A request for current census, for example, should not produce a sum of daily snapshots.</p><p><strong>Done when:</strong> the selected objects have documented grain and descriptions, declared keys reflect validated data, simplifying views are available, and business owners have approved the metric contract. Five to ten objects is a practical initial scope.</p><h3>Stage 2: Build certified assets in Unity Catalog</h3><p>Once an analyst knows which sources to use, you show them the approved calculations. Do the same for Genie. Stage 1 put the definitions on paper; this stage turns them into assets the agent can query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*ZFeeUR0TRGRED7kcF8732A.png" /></figure><p><strong>Create Metric Views.</strong> Use Metric Views to define measures and the dimensions available for analysis. The metric contract provides the specification; the implemented view provides the calculation.</p><pre>CREATE OR REPLACE VIEW analytics.mv_encounters<br>WITH METRICS<br>LANGUAGE YAML<br>AS $$<br>version: 1.1<br>source: analytics.genie_encounters<br>dimensions:<br>  - name: department<br>    expr: source.department<br>measures:<br>  - name: total_los_days<br>    expr: SUM(source.length_of_stay_days)<br>    synonyms: [total length of stay days]<br>$$;<br>-- Group the approved measure by department.<br>SELECT department, MEASURE(total_los_days) AS total_los_days<br>FROM analytics.mv_encounters<br>GROUP BY ALL;</pre><p>Reconcile each measure to its authoritative report before certifying it. Review synonyms with business users as well. Terms such as “LOS” may be used for an average or a total, so avoid treating them as interchangeable without an agreed definition.</p><p><strong>Use functions for recurring rules.</strong> Encode rules used across questions, such as fiscal calendar calculations, in Unity Catalog SQL functions. Assign owners, test the logic, and manage changes alongside the other certified assets.</p><p><strong>Done when:</strong> certified metrics and reusable rules are implemented in governed assets, reconciled to approved results, and assigned to owners.</p><h3>Stage 3: Configure the Genie agent</h3><p>Now give the agent its working set: the sources, calculations, and examples it needs for the job. This is where the thirty raw tables in the opening story should have become a small, deliberate selection. Write instructions after that structure is in place.</p><p><strong>Limit the initial scope.</strong> Start with a few curated views and Metric Views, the functions required by the use case, five to fifteen example queries, and a concise instructions block. Each additional object should answer a documented need. Avoid including raw tables solely to accommodate hypothetical future questions.</p><p><strong>Distinguish certified reporting from exploration.</strong> Use the approved metric definitions for numbers that appear in reporting. Curated views can support further investigation, such as examining the records behind a result. Test that exploratory access does not introduce competing calculations for certified metrics. When recurring questions fall outside the available assets, extend the model deliberately and add corresponding tests.</p><p><strong>Give each agent a clear remit.</strong> When a new domain brings its own owners, definitions, and test questions, build a focused agent for it. Encounters, readmissions, and bed capacity are candidates for separate scopes. A routing layer, such as Genie One or a Supervisor Agent, can direct questions to the relevant agent. Validate routing and questions that span domains as part of the overall solution.</p><p><strong>Provide representative example queries.</strong> Pair real questions with approved SQL, particularly where terminology alone does not convey the intended calculation. For example, show how to select each unit’s latest census snapshot when answering a question about current capacity.</p><p><strong>Keep instructions specific.</strong> Document vocabulary, defaults, and when to ask for clarification. Keep certified calculations in governed assets. Instructions can guide responses, but access restrictions must be enforced through permissions and applicable row filters or column masks. A request in the instructions to avoid exposing PHI is not an access control.</p><p><strong>Configure the SQL warehouse.</strong> Use a Serverless or Pro SQL warehouse sized for short, bursty questions. Test expected concurrency and response times, then tune capacity against cost.</p><p><strong>Done when:</strong> the agent has access to the intended assets, example queries cover important interpretations, instructions are concise, and access controls have been tested.</p><h3>Stage 4: Validate with real questions</h3><p>The agent in the opening story passed its demo. The staffing question exposed what that demo had missed. Before a new analyst’s work reaches an SVP, someone checks the calculation against a trusted result. Give Genie that same review, using the questions it will face in production.</p><p><strong>Build a benchmark.</strong> Use Genie’s benchmark capability to evaluate questions against approved answers or reference SQL. Start with the questions collected in Stage 0 and have business owners review the expected results. Include time logic, joins, aggregation, ambiguity, and questions outside the agent’s scope. Test security under the relevant user permissions as well.</p><p><strong>Vary the wording.</strong> Test two to four phrasings of important questions while keeping the intended meaning consistent. Include abbreviations and incomplete requests that users actually make. Review explanations and clarifying questions manually, since a correct result alone does not establish that the response is useful.</p><p><strong>Classify failures.</strong> Record whether an error comes from an ambiguous definition, an incorrect join, a missing synonym, an aggregation issue, or another cause. Correct the relevant asset or configuration, then rerun the affected tests. Avoid adding instructions before understanding why the answer failed.</p><p><strong>Run a beta with representative users.</strong> Include people who know the authoritative reports and can assess the answers in the context of their work. Use feedback and review requests to collect issues, and inspect the generated SQL during triage. Turn each confirmed error into a regression test. Fix the definition, view, example, or instruction responsible so the correction carries forward to the next user.</p><p><strong>Done when:</strong> the benchmark baseline is recorded, beta users have completed real workflows, and release criteria are met. Document any accepted defects, their business impact, the accountable approver, and any required limits on use.</p><h3>Stage 5: Operate and maintain</h3><p>Onboarding does not end with the first approved answer. An analyst needs to know when a definition changes; the agent’s assets and tests need the same update. Keep deployed definitions aligned with source control so the team can review, reproduce, and roll back changes.</p><ul><li><strong>Version the assets.</strong> Store Metric View YAML, view and function definitions, example queries, instructions, and benchmarks in Git.</li><li><strong>Use a repeatable deployment process.</strong> Deploy the Genie space and its SQL dependencies through Databricks Asset Bundles, with controlled promotion across environments.</li><li><strong>Gate changes with validation.</strong> Require reconciliation and benchmark checks before promoting changes to production.</li><li><strong>Monitor usage and quality.</strong> Review failed queries, unanswered questions, user feedback, cost, and benchmark results on an agreed cadence.</li><li><strong>Manage definition changes.</strong> Obtain approval for changes to certified metrics and explain the impact to users before releasing them.</li></ul><p><strong>Done when:</strong> assets are versioned, deployment is repeatable, validation runs before release, and operational responsibilities are assigned.</p><h3>Back to that staffing decision</h3><p>For the team on that call, the immediate task would be to correct the join and reconcile the number used by the SVP. The lasting fix would be to make that question part of the agent’s onboarding: an agreed definition, a documented join path, an approved calculation, and a test that runs after every change.</p><p>That is what I mean by onboarding Genie like your best analyst. Give it a clear assignment. Show it the authoritative sources. Teach it the calculations your business has agreed on. Review its work, then keep those expectations current as the business changes.</p><p>If you already have a Genie agent in production, start with one question someone uses to make a decision. Trace the answer through the generated SQL to the source data. Check the grain, joins, and metric definition with the business owner. Save the approved result as a benchmark, then test the same question in the different ways users ask it.</p><p>Repeat that process for your priority questions. You will build a useful set of examples and tests while finding the gaps that matter. That is how this playbook becomes a working practice, and how the next staffing answer earns the SVP’s trust.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fed6d456105" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Guide to Environment Isolation and Access Control with Unity Catalog]]></title>
            <link>https://medium.com/@adithya.nanduri/a-practical-guide-to-environment-isolation-and-access-control-with-unity-catalog-5fd8e2939b1f?source=rss-198ccd09af11------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fd8e2939b1f</guid>
            <category><![CDATA[governance]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[unity-catalog]]></category>
            <category><![CDATA[access-control]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[Adithya Nanduri]]></dc:creator>
            <pubDate>Tue, 03 Jun 2025 21:55:23 GMT</pubDate>
            <atom:updated>2025-06-03T21:55:23.710Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Secure and Scalable Data Architectures with Databricks Unity Catalog</h3><p>Establishing a secure and well-structured data architecture is essential for scaling analytics in modern enterprises, particularly in regulated industries like healthcare. Databricks Unity Catalog provides a unified governance layer to manage data assets, enforce access policies, and isolate environments across the software development lifecycle (SDLC). This post outlines how to design secure environments using Unity Catalog and organize data for scalable, compliant operations.</p><h3>Understanding SDLC Environments</h3><p>Most organizations implement multiple environments to support code quality and system stability:</p><ul><li><strong>Development (DEV):</strong> For initial coding and testing</li><li><strong>Staging (STG):</strong> For integration testing and QA</li><li><strong>Production (PRD):</strong> The live, customer-facing environment</li></ul><p>To further strengthen isolation and control, many enterprises separate environments with dedicated storage, virtual networks, and individual Databricks workspaces. This helps prevent accidental cross-environment access, which is particularly important in production.</p><blockquote>A useful analogy is to think of these environments as zones within a hospital:</blockquote><blockquote><strong>DEV</strong> is like the research lab — used for experiments and new ideas.</blockquote><blockquote><strong>STG</strong> resembles a simulation floor, where workflows are validated and refined.</blockquote><blockquote><strong>PRD</strong> is the actual hospital, where actions have real consequences and must be tightly controlled.</blockquote><blockquote>Maintaining clear separation between these areas improves safety, traceability, and operational consistency — just as Unity Catalog enables in your data platform.</blockquote><h3>Unity Catalog Isolation Capabilities</h3><p>Unity Catalog enhances environment isolation through:</p><ul><li><strong>Administrative Isolation:</strong> Assign admins per environment to delegate responsibilities.</li><li><strong>Workspace-Catalog Mapping:</strong> Bind workspaces to specific catalogs (e.g., production to its own catalog, development with broader access).</li><li><strong>Storage Isolation:</strong> Use separate physical storage per catalog to avoid data overlap.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*HXo_jOt4xXDaOZMB.png" /></figure><ul><li><strong>Granular Access Control:</strong> Enforce user-level permissions for data and metadata access.</li></ul><p>Unity Catalog simplifies governance by aligning security and management practices with the structure of modern development workflows.</p><blockquote>In a hospital, each department has its own structure<em>, a head (</em><strong><em>admin</em></strong><em>), its own floor (</em><strong><em>workspace</em></strong><em>), separate equipment rooms (</em><strong><em>storage</em></strong><em>), and strict access policies for staff (</em><strong><em>permissions</em></strong><em>). You wouldn’t let a medical intern walk into surgery or store pediatric supplies in the ICU. Similarly, Unity Catalog keeps each environment isolated and access-controlled, ensuring safety, clarity, and compliance across the system.</em></blockquote><h3>Organizing Data in Databricks: Catalogs, Schemas, and Tables</h3><p>After setting up environment isolation, the next step is to organize data for clarity, security, and scalability. Unity Catalog offers a three-tier structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*2cxItHAIBpUzuntX.png" /></figure><h3>Catalogs</h3><p>Top-level containers used to separate data by environment, business function, or domain. Each catalog enforces its own access policies.<br> <em>Example:</em> org_dev, org_stg, org_prod</p><h3>Schemas</h3><p>Schemas live within catalogs and group related data by project, team, or subject area.<br> <em>Example:</em> Inside org_prod, you might have clinical, lab_results, and treatments</p><h3>Tables and Views</h3><p><strong>Tables</strong> hold actual data:</p><ul><li><em>Managed:</em> Stored and controlled within Unity Catalog</li><li><em>External:</em> Reference data from external sources like existing data lakes</li></ul><p><strong>Views</strong> are virtual tables used for simplified queries or controlled data exposure (e.g., masking PHI)</p><p>This hierarchy ensures clean data organization and enforces fine-grained access in healthcare environments.</p><blockquote>Organizing data in Unity Catalog is similar to how hospitals manage medical records. A <strong>Catalog</strong> is like an entire records room. One might be used for research, another for active patient care, and another for audits. Within each room, <strong>Schemas</strong> act like filing cabinets organized by department, such as cardiology or oncology. <strong>Tables</strong> represent the individual patient records, while views are redacted versions shared with interns or billing teams. They contain limited information but still serve a purpose. This structure helps keep data organized, secure, and compliant, just as hospitals do with sensitive patient information.</blockquote><h3>Controlling Access with Databricks Identities</h3><p>Databricks defines identity through three core constructs, essential for securing access to data and compute:</p><ol><li><strong>Users:</strong> Human identities tied to email addresses, added directly or synced via IdP.<br> <em>Use:</em> Interactive access to workspaces and data<br> <em>Example:</em> A data scientist running notebooks in DEV</li><li><strong>Service Principals:</strong> Non-human identities for automation tools, jobs, or CI/CD pipelines.<br> <em>Use:</em> Secure automated workflows<br> <em>Example:</em> A nightly ingestion job using a service principal</li><li><strong>Groups:</strong> Logical collections of users and/or service principals.<br> <em>Use:</em> Simplify RBAC by assigning permissions at scale<br> <em>Example:</em> A Data Engineers group with write access to dev schemas</li></ol><p>In Databricks Unity Catalog, <strong>managing access through groups</strong> rather than individual users is the recommended approach for scalable and consistent governance. Assigning privileges to groups allows you to manage access centrally as team membership changes. For example, when employees join or leave, you only need to update group membership instead of adjusting permissions for each user account. This approach keeps access policies consistent, easier to audit, and simpler to maintain over time.</p><blockquote>Think of users, service principals, and groups like hospital staff badges. <strong>Users</strong> are like doctors or nurses who need access to certain areas to perform their work. <strong>Service principals</strong> are more like automated carts that deliver supplies along predefined routes without human involvement. <strong>Groups</strong> represent departments such as Radiology or Billing. Instead of setting permissions for each person individually, you grant access to the department as a whole. When someone joins or leaves, you simply update their group membership, rather than reworking the entire access plan.</blockquote><h3>Group-Based Access Control Best Practices</h3><p>With data organized and identities defined, the next step is <strong>access control</strong>. The best practice is to assign permissions to <strong>groups</strong> rather than <strong>individuals</strong>. This approach simplifies management and supports <strong>scalable</strong>, <strong>consistent governance</strong> as teams grow or change.</p><p>All <strong>Databricks identities</strong>, including <strong>users</strong> and <strong>service principals</strong>, can be added to <strong>groups</strong>. These groups can be created directly in <strong>Databricks</strong> or synced from your <strong>identity provider</strong> such as <strong>Azure AD</strong>, <strong>Okta</strong>, or <strong>Google Workspace</strong>. <strong>Syncing groups</strong> ensures that access remains aligned with your <strong>enterprise directory structure</strong> and <strong>role-based policies</strong>.</p><p><strong>Group members</strong> automatically inherit the <strong>privileges</strong> assigned to the group. This makes it easy to manage access across <strong>catalogs</strong>, <strong>schemas</strong>, <strong>tables</strong>, and <strong>models</strong> with minimal overhead.</p><h3>Common Group Structures in a Typical Organization</h3><p>When designing your access strategy, think in terms of <strong>roles and responsibilities</strong>. Here are examples of common groups you might define:</p><p><strong>Service-principal group (</strong><strong>prod-pipelines)</strong></p><ul><li>Contains only CI/CD or scheduled-job identities.</li><li>Owns production writes (e.g., schema migrations, table refreshes).</li><li>Granted only what’s needed: CREATE TABLE, ALTER, INSERT, plus USE CATALOG/USE SCHEMA.</li></ul><p><strong>Human users</strong></p><ul><li>Enable interactive access for users in development and read-only roles in production</li><li>Development and testing occur in <strong>DEV/STG</strong>; <strong>PRD</strong> is read-only</li></ul><p>Example groups under this category:</p><ul><li>data-engineers: read-only access to prod tables</li><li>data-scientists: execute access on ML models, no table writes</li><li>clinical-team: read prod clinical data; limited write if approved</li><li>analysts: access to curated views and dashboards</li><li>compliance: read access to audit logs and lineage metadata</li></ul><p><strong>Prod-admins (optional)</strong></p><ul><li>A small, tightly controlled group with elevated write access in <strong>PRD</strong>.</li><li>Used only in emergencies; access should be gated by <strong>MFA</strong> and audit logging (“break-glass” procedure).</li><li>Enable full audit logging (“break-glass” procedure)</li></ul><p>These groupings help enforce <strong>principle of least privilege</strong> while supporting operational efficiency. By aligning groups with business units or functional roles, you reduce the chance of privilege sprawl and make onboarding/offboarding effortless.</p><blockquote>Imagine a hospital where access is based on your <strong>department badge</strong>, not your name. <strong>Surgeons</strong> can enter the <strong>operating room</strong>, <strong>nurses</strong> access the <strong>wards</strong>, and <strong>janitorial staff</strong> use the <strong>supply rooms</strong>. You do not create rules for each individual. Instead, you define them for the <strong>role</strong>.</blockquote><blockquote>When a new surgeon joins, they automatically get the right access. <strong>Unity Catalog groups</strong> follow the same principle. Assign access to <strong>roles</strong>, not individuals, and you will spend less time on <strong>access management</strong> and more time on <strong>delivering value</strong>.</blockquote><h3>Enforcing Access with Groups and ACLs</h3><p>Once groups are defined and access strategies are mapped, Unity Catalog applies <strong>Access Control Lists (ACLs)</strong> to enforce data access policies. ACLs specify which principals <strong>users, service principals, or groups</strong> have which privileges on <strong>securable objects</strong> like catalogs, schemas, tables, and models.</p><p>In practice, this means every object in Unity Catalog has a list of grants attached to it, and <strong>Databricks checks these ACLs at query time</strong> to determine if a user is authorized.</p><h3>Example: How ACLs Apply Across the Hierarchy</h3><p>Let’s say a user in the clinical-team group attempts to query a table main.clinical.transactions. Unity Catalog checks:</p><ol><li>Does the user (via group membership) have USE CATALOG on main?</li><li>Do they have USE SCHEMA on main.clinical?</li><li>Do they have SELECT on main.clinical.transactions?</li></ol><p>Only if <strong>all three permissions are satisfied</strong>, the query is allowed. This makes access <strong>predictable, layered, and secure</strong>.</p><h3>Best Practices for ACL Management</h3><ul><li><strong>Start at the top:</strong> Grant USE CATALOG first, then schema-level, then object-level</li><li><strong>Group-first approach:</strong> Avoid assigning privileges directly to users</li><li><strong>Use </strong><strong>SHOW GRANTS</strong> regularly to audit and verify who has access</li><li><strong>Remove broad defaults</strong> (like users group access) and replace with specific group grants</li></ul><pre>-- ========================<br>-- CATALOG-LEVEL PERMISSIONS<br>-- ========================<br>-- Grant USE CATALOG to allow visibility and access to schemas inside<br>GRANT USE CATALOG ON CATALOG main TO `data-engineers`;<br>GRANT USE CATALOG ON CATALOG main TO `clinical-team`;<br>GRANT USE CATALOG ON CATALOG main TO `ml-team`;<br><br>-- ========================<br>-- SCHEMA-LEVEL PERMISSIONS<br>-- ========================<br>-- Grant access to schemas for different groups<br>GRANT USE SCHEMA ON SCHEMA main.analytics TO `data-engineers`;<br>GRANT USE SCHEMA ON SCHEMA main.clinical TO `clinical-team`;<br>GRANT USE SCHEMA ON SCHEMA main.ml_models TO `ml-team`;<br>-- Allow CREATE TABLE in specific schemas (dev/staging only)<br>GRANT CREATE TABLE ON SCHEMA main.analytics TO `data-engineers`;<br>GRANT CREATE TABLE ON SCHEMA main.clinical TO `clinical-team`;<br>-- Grant full control to admin group over a schema<br>GRANT ALL PRIVILEGES ON SCHEMA main.hr TO `hr-admins`;<br><br>-- ========================<br>-- TABLE-LEVEL PERMISSIONS<br>-- ========================<br>-- Grant SELECT on specific tables<br>GRANT SELECT ON TABLE main.clinical.transactions TO `clinical-team`;<br>GRANT SELECT ON TABLE main.analytics.cleaned_data TO `data-scientists`;<br><br>-- ========================<br>-- FUNCTION/ML MODEL ACCESS<br>-- ========================<br>-- Grant execute access to ML models/functions<br>GRANT EXECUTE ON FUNCTION main.ml_models.predict_sales TO `ml-team`;<br><br>-- ========================<br>-- AUDIT &amp; CLEANUP EXAMPLES<br>-- ========================<br>-- View current grants<br>SHOW GRANTS ON SCHEMA main.analytics;<br>SHOW GRANTS `data-engineers` ON SCHEMA main.analytics;<br>-- Revoke privileges when access is no longer needed<br>REVOKE CREATE TABLE ON SCHEMA main.analytics FROM `data-engineers`;<br>REVOKE SELECT ON TABLE main.clinical.transactions FROM `clinical-team`;</pre><h3>Row Level Security in Databricks</h3><p>Unity Catalog introduced the ability to apply row filters directly to tables using User Defined Functions (UDFs). This approach has several advantages:</p><ul><li>RLS only needs to be defined once per physical Delta table</li><li>Virtual objects like views automatically inherit the filtering</li><li>Users don’t need to be blocked from underlying Delta tables</li></ul><p>Let’s look at some examples of implementing RLS with Unity Catalog:</p><h4>Example 1: Simple Region-Based Access Control</h4><pre>-- Create a function that filters data based on user group membership<br>CREATE FUNCTION us_filter(region STRING)<br>RETURN IF(IS_ACCOUNT_GROUP_MEMBER(&#39;admin&#39;), true, region=&#39;US&#39;);<br><br>-- Apply the function to a table as a row filter<br>CREATE TABLE sales (region STRING, id INT);<br>ALTER TABLE sales SET ROW FILTER us_filter ON (region);</pre><p>In this example, we’ve created a function that checks if the user belongs to the ‘<strong>admin</strong>’ group. If they do, they can access all records. If not, they can only see records where region=’<strong>US</strong>’.</p><h4>Example 2: Creating a New Table with Row Filter</h4><pre>-- Create a table with the row filter applied directly<br>CREATE TABLE sales (region STRING, id INT)<br>WITH ROW FILTER us_filter ON (region);</pre><p>This example shows how to create a new table with a row filter already applied, which is a cleaner approach when starting from scratch.</p><h4>Example 3: Removing a Row Filter</h4><pre>-- Disable the row filter<br>ALTER TABLE sales DROP ROW FILTER;</pre><p>This command removes the row filter, allowing all users to see all rows in the table</p><h3>Column Level Security through Column Masking</h3><p>Column masking allows you to transform sensitive data at query runtime based on who is accessing it. This approach is particularly useful for scenarios where some users should see masked values while others see the original data.</p><h3>Example 1: Simple SSN Masking</h3><pre>-- Create a masking function for SSN<br>CREATE FUNCTION mask_ssn(ssn STRING) <br>RETURN CASE WHEN is_account_group_member(&#39;HumanResourceDept&#39;) <br>           THEN ssn <br>           ELSE &#39;***-**-****&#39; <br>      END;<br><br>-- Create a table with a masked column<br>CREATE TABLE persons(<br>    name STRING, <br>    ssn STRING MASK mask_ssn<br>);<br>-- Insert some test data<br>INSERT INTO persons VALUES(&#39;James&#39;, &#39;123-45-6789&#39;);</pre><p>When users who aren’t members of the ‘HumanResourceDept’ group query this table, they’ll see masked SSN values. Only members of the specified group will see the actual SSNs.</p><h3>Example 2: Regional PII Masking</h3><pre>-- Create a masking function with multiple parameters<br>CREATE FUNCTION mask_pii_regional(value STRING, region STRING)<br>RETURN IF(is_account_group_member(region || &#39;_HumanResourceDept&#39;), <br>           value, <br>           &#39;REDACTED&#39;);<br><br>-- Create a table with a masked column using additional parameters<br>CREATE TABLE persons(<br>    name STRING, <br>    address STRING MASK mask_pii_regional USING COLUMNS (region), <br>    region STRING<br>);<br>-- Insert test data<br>INSERT INTO persons VALUES(&#39;James&#39;, &#39;160 Spear St, San Francisco&#39;, &#39;US&#39;);</pre><p>This example demonstrates a more complex masking function that takes multiple parameters. The function masks the address based on both the user’s group membership and the region value from the same row.</p><h3>Example 3: Adding a Column Mask to an Existing Table</h3><pre>-- Create a table first<br>CREATE TABLE users (name STRING, ssn STRING);<br><br>-- Add data<br>INSERT INTO users VALUES(&#39;Maria&#39;, &#39;987-65-4321&#39;);<br>-- Apply a column mask to an existing column<br>ALTER TABLE users ALTER COLUMN ssn SET MASK mask_ssn;</pre><p>This example shows how to add a column mask to an existing table rather than when creating the table.</p><h3>Example 4: Removing a Column Mask</h3><pre>-- Remove a column mask<br>ALTER TABLE users ALTER COLUMN ssn DROP MASK;</pre><p>This removes the column mask, returning the column to its original behavior.</p><h3>Conclusion</h3><p>Designing a <strong>secure</strong> and <strong>scalable data architecture</strong> with <strong>Unity Catalog</strong> is not just a governance task. It is a foundational strategy for enabling <strong>trust</strong>, accelerating innovation, and ensuring compliance in modern enterprises. From isolating environments across your <strong>software development lifecycle (SDLC)</strong> to implementing granular <strong>data access controls</strong> using <strong>groups</strong>, <strong>ACLs</strong>, <strong>row-level filters</strong>, and <strong>column masking</strong>, Unity Catalog offers a robust and unified framework for managing data responsibly.</p><p>By adopting best practices such as <strong>group-based access control</strong>, aligning your architecture with <strong>SDLC principles</strong>, and using features like <strong>row filters</strong> and <strong>column masking</strong>, organizations especially those in <strong>regulated industries</strong> such as healthcare can confidently support <strong>data democratization</strong> without compromising on <strong>security</strong> or <strong>compliance</strong>.</p><h3>Additional Resources</h3><p>To take your implementation further, consider the following tools and documentation:</p><h4>1. Terraform for Automation</h4><p>Automate your Unity Catalog setup using <a href="https://registry.terraform.io/providers/databricks/databricks/latest"><strong>Databricks Terraform Provider</strong></a>:</p><ul><li>Define access policies, groups, and workspace-to-catalog mappings as code</li><li>Version control and review your security infrastructure</li></ul><h4>2. Unity Catalog Documentation</h4><p>Deep dive into Unity Catalog features directly from Databricks:</p><ul><li><a href="https://www.databricks.com/product/unity-catalog"><strong>Unity Catalog Overview</strong></a></li><li><a href="https://docs.databricks.com/aws/en/tables/row-and-column-filters"><strong>Row-Level Security</strong></a></li></ul><h4>3. CI/CD &amp; Access Auditing</h4><p>Integrate Unity Catalog access controls with:</p><ul><li><a href="https://docs.databricks.com/aws/en/dev-tools/ci-cd/"><strong>CI/CD pipelines</strong></a>: Use service principals to promote code safely</li><li><a href="https://docs.databricks.com/aws/en/admin/account-settings/audit-logs"><strong>Audit logs &amp; lineage</strong></a>: Monitor access and transformations with built-in observability</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fd8e2939b1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cohort Builder: Streamlining Data Segmentation with Streamlit and Snowflake]]></title>
            <link>https://medium.com/snowflake/cohort-builder-streamlining-data-segmentation-with-streamlit-and-snowflake-f4f0137068a0?source=rss-198ccd09af11------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4f0137068a0</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[cohorts]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Adithya Nanduri]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 20:47:55 GMT</pubDate>
            <atom:updated>2024-08-10T17:31:19.434Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever struggled with segmenting large datasets to tailor marketing campaigns or optimize product offerings? Do you need a streamlined way to manage customer data while ensuring up-to-date insights? Are you looking for a solution that can automate data refreshes without manual intervention?</p><p>If so, the Cohort Builder is the tool you’ve been searching for!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/0*F6Vtp2rlB8GMFKfT.png" /></figure><h3>What Is It?</h3><p>The Cohort Builder is a versatile solution designed to facilitate the creation, management, and scheduling of customer cohorts using Streamlit and Snowflake. This tool leverages a user-friendly Streamlit application to define and manage groups of individuals based on shared characteristics or behaviors. The Cohort Builder can be seamlessly deployed within your Snowflake environment, offering a comprehensive platform for data-driven decision-making.</p><h3>Key Functionalities</h3><ol><li><strong>Cohort Building:</strong> Define cohort criteria using an easy-to-use interface that generates SQL queries. This feature enables users to segment data based on attributes like AGE_CODE, LOCATION, and DATE.</li><li><strong>Cohort Management:</strong> Offers tools for updating and maintaining cohorts, ensuring they remain relevant and accurate as new data becomes available.</li><li><strong>Cohort Scheduling:</strong> Automates the refreshing of cohort data at regular intervals, utilizing Snowflake’s dynamic tables, tasks, and procedures.</li></ol><h3>Use Cases</h3><ul><li><strong>Targeted Marketing:</strong> Create cohorts based on customer purchase behaviors to tailor marketing campaigns and improve engagement.</li><li><strong>Product Insights:</strong> Group users by product usage patterns to identify areas for enhancement or new feature development.</li><li><strong>Healthcare Analytics:</strong> Segment patients by treatment outcomes to evaluate the effectiveness of medical interventions.</li><li><strong>Customer Support Optimization:</strong> Segment customers based on support interaction frequency and satisfaction levels to enhance support strategies and prioritize resources.</li><li><strong>Churn Prediction:</strong> Identify customer cohorts based on churn risk factors, enabling proactive retention strategies and personalized outreach.</li></ul><h3>Setting Up the Cohort Builder</h3><p><strong>Pre-requisites:</strong></p><ul><li><strong>Work with Org Admin:</strong> Collaborate with your organization’s admin to set up the Cohort Builder on your account or to obtain the necessary permissions to set it up yourself.</li><li><strong>Ensure Data Access:</strong> Verify that the role you are using has access to the datasets you plan to work on. This will ensure smooth data retrieval and analysis.</li></ul><p><strong>To get started with the Cohort Builder, follow these steps:</strong></p><ol><li>Visit the solution’s <a href="https://github.com/Snowflake-Labs/sfguide-cohort-builder">github repository</a></li><li><strong>Run Setup Script:</strong> Execute sql/app_setup.sql as ACCOUNTADMIN in your Snowflake account to initialize the necessary database and schema.</li><li><strong>Access the Database:</strong> Set your role to COHORT_BUILDER_ROLE in Snow sight, then navigate to the COHORT_BUILDER_FOR_SNOWFLAKE database and select the APP schema.</li><li><strong>Upload Files to Stage:</strong> Go to the Stages section, choose STAGE_COHORT_BUILDER, and upload the required files from the Git repository. Ensure the stage contents match the example provided.</li><li><strong>Launch the Application:</strong> In the Projects section, select the Streamlit and open the COHORT_BUILDERapp and follow the in-app instructions to begin building, managing, and scheduling your cohorts.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*fyzPUxabn5iH8diJ.png" /></figure><h3>Steps Involved in Creating Cohorts on the Build Cohort Page</h3><h3>Select Dataset</h3><ul><li><strong>Choose Data Source:</strong> Begin by selecting the dataset you want to use for cohort creation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*f2I1jjugjnHmqmUW.png" /></figure><h3>Data Dictionary (Select Primary and Secondary Filters)</h3><ul><li><strong>Explore Data Attributes:</strong> Review the data dictionary to understand the available fields and their definitions.</li><li><strong>Select Primary Filters:</strong> Choose the core attributes that define the primary characteristics of the cohort, such as AGE_CODE, GENDER, and STATE_CODE.</li><li><strong>Select Secondary Filters:</strong> Identify additional criteria that refine the cohort, such as EMAIL_CLICK_COUNT, LAST_TICKET_PURCHASE_DATE, or EXCLUSIVE_OFFERS. These filters allow for more granular segmentation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*yXjdZNMJMPAT9WcT.png" /></figure><h3>Build Cohort</h3><ul><li><strong>Apply Filters:</strong> Implement the selected primary and secondary filters to define the cohort. Set specific conditions for each filter, such as age ranges or behavior thresholds.</li><li><strong>Preview and Adjust:</strong> Review a sample of the cohort data to ensure the filters are correctly applied. Make any necessary adjustments to refine the selection.</li><li><strong>Save Cohort:</strong> Name the cohort and save the defined criteria for future reference or modification.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*u7GjWCTPdbe4GDPl.png" /></figure><h3>Schedule Cohort</h3><ul><li><strong>Set Update Frequency:</strong> Schedule the cohort to be updated at regular intervals (e.g., daily, weekly, monthly). This ensures that the cohort data remains current and relevant.</li><li><strong>Configure Automation:</strong> Utilize Snowflake’s dynamic tables, tasks, and procedures to automate the cohort refresh process, minimizing manual intervention and maintaining data accuracy.</li></ul><h3>Managing and Viewing Your Existing Cohorts</h3><p>The <strong>Existing Cohorts</strong> page provides a comprehensive overview of all created cohorts, displaying key details such as names, and back-end queries. It allows users to view, manage, and update cohorts, ensuring efficient organization and access to relevant data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*C2fSFO-AO_EGQ6Ni.png" /></figure><h3>Conclusion</h3><p>The Cohort Builder simplifies the complex process of cohort creation and management, enabling businesses to make data-driven decisions with confidence. By automating cohort updates, it ensures that you are always taking actions based on the most current data. Whether you’re aiming to optimize marketing strategies, improve product offerings, or analyze healthcare data, the Cohort Builder provides a versatile solution for managing customer data.</p><p>If you’d like assistance in customizing your own Cohort Builder, reach out to your Sales team.</p><p><em>Disclaimer: The opinions expressed in this post are my own and not necessarily those of my employer (Snowflake).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4f0137068a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/cohort-builder-streamlining-data-segmentation-with-streamlit-and-snowflake-f4f0137068a0">Cohort Builder: Streamlining Data Segmentation with Streamlit and Snowflake</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Empowering Retailers: A Comprehensive Guide to Market Basket Analysis with Snowflake]]></title>
            <link>https://medium.com/snowflake/empowering-retailers-a-comprehensive-guide-to-market-basket-analysis-with-snowflake-3c5f5ce28298?source=rss-198ccd09af11------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c5f5ce28298</guid>
            <category><![CDATA[retail]]></category>
            <category><![CDATA[snowpark]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Adithya Nanduri]]></dc:creator>
            <pubDate>Sat, 24 Feb 2024 17:42:02 GMT</pubDate>
            <atom:updated>2024-02-24T17:42:02.013Z</atom:updated>
            <content:encoded><![CDATA[<p>You know that feeling when the latest iPhone drops, and suddenly, you’re glued to Apple and BestBuy websites, eyeing every cool feature and mentally adding it to your cart? Then suddenly, you see an array of phone cases being suggested to you. That’s the magic of MBA in action.</p><p><strong>But MBA goes beyond fancy placement.</strong> Retailers use it to uncover hidden relationships between what you buy. Think peanut butter and bread, chips and salsa, razors and shaving cream — you get the idea. These co-relations of the shopping world are revealed by MBA, allowing retailers to:</p><ul><li><strong>Craft irresistible deals:</strong> Bundle discounts on phone+case+screen protector? Yes, MBA tells them what you’re likely to buy together, then sweetens the pot with savings you can’t resist.</li><li><strong>Stock the right stuff:</strong> No more wandering aisles in search of that elusive phone charger. MBA helps retailers predict what you’ll need and keep it readily available, making your shopping trip a breeze.</li><li><strong>Personalize your experience:</strong> Imagine online stores suggesting the perfect outfit to go with those shoes you just clicked on. MBA lets the retailers tailor recommendations just for you.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjN_x1gG9gHqwD6x74z2ow.png" /><figcaption>Products before MBA</figcaption></figure><p>In this post I will show you how you can quickly run your MBA using <strong>Apriori Algorithm</strong>, powered by <strong>Snowpark ML Modeling.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*diyVjm-sErLOhymjiv6vcw.png" /><figcaption>Product associations after MBA using Apriori Algorithm</figcaption></figure><p>To demonstrate this, we’ll dive into the Acme Retail’s sales dataset, which is publicly available. As we delve into this dataset, we’ll not only explore its contents but also conduct our Market Basket Analysis (MBA). In the process we will figure out which products tend to co-sell and how we can strategically place them in retail stores.</p><h3>Initial Setup:</h3><p>Download this <a href="https://drive.google.com/file/d/1gUjKq9v7eY-fboucXYNWGIT4er___CWz/view?usp=sharing">zip file</a> and unzip the files into your working folder.</p><p>Load the data from the <strong>retail_sales.csv</strong> into your snowflake account. For the sake of this demo I am using a database called <strong>frostbyte_mba</strong> and a schema called <strong>analytics</strong>. For this exercise, we will be loading the data into a table called <strong>retail_sales_order</strong>.</p><p>The csv sales data for a retail store in New York between April 2022 and October 2022. We will be using this sample dataset for our exercise.</p><h4>Import packages:</h4><pre>## Import snowflake packages<br>from snowflake.snowpark import Session<br>from snowflake.snowpark import functions as F<br><br>## Utility packages<br>import json<br>import pandas as pd<br>import warnings<br>import numpy as np<br>warnings.filterwarnings(&quot;ignore&quot;)<br><br>## Visualization packages  <br>import matplotlib.pyplot as plt <br>plt.rc(&quot;font&quot;, size=14)<br>import seaborn as sns<br>sns.set(style=&quot;white&quot;)<br>sns.set(style=&quot;whitegrid&quot;, color_codes=True)<br><br>## Mlxtend&#39;s Apriori <br>from mlxtend.frequent_patterns import apriori, association_rules</pre><h4>Connect to Snowflake:</h4><pre>## Set snowflake connection parameters<br>connection_parameters = {<br>  &quot;account&quot;: account,<br>  &quot;user&quot;: username,<br>  &quot;password&quot;: password,<br>  &quot;role&quot;: &quot;accountadmin&quot;,<br>  &quot;warehouse&quot;: &quot;demo_build_wh&quot;,<br>  &quot;database&quot;: &quot;frostbyte_mba&quot;,<br>  &quot;schema&quot;: &quot;analytics&quot;<br>}<br><br>## Connect<br>session = Session.builder.configs(connection_parameters).create()</pre><h4>Create table:</h4><p>Run the below command in your snowflake worksheet and create the table.</p><pre>CREATE OR REPLACE TABLE frostbyte_mba.analytics.retail_sales_orders (<br> SALES_ORDER_ID BIGINT<br> ,SALES_DATE DATE<br> ,QUANTITY INT<br> ,ITEM_NAME VARCHAR(250)<br> ,ITEM_PRICE DECIMAL(38, 2)<br> ,DEPARTMENT_NAME VARCHAR(250)<br> ,CATEGORY_NAME VARCHAR(250)<br> ,COUNTRY VARCHAR(250)<br> ,REGION VARCHAR(250)<br> ,MUNICIPALITY VARCHAR(250)<br> ,LONGITUDE FLOAT<br> ,LATITUDE FLOAT<br> ,CHANNEL_NAME VARCHAR(250)<br> ,SALES_AMOUNT DECIMAL(38, 2)<br> );</pre><h4>Load data from CSV:</h4><pre># Create a stage for hosting the csv and store model files<br>stage_name = &#39;model_stage&#39;<br>session.sql(f&quot;CREATE OR REPLACE STAGE {stage_name}&quot;).collect()<br><br># Put the CSV file into the stage<br>csv_file_path = &#39;/Users/ananduri/Downloads/Testin/retail_sales.csv&#39;<br>session.sql(f&quot;PUT &#39;file://{csv_file_path}&#39; @{stage_name}&quot;).collect()<br><br># Copy data from the stage into the table<br>table_name = &#39;retail_sales_orders&#39;<br>session.sql(f&quot;&quot;&quot;<br>COPY INTO {table_name} FROM @{stage_name}<br>FILE_FORMAT = (TYPE = CSV)<br>ON_ERROR = &#39;CONTINUE&#39;<br>&quot;&quot;&quot;).collect()</pre><h3>Data Analysis using Snowpark:</h3><p>We will be using Snowpark in Snowflake to run our exploratory analysis.</p><h4>What is Snowpark?</h4><p>Snowpark in Snowflake supports lazy execution, enabling developers to build data transformations using familiar languages like Python and Java. It employs a “convert on first use” approach, where code is translated into SQL and executed when necessary, optimizing performance and providing a dynamic and efficient data processing environment within the Snowflake Data Cloud platform.</p><h4>Orders by Product Category &amp; Week:</h4><pre>## Get orders for each category in NY from April 2022 to October 2022<br>region = &quot;NY&quot;<br>category_orders_df = session.table(<br>        &quot;FROSTBYTE_MBA.ANALYTICS.RETAIL_SALES_ORDERS&quot;) \<br>        .filter((F.col(&quot;SALES_DATE&quot;) &gt;= F.lit(&quot;2022-04-01&quot;)) \<br>         &amp; (F.col(&quot;SALES_DATE&quot;) &lt; F.lit(&quot;2022-11-01&quot;)) \<br>         &amp; (F.col(&quot;REGION&quot;) == F.lit(region))) \<br>        .select( F.col(&quot;SALES_ORDER_ID&quot;), <br>                 F.col(&quot;CATEGORY_NAME&quot;),<br>                 F.to_varchar(F.col(&quot;SALES_DATE&quot;), &quot;yyyy-MM&quot;).alias(&quot;MONTH&quot;)<br>               ) \<br>        .groupBy(F.col(&quot;CATEGORY_NAME&quot;), F.col(&quot;MONTH&quot;)) \<br>        .agg(F.count_distinct(F.col(&quot;SALES_ORDER_ID&quot;)).alias(&quot;TOTAL_ORDERS&quot;)) \<br>        .sort(F.col(&quot;MONTH&quot;)).toPandas()<br><br>## Visualize the information<br>lp = sns.lineplot(data=category_orders_df, x=&quot;MONTH&quot;, y=&quot;TOTAL_ORDERS&quot;, ci=None, hue=&quot;CATEGORY_NAME&quot;)<br>lp.legend(loc=&#39;upper right&#39;, bbox_to_anchor=(1.6, 1))<br>plt.title(&quot;Category - # of Orders&quot;)<br>plt.xlabel(&quot;Time&quot;)<br>plt.ylabel(&quot;# of Orders&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*ouN0Ecve2yCsHuueF_BO8Q.png" /><figcaption>Orders by Product Category</figcaption></figure><p><strong>Dairy</strong> has seen a sharp decline in # of orders <strong>after June 2022</strong> and has not recovered. While other categories maintained their usual total orders month over month.</p><h4>Dairy Orders by Department &amp; Week:</h4><pre>## Get orders for each department in Dairy in NY from April 2022 to October 2022<br><br>dep_orders_df = session.table(<br>        &quot;FROSTBYTE_MBA.ANALYTICS.RETAIL_SALES_ORDERS&quot;) \<br>        .filter((F.col(&quot;SALES_DATE&quot;) &gt;= F.lit(&quot;2022-04-01&quot;)) \<br>         &amp; (F.col(&quot;SALES_DATE&quot;) &lt; F.lit(&quot;2022-11-01&quot;)) \<br>         &amp; (F.col(&quot;REGION&quot;) == F.lit(region))<br>         &amp; (F.col(&quot;CATEGORY_NAME&quot;) == F.lit(&quot;Dairy&quot;))) \<br>        .select( F.col(&quot;SALES_ORDER_ID&quot;), <br>                 F.col(&quot;DEPARTMENT_NAME&quot;),<br>                 F.to_varchar(F.col(&quot;SALES_DATE&quot;), &quot;yyyy-MM&quot;).alias(&quot;MONTH&quot;)<br>               ) \<br>        .groupBy(F.col(&quot;DEPARTMENT_NAME&quot;), F.col(&quot;MONTH&quot;)) \<br>        .agg(F.count_distinct(F.col(&quot;SALES_ORDER_ID&quot;)).alias(&quot;TOTAL_ORDERS&quot;)) \<br>        .sort(F.col(&quot;MONTH&quot;)).toPandas()<br><br>## Visualize the information<br>lp = sns.lineplot(data=dep_orders_df, x=&quot;MONTH&quot;, y=&quot;TOTAL_ORDERS&quot;, ci=None, hue=&quot;DEPARTMENT_NAME&quot;)<br>lp.legend(loc=&#39;upper right&#39;, bbox_to_anchor=(1.3, 1))<br>plt.title(&quot;Department - # of Orders&quot;)<br>plt.xlabel(&quot;Time&quot;)<br>plt.ylabel(&quot;# of Orders&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*TfsF-KmSjFrL082eOOm85g.png" /><figcaption>Orders by Department</figcaption></figure><p>All departments seem to have dipped. In particular, <strong>Yogurt</strong> sees the largest dip in # of orders from <strong>June 2022</strong> to <strong>July 2022</strong> and has not recovered until <strong>October 2022</strong>. The total orders have dropped by ~70% (from ~35,000 orders to ~10,000 orders)</p><h4>Item Popularity for Dairy:</h4><p>Next let’s look at the item popularity to find the most and the least popular items in Diary department.</p><pre>## Get number of orders containing each item in Dairy for NY for October 2022<br>item_orders_df = category_orders_df = session.table(<br>        &quot;FROSTBYTE_MBA.ANALYTICS.RETAIL_SALES_ORDERS&quot;) \<br>        .filter((F.col(&quot;SALES_DATE&quot;) &gt;= F.lit(&quot;2022-10-01&quot;)) \<br>         &amp; (F.col(&quot;SALES_DATE&quot;) &lt; F.lit(&quot;2022-11-01&quot;)) \<br>         &amp; (F.col(&quot;REGION&quot;) == F.lit(region))<br>         &amp; (F.col(&quot;CATEGORY_NAME&quot;) == F.lit(&quot;Dairy&quot;))) \<br>        .select( F.col(&quot;SALES_ORDER_ID&quot;), <br>                 F.col(&quot;ITEM_NAME&quot;)) \<br>        .groupBy(F.col(&quot;ITEM_NAME&quot;)) \<br>        .agg(F.count_distinct(F.col(&quot;SALES_ORDER_ID&quot;)).alias(&quot;TOTAL_ORDERS&quot;)) \<br>        .toPandas().sort_values(&quot;TOTAL_ORDERS&quot;,ascending=False)<br><br>## Visualize the information from above cell<br>x = item_orders_df[&quot;ITEM_NAME&quot;]<br>y = item_orders_df[&quot;TOTAL_ORDERS&quot;]<br>plt.title(&quot;Item popularity&quot;)<br>ax = sns.barplot(y= &quot;ITEM_NAME&quot;,x = &quot;TOTAL_ORDERS&quot;, data = item_orders_df, orient=&#39;h&#39;, ci=None)<br>plt.xlabel(&quot;# of Orders&quot;)<br>plt.ylabel(&quot;Item&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*DgX9GUSFRylwsKyja68VMg.png" /><figcaption>Item Popularity in Dairy</figcaption></figure><p>We can see that Butter- Unsalted, Eggs- Dozen, Almond Milk Unsweetened, Cheddar Cheese and Organic Milk are some of the most popular items within the Dairy Department.</p><p>Gogurt, Greek Yogurt- Vanilla, Greek Yogurt- Plain, Eggs- 18 Pack are some of the lease popular items.</p><h3>Machine Learning Model:</h3><p>We will be using the current sales data at hand and create a python stored procedure for getting the association rules. The stored procedure will leverage mlxtends implementation of the APRIORI algorithm to get the association rules from the transactional data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wk1VSo0VUzlDnRR70KTi_g.png" /><figcaption>ML Model for generating association rules</figcaption></figure><pre>## Create and register stored procedure which mines asscociation rule for a given month, region and category.<br><br>@F.sproc(name=&quot;association_rules_sp&quot;,<br>         is_permanent=True,<br>         stage_location=&quot;@model_stage&quot;,<br>         packages = [&#39;snowflake-snowpark-python&#39;,&#39;pandas&#39;],<br>         imports = [&#39;mlxtend&#39;],<br>         replace=True,<br>         session=session)<br>def get_association_rules(session: Session, time_period: str, region: str, category: str) -&gt; str:<br>    <br>    ## Import required packages<br>    from mlxtend.frequent_patterns import apriori, association_rules<br>    import pandas as pd<br>    <br>    ## Read data into Snowpark dataframe<br>    if category == &#39;Cross-category&#39;:<br>        df_sales_order = session.table(<br>        &quot;FROSTBYTE_MBA.ANALYTICS.RETAIL_SALES_ORDERS&quot;) \<br>        .filter(( F.to_varchar(F.col(&quot;SALES_DATE&quot;), &quot;yyyy-MM&quot;) == F.lit(time_period)) \<br>         &amp; (F.col(&quot;REGION&quot;) == F.lit(region))) \<br>        .select([&quot;SALES_ORDER_ID&quot;,&quot;ITEM_NAME&quot;,&quot;QUANTITY&quot;])<br>    else:<br>        df_sales_order = session.table(<br>        &quot;FROSTBYTE_MBA.ANALYTICS.RETAIL_SALES_ORDERS&quot;) \<br>        .filter(( F.to_varchar(F.col(&quot;SALES_DATE&quot;), &quot;yyyy-MM&quot;) == F.lit(time_period)) \<br>         &amp; (F.col(&quot;REGION&quot;) == F.lit(region)) \<br>         &amp; (F.col(&quot;CATEGORY_NAME&quot;) == F.lit(category))) \<br>        .select([&quot;SALES_ORDER_ID&quot;,&quot;ITEM_NAME&quot;,&quot;QUANTITY&quot;])<br><br>    ## Prepare data for market basket analysis <br>    basket_NY = (df_sales_order.to_pandas().groupby([&quot;SALES_ORDER_ID&quot;,&quot;ITEM_NAME&quot;])[&quot;QUANTITY&quot;] \<br>                 .sum().unstack().reset_index() \<br>                 .fillna(0) \<br>                 .set_index(&quot;SALES_ORDER_ID&quot;))<br><br>    ## Create sparse matrix from order data <br>    basket_NY = basket_NY.applymap(lambda x: True if x &gt; 0 else False)<br><br>    ## Get asscociation rules using Apriori <br>    frq_items = apriori(basket_NY, min_support = 0.008, use_colnames = True, low_memory = True)<br>    rules = association_rules(frq_items, metric = &quot;lift&quot;, min_threshold = 1)<br>    rules[&quot;antecedents&quot;] = rules[&quot;antecedents&quot;].apply(lambda x: &#39;, &#39;.join(list(x))).astype(&quot;unicode&quot;)<br>    rules[&quot;antecedents length&quot;] = rules[&quot;antecedents&quot;].apply(lambda x: len(x.split(&#39;,&#39;)))<br>    rules[&quot;consequents&quot;] = rules[&quot;consequents&quot;].apply(lambda x: &#39;, &#39;.join(list(x))).astype(&quot;unicode&quot;)<br>    rules[&quot;consequents length&quot;] = rules[&quot;consequents&quot;].apply(lambda x: len(x.split(&#39;,&#39;)))<br>    df = pd.DataFrame(rules)<br>    df[&quot;time period&quot;] = time_period<br>    df[&quot;region&quot;] = region<br>    df[&quot;category name&quot;] = category<br>    df = df[df[&quot;antecedents&quot;] != df[&quot;consequents&quot;]]<br>    <br>    ##Persist result to tables <br>    if len(df) &gt; 0 :<br>        session.write_pandas(df, &quot;ASSOCIATION_RULES_REGION_CAT_MONTHLY&quot;, <br>                             auto_create_table = True,<br>                             database=&quot;FROSTBYTE_MBA&quot;,<br>                             schema=&quot;ANALYTICS&quot;) <br>    <br>    return &quot;# of association rules found : &quot; + str(len(df))</pre><p>This stored procedure will produce the necessary association rules and write it back to a table called <strong>association_rules_region_cat_monthly</strong>.</p><h3>Analyze the Association Rules:</h3><p>For this we will first call the stored procedure we built above. We will be running our analysis on the just the last month of sales data we have.</p><pre>## Calling the procedure<br>session.sql(&#39;&#39;&#39;CALL association_rules_sp(&#39;2022-10&#39;,&#39;NY&#39;,&#39;Dairy&#39;)&#39;&#39;&#39;).show()<br><br>## Association Rules Output<br>rules = session.table(&quot;FROSTBYTE_MBA.ANALYTICS.ASSOCIATION_RULES_REGION_CAT_MONTHLY&quot;)\<br>        .toPandas()<br>rules.sort_values(by=&#39;confidence&#39;, ascending=False).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aYIMwnpjA5LXjT8OR7b6sg.png" /><figcaption>Association rules</figcaption></figure><ul><li><strong>Support (1.71%)</strong>: Approximately <strong>1.71</strong>% of all transactions contain both “Almond Milk Vanilla” and “Butter- Unsalted”. It represents the frequency of occurrence of this specific combination in the dataset.</li><li><strong>Confidence (88.84%)</strong>: The confidence of <strong>88.84</strong>% suggests that out of all transactions containing “Butter- Unsalted”, <strong>88.84</strong>% also contain “Almond Milk Vanilla”. It measures how often the association rule is correct.</li><li><strong>Lift (2.77)</strong>: The lift value of <strong>2.77</strong> indicates that the occurrence of “Almond Milk Vanilla” and “Butter- Unsalted” together is about <strong>2.77</strong> times more likely than if they were independent. It measures the strength of the association between the two items. A lift value greater than 1 indicates a positive association.</li></ul><p>Now let’s look at the associations where high and low performing products are matched together.</p><pre>df = rules[(rules[&quot;antecedents length&quot;] == 1 ) \<br>      &amp; (rules[&quot;consequents length&quot;] == 1) \<br>      &amp; (rules[&quot;consequent support&quot;] &lt; rules[&quot;antecedent support&quot;]) \<br>      &amp; (rules[&quot;consequents&quot;].isin(list(item_orders_df.tail(5)[&quot;ITEM_NAME&quot;])))] \<br>.sort_values([&quot;consequent support&quot;,&quot;antecedent support&quot;],ascending=[True,False]) \<br>.drop([&quot;antecedents length&quot;,&quot;consequents length&quot;,&quot;time period&quot;,&quot;region&quot;,&quot;category name&quot;], axis=1) \<br>[[&quot;antecedents&quot;,&quot;consequents&quot;,&quot;lift&quot;,&quot;consequent support&quot;,&quot;antecedent support&quot;]] \<br>.sort_values([&quot;consequent support&quot;,&quot;lift&quot;],ascending=[True,False]) \<br>.groupby(&quot;consequents&quot;).head(1)<br><br><br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cH4fJj5vopH1YX8VWCs4A.png" /></figure><p>We can see from the above output that <strong>Greek Yogurt — Vanilla</strong> (one of the most unpopular Yogurt department within Dairy category item) is positively associated (based on lift metric &gt; 1) with <strong>Eggs — Dozen</strong> (one of the popular items in Diary). So, placing them together should drive up the sale of <strong>Greek Yogurt — Vanilla</strong>.</p><p>We can also see a similar association between <strong>Almond Milk Unsweetened</strong> and <strong>Greek Yoguet — Plain</strong>. So, placing these two together should drive up the sales on <strong>Greek Yoguet — Plain.</strong></p><p>We can further enhance this by visualizing association rule metrics like support, confidence, and lift, enabling intuitive dashboards or creating application that will help us understand our model results better.</p><p><strong>Power BI Dashboards:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K5IUi0OtWN0s9tcGPnVsRA.png" /><figcaption>Power BI dashboard</figcaption></figure><p><strong>Streamlit Application:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcIChIn_7nMxSyq8u7QQxw.png" /><figcaption>Streamlit Recommendation Application</figcaption></figure><h3>Synopsis:</h3><p>We demonstrated how you can easily run Market Basket Analysis (MBA) to craft compelling deals, optimize inventory management and delivery personalized shopping experiences in <strong>Snowflake.</strong></p><p>Below are some of the Snowflake features that we have used for this exercise:</p><ol><li><strong>Scalability</strong>: Snowflake handles large data volumes effortlessly through horizontal scaling, allowing ML models to process extensive datasets without hardware limitations.</li><li><strong>Separation of Storage and Compute</strong>: Snowflake’s architecture separates storage and compute resources, enabling independent scaling based on workload needs. This ensures ML models access data without compute resource constraints.</li><li><strong>Native Integrations</strong>: Snowflake seamlessly integrates with popular ML frameworks like TensorFlow, PyTorch, and scikit-learn, facilitating streamlined ML workflows within the Snowflake environment.</li><li><strong>Security and Compliance</strong>: Snowflake boasts robust security features, including encryption and role-based access control, ensuring that sensitive ML data is protected and compliant with regulations like SOC 2 and GDPR.</li><li><strong>Performance Optimization</strong>: Snowflake’s query optimization and caching enhance the performance of ML tasks. By optimizing query execution plans and caching frequently accessed data, Snowflake ensures efficient ML workload execution with minimal latency.</li></ol><h3>Contact Snowflake:</h3><p>Solution designed and developed by team frostbyte and Snowflake industry experts: <a href="https://www.linkedin.com/in/shriyarai/"><strong>Shriya Rai</strong></a>, <a href="https://www.linkedin.com/in/adithya-nanduri-bb904a194/"><strong>Adithya Nanduri</strong></a>, and <a href="https://www.linkedin.com/in/robert-guglietti-21a7803/"><strong>Robert Guglietti</strong></a>.</p><p>Web: <a href="https://www.snowflake.com/contact/">https://www.snowflake.com/contact/</a><br>Email: <a href="/service/mailto:se-sit-frostbyte-DL@snowflake.com">se-sit-frostbyte-DL@snowflake.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c5f5ce28298" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/empowering-retailers-a-comprehensive-guide-to-market-basket-analysis-with-snowflake-3c5f5ce28298">Empowering Retailers: A Comprehensive Guide to Market Basket Analysis with Snowflake</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quote Manipulation Detection in the Finance Industry using Snowflake]]></title>
            <link>https://medium.com/snowflake/quote-manipulation-detection-in-the-finance-industry-using-snowflake-e87e73a60952?source=rss-198ccd09af11------2</link>
            <guid isPermaLink="false">https://medium.com/p/e87e73a60952</guid>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[snowpark]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Adithya Nanduri]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 22:07:32 GMT</pubDate>
            <atom:updated>2024-02-23T22:07:32.305Z</atom:updated>
            <content:encoded><![CDATA[<p>Written By: <a href="https://www.linkedin.com/in/adithya-nanduri-bb904a194/"><strong>Adithya Nanduri</strong></a> &amp; <a href="https://www.linkedin.com/in/shriyarai/"><strong>Shriya Rai</strong></a></p><p>The finance industry is a complex landscape involving various entities managing the seamless flow of money. Within this, the <strong>auto insurance</strong> sector is vital for protecting drivers and their assets.</p><p>Auto insurance industry deals with a complex web of issues.</p><ul><li>Surge in uninsured motorists due to economic hardships and rising premiums.</li><li>Financial strain on responsibly insured drivers and introduces complications in the claims processes for insurance companies.</li><li>Policies and regulations are yet to fully adapt to the intricacies of accidents involving cutting-edge automated vehicles.</li><li>A pivotal concern within this landscape is quote manipulation, where individuals deceitfully manipulate information during the insurance quoting process.</li></ul><p>Let’s dive deeper into quote manipulation. Dishonest individuals manipulate information when requesting auto insurance quotes, aiming to secure lower premiums. This poses a dual threat — compromising the profitability of insurance companies and potentially resulting in higher premiums for honest customers. Detecting and preventing such fraudulent activities remains an ongoing challenge for the industry.</p><p>Some technical challenges faced by the data teams in the industry are</p><ul><li><strong>Unified Platform</strong> — not able get data from all the sources and combining them with third party datasets</li><li><strong>Data Sharing</strong> — Challenges in sharing data with different teams within the organization</li><li><strong>Data Compliance </strong>— being able to create masking policies , role based access rules when dealing with PII data</li><li><strong>Complex Data</strong> — Handling semi-structured data and converting it into a tabular form</li><li>Some of the other problems are having delayed access to data , not getting the data in a simplified or needed format</li></ul><p>In this article, we delve into the efforts of FrostByte team which partnered with a UK based company to address the issue of quote manipulation.</p><p>Our objective extends beyond merely addressing quote manipulation; we aim to leverage the robust capabilities and resources within Snowflake to illuminate innovative solutions, that will help solve some of the technical difficulties faced by the industry.</p><p>Let us first take a look at the Reference Architecture for the end-to-end data pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7eBN2OVuFrq3gLeZ.png" /></figure><p>As you can see from the architecture diagram there are 3 data sources we will be using for this solution</p><ul><li>First party data streaming in from the front end application.</li><li>Historical first party datasets from the blob storage/data lake.</li><li>The third data sets from Snowflake’s Marketplace dataset.</li></ul><h3>End-To-End Flow</h3><ul><li>The customer comes in a submits a quote in the front end application</li><li>This customer data is compared with the total population of customer data, we can identify a customer using first name, last name , postal code and age</li><li>We then enhance this data using third party data sets available in snowflake’s marketplace</li><li>After this we run feature engineering modules and run quote manipulation detection to produce anomaly scores for each customer</li><li>Dashboards are created from the outputs of machine learning that provide the sales and marketing teams with 360 customer view</li><li>Finally we enable management to determine corrective programs to address potential quote manipulation challenges and help drive price optimization</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7JKNOPz7C6yBHFPD.png" /></figure><h3>Data Pipelines</h3><p>In the auto industry, dealing with complex semi-structured data poses significant challenges due to the diverse and varied nature of information generated across the automotive ecosystem. This data may include vehicle specifications, maintenance records, customer interactions, and more, often in different formats such as JSON or XML. Navigating through this intricate web of data can be time-consuming and labor-intensive, requiring advanced tools for efficient processing and analysis.</p><p>However Snowflake’s support for semi-structured data formats like JSON &amp; XML allows flexibility in data modeling. The platform accommodates changes in data structure without requiring a predefined schema, making it adaptable to the dynamic nature of auto industry data.</p><p>For example, quotes data is a complex XML file with multiple layers and sub nodes , lets take a look at the code for one of the tables to see how we are converting the semi-structured data into tabular form</p><p>Below is a example of how the Drivers node looks like in the quotes data.</p><pre>&lt;Drivers&gt;<br>    &lt;Driver&gt;<br>     &lt;Driver_Prn Val=&quot;1&quot; /&gt;<br>     &lt;Driver_DrivesVehicle1Ind Val=&quot;M&quot; /&gt;<br>     &lt;Driver_ClassOfUse Val=&quot;04&quot; /&gt;<br>     &lt;Driver_RelationshipToProposer Val=&quot;P&quot; /&gt;<br>     &lt;Driver_NoOfOtherVehiclesDriven Val=&quot;0&quot; /&gt;<br>     &lt;Driver_MotoringOrganisationMembership Val=&quot;99&quot; /&gt;<br>     &lt;Driver_Sex Val=&quot;REDACTED&quot; /&gt;<br>     &lt;Driver_DateOfBirth Val=&quot;1989-12-17T00:00:00&quot; /&gt;<br>     &lt;Driver_UkResidencyDate Val=&quot;2005-07-14T00:00:00&quot; /&gt;<br>     &lt;Driver_ResidentOutsideUkInd Val=&quot;N&quot; /&gt;<br>     &lt;Driver_MaritalStatus Val=&quot;M&quot; /&gt;<br>     &lt;Driver_RefusedCoverInd Val=&quot;N&quot; /&gt;<br>     &lt;Driver_ClaimsInd Val=&quot;N&quot; /&gt;<br>     &lt;Driver_ConvictionsInd Val=&quot;N&quot; /&gt;<br>     &lt;Driver_MedicalConditionInd Val=&quot;N&quot; /&gt;<br>     &lt;ClaimConvictionCountsList&gt;<br>      &lt;ClaimConvictionCounts&gt;<br>       &lt;ClaimConvictionCounts_AlrCode Val=&quot;01&quot; /&gt;<br>       &lt;ClaimConvictionCounts_AlrClaimsFire Val=&quot;0&quot; /&gt;<br>       &lt;ClaimConvictionCounts_AlrClaimsTheft Val=&quot;0&quot; /&gt;<br>      &lt;/ClaimConvictionCounts&gt;<br>      &lt;ClaimConvictionCounts&gt;<br>       &lt;ClaimConvictionCounts_AlrCode Val=&quot;10&quot; /&gt;<br>       &lt;ClaimConvictionCounts_AlrClaimsFire Val=&quot;0&quot; /&gt;<br>       &lt;ClaimConvictionCounts_AlrClaimsTheft Val=&quot;0&quot; /&gt;<br>      &lt;/ClaimConvictionCounts&gt;<br>     &lt;/ClaimConvictionCountsList&gt;<br>     &lt;DrivesVehicle&gt;<br>      &lt;DrivesVehicle_DrivingFrequency Val=&quot;M&quot; /&gt;<br>      &lt;DrivesVehicle_DriverIsRatee Val=&quot;Y&quot; /&gt;<br>     &lt;/DrivesVehicle&gt;<br>     &lt;Occupations&gt;<br>      &lt;Occupation&gt;<br>       &lt;Occupation_Code Val=&quot;74C&quot; /&gt;<br>       &lt;Occupation_EmploymentType Val=&quot;F&quot; /&gt;<br>       &lt;Occupation_EmployersBusiness Val=&quot;950&quot; /&gt;<br>       &lt;Occupation_FullTimeEmploymentInd Val=&quot;Y&quot; /&gt;<br>      &lt;/Occupation&gt;<br>     &lt;/Occupations&gt;<br>    &lt;/Driver&gt;<br>    &lt;Driver&gt;<br>     &lt;Driver_Prn Val=&quot;2&quot; /&gt;<br>     &lt;Driver_DrivesVehicle1Ind Val=&quot;F&quot; /&gt;<br>     &lt;Driver_ClassOfUse Val=&quot;04&quot; /&gt;<br>     &lt;Driver_RelationshipToProposer Val=&quot;M&quot; /&gt;<br>     &lt;Driver_NoOfOtherVehiclesDriven Val=&quot;1&quot; /&gt;<br>     &lt;Driver_MotoringOrganisationMembership Val=&quot;99&quot; /&gt;<br>     &lt;Driver_Sex Val=&quot;REDACTED&quot; /&gt;<br>     &lt;Driver_DateOfBirth Val=&quot;a56e0e6d69ddd38c947b0309e10fb061f62c730d7f43b0d21bfcd6c277eb6d29&quot; /&gt;<br>     &lt;Driver_UkResidencyDate Val=&quot;1975-08-21T00:00:00&quot; /&gt;<br>     &lt;Driver_ResidentOutsideUkInd Val=&quot;N&quot; /&gt;<br>     &lt;Driver_MaritalStatus Val=&quot;c8d38b3ebec884d17b9b8a5bb64b7968b5aff5753d03835a8fd37e190e7d3e0f&quot; /&gt;<br>     &lt;Driver_RefusedCoverInd Val=&quot;N&quot; /&gt;<br>     &lt;Driver_ClaimsInd Val=&quot;N&quot; /&gt;<br>     &lt;Driver_ConvictionsInd Val=&quot;N&quot; /&gt;<br>     &lt;ClaimConvictionCountsList&gt;<br>      &lt;ClaimConvictionCounts&gt;<br>       &lt;ClaimConvictionCounts_AlrCode Val=&quot;01&quot; /&gt;<br>       &lt;ClaimConvictionCounts_AlrClaimsFire Val=&quot;0&quot; /&gt;<br>       &lt;ClaimConvictionCounts_AlrClaimsTheft Val=&quot;0&quot; /&gt;<br>       &lt;ClaimConvictionCounts_AlrClaimsFault Val=&quot;0&quot; /&gt;<br>       &lt;ClaimConvictionCounts_AlrClaimsNonFault Val=&quot;0&quot; /&gt;<br>       &lt;ClaimConvictionCounts_AlrClaimsWindscreen Val=&quot;0&quot; /&gt;<br>       &lt;ClaimConvictionCounts_AlrClaimsTotal Val=&quot;0&quot; /&gt;<br>      &lt;/ClaimConvictionCounts&gt;<br>     &lt;/ClaimConvictionCountsList&gt;<br>     &lt;DrivesVehicle&gt;<br>      &lt;DrivesVehicle_DrivingFrequency Val=&quot;F&quot; /&gt;<br>     &lt;/DrivesVehicle&gt;<br>     &lt;Occupations&gt;<br>      &lt;Occupation&gt;<br>       &lt;Occupation_Code Val=&quot;456&quot; /&gt;<br>       &lt;Occupation_EmploymentType Val=&quot;E&quot; /&gt;<br>       &lt;Occupation_EmployersBusiness Val=&quot;018&quot; /&gt;<br>       &lt;Occupation_FullTimeEmploymentInd Val=&quot;Y&quot; /&gt;<br>      &lt;/Occupation&gt;<br>     &lt;/Occupations&gt;<br>    &lt;/Driver&gt;<br>   &lt;/Drivers&gt;</pre><p>The XML for quotes here has multiple subnodes within it. We first extract the node PolicyInfo, then extract the PolData node from it. Finally we get to the Drivers node.</p><pre>SELECT rts.uuid as UUID<br>      ,PARSE_XML(flt.value) as RTS_Driver_vrnt<br>      ,XMLGET(RTS_Driver_vrnt,&#39;Driver_LicenceValidatedIndList&#39;) as RTS_DriverLicense_vrnt<br>      ,XMLGET(RTS_Driver_vrnt,&#39;LicenceRestrictionsList&#39;) as RTS_DriverLicenseRestriction_vrnt<br>      ,XMLGET(RTS_Driver_vrnt,&#39;MedicalConditionList&#39;) as RTS_DriverMedical_vrnt<br>      ,XMLGET(RTS_Driver_vrnt,&#39;Occupations&#39;) as RTS_DriverOccupation_vrnt<br>      ,XMLGET(RTS_Driver_vrnt,&#39;Qualifications&#39;) as RTS_DriverQualification_vrnt <br>      ,XMLGET(RTS_Driver_vrnt,&#39;Incidents&#39;) as RTS_DriverIncidents_vrnt<br>      ,XMLGET(RTS_Driver_vrnt,&#39;InsurerRatingFactors&#39;) as RTS_InsurerRatingFactors_vrnt <br>      ,XMLGET(RTS_Driver_vrnt,&#39;QuoteBreakdownResult&#39;) as RTS_QuoteBreakdown_vrnt<br>      ,XMLGET(RTS_Driver_vrnt,&#39;Driver_Prn&#39;):&quot;@Val&quot;::string as Driver_Prn<br>      ,XMLGET(RTS_Driver_vrnt,&#39;Driver_AnnualMileage&#39;):&quot;@Val&quot;::string as AnnualMileage<br>      ,XMLGET(RTS_Driver_vrnt,&#39;Driver_ClaimsInd&#39;):&quot;@Val&quot;::string as ClaimsInd<br>      ,XMLGET(RTS_Driver_vrnt,&#39;Driver_ConvictionsInd&#39;):&quot;@Val&quot;::string as ConvictionsInd<br>FROM frostbyte_qm.raw.quotes_xml rts<br>    ,LATERAL FLATTEN(TO_ARRAY(XMLGET(XMLGET(XMLGET(PARSE_XML(message), &#39;PolicyInfo&#39;), &#39;PolData&#39;),&#39;Drivers&#39;):&quot;$&quot;)) flt<br>WHERE xml_type = &#39;Request to service&#39;;</pre><p>In order to get the information of multiple drivers as you can see in the above code we are using LATERAL FLATTEN function to parse the XML and convert the semi structured data into tabular form</p><p>Combining this with Snowflake’s Dynamic tables &amp; Streams &amp; Tasks makes the data pipeline management and development very seemless.</p><h4><strong>Snowflake takeaways:</strong></h4><ul><li>Powerful in built functions like LATERAL FLATTEN , XMLGET , PARSEXML make converting the semi structured data into tabular form very easy</li><li>Automating the pipelines with dynamic table using lag with a minimum time of 1 min which gives us almost instant access to new quotes that are coming in , the lag time is flexible in our solution we have set the lag time for policy tables as 24 hrs . The Dynamic tables can be designed and structured according to your own business need</li><li>Streams and Tasks enable the upstream tables to be refreshed when ever the base table has new data in it.</li></ul><p>For more information on dynamic tables you can take a look at the documentation <a href="https://docs.snowflake.com/en/user-guide/dynamic-tables-about">here</a>.</p><h3>Data Science Pipeline</h3><p>Here is how the architecture for the data science pipeline looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1VkZl9EnckL_vltI.png" /></figure><ul><li>Through dynamic tables, Snowflake streams, and tasks, we transform raw data to create a comprehensive quote summary table.</li><li>Fuzzy matching is employed for user identification using email and IP address data.</li><li>The quote summary table consists of individual rows for each user accepted policy.</li><li>Over 150 features are engineered from a mix of first-party and third-party datasets from the Snowflake Marketplace.</li><li>Features encompass various metrics like the number of quotes submitted, total claims, credit score, age, etc.</li><li>Specific details such as the number of changes to date of birth and credit score are also included.</li><li>This approach provides a detailed and nuanced understanding of user profiles.</li><li>This data is made available to the data science team as a view “<strong>QUOTE_SUMMARY_V</strong>”.</li></ul><p>Let’s look on what the data science team has done to implement quote manipulation detection for an accepted policy to identify fraudulent activity</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qbYPK1f41jv8aw1h" /></figure><h3>Data Prep using Snowpark Dataframe &amp; Snowpark ML</h3><p>We prep input data using Snowpark &amp; Snowpark ML Preprocessing allowing us to push down operation to Snowflake compute while taking advantage of the security and governance provided by Snowflake with no data movement outside of our environment.</p><ul><li><strong>Import Packages: </strong>We import the Snowpark packages similar to any other python package. We will also be importing <strong><em>Snowpark ML Modeling</em></strong> which is a collection of Python APIs for preprocessing data and training models.</li></ul><pre># Import Snowflake modules<br>from snowflake.snowpark import Session<br>from snowflake.snowpark import Window<br>import snowflake.snowpark.functions as F<br>from snowflake.snowpark.functions import max as max_, min as min_, when<br>import snowflake.snowpark.types as T<br># Import Snowpark ML modules<br>from snowflake.ml.modeling.ensemble import IsolationForest<br>from snowflake.ml.modeling.preprocessing import LabelEncoder</pre><ul><li><strong>Connect to Snowflake:</strong></li></ul><p>We will use our Snowflake account credentials to connect to Snowflake and create a Snowpark session. We use our Data Scientist Snowflake role, to connect to our database and will be leveraging our dedicated compute for data science workloads.</p><pre># Get account credentials from json file<br>with open(&quot;data_scientist_auth.json&quot;) as f:<br>    data = json.load(f)<br>    username = data[&quot;username&quot;]<br>    password = data[&quot;password&quot;]<br>    account = data[&quot;account&quot;]<br><br># Specify connection parameters<br>connection_parameters = {<br>    &quot;account&quot;: account,<br>    &quot;user&quot;: username,<br>    &quot;password&quot;: password,<br>    &quot;role&quot;: &quot;DATA_SCIENTIST&quot;,<br>    &quot;warehouse&quot;: &quot;DS_WH&quot;,<br>    &quot;database&quot;: &quot;FROSTBYTE_QM&quot;,<br>    &quot;schema&quot;: &quot;ANALYTICS&quot;,<br>}# Create Snowpark session<br>session = Session.builder.configs(connection_parameters).create()</pre><ul><li><strong>Read the input data</strong>: We create a Snowpark dataframe to read in our input data.</li></ul><pre>key_cols = [&#39;CUSTID&#39;,&#39;POLICY_BATCHID&#39;,&#39;ACCEPTEDQUOTE_UUID&#39;] <br>cat_cols = [&#39;MODEL&#39;,&#39;LOCATIONKEPTOVERNIGHT&#39;,&#39;VEHICLEKEPTDAYTIME&#39;,&#39;LICENCETYPE&#39;,&#39;TRANSMISSIONTYPE&#39;,&#39;TYPEOFFUEL&#39;, \<br>            &#39;OWNERSHIP&#39;,&#39;INSURERDERIVEDCLASSOFUSE&#39;,&#39;OCCUPATION_CODE1&#39;,&#39;EMPLOYERSBUSINESS1&#39;,\<br>            &#39;OCCUPATION_CODE2&#39;,&#39;EMPLOYERSBUSINESS2&#39;,&#39;VECHICLEPOSTCODE&#39;]<br>date_cols = [&#39;PURCHASEDATE&#39;,&#39;FIRSTREGDYEAR&#39;,&#39;LICENSEDATE&#39;]<br>pii_cols = [&#39;MARITALSTATUS&#39;,&#39;SEX&#39;]<br>num_cols = [&#39;DEBITFRQCY&#39;,&#39;NOOFOTHERVEHICLESOWNED&#39;,&#39;ANNUALMILEAGE&#39;,&#39;NOOFOTHERVEHICLESDRIVEN&#39;,&#39;VEHICLEANNUALMILEAGE&#39;, \<br>            &#39;NOOFSEATS&#39;,&#39;VEHICLEVALUE&#39;,&#39;MILEOMETERREADING&#39;,&#39;NCD_CLAIMEDYEARS&#39;,&#39;CREDITSCORE&#39;,&#39;TOTALPREMIUMPAYABLE&#39;, \<br>            &#39;NOOFCHILDREN&#39;,&#39;NOCLAIMS&#39;,&#39;NOCONVICTIONS&#39;,&#39;NOMEDICALCONDITIONS&#39;,&#39;NOPENALTYPOINTS&#39;,&#39;NUMOFQUALIFICATIONS&#39;] <br>ord_cols = [&#39;AGE_BUCKET&#39;]<br>change_cols = [col for col in quotes_df.columns if &#39;_CHANGE&#39; in col] + [&#39;QUOTE_COUNT&#39;,&#39;IPLOCATION_COUNT&#39;]<br>ind_cols = list(set([col for col in quotes_df.columns if &#39;IND&#39; in col]) - set(change_cols))<br>diff_cols = [col for col in quotes_df.columns if &#39;_DIFF&#39; in col]<br>first_df = quotes_df.select(key_cols + cat_cols + ind_cols + date_cols + pii_cols + num_cols + ord_cols) <br>sec_df= quotes_df.select(key_cols + change_cols + diff_cols)</pre><p><strong>NOTE:</strong> <em>The columns used above are subject to the dataset we used for the quote manipulation detection, you should be able to adjust them to your dataset and requirements.</em></p><ul><li><strong>Impute Missing Indices using Snowpark:</strong> Identify and replace any nulls in the data.</li></ul><pre># Fill nulls with &quot;U&quot; using Snowpark&#39;s inbuilt function fillna<br>df = df.fillna(value=&quot;U&quot;, subset=ind_cols)</pre><ul><li><strong>Encode Categorical columns: </strong>Many of the columns have textual data we will have to represent these categorical columns as numeric for our model. We leverage<strong><em> Snowflake ML Preprocessing Label Encoder </em></strong>to achieve this representation.</li></ul><pre>cat_enc_df = df.select(cat_cols + key_cols)<br>for inp_col in cat_cols:<br>    enc_col = &quot;ENC_&quot; + inp_col<br>    snowml_oe = LabelEncoder(input_cols=inp_col, output_cols=enc_col)<br>    cat_enc_df = snowml_oe.fit(cat_enc_df).transform(cat_enc_df)</pre><ul><li><strong>Encode Ordinal columns:</strong> We will encode ordinal columns which is similar to categorical columns such that they are textual but they have a certain order to them. Here we are converting at age buckets column into numeric format using Snowpark ML preprocessing Ordinal Encoder.</li></ul><pre># Encode ordinal columns<br>enc_ord_cols = [&quot;ENC_&quot;+ col for col in ord_cols]<br>categories = {&quot;AGE_BUCKET&quot;: np.array([&#39;15-20&#39;,&#39;20-25&#39;,&#39;25-30&#39;,&#39;30-35&#39;,&#39;35-40&#39;,&#39;40-45&#39;,&#39;45-50&#39;,&#39;50-55&#39;,&#39;55-60&#39;,&#39;60-65&#39;,&#39;65-70&#39;,&#39;70-75&#39;, \<br>                                       &#39;75-80&#39;,&#39;80-85&#39;,&#39;85-90&#39;,&#39;90-95&#39;,&#39;95-100&#39;])}<br>snowml_oe = OrdinalEncoder(input_cols=ord_cols, output_cols=enc_ord_cols, categories=categories, \<br>                                  handle_unknown = &#39;use_encoded_value&#39;, encoded_missing_value = -99, unknown_value = np.nan)<br>ord_enc_df = df.select(ord_cols + key_cols)<br>ord_enc_df = snowml_oe.fit(ord_enc_df).transform(ord_enc_df)</pre><ul><li><strong>Encode Flag columns:</strong> We will next convert Yes and No columns to numeric. Here we converted Y,N to 1,0 conditionally using the <strong><em>Snowpark Datafame when</em></strong> function.</li></ul><pre>ind_enc_df =df.select(key_cols + ind_cols)<br>for inp_col in ind_cols:<br>    new_col = &quot;ENC_&quot; + inp_col<br>    ind_enc_df = ind_enc_df.withColumn(new_col,<br>                           when(F.col(inp_col) == F.lit(&quot;N&quot;) , F.lit(0)) \<br>                           .when(F.col(inp_col) == F.lit(&quot;Y&quot;), F.lit(1)) \<br>                           .otherwise(F.lit(-99)))</pre><ul><li><strong>Drop columns unnecessary columns</strong> : We finally drop any columns that have only one unique value and any columns which are entirely nulls using<strong><em> Snowpark Dataframe drop </em></strong>function.</li></ul><pre># Drop change columns which only have one unique value <br>drop_cols = list(df.columns[change_df_pd.nunique() == 1])<br>df = df.drop(drop_cols)<br>print(len(df.columns))<br><br># Drop columns which are entirely nulls<br>null_df = df.select([F.count(F.when(F.col(c).isNull(), c)).alias(c) \<br>                           for c in df.select(feat_cols).columns]).toPandas() \<br>                  .T.reset_index().rename(columns={&quot;index&quot;: &quot;Column&quot;, 0: &quot;Count&quot;})<br>null_df = null_df[null_df[&#39;Count&#39;] &gt; 0]<br>drop_cols = list(null_df[null_df[&#39;Count&#39;] == df.count()][&quot;Column&quot;])<br>final_df = df.drop(drop_cols)</pre><ul><li><strong>Store prepped data: </strong>Once the data required is cleaned and prepped, we save it to a Snowflake table.</li></ul><pre># Save prepped data into table <br>final_df.write.mode(&quot;overwrite&quot;).save_as_table(&quot;FROSTBYTE_QM.ANALYTICS.INPUT_QUOTE_MANIPULATION&quot;)<br># Enable change tracking on the above table as it is utilized by DT downstream<br>session.sql(&quot;&quot;&quot;ALTER TABLE FROSTBYTE_QM.ANALYTICS.INPUT_QUOTE_MANIPULATION SET CHANGE_TRACKING = TRUE;&quot;&quot;&quot;).collect()</pre><h3>Model Training</h3><p>Lets get into the model training portion that will train the model to <strong>detect anomalies</strong> in the prepped data. We will build <strong><em>Isolation Forest</em></strong> by leveraging <strong><em>Snowpark ML modeling</em></strong> API.</p><p>Isolation Forest is an anomaly detection algorithm that efficiently isolates outliers by randomly selecting features and partitioning data points into trees. It’s particularly effective in identifying anomalies within large datasets with high-dimensional features due to its simplicity and ability to work without requiring normal data for training.</p><p>First we will create a stage to host our model file , stored procedures and UDFs.</p><pre># Create stage to host files, UDF &amp; Stored Procedures<br>session.sql(&quot;CREATE STAGE IF NOT EXISTS QM_STAGE&quot;).collect()</pre><p>As mentioned, we will leverage Snowflake ML API to train Isolation forest model to detect anomalies in our data. The model.fit() function creates a temporary stored procedure in the background enabling us to leverage Snowflake compute to train the model without moving the data outside the secure Snowflake environment. Here is the code snippet</p><pre># Add the list of columns you are using in the model.<br>feature_cols = [..]<br>output_cols = [&quot;Anomaly_Ind&quot; ]<br>data = session.table(&quot;FROSTBYTE_QM.ANALYTICS.INPUT_QUOTE_MANIPULATION&quot;)<br># Define the Isolation Forest<br>model = IsolationForest(<br>    input_cols=feature_cols,<br>    output_cols=output_cols,<br>    contamination=0.01,<br>    random_state=12<br>)<br># Train<br>model.fit(data)</pre><p><strong>NOTE:</strong> <em>Update the feature_cols with a list of columns that you are using.</em></p><p>After training the model we load it into a stage.</p><pre># Save our model <br>skmodel = model.to_sklearn()<br>MODEL_FILE = &#39;model.joblib&#39;<br># Pickling model <br>joblib.dump(skmodel, MODEL_FILE) <br># Saving pickled object on to the stage<br>session.file.put(MODEL_FILE, &quot;@QM_STAGE&quot;, overwrite=True)</pre><h3>Model Inference</h3><ul><li><strong>Creating a function for Model Inference : </strong>This function loads the saved model and predicts the anomaly scores from input features. Here is the code snippet of the function</li></ul><pre># Function to load the model from file and cache the result<br>@cachetools.cached(cache={})<br>def load_model(filename):<br>    <br>    # Import packages<br>    import sys<br>    import os<br>    import joblib<br>    <br>    # Get the import directory where the model file is stored<br>    import_dir = sys._xoptions.get(&quot;snowflake_import_directory&quot;)<br>    <br>    # Load and return the model<br>    if import_dir:<br>        with open(os.path.join(import_dir, filename), &#39;rb&#39;) as file:<br>            m = joblib.load(file)<br>            return m<br># Function to detect quote manipulation<br>def forest_anomaly_scores(X: pd.DataFrame) -&gt; pd.Series:<br>    <br>    # Load the model<br>    model = load_model(&quot;model.joblib.gz&quot;)<br>    <br>    # Assign column names to data<br>    # Add the list of columns you are using in the model.<br>    X.columns = [..]    # Return raw anomaly scores<br>    return model.score_samples(X).astype(&quot;float64&quot;).round(4)</pre><p><strong>NOTE:</strong> <em>Update the </em>X.columns<em> with a list of columns that you are using.</em></p><p>Because we specified the input as a pandas DataFrame and output as a pandas Series, the user-defined function will execute in batches instead of one row at a time. In many cases, this reduces the overall execution time for the query calling the user-defined function.</p><ul><li><strong>Register the function to Snowflake: </strong>To register the function on Snowflake as a user-defined function, we specify the python packages required. Here we specify:</li><li>Sklearn (for making predictions)</li><li>Joblib (for loading the model from file)</li><li>Cachetools (for caching the loaded model)</li></ul><pre>session.udf.register(<br>    func=forest_anomaly_scores,<br>    name=&quot;udf_anomaly_scores&quot;,<br>    stage_location=&quot;@QM_STAGE&quot;,<br>    input_types=[T.DoubleType()] * len(feature_cols),<br>    return_type=T.FloatType(),<br>    replace=True,<br>    is_permanent=True,<br>    imports=[&quot;@QM_STAGE/model.joblib.gz&quot;],<br>    packages=[&quot;scikit-learn==1.2.2&quot;, &quot;joblib&quot;, &quot;cachetools&quot;],<br>)</pre><p>Calling the deployed UDF to preview the anomaly scores using <strong><em>Snowpark’s call_udf </em></strong>function.</p><pre>snowpark_df = session.table(&quot;FROSTBYTE_QM.ANALYTICS.INPUT_QUOTE_MANIPULATION&quot;)<br>pred_df = snowpark_df.select(<br>        F.col(&quot;CUSTID&quot;),<br>        F.col(&quot;POLICY_BATCHID&quot;),<br>        F.col(&quot;ACCEPTEDQUOTE_UUID&quot;),<br>        F.call_udf(&quot;udf_anomaly_scores&quot;, [F.col(c) for c in feature_cols]).alias(&quot;RAW_SCORES&quot;)<br>)<br>pred_df.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RUoCh9VdUJZS26ua.png" /><figcaption>Anomaly scores detected generated by the model</figcaption></figure><h3>Model Explanation</h3><p>We further enhance our pipeline by building model interpretability by using SHAP library which enables us to understand how our model produces it’s anomaly score. This empowers us to understand which factors could contribute quote manipulation. Below is a code snippet to do so:</p><pre># Build Shap <br>  explainer = shap.TreeExplainer(skmodel)<br>  <br>  # Get shap values<br>  shap_df = pd.DataFrame(np.negative(explainer.shap_values(input_df[feature_cols])), columns = feature_cols)</pre><p>It is possible to create a Snowpark Stored procedure to perform the SHAP analysis which allows us to push down our operations onto Snowflake compute and run it within the secure walls of Snowflake.</p><h3>Pipeline Automation</h3><p>We can <strong>bring together</strong> all we have built in the previous sections to create the <strong>automation pipeline:</strong></p><ul><li>Feature Engineering</li><li>Trained Model</li><li>Model Inference</li><li>Model Explanation</li></ul><p>We do so by wrapping the operations for each in<strong><em> Snowpark stored procedures</em></strong> and creating <strong><em>DAG tasks</em></strong> to run these stored procedures such that the parent step is the feature engineering task which preps the data followed by inference &amp; SHAP tasks which run in parallel after the feature engineering task is complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vyy8WsJw4DMUshAR.png" /><figcaption>Task DAG</figcaption></figure><h3>So far we saw how to,</h3><ul><li>Perform feature engineering using <strong><em>Snowpark Dataframe API &amp; Snowflake ML preprocessing</em></strong></li><li>Train a model to be leveraged in quote manipulation detection using <strong><em>Snowflake ML modeling API</em></strong></li><li>Utilize the model in Snowflake for inferring quote manipulation score &amp; explain the given scores using <strong><em>Snowpark UDF &amp; Stored procedures</em></strong></li><li>Automate ML workflow by utilizing<strong><em> Snowpark stored procedures</em></strong> followed by leveraging <strong><em>Snowflake tasks</em></strong></li></ul><p>This setup guarantees inclusive model inference, preserving security and governance within Snowflake, while also optimizing performance through push-down operations to Snowflake compute, eliminating the need for data transfer outside the platform allowing for an efficient path to production.</p><h3>Analytics</h3><p>The output of data science was then pulled into Power BI using Direct Query to leverage the processing power of Snowflake and keep the data in the data warehouse.</p><p>Here are some of the dashboards that was created by the Analytics team:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5S7ZPqG7jLKHeE7m.png" /><figcaption>Anomaly Scores &amp; Quote Count Dashboards</figcaption></figure><h3>Streamlit App</h3><p>We created a desktop application for the call center reps , who will have a 360 view of the customer and can take a decision based on the data available for the customer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*xLp2PKymALs8dVqQ.gif" /><figcaption>Stream lit application for Call Center Rep with a 360 Customer view</figcaption></figure><h3>Synopsis</h3><p>The FrostByte team has meticulously constructed a sophisticated infrastructure, harnessing the diverse capabilities of Snowflake. This automated end-to-end pipeline seamlessly navigates from quote submission to the ultimate data science output. The result? Anomaly scores are generated for individual customers, empowering Customer Representatives with invaluable insights.</p><h3>Contact Snowflake</h3><p>Solution designed and developed by team frostbyte and Snowflake industry experts: <a href="https://www.linkedin.com/in/shriyarai/"><strong>Shriya Rai</strong></a><strong> &amp; </strong><a href="https://www.linkedin.com/in/adithya-nanduri-bb904a194/"><strong>Adithya Nanduri</strong></a>.</p><p>Web: <a href="https://www.snowflake.com/contact/">https://www.snowflake.com/contact/</a><br>Email: <a href="/service/mailto:se-sit-frostbyte-DL@snowflake.com">se-sit-frostbyte-DL@snowflake.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e87e73a60952" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/quote-manipulation-detection-in-the-finance-industry-using-snowflake-e87e73a60952">Quote Manipulation Detection in the Finance Industry using Snowflake</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>