<?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 Daniel Ong on Medium]]></title>
        <description><![CDATA[Stories by Daniel Ong on Medium]]></description>
        <link>https://medium.com/@daniel.ong_3518?source=rss-8cf63664e12b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rMIQ5sQpLh6ydm8D6N-XUw.png</url>
            <title>Stories by Daniel Ong on Medium</title>
            <link>https://medium.com/@daniel.ong_3518?source=rss-8cf63664e12b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:25:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daniel.ong_3518/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[Deploy LLM on Snowpark Container Services with vLLM]]></title>
            <link>https://medium.com/@daniel.ong_3518/deploy-any-llm-on-spcs-with-vllm-7442f00d02d5?source=rss-8cf63664e12b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7442f00d02d5</guid>
            <category><![CDATA[snowpark-container]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Daniel Ong]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 11:33:20 GMT</pubDate>
            <atom:updated>2025-02-25T05:36:34.626Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5dAoNq5x7S9sw200V8s0g.jpeg" /></figure><p>Snowflake provides serverless LLM capabilities with <a href="https://www.snowflake.com/en/data-cloud/cortex/">Cortex</a>. Currently, this is served as SQL endpoint, which is great for conveniently analyzing data in tables. A lot of the open-source tools around LLM take in models as REST endpoints, such as LangChain, Llama Index etc. If you have a need to integrate with these packages, use any specific LLM outside of what’s available in <a href="https://docs.snowflake.com/en/sql-reference/functions/complete-snowflake-cortex#arguments">Cortex</a>, or simply want your own dedicated LLM environment, one of the ways is deploy your own LLM on Snowpark Container Services (SPCS) with <a href="https://docs.vllm.ai/en/stable/">vLLM</a></p><p>vLLM is a fast and easy Python library for running a http inferencing server with high throughput. In this article, I will guide you step by step in</p><ol><li>Creating a bootstrap environment on Snowflake to run SPCS</li><li>Deploying vLLM from a docker image to SPCS image repository</li><li>Creating the yaml specification file and upload to a stage</li><li>Creating the service</li><li>Doing the same for Streamlit</li></ol><p>Before we begin, you would need a <a href="https://signup.snowflake.com/">Snowflake</a> account in these <a href="http://CREATE COMPUTE POOL GPU_NV_M   MIN_NODES = 1   MAX_NODES = 1   INSTANCE_FAMILY = GPU_NV_M;">regions</a> that support SPCS and <a href="https://www.docker.com/">Docker</a> installed on your laptop.</p><p>All the code can be found in my GitHub <a href="https://github.com/sfc-gh-dong/vllm">repo</a>.</p><h3>1. Create the bootstrap environment (Snowflake)</h3><p><strong><em>**Don’t worry, the sqls are all </em></strong><a href="https://github.com/sfc-gh-dong/vllm/blob/main/vllm/bootstrap.sql"><strong><em>here</em></strong></a></p><p>SPCS requires a</p><ul><li>compute pool to run your GPU-based containers</li><li>an image repository to store your code</li><li>stages to store the yaml settings and model files</li><li>a service to run your containers in the compute pool</li></ul><p><strong><em>i) Compute Pool</em></strong></p><p>If you’re not familiar with containers, think of how you install an application today. You need the software, OS, patches etc and that’s normally tied to the type of hardware. Deploying an application needs to deal with these different layers. A container simplifies the deployment by abstracting this as a package. You can think of this broadly as application virtualization, compared with virtual machines as hardware virtualization.</p><p>A compute pool then is a collection of virtual machines (VMs) that run your containers. Just like most objects you create in Snowflake, you need to ‘house’ them in a database and schema. Login as any user with sysadmin rights.</p><pre>USE ROLE ACCOUNTADMIN;<br>GRANT BIND SERVICE ENDPOINT ON ACCOUNT TO ROLE SYSADMIN;<br><br>USE ROLE SYSADMIN;<br>CREATE DATABASE IF NOT EXISTS LLM;<br>USE DATABASE LLM;</pre><p>Next, <a href="https://docs.snowflake.com/en/sql-reference/sql/create-compute-pool">create</a> a GPU compute pool</p><pre>CREATE COMPUTE POOL GPU_NV_M<br>  MIN_NODES = 1<br>  MAX_NODES = 1<br>  INSTANCE_FAMILY = GPU_NV_M;</pre><p>When a compute pool is first created, Snowflake creates a Kubernetes cluster — one for each account. You can create more compute pools in that cluster. The control plane for the cluster resides in Snowflake’s Cloud Services.</p><p>By default, the compute pool will be automatically suspended after 60 mins of idle time. You can change this by setting the <strong>AUTO_SUSPEND_SECS </strong>parameter. You can also manually suspend/resume the compute pool by running</p><pre>ALTER COMPUTE POOL GPU_NV_M SUSPEND/RESUME;</pre><p><strong><em>ii) Image repository</em></strong></p><p>SPCS provides an OCIv2-compliant image registry service and a storage unit call repository to store the images of your containers.</p><pre>CREATE OR REPLACE IMAGE REPOSITORY images;</pre><p><strong><em>iii) Stages</em></strong></p><pre>-- Stage to store LLM models<br>CREATE OR REPLACE STAGE models<br> DIRECTORY = (ENABLE = TRUE)<br> ENCRYPTION = (TYPE=&#39;SNOWFLAKE_SSE&#39;);<br><br>-- Stage to store yaml specs<br>CREATE OR REPLACE STAGE specs<br> DIRECTORY = (ENABLE = TRUE)<br> ENCRYPTION = (TYPE=&#39;SNOWFLAKE_SSE&#39;);</pre><p><strong><em>iv) External access</em></strong></p><p>vLLM downloads model files from Hugging Face. In order to allow Snowflake to reach Hugging Face, you create a network rule and external access integration. Since Hugging Face might host their models on CDN, it’ll be easier to just enable egress for 0.0.0.0 and if need be, remove that rule after the models get downloaded (the very first run).</p><pre>CREATE OR REPLACE NETWORK RULE hugging_face_network<br>  MODE = EGRESS<br>  TYPE = HOST_PORT<br>  VALUE_LIST = (&#39;0.0.0.0&#39;);<br><br>USE ROLE ACCOUNTADMIN;<br>CREATE OR REPLACE EXTERNAL ACCESS INTEGRATION hugging_face_integration<br>  ALLOWED_NETWORK_RULES = (hugging_face_network)<br>  ENABLED = TRUE;<br><br>GRANT USAGE ON INTEGRATION hugging_face_integration TO ROLE SYSADMIN;</pre><h3>2. Deploy vLLM docker to image repository (Mostly from your laptop)</h3><p>First, you need to clone the <a href="https://github.com/sfc-gh-dong/vllm">repo</a>. Then go to the vllm directory - the Dockerfile and related files for this section are there.</p><p>This is the Dockerfile</p><pre>FROM vllm/vllm-openai:v0.4.2<br>COPY entrypoint.sh /entrypoint.sh<br>RUN chmod +x /entrypoint.sh<br>ENTRYPOINT [&quot;/entrypoint.sh&quot;]</pre><p>I’m pulling v0.4.2 from vLLM’s <a href="https://hub.docker.com/r/vllm/vllm-openai/tags">Docker Hub</a>. As of this writing, the latest vLLM version requires CUDA 12.4 which is not supported in SPCS yet.</p><p>This is the entrypoint.sh file</p><pre>#!/bin/bash<br><br>start_service() {<br>    local log_file_basename=$1<br><br>    # Generate the current date/hour/minute format<br>    local datetime_prefix=$(date +&quot;%Y%m%d-%H%M&quot;)<br><br>    # Modify log_file to include the datetime prefix and models directory<br>    local log_file=&quot;/models/logs/${datetime_prefix}_${log_file_basename}&quot;<br><br>    mkdir -p /models/logs<br>    touch $log_file<br><br>    echo &quot;Starting vLLM server...&quot;<br>    python3 -m vllm.entrypoints.openai.api_server --model $MODEL --download-dir /models/ --trust-remote-code &gt; $log_file 2&gt;&amp;1 &amp;<br><br>    # Start tailing the logs and send the process to background<br>    tail -F $log_file &amp;<br><br>    echo &quot;Waiting for vLLM server to be ready...&quot;<br>    while true<br>    do<br>      if grep -q &quot;Uvicorn running&quot; $log_file || grep -q &quot;100%&quot; $log_file; then<br>        break<br>      fi<br>      sleep 1<br>    done<br><br>    # Stop tailing the logs after the service is ready<br>    pkill -P $$ tail<br><br>    echo &quot;vLLM server is ready.&quot;<br>}<br><br>start_service vllm.log<br><br># wait indefinitely<br>tail -f /dev/null</pre><p>Entrypoint.sh will :</p><ul><li>Create and archive the application log files in the stage</li><li>Run vLLM. In my example, I’m just using llama 2 but you can use any model available on Hugging Face. Go to Hugging Face to find the model url. In my case, I’m using <a href="https://huggingface.co/meta-llama/Llama-2-7b-chat-hf">https://huggingface.co/meta-llama/Llama-2-7b-chat-hf</a> so the model url is simply meta-llama/Llama-2–7b-chat-hf</li><li>At the initial run, vLLM will download the model files to the download directory specified by the download-dir parameter. This is mapped to the Snowflake stage in the YAML file.</li><li>In order to download the model, you also need a <a href="https://huggingface.co/docs/hub/en/security-tokens">Hugging Face token</a>. The HF_TOKEN is specified in the YAML file as well.</li></ul><p>So as you can see, the YAML file is very important…</p><p>Run this on Snowflake to get the image repository url</p><pre>SHOW IMAGE REPOSITORIES;</pre><p>To login from docker without MFA, run this from your command prompt at the same folder of the Dockerfile. <strong>&lt;spcs_user&gt;</strong> is the identity used to create the objects in Step 1 above.</p><pre>docker login &lt;image_repository_url&gt; -u &lt;spcs_user&gt;</pre><p>If you have MFA enabled, you need to setup <a href="https://docs.snowflake.com/en/developer-guide/snowflake-cli-v2/index">Snow CLI</a> first with your connection in the ~/.snowflake/config.toml for the user in Step 1 above.</p><pre>snow spcs image-registry token -c &lt;connection_name&gt; --format=JSON | docker login &lt;image_repository_url&gt; -u 0sessiontoken --password-stdin</pre><p>Your connection profile should look like this</p><pre>[connections.connection_name]<br>account = &quot;&quot;<br>user = &quot;&lt;spcs_user&gt;&quot;<br>password = &quot;&quot;<br>region = &quot;&quot;<br>database = &quot;LLM&quot;<br>schema = &quot;PUBLIC&quot;<br>warehouse = &quot;COMPUTE_WH&quot;<br>role = &quot;SYSADMIN&quot;</pre><p>Then, build and push the image to the repository. Your image name is vllm. I’m using Mac on Apple M1 Pro but the container is on Intel, so I need the — platform linux/amd64 flag to build accordingly. If you’re using Intel, you don’t need that. In the vllm folder that contains the Dockerfile, run</p><pre><br>docker build -t vllm . --platform linux/amd64 <br>docker tag vllm &lt;image_repository_url&gt;/vllm<br>docker push &lt;image_repository_url&gt;/vllm</pre><h3>3. Create the YAML file (Laptop)</h3><p>In the same folder, you can see the <a href="https://docs.snowflake.com/en/developer-guide/snowpark-container-services/specification-reference">services.yaml</a> file</p><p><strong>Remember to change the &lt;image_repository_url&gt; and &lt;your_hf_token&gt;</strong></p><pre>spec:<br>  containers:<br>    - name: vllm-container<br>      image: &lt;image_repository_url&gt;/vllm<br>      resources:<br>        requests:<br>          nvidia.com/gpu: 1<br>        limits:<br>          nvidia.com/gpu: 1<br>      env:<br>        MODEL: meta-llama/Llama-2-7b-chat-hf<br>        HF_TOKEN: &lt;your_hf_token&gt;<br>        NUM_GPU: 1<br>        MAX_GPU_MEMORY: 24Gib<br>      volumeMounts:<br>        - name: models<br>          mountPath: /models<br><br>  endpoints:<br>    - name: llama<br>      port: 8000<br>      public: true<br>  volumes:<br>    - name: models<br>      source: &quot;@LLM.PUBLIC.models&quot;<br><br>  networkPolicyConfig:<br>    allowInternetEgress: true</pre><p>The endpoint for this service accessible from within the cluster will be <a href="http://llama:8000/v1"><strong>http://llama:8000/v1</strong></a></p><p>Finally, upload the YAML file to specs stage created earlier in the llm.public schema either through the UI or if you have <a href="https://docs.snowflake.com/en/developer-guide/snowflake-cli-v2/index">Snow CLI</a> installed</p><pre>snow stage copy ./services.yaml @specs -c &lt;connection_name&gt; --overwrite --debug</pre><h3>4. Create the service (Snowflake)</h3><p>Service enables you to easily deploy, manage, and scale containerized applications by defining parameters such memory and cpu/gpu requirements in YAML file. Wait for the compute pool you created earlier to be in the active or idle state</p><pre>describe compute pool GPU_NV_M;</pre><p>Then, create the service</p><pre>USE ROLE SYSADMIN;<br>CREATE SERVICE LLAMA<br>IN COMPUTE POOL GPU_NV_M<br>FROM @specs<br>SPEC=&#39;services.yaml&#39;<br>EXTERNAL_ACCESS_INTEGRATIONS = (HUGGING_FACE_INTEGRATION);</pre><p>Check that the service is being deployed to the container. It might take a few minutes.</p><pre>show services;</pre><p>Once the status progressed from ‘PENDING’ to ‘RUNNING’ as shown below, verify that vLLM is running properly by running the following command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*Kd2pYAt-Sn4xP9ckN-ywkg.png" /></figure><pre>call SYSTEM$GET_SERVICE_STATUS(&#39;llama&#39;);</pre><p>You should see something like this</p><pre>[{&quot;status&quot;:&quot;READY&quot;,&quot;message&quot;:&quot;Running&quot;,&quot;containerName&quot;:&quot;vllm-container&quot;,&quot;instanceId&quot;:&quot;0&quot;,&quot;serviceName&quot;:&quot;LLAMA&quot;,&quot;image&quot;:&quot;xxx/llm/public/images/vllm&quot;,&quot;restartCount&quot;:0,&quot;startTime&quot;:&quot;2024-06-28T02:57:10Z&quot;}]</pre><p>If the status is READY, check the application log</p><pre>call SYSTEM$GET_SERVICE_LOGS(&#39;llama&#39;, &#39;0&#39;, &#39;vllm-container&#39;, &#39;100&#39;);</pre><pre>INFO:     Started server process [10]<br>INFO:     Waiting for application startup.<br>INFO:     Application startup complete.<br>INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)<br>vLLM server is ready.</pre><p>Now vLLM is up and running on SPCS! The first run might take a longer time, depending on the size of the model to download. It took ~30 minutes for me. Subsequent runs do not require the models to be downloaded again and will be faster.</p><p>You suspend the service and compute pool if you’re not using them</p><pre>alter service llama suspend;<br>alter compute pool GPU_NV_M_1 suspend;</pre><h3>5. Repeat for Streamlit</h3><p>Deploying Streamlit to Docker is pretty similar. You can skip step 1 since the environment has already been set up and just run the Docker commands from the <a href="https://github.com/sfc-gh-dong/vllm/tree/main/streamlit">streamlit</a> folder (that contains your Dockerfile)</p><pre>docker build -t streamlit . --platform linux/amd64 <br>docker tag streamlit &lt;image_repository_url&gt;/streamlit<br>docker push &lt;image_repository_url&gt;/streamlit</pre><p><strong>If there’s a connection error, re-login to Docker as shown in Step 2 above.</strong></p><p>Upload the streamlit.yaml file</p><pre>snow stage copy ./streamlit.yaml @specs -c &lt;connection_name&gt; --overwrite --debug</pre><p>Create the service in Snowflake</p><pre>USE ROLE SYSADMIN;<br>CREATE SERVICE chat<br>IN COMPUTE POOL GPU_NV_M<br>FROM @specs<br>SPEC=&#39;streamlit.yaml&#39;;</pre><p>Check to see if Streamlit is running</p><pre>call SYSTEM$GET_SERVICE_LOGS(&#39;chat&#39;, &#39;0&#39;, &#39;streamlit-container&#39;, &#39;100&#39;);</pre><p>In order to access the Streamlit app, you need to get the public endpoint. It might take a minute or two before it’s provisioned.</p><pre>show endpoints in service chat;</pre><p>Copy and paste the ingress_url in a browser, and you’re ready to chat!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*gScB4DYhD9qV3C075gtQ2g.gif" /></figure><p>You can change the model in services.yaml to use different models. But take note of a few things :</p><ul><li><strong>Make sure you check the model card in HF. Sometimes you need to accept the terms and conditions or request for access</strong></li><li><strong>Make sure you change the model parameter in streamlit.yaml as well</strong></li><li>When vLLM is started with a new model, it will take some time to download the model files. You can check the progress by doing a ls @models in Snowflake</li><li>For further customization when you run vLLM, refer to the engine <a href="https://docs.vllm.ai/en/latest/models/engine_args.html">parameters</a></li><li>To scale vLLM across multiple nodes in a GPU cluster, consider using <a href="https://docs.ray.io/en/latest/serve/tutorials/vllm-example.html">Ray</a>. Great article on <a href="https://medium.com/snowflake/run-multi-node-multi-gpu-ray-inside-snowflake-76116826a414">running multi-node, multi-GPU with Ray on SPCS</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7442f00d02d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combining SQL and Semantic Search of AirBnB Reviews with Snowflake Cortex]]></title>
            <link>https://medium.com/@daniel.ong_3518/semantic-search-of-airbnb-reviews-with-snowflake-cortex-35bf47263e57?source=rss-8cf63664e12b------2</link>
            <guid isPermaLink="false">https://medium.com/p/35bf47263e57</guid>
            <dc:creator><![CDATA[Daniel Ong]]></dc:creator>
            <pubDate>Wed, 27 Mar 2024 12:52:22 GMT</pubDate>
            <atom:updated>2024-05-30T14:37:59.057Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHQCzypyIKUbymrGcV4igg.png" /></figure><p>One of the use cases in natural language processing is semantic search. Semantic search returns content based on the meaning of words, rather than literal matching of words. For example, if you search for “a place with sea view”, listings with “ocean”, “beachfront” etc should come out in your search, because they are related. Semantic search is greatly improved with LLM’s tremendous ability to understand language.</p><h3>Synopsis</h3><p>In this example, I’ll be using AirBnB’s data that’s available in the <a href="https://app.snowflake.com/marketplace/listing/GZT0ZKSJ2AN/bright-data-airbnb-properties-information?originTab=provider&amp;providerName=Bright+Data&amp;profileGlobalName=GZT0ZKSJ274">Snowflake Marketplace</a> that’s free to try by Bright Data and <a href="https://docs.snowflake.com/en/user-guide/snowflake-cortex/llm-functions#label-cortex-llm-availability">Snowflake Cortex</a> recently on Public Preview. The dataset contains a mix of relational fields — no of rooms, price etc and unstructured data — user reviews — for various AirBnB locations worldwide, condensed in a single table.</p><p>The idea is to take in a user’s query such as ‘<em>Show me listings with a great sea view! I have a minimum of 5 guests’ </em>and return the results.</p><p>Sounds simple, but if you look at the query in parts :</p><p><em>Show me listings with a great sea view</em></p><p>This is the natural language part that can be fed into an LLM based on the reviews as input.</p><p><em>I have a minimum of 5 guests</em></p><p>This is the part that is relational that should be used to derive the SQL query. (since no. of guest is simply a column in the table)</p><p>Eventually the results would be the rows returned from SQL that satisfy the semantic criteria.</p><p><strong>One of the advantages of using LLM based on SQL is that you can process complex queries that contain structured and unstructured data.</strong></p><h3>Technique</h3><p>The first technique used is <strong>query decomposition</strong> that breaks down a complex prompt into sub-queries. This <a href="https://python.langchain.com/docs/use_cases/query_analysis/techniques/decomposition">article</a> for LangChain shows an example. It’s basically leveraging the LLM to perform prompt engineering for you. If you’ve used ChatGPT for image generation, you would have seen this technique in action.</p><p>The second technique used is <strong>few-shot prompting. </strong>LLMs or Large Language Models are a type of pre-trained deep learning model that uses zero shot learning (ZSL) — they can make inference on unseen data. Which is why you can feed in any prompt to the LLM, and it’ll generate content.</p><p>One of the ways to improve the results returned, is to use few-shot prompting. In few-shot prompting, we provide at least some labeled data to further instruct the model. In this example, few-shot prompting is used to frame the output of the LLM into a more structured format.</p><p>With these techniques, the prompt used to decompose the query is :</p><pre>&lt;Context&gt;<br>You are a chatbot for airbnb. You need to decide based on the question, <br>if a user is searching for listing, or just chatting in general. <br>If the user is searching for a listing then do this : <br><br>The question can be separated by comma,and,or. <br>You need decompose the question into 2 parts. <br>You are given a table with the columns : price, guests. <br>Part 1 provides the WHERE clause for querying the given table and <br>you must only use the given column names. <br>Part 2 queries an LLM <br>Part 1 must only contain conditions based on the columns (price, guests). <br>The output format is :<br>    <br>Example Question : <br>Show me the listings with good host, a sea view <br>    <br>Example Output :<br>&lt;q1&gt;price &gt;= 0 and guests &gt;= 0&lt;/q1&gt;\n<br>    <br>&lt;q2&gt;good host and a sea view&lt;/q2&gt;<br>    <br>Example Question : <br>Show me the listings which are near town. I have a budget of 100 <br>    <br>Example Output :<br>&lt;q1&gt;price &lt;= 100 and guests &gt;= 0&lt;/q1&gt;\n<br>    <br>&lt;q2&gt;near town&lt;/q2&gt;<br>    <br>Do provide repeated or overlapping criteria in each part. <br>Do not provide any other explanation outside of this format.<br>If the user is just chatting in general, then you do not need to <br>follow the format mentioned.<br>&lt;/Context&gt;</pre><p>This prompt is fed via the COMPLETE function to an underlying LLM model in Cortex — Llama 70b</p><p>I noticed that providing information in markup tags &lt;&gt;&lt;/&gt; works pretty well in helping to frame the output so that the relevant parts can be easily extracted with regex. Providing the schema of the table in the prompt helps the model to understand what to extract.</p><p>The second part of the prompt is an example of <strong>few-shot prompting</strong>, where we instruct the model with some labeled sample — examples of input and output. After toying with a few examples, I find that even though some columns are not used in the query, it’s good to set default values.</p><h3>Semantic Search</h3><p>Semantic search can then be made easy with vector search. Vector is a way to represent text numerically (in an array), in a way that can be understood by models. There are N dimensions in a vector, and each dimension represent an attribute of the text.</p><p>Snowflake provide native functions to convert text to vector embeddings (native data type in Snowflake). Similarity functions such as L2 distance or cosine similarity are also available natively to find texts that are contextually similar, which is basically calculating how close the two texts are in the vector space.</p><p>Out of say top 10 results returned from the vector similarity search, I further refine the results by feeding that into the Cortex LLM. Based on the same example, the prompt looks like :</p><pre>select snowflake.cortex.complete(&#39;llama2-70b-chat&#39;, \<br>concat(&#39;based on these reviews &lt;review&gt;&#39;,reviews,\<br>&#39;&lt;/review&gt; of an airbnb listing, \<br>does it have)&#39;)) from airbnb limit 1;</pre><p>Why do I feed into the LLM again? Well, it gives higher accuracy and explainability of the search results returned, as we can soon see in the demo below. Overall, the process looks like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Etml6sbKA_SapSeZf-7Yag.gif" /><figcaption>Semantic Search with Query Decomposition</figcaption></figure><h3>Demo</h3><h4>1. Summarisation and Sentiment Analysis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UO1CpnfACq5epon_gIBJPw.gif" /></figure><p>Phew, long reviews are now summarised.</p><h4>2. Search</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axK7o61S7J9lNpLdcV9Kow.gif" /></figure><p>First of all, the property can house 8 guests, so it meets your minimum no. of guests requirements. This is simply obtained from SQL on the table based on the condition guests &gt; 5. Based on the results returned, we further shortlist properties that meet your semantic search requirements. You can see the reason given by the LLM for this property based on semantic search on the customer reviews :</p><pre>The listing has great sea views and bars. Several reviewers mentioned the <br>apartment&#39;s direct beach access, great pools, and beautiful sea views. <br>Additionally, one reviewer mentioned that the apartment is located in a large <br>front beach property with plenty of amenities, which suggests that there are <br>likely bars and restaurants nearby. Therefore, it can be inferred that the <br>listing has great sea views and bars.</pre><p>The complete SQL generated in Snowflake for this query is this :</p><pre>select name, guests, price, summary, sentiment, image, lat, lon, url, <br>snowflake.cortex.complete(&#39;llama2-70b-chat&#39;,concat(&#39;based on these reviews &lt;review&gt;&#39;,<br>reviews,&#39;&lt;/review&gt; of an airbnb listing, does it have great sea view?  <br>The output format is :         <br>Part 1: 1 if all criteria are met, and 0 otherwise         <br>Part 2: Provide explanation             <br>Example Output:     Part 1: 1     Part 2: {Explain}         <br>Do not provide any other explanation outside of this format    &#39;)) as results,<br>case when left(trim(results), 9)=&#39;Part 1: 1&#39; then True else False end as filter <br>from (select *, VECTOR_L2_DISTANCE(embedding, snowflake.cortex.embed_text(&#39;e5-base-v2&#39;, <br>&#39;great sea view&#39;)) <br>as l2 from airbnb_clean                   <br>where price &gt;= 0 and guests &gt;= 5 order by l2 asc limit 10)</pre><p>The query contains :</p><ol><li>the part fed into an LLM, taken from</li><li>results returned from vector similarity search, taken from</li><li>results returned from a SQL query that filters the table based on price, no. guests etc</li></ol><p>Full code is here <a href="https://github.com/sfc-gh-dong/airbnb/tree/main">https://github.com/sfc-gh-dong/airbnb/tree/main</a></p><h3>Summary</h3><p>Go use LLM for this :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35bf47263e57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RFM Customer Segmentation using K-Means Clustering on Snowpark]]></title>
            <link>https://medium.com/@daniel.ong_3518/rfm-customer-segmentation-using-k-means-clustering-on-snowpark-23c680f450e1?source=rss-8cf63664e12b------2</link>
            <guid isPermaLink="false">https://medium.com/p/23c680f450e1</guid>
            <category><![CDATA[customer-segmentation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[snowpark]]></category>
            <dc:creator><![CDATA[Daniel Ong]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 12:17:16 GMT</pubDate>
            <atom:updated>2023-06-26T04:25:21.560Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*ZCnM_pLWkbmyWEJAnvgPrg.jpeg" /></figure><p>One of the first steps in developing a personalization engine is to segment your customers. A popular method is using the RFM segmentation.</p><p><strong>R</strong> stands for recency<br><strong>F</strong> stands for frequency, and<br><strong>M</strong> stands for monetary</p><p>That is to say we segment our customers based on how recent they made the last purchase, how often they bought and how much($ value) they bought.</p><p>RFM segmentation is also often used in predicting the LTV (lifetime value) of a customer. A typical high value customer, would buy frequently, spends a lot and still active (made recent purchases).</p><p>In this article, I want to show you how you can build a simple RFM model to segment your customers using K-Means clustering with Snowpark.</p><p>We begin by using a Kaggle dataset for retail <a href="https://www.kaggle.com/datasets/vijayuv/onlineretail">here</a></p><h4>Loading data into Snowflake</h4><p>First create a new table in your database, let’s call it retail.</p><pre>create or replace table retail<br>(<br>InvoiceNo VARCHAR,<br>StockCode VARCHAR,<br>Description VARCHAR,<br>Quantity VARCHAR,<br>InvoiceDate DATETIME ,<br>UnitPrice NUMBER (10,2),<br>CustomerID NUMBER(5,0),<br>Country VARCHAR<br>);</pre><p>From SnowSQL, upload the Kaggle dataset into a stage in Snowflake.</p><pre>put file:///Users/Downloads/OnlineRetail.csv @%retail;<br>list @%retail;</pre><p>The @%retail is a default stage tied to the retail table created.</p><p>Next, create a file format to tell Snowflake how to handle the file.</p><pre>create or replace file format csv_format<br> type = csv<br> skip_header = 1<br> field_optionally_enclosed_by = &#39;&quot;&#39;<br> empty_field_as_null = true;</pre><p>There’s a datetime field in the dataset, and we want to make sure Snowflake parses that correctly.</p><pre>alter session set timestamp_input_format = &#39;DD-MM-YYYY HH24:MI&#39;;</pre><p>Now, we’re ready to copy the data from stage into the retail table</p><pre>copy into retail<br>file_format = csv_format;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z4PkqlAB8I15yXJacW9vyA.png" /></figure><h4>Transforming data with Snowpark</h4><p>Snowpark provides server-side transformation on your data in Snowflake while running the code from your familiar Jupyter notebook. If you are new to Snowpark, <a href="https://quickstarts.snowflake.com/guide/getting_started_with_snowpark_dataframe_api/index.html?index=..%2F..index#0">here</a> is a great tutorial to get started.</p><p>First, let’s import the libraries and get connected</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/131008207ccd9494815ebf5f691dc1a0/href">https://medium.com/media/131008207ccd9494815ebf5f691dc1a0/href</a></iframe><p>The connection information is stored in config.py in the same directory</p><pre>snowflake_conn_prop = {<br>   &quot;account&quot;: &quot;xxx&quot;,<br>   &quot;user&quot;: &quot;xxx&quot;,<br>   &quot;password&quot;: &quot;xxx&quot;,<br>   &quot;role&quot;: &quot;SYSADMIN&quot;,<br>   &quot;database&quot;: &quot;RETAIL&quot;,<br>   &quot;schema&quot;: &quot;PUBLIC&quot;,<br>   &quot;warehouse&quot;: &quot;COMPUTE_WH&quot;,<br>}</pre><h4>Exploratory Data Analysis</h4><p>Let’s take a look at a summary of our data</p><pre>df.describe().show()</pre><pre>---------------------------------------------------------------------------------------------------------------------------------------------<br>|&quot;SUMMARY&quot;  |&quot;INVOICENO&quot;  |&quot;STOCKCODE&quot;  |&quot;DESCRIPTION&quot;                   |&quot;QUANTITY&quot;  |&quot;UNITPRICE&quot;        |&quot;CUSTOMERID&quot;       |&quot;COUNTRY&quot;    |<br>---------------------------------------------------------------------------------------------------------------------------------------------<br>|count      |541909       |541909       |540455                          |541909      |541909.0           |406829.0           |541909       |<br>|mean       |NULL         |NULL         |NULL                            |NULL        |4.61111362         |15287.69057        |NULL         |<br>|stddev     |NULL         |NULL         |NULL                            |NULL        |96.75985306153116  |1713.600303321635  |NULL         |<br>|min        |536365       |10002        | 4 PURPLE FLOCK DINNER CANDLES  |-1          |-11062.06          |12346.0            |Australia    |<br>|max        |C581569      |m            |wrongly sold sets               |992         |38970.0            |18287.0            |Unspecified  |<br>---------------------------------------------------------------------------------------------------------------------------------------------</pre><p>We see some NULL values, and negative values for Quantity and UnitPrice, so we have to remove them.</p><pre>df = df.dropna()<br>df = df.filter(&quot;QUANTITY &gt; 0 and UNITPRICE &gt; 0&quot;)<br>df.show()</pre><pre>----------------------------------------------------------------------------------------------------------------------------------------------------<br>|&quot;INVOICENO&quot;  |&quot;STOCKCODE&quot;  |&quot;DESCRIPTION&quot;                        |&quot;QUANTITY&quot;  |&quot;INVOICEDATE&quot;        |&quot;UNITPRICE&quot;  |&quot;CUSTOMERID&quot;  |&quot;COUNTRY&quot;       |<br>----------------------------------------------------------------------------------------------------------------------------------------------------<br>|536365       |85123A       |WHITE HANGING HEART T-LIGHT HOLDER   |6           |2010-12-01 08:26:00  |2.55         |17850         |United Kingdom  |<br>|536365       |71053        |WHITE METAL LANTERN                  |6           |2010-12-01 08:26:00  |3.39         |17850         |United Kingdom  |<br>|536365       |84406B       |CREAM CUPID HEARTS COAT HANGER       |8           |2010-12-01 08:26:00  |2.75         |17850         |United Kingdom  |<br>----------------------------------------------------------------------------------------------------------------------------------------------------</pre><p>Let’s see how much data we have for each country</p><pre>df.group_by(&quot;COUNTRY&quot;).count().show()</pre><pre>----------------------------<br>|&quot;COUNTRY&quot;       |&quot;COUNT&quot;  |<br>----------------------------<br>|United Kingdom  |354317   |<br>|France          |8341     |<br>|Australia       |1182     |<br>|Germany         |9040     |<br>|Norway          |1071     |<br>|EIRE            |7236     |<br>|Switzerland     |1841     |<br>|Spain           |2484     |<br>|Portugal        |1462     |<br>|Italy           |758      |<br>----------------------------</pre><p>Most of the transactions are from UK, so there might be enough representation sampled from the other clusters. Let’s filter to only the UK folks for our analysis.</p><pre>df = df.filter(&quot;COUNTRY = &#39;United Kingdom&#39;&quot;)</pre><h4>Feature Preparation</h4><p>The 3 key features for RFM segmentation are the recency, frequency and monetary values. This can be easily obtained through basic Snowpark dataframe operations. That’s the beauty of Snowpark : Just a single line to perform transformation without moving your data out of Snowflake.</p><pre># create a new column to store the max invoicedate, use as the reference date to calculate recency<br>df = df.join(df.select(F.max(&quot;INVOICEDATE&quot;).alias(&quot;NOW&quot;)))<br><br>#RECENCY, FREQUENCY, MONETARY<br>df_tf = df.group_by(&quot;CUSTOMERID&quot;)\<br>          .agg(F.max(&quot;INVOICEDATE&quot;),\<br>               F.max(&quot;NOW&quot;),\<br>               F.sum(col(&quot;QUANTITY&quot;)*col(&quot;UNITPRICE&quot;)).alias(&quot;Monetary&quot;),\<br>               F.count(&quot;INVOICENO&quot;).alias(&quot;Frequency&quot;)).select(&quot;CUSTOMERID&quot;,&quot;Frequency&quot;,&quot;Monetary&quot;,\<br>                                    F.datediff(&quot;days&quot;,col(&quot;MAX(INVOICEDATE)&quot;),col(&quot;MAX(NOW)&quot;)).alias(&quot;RECENCY&quot;))<br><br>df_tf.show()</pre><pre>----------------------------------------------------------<br>|&quot;CUSTOMERID&quot;  |&quot;FREQUENCY&quot;  |&quot;MONETARY&quot;     |&quot;RECENCY&quot;  |<br>----------------------------------------------------------<br>|17850         |297          |5391.2100000   |372        |<br>|13047         |172          |3237.5400000   |31         |<br>|13748         |28           |948.2500000    |95         |<br>|15100         |3            |876.0000000    |333        |<br>|15291         |103          |4668.3000000   |25         |<br>|14688         |327          |5630.8700000   |7          |<br>|17809         |61           |5411.9100000   |16         |<br>|16098         |67           |2005.6300000   |87         |<br>|18074         |13           |489.6000000    |373        |<br>|16029         |242          |81024.8400000  |38         |<br>----------------------------------------------------------</pre><p>K-means can be quite sensitive to outliers, so let’s remove them through the percentile method — any data above the 99 percentile are discarded.</p><pre>freq_99pc = df_tf.select(F.percentile_cont(0.99).within_group(&quot;FREQUENCY&quot;)).collect()<br>rec_99pc = df_tf.select(F.percentile_cont(0.99).within_group(&quot;RECENCY&quot;)).collect()<br>mon_99pc = df_tf.select(F.percentile_cont(0.99).within_group(&quot;MONETARY&quot;)).collect()<br><br>df_tf = df_tf.filter((col(&quot;FREQUENCY&quot;) &lt; freq_99pc[0][0]) &amp; \<br>                     (col(&quot;RECENCY&quot;) &lt; rec_99pc[0][0]) &amp; \<br>                     (col(&quot;MONETARY&quot;) &lt; mon_99pc[0][0]))</pre><p>We can visualize the distribution of the features</p><pre>import seaborn as sns<br>import matplotlib.pyplot as plt<br>import numpy as np<br><br>fig, ax = plt.subplots(1, 3, figsize=(16, 8))<br><br>df_pd = df_tf.select(&quot;CUSTOMERID&quot;, &quot;FREQUENCY&quot;, &quot;RECENCY&quot;, &quot;MONETARY&quot;).toPandas()<br><br># Recency distribution plot<br>sns.histplot(df_pd[&#39;RECENCY&#39;], kde=True, ax=ax[0])<br><br># Frequency distribution plot<br>sns.histplot(df_pd[&#39;FREQUENCY&#39;], kde=True, ax=ax[1])<br><br># Monetary distribution plot<br>sns.histplot(df_pd[&#39;MONETARY&#39;], kde=True, ax=ax[2])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*hk7aN_4-g00DwKHRDH7cNw.png" /></figure><p>The histogram is right skewed and a large majority of the customers are spending in the range ~ 500, buy ~10 times in the last ~ 20 days (from the latest invoice date)</p><p>How then shall we segment our customers based on these attributes? One way is to use K-means clustering across R,F and M.</p><h4>K-Means Clustering</h4><p>We can perform K-means clustering on Snowflake by writing a stored procedure with Snowpark. Since we don’t know the optimal value of k yet, we will iterate the algorithm for some values of k and return the value of inertia — which measures how well the data are clustered by K-Means.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45b22af838bac437f1eb743aad862c0a/href">https://medium.com/media/45b22af838bac437f1eb743aad862c0a/href</a></iframe><p>Before we can use this, we need to register the stored procedure with the necessary Python libraries added.</p><pre>from snowflake.snowpark.functions import sproc<br><br># This adds the necessary packages to our Python environment in Snowflake<br># session.clear_packages()<br>session.add_packages(&quot;snowflake-snowpark-python&quot;,&quot;pandas&quot;,&quot;scikit-learn&quot;)<br><br># We need a stage to host the stored proc<br>_ = session.sql(&#39;CREATE STAGE IF NOT EXISTS MODELS&#39;).collect()<br><br># Register the stored proc<br>session.sproc.register(kmeans_cluster, name=&quot;kmeans_cluster&quot;, is_permanent=True, stage_location=&quot;@models&quot;, replace=True)</pre><p>Calling this procedure will execute the Sci-Kit Learn K-Means clustering algorithm iterating over k = 2 to k = 12 on the dataset and return the inertia as an array.</p><pre>max_iter = 12<br>results = session.call(&quot;kmeans_cluster&quot;, max_iter, 1)<br>inertia = np.array(results[1:-1].split(&#39;,&#39;)).astype(float)</pre><p>We can then plot and elbow chart to find the optimal value of k</p><pre>import matplotlib.pyplot as plt<br><br>K = range(2,max_iter)<br>plt.figure(figsize=(16,8))<br>plt.plot(K, inertia, &#39;bx-&#39;)<br>plt.xlabel(&#39;k&#39;)<br>plt.ylabel(&#39;Inertia&#39;)<br>plt.title(&#39;Elbow Chart&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*Y3dd8FPLyGZAnzzigVcOnw.png" /></figure><p>We can see that the optimal value is k = 4</p><p>The final step is to run the clustering again for k=4, and save the results in a table. It’s using the same function kmeans_cluster above (me being lazy), with just a flag to switch the behaviour.</p><pre>max_iter = 4<br>results = session.call(&quot;kmeans_cluster&quot;, max_iter, 0)</pre><h4>Streamlit</h4><p>Now we can see the results in Jupyter, or we can use Streamlit to visualize the cluster, and share it with others! (and build apps as well)</p><p>The app was built on <a href="https://streamlit.io/">Streamlit Cloud</a> that integrates with my Python code for Streamlit on GitHub. In fact, you can connect to Snowpark from Streamlit and use the dataframe directly in charts. What’s cool too, is each commit in GitHub rebuilds the app automatically (without re-installing the packages), so it greatly simplifies the development process. There’s also no need to build an app/web server to host this application, as the deployment is entirely serverless.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffb12dd818dd283c2b1e8d97f12c934b/href">https://medium.com/media/ffb12dd818dd283c2b1e8d97f12c934b/href</a></iframe><h4>So here you go <a href="https://segmentation.streamlit.app/">https://segmentation.streamlit.app/</a></h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fsegmentation.streamlit.app%2F%3Fembed%3Dtrue&amp;display_name=Streamlit&amp;url=https%3A%2F%2Fsegmentation.streamlit.app&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fs4a-prod-share-preview%2Fdefault%2Fst_app_screenshot_image%2Fdc6d4f8d-daaa-4030-bbd3-fca33f356d90%2FHome_Page.png&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=streamlit" width="560" height="630" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9097dcd880f29d061190bb2f30c01b7/href">https://medium.com/media/c9097dcd880f29d061190bb2f30c01b7/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23c680f450e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Market Basket Analysis on Snowpark]]></title>
            <link>https://medium.com/@daniel.ong_3518/market-basket-analysis-on-snowpark-b7e20b16dc99?source=rss-8cf63664e12b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7e20b16dc99</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[market-basket-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[retail]]></category>
            <category><![CDATA[snowpark]]></category>
            <dc:creator><![CDATA[Daniel Ong]]></dc:creator>
            <pubDate>Thu, 27 Oct 2022 15:43:49 GMT</pubDate>
            <atom:updated>2024-03-27T04:53:16.490Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJXSuKjRGjb3vWG27xBweA.jpeg" /><figcaption>Image taken from <a href="http://www.pexels.com/">pexels.com</a></figcaption></figure><h3>Crash course..</h3><p>(If you’re familiar with market basket analysis, or association rules learning feel free to skip to the next section..)</p><p>Market Basket Analysis is a type of unsupervised machine learning for finding out items that are frequently bought together using association rules.</p><p>A rule such as</p><pre>{ Flashlight } -&gt; { Batteries }</pre><p>Which simply says, if someone buys flashlights they also tend to buy batteries.</p><p>The group of items considered is known as the <strong>itemset </strong>(flashlights and batteries).<br>The item(s) on the left is the <strong>antecedent </strong>(flashlight), or a prior event.<br>The item(s) on the right is the <strong>consequent</strong> (batteries), or a posterier event.</p><p><strong>Support </strong>is the percentage of transactions that contain the itemset.</p><p><strong>Confidence</strong> is the proportion of flashlights buyers who have also bought batteries.</p><p><strong>Lift </strong>is confidence/support (of the consequent)<br>It compares confidence to a baseline proportion. So if most people are already buying batteries, you need a higher level of confidence for the model to add value.<br>A lift of 1.5 means that there is an increase of 50% in likelihood that batteries are bought due to its association with flashlights. A lift of 1, although you might have a high confidence means that there is no ‘lift’ or benefit from applying the model. It’s probably just a batteries sale!</p><p>Lift and confidence would be important indicators to look at. Good lift and confidence levels would mean that it makes sense to bundle the items together or place them closer in a rack.</p><p>Take note of this, as we’ll be using these terminologies soon..</p><h3>The Ingredients</h3><p>Where can you get good data in abundance? - wide variety of dimensions, deep level of granularity and nicely cleaned. Just like where you can get good ingredients for your recipe. At the market place!</p><p>I visited Snowflake’s Marketplace to see if I could scout for some data closer to ASEAN and found an interesting dataset of about 1 billion rows on retail point of sales transactions in stores all across Indonesia <a href="https://app.snowflake.com/marketplace/listing/GZSWZ38SCP">here</a> provided by <a href="https://eyos.one/">Eyos</a></p><p>Nice!</p><h3>Washing..</h3><p>A quick look at the data in Snowflake revealed that it’s not perfect. Well, nothing is. Some categories ought to be same, but differed because of typos. Some nulls and ‘-’s here and there. Nothing major.</p><p>So I wrangled the data, grouped similar items together and filtered out the nulls. I also grouped some items so that the proportion of certain categories were high enough to surface up during the association rules learning process.</p><p>Here’s the SQL</p><pre>create or replace table RETAIL_POS as<br>select <br>    case <br>    when product_fmcg_category in (&#39;Assorted Biscuits&#39;,&#39;Biscuit&#39;,&#39;Cookies&#39;,&#39;Crackers&#39;,&#39;Marie Biscuits&#39;,&#39;Other Biscuits&#39;,&#39;Stick Biscuits&#39;,&#39;Wafer&#39;) or contains(product_fmcg_category,&#39;Snack&#39;) then &#39;Snacks&#39;<br>    when product_fmcg_category in (&#39;Coffee Beans&#39;,&#39;Coffee Powder&#39;) then &#39;Coffee Beans/Powder&#39;<br>    when product_fmcg_category in (&#39;Cup Yoghurt&#39;,&#39;Cup Yogurt&#39;,&#39;Drinking Yoghurt&#39;,&#39;Drinking Yogurt&#39;) then &#39;Yogurt&#39;<br>    when product_fmcg_category in (&#39;Face Makeup&#39;,&#39;Makeup - Face&#39;,&#39;Makeup - Lip&#39;,&#39;Eye Makeup&#39;) then &#39;Makeup&#39;<br>    when product_fmcg_category in (&#39;Sweetener&#39;,&#39;Sweeteners&#39;) then &#39;Sweetener&#39;<br>    when product_fmcg_category in (&#39;Prepared/Processed Foods&#39;,&#39;Prepared/Processed Foods (Canned)&#39;,&#39;Prepared/Processed Foods (Frozen)&#39;,&#39;Canned Food&#39;,&#39;Preserved Food&#39;,&#39;Dried Food&#39;) then &#39;Processed Food&#39;<br>    when product_fmcg_category in (&#39;Facial Moisturizer&#39;,&#39;Facial Moisturizing&#39;) then &#39;Facial Moisturizer&#39; <br>    when product_fmcg_category in (&#39;Hair Colorant&#39;,&#39;Hair Coloring&#39;,&#39;Hair Conditioner&#39;,&#39;Hair Styling&#39;,&#39;Hair Treatment&#39;,&#39;Shampoo&#39;) then &#39;Hair Products&#39;<br>    when product_fmcg_category in (&#39;Toothbrush&#39;,&#39;Toothpaste&#39;,&#39;Mouthwash&#39;) then &#39;Oral Hygiene&#39;<br>    when product_fmcg_category in (&#39;Beer&#39;,&#39;Liquor&#39;,&#39;Spirit&#39;,&#39;Whisky&#39;,&#39;Vodka&#39;,&#39;Wine&#39;) then &#39;Alchohol&#39;<br>    when product_fmcg_category in (&#39;Seasoning&#39;,&#39;Seasoning Flour&#39;,&#39;Seasoning Liquid&#39;) then &#39;Seasoning&#39;<br>    when product_fmcg_category in (&#39;Facial Cotton&#39;,&#39;Facial Cleanser&#39;,&#39;Facial Mask&#39;,&#39;Facial Moisturizer&#39;,&#39;Facial Treatment&#39;,&#39;Eye Mask&#39;) then &#39;Face Care&#39;<br>    when product_fmcg_category in (&#39;Shaving Cream&#39;,&#39;Shaving Foam&#39;,&#39;Shaving Razor&#39;) then &#39;Shaving Products&#39;<br>    when product_fmcg_category in (&#39;Fabric Detergent&#39;,&#39;Fabric Freshener&#39;,&#39;Fabric Softener&#39;) then &#39;Fabric Care&#39;<br>    when product_fmcg_category in (&#39;Instant Noodle&#39;,&#39;Instant Porridge&#39;,&#39;Instant Soup&#39;,&#39;Instant Vermicelli&#39;) then &#39;Instant Noodles&#39;<br>    when contains(product_fmcg_category,&#39;Baby&#39;) then &#39;Baby Products&#39;<br>    else product_fmcg_category end as category,*<br>from fmcg_retail_indo.public.raw_mp_id_fmcg where product_fmcg_category not in (&#39;-&#39;,&#39;Null&#39;,&#39;&#39;)</pre><p>First, create a database called FMCG_RETAIL_INDO and then a warehouse through the Snowflake UI.</p><p>After you run the SQL, the new table RETAIL_POS will be created. That’s the table that we’ll be mainly working on.</p><h3>Marinating</h3><p>To get started with Snowpark, follow these instructions <a href="https://docs.snowflake.com/en/developer-guide/snowpark/python/setup.html">here</a></p><p>Snowpark allows you to run your transformations <strong>in situ</strong> on Snowflake through your language of choice — Java, Python, Scala.</p><p>Let’s start by using the Snowpark API to connect to my Snowflake table. For quick reference, the APIs are <a href="https://docs.snowflake.com/en/developer-guide/snowpark/reference/python/_autosummary/snowflake.snowpark.html#">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/131008207ccd9494815ebf5f691dc1a0/href">https://medium.com/media/131008207ccd9494815ebf5f691dc1a0/href</a></iframe><p>I stored all my connection properties in a config file (Note: I used the accountadmin role for convenience, but feel free to relegate that to other roles)</p><p>The &lt;account.region&gt; indicator can be obtained from the Snowflake URL https://&lt;account.region&gt;snowflakecomputing.com</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59ae26b4b7ab21f0dda297adabcfd7f7/href">https://medium.com/media/59ae26b4b7ab21f0dda297adabcfd7f7/href</a></iframe><p>Once connected, you should see the details printed out.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/647574f67a9f66e7453482d1cdbfe9e5/href">https://medium.com/media/647574f67a9f66e7453482d1cdbfe9e5/href</a></iframe><p>The 1st line creates a Snowpark Dataframe from a table in Snowflake — RETAIL_POS. Unlike Pandas, a Snowpark Dataframe does not ‘read’ data locally into your laptop, so the underlying data stays in the server.</p><p>Next, it selects the unique categories listed for each receipt. At this point, nothing is executed yet because Snowflake uses <strong>lazy execution</strong>, like Spark.</p><p>It’s meaningless to have a basket for just 1 category, so I used a windowing function and filtered accordingly.</p><p>Once I hit show(), Snowpark translates the queries into SQL, executes them on Snowflake through the warehouse created, and prints out the first 10 rows.</p><p>Here’s the results</p><pre>--------------------------------------------------<br>|&quot;RECEIPT_ID&quot;  |&quot;CATEGORY&quot;             |&quot;COUNT&quot;  |<br>--------------------------------------------------<br>|171159987     |Soy Sauce              |17       |<br>|236460450     |Jelly &amp; Pudding        |17       |<br>|246035648     |Stock Soup             |17       |<br>|170911774     |Sausage                |17       |<br>|423657600     |Dry Noodle&amp;vermicelli  |17       |<br>|423657600     |Instant Noodles        |17       |<br>|173984214     |Powdered Beverage      |17       |<br>|238183176     |Tissue                 |17       |<br>|164472976     |Jelly Drink            |17       |<br>|335749496     |Baking Needs           |17       |<br>--------------------------------------------------</pre><p>The algorithm used for market basket analysis is only interested in binary states, so</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6579d001bf8115dfe9535928b371669e/href">https://medium.com/media/6579d001bf8115dfe9535928b371669e/href</a></iframe><p>Here’s the results</p><pre>------------------------------------------------<br>|&quot;RECEIPT_ID&quot;  |&quot;CATEGORY&quot;           |&quot;COUNT&quot;  |<br>------------------------------------------------<br>|380134330     |Stock Soup           |1        |<br>|186484793     |Liquid Milk          |1        |<br>|152556930     |Face Care            |1        |<br>|218900953     |Liquid Soap          |1        |<br>|262682466     |Insecticides         |1        |<br>|246919629     |Wet Wipes            |1        |<br>|353627599     |Feminine Protection  |1        |<br>|205326800     |Baking Needs         |1        |<br>|186669916     |Baby Products        |1        |<br>|166151154     |Soy Sauce            |1        |<br>------------------------------------------------</pre><p>Before feeding into the algorithm, I need to pivot the data so that category appears as columns and receipt_id remains as rows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0d3b09b464e70df6f5002bc807a9f9e/href">https://medium.com/media/b0d3b09b464e70df6f5002bc807a9f9e/href</a></iframe><p>The resultant table in Snowflake looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-Q4h_hPV4uaBIqw_PgX7g.png" /></figure><p>What we’ve done so far is known as feature engineering, where we got the data into a shape that can be used for machine learning. This took just a few minutes on ~ 1 billion rows of data.</p><h3>Cooking</h3><p>For market basket analysis, I’m using fpgrowth algorithm from mlxtend Python package to learn the association rules. The usual apriori algorithm works by generating different bags of items bottoms up, and performs many database scans. Bad for large datasets. Fpgrowth on the other hand, only scans the database twice and stores the information in a tree structure (FP-tree). If you’re interested, you can read more about fpgrowth <a href="https://towardsdatascience.com/understand-and-build-fp-growth-algorithm-in-python-d8b989bab342">here</a>.</p><p>Rather than running the learning on my laptop, why not run it all on Snowflake? Sure, we can do that through stored procedures.</p><p>I can continue in the same Jupyter environment, and create the definition below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36e5fe94e6ac332da8c17ba1557282b8/href">https://medium.com/media/36e5fe94e6ac332da8c17ba1557282b8/href</a></iframe><p>Couple of parameters here :</p><ul><li>Min_support=0.01 means that I’m only considering items that appear 1 out of 100 transactions.</li><li>Metric=”Lift” and Min_threshold=1 means that I’m only considering associations lift with &gt; 1</li></ul><p>(refer to my crash course above..)</p><p>Normally, next I’d only need to register the stored procedure in staging for use in Snowflake. In this case, mlxtend is not part of Anaconda library and so likely not part of Snowflake’s server-side Python packages.</p><p>(To see the list of Python packages in Anaconda’s Snowflake channel, go <a href="https://repo.anaconda.com/pkgs/snowflake/">here</a>)</p><p>Not a problem, I can simply import the package with its dependencies over to Snowflake.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b430b959777e6f270ce8fc5ac62e87c/href">https://medium.com/media/5b430b959777e6f270ce8fc5ac62e87c/href</a></iframe><p>How do I know the dependencies? An easy way is to just run pip show mlxtend</p><p>Now I just need to run</p><pre>session.call(&quot;market_basket&quot;, &quot;Encoded&quot;, &quot;Market_Basket_Results&quot;)</pre><p>and the results will be stored in a table — MARKET_BASKET_RESULTS</p><h3>Serving the dish</h3><p>What’s a good dish without nice presentation? So, I used Tableau to visualize the results to answer some of my questions.</p><p><strong>Where are the store locations?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FtKMAdDN2PrAxvuHy5EPxA.png" /></figure><p><strong>What are the frequently bought items?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lo0viwVMCJNsS08LCNTHoA.png" /></figure><p>We can see that liquid milk, chocolate and snacks are often bought together with a confidence level of 0.67</p><p><strong>What are the main frequently bought items?</strong></p><p>Let’s filter to those items with confidence level &gt; 0.5</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqUYBc89ghTOqPd6kmMWEQ.png" /></figure><p>Oddly dishwashing agents, hair products and fabric care are often bought together. 🤔🤷🏻‍♂️</p><p>There must be some serious dishwashing going on there..</p><p>Well, here’s my <a href="https://github.com/dan1elong/mba">code</a> on GitHub</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7e20b16dc99" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>