<?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 Jaelin Lee on Medium]]></title>
        <description><![CDATA[Stories by Jaelin Lee on Medium]]></description>
        <link>https://medium.com/@jaelin_75015?source=rss-fd55dece4858------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Q4jLmwyOU-lD79ntVzLglA.jpeg</url>
            <title>Stories by Jaelin Lee on Medium</title>
            <link>https://medium.com/@jaelin_75015?source=rss-fd55dece4858------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:32:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jaelin_75015/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[How to set up Snowflake SQS Notification]]></title>
            <link>https://medium.com/@jaelin_75015/how-to-set-up-snowflake-sqs-notification-43463ac567b4?source=rss-fd55dece4858------2</link>
            <guid isPermaLink="false">https://medium.com/p/43463ac567b4</guid>
            <category><![CDATA[aws-sqs]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[snowpipe]]></category>
            <dc:creator><![CDATA[Jaelin Lee]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 20:24:28 GMT</pubDate>
            <atom:updated>2025-08-26T20:24:28.426Z</atom:updated>
            <content:encoded><![CDATA[<p>Integrating AWS S3 bucket with Snowflake staging</p><h3>Objective: Setting Up Notifications Between S3 and Snowpipe in Snowflake</h3><ul><li>Reference: <a href="https://docs.snowflake.com/en/user-guide/data-load-snowpipe-auto-s3">https://docs.snowflake.com/en/user-guide/data-load-snowpipe-auto-s3</a></li></ul><h3>How To:</h3><h3>1/ Create a Snowpipe</h3><p><strong>1. Verify Pipe Creation</strong></p><ul><li>Confirm that you have created the Snowpipe correctly.</li><li>Check the integration settings to ensure everything is linked properly.</li></ul><p><strong>2. Create and Describe the Pipe</strong></p><ul><li>Create a pipe procedure for your JSON files.</li><li>Specify the source stage (your S3 bucket) and the destination table in Snowflake.</li></ul><p><strong>3. Document the Process</strong></p><ul><li>Keep track of the pipe name and the SQS queue ARN for future reference in next step below.</li></ul><h3>2/ Set Up Event Notifications in S3 Bucket Properties</h3><p><strong>1. Access S3 Bucket Properties</strong></p><ul><li>Navigate to your S3 buckets in AWS.</li><li>Go to the ‘Properties’ section.</li><li>Locate the ‘Event Notification’ section.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGCrsORxYsaroOiLw1lEVg.png" /></figure><p><strong>2. Create a Snowpipe</strong></p><ul><li>Initially, create a Snowpipe in Snowflake.</li><li>Note that this process diverges to replace the table entirely instead of adding rows.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0pR72Awk56tcclib43t03Q.png" /></figure><p><strong>3. Set Up Event Notifications</strong></p><ul><li>Ensure you have an external S3 connection to Snowflake.</li><li>Set up SQS event notifications to ingest data into the Snowpipe.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*px1tgfLzFPV8px4fk8hMpQ.png" /><figcaption><a href="https://docs.snowflake.com/en/user-guide/data-load-snowpipe-auto-s3">https://docs.snowflake.com/en/user-guide/data-load-snowpipe-auto-s3</a></figcaption></figure><p><strong>4. Configure S3 Bucket for Notifications</strong></p><ul><li>Inside your S3 bucket, create a notification for Snowpipe events.</li><li>Specify the event types for which you want to receive notifications (e.g., ‘Put’ or ‘Copy’ actions).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uDm7joFTY2fhbsZpqzEF4Q.png" /></figure><p><strong>5. Choose Notification Destination</strong></p><ul><li>Set the destination for notifications to an SQS queue.</li><li>Enter the SQS queue ARN (Amazon Resource Name) for Snowflake.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRYhxYfUv5dULjm7s6yDrw.png" /></figure><p>Done!</p><h3>Final State:</h3><ul><li>Above set up results in a notification from S3 to Snowflake staging whenever update happens in the S3 bucket.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43463ac567b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up Slack Webhook to Receive Messages]]></title>
            <link>https://medium.com/@jaelin_75015/how-to-set-up-slack-webhook-to-receive-messages-3fb6b3fdc91b?source=rss-fd55dece4858------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fb6b3fdc91b</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[slackbot]]></category>
            <category><![CDATA[webhooks]]></category>
            <dc:creator><![CDATA[Jaelin Lee]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 23:48:22 GMT</pubDate>
            <atom:updated>2025-06-25T23:48:22.281Z</atom:updated>
            <content:encoded><![CDATA[<p>In my process of developing an Agentic AI tool, Slack webhook integration was chosen for a quick demo.</p><blockquote>ONE THING:</blockquote><blockquote>Step-by-step implementation guide to send alert to Slack workspace from other sources like GitHub Actions.</blockquote><h3>Reference:</h3><ul><li><a href="https://api.slack.com/messaging/webhooks">https://api.slack.com/messaging/webhooks</a></li><li><a href="https://tools.slack.dev/python-slack-sdk/webhook/">https://tools.slack.dev/python-slack-sdk/webhook/</a></li></ul><h3>STEP 1: Create Slack app</h3><ul><li>Go to <a href="https://api.slack.com/apps?new_app=1"><strong>https://api.slack.com/apps</strong></a> &gt; <strong>Create an App</strong> &gt; <strong>From scratch</strong></li><li>Choose <strong>App Name</strong></li><li>Choose <strong>workplace</strong> to develop your app (If you don’t see a workplace that you want, you can login with your other accounts. If you still don’t see the workplace your want in the dropdown, you can also create a new workspace — which I did).</li><li><strong>What apps are unsuitable for Slack Marketplace?</strong> Refer to this guide (<a href="https://api.slack.com/slack-marketplace/guidelines">https://api.slack.com/slack-marketplace/guidelines</a>)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*_vOM_MEBA2XDQ7tw-H_9aQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zyADkam0-q9sTzQ8g1_A4Q.png" /></figure><h3>STEP 2: Save App Credentials</h3><ul><li>Save app credentials to a secure place</li><li>Update App description</li><li><strong>Save Changes</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9SlZ4YOWJ2KzpvdUKGkRVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WmgT21ZKguBWt7co9ctTvw.png" /></figure><h3>STEP 3: Set Up an Webhook</h3><p>There are many interesting interactive options like adding interactive buttons, bots, slash commands, etc. But, for now, we are going to focus on setting up incoming webhooks (i.e. <strong>POST </strong>messages to Slack).</p><ul><li>Manage Distribution &gt; Enable Features &amp; Functionality &gt; <strong>Incoming Webhooks</strong></li><li>Toggle <strong>ON </strong>to activate incoming webhooks</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PHR7C6cQXtlu6R98aKEUXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*ilwByuhIehUQ-PcApuZi1Q.png" /></figure><h3>STEP 4: Test Webhook in Postman</h3><ul><li>Add App credentials to <strong>Postman</strong> <strong>Environments</strong> as variables</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWOcRicItqwCHPFYA5F7yQ.png" /></figure><ul><li>Create a new collection in Postman: <strong>Collection &gt; Slack</strong></li><li>Set Auth: <strong>Authorization</strong> &gt; <strong>Auth Type</strong> &gt; <strong>Basic Auth</strong></li><li>Enter <strong>Username</strong> and <strong>Password</strong> from Environment Variables.</li><li>‼️This is the most secure way to handle secret keys in Postman. Please avoid directly entering keys in here. And, make sure to use the environment variables as shown below in the screenshot.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pP5Cqqvbc1MiKEnpeBqC5g.png" /><figcaption>Secret keys imported from Environment variables</figcaption></figure><ul><li>Send a new request to check to see if the webhook works.</li><li><strong>New Request</strong> &gt; <strong>POST</strong> &gt; {{ your_slack_webhook_url }}</li><li><strong>Body</strong> &gt; <strong>raw</strong> &gt; <strong>JSON</strong> &gt; {“text”: “Hello, World!”}</li><li>If you see the response at the bottom as <strong>200 OK</strong>, you’re all good!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFmLQulP-rrTfEJYCm2b4A.png" /><figcaption>200 OK</figcaption></figure><h3>STEP 5: Install the App to your Workspace</h3><ul><li>Install App &gt; Install to (your-workspace)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7R89ouTjoZig0W1DVux-PQ.png" /></figure><ul><li><strong>Dropdown</strong> &gt; <strong>Select or create</strong> a new <strong>channel</strong> &gt; <strong>Allow</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SeWP5Vrrt0qeDI50CWkWWw.png" /></figure><ul><li>Copy OAuth token (<a href="https://api.slack.com/authentication/oauth-v2">https://api.slack.com/authentication/oauth-v2</a>)</li></ul><p><strong>STEP 5: Check Installed App</strong></p><ul><li>Log in to Slack to see the installed App</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MOpmfbU9fZK5J9BVs1swAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FX0BIL2zTs-xd5x9Xvu6jQ.png" /><figcaption>Slackbot</figcaption></figure><h3>SUCCESS!</h3><p>That’s all. Now, you can connect this Slack app to your other web clients. I’ve connected mine with GitHub Actions to receive scheduled daily notifications as Slack messages. I can share how to set up that integration in my next post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fb6b3fdc91b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full-Stack ML Pipeline in One GitHub Codespace (Docker, FastAPI, GCP — Cloud Storage, BigQuery — …]]></title>
            <link>https://medium.com/@jaelin_75015/full-stack-ml-pipeline-in-one-github-codespace-docker-fastapi-gcp-cloud-storage-bigquery-a56a6cfbdd19?source=rss-fd55dece4858------2</link>
            <guid isPermaLink="false">https://medium.com/p/a56a6cfbdd19</guid>
            <category><![CDATA[looker]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[github-codespaces]]></category>
            <dc:creator><![CDATA[Jaelin Lee]]></dc:creator>
            <pubDate>Wed, 21 May 2025 21:41:49 GMT</pubDate>
            <atom:updated>2025-06-03T14:25:52.684Z</atom:updated>
            <content:encoded><![CDATA[<h3>TariffRisk — Full-Stack ML Pipeline in One GitHub Codespace (Docker, FastAPI, GCP, Cloud Storage, BigQuery, Looker)</h3><p>Set up a real end-to-end ML pipeline — fast — with just your dev environment and GitHub Codespaces.</p><p>Ever felt stuck between a ML idea and the messy reality of gluing everything together?</p><p>This template is for you. Whether you’re prototyping a risk model or just want to get your hands dirty with real infrastructure, this GitHub Codespace setup helps you launch a working ML pipeline — fast. It connects GitHub, GCS, BigQuery, FastAPI, and GitHub Actions in a clean, modular way. No yak shaving. Just signal.</p><p>In this walkthrough, I’ll show you how to take a real dataset (i.e. Trump Tariffs Data 2025), automate ingestion and transformation, and set up a baseline API + dashboard — all without leaving your dev environment.</p><blockquote><em>🎯 </em><strong><em>The ONE THING</em></strong><em>: By the end of this walkthrough, you’ll have a reproducible pipeline that pulls data from GCS, transforms it into BigQuery, serves an API with FastAPI, and visualizes insights with Looker — all deployable via GitHub Actions.</em></blockquote><h3>What You’ll Use</h3><ul><li><strong>GitHub Codespaces</strong>: Cloud dev environment, preconfigured</li><li><strong>GitHub Actions</strong> (CI/CD)</li><li><strong>FastAPI</strong>: Lightweight backend for serving models</li><li><strong>Pytest</strong> (unit testing)</li><li><strong>Docker</strong>: Containerization for consistency</li><li><strong>Makefile</strong></li><li><strong>GCS</strong> (Google Cloud Storage — unstructured/structured) — create a bucket</li><li><strong>Google BigQuery</strong> (SQL based data lake — structured)</li><li><strong>Looker Studio</strong> (<a href="https://lookerstudio.google.com/">https://lookerstudio.google.com/</a>) — Visualize</li></ul><h3>Dataset</h3><ul><li>Kaggle — Trump Tariff Data 2025 (<a href="https://www.kaggle.com/datasets/mesumraza/trump-tarrif-data">https://www.kaggle.com/datasets/mesumraza/trump-tarrif-data</a>)</li></ul><h3>Folder Structure</h3><p>Separation of concerns:</p><ul><li><strong>src</strong>/: app code (API, endpoints, ML models)</li><li><strong>pipeline</strong>/: data ingestion, transformation, deployment</li><li><strong>config</strong>/: configurations and environment settings</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*LTESwsTTyCu6MHdsKaZglw.png" /><figcaption>Folder Structure (High-level)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IHrHqs7U5A9FDAEWoVIPew.png" /><figcaption>Folder structure (Expanded)</figcaption></figure><h3><strong>What This Pipeline Does: The 8 Key Parts</strong></h3><ol><li><strong>Build &amp; Service FastAPI app: Serving Your ML App</strong></li><li><strong>Unit Testing with PyTest</strong></li><li><strong>Set up GitHub Actions — Automate a data ingestion + preprocessing</strong></li><li><strong>Create GCP Service Account</strong></li><li><strong>Add GCP Service Account secret to GitHub Action</strong></li><li><strong>GitHub Action</strong></li><li><strong>Create GCP Resources</strong></li><li><strong>Visualized in Looker Studio: Tariff Risk Dashboard</strong></li></ol><h3>1. Build &amp; Service FastAPI app: Serving Your ML App</h3><ul><li>Based URL (https://your-code-space-8000.app.github.dev)</li><li>FastAPI auto-generates a Swagger UI at /docs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w6Hl7fMm-FIDUqDnDVUjbQ.png" /><figcaption>Swagger UI (FastAPI auto-generates it at /docs)</figcaption></figure><ul><li>If you want to try it using CURL command:</li></ul><pre>curl -X POST http://localhost:8000/hello \<br>-H &quot;Content-Type: application/json&quot; -d &#39;{&quot;name&quot;: &quot;Jaelin&quot;}&#39;</pre><h3>2. Unit Testing with PyTest</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ndOmtZWG5kyzpF4JeVFlcA.png" /><figcaption>3 unit tests — Passed (pytest tests)</figcaption></figure><h3><strong><em>From Local Confidence to Cloud Automation</em></strong></h3><blockquote><em>You’ve built a working FastAPI app, tested it with real data, and verified that your logic holds. But serving a single request from a Codespace isn’t enough — especially when your pipeline needs to run reliably, at scale, and without human intervention.</em></blockquote><blockquote><em>Now it’s time to shift from development to deployment.</em></blockquote><blockquote><em>In this next step, we’ll automate your data pipeline so it runs seamlessly on GCP, triggered by GitHub Actions. You’ll create a service account, set up secure permissions, and wire your ingestion + transformation steps to run on commit — no manual triggers, no surprises.</em></blockquote><blockquote><em>This is where your ML project becomes real infrastructure.</em></blockquote><h3>3. Set up GitHub Actions — Automate a <strong>data ingestion + preprocessing</strong></h3><ul><li>Read the Trump_Tariff_Data.xlsx from <strong>GCS</strong></li><li>Preprocess and upload selected features to <strong>BigQuery</strong></li><li>Keep FastAPI app clean and focused on API logic.</li></ul><h3>4. Create GCP Servie Account</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VdAlV-CvaaohOsZ3diLQTQ.png" /><figcaption>Data ingestion pipeline service account (SA) from GCS to BigQuery</figcaption></figure><h3>5. Add GCP Service Account secret to GitHub Action</h3><ul><li>Settings &gt; Secrets and variables &gt; New repository secret</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xdix9vAnZT6C3HWZ11a03Q.png" /></figure><h3>6. GitHub Action</h3><p>Run the GCP pipeline logic <em>only</em> from the GitHub Action (not from the FastAPI app (main.py) itself).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rw2hl_bNA2EZ4amyzqdIXQ.png" /></figure><ul><li>Add principals (service account email: xxx.iam.gserviceaccount.com)</li></ul><pre>Role &gt; Storage Object Viewer<br>Role &gt; BigQuery Data Editor<br>Role &gt; BigQuery Job User</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kEBGeyCnmZ8kw9vMYjt3PA.png" /><figcaption>Updated SA Access</figcaption></figure><blockquote>With data now structured in BigQuery, let’s visualize insights that could shape merchant strategy.</blockquote><h3>7. Create GCP Resources</h3><p>Project: your-project</p><ul><li><strong>Bucket</strong>: gs://your_bucket</li><li><strong>Input File</strong>: your_data.xlsx (upload file via Cloud Storage UI)</li><li><strong>Dataset</strong>: your_dataset</li><li><strong>Output Table</strong>: risk_features</li></ul><ol><li><strong>Create a Cloud Storage (GCP Project &gt; Cloud Storage)</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4rb2ju9LTMwV7f6PH0dqQ.png" /><figcaption>Cloud Storage — cost is minimal small data with low usage (&lt;$1/month)</figcaption></figure><p><strong>2. Create a bucket (GCP Project &gt; Cloud Storage &gt; Create a bucket)</strong></p><p><strong>3. Create a dataset (BigQuery &gt; Project &gt; create dataset)</strong></p><ul><li>config.yaml</li><li>Data location: northamerica-northeast1</li><li>Dataset ID: us-tariff-project.tariff_risk_dataset</li><li>path convention: {project_id}.{dataset}.{table_name}</li></ul><pre># config.yaml<br>gcp:<br>  project: your-project<br>  bucket: your_bucket<br>  input_file: your_data.xlsx<br>  dataset: your_dataset<br>  output_table: risk_features</pre><h3>8. Visualized in Looker Studio: Tariff Risk Dashboard</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dh71lzcfXXzB8txBgFNBsQ.png" /><figcaption>Looker Studio Account Setup</figcaption></figure><ul><li>Initial dashboard visualizing Trump-era tariff responses by country. This report serves as a baseline to explore potential trade risks. Future updates will introduce merchant-specific risk scoring based on trade patterns and tariff impact on their merchandise.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TvWrob5yIRlY2l90g2Z15g.png" /><figcaption><a href="https://lookerstudio.google.com/reporting/a09627ea-e36a-42e9-ae2f-284c27800ef7">https://lookerstudio.google.com/reporting/a09627ea-e36a-42e9-ae2f-284c27800ef7</a></figcaption></figure><h3>Final Thought: Build What Matters</h3><blockquote>You now have a live pipeline, API, and dashboard — all from your Codespace. The hard part isn’t infra anymore. It’s deciding: what’s the <strong>one insight</strong> your users truly need?</blockquote><blockquote>Maybe it’s a merchant risk score. Maybe a trade warning alert. This setup is your launchpad. Start with that next signal. Strip away noise. Build the thing that matters.</blockquote><blockquote>(Coming soon: Merchant risk scoring and Looker automation. Follow to stay in the loop.)</blockquote><p>References:</p><ul><li>GitHub source code: <a href="https://github.com/jaelin215/TariffRisk">https://github.com/jaelin215/TariffRisk</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a56a6cfbdd19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DoWhy — Causal Inference]]></title>
            <link>https://medium.com/@jaelin_75015/dowhy-causal-inference-1aa62cab1d8e?source=rss-fd55dece4858------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aa62cab1d8e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[dowhy]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[causal-inference]]></category>
            <dc:creator><![CDATA[Jaelin Lee]]></dc:creator>
            <pubDate>Wed, 14 May 2025 18:12:58 GMT</pubDate>
            <atom:updated>2025-05-14T19:03:06.840Z</atom:updated>
            <content:encoded><![CDATA[<h3>DoWhy — Causal Inference</h3><p>Understanding and interpreting causal inference results</p><p><strong>“What’s the ONE insight about your data that, if you truly understood it, would change every decision you make?”</strong></p><p>In this article, I explore that one insight through the lens of causal inference using DoWhy — not just asking <em>what </em>correlates, but uncovering <em>why</em> things happen. We’ll look at a simple, real-world question: <em>Does taking vitamins daily really improve your energy levels?</em></p><p><em>“Let’s apply this mindset to a common health behavior: does taking vitamins really boost energy?”</em></p><h3>Reference:</h3><ul><li>GitHub: <a href="https://github.com/py-why/dowhy">https://github.com/py-why/dowhy</a></li><li>Data: synthetic data (5,000 rows)</li><li>Code Notebook: <a href="https://github.com/jaelin215/causal_inference/blob/main/dowhy.ipynb">https://github.com/jaelin215/causal_inference/blob/main/dowhy.ipynb</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2cZ9xyo7xrvt-Fi18Wfldw.png" /><figcaption>sample input dataset</figcaption></figure><h3>Terminologies:</h3><ul><li>Objective: Does <strong>taking vitamins</strong> causally affect <strong>energy level</strong>?</li><li>Treatment (v0)</li><li>Outcome (y)</li><li>Confounders (w0,w1,w2,…): Variables that affect <strong>both</strong> taking vitamins and energy level (e.g., sleep, diet, income, exercise). → Must be adjusted for to block <strong>backdoor paths</strong>.</li><li>Instruments (z0,z1,z2…): Variables that affect <strong>only</strong> taking vitamins, not energy directly (e.g., prescription, having vitamins at home). → Used to identify causal effects when confounders can’t be fully observed or adjusted for.</li><li>Effect modifier (x0,x1,…): Variables that may <strong>change the strength or direction of the treatment effect</strong> (e.g., age group, gender). → Help analyze <strong>heterogeneous treatment effects</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-j9T3obyDJUozXbATqEgbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UeMEG0thFHV74CBfsBiECQ.png" /><figcaption>renamed input dataset</figcaption></figure><h3>Input Data</h3><ul><li>Treatment (v0): binary (binomial), categorical, continuous</li><li>Outcome (y)</li><li>Confounders (w0,w1,w2,…), Instruments (z0,z1,z2…), Effect modifier (x0,x1,…): must be <strong>numeric </strong>because most modeling steps (i.e. regression, propensity scoring, or ML models) required numeric inputs.</li></ul><h3>Encode Data</h3><ul><li>one-hot encoding (i.e. pd.get dummies)</li><li>label encoding (if variables are natural order)(i.e. age, temperature, etc.)</li></ul><h3>Scale Data (optional)</h3><ul><li>Especially useful if using ML models as the back-end estimator (i.e. Random forest, XGBoost)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*dP2UdP3xwkS4IG9hS6USXw.png" /><figcaption>Causal DAG</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gee_uU82gbyY2AodDxRXQQ.png" /></figure><h3>Results</h3><ul><li>Causal Estimate: 0.1783</li><li>This means that taking vitamins daily increases normalized energy level by ~0.178 units on average, holding the confounders constant.</li><li>Outcome scale: Since you normalized energy_level (e.g., between 0 and 1), the effect is now interpreted on that scale.</li><li>Taking vitamins daily is associated with an average 17.8% increase in normalized energy level, controlling for confounders.</li></ul><h3>Assumptions</h3><ul><li>The estimate relies on the backdoor criterion, which assumes:</li><li>All confounders that affect both the treatment (takes_vitamins_daily) and the outcome (energy_level) are observed and included (like workout, sleep, etc.).</li><li>There are no unobserved confounders (i.e., the assumption of unconfoundedness holds).</li></ul><h3>Refutation</h3><ul><li>Refutations don’t prove that the estimate is “true,” but they increase confidence that it’s not an artifact of bias or model instability.</li><li>It’s still crucial that your <strong>confounders are correctly specified</strong> and there’s <strong>no hidden confounding</strong>.</li><li>Since the p-values of all refutations are above 0.05, we fail to reject the null hypothesis that the estimated causal effect remains unchanged under perturbations.</li><li>Therefore, the causal estimate of 0.178 (or an 17.8% increase in normalized energy level from daily vitamin intake) is robust to refutations and likely reliable, assuming model assumptions hold.</li></ul><h3>Understanding ATE, ATT, and ATC</h3><p><strong>ATE (Average Treatment Effect):</strong></p><ul><li>Represents the average effect of the treatment (e.g., taking vitamins) across the <strong>entire population</strong>, regardless of whether individuals actually received the treatment.</li><li><strong>Use it when:</strong> you want a <strong>broad policy insight</strong> or a generalizable conclusion.</li></ul><p><strong>ATT (Average Treatment Effect on the Treated):</strong></p><ul><li>Measures the effect <strong>specifically on those who actually received the treatment</strong>.</li><li><strong>Use it when:</strong> you want to understand how effective the treatment was <strong>for the people who took it</strong> — useful in program evaluation or user personalization.</li></ul><p><strong>ATC (Average Treatment Effect on the Control):</strong></p><ul><li>Estimates the hypothetical effect <strong>on those who didn’t receive the treatment</strong>, had they received it.</li><li><strong>Use it when:</strong> you want to <strong>forecast the benefit for new or untreated groups</strong> — essential for expansion planning or targeting new users.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*P9AwhxlRw-FpOH6aQ8LBDA.png" /><figcaption>ATE/ATT/ATC</figcaption></figure><h3>Why ATE/ATT/ATC Matters</h3><p>These metrics let you tailor decision-making:</p><ul><li><strong>Policy makers</strong> use ATE to justify broad adoption.</li><li><strong>Product teams</strong> use ATT to assess impact on current users.</li><li><strong>Growth teams</strong> use ATC to identify the potential gain for new user segments.</li></ul><h3>Practical Deployment: Bringing Causal Inference to the Cloud</h3><p>In a real-world, cloud-first ML pipeline, causal inference models like DoWhy fit seamlessly into the decision intelligence layer. After the data ingestion and preprocessing stages (via tools like Apache Airflow or AWS Glue), your causal analysis script can run as a modular job — e.g., in a Jupyter notebook orchestrated by SageMaker, Vertex AI, or Azure ML. This component doesn’t replace predictive ML models; instead, it <strong>complements them</strong> by answering <em>why</em> something happens, not just <em>what</em> will happen. Results from DoWhy can be logged and visualized via dashboards (like Streamlit or Looker), helping decision-makers act on insights that are <strong>statistically grounded and policy-relevant</strong>. It turns analytics into strategy.</p><p>Raw Data (RDS / S3 / BigQuery)<br> ↓<br>Data Processing &amp; Encoding (e.g., Pandas, Spark, AWS Glue)<br> ↓<br>Feature Store or Data Lake<br> ↓<br>Causal Modeling (DoWhy)<br> ↓<br>Effect Estimate + Refutation Results<br> ↓<br>Visualization / API Layer (Streamlit, Dash, Looker)<br> ↓<br>Decision Support (marketing, health policy, A/B test design)</p><h3><strong>The ONE Thing to Remember</strong></h3><p>In a world flooded with data, correlation is cheap — but causation is powerful. With DoWhy, we move beyond surface-level patterns to uncover true drivers of change.</p><p>So the next time you’re swimming in metrics, pause and ask: <em>What’s the one intervention that would actually move the needle?</em></p><p>Find that, and you stop guessing — you start leading.</p><p><em>“Curious what your data is really saying? Run this notebook and find out.”</em></p><p><a href="https://github.com/jaelin215/causal_inference/blob/main/dowhy.ipynb">https://github.com/jaelin215/causal_inference/blob/main/dowhy.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aa62cab1d8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parquet, Arrow, LFS, Fuzzywuzzy]]></title>
            <link>https://medium.com/@jaelin_75015/parquet-arrow-lfs-fuzzywuzzy-3cc9d9d57e85?source=rss-fd55dece4858------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cc9d9d57e85</guid>
            <category><![CDATA[hugging-face-datasets]]></category>
            <category><![CDATA[arrow-file]]></category>
            <category><![CDATA[parquet-file]]></category>
            <category><![CDATA[git-lfs]]></category>
            <category><![CDATA[fuzzywuzzy]]></category>
            <dc:creator><![CDATA[Jaelin Lee]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 02:00:51 GMT</pubDate>
            <atom:updated>2024-09-04T02:00:51.261Z</atom:updated>
            <content:encoded><![CDATA[<p>What is parquet file format and how to use it?</p><p>Parquet file is a compressed file format that allows efficient reading/filtering of dataset. You can download it to your local cache. Once it’s in the local cache, it doesn’t try to download it again.</p><h4>Reference:</h4><ul><li>Apache parquet — <a href="https://github.com/apache/parquet-format">https://github.com/apache/parquet-format</a></li><li>Apache arrow — h<a href="https://github.com/apache/arrow">ttps://github.com/apache/arrow</a></li><li>LFS — <a href="https://git-lfs.com/">https://git-lfs.com/</a></li></ul><h4><strong>Benefit</strong>:</h4><p>Efficient storage and I/O operations for large datasets</p><h4>Terminologies:</h4><ul><li><strong>Parquet</strong> is a columnar storage file format. It’s a format that is saved to local drive cache.</li><li><strong>Arrow</strong> is a columnar storage file format of Apache. It’s a binary file that stores a series of arrow data. Often used in conjunction with parquet file. Similar to parquet, but different. Arrow file actually contains data itself, not just a reference. Data can be saved to a local disk in parquet, but can be loaded to a memory in arrow format. These files can be read and processed directly in memory using libraries that support the Arrow format, such as pyarrow in Python.</li><li><strong>LFS</strong> is a file format that saves data to a remote server. In your GitHub, DagsHub, HuggingFace repository, it only has a small pointer file. So, your repository is not slowed down with a large dataset.</li><li><strong>checksum</strong> is a value used to verify the integrity of a file or data. It detects errors that may have been introduced during its transmission or storage. (If null, it indicates that checksum value is missing. This means that the integrity of data cannot be verified. It doesn’t mean that it’s not corrupt.)</li><li><strong>local cache</strong> is not an inherent feature of parquet file. Some platforms like HuggingFace saves it to local cache. And, it won’t redownload it unless it’s moved or modified. (i.e. hugging face local cache file path: ‘<strong>/Users/jaelinlee/.cache/huggingface/datasets/</strong>harvard-lil___cold-cases/default/0.0.0/5d8d0d8457ef63b6463af9737da21d3badd924ad/cold-cases-train-00000-of-00139.arrow)</li><li><strong>Shards</strong> refer to pieces or segments of a larger dataset. Sharding is a technique used to divide a large dataset into smaller, more manageable parts. It helps with parallel processing, distributing data to multiple systems, loading only necessary shard.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L2p5V1YM80I2nGoUklMChQ.png" /><figcaption>a parquet file from huggingface stored in LFS remote server. it will take up 1.13GB in local disk once downloaded. Within this huggingface COLD-CASE repo, it only has a pointer file. This pointer file (135 Bytes) references the actual Parquet file (1.13GB) stored on the Git LFS remote server</figcaption></figure><h4>Hugging Face dataset — Filter</h4><ul><li>Filtered based on each arrow file’s date_filed column value.</li><li>Only kept cases that were filed on and after 1964–01–01</li><li>filter ([True/False,…])</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jQ-q-8R-JwSxv3u6VCcmmg.png" /><figcaption>Parquet file filter is directly applied to the dataset (no need to open the dataset. took ~ 9min)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRLusoLSpfAAYnDEP7subw.png" /><figcaption>downloaded huggingface dataset is in .arrow format. And, it’s saved to local cache.</figcaption></figure><pre># local cache file path:<br>&#39;/Users/jaelinlee/.cache/huggingface/datasets/.../.../xxx.arrow</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oa201GL958A9uXY-ovZSmA.png" /><figcaption>Check the size of each arrow file (56 Bytes)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XB14VrmxhMyGK2iX47Y-Qg.png" /><figcaption>Failed to save hf downloaded dataset (arrow files) to a local folder. I don’t think this step is necessary.</figcaption></figure><h4>Hugging Face dataset — Fuzzy filter</h4><ul><li>An array of [True, False, …]</li><li><strong>Fuzzywuzzy</strong> (<a href="https://pypi.org/project/fuzzywuzzy/">https://pypi.org/project/fuzzywuzzy/</a>)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQ_dsxVqC_xnzJcH6D1b8w.png" /><figcaption>Fuzzy logic match took 2 hours to process</figcaption></figure><p><strong>High Threshold (90–100)</strong>: Use this when you need very precise matches. This is appropriate for cases where even small differences are important.<br><strong>Medium Threshold (70–89)</strong>: Suitable for general fuzzy matching where some degree of difference is acceptable. — -&gt; since there are sometimes some additional elements like * and so on between elements of the string sometimes I went with this, this will also address “case-sensitivness”. but in general, the opinions write key legislation they refer to this way “Title VII of the Civil Rights Act of 1964”…<br><strong>Low Threshold (60–69 or lower)</strong>: Use this if you want to capture even loosely related matches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v2rHNSf4vlHdjT0vX0nMPw.png" /><figcaption>check if a keyword exists in each string</figcaption></figure><h4>Convert HF dataset to DataFrame</h4><pre>from datasets import load_from_disk<br>path = &#39;/content/drive/MyDrive/cold-cases-data/train&#39;<br>dataset = load_from_disk(path)<br><br># Display the dataset<br>print(dataset)<br><br># Convert to Pandas DataFrame if needed<br>df = dataset.to_pandas()<br><br># Display the DataFrame<br>df.head()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cc9d9d57e85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sort, Filter Arrow Files (.arrow)]]></title>
            <link>https://medium.com/@jaelin_75015/sort-filter-arrow-files-arrow-09f1e9f7f2ff?source=rss-fd55dece4858------2</link>
            <guid isPermaLink="false">https://medium.com/p/09f1e9f7f2ff</guid>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[sort]]></category>
            <category><![CDATA[arrow-file]]></category>
            <category><![CDATA[filters]]></category>
            <category><![CDATA[hugging-face]]></category>
            <dc:creator><![CDATA[Jaelin Lee]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 01:05:51 GMT</pubDate>
            <atom:updated>2024-09-04T01:05:51.325Z</atom:updated>
            <content:encoded><![CDATA[<p>Hugging Face datasets arrow files are loaded and sorted, filtered</p><h3>1. Download dataset from Hugging Face</h3><h4>1.1 — load_dataset (harvard-lil/cold-cases) (Option 1)</h4><ul><li><a href="https://huggingface.co/datasets/harvard-lil/cold-cases">https://huggingface.co/datasets/harvard-lil/cold-cases</a></li><li>file type: .arrow</li><li>8,362,176 cases</li></ul><pre>from datasets import load_dataset<br><br>dataset = load_dataset(&quot;harvard-lil/cold-cases&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3B5wEhoO76yZJHpYq-lCw.png" /><figcaption>took 4.5 sec to load dataset</figcaption></figure><h4>1.2 — load_from_disk (`<strong>clean`</strong> folder) (Option 2)</h4><ul><li>Within folder there are 3 arrow files (00000, 00001, 00002)</li><li>Total 27,798 cases</li></ul><pre>import re<br>import datetime<br>import pandas as pd<br>from datasets import load_from_disk<br><br># load arrow files by providing a folder name that includes them<br>clean_dataset = load_from_disk(&#39;/Users/jaelinlee/Documents/projects/case_law/hanieh/clean&#39;)<br>clean_dataset<br><br># Convert &#39;date_filed&#39; to datetime if it&#39;s not already<br>def convert_to_date(example):<br>    example[&#39;date_filed&#39;] = pd.to_datetime(example[&#39;date_filed&#39;])<br>    return example<br><br># Apply the conversion<br>dataset = dataset.map(convert_to_date)<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SxhbwjuKaksCMfBqN5XG3w.png" /><figcaption>dataset loaded</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*tF4Z8yk5GSEqvWEAScvakw.png" /><figcaption>‘clean’ folder has 3 <strong>.arrow</strong> files</figcaption></figure><h3>2. Clean dataset</h3><h4>2.1. filter by date</h4><ul><li>(date_filed &gt;= 1964–01–01)</li><li>5,622,025 cases (reduced to 67%)</li></ul><pre>import re<br>import datetime<br>import pandas as pd<br>from datasets import load_dataset<br><br># Define the cutoff date<br>cutoff_date = datetime.date(1964, 1, 1)<br><br># Filter the dataset<br>filtered_dataset = dataset.filter(lambda x: x[&#39;date_filed&#39;] &gt;= cutoff_date)<br>filtered_dataset</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k9KgtCSMtCxu0EEUi53tgw.png" /><figcaption>took 8m 30s to filter by date</figcaption></figure><h4>2.2. filter by regex</h4><ul><li>(<strong>r</strong>’\bTitle VII of the Civil Rights Act of 1964\b’)</li><li>Total 28,403 cases</li></ul><pre># Define your regex filter function<br>def regex_filter_opinions(example):<br>    pattern = r&#39;\bTitle VII of the Civil Rights Act of 1964\b&#39;<br>    if example[&#39;opinions&#39;] is not None:<br>        for opinion in example[&#39;opinions&#39;]:<br>            if isinstance(opinion[&#39;opinion_text&#39;], str):<br>                opinion_text = opinion[&#39;opinion_text&#39;]<br>                if re.search(pattern, opinion_text, re.IGNORECASE):<br>                    return True<br>    return False<br><br># Apply the filter to the dataset<br>title_vii_dataset = filtered_dataset.filter(regex_filter_opinions)<br>title_vii_dataset</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uY94nJ43vLzcxHPXdAOVlw.png" /><figcaption>took 22m to filter for TitleVII</figcaption></figure><ul><li>Save Arrow files to local (<strong>train</strong> split is saved)</li></ul><pre># When saving to local, the train split is automatically chosen<br># There is only `train` split (no `test` or `val`)<br>sorted_dataset.save_to_disk(&#39;input/cold_cases_filtered/arrow/&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VerhZfyyuL7VsAUyZ-WqDg.png" /><figcaption>took 50 sec to save arrow files to local disk</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_1zerPVofARkqkdh3sc_2g.png" /></figure><ul><li>Save to CSV (<strong>train</strong> split is saved)</li></ul><pre># When saving to local, the train split is automatically chosen<br># There is only `train` split (no `test` or `val`)<br>sorted_dataset[&#39;train&#39;].to_csv(&#39;input/cold_cases_filtered/train.csv&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kgrSLrtMBgi19DbRDg_OVA.png" /><figcaption>took 1 m to convert to CSV and save to local</figcaption></figure><h4>2.2.1. filter by fuzzy match (optional — unused)</h4><ul><li>fuzzywuzzy to filter for <strong>“Title VII of the Civil Rights Act of 1964”</strong> with threshold <strong>80%</strong></li></ul><pre>from fuzzywuzzy import fuzz<br><br>def fuzzy_filter_opinions(example):<br>    query = &quot;VII of the Civil Rights Act of 1964&quot;<br>    threshold = 80<br><br>    # Check if &#39;opinions&#39; is not None and is a list<br>    if example[&#39;opinions&#39;] is not None:<br>        for opinion in example[&#39;opinions&#39;]:<br>            opinion_text = opinion[&#39;opinion_text&#39;]<br>            if fuzz.partial_ratio(query, opinion_text) &gt;= threshold:<br>                return True<br>    return False<br><br># filtered dataset<br>fuzz_dataset = title_vii_dataset.filter(fuzzy_filter_opinions)<br>fuzz_dataset</pre><h3>3. Sort</h3><pre># Sort the dataset by the &#39;date_filed&#39; column<br>sorted_dataset = dataset.sort(&#39;date_filed&#39;)<br><br># Verify the sorting by looking at the first few entries<br>print(sorted_dataset[:5])</pre><h3>4. Filter — Create sub-datasets</h3><ul><li>filter by columns</li></ul><pre># Filter the dataset by column<br>filtered_dataset = sorted_dataset.filter(lambda x: (x[&#39;court_type&#39;] == &#39;F&#39;) | (x[&#39;court_type&#39;] == &#39;FD&#39;))</pre><ul><li>filter by nested columns</li></ul><pre># Filter the dataset by nested column keys<br># Filter the dataset to include only entries with any of the most important opinion types<br>filtered_dataset = sorted_dataset.filter(<br>    lambda x: any(<br>        (opinion.get(&#39;type&#39;) in [&quot;015unamimous&quot;, &quot;020lead&quot;, &quot;080onthemerits&quot;, &quot;025plurality&quot;, &quot;030concurrence&quot;, &quot;040dissent&quot;]) <br>        or (opinion.get(&#39;per_curiam&#39;) == True)<br>        for opinion in x[&#39;opinions&#39;]<br>    )<br>)<br><br>filtered_dataset</pre><ul><li>filter by date</li></ul><pre>def filter_by_dates(example, start=1964, end=2024):<br>    if example[&#39;date_filed&#39;]:<br>        try:<br>            example[&#39;date_filed&#39;] = pd.to_datetime(example[&#39;date_filed&#39;])<br>            if (start &lt;= (example[&#39;date_filed&#39;].year) &lt; end) and (start &lt;= (example[&#39;date_filed&#39;].year) &gt;= start):<br>                return True<br>        except Exception as e:<br>            print(f&quot;Date conversion error: {e}&quot;)<br>    return False<br><br>dataset_1990_before_2000 = filtered_dataset.filter(lambda x: filter_by_dates(x, start=1990, end=2000))<br>dataset_1990_before_2000.to_csv(&#39;output/by_date_filed/dataset_1990_before_2000.csv&#39;)<br><br>dataset_2000_before_2010 = filtered_dataset.filter(lambda x: filter_by_dates(x, start=2000, end=2010))<br>dataset_2000_before_2010.to_csv(&#39;output/by_date_filed/dataset_2000_before_2010.csv&#39;)<br><br>dataset_2000_before_2020 = filtered_dataset.filter(lambda x: filter_by_dates(x, start=2010, end=2020))<br>dataset_2000_before_2020.to_csv(&#39;output/by_date_filed/dataset_2000_before_2020.csv&#39;)<br><br>dataset_2010_before_2015 = filtered_dataset.filter(lambda x: filter_by_dates(x, start=2010, end=2015))<br>dataset_2010_before_2015.to_csv(&#39;output/by_date_filed/dataset_2010_before_2015.csv&#39;)<br><br>dataset_2015_before_2023 = filtered_dataset.filter(lambda x: filter_by_dates(x, start=2015, end=2023))<br>dataset_2015_before_2023.to_csv(&#39;output/by_date_filed/dataset_2015_before_2023.csv&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qzRPzu9biPSwHAFwhEWuEw.png" /><figcaption>2,361 cases</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkfSQtVWw8VT0uT0rLTOpA.png" /><figcaption>1,360 cases</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTgDAf3DP42I5VwVtqLG3A.png" /><figcaption>1,652 cases</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ABzkdZ730G1MWcGLwYZPeA.png" /><figcaption>1,225 cases</figcaption></figure><h3>5. Load from disk</h3><h4>5.1. load arrow files</h4><ul><li>Total 28,403 cases</li></ul><pre>import re<br>import datetime<br>import pandas as pd<br>from datasets import load_from_disk<br><br># load arrow files by providing a folder name that includes them<br>dataset = load_from_disk(&#39;/Users/jaelinlee/Documents/projects/case_law/app/input/cold_cases_filtered/arrow/train&#39;)<br>dataset</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7UfPPrCoD4WVH4yxW9YPQ.png" /><figcaption>took 0 seconds to load CSV with 28,403 cases</figcaption></figure><h4>5.2. filter by date_filed</h4><pre>def filter_by_dates(example, start=1964, end=2024):<br>    if example[&#39;date_filed&#39;]:<br>        try:<br>            example[&#39;date_filed&#39;] = pd.to_datetime(example[&#39;date_filed&#39;])<br>            if (start &lt;= (example[&#39;date_filed&#39;].year) &lt; end) and (start &lt;= (example[&#39;date_filed&#39;].year) &gt;= start):<br>                return True<br>        except Exception as e:<br>            print(f&quot;Date conversion error: {e}&quot;)<br>    return False<br><br><br>dataset_1964_before_1990 = filtered_dataset.filter(lambda x: filter_by_dates(x, start=1964, end=1990))<br>dataset_1964_before_1990.to_csv(&#39;output/by_date_filed/dataset_1964_before_1990.csv&#39;)<br>dataset_1964_before_1990<br><br>dataset_1990_before_2000 = filtered_dataset.filter(lambda x: filter_by_dates(x, start=1990, end=2000))<br>dataset_1990_before_2000.to_csv(&#39;output/by_date_filed/dataset_1990_before_2000.csv&#39;)<br>dataset_1990_before_2000<br><br>dataset_2000_before_2010 = filtered_dataset.filter(lambda x: filter_by_dates(x, start=2000, end=2010))<br>dataset_2000_before_2010.to_csv(&#39;output/by_date_filed/dataset_2000_before_2010.csv&#39;)<br>dataset_2000_before_2010<br><br>dataset_2010_before_2015 = filtered_dataset.filter(lambda x: filter_by_dates(x, start=2010, end=2015))<br>dataset_2010_before_2015.to_csv(&#39;output/by_date_filed/dataset_2010_before_2015.csv&#39;)<br>dataset_2010_before_2015<br><br>dataset_2015_before_2024 = filtered_dataset.filter(lambda x: filter_by_dates(x, start=2015, end=2024))<br>dataset_2015_before_2024.to_csv(&#39;output/by_date_filed/dataset_2015_before_2024.csv&#39;)<br>dataset_2015_before_2024</pre><ul><li>dataset_1964_before_1990 (Total 2,462 cases)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDHyKsAZMBlXehVJvRHdfA.png" /></figure><ul><li>dataset_1990_before_2000 (Total 1,383 cases)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*upDZnUJ_wHJ46q8Rc9_l0g.png" /></figure><ul><li>dataset_2000_before_2010 (Total 2,145 cases)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qLurnQNYGJUyIrgn8snPKw.png" /></figure><ul><li>dataset_2000_before_2010 (Total 1,677 cases)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mP0bKrRMX8HXvR9x_K14Q.png" /></figure><p>dataset_2015_before_2024 (Total 1,234 cases)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YlSKADWUKL8b0lYV1SsDMQ.png" /></figure><h3>6. Create DataFrame</h3><ul><li>Toal 28,403 cases</li></ul><pre>df = pd.DataFrame(dataset)<br>df.shape</pre><h4>6.1. Extract keys within opinion column</h4><pre># Initialize an empty set to store unique keys<br>all_keys = set()<br><br># Iterate over each row in the DataFrame<br>df[&#39;opinions&#39;].apply(lambda opinions: [all_keys.update(opinion.keys()) for opinion in opinions])<br><br># Convert the set to a list (optional)<br>all_keys = list(all_keys)<br><br># Display all unique keys<br>print(all_keys)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_86HCIyKmScBrLTxIE3KYQ.png" /><figcaption>opinion keys</figcaption></figure><pre># [&#39;ocr&#39;, &#39;page_count&#39;, &#39;download_url&#39;, &#39;per_curiam&#39;, &#39;type&#39;, &#39;opinion_id&#39;, &#39;author_id&#39;, &#39;author_str&#39;, &#39;opinion_text&#39;]<br><br>df[&#39;opinion_id&#39;] = df[&#39;opinions&#39;].apply(lambda x: [opinion.get(&#39;opinion_id&#39;, None) for opinion in x if &#39;opinion_id&#39; in opinion])<br>df[&#39;type&#39;] = df[&#39;opinions&#39;].apply(lambda x: [opinion.get(&#39;type&#39;, None) for opinion in x if &#39;type&#39; in opinion])<br>df[&#39;per_curiam&#39;] = df[&#39;opinions&#39;].apply(lambda x: [opinion.get(&#39;per_curiam&#39;, None) for opinion in x if &#39;per_curiam&#39; in opinion])<br>df[&#39;author_id&#39;] = df[&#39;opinions&#39;].apply(lambda x: [opinion.get(&#39;author_id&#39;, None) for opinion in x if &#39;author_id&#39; in opinion])<br>df[&#39;author_str&#39;] = df[&#39;opinions&#39;].apply(lambda x: [opinion.get(&#39;author_str&#39;, None) for opinion in x if &#39;author_str&#39; in opinion])<br>df[&#39;opinion_text&#39;] = df[&#39;opinions&#39;].apply(lambda x: [opinion.get(&#39;opinion_text&#39;, None) for opinion in x if &#39;opinion_text&#39; in opinion])<br>df.shape</pre><h4>6.2. filtered by opinion type</h4><ul><li>selected opinion type: [“015unamimous”, “020lead”, “080onthemerits”, “025plurality”, “030concurrence”, “040dissent”]</li><li>Total 8,901 cases</li></ul><pre># filtered_dataset = sorted_dataset.filter(lambda x: (x[&#39;court_type&#39;] == &#39;F&#39;) | (x[&#39;court_type&#39;] == &#39;FD&#39;))<br><br># Filter the dataset to include only entries with any of the most important opinion types<br>filtered_dataset = dataset.filter(<br>    lambda x: any(<br>        (opinion.get(&#39;type&#39;) in [&quot;015unamimous&quot;, &quot;020lead&quot;, &quot;080onthemerits&quot;, &quot;025plurality&quot;, &quot;030concurrence&quot;, &quot;040dissent&quot;]) <br>        or (opinion.get(&#39;per_curiam&#39;) == True)<br>        for opinion in x[&#39;opinions&#39;]<br>    )<br>)<br><br>filtered_dataset</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cohBCZfbYV0fPaxlfMmx8Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09f1e9f7f2ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lightning.ai example (BERTScore)]]></title>
            <link>https://medium.com/@jaelin_75015/lightning-ai-example-bertscore-00ccebc5fe0b?source=rss-fd55dece4858------2</link>
            <guid isPermaLink="false">https://medium.com/p/00ccebc5fe0b</guid>
            <category><![CDATA[bert-score]]></category>
            <category><![CDATA[free-gpu]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Jaelin Lee]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 13:56:42 GMT</pubDate>
            <atom:updated>2024-09-03T14:03:57.764Z</atom:updated>
            <content:encoded><![CDATA[<p>Test run BERTScore in Lightning.ai</p><h3>References</h3><ul><li>lightning.ai</li><li>BERTScore Installation Guide (<a href="https://huggingface.co/docs/huggingface_hub/en/installation#check-installation">https://huggingface.co/docs/huggingface_hub/en/installation#check-installation</a>)</li><li>BERTScore Hugging Face (<a href="https://huggingface.co/spaces/evaluate-metric/bertscore">https://huggingface.co/spaces/evaluate-metric/bertscore</a>)</li><li>BERTScore GitHub (<a href="https://github.com/Tiiiger/bert_score#readme">https://github.com/Tiiiger/bert_score#readme</a>)</li><li>BERTScore Tutorial in Google Colab (<a href="https://colab.research.google.com/drive/1kpL8Y_AnUUiCxFjhxSrxCsc6-sDMNb_Q">https://colab.research.google.com/drive/1kpL8Y_AnUUiCxFjhxSrxCsc6-sDMNb_Q</a>)</li></ul><h3>Lightning.ai Overview</h3><ul><li>Use org/edu account to get verified instantly (else, 2–3 biz days)</li><li>Free 22 GPU hours/month</li><li>Free studios (24/7*) become paid after 4 hours. Upgrade to keep free.</li><li>Connect to AWS and use your cloud credits</li><li>1 virtual conda environment per Studio</li><li>$50/month or $480/yr + pay as you go (1 studio)</li><li>Billed by second</li><li>Create and deploy an inference API for your large language model (LLM) using Lightning AI.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tS-igQtU-tM6y94csR4SgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*27vnEXM9BuM6UGG2e_zXOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eX2Cs55a36Pf7KgSnrghkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGBic_RlxKe4G2HlzeVUvA.png" /></figure><h3><strong>1. Set up Hugging-Face CLI</strong></h3><ul><li>(<a href="https://huggingface.co/docs/huggingface_hub/en/installation#check-installation">https://huggingface.co/docs/huggingface_hub/en/installation#check-installation</a>)</li></ul><pre># Install dependencies for tensorflow-specific features<br># Warning: this is not equivalent to `pip install tensorflow`<br>pip install &#39;huggingface_hub[tensorflow]&#39;<br><br># Install dependencies for both torch-specific and CLI-specific features.<br>pip install &#39;huggingface_hub[cli,torch]&#39; </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klXhOhtQi0xaeSKqQtXQ6g.png" /><figcaption>BERTScore (from: <a href="https://github.com/Tiiiger/bert_score/blob/master/bert_score.png">https://github.com/Tiiiger/bert_score/blob/master/bert_score.png</a>)</figcaption></figure><h3>2. Install BERTScore</h3><ul><li>Hugging Face (<a href="https://huggingface.co/spaces/evaluate-metric/bertscore">https://huggingface.co/spaces/evaluate-metric/bertscore</a>)</li><li>GitHub (<a href="https://github.com/Tiiiger/bert_score#readme">https://github.com/Tiiiger/bert_score#readme</a>)</li><li>Tutorial in Colab (<a href="https://colab.research.google.com/drive/1kpL8Y_AnUUiCxFjhxSrxCsc6-sDMNb_Q">https://colab.research.google.com/drive/1kpL8Y_AnUUiCxFjhxSrxCsc6-sDMNb_Q</a>)</li></ul><pre>pip install bert-score</pre><h3>3. Set up to test run BERTScore</h3><pre>from bert_score import score<br><br># download sample data<br># cloning the repo because we need to get some example data<br>!git clone https://github.com/Tiiiger/bert_score.git<br><br># open sample data<br>with open(&quot;bert_score/example/hyps.txt&quot;) as f:<br>    cands = [line.strip() for line in f]<br><br>with open(&quot;bert_score/example/refs.txt&quot;) as f:<br>    refs = [line.strip() for line in f]</pre><h3>4. View examples (Candidates vs. References): a list of split single sentences from .txt</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rDaLUruXza5JSvGX0Nyh7A.png" /><figcaption>example (hyps.txt)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iUNz1x_84MDCgQLV5-bdGA.png" /><figcaption>example (refs.txt)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zxUF71EsHuQATZbIkuzYA.png" /><figcaption>example split into a list of sentences</figcaption></figure><h3>5. Run BERTScore test (F1, Precision, Recall)</h3><pre># When you are running this cell for the first time, <br># it will download the model which will take relatively longer<br><br># OPTION1: default model_type=&#39;roberta-large&#39;<br>P, R, F1 = score(cands, refs, lang=&quot;en&quot;, verbose=True)<br><br># OPTION2: in order to have the best correlation with human evaluation,<br># use model_type=&#39;microsoft/deberta-xlarge-mnli&#39; as below<br>P, R, F1 = score(cands, refs, lang=&quot;en&quot;, verbose=True, model_type=&#39;microsoft/deberta-xlarge-mnli&#39;)<br><br># Check F1 score<br>print(F1)<br>print(f&quot;System level F1 score: {F1.mean():.3f}&quot;)</pre><h3>6. Visualize F1 score distribution</h3><pre># visualize distribution of bert score<br>import matplotlib.pyplot as plt<br><br>plt.hist(F1, bins=20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OEv5rE3wWma22JgYGrAa6w.png" /><figcaption>model_type=’microsoft/deberta-xlarge-mnli’</figcaption></figure><pre>from bert_score import plot_example<br><br>cand = cands[0]<br>ref = refs[0]<br>plot_example(cand, ref, lang=&quot;en&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t0u3jKLuQekU0O-Mttip4g.png" /><figcaption>model_type=’microsoft/deberta-xlarge-mnli’</figcaption></figure><h3>7. Optional: Run directly form a list of texts</h3><ul><li>applied<strong> idf_weighting</strong> (use tokenizer from hugging face transformers)</li><li>generate <strong>idf_dict</strong> using a tokenizer (bert-base-uncased)</li><li>use <strong>refs</strong> (reference sentences) to compute IDF scores</li></ul><pre># calculate BERTScore<br>cands = [&quot;hi there&quot;, &quot;today is cold&quot;, &quot;I don&#39;t like it.&quot;]<br>refs = [&quot;hello&quot;, &quot;it&#39;s cold today&quot;, &quot;I dislike it.&quot;]<br>P, R, F1 = score(cands, refs, lang=&quot;en&quot;)<br>print(f&quot;F1 Score: {F1.mean():.3f}&quot;)<br><br># visualize F1 score distribution<br>import matplotlib.pyplot as plt<br>plt.hist(F1, bins=20)<br><br># visualize pairwise cosine similarity<br>from bert_score import plot_example<br><br># apply the idf weighting.<br>from bert_score import plot_example, get_idf_dict<br>from transformers import AutoTokenizer<br><br># Step 1: Initialize the tokenizer (e.g., using &#39;bert-base-uncased&#39;)<br>tokenizer = AutoTokenizer.from_pretrained(&quot;bert-base-uncased&quot;)<br><br># Step 2: Compute IDF scores using the reference sentences<br>idf_dict = get_idf_dict(refs, tokenizer=tokenizer)<br><br># Step 3: Use IDF scores in the plot_example function<br>P, R, F1 = score(cands, refs, lang=&quot;en&quot;, idf=idf_dict)<br><br># 1 sentence vs 1 sentence<br>cand = cands[0]<br>ref = refs[0]<br>plot_example(cand, ref, lang=&quot;en&quot;)</pre><ul><li>F1 Score: 0.914 (for comparing all sentences in <strong>cands vs. refs</strong>)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTzpZe70jO86luIQQLflkQ.png" /><figcaption>Visualize item 1 comparison: cands[0], refs[0]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gMz9uitEDggRKEF8U9Njg.png" /><figcaption>Visualize item 2comparison: cands[1], refs[1]</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00ccebc5fe0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Install PyTorch + Metal Processor for MacOS (M1, M2)]]></title>
            <link>https://medium.com/@jaelin_75015/how-to-install-pytorch-metal-processor-for-macos-m1-m2-a7d043b886cf?source=rss-fd55dece4858------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7d043b886cf</guid>
            <dc:creator><![CDATA[Jaelin Lee]]></dc:creator>
            <pubDate>Sat, 06 Jul 2024 03:08:15 GMT</pubDate>
            <atom:updated>2024-07-06T03:08:15.013Z</atom:updated>
            <content:encoded><![CDATA[<p>With Anaconda.</p><h3>Reference:</h3><ul><li>For Apple Silicon (<a href="https://developer.apple.com/metal/pytorch/">https://developer.apple.com/metal/pytorch/</a>)</li></ul><h3>1. Install Metal Processor</h3><pre>curl -O https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-arm64.sh<br>sh Miniconda3-latest-MacOSX-arm64.sh</pre><h3>2. Install PyTorch (Anaconda)</h3><pre>conda install pytorch torchvision torchaudio -c pytorch-nightly</pre><h3>3. Verify</h3><pre>import torch<br>if torch.backends.mps.is_available():<br>    mps_device = torch.device(&quot;mps&quot;)<br>    x = torch.ones(1, device=mps_device)<br>    print (x)<br>else:<br>    print (&quot;MPS device not found.&quot;)<br><br># If mps enabled, output should be<br># tensor([1.], device=&#39;mps:0&#39;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7d043b886cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Kaggle API to get Datasets List]]></title>
            <link>https://medium.com/@jaelin_75015/how-to-use-kaggle-api-to-get-datasets-list-9dbba45975af?source=rss-fd55dece4858------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dbba45975af</guid>
            <dc:creator><![CDATA[Jaelin Lee]]></dc:creator>
            <pubDate>Sat, 06 Jul 2024 01:29:47 GMT</pubDate>
            <atom:updated>2024-07-06T01:29:47.193Z</atom:updated>
            <content:encoded><![CDATA[<p>For MacOS (including M1/M2).</p><h3>Goal:</h3><ul><li>To create a pandas dataframe with a list of Kaggle Datasets</li></ul><h3>Solultion:</h3><ol><li>Activate virtual environment</li></ol><pre># If you don&#39;t already have a conda environment, create one<br>conda create -n kaggleVenv<br><br># If you already have the conda environment, just eactivate it<br>conda activate kaggleVenv</pre><p>2. Install Kaggle CLI from your terminal</p><pre>pip install kaggle</pre><p>3. Create and Download your personal Kaggle API token (`kaggle.json`)</p><ul><li>Click <strong>Settings</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w7G3xBI_-IBO31DRrh35wA.png" /></figure><ul><li>Click <strong>Create New Token</strong></li><li>It will download the token kaggle.json to your local computer</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*6EMsRx-Oteg-63765Yd9cw.png" /></figure><ul><li>Move the downloaded kaggle.json file to under ~/.kaggle folder.</li></ul><pre># First, navigate to the folder where your kagggle.json file is<br># Then, you move the file to a new folder as below<br>mv kaggle.json ~/.kaggle/kaggle.json</pre><p>4. Within the notebook, save the datasets list as <strong>csv</strong></p><ul><li>Use -s to filter the search result to a specific keyword.</li><li>In the example below, I am filtering for healthcare datasets</li></ul><pre>output = !kaggle datasets list -s healthcare --csv<br>output</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dbba45975af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to set up Conda environment for MacOS (including M1, M2)]]></title>
            <link>https://medium.com/@jaelin_75015/how-to-set-up-conda-environment-for-macos-including-m1-m2-f94016a73e0f?source=rss-fd55dece4858------2</link>
            <guid isPermaLink="false">https://medium.com/p/f94016a73e0f</guid>
            <dc:creator><![CDATA[Jaelin Lee]]></dc:creator>
            <pubDate>Fri, 05 Jul 2024 15:31:54 GMT</pubDate>
            <atom:updated>2024-07-05T15:32:07.556Z</atom:updated>
            <content:encoded><![CDATA[<h3>Question:</h3><ul><li>Which Conda environment should I choose?</li><li>I am working on Data Science / Machine Learning projects.</li></ul><h3>Answer:</h3><ol><li>If you don’t want to install pandas, numpy, jupyter, etc. every time you create a new conda environment, <strong>use Conda.</strong></li><li>If you want to have a clean slate, and install which pandas, numumpy, Jupyter, … version you want to install for each environment without deleting what’s already installed by default within the environment, <strong>use Miniconda</strong>.</li></ol><pre># If you are using Minicoda, <br># you have to run below in your terminal<br># every time you create a new conda environemnt <br>conda install numpy pandas scikit-learn matplotlib seaborn jupyter</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f94016a73e0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>