<?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 Alison Yuhan Yao on Medium]]></title>
        <description><![CDATA[Stories by Alison Yuhan Yao on Medium]]></description>
        <link>https://medium.com/@AlisonYuhanYao?source=rss-17016fd04e22------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*e4LwU0fXlqQ2SDs_gtETdA.jpeg</url>
            <title>Stories by Alison Yuhan Yao on Medium</title>
            <link>https://medium.com/@AlisonYuhanYao?source=rss-17016fd04e22------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:16:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@AlisonYuhanYao/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[What are Agent Skills beyond Claude]]></title>
            <link>https://medium.com/data-science-collective/what-is-agent-skills-beyond-claude-4cb064b513ab?source=rss-17016fd04e22------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cb064b513ab</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[agent-skills]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Alison Yuhan Yao]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 19:21:05 GMT</pubDate>
            <atom:updated>2026-03-14T05:12:21.624Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to design and implement agent skills for custom agents outside the Claude ecosystem</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0K95n-wLzfhveRXSTM6mcQ.png" /><figcaption>Image Generated with Gemini</figcaption></figure><p><a href="https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview">Agent Skills</a> were introduced by Anthropic on Oct 16, 2025, as a way to extend Claude with reusable capabilities. Within months, the concept gained traction across the AI community and began evolving into a broader design pattern for building modular, portable agent capabilities beyond Claude itself.</p><p>As an AI practitioner, I’ve been using Claude Code for quite some time and have seen many tutorials explaining how to create Agent Skills within the Claude ecosystem. However, when I tried to implement the same concept for <a href="https://azure.microsoft.com/en-us/blog/optimizing-incident-management-with-aiops-using-the-triangle-system/">our enterprise solution</a> without relying on Claude, I quickly ran into a different set of design questions. What exactly defines an “agent skill”? How should it be structured? And how should skills be triggered and orchestrated in a custom agent framework?</p><p>In Claude, a typical Agent Skill is defined as a Markdown file containing a name, description, instructions, and scripts. This natural-language interface works well in many situations, especially when ambiguity is acceptable. But in production systems, precision often matters more than flexibility. One recurring challenge I encountered was skill triggering: sometimes a skill would be powerful and well-designed, yet Claude would fail to invoke it because the description was too vague.</p><p>For our agents, I need stricter guarantees — skills that trigger deterministically and behave consistently every time. That requirement led me to implement skills directly in Python with explicit logic. But doing so raised an interesting architectural question: if a skill is implemented purely in code, how is it different from a tool, a feature, or just another function? Even if these skills are reusable and invoked on demand, what actually makes them <em>agent skills</em>?</p><p>This article explores these questions and shares a practical perspective on designing and implementing agent skills for custom AI agents without relying on Claude.</p><h3>Agent skills vs Tools vs Features</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZcGdoN6MsaDV2WkA5Uzcg.png" /><figcaption>Image by Author</figcaption></figure><p><strong>A tool</strong> is a primitive capability, or a single action the agent can take. Each tool does one specific thing. Tools are individual instruments, like hammers, saws, and drills.</p><ul><li>Example: Claude’s tools include things like bash_tool (run a command), web_search (search the internet), view (read a file), str_replace (edit a file), web_fetch (get a webpage), places_search, weather_fetch and so on.</li></ul><p><strong>A skill</strong> is a set of instructions for how to orchestrate multiple tools to accomplish a complex task well. <strong>A skill doesn’t give me new capabilities.</strong> It gives agents expertise in <strong>combining existing tools effectively.</strong> Skills are like a detailed recipe that tells the agents which instruments to use, in what order, and what mistakes to avoid.</p><ul><li>Example: The docx skill, for example, tells Claude to use bash_tool to run npm install docx, then write JavaScript using specific patterns, then run bash_tool again to validate the output, then use present_files to share it.</li></ul><p><strong>A feature</strong> is a product-level concept, or something the user sees and can toggle on or off. A feature is enabled by giving the agent access to certain tools and skills.</p><ul><li>Examples: “Code Execution and File Creation,” “Web Search,” and “Artifacts” are features. So “file creation” as a feature is powered by the bash tool, the file creation tool, various document skills, and the present_files tool, all working together.</li></ul><p>Skills are what bridge the gap between raw tool access and high-quality output. Without the docx skill, Claude could still technically create a Word document, but it might miss things like “always set page size explicitly because docx-js defaults to A4” or “never use unicode bullets.”</p><h3>Do agent skills have to be in the format of markdown files?</h3><p>No. The concept is broader than the format.</p><p>A skill is fundamentally <strong>codified expertise for how to accomplish a task well</strong>. That expertise could live in many forms:</p><ul><li>A markdown file with instructions (typical Claude Agent Skill)</li><li>A Python script that does the work directly</li><li>A config file or JSON schema</li><li>A set of example inputs and outputs</li><li>A combination of all of the above</li></ul><p>In my case, the <strong>Python script</strong> seems appropriate because I need deterministic and reliable execution every single time with no variation. It’s faster, cheaper, and more predictable for a procedural process. The <strong>markdown instruction</strong> approach becomes valuable when the task involves ambiguity or judgment. Sometimes, we need LLM reading instructions and reasoning about what to do next to add value over a rigid script.</p><p>A <strong>hybrid</strong> approach is also common. I can keep my Python code and downgrade it to a tool implementation, but add a markdown skill file that helps the agents understand when to invoke my agent skill and how to interpret the results. A typical product iteration might begin with a Python implementation and gradually incorporate Markdown instructions, eventually forming a hybrid skill design.</p><h3>Agent skill vs MCP? Agent Skill + MCP!</h3><p>Our agents already connect to data sources through MCP servers, but many of our agent skills also include the ability to read directly from databases. This raises a practical architectural question: <strong>when should an agent use MCP, and when should the capability live inside a skill?</strong></p><p><a href="https://resources.anthropic.com/hubfs/The-Complete-Guide-to-Building-Skill-for-Claude.pdf">Anthropic</a> explains the distinction clearly with a helpful kitchen analogy:</p><blockquote>MCP connects Claude to data; Skills teaches Claude what to do with that data.</blockquote><ul><li>MCP provides the professional kitchen — access to tools, ingredients, and equipment.</li><li>Skills provide the recipes — instructions that tell the agent how to use those resources to produce something valuable.</li></ul><p>In my design, I treat <strong>MCP connections as infrastructure</strong> and <strong>skills as orchestration on how the data is used</strong>.</p><p>MCP servers are responsible for exposing external data sources and services. For example, they may provide structured access to databases, logs, APIs, or internal systems. Their role is to make these resources available to the agent in a standardized way.</p><p>Agent skills, on the other hand, define how the agent should use the data from MCP servers and other databases to accomplish a task.</p><p>For this reason, I typically implement:</p><ul><li><strong>Database access, APIs, and data retrieval as tools (or MCP capabilities)</strong></li><li><strong>Decision logic and workflows as agent skills</strong></li></ul><h3>Skills as “Agentic RAG”</h3><p>Ideally, the agent skills load information dynamically from tools when they are executed. This makes the pattern very similar to <strong>agentic retrieval-augmented generation (RAG)</strong>.</p><p>Instead of preloading all context into the prompt, the skill can:</p><ol><li>Identify what information it needs</li><li>Retrieve the relevant data through a tool or MCP server</li><li>Process that data according to its instructions</li><li>Produce the final output</li></ol><p>This approach keeps the agents lightweight while still allowing skills to access large or changing datasets on demand.</p><h3>Conclusion</h3><p>Anthropic introduced an important paradigm shift, and Claude’s implementation of Agent Skills offers valuable inspiration for building our own agent systems. As long as our skills capture the core purpose of what a skill is meant to do, which is encapsulating reusable on-demand capabilities for an agent, the specific format and implementation details can vary. Ultimately, the design decisions around when and how to use skills should be guided by the needs and constraints of the product we are building.</p><p>Thank you for reading! I hope this has been helpful to you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cb064b513ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/what-is-agent-skills-beyond-claude-4cb064b513ab">What are Agent Skills beyond Claude</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science Master’s Journey]]></title>
            <link>https://medium.com/@AlisonYuhanYao/data-science-masters-journey-ec1664c63f20?source=rss-17016fd04e22------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec1664c63f20</guid>
            <category><![CDATA[graduate-school]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[masters-degree]]></category>
            <category><![CDATA[graduation]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Alison Yuhan Yao]]></dc:creator>
            <pubDate>Fri, 05 Jul 2024 15:29:30 GMT</pubDate>
            <atom:updated>2024-07-05T15:30:40.187Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*fS3UYc7SmXKvaKCBGwgF1w.png" /><figcaption>Image by Author</figcaption></figure><p>Time flies. All of a sudden, I graduated again! Before I start my full-time job, I want to look back at the past 2 years of working toward my Master’s degree in Data Science and briefly summarize.</p><p>Before my Master’s, I did 4 years of undergrad in Data Science (read <a href="https://medium.com/nerd-for-tech/data-science-undergrad-journey-part1-why-did-i-choose-data-science-as-my-major-606202be1aba">here</a>), but there were more topics I wanted to explore and I knew that the <a href="https://seas.harvard.edu/masters-data-science">Harvard Data Science Master’s program</a> had a rigorous curriculum that would give me the opportunities to learn more. Plus, I can always cross-register at MIT if there are any courses that I am interested in.</p><h3>Chronologically</h3><p>The first year was incredibly intense. I was taking required classes and electives of my interest (4–5 classes per semester) and the workload can be huge because the classes go into detail and digesting and applying them takes time. The first year is a quick review of the theories and main topics in Data Science, a lot of which I have learned in undergrad, but it helps me review and gain a new perspective in understanding. It was also great for job interview preparations because I didn’t need to prepare too many extra things, as the classes already covered most of the key points in entry-level data scientist jobs.</p><p>The second year was all about application. I did research and big projects that went all the way to deployment so that users could actually use the apps I built. I also did countless projects in the first year and my undergrad but they mostly ended with finishing running a Jupyter Notebook.</p><h3>Key Growth Points</h3><h4>Generative AI</h4><p>I wanted to explore generative AI more so 1/3 to a half of my classes are focused on Gen AI. I mostly learned about NLP (again) and image generation with stable diffusion and I played with Midjourney, ChatGPT, and DallE whenever possible. I am still playing with all the cool applications out there like ElevenLabs and Pika now because this field develops so fast. It would be cool if I could create a movie with AI someday!</p><h4>Development Skills</h4><p>Seeing a deployed app of your data science algorithm feels incredible. I learned development skills like docker, Cloud, and more and was able to create an app on my own. For example, check out:</p><ul><li><a href="https://towardsdatascience.com/label-studio-customized-backend-for-semiautomatic-image-segmentation-labeling-324c2310d756">Label Studio Customized Backend for Semiautomatic Image Segmentation Labeling</a></li><li><a href="https://medium.com/institute-for-applied-computational-science/ta2studio-using-stable-diffusion-and-text-inversion-to-create-personalized-tattoo-designs-5e2ae2545ab2">Ta2Studio — Using Stable Diffusion and Text Inversion to Create Personalized Tattoo Designs</a></li></ul><h3>To be continued</h3><p>I will soon start my first full-time job as a data scientist and we will see how it goes!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*63K5uYWArVeZ-dcCMrZkSg.jpeg" /><figcaption>Image by Author</figcaption></figure><p>Thank you for reading! I hope this has been helpful to you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec1664c63f20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Label Studio Customized Backend for Semiautomatic Image Segmentation Labeling]]></title>
            <link>https://medium.com/data-science/label-studio-customized-backend-for-semiautomatic-image-segmentation-labeling-324c2310d756?source=rss-17016fd04e22------2</link>
            <guid isPermaLink="false">https://medium.com/p/324c2310d756</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[annotations]]></category>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[fashion]]></category>
            <dc:creator><![CDATA[Alison Yuhan Yao]]></dc:creator>
            <pubDate>Sat, 20 Apr 2024 15:28:35 GMT</pubDate>
            <atom:updated>2024-07-12T01:31:57.002Z</atom:updated>
            <content:encoded><![CDATA[<h4>Customized backend; GCP Deployment; Data Versioning with GCS Integration</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t41c-xM3byCQadgN4qAw0w.png" /><figcaption>Image by Author</figcaption></figure><h4>Table of Contents</h4><p>· <a href="#202a">Introduction</a><br>· <a href="#d792">Overview</a><br> ∘ <a href="#2329">Goal</a><br> ∘ <a href="#b71f">Why semiautomatic?</a><br> ∘ <a href="#d3f4">Entering Label Studio</a><br> ∘ <a href="#5a72">1 frontend + 2 backends</a><br>· <a href="#4dc5">Implementation (Local)</a><br> ∘ <a href="#e769">1. Install git and docker &amp; download backend code</a><br> ∘ <a href="#fa97">2. Set up frontend to get access token</a><br> ∘ <a href="#4cc0">3. Set up backend containers</a><br> ∘ <a href="#f7ab">4. Connect containers</a><br> ∘ <a href="#763a">5. Happy labeling!</a><br>· <a href="#8783">GCP Deployment</a><br> ∘ <a href="#8b11">1. Select project/Create new project and set up billing account</a><br> ∘ <a href="#a1b4">2. Create VM instance</a><br> ∘ <a href="#cf45">3. Set up VM environment</a><br> ∘ <a href="#2ea2">4. Follow previous section &amp; set up everything on VM</a><br>· <a href="#f815">GCS Integration</a><br> ∘ <a href="#4329">1. Set up GCS buckets</a><br> ∘ <a href="#84f3">2. Create &amp; set up service account key</a><br> ∘ <a href="#2e13">3. Rebuild backend containers</a><br> ∘ <a href="#3d43">4. SDK upload images from source bucket</a><br> ∘ <a href="#165a">5. Set up Target Storage</a><br>· <a href="#cc13">Acknowledgement</a><br>· <a href="#cb81">References</a></p><h3>Introduction</h3><p>Creating training data for image segmentation tasks remains a challenge for individuals and small teams. And if you are a student researcher like me, finding a cost-efficient way is especially important. In this post, I will talk about one solution that I used in <a href="https://seas.harvard.edu/news/2024/05/masters-student-capstone-spotlight-ai-fashion">my capstone project</a> where a team of 9 people successfully labeled 400+ images within a week.</p><p>Thanks to Politecnico di Milano <a href="https://www.centroricercagianfrancoferre.it/home/FGFhome.php?lang=en">Gianfranco Ferré Research Center</a>, we obtained thousands of fashion runway show images from Gianfranco Ferré’s archival database. To explore, manage, enrich, and analyze the database, I employed <em>image segmentation </em>for<em> </em>smarter cataloging and fine-grained research. Image segmentation of runway show photos also lays the foundation for creating informative textual descriptions for better search engine and text-to-image generative AI approaches. Therefore, this blog will detail:</p><ul><li>how to create your own backend with <a href="https://labelstud.io/">label studio</a>, on top of the existing <a href="https://labelstud.io/blog/get-started-using-segment-anything/">segment anything backend</a>, for semiautomatic image segmentation labeling,</li><li>how to host on Google Cloud Platform for group collaboration, and</li><li>how to employ Google Cloud Storage buckets for data versioning.</li></ul><blockquote>Code in this post can be found in this <a href="https://github.com/AlisonYao/label-studio-customized-ml-backend">GitHub repo</a>.</blockquote><h3>Overview</h3><h4>Goal</h4><p>Segment and identify the names and typologies of fashion clothing items in runway show images, as shown in the first image.</p><h4>Why semiautomatic?</h4><p>Wouldn’t it be nice if a trained segmentation model out there could perfectly recognize every piece of clothing in the runway show images? Sadly, there isn’t one. There exist trained models tailored to fashion or clothing images but nothing can match our dataset perfectly. Each fashion designer has their own style and preferences for certain clothing items and their color and texture, so even if a segmentation model can be 60% accurate, we call it a win. Then, we still need humans in the loop to correct what the segmentation model got wrong.</p><h4>Entering Label Studio</h4><p>Label Studio provides an open-source, customizable, and free-of-charge community version for various types of data labeling. One can create their own backend, so I can connect the Label Studio frontend to the trained segmentation model (mentioned above) backend for labelers to further improve upon the auto-predictions. Furthermore, Label Studio already has an interface that looks somewhat similar to Photoshop and a series of segmentation tools that can come in handy for us:</p><ul><li>Brush &amp; eraser</li><li><a href="https://labelstud.io/tags/magicwand">Magic Wand</a> for similar-color pixel selection</li><li><a href="https://labelstud.io/blog/get-started-using-segment-anything/">Segment Anything</a> backend which harnesses the power of <a href="https://segment-anything.com/">Meta’s SAM</a> and allows you to recognize the object within a bounding box you draw.</li></ul><h4>1 frontend + 2 backends</h4><p>So far, we want 2 backends to be connected to the frontend. One backend can do the segmentation prediction and the second can speed up labelers’ modification if the predictions are wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGe7cU38QDjZ1pasd0sx2g.png" /><figcaption>Image by Author</figcaption></figure><h3>Implementation (Local)</h3><p>Now, let’s fire up the app locally. That is, you will be able to use the app on your laptop or local machine completely for free but you are not able to invite your labeling team to collaborate on their laptops yet. We will talk about teamwork with GCP in the next section.</p><h4>1. Install git and docker &amp; download backend code</h4><p>If you don’t have <a href="https://git-scm.com/downloads">git</a> or <a href="https://www.docker.com/products/docker-desktop/">docker</a> on your laptop or local machine yet, please install them. (Note: you can technically bypass the step of installing git if you download the zip file from <a href="https://github.com/AlisonYao/label-studio-customized-ml-backend">this GitHub repo</a>. If you do so, skip the following.)</p><p>Then, open up your terminal and clone <a href="https://github.com/AlisonYao/label-studio-customized-ml-backend">this repo</a> to a directory you want.</p><pre>git clone https://github.com/AlisonYao/label-studio-customized-ml-backend.git</pre><p>If you open up the label-studio-customized-ml-backend folder in your code editor, you can see the majority are adapted from the <a href="https://github.com/HumanSignal/label-studio-ml-backend">Label Studio ML backend</a> repo, but this directory also contains frontend template code and SDK code adapted from <a href="https://github.com/HumanSignal/label-studio-sdk">Label Studio SDK</a>.</p><h4>2. Set up frontend to get access token</h4><p>Following the official guidelines of <a href="https://labelstud.io/blog/get-started-using-segment-anything/">segment anything</a>, do the following in your terminal:</p><pre>cd label-studio-customized-ml-backend/label_studio_ml/examples/segment_anything_model<br><br>docker run -it -p 8080:8080 \<br>    -v $(pwd)/mydata:/label-studio/data \<br>    --env LABEL_STUDIO_LOCAL_FILES_SERVING_ENABLED=true \<br>    --env LABEL_STUDIO_LOCAL_FILES_DOCUMENT_ROOT=/label-studio/data/images \<br>    heartexlabs/label-studio:latest</pre><p>Then, open your browser and type <a href="http://0.0.0.0:8080/">http://0.0.0.0:8080/</a> and you will see the frontend of Label Studio. Proceed to sign up with your email address. Now, there is no project yet so we need to create our first project by clicking <strong>Create Project</strong>. Create a name and description (optional) for your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gx0xGYPP3s4_9hzSQQxBqQ.png" /><figcaption>Image by Author</figcaption></figure><p>Upload some images locally. (We will talk about how to use cloud storage later.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oWdkxA5jlVEMYW5oAsN2pg.png" /><figcaption>Image by Author</figcaption></figure><p>For Labeling Setup, click on <strong>Custom template</strong> on the left and copy-paste the HTML code from the label-studio-customized-ml-backend/label_studio_frontend/view.html file. You do not need the four lines of Headers if you don’t want to show image metadata in the labeling interface. Feel free to modify the code here to your need or click <strong>Visual</strong> to add or delete labels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4GN8H2IdMcBJitYc9CV6pA.png" /><figcaption>Image by Author</figcaption></figure><p>Now, click <strong>Save</strong> and your labeling interface should be ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzYD-GtLBMhDvals_ghAKg.png" /><figcaption>Image by Author</figcaption></figure><p>On the top right, click on the user setting icon and click <strong>Account &amp; Setting</strong> and then you should be able to copy your access token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qXDhjWeLFV1LKDZ7AdWEvA.png" /><figcaption>Image by Author</figcaption></figure><h4>3. Set up backend containers</h4><p>In the label-studio-customized-ml-backend directory, there are many many backends thanks to the Label Studio developers. We will be using the customized ./segmentation backend for segmentation prediction (container 1) and the ./label_studio_ml/examples/segment_anything_model for faster labeling (container 2). The former will use port 7070 and the latter will use port 9090, making it easy to distinguish from the frontend port 8080.</p><p>Now, paste your access token to the 2 docker-compose.yml files in ./segmentationand ./label_studio_ml/examples/segment_anything_model folders.</p><pre>environment:<br>  - LABEL_STUDIO_ACCESS_TOKEN=6dca0beafd235521cd9f23d855e223720889f4e1</pre><p>Open up a new terminal and you cd into the segment_anything_model directory as you did before. Then, fire up the segment anything container.</p><pre>cd label-studio-customized-ml-backend/label_studio_ml/examples/segment_anything_model<br><br>docker build . -t sam:latest<br>docker compose up</pre><p>Then, open up another new terminal cd into the segmentation directory and fire up the segmentation prediction container.</p><pre>cd label-studio-customized-ml-backend/segmentation<br><br>docker build . -t seg:latest<br>docker compose up</pre><p>As of now, we have successfully started all 3 containers and you can double-check.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JOSuhlQK8QfVXmfnA-JfLg.png" /><figcaption>Image by Author</figcaption></figure><h4>4. Connect containers</h4><p>Before, what we did with the access token was helping us connect containers already, so we are almost done. Now, go to the frontend you started a while back and click <strong>Settings</strong> in the top right corner. Click <strong>Machine Learning</strong> on the left and click <strong>Add Model</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cPrvWdwF8NjaMrKej54v6w.png" /><figcaption>Image by Author</figcaption></figure><p>Be sure to use the URL with port 9090 and toggle on interactive preannotation. Finish adding by clicking <strong>Validate and Save</strong>.</p><p>Similarly, do the same with the segmentation prediction backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8kc5Tr1OG2xXvi0wcyrRjQ.png" /><figcaption>Image by Author</figcaption></figure><p>Then, I like to toggle on <strong>Retrieve predictions when loading a task automatically</strong>. This way, every time we refresh the labeling page, the segmentation predictions will be automatically triggered and loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TLw9td0xYzmQL0Qh0-__zA.png" /><figcaption>Image by Author</figcaption></figure><h4>5. Happy labeling!</h4><p>Here is a demo of what you should see if you follow the steps above.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4iziG7agxro%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4iziG7agxro&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4iziG7agxro%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ca5ad2e7e82f5da8c3c8a1a70435d28/href">https://medium.com/media/7ca5ad2e7e82f5da8c3c8a1a70435d28/href</a></iframe><p>If we are not happy with the predictions of let’s say the skirt, we can delete the skirt and use the purple magic (segment anything) to quickly label it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDOUiowhX26k&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDOUiowhX26k&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FDOUiowhX26k%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1a15128961b5d6c71f3b29a29b2f72b/href">https://medium.com/media/d1a15128961b5d6c71f3b29a29b2f72b/href</a></iframe><p>I’m sure you can figure out how to use the brush, eraser and magic wand on your own!</p><p>If you are working solo, you are all set. But if you are wondering how to collaborate with your team without subscribing to Label Studio Enterprise, we need to host everything on cloud.</p><h3>GCP Deployment</h3><p>I chose GCP because of education credits, but you can use any cloud of your choice. The point is to host the app on cloud so that anyone in your labeling team can access and use your Label Studio app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8jklFmUnY8zux-Z_QFEjg.png" /><figcaption>Image by Author</figcaption></figure><h4>1. Select project/Create new project and set up billing account</h4><p>Go to <a href="https://console.cloud.google.com/">GCP console</a> and create a new project if you don’t have an existing one and set up the billing account information as required (unfortunately, cloud costs some money). Here, I will use the <em>Fashion</em> project I created to demonstrate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDZ5oAZ6T_ASyujlSj1kTQ.png" /><figcaption>Image by Author</figcaption></figure><h4>2. Create VM instance</h4><p>To have a public IP address for labeling teamwork, we need to create a Virtual Machine (VM) on GCP and host everything here. After going to the project you created or selected, search <strong>compute engine</strong> in the search bar and the first thing that pops up should be <strong>VM instances</strong>. Click <strong>CREATE INSTANCE</strong> and choose the setting based on your need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MK9ey5MW5xKENfUn-h1kkQ.png" /><figcaption>Image by Author</figcaption></figure><p>The default 10GB persistent disk will give you problems, so bump it up please. And more importantly, allow HTTP traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*PdVNrfA7Vj9YT0ZYQLL37g.png" /><figcaption>Image by Author</figcaption></figure><p>It is a bit painful to modify these settings later, so try to think it through before clicking CREATE.</p><h4>3. Set up VM environment</h4><p>You can think of a VM as a computer somewhere in the cloud, similar to your laptop, but you can only ask it to do things via the terminal or command line. So now we need to set up everything on the VM the same way we set up everything locally (see previous section).</p><p>Click SSH, authorize and open up the command line interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwBYouHVEd1JPgIO-WBC5Q.jpeg" /><figcaption>Image by Author</figcaption></figure><p>Do routine update and install docker, docker compose, git and Python.</p><pre>sudo apt-get update<br><br>curl -fsSL https://get.docker.com -o get-docker.sh<br>sudo sh get-docker.sh<br>sudo docker --version<br><br>sudo apt-get install docker-compose-plugin<br><br>sudo apt install git<br><br>sudo apt install python3-pip</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_NGYZhmco2hylnxpg2jnAw.jpeg" /><figcaption>Image by Author</figcaption></figure><h4>4. Follow previous section &amp; set up everything on VM</h4><p>Now, you can follow steps 1–4 in the previous section but there are some changes:</p><ol><li>Add <strong>sudo</strong> when you have docker permission denied error.</li><li>If you have data permission error, modify permission using something like sudo chmod -R 777 mydata. And then you should be able to run your frontend container.</li><li>The server is not at <a href="http://0.0.0.0:8080/">http://0.0.0.0:8080</a> anymore. Instead, swap 0.0.0.0 with the external IP address of your VM. An example is <a href="http://34.1.1.87:8080/">http://34.1.1.87:8080/</a>. You can find the external IP address next to the <strong>SSH</strong> button you clicked before. However, you probably still cannot access the frontend just yet. You need to search firewall on GCP console and click <strong>Firewall (VPC network)</strong> and then click <strong>default-allow-http.</strong> Now, change the setting to the following and you should be able to access the frontend.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H4L04cA5wVPlfLUk-Wo46w.png" /><figcaption>Image by Author</figcaption></figure><p>4. When editing docker-compose.yml files, apart from copy-pasting access token, also modify the LABEL_STUDIO_HOST. Again, swap host.docker.internal with the VM external IP address. An example is <a href="http://34.1.1.87:8080/">http://34.1.1.87:8080</a> .</p><p>5. Similarly, when adding <em>Machine Learning</em> in the frontend settings, also use <a href="http://34.1.1.87:9090/">http://34.1.1.87:9090</a> and <a href="http://34.1.1.87:7070.">http://34.1.1.87:7070.</a></p><p>You can then export your labeling results and tailor to your uses.</p><p>If you only have a couple of images to label or you are fine with uploading images from local, by all means. But for my project, there are thousands of images, so I prefer using Google Cloud Storage to automate data transferring and data versioning.</p><h3>GCS Integration</h3><h4>1. Set up GCS buckets</h4><p>Search bucket in the GCP console and navigate to Cloud Storage buckets. Create 2 buckets: one with your images (source) and another empty (target). The second one will be populated later when you start labeling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gdOw2Hn8vt0tMma1rE67jg.jpeg" /><figcaption>Image by Author</figcaption></figure><p>Then, following the <a href="https://labelstud.io/guide/storage.html#Google-Cloud-Storage">official documentation</a>, we need to set up cross-origin resource sharing (CORS) access to the buckets. Click <strong>Activate Cloud Shell</strong> on the top right, and run the following commands.</p><pre>echo &#39;[<br>   {<br>      &quot;origin&quot;: [&quot;*&quot;],<br>      &quot;method&quot;: [&quot;GET&quot;],<br>      &quot;responseHeader&quot;: [&quot;Content-Type&quot;,&quot;Access-Control-Allow-Origin&quot;],<br>      &quot;maxAgeSeconds&quot;: 3600<br>   }<br>]&#39; &gt; cors-config.json<br><br>gsutil cors set cors-config.json gs://ferre-runway # use your bucket name<br>gsutil cors set cors-config.json gs://ferre-runway-labeled # use your bucket name</pre><p>If you want to set up data versioning for the labeling results, you can click on the bucket and turn on versioning in <strong>PROTECTION</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1PxZBhScvtUQvvmeuqJc-A.png" /><figcaption>Image by Author</figcaption></figure><h4>2. Create &amp; set up service account key</h4><p>Chances are that you do not want your buckets to be public, then label studio needs authentication to have access to these images. Click <strong>CREATE SERVICE ACCOUNT</strong> and grant the role of <strong>Storage Admin</strong> so that we can read and write to the GCS buckets. You should be able to see this service account in the permissions list of the buckets as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zoq5tBJi_tlgbMZzhpHkuw.png" /><figcaption>Image by Author</figcaption></figure><p>Now, click on the newly created service account and click <strong>KEYS</strong>. Now add a new key and be sure to download the JSON file to somewhere safe.</p><p>Now, open up your local terminal and encode the JSON file.</p><pre>base64 -i service_account_key.json -o service_account_key_encoded.txt<br>cat service_account_key_encoded.txt</pre><p>You can see the random character and number string and copy it. We are now pasting it as metadata for the VM. Click on your VM, click <strong>EDIT</strong>, and add your custom metadata. For example, my key is GOOGLE_APPLICATION_CREDENTIALS_BASE64.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sic46WpoqDDKZTvAMvS9kQ.png" /><figcaption>Image by Author</figcaption></figure><p>We will then decode the service account key for authentication in our Python code.</p><h4>3. Rebuild backend containers</h4><p>Since we modified the docker-compose.yml files, we need to run the new script and rebuild the backend containers.</p><pre># Check running containers and their IDs, find the backends you need to kill<br>sudo docker ps<br><br>sudo docker kill a5a5e21537cb<br>sudo docker kill 54e51b0ae78f<br><br># navigate to the right folders like before and build new containers<br>sudo docker compose up</pre><p>Now, you should see the new containers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YyhdCawJzP0E_N5tsdPSbA.png" /><figcaption>Image by Author</figcaption></figure><h4>4. SDK upload images from source bucket</h4><p>If you simply want to upload the images without metadata, you can skip this section and do the exact same thing as step 5 (see next). By metadata, I mean the useful information for each image on the labeling interface that might help with labeling more accurately.</p><p>Based on the example from Label Studio SDK repo, you can modify what metadata and how you want to import in the ./label_studio_sdk/annotate_data_from_gcs.ipynb file. After running the python notebook locally, you should be able to see your images and metadata on the frontend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhscsWxfSDU_tTF7_2m8Ig.png" /><figcaption>Image by Author</figcaption></figure><p>And you should also see the Source Storage bucket in the settings. Do NOT click Sync Storage as it will sync directly from the bucket and mess up the metadata we imported.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e9CpgKbXelIQoHJz4mpyAA.png" /><figcaption>Image by Author</figcaption></figure><h4>5. Set up Target Storage</h4><p>Click <strong>Add Target Storage</strong>, and filling in the information accordingly. Copy-paste your service account key in the Google Application Credentials textbox and you are all set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4buz-cQG9W-Jn0LKqkmKng.png" /><figcaption>Image by Author</figcaption></figure><p>Every time you click <strong>Sync Storage</strong> on the Target Cloud Storage, it will sync the labeling outcome in the format of text into the GCS bucket. After clicking sync once, the process should be trigger automatically when submitting labeling results, but please check if you need to manually sync from time to time just in case.</p><p>Happy labeling!</p><h3>Acknowledgement</h3><p>It is my pleasure to be a part of <a href="https://sites.google.com/view/datashack-harvard-polimi/data-shack-2024?authuser=0">Data Shack 2024</a> in collaboration with Politecnico di Milano <a href="https://www.centroricercagianfrancoferre.it/home/FGFhome.php?lang=en">Gianfranco Ferré Research Center</a>. I would like to thank Prof. <a href="https://medium.com/u/69c7cfe8dc8e">Pavlos Protopapas</a> and Prof. Paola Bertola for your guidance and for making this project happen in the first place. I would like to thank <a href="https://medium.com/u/afb3db007f0b">Chris Gumb</a> and Prof. <a href="https://medium.com/u/88b92e077317">Marco Brambilla</a> for technical support and Prof. Federica Vacca and Dr. <a href="https://medium.com/u/e391affa9647">Angelica Vandi</a> for domain knowledge expertise in fashion. Finally, I would like to thank my teammates <a href="https://medium.com/u/48b7440feb38">Luis Henrique Simplicio Ribeiro</a>, <a href="https://medium.com/u/10478e152ee4">Lorenzo Campana</a> and Vittoria Corvetti for your help and for figuring things out with me along the way. I also want to give a round of applause to Emanuela Di Stefano, Jacopo Sileo, Bruna Pio Da Silva Rigato, Martino Fois, Xinxi Liu, and Ilaria Trame for your continued support and hard work.</p><h3>References</h3><ul><li>11655 Gianfranco Ferré, Ready-To-Wear Collection, Fall-Winter 2004. Courtesy of Gianfranco Ferré Research Center</li><li>13215 Gianfranco Ferré, Ready-To-Wear Collection, Spring-Summer 1991. Courtesy of Gianfranco Ferré Research Center</li></ul><p>Thank you for reading! I hope this blog has been helpful to you.</p><blockquote>Code in this post can be found in this <a href="https://github.com/AlisonYao/label-studio-customized-ml-backend">GitHub repo</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=324c2310d756" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/label-studio-customized-backend-for-semiautomatic-image-segmentation-labeling-324c2310d756">Label Studio Customized Backend for Semiautomatic Image Segmentation Labeling</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Visual Summary of SQL Date/Time Functions]]></title>
            <link>https://medium.com/data-science/a-visual-summary-of-sql-date-time-functions-8bb96ce4f1b4?source=rss-17016fd04e22------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bb96ce4f1b4</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[datetime]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[data-science-interview]]></category>
            <dc:creator><![CDATA[Alison Yuhan Yao]]></dc:creator>
            <pubDate>Fri, 29 Jul 2022 13:20:00 GMT</pubDate>
            <atom:updated>2022-07-29T13:20:00.171Z</atom:updated>
            <content:encoded><![CDATA[<h4>Preparing for SQL interviews?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uAoz1oTTh-1v8t7M" /><figcaption>Photo by <a href="https://unsplash.com/@agebarros?utm_source=medium&amp;utm_medium=referral">Agê Barros</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Between timestamp, date, and time data types, SQL date/time functions can be quite confusing. In this blog, I will attempt to map out the common data/time commands in SQL interviews using <strong>PostgreSQL syntax</strong>.</p><h3>Before SQL Code</h3><p>Before we start to code, let’s first pause and think about the elements in date/time representations. We know that time is linear, goes one way, and can be represented mathematically as a vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bq1Jl8bCWYa1qw4In4ZLYw.png" /><figcaption>Image by Author</figcaption></figure><p>The two key elements on the time vector t are <em>moment</em> and <em>duration</em>. These terms are probably not the most accurate, but since keywords like <em>timestamp</em> and <em>interval</em> are taken by SQL, let’s use different words for now to understand the concept.</p><ul><li><strong>Moment</strong> refers to the split second when an incident occurs. A moment is instantaneous, so it’s represented as a dot on the vector t. t1 and t2 are moments.</li><li><strong>Duration</strong> refers to the time span between two moments. A duration is made up of countless moments and has a beginning and an end.</li></ul><p>Therefore, we really just need to understand the two elements and the conversion between these two elements to master date/time functions in SQL.</p><h3>Moment &amp; Moment Family</h3><p><em>Timestamp</em> gives us the most information. A timestamp can be precise to milliseconds and informative to include time zone, but most of the time, a moment of the format YYYY-MM-DD HH:MM:SS will suffice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_6LNgYMMBLp3BStxh5VqA.png" /><figcaption>Image by Author</figcaption></figure><p><em>Timestamp</em> can be split into two parts, <em>date</em> and <em>time</em>, by casting a <em>timestamp</em> into a <em>date</em> or <em>time</em> object (shorthand ::). However, it is not advisable to cast a <em>date</em> or <em>time</em> back to a timestamp because you will be missing half of the information in the <em>timestamp</em> or SQL will throw an error.</p><p>A lot of information can be extracted from a <em>timestamp</em>, such as year, month, day, hour, minute, second, etc. However, not all information can be extracted from <em>date</em> or <em>time</em> objects alone. For example, you cannot extract the year from <em>time</em> 01:50:39.</p><p>Here are a few examples in PostgreSQL code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/632bf01b601a112cdbc6967999888ea0/href">https://medium.com/media/632bf01b601a112cdbc6967999888ea0/href</a></iframe><h4>Creating moment</h4><p>More often than not, you are given a moment in a SQL interview question. For example, it could be the login time of a user, the moment a user sends a message to another, or the moment a customer places an order. However, this is not guaranteed. Sometimes, you simply need to create your moment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lzXd_TniMZGlITSTbbOMnA.png" /><figcaption>Image by Author</figcaption></figure><p><strong>The present</strong>: 99% of the time, we need to use the present moment for some calculation. CURRENT_TIMESTAMP and NOW() give you the exact same timestamp of the present moment. More variations are presented in the image above. Please note that there is no such thing as a LOCALDATE.</p><p><strong>Customized moment:</strong> It’s rare to encounter scenarios where one needs to customize a specific moment, but if you do, MAKE_TIMESTAMP will do the trick. More variations are presented in the image above.</p><h4>From one moment to another</h4><p>DATE_TRUNC converts one moment to another. It works like a floor function that resets a timestamp to the beginning of year/month/week/day/hour/… of the timestamp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*999Mygo08k-ohKw3-ccXBg.png" /><figcaption>Image by Author</figcaption></figure><p>You can input a <em>date</em>, instead of a <em>timestamp</em>, to the function DATE_TRUNC and it will output results by filling in the unknown time with zeros. However, inputting a <em>time</em> will throw an error.</p><h3>Duration</h3><p>Now, let’s talk about duration. Duration corresponds to <em>interval</em> in PostgreSQL, which is presented in the format of ‘<em>20 years 11 months 6 days’.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hG9Ej5qKX25lPrMUyBU09g.png" /><figcaption>Image by Author</figcaption></figure><p>We can borrow the functions EXTRACT and DATE_PART again to get the specific year/month/day/hour/minute/second/… of the interval. The AGE function gives us a more holistic view. Please note that if only one input is given to the AGE function, it will automatically compare the input with the current timestamp, but the precision of the output will be consistent with your input.</p><h4>Putting together moments and intervals</h4><p>Knowing that timestamp2-timestamp1=interval, as long as we know two elements of the equation, we can calculate the third. Therefore, we can use timestamps and intervals to obtain other timestamps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AupC4hq5O5jI0FJffkjOrw.png" /><figcaption>Image By Author</figcaption></figure><p>Thank you for reading! I hope this blog has been helpful to you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bb96ce4f1b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-visual-summary-of-sql-date-time-functions-8bb96ce4f1b4">A Visual Summary of SQL Date/Time Functions</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forecasting Time Series Data: Netflix Stock Price Prediction]]></title>
            <link>https://pub.towardsai.net/forecasting-time-series-data-netflix-stock-price-prediction-a941fa2c4893?source=rss-17016fd04e22------2</link>
            <guid isPermaLink="false">https://medium.com/p/a941fa2c4893</guid>
            <category><![CDATA[netflix]]></category>
            <category><![CDATA[arima]]></category>
            <category><![CDATA[garch]]></category>
            <category><![CDATA[arch]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <dc:creator><![CDATA[Alison Yuhan Yao]]></dc:creator>
            <pubDate>Tue, 31 May 2022 15:09:58 GMT</pubDate>
            <atom:updated>2022-06-03T01:39:25.284Z</atom:updated>
            <content:encoded><![CDATA[<h4>ARIMA-(G)ARCH models with MiniTab and R</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c7IlirlvSLkRl9RN" /><figcaption>Photo by <a href="https://unsplash.com/@jakehills?utm_source=medium&amp;utm_medium=referral">Jake Hills</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The Netflix stock price has been quite volatile recently, which makes the prediction of the time series data very interesting. In this blog, I will use ARIMA-(G)ARCH models for prediction, Minitab for plotting, and R for model selection. (Because of the instructions of this class project, I will have to comply with some restrictions.)</p><p>Some prior knowledge before reading this blog includes:</p><ul><li><a href="https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average">ARIMA model</a></li><li><a href="https://www.youtube.com/watch?v=Li95a2biFCU">ARCH</a> and <a href="https://www.youtube.com/watch?v=inoBpq1UEn4">GARCH</a> models</li></ul><h3>Data Description</h3><p>This project uses the daily stock price of Netflix from 2002–05–23 to 2022–03–18 (4991 observations) for the time series forecast. The 2022–03–18 data is the latest entry from <a href="https://finance.yahoo.com/quote/NFLX/history?period1=1022112000&amp;period2=1647820800&amp;interval=1d&amp;filter=history&amp;frequency=1d&amp;includeAdjustedClose=true">Yahoo Finance</a> as of the time I obtained the dataset. The head of the table is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vvh7gmN2TR0TM-JqiZsHEw.png" /><figcaption>Image by Author</figcaption></figure><p>I will leave out the last data point, which is the data for 2022–03–18 for the ARIMA-(G)ARCH modeling. Therefore, n=4991–1=4990 and I will be using the <em>Adj Close</em> data from 2002–05–23 to 2022–03–17.</p><h3>ARIMA modeling</h3><p>The time series plots of Netflix stock price (Adj Close), DifNetflix, LogNetflix, and DifLogNetflix are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nzLR-M__0iK91c3pNa_XaA.png" /><figcaption>Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eh4WkZ8rKV8wZygHXrO99g.png" /><figcaption>Image by Author</figcaption></figure><p>There is strong evidence that Netflix has level-dependent volatility. Netflix stock prices are more volatile in recent years. <strong>Taking log can help us mitigate level-dependent volatility and linearize the plot</strong>, as the volatility of DifLogNetflix does not seem to depend on a level anymore.</p><p>For choosing an ARIMA(p,d,q) model, we need to <strong>first determine the value of d and see how many times we need to difference the data to make it stationary</strong>. The ACF and PACF plot of LogNetflix is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFsOgjnvg_VIZ6lmK75tiA.png" /><figcaption>Image by Author</figcaption></figure><p>The ACF plot of LogNetflix indicates a hanging behavior and the PACF plot of LogNetflix cuts off after lag 1, so LogNetflix is non-stationary. We need to difference the data.</p><p>The ACF and PACF plots of DifLogNetflix show that differencing once seems to make the data stationary, as there are no statistically significant lags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_e0S20q6bZ-O0yI8jkjK-g.png" /><figcaption>Image by Author</figcaption></figure><p>To double-check if d=1, we can difference the data again and look for a sign of over-differencing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GU626lOFDzNtIowhjuVUUw.png" /><figcaption>Image by Author</figcaption></figure><p>Indeed, differencing twice shows <strong>strong evidence of over-differencing as the PCF of Dif2LogNetflix is statistically significantly negative at lag 1 and close to -0.5</strong>. Therefore, we conclude that d=1 in the ARIMA model. The ACF plot of DifLogNetflix suggests an ARIMA(0,1,4) model, while the PACF of DifLogNetflix suggests an ARIMA(4,1,0) model.</p><p>Now, we need to select the p and q in the ARIMA model. Let’s pick p,q = 0,1,2 arbitrarily (because of the principle of parsimony) and compare AICc. The formula for AICc is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*vMO3EwViJy66kojvLDNMeA.png" /><figcaption>Image by Author</figcaption></figure><p>The SS means the sum of squared error and it can be obtained from Minitab output. We know N = n–d = 4990–1 = 4989.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9_cMPh3vsazXsc5OV1wEA.png" /><figcaption>Image by Author</figcaption></figure><p>ARIMA(0,1,1) with constant gives us the smallest AICc value, so we choose ARIMA(0,1,1) with constant. The Minitab output for ARIMA(0,1,1) with constant is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Ow9IW4SwYC0eCyix1X578w.png" /><figcaption>Image by Author</figcaption></figure><p>Both the MA1 coefficient and the constant are statistically significant, with p-values less than 0.05. Therefore, if we denote {x_t} as the time series of Netflix, {y_t} as LogNetflix and {z_t} as DifLogNetflix. The best estimate of the MA1 coefficient is -0.0309 and that of the constant is 0.001151. Therefore, the fitted model is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8d8fhSFgOyZ_VjuF1ZDdxw.png" /><figcaption>Image by Author</figcaption></figure><p>where z_t = y_t-y_{t-1} = log(x_t)-log(x_{t-1}).</p><p>The one step ahead forecast and 95% forecast interval are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*ILcxyx3w-XB7OtLZC8fnHw.png" /><figcaption>Image by Author</figcaption></figure><p>The time series plot of the <em>residuals</em> is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*owKjJxEX2VuA8YitxEprLA.png" /><figcaption>Image by Author</figcaption></figure><p>The residuals look relatively random, with only a few with absolute values over 0.3. The ACF and PACF plots of the residuals are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H9CBb4ilHrBV6a3o-_G8Ng.png" /><figcaption>Image by Author</figcaption></figure><p>There aren’t many statistically significant lags in the residuals, meaning that the residuals look uncorrelated. The ACF and PACF of <em>squared residuals</em> are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WvXJb4d16Z09C53rmjcy4g.png" /><figcaption>Image by Author</figcaption></figure><p>However, the squared residuals have multiple lags that are statistically significant, meaning that the residuals are not independent. Also, we can see from the time series plot of the residuals that the variance is not constant. There exists evidence of conditional heteroscedasticity.</p><p>Before doing the (G)ARCH modeling, we need to save the residual information from Minitab to a txt file and import it into R.</p><pre># read file &amp; check head<br>res = scan(&quot;RES.txt&quot;, what=&quot;list&quot;)<br>head(res)</pre><pre># clean up data &amp; convert data type<br>res = res[-c(1,2)]<br>res = as.numeric(res)<br>head(res)</pre><h3>(G)ARCH modeling</h3><h4>ARCH(q)</h4><p>To select the ARCH(q) model with q ranging from 0 to 10, we can calculate the AICc. The formula for AICc changes here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*DpNlrfTekR-sCeWeJMoiRA.png" /><figcaption>Image by Author</figcaption></figure><p>The values of logLik can be obtained from R.</p><pre>library(tseries)</pre><pre># check different ARCH models<br>for (i in 1:10){<br>  print(paste0(&#39;model ARCH(&#39;, i, &#39;)&#39;))<br>  model = garch(res, c(0,i), trace=F)<br>  print(summary(model))<br>  print(logLik(model))<br>}</pre><pre># ARCH(0) model has to be manually calculated<br># model = garch(res, c(0,0), trace=F) is going to give an error<br>N = 4989<br>print(paste0(&#39;log Lik.&#39;, -0.5*N*(1+log(2*pi*mean(res^2)))))</pre><p>Again, we know N = n–d = 4990–1 = 4989, so we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HkYI6NqY6CJhhjeWLu8dKQ.png" /><figcaption>Image by Author</figcaption></figure><h4>GARCH(1,1)</h4><p>We can also consider the GARCH(1,1) model due to the principle of parsimony. We have logLik = 9799.593 (q=2) and the corresponding AICc is -19593.18118555667. GARCH(1,1) yields the smallest AICc, so we choose GARCH(1,1).</p><pre># compared with GARCH(1,1) model<br>model=garch(res,c(1,1), trace=F)<br>print(summary(model))<br>print(logLik(model))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MR61J-KfY4RqfktBiQTU1Q.png" /><figcaption>Image by Author</figcaption></figure><p>The p-values are not correct because they are for a 2-tailed test. We should look at half of the presented p-values, but they are so small that half of any of these p-values is strongly statistically significant. Therefore, a0, a1, and b1 are all statistically significant. However, the Jarque Bera test has a p-value less than 0.05, which indicates that the conditional distribution of GARCH residuals is not normally distributed. The Ljung-Box test has a p-value greater than 0.05, which means that the GARCH residuals are not correlated. But overall, the model is inadequate.</p><p>To write the complete form of the chosen GARCH(1,1) model, we have ω=0.000005875, α=0.01425, and β=0.9814. Therefore, the complete form is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w1ldpvUuDINPKoCAqfexBw.png" /><figcaption>Image by Author</figcaption></figure><p>The unconditional variance is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j_5BmQKKdACThr_ZLKRlcA.png" /><figcaption>Image by Author</figcaption></figure><p>We know from the residual data that ϵ_4990=0.035765. We also know that h_4990=0.00138539642318183. Therefore, <br>h_4991=0.000005875 + 0.01425 × 0.035765² + 0.9814 × 0.00138539642318183 = 0.001383731.</p><p>From the ARIMA(0,1,1) model, we know that f_4990,1=5.91954. The 95% forecast interval of the ARIMA-GARCH model is, therefore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LBWpfKNRtDEBu4wol74JdQ.png" /><figcaption>Image by Author</figcaption></figure><p>Compared to the ARIMA(0,1,1) model, which has a 95% forecast interval of (5.84927, 5.98981), the ARIMA-GARCH model has a wider forecast interval.</p><p>The 5th percentile of the conditional distribution of the next period’s log exchange rate is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rpCn7sLUN91SoX_nHBss9g.png" /><figcaption>Image by Author</figcaption></figure><p>Now we calculate the <em>conditional variance</em> ht:</p><pre># calculate ht<br>ht = model$fit[,1]^2<br>ht[1:5] # has NA<br>write(c(&#39;ht&#39;, &#39;*&#39;, ht), &#39;../htfile.txt&#39;, 1)</pre><p>The time series plot of ht is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*0LLz_xy15Ge8axEa3Mf98g.png" /><figcaption>Image by Author</figcaption></figure><p>The ht from 2002/5/23 to 2014/4/14 is more volatile than later ht. Bursts of high volatility reside between 2002/5/23 to 2014/4/14, with the highest volatility residing between 2022/5/23 to 2005/5/9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*01tSPgiM4ybEQ6uFqyp1Rg.png" /><figcaption>Image by Author</figcaption></figure><p>Compared with the time series plot of LogNetflix, it seems that these bursts of high volatility do agree with those found from the examination of the time series plot of the log exchange rates themselves.</p><p>The time series plot of logNetflix and one-step ahead 95% forecast intervals is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*nBJloZGoC2vXFp2muOsZuw.png" /><figcaption>Image by Author</figcaption></figure><p>According to the plot, LogNetflix is mostly between low and high, so the forecast interval is quite accurate. However, since the ARIMA-GARCH parameters are estimated from the entire data set, not just the observations up to the time at which the forecast is to be constructed, the performance may be somewhat better here than in an actual forecasting context, so the practical usefulness is somewhat questionable for x_1 to x_4990. However, x_4991 was not utilized in building the ARIMA-GARCH model, so the forecast for x_4991 is more practically useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*SltUtISzlMQilnfNdhK90A.png" /><figcaption>Image by Author</figcaption></figure><p>The test tells us that the p-value is smaller than 0.005, so <em>archres</em> are not normally distributed. The s-shaped plot is an indicator that a heavier tail, which means that the model does not seem to have adequately described the leptokurtosis in the data.</p><p>There are 209 failures in prediction intervals, which is about 209/4988 = 4.19% of all intervals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/104/1*JIf2wActWe9j01peowCv6Q.png" /><figcaption>Image by Author</figcaption></figure><h3>Performance Check</h3><p>For LogNetflix, the 95% forecast interval of the ARIMA model is (5.84927, 5.98981), which corresponds to an interval of (347.89, 399.339) for Netflix. x_4991=380.6 is within the forecast interval.</p><p>The 95% forecast interval of the ARIMA-GARCH model is (5.846631, 5.992449), which corresponds to an interval of (346.0665, 400.39398) for Netflix. x_4991=380.6 is within the forecast interval.</p><p>The ARIMA interval and ARIMA-GARCH interval are very similar. Both forecast intervals seem neither too wide nor too narrow. The ARIMA-GARCH interval is slightly wider to adapt to the recent higher volatility because ARIMA-GARCH is adaptive, but ARIMA is not.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a941fa2c4893" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/forecasting-time-series-data-netflix-stock-price-prediction-a941fa2c4893">Forecasting Time Series Data: Netflix Stock Price Prediction</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Guide to Data Science Masters Application]]></title>
            <link>https://medium.com/data-science/a-comprehensive-guide-to-data-science-masters-application-c9fbefe41825?source=rss-17016fd04e22------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9fbefe41825</guid>
            <category><![CDATA[graduate-school]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-science-training]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[grad-school-application]]></category>
            <dc:creator><![CDATA[Alison Yuhan Yao]]></dc:creator>
            <pubDate>Mon, 21 Mar 2022 14:42:53 GMT</pubDate>
            <atom:updated>2022-06-01T19:15:23.549Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Science Undergrad Journey Part 4</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tCsT0735NDPqL_UA" /><figcaption>Photo by <a href="https://unsplash.com/@ryanhoffman007?utm_source=medium&amp;utm_medium=referral">Ryan Hoffman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Table of content</h4><p>· <a href="#f884">Action Timeline</a><br> ∘ <a href="#023f">Make up your mind early</a><br> ∘ <a href="#d2b8">Know what programs are out there for you</a><br> ∘ <a href="#5ed1">Get GRE, TOEFL, resume and LOR done early</a><br> ∘ <a href="#bf34">Grind Statement of Purpose/Personal Statement</a><br> ∘ <a href="#d48b">Choose your target programs wisely</a><br> ∘ <a href="#1d0c">Apply?!!!</a><br> ∘ <a href="#d84e">Summary Algorithm</a><br>· <a href="#a659">Application Handbook</a><br> ∘ <a href="#d0cb">Chapter 1 — SOP/PS</a><br> ∘ <a href="#d036">Chapter 2 — Diversity Statement</a><br> ∘ <a href="#5df9">Chapter 3 — LOR</a><br> ∘ <a href="#5a1c">Chapter 4 — Resume/CV</a><br> ∘ <a href="#1c28">Chapter 5 — GPA, GRE &amp; TOEFL</a><br> ∘ <a href="#4678">Chapter 6 — Interview</a><br> ∘ <a href="#713d">Chapter 7 — Miscellaneous</a><br> ∘ <a href="#5ab5">Chapter 8 — Mindset</a><br>· <a href="#f3fa">Final Words</a></p><p>I wish someone would have written a blog post like this when I was applying to Data Science Masters programs. As a Data Science undergrad, I knew I wanted to go to grad school and continue my studies in DS for a long time, but the actual application can be complicated. From last December to this February, I finally did all the work for the applications and have been admitted into my dream program!</p><p>Grad school application is an emotional soul-searching journey. It’s now March 2022, so I am writing everything down when my memory is still fresh and the struggle still feels real. I want this post to be informative, practical, but also personal.</p><p>Before we start, a little background information about me.</p><blockquote>I am a DS undergrad. <br>I am an international student from Shanghai. <br>I planned to apply to 12 DS Masters programs in the US but actually applied to 10 because I received my dream offer before the deadline of the last 2. <br>Stats: GPA 3.9+, GRE 325+, TOEFL 110+</blockquote><h3>Action Timeline</h3><h4>Make up your mind early</h4><p>Going to grad school is a big life decision. I have contemplated this question for 4 years all through my undergrad. Should I go to grad school or should I go straight to work? Having been in the Medium DS community for a long time and read so many inspiring stories of self-taught data scientists, I know receiving formal education is not the only way to break into the DS field. But I love academia and I have met many great researchers and scholars throughout my undergrad studies. Therefore, I chose to reject some perfectly great full-time job offers and go for grad schools instead.</p><p>Making up your mind early means that you have much more time to accumulate experiences and prepare for grad school applications. Here are some practical benefits:</p><ul><li><strong>Take your GRE (and TOEFL) early</strong><br>You cannot take these tests the day before your application deadline, so it is best to have plenty of time to prepare and give ETS enough time to send your test scores.</li><li><strong>Easier to maintain a high GPA</strong> <br>I would be lying if I say GPA doesn’t matter. It matters especially if you are applying to a competitive program. And maintaining a high GPA requires years of consistent effort. It is impossible to boost your GPA to a 3.8 in one semester when you only have a 2.0 to begin with.</li><li><strong>Have more time to network with potential recommenders</strong> <br>I hate to sound so utilitarian, but let’s face it, grad school applications require at least 2 letters of recommendations (LOR) and there is nothing worse than thinking back and realizing you have never bonded with a DS expert who would be willing to be your recommender. I, for example, have had amazing professors in academia and mentors in the industry who know my abilities and my career plans and discuss grad school stuff with me to help me make sure going to grad school is the right choice. I got close with them and became familiar with their work, all of which inspired me to be in academia and become a data scientist. When the time came and I needed LORs, they were very happy to help. However, it takes time and effort to maintain a genuine and reciprocal mentor-mentee relationship that helps you grow.</li></ul><p>A rough timeline is that I knew I wanted to go to grad school in my sophomore year. Of course it’s better to prepare for things early on, but don’t freak out if you think you are running out of time.</p><h4>Know what programs are out there for you</h4><p>Now that you know for sure that going to a Data Science Masters program is the way to go, it’s important to keep an eye on related information. Perhaps you are looking for online programs or part-time programs, or maybe full-time programs (like me). You need to first have some idea of what options are out there. For example, my soon-to-be alma mater NYU has an exceptional DS Masters program, so I’ve known about that for years.</p><p>A rough timeline for me is that throughout my junior year, I gathered all kinds of information from upperclassmen about the programs they are applying to and got accepted into. I had a pretty good idea of which programs I should look out for. I kept a Google sheet of programs that I shared with my fellow friends who are also applying to DS Masters.</p><h4>Get GRE, TOEFL, resume and LORs done early</h4><p>I never enjoyed a bit about preparing for the GRE exam, but GRE scores are sometimes required for application. I cannot always waive TOEFL as an international student, so I had to take it as well. And tests need time and energy to prepare. I took my GRE during the winter break of my junior year (prepared for 1 week) and TOEFL the summer before my senior year (prepared the day before). I only took each test once. Maybe I could have done better, but I had more exciting things in life that I wanted to spend time on, you know. I do have friends whose sheer willpower helped them through 4 GREs in a year. I am absolutely in awe. A satisfactory score in the end is worth all the trouble depending on the level of your expectation. I recommend doing GRE and TOEFL early because you don’t need to worry about these tests by the time you are applying.</p><p>I prepared a 2-page academic resume that is tailored to DS applications. It is longer than a resume used for any job application and has more details to it. I will talk more about this later.</p><p>LOR, on the other hand, is much trickier. It’s a courtesy to ask your recommenders and confirm that they are willing to write you a LOR early. Put yourself in their shoes and you would understand that they are very busy and probably have a lot of other students asking them the same thing. Do not wait until the last minute to ask your professors or supervisors!! It lowers your chances of securing the LOR. I asked all my recommenders by the end of September (senior fall semester). Of course, one exception is if you met a great recommender during your senior fall semester. After midterms, which is when you will be assessed, your professor probably has a better idea of your ability and your goal. Asking them for a LOR after the midterm is still not too late.</p><p>A rough timeline for me is that I got these 4 pretty much done by the beginning of my senior fall semester.</p><h4>Grind Statement of Purpose/Personal Statement</h4><p>I spent so many late nights working on my statement of purpose (POS), or personal statement (PS), because it was both trash and so beautiful at the same time. Yea, I certainly have a love-hate relationship with my SOP/PS. I don’t think there is much difference between SOP and PS. Unless the school specifically outlined requirements for their essays, I used the same 1000-word version that combined my DS experience and personal aspiration.</p><p>A rough timeline is that I started to reflect on my past experience and think about how I am going to write the SOP during the summer before my senior year. That is why I started blogging! It helped me clear my thoughts and organize my professional experience to write the first few blogs about <a href="https://medium.com/codex/ds-undergrad-journey-part3-my-internship-research-experience-907aaa57c497">my undergrad journey</a>. And at the same time, I have been actively researching everything about a DS career throughout my undergrad and I constantly think about why I like DS, why DS is suitable for me as a career and triple-check that this match is truly optimal for me right now. I know so many people graduating from DS and working as software engineers. I really needed to sort out the rationale behind why DS is exactly what I want for me and put my thoughts into an essay later.</p><p>But I didn’t actually open up a new Word file and started writing until the beginning of my senior year fall semester. I wish writing SOP was as easy as writing blogs, but it is not. A SOP needs to be informative, entertaining, and concise. Informative because you need to recap 3 years of DS experience; Entertaining because you do not want your essay to be bland and soporific; concise because you need to employ formal English language to tell your story in 1000 words. It really takes a lot of revising to birth a satisfactory SOP.</p><h4>Choose your target programs wisely</h4><p>Remember your list of all the programs available? It’s time to narrow down and pick your target programs. It all comes down to a matching game. You are looking for the right program for you and grad schools are looking for the right candidates for them.</p><p><strong>Know your target programs<br></strong>Grad schools typically have a devoted webpage that details everything about their DS programs. You can get a lot of information by reading through online information. Here, I list some aspects you might think about when choosing your programs:</p><ul><li>Curriculum</li><li>Cohort size</li><li>School location</li><li>Length of the program <br>Most full-time DS programs in the US are 1 to 2 years, with rare exceptions that can be extended to 3 years.</li><li>Tuition</li><li>Is the program research-oriented or career-oriented? <br>A research-oriented program might be right for you if you want to pursue a Ph.D. in the future. Otherwise, career-oriented programs are great because they often provide students with internship opportunities.</li><li>Faculty research interest</li><li>Is it easy to obtain the visa and OPT/CPT? <br>Access to OPT and CPT is crucial if you want to work in the US as an international student.</li><li>Does the program require GRE?</li><li>Institution reputation</li><li>Do you vibe with the university and the program? <br>I think this question is the most important one. Studying offline and spending more than a year on a university campus shape new perspectives and transform a person. Do you agree with the values and initiatives this university is working on?</li></ul><p>Examining program websites is already plenty of work, but if you are really interested in a particular program, you can go to their zoom info session or talk to their program student ambassador if possible.</p><p><strong>Know yourself<br></strong>This part is much trickier because knowing ourselves is a lifelong endeavor, but at least you know the basics. You have the metrics, namely GPA, GRE, etc, that schools impose on you. Some universities would tell you their mean and medium GPA and GRE on their website. You can quickly check if you seem like a competitive candidate.</p><p>Now that you have done some research, you can make another list of your safety, match, and reach schools. I migrated to Notion to keep track of everything. There are 20 more marked “not applying” that did not make it on to the screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lpsw77xosYJvMSaJD8SOLQ.png" /><figcaption>Image by Author</figcaption></figure><p>This is my list of target schools, among which 2 are my absolute favorites. I picked each and every one of them after careful consideration. Since I care a lot about whether I vibe with the school or not, I have some sort of personal connection to all these schools or the cities they are in. I have friends from 10 out of the 12 universities listed here and many professors I am close to graduated from these schools. I’ve only personally been to 3 of these schools, but I have a pretty good idea of what their vibes are like and I know I want to be like the friends and professors I look up to.</p><h4>Apply?!!!</h4><p>Not so fast. As you start applying, this list is bound to undergo so many updates so quickly that you might as well call it your dynamic array. And when you are writing your SOP, you will find yourself going back to the program websites again and again to double-check all the little details.</p><p>But you can start with the application process by first creating an account and filling out basic information such as name and education background. My suggestion would be to quickly skim everything in every section on every application page. If in some cases, you cannot go to the next page before filling out the current page, just type something in the input box or upload a blank PDF file to force the system to move on. You can typically change this information later, but be sure to double-check.</p><p>A holistic view of what is required of you enables you to:</p><ul><li>get to the recommendation page and send emails to your recommenders sooner</li><li>get to your test score page and check if the school has received your official scores from ETS or not</li><li>identify the trickier pages such as SOP, diversity, faculty interests, etc that you cannot fill out right away and write down instructions.</li></ul><p>Now that you have some ideas of what is happening, you can go back to doing research on the program and polishing your SOP. I will talk about this more in the next section of this blog.</p><h4>Summary Algorithm</h4><p>Here is an algorithm to sum up everything till now because I have been reading so many papers for my capstone research lately. All I can think about is algorithms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gaEVTZlE7YNkisjExsNWrw.png" /><figcaption>Image by Author</figcaption></figure><h3>Application Handbook</h3><h4>Chapter 1 — SOP/PS</h4><p>I said in the very beginning that the application is a soul-searching journey, and the SOP should be where you pour your heart and soul into.</p><ul><li><strong>SOP vs PS </strong><br>I personally don’t think SOP and PS are any different in my applications because I have never been asked to submit them both. But from the Googling I’ve done, they should be different. SOP, or statement of (academic) purpose, is purely about facts like academic background, technical abilities, research interest, and career plan. PS, personal statement, is the one to tell your life story, identify hardship, and explain weaknesses (eg. why there’s a C on the transcript). However, since no program asked me to submit both an SOP and a PS, I just wrote a 2-page essay of about 1000 words and essentially merged the two into one.</li><li><strong>Requirement of SOP/PS<br></strong>1. describe your past and present work related to this program<br>2. what makes you qualified for this program<br>3. why are you interested in applying to this program<br>4. career/research plans<br>5. why and how will this program help you achieve your goal</li><li><strong>Read others’ SOP for reference<br></strong>You can easily find other people’s DS SOP online if you are unsure about how to start writing yours. I think it’s okay to read some before you start writing, but eventually, your SOP needs to be yours and tailored to you alone.</li><li><strong>Introduction<br></strong>For the reasons I have explained above, SOP is not merely listing your DS experience. Instead, it is telling a story of who you are, what you are capable of, and who you want to be. You need a strong first paragraph as a gripping introduction that highlights a key moment in life that you need to somehow connect to DS. It could be a turning point in your studies that you realize your old major is not sufficient anymore and you want to pursue DS instead. It could be the biggest accomplishment in your DS journey that reinforced your determination. It can also be extremely personal. Maybe the reason you want to study DS is because of your family or certain life experience. The first paragraph is like the beginning of a good film. It introduces the main character, you, and leaves a deep impression on the audience.</li><li><strong>Body</strong><br>Then, you can present your experience in a logical way. By logical, I mean the body paragraphs do not need to be chronological. They just need to make sense and showcase your progression over time. But it wouldn’t make you stand out among thousands of applicants if all you have is the academic abilities to thrive in future studies. You need to dig deep into your core, be it your characteristics or your belief. Why is DS the one area you want to study? Perhaps it’s because of your curious nature. There must be something deeper that drives you toward DS. And given this connection, it is most likely that you are going to stick to DS in the future as well.</li><li><strong>Career/research plan<br></strong>I think only a few of us know exactly what we want to do in the future, but in the SOP, your career or research plan is better to be detailed. Therefore, writing this SOP is a good time to think about what you want to accomplish in life. You can write down your answer in the second to last paragraph, but it needs to have some connection to your previous experience. Otherwise, it would feel strange and made up. The harsh truth is that the world tends to reward those who have a clear idea of what they want to do with their life.</li><li><strong>Why and how will this program help you achieve your goal<br></strong>In the last paragraph, you can identify specific courses that fit your research interest, professors you want to work with, clubs you want to join, and anything else you deem suitable. Since I was applying to multiple programs, I kept everything else the same except the last paragraph to talk specifically about each program.</li><li><strong>The spine of the SOP<br></strong>I’d like to think that writing an SOP is like creating a script for a protagonist in a film, so I am going to use the lingo “spine” to refer to the core of a hero’s story (I am very interested in filmmaking as well). Similarly, a strong SOP showcases one or two key desirable characteristics of an applicant. Ambitious, curious, determined, proactive, organized, hardworking, passionate, etc, are all positive characteristics, but you cannot say it out loud in the SOP. You need to show the “spine” by describing your actions in the past which corresponds to these adjectives. Otherwise, your “film” might not be engaging enough and the “lines” might sound didactic.</li><li><strong>Proofread<br></strong>You can ask the writing services at your university or simply your friends to help proofread your SOP. I think it’s important to have a proofreader whose major is completely non-technical. They might be able to spot things that are otherwise undetectable. For example, they might find your writing too technical that they cannot understand at all. If so, it’s probably a good idea to tone it down a little. There definitely are ways to describe a project with fewer technical terms. Although everyone on the admissions committee probably comes from a STEM background, ensuring the readability of your SOP is still important.</li></ul><h4>Chapter 2 — Diversity Statement</h4><p>A diversity statement is usually optional, but I have seen schools requiring a personal statement, while in fact, it was asking for a diversity statement.</p><p>Typically, you talk about how you can contribute to the diversity of the university as a diverse individual. Diversity lies in gender, ethnicity, sexual orientation, religion, nationality, socioeconomic status, life experience, family condition, and so on. There is a lot of flexibility in what you can write about. For example, I thought it would be nice to link my diverse background to my major, so I wrote about how diversity is important to eliminating AI biases.</p><h4>Chapter 3 — LOR</h4><p>LORs are from either your professors or internship/job supervisors. The more related their field of expertise is to DS the better because they can better attest to your technical abilities. I’ve heard people saying that one probably prefers someone with a bigger title to write your LOR, but I don’t think the title is something one should be too concerned about. Instead, I believe you should find the recommenders who really know you and understand your career or research goals. Their familiarity with you can be naturally presented in LORs and the admission committee will feel it.</p><ul><li><strong>LOR Content <br></strong>A LOR needs to show that the candidate has strong quantitative skills, solid soft skills, and anything that stands out to your recommender.</li><li><strong>What makes a strong LOR? <br></strong>Your recommenders probably have written so many LORs before that they already have a template. However, a template is bad for us students because templates do not make you more competitive than others. Therefore, this is why finding recommenders who are familiar with you helps. People who really know you will probably write a tailored LOR instead of using a template.</li><li><strong>Should I waive my right to access LORs? <br></strong>Generally speaking, waiving your right makes the LOR more credible. I have professors who specifically asked me to waive my rights, so I waived them all.</li></ul><h4>Chapter 4 — Resume/CV</h4><p>While a resume for job interviews is typically 1-page-long, an academic CV can have 2 pages or more. But the third page onward probably won’t get as much attention. So a rule of thumb is to write the important things first and preferably within the first 2 pages.</p><ul><li><strong>Sections<br></strong>My CV had 7 sections: education, work experience, research &amp; publication, scholarships &amp; honors, activities, Data Science competitions &amp; projects, and skills. You can certainly add more sections or get rid of some according to your need. I arranged these sections to be exactly 2 pages.</li><li><strong>Add links to your projects<br></strong>The only thing I want to emphasize is adding links to your GitHub or website or paper next to each of your projects and research. This shows evidence that you indeed contributed a lot to the projects and it also gives the admission committee a way to further evaluate your technical skills. It’s best if you have websites that visualize project outcomes.</li></ul><h4>Chapter 5 — GPA, GRE &amp; TOEFL</h4><p>These stats are important but not that important. Don’t be too frustrated if some of them are not as high as you wanted. As long as you have learned the skills necessary for DS, GPA and GRE are merely numbers. They won’t put a damper on your dream of becoming a data scientist in the long run. However, getting a decent score does take plenty of time and energy, so again, it’s better to do everything early before the actual application.</p><h4>Chapter 6 — Interview</h4><p>I personally did not apply to any programs that require an interview. But from the information I learned from my friends, an admission interview is more of a behavioral interview than a technical one. You need to be prepared to talk about some project details on your resume and answer some general questions about, for example, how you overcame a challenge in group work or what’s your biggest weakness. Getting an interview is a positive sign that shows you are one step closer to admission, so just be confident and be ready to chat. Admissions and professors are humans too.</p><h4>Chapter 7 — Miscellaneous</h4><ul><li><strong>Portfolio website <br></strong>If there is anything else to make an application even stronger, it would be having a DS portfolio website. It’s also a good way to demonstrate some software engineering skills if you can build your own website. An easy and budget-friendly way is hosting your portfolio website on GitHub.</li><li><strong>Clean up GitHub page <br></strong>If you are running out of time or simply don’t want to code a portfolio website, you can always use your GitHub page. But I bet most people who are applying to DS programs have a GitHub page, so you can stand out by cleaning up your GitHub page:<br>1. Add a profile page/about me page<br>2. Add a proper README.md to each of your projects</li><li><strong>Helpful Reddit Q&amp;A with Grad Admissions Director<br></strong>Most I’ve written so far is from the perspective of an applicant (hope you can relate), so it’s very helpful to see from what the admissions are looking for. In <a href="https://www.reddit.com/r/gradadmissions/comments/rv9242/grad_admissions_director_here_what_burning/">this Reddit Q&amp;A</a>, a grad admissions director was very generous with their time and answered many good questions that students have. The director’s advice applies to STEM in general but also DS as well.</li></ul><h4>Chapter 8 — Mindset</h4><p>Waiting for application outcomes is the worst. Each program seemed like a hundred-dollar lottery ticket. I wondered if I am qualified for these programs all the time and kept thinking about maybe applying to more programs just to be sure. I think it’s perfectly normal to have anxiety, but please make sure to talk to someone and process these feelings in a healthy way. And then one day, you will get your first offer and everything will be different, but in a good way.</p><h3>Final Words</h3><p>As much as I want to show you some (hopefully helpful) advice on DS Masters application, the application is still your own journey of self-reflection and self-discovery. The application process is the perfect chance in your undergrad to pause and think about your future. I want to use this blog to encourage applicants to really think more. Please don’t do something you don’t enjoy just because the field seems hot.</p><p>For me, work, aka what I do, is extremely important to my identity and my happiness. I take pride in my work and enjoy the pleasure from a simple task well done. Therefore, I enjoyed thinking about the whole application process and anything relating to DS. Well, you should know that from the fact that I write Medium blogs. So, my main challenge was what not to include in my SOP, because I have a million things to write about.</p><p>Latest update on my applications:</p><blockquote>I have heard back from 6 schools as of today. I got 5 ADs and 1 rejection (hey, no one is perfect). I am very excited to go to my dream school, but really, I would have been very happy to get any offer to continue my DS journey. I am going to leave the university name out of this blog because what’s important is finding the right fit for what you love. (Thanks for your curiosity if you actually read to this part, but I’m sure you can find out if you really want to. After all, we are all researchers:) )</blockquote><p>If there’s anything I failed to cover in this blog, please leave a comment or reach out to me directly. I want to help however I can.</p><p>Thank you for reading! I hope this has been helpful to you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9fbefe41825" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-comprehensive-guide-to-data-science-masters-application-c9fbefe41825">A Comprehensive Guide to Data Science Masters Application</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression for Causal Inference]]></title>
            <link>https://medium.com/codex/linear-regression-for-causal-inference-242da2a01086?source=rss-17016fd04e22------2</link>
            <guid isPermaLink="false">https://medium.com/p/242da2a01086</guid>
            <category><![CDATA[directed-acyclic-graph]]></category>
            <category><![CDATA[r-language]]></category>
            <category><![CDATA[causality]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[violence-against-women]]></category>
            <dc:creator><![CDATA[Alison Yuhan Yao]]></dc:creator>
            <pubDate>Sun, 06 Feb 2022 21:18:03 GMT</pubDate>
            <atom:updated>2022-02-07T04:02:01.033Z</atom:updated>
            <content:encoded><![CDATA[<h4>A deeper dive into correlation vs causation.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aOkqabqk54Y3barl" /><figcaption>Photo by <a href="https://unsplash.com/@sunder_2k25?utm_source=medium&amp;utm_medium=referral">Sunder Muthukumaran</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Correlation does not imply causation.</p><p>Yes, you’ve probably heard this many times. I’ve heard it again and again throughout my undergraduate training in Data Science that it has left a mark on my soul for eternity. But it turns out that linear regression can do more than just prediction (using correlation). It can also help us make <em>causal inferences</em>! Maybe the relationship between correlation and causation is more complicated than we originally thought.</p><p>In this blog, let’s take a look at:</p><ul><li>how to interpret causal graphs,</li><li>what confounder and spurious relationship are, and</li><li>how to conduct causal inference with linear regression through a simple example in R.</li></ul><h3>Causal Graph</h3><p>We can represent a causal relationship in a causal <a href="https://en.wikipedia.org/wiki/Directed_acyclic_graph">directed acyclic graphs</a> (DAG), or a <a href="https://en.wikipedia.org/wiki/Causal_graph">causal graph</a>. For example, this is a causal DAG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1OqpJzQONhTL6HzxMXCGqA.png" /><figcaption>Image by Author</figcaption></figure><p>A and B are 2 variables. The arrow from A to B indicates that A causes B. That’s pretty much it. DAGs paint a clear picture of your assumptions of the causal relationship between variables. And before you know it, the causal graph can get pretty complicated.</p><pre># a bit of R code<br>library(dagitty) <br>library(ggdag)  <br>dag &lt;- dagitty(&quot;dag{ A -&gt; B; C -&gt; B; A -&gt; C; D -&gt; C; E -&gt; C; F -&gt; E; F -&gt; D; G -&gt; A; G -&gt; C; E -&gt; A; }&quot;)<br>ggdag(dag)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LQyZStfaYfUYMMQ0sFagPg.png" /><figcaption>Image by Author</figcaption></figure><p>However, as the name directed acyclic graph (DAG) suggests, no matter how complicated the causal graph gets, there are 2 rules:</p><ol><li>Any edge can only be <strong>unidirectional</strong>, or one-directional, meaning A and B cannot cause each other. Because time only flows one way. There is always a temporal sequence between A and B. However, sometimes there can be bidirectional arcs, but that means the 2 variables are dependent but <em>the cause is unclear</em> [1].</li><li>There are <strong>no loops</strong> in the graph, meaning it is impossible for A to cause B, B to cause C and then C to cause A (or any loop that involves more variables). For the same reason as above, if A happens first and C happens the last, there cannot be an edge pointing from C to A. [2]</li></ol><p>Therefore, for variables that are correlated and not necessarily causal, the edge in the causal graph may or may not exist. If it does, the direction is undetermined. If we do believe a correlation can lead to a possible causation, we usually have a strong theoretical foundation to back up our assumptions.</p><p>Now, we can use causal graph to understand confounder and spurious relationship.</p><h3>Confounder &amp; Spurious Relationship</h3><p><em>Confounders</em>, or <a href="https://www.scribbr.com/methodology/confounding-variables/">confounding variables</a>/factors, is a third variable that influences both the independent variable and the dependent variable. The false relationship between the independent and dependent variables that does not actually exist is therefore called a <a href="https://en.wikipedia.org/wiki/Spurious_relationship"><em>spurious relationship</em></a>.</p><p>Here, we introduce variable C as the sole confounder for independent variable A and dependent variable B. Suppose C causes A and B, then we can get rid of the edge between A and B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FcX0CNPMRwhoAZvhfuBFeA.png" /><figcaption>Image by Author</figcaption></figure><p>However, most of the time, the edge between A and B is not so easy to cross out. Normally, there wouldn’t be a sole confounder. There would be a long list of confounders from C1 to Cn and we can hardly find them all.</p><p>A classic example is that A = ice cream sales and B = crime rates. <a href="https://www.lifehack.org/624604/the-most-common-bias-people-have-that-leads-to-wrong-decisions">Statistics</a> show that ice cream sales are highly correlated with crime rates, but does it mean selling more ice cream causes more crime? Your sanity probably tells you no, it doesn’t. So, what could be the confounder C in this scenario?</p><p>Answer:<em> </em><strong><em>Heat in the hot summer weather</em></strong><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFKWKoFvku2Tc3aGVEPflw.png" /><figcaption>Image by Author</figcaption></figure><p>It is easy to see how heat can cause ice cream sales to rise. As for crime rates, perhaps people are more impulsive when the weather is hot and therefore more likely to commit crimes. We can speculate, but it is hard to prove that. That is why the causal graph is a representation of our assumptions. We cannot say much for certain by observing data without doing experiments. Nevertheless, the causal graphs are simple and useful enough to differentiate key processes of human logic.</p><h3>Example with R</h3><p>Finally, we can start coding. In this <a href="https://github.com/AlisonYao/Violence-Against-Women">project</a>, we investigated the relationship between alcohol consumption and the prevalence of violence against women. The datasets involved here are:</p><ol><li><a href="https://github.com/AlisonYao/Violence-Against-Women/blob/main/Data/prevalence.csv">Prevalence of violence against women</a> from <a href="https://data.oecd.org/inequality/violence-against-women.htm#indicator-chart">2019 OECD study</a></li><li><a href="https://github.com/AlisonYao/Violence-Against-Women/blob/main/Data/alcohol.csv">Alcohol consumption data</a> from <a href="https://data.worldbank.org/indicator/SH.ALC.PCAP.LI">The World Bank</a></li><li><a href="https://github.com/AlisonYao/Violence-Against-Women/blob/main/Data/poverty_cleaned.csv">Poverty headcount data</a> from <a href="https://data.worldbank.org/indicator/SI.POV.NAHC">The World Bank</a></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5295a5f95cd4b21a32e8df5431d74d28/href">https://medium.com/media/5295a5f95cd4b21a32e8df5431d74d28/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4v3QSZjmtxP5UR6dynAc6Q.png" /><figcaption>Image by Author</figcaption></figure><p>The plot is quite strange. We would expect more alcohol consumption to associate with, or even contribute to, a higher prevalence of violence against women, but the slope of the line is negative and indicates the exact opposite.</p><p>To be more precise, we can run a univariate linear regression.</p><pre>reg_uni &lt;- brm(formula = Prevalence ~ Alcohol_pc,                              <br>               data=df,                        <br>               refresh = 0,                        <br>               seed = 123) # stabilize outcome for reproducibility <br>summary(reg_uni)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*Qu7bXeWxkIfi-UvUI__Mxg.png" /><figcaption>Image by Author</figcaption></figure><p>We would expect alcohol to cause more violence against women, but the data shows us otherwise. This led us to question if there might have been a confounding variable causing this spurious relationship.</p><p>After doing some literature review, we chose poverty as our target and used the poverty headcount ratio as the indicator for poverty. This indicator showed the percentage of each country’s population that was living below the national poverty line. We thought that an indicator specific to each country was better than a global indicator because it took into account the different definitions of poverty that each country has. Now, we can use a multilinear regression to see if poverty headcount ratio might be a confounder.</p><pre>reg_multi &lt;- brm(formula = Prevalence ~ Alcohol_pc + <br>                 poverty_headcount_ratio,                  <br>                 data=df,                  <br>                 refresh = 0,                  <br>                 seed = 123) # stabilize outcome for reproducibility <br>summary(reg_multi)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*n1Lk09eos1opWc26pf3Vrw.png" /><figcaption>Image by Author</figcaption></figure><p>This time, our best estimate showed that one liter increase in total alcohol consumption was associated with a 0.96 percentage point decrease in prevalence, with an uncertainty interval ranging from -1.65 to -0.22.</p><p>Compared to the earlier estimate, including poverty headcount ratio reduced the size of the association by roughly a third (1.52 to 0.96). Therefore, <strong>the original association can be partially explained by the inclusion of poverty_headcount_ratio as a control variable.</strong></p><p>To draw a causal graph, we can run the following code.</p><pre>library(dagitty) <br>library(ggdag) <br>vaw_dag &lt;- dagify(Prevalence ~ ph + ac,<br>                  ac ~ ph, <br>                  labels = c(&quot;Prevalence&quot; = &quot;Prevalence&quot;, <br>                             &quot;ph&quot; = &quot;Poverty Headcount&quot;, <br>                             &quot;ac&quot; = &quot;Alcohol Consumption&quot;)                       <br>                  ) <br># ggdag(vaw_dag, text = FALSE, use_labels = &quot;label&quot;) # left graph <br>ggdag(vaw_dag, text = TRUE) # right graph</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phbMLY_C68xX26CaNjyr8w.png" /><figcaption>Image by Author</figcaption></figure><p>Every time you run the code, the graphs are going to be slightly different. I am not fully satisfied with either version. The labels on the left is covering up the arrowhead and the text on the right one is incomplete. You can run a couple of times and try to find the most perfect version.</p><h3>References</h3><p>[1] <a href="https://en.wikipedia.org/wiki/Causal_graph">https://en.wikipedia.org/wiki/Causal_graph</a></p><p>[2] <a href="https://en.wikipedia.org/wiki/Directed_acyclic_graph">https://en.wikipedia.org/wiki/Directed_acyclic_graph</a></p><blockquote><em>All code for this project can be found in this </em><a href="https://github.com/AlisonYao/Violence-Against-Women"><em>GitHub Repo</em></a><em>.</em></blockquote><p>Special thanks to Professor Kubinec for introducing me to causation and my wonderful teammate Oscar for helping me with project implementation.</p><p>Thank you for reading! I hope this has been helpful to you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=242da2a01086" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/linear-regression-for-causal-inference-242da2a01086">Linear Regression for Causal Inference</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bechdel Test: Comparing Female Representation Metrics in Movies]]></title>
            <link>https://medium.com/data-science/bechdel-test-comparing-female-representation-metrics-in-movies-6cbade15010f?source=rss-17016fd04e22------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cbade15010f</guid>
            <category><![CDATA[bechdel-test]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[feminism]]></category>
            <category><![CDATA[data-for-change]]></category>
            <dc:creator><![CDATA[Alison Yuhan Yao]]></dc:creator>
            <pubDate>Thu, 13 Jan 2022 06:14:23 GMT</pubDate>
            <atom:updated>2022-01-14T15:53:50.073Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/data-for-change">Data for Change</a></h4><h4>Collect data using an API, make animated graphs, and bridge the gap between on-screen and off-screen female representation in movies with Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BtuUBuPZo1OjBFET" /><figcaption>Photo by <a href="https://unsplash.com/@jontyson?utm_source=medium&amp;utm_medium=referral">Jon Tyson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Table of Content</h4><p>· <a href="#2595">Data Collection</a><br> ∘ <a href="#26d7">Using an API to fetch data</a><br> ∘ <a href="#f45d">Data Wrangling</a><br> ∘ <a href="#f42f">Dataset Update</a><br>· <a href="#6627">Data Analysis &amp; Visualization</a><br> ∘ <a href="#8ed3">Understanding the Bechdel data</a><br> ∘ <a href="#894f">Comparing on-screen &amp; off-screen metrics</a><br>· <a href="#09c3">Conclusions</a><br>· <a href="#9d19">References &amp; Related Readings</a></p><p>As a big fan of movies and TV shows, I was intrigued when I first learned about the <a href="https://en.wikipedia.org/wiki/Bechdel_test">Bechdel Test</a> in class. It measures the representation of women in fiction by checking 3 criteria:</p><ul><li>The movie has to have at least 2 [named] female characters</li><li>who talk to each other</li><li>about something other than a man.</li></ul><p>This test was invented by Alison Bechdel in 1985, but it is still relevant in the present day. I expected it to be a simple test that all movies should pass, but is that the reality?</p><p>Before knowing what the Bechdel Test is, I would think about metrics such as if the director is a woman or the percentage of female cast members when talking about female representation in movies. These are <strong>off-screen</strong> representation metrics, while the Bechdel Test gives us a guideline for <strong>on-screen</strong> female representation, something that is rather difficult to quantify.</p><p>Therefore, to further investigate this topic and bridge the gap between on-screen and off-screen metrics, I obtained the Bechdel Test data on 9,300+ movies from this amazing website called <a href="https://bechdeltest.com/">Bechdel Test Movie List</a> to answer the following questions:</p><ul><li>How do Bechdel Test scores change over time? Are movies doing better at passing the Bechdel Test 🤞?</li><li>How does the Bechdel Test compare with other benchmarks of off-screen representation?</li></ul><blockquote><em>Check </em><a href="https://www.kaggle.com/alisonyao/movie-bechdel-test-scores"><em>Kaggle</em></a><em> for the dataset. <br>Code in this post can be found in this </em><a href="https://github.com/AlisonYao/HCDS-Bechdel-Test-Final-Project"><em>GitHub repo</em></a><em>.</em></blockquote><h3>Data Collection</h3><p>All credits of the Bechdel Test data go to <a href="https://bechdeltest.com/">Bechdel Test Movie List</a>, which provides a handy API for anyone to retrieve the raw data. The data comes with a CC BY-NC 3.0 license. We’re grateful to <a href="http://bechdeltest.com/">bechdeltest.com</a> for the permission to use the data in this post.</p><h4>Using an API to fetch data</h4><p>The <a href="https://medium.com/r?url=https%3A%2F%2Fbechdeltest.com%2Fapi%2Fv1%2Fdoc">API documentation</a> gives us 4 methods to call the data:</p><ol><li>getMovieByImdbId (returns one movie with 9 columns)</li><li>getMoviesByTitle (returns multiple movies with matching title, 9 columns)</li><li>getAllMovieIds (returns all movies in database, 2 columns)</li><li>getAllMovies (returns all movies in database, 5 columns)</li></ol><p>We can see right away that simply using one method will not give us all the information in the database. A dataframe of all information should probably contain all movies with 9 columns, so what are the missing 3 features from method #4 getAllMovies? Well, let’s check what getAllMovies really get us.</p><pre># import library <br>import pandas as pd <br># get dataframe <br>df = pd.read_json(&#39;http://bechdeltest.com/api/v1/getAllMovies&#39;) <br># check the last 5 rows of the dataframe <br>df.tail() <br># you can check the first 5 rows by running df.head()</pre><pre><em># save dataframe to a csv file<br></em>df.to_csv(&#39;Bechdel.csv&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jFXSdK1O6GPrpYBllq4Rdw.png" /><figcaption>Image by Author</figcaption></figure><p>The movies are added chronologically, so the more recent ones are at the bottom. And we can see that <em>Cruella</em> does not have an imdbid, which is a problem we need to fix later.</p><p>The useful information method #4 getAllMovies gives us are movie title, IMDb id, unique website id (id), Bechdel Test score (rating), and year of release. <strong>The Bechdel test score, or rating, is calculated by checking the 3 criteria.</strong> Since each criterion is built upon the previous one, ie. a movie cannot fulfill criterion #2 if criterion #1 is not met, a score of 0 means a movie does not have 2 female characters. 1 means a movie has 2 female characters but they do not talk to each other. 2 means a movie has 2 women talking but they talk about men. 3 means completely passing the Bechdel Test. So, congrats to <em>Cruella</em>, <em>West Side Story</em>, <em>Every Time a Bell Rings</em>, and <em>Single All The Way</em>!</p><p>Now let’s see what method #1 getMovieByImdbId gives us.</p><pre># Using Single All The Way as an example (imdbid=14315756) pd.read_json(&#39;http://bechdeltest.com/api/v1/getMovieByImdbId?imdbid=14315756&#39;, typ=&#39;series&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Hc8tD0nJiR_WJ5rSo3NSg.png" /><figcaption>Image by Author</figcaption></figure><p>It does not have an index but has 4 additional columns: visible, date of the movie being added to the list, dubious, and submitter id. Visible is always 1 for every movie because only the visible movies are returned by the API call. What is interesting is the <strong>dubious</strong> column. It indicates “whether the submitter considered the rating dubious”. In other words, we cannot trust the ratings of dubious movies, as they are susceptible to modification.</p><p>And this complicates things… dubious is now too important a column to ignore. We may discard the dubious movies, or we may treat dubious as another category. Either way, the df we have now needs a new column — dubious. And that took me an extra 7 hours.</p><h4>Data Wrangling</h4><p>Now that we have the IMDb id of each 9,300+ movies, we can use it to get the full information on each movie, which means we need to call the API thousands of times. The website states that:</p><blockquote><em>Please keep in mind I’m running this site on a shared hosting plan, so if you send lots of queries in a short time, you might get me in trouble. Please be nice and definitely don’t use this data on anything with a lot of traffic.</em></blockquote><p>I don’t want to cause any trouble, so I called the API every few seconds (hence it took me 7 hours). I did experience some timeout errors and unstable internet (that’s my bad), so maybe a few seconds was still too frequent. But thankfully, the website did not crash. For this reason, <strong>I suggest checking out this </strong><a href="https://www.kaggle.com/alisonyao/movie-bechdel-test-scores"><strong>Kaggle database</strong></a><strong> if you want to use the dataset and avoid calling the API again and causing more unnecessary traffic.</strong></p><p>But the code to get the extra 4 columns is here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cda0721ad862c1c5b862d1fe9877bf0/href">https://medium.com/media/9cda0721ad862c1c5b862d1fe9877bf0/href</a></iframe><p>However, we are not done yet. If we check the Bechdel_detailed.csv file, we will see 3 new columns and some NANs.</p><pre>bechdel_detailed_df = pd.read_csv(&#39;Bechdel_detailed.csv&#39;, index_col=0) <br>bechdel_detailed_df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ndB3qA-w62zcLLwWIlwdg.png" /><figcaption>Image by Author</figcaption></figure><p>A lot of dubious are NAN because the website returns null in their API, but there are 9373–9369=4 movies that seems strange. Let’s take a look at them.</p><pre>bechdel_detailed_df[bechdel_detailed_df[&#39;title&#39;].isna()]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*raFn4zAre8kI3G3mPCXjJg.png" /><figcaption>Image by Author</figcaption></figure><p>No surprise here because index 9369 is <em>Cruella</em>, which does not have an imdbid. We expected it to cause problem and now it’s time to fix it. We can go to IMDb and manually get the imdbid. Now, just a bit more data cleaning and we are done.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0be1ff0e7e604bc8ef4027665b6ff748/href">https://medium.com/media/0be1ff0e7e604bc8ef4027665b6ff748/href</a></iframe><p>The current Bechdel_detailed.csv file should look like this. It contains 9,373 movies from year 1874 to 2021.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TiiMSJR59JQcHug7X8E5cw.png" /><figcaption>Image by Author</figcaption></figure><h4>Dataset Update</h4><p>The website is updated quickly and the analysis here is based on the data from Dec. 23, 2021. Please check <a href="https://www.kaggle.com/alisonyao/movie-bechdel-test-scores">Kaggle</a> for the latest dataset (I intend to maintain it quarterly).</p><h3>Data Analysis &amp; Visualization</h3><p>As always, for any dataset, we start from exploratory data analysis (EDA) and visualize the data to get a sense of what we are dealing with.</p><h4>Understanding the Bechdel data</h4><p>Continuing where we left off, let’s first import more libraries and check the basic information of bechdel_detailed_df again.</p><pre># import libraries <br>import numpy as np <br>import matplotlib.pyplot as plt <br>%matplotlib inline <br>from plotnine import * <br>from mizani.formatters import percent_format </pre><pre># rename column because the name rating a little confusing<br>bechdel_detailed_df.rename(columns={&#39;rating&#39;: &#39;bt_score&#39;}, inplace=True)</pre><pre># check null <br>bechdel_detailed_df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_ojeur4akH4Q1WfWuIzcQ.png" /><figcaption>Image by Author</figcaption></figure><p>There are some dubious = NaN in the dataset, but not too many, so we can go ahead and drop them.</p><pre># drop NAN <br>bechdel_detailed_df = bechdel_detailed_df.dropna().reset_index(drop=True)</pre><pre>len(bechdel_detailed_df) # returns 9074</pre><p>Now, we have 9,074 movies in total. We also need to check duplicates and drop the 9 duplicated movies.</p><pre>bechdel_detailed_df.duplicated().sum() # returns 9<br>bechdel_detailed_df.drop_duplicates(inplace=True) <br># reset index<br>bechdel_detailed_df = bechdel_detailed_df.reset_index(drop=True)<br># left with 9,065 movies</pre><p>Okay, we can start to visualize. Since I have been learning R in the past few months (my native language is Python), I have started to love the ggplot2 style, so I chose to use a mixture of matplotlib and plotnine for visualization.</p><p>First, I am curious about the score distribution and percentages in the dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b2e7161123b274d70454b0eaef17eac/href">https://medium.com/media/0b2e7161123b274d70454b0eaef17eac/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1tenqjB9bXkfulwgGkPsYw.png" /><figcaption>Image by Author</figcaption></figure><p>More than half of the movies pass the Bechdel Test, which is quite disappointing considering the Bechdel Test does not seem too difficult to pass. However, fivethirtyeight says that the ~56% passing rate is already higher than expected [1]. They also point out a “feminist-leaning” problem, which means that people subconsciously pick the movies that are more likely to pass the Bechdel Test, because they know in advance that they are going to submit a score to the Bechdel website [1]. Also, it is not difficult to see that most of the movies in the database are popular Hollywood movies, which puts a geolocation restriction to our analysis as well.</p><p>It is important to acknowledge the <strong>biases</strong> in datasets and EDA helps us do that.</p><p>Let’s continue by dealing with dubious movies. Please recall that dubious movie scores are susceptible to changes and we have dropped the rows with dubious = nan, so now we are interested in the movies marked dubious = 1.</p><pre>dubious_count = bechdel_detailed_df[&#39;dubious&#39;].value_counts()</pre><pre>print(&#39;Percentage of dubious movie scores:&#39;, str(&#39;{:.2f}&#39;.format(dubious_count[1.0] / (dubious_count[1.0] + dubious_count[0.0]) * 100))+&#39;%&#39;)</pre><p>Percentage of dubious movie scores: 8.92%</p><p>~9% is not too bad, but I don’t think we should drop the dubious movies right now. Instead, I intend to treat it as a new category at the same level as bt_score = 0, 1, 2 and 3. Let’s create another column called “category” and mark the 5 possibilities:</p><ul><li>Dubious</li><li>0-Fewer than two female characters</li><li>1-Female characters do not talk</li><li>2-Female characters talk about men</li><li>3-Passes Bechdel Test</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/463de895d85edfa432edd4fa56ad9877/href">https://medium.com/media/463de895d85edfa432edd4fa56ad9877/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ORuMlDDocDwrdkScpP-yPw.png" /><figcaption>Image by Author</figcaption></figure><p>Alright, let’s go on to analyze the trend over the years. We can calculate the mean score of each year and visualize in a scatter plot.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f97c2a8f6b4ac8c121bcf90d991bddf/href">https://medium.com/media/2f97c2a8f6b4ac8c121bcf90d991bddf/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJdSK4zn8C0cHBU1lCsaPg.png" /><figcaption>Image by Author</figcaption></figure><p>I added a smooth curve so that it is easier to see the trend. Movies in the early years are performing extremely poorly, but the mean score is improving over time. Recent years have seen an all-time high.</p><p>Is it because the proportion of movies passing the test is increasing? Let’s find out.</p><p>I chose to use an animated pie chart for visualization because it shows the time flow nicely (fitting ~150 years in a bar chart looks terrible). Plus, it’s good to practice something new. And this time, I color-coded the 5 categories.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/695810b1209f9b3a7fa52588264258e6/href">https://medium.com/media/695810b1209f9b3a7fa52588264258e6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*3qJRcZ3ABaDsFwDgz_hHlw.gif" /><figcaption>GIF by Author (Animated graphs can show changes over time very nicely)</figcaption></figure><p>We can see that the early years are all orange, meaning that 0 movies pass the test. But over the years, more green color is popping up, meaning that more movies pass the test. However, the green proportion is unstable, because the interval of 1 year is too small. So, let’s use an interval of 10 years instead. And this time, we can finally fit everything in a bar chart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1803f76a9fb094ebafe528adf87ffa78/href">https://medium.com/media/1803f76a9fb094ebafe528adf87ffa78/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hRUX0QrAsv1ov0dqir9pYA.png" /><figcaption>Image by Author (It’s a percentage stacked bar chart that shows proportion, not a common bar chart that shows frequency, or counts.)</figcaption></figure><p>Dubious movies are in the middle so that the human eyes can better compare the green and the orange proportions. We can see that as the green proportion is getting bigger, the orange proportion is getting lighter. That is, many movies still fail the test, but more are getting 1’s and 2’s instead of 0’s, which shows progress. Yay!</p><p>Now, I want to take some time to emphasize that the terms “more” or “fewer” here are all in terms of proportion, or percentage, or ratio. They do not refer to the pure number, or volume, or quantity of the movies. <em>Comparing numbers is meaningless.</em> Why? Because of the <strong>population effect</strong>, or the <strong>size effect</strong>.</p><p>For example, there might be more movies (in terms of number) passing the Bechdel test in the year 2122 than 2022 simply because the year 2122 has 10 times more movies released than 2022. The proportion may drop, even if the number rises, so numbers alone do not tell us much useful information. Another example I heard recently is that a friend of mine is doing NLP and he found that the negative comments in sentiment analysis tend to be shorter, but the reason could be there are more short comments (in terms of number) on the internet in general, so his conclusion might not be meaningful. This pitfall has the term “population” in it because it is commonly associated with population. China has more births than Japan simply because China has a larger population. This is not interesting. What is interesting is the birth rate, not the birth number. Similarly, we talk about GDP per capita, not GDP as a whole. It is surprising how often we misinterpret the population effect as something meaningful.</p><p>Okay, let’s get back to the analysis. Now that we have a pretty good understanding of the Bechdel data and the general trend over time, let’s compare it with off-screen metrics.</p><h4>Comparing on-screen &amp; off-screen metrics</h4><p>By off-screen metrics of female representation in movies, I mean the female ratios in cast and crew members. To get the ratios, we can use this popular <a href="https://www.kaggle.com/rounakbanik/the-movies-dataset?select=credits.csv">Kaggle dataset</a>. The credits.csv file marks the gender information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QdScyQ_UWeVLv6Cxg6idEw.png" /><figcaption>Image by Author</figcaption></figure><p>To join the Bechdel data with the gender data, we need the links.csv file.</p><pre># import more libraries<br>import ast <br>from collections import defaultdict<br>import seaborn as sns</pre><pre># load the 2 new datasets <br>links_df = pd.read_csv(&#39;./TheMoviesData/links.csv&#39;, index_col=0) <br>credits_df = pd.read_csv(&#39;./TheMoviesData/credits.csv&#39;)<br># there are 37 duplicates in credits_df, but let&#39;s drop them later</pre><pre># merge <br>bechdel_df = pd.merge(bechdel_detailed_df, links_df, left_on=&#39;imdbid&#39;, right_on=&#39;imdbId&#39;, how=&#39;inner&#39;).drop(columns=[&#39;imdbId&#39;]) </pre><pre>bechdel_df = pd.merge(bechdel_df, credits_df, left_on=&#39;tmdbId&#39;, right_on=&#39;id&#39;, how=&#39;inner&#39;).drop(columns=[&#39;imdbid&#39;, &#39;submitterid&#39;, &#39;date&#39;, &#39;visible&#39;, &#39;tmdbId&#39;, &#39;id_x&#39;, &#39;id_y&#39;]) </pre><pre>bechdel_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sx3vGoi_UO421e-Y2cZwsA.png" /><figcaption>Image by Author</figcaption></figure><p>There are some empty values in cast and crew. Let’s calculate the percentage of empty values and see what we should do.</p><pre>count1, count2 = 0, 0 <br>for index, row in bechdel_df.iterrows():<br>     cast_list = ast.literal_eval(row[&#39;cast&#39;])<br>     crew_list = ast.literal_eval(row[&#39;crew&#39;])<br>     if len(cast_list) == 0:<br>         count1 += 1<br>     if len(crew_list) == 0:<br>         count2 += 1 </pre><pre>print(&#39;Empty cast percentage:&#39;, str(&#39;{:.2f}&#39;.format(count1/len(bechdel_df) * 100))+&#39;%&#39;) </pre><pre>print(&#39;Empty crew percentage:&#39;, str(&#39;{:.2f}&#39;.format(count2/len(bechdel_df) * 100))+&#39;%&#39;)</pre><p>Empty cast percentage: 0.41% <br>Empty crew percentage: 0.11%</p><p>This is a very small percentage, so we can go ahead and drop them. Also, we need to drop duplicates.</p><pre>bechdel_df = bechdel_df[(bechdel_df[&#39;cast&#39;] != &#39;[]&#39;) &amp; (bechdel_df[&#39;crew&#39;] != &#39;[]&#39;)].reset_index(drop=True) </pre><pre># check &amp; drop duplicates<br>print(bechdel_df.duplicated().sum()) # returns 9 bechdel_df.drop_duplicates(inplace=True)<br>bechdel_df = bechdel_df.reset_index(drop=True)</pre><p>However, there is another problem of unknown genders in the Kaggle dataset. The original data source of the Kaggle dataset did not keep a detailed record on the gender information. In fact, there are a lot of unknowns.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8771f2786b75ed880529adeab0dee125/href">https://medium.com/media/8771f2786b75ed880529adeab0dee125/href</a></iframe><p>Percentage of unknowns in Cast: 36.29% <br>Percentage of unknowns in Crew: 59.01% <br>Percentage of unknowns in Directing: 39.44% <br>Percentage of unknowns in Writing: 38.91%</p><p>Since there are way too many unknowns, we can fill in the blanks by predicting gender from the first name. The <a href="https://pypi.org/project/gender-guesser/">gender-guesser</a> package is a good choice [2]. This package treats gender as binary (could be a limitation) and tells us if a first name is male/female, or mostly male/female, or unknown/androgynous. For example, my name Chinese name Yuhan can belong to any gender and the package would tell you my gender is unknown, but you can tell from my English name Alison that I’m female.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/571faf714ac9e7d1f084bb3de85a2449/href">https://medium.com/media/571faf714ac9e7d1f084bb3de85a2449/href</a></iframe><p>Percentage of unknowns in Cast: 4.78% <br>Percentage of unknowns in Crew: 4.99% <br>Percentage of unknowns in Directing: 4.21% <br>Percentage of unknowns in Writing: 4.99%</p><p>The percentages of unknown have dropped significantly, which is great! Now, it’s time to decide which metrics we want. The female ratios that I think are of importance are:</p><ul><li>Cast female ratio</li><li>Crew female ratio</li><li>Directing female ratio (there are director, assistant director, etc)</li><li>Writer female ratio</li></ul><p>So, we can add a new column by running:</p><pre>bechdel_df[&#39;cast_female_ratio&#39;] = gender_df[&#39;cast_female_num&#39;] / gender_df[&#39;cast_total_num&#39;] </pre><pre>bechdel_df[&#39;crew_female_ratio&#39;] = gender_df[&#39;crew_female_num&#39;] / gender_df[&#39;crew_total_num&#39;] </pre><pre>bechdel_df[&#39;directing_female_ratio&#39;] = gender_df[&#39;Directing_female&#39;] / gender_df[&#39;Directing_total&#39;] </pre><pre>bechdel_df[&#39;writing_female_ratio&#39;] = gender_df[&#39;Writing_female&#39;] / gender_df[&#39;Writing_total&#39;] </pre><pre>bechdel_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IarrUup3bhTPr0ta4eCpdw.png" /><figcaption>Image by Author</figcaption></figure><p>There are some NaN in the writing_female_ratio column because 0/0 is NaN. If the total number of writers is 0 (the denominator), then the records of these movies are probably incomplete and not useful to us. Let’s drop the null. Also, this time, we cannot consider the dubious anymore when comparing metrics, because dubious scores are not reliable.</p><pre>bechdel_df_no_nan = bechdel_df.dropna().reset_index(drop=True) <br>bechdel_df_no_nan_no_dubious = bechdel_df_no_nan[bechdel_df_no_nan[&#39;dubious&#39;]==0].reset_index(drop=True)</pre><p>Now we can check the mean Bechdel score for each metric.</p><pre>bechdel_df_no_nan_no_dubious.groupby(&#39;bt_score&#39;).mean()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2MP5LJM0uX0JIl2GgXGsDg.png" /><figcaption>Image by Author</figcaption></figure><p>By eyeballing the means, it seems that a higher female ratio is correlated with a higher bt_score. To visualize the means and their uncertainty intervals, we can use error bars to compare the metrics with the Bechdel score. For cast female ratio vs Bechdel score, we have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a56ad80eee1cee6c450fd2e8daf2535/href">https://medium.com/media/3a56ad80eee1cee6c450fd2e8daf2535/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQ6pFmuqO2g4S3UxOZDcCQ.png" /><figcaption>Image by Author</figcaption></figure><p>The error bars do not overlap, which indicates that the means of the 4 groups where bt_score = 0, 1, 2 and 3 are statistically different. And the positive correlation is very obvious.</p><p>By changing the column name from cast_female_ratio to others, we can plot all 4 graphs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1tBx-7BxJCTxoylQIMxlMw.png" /><figcaption>Image by Author</figcaption></figure><p>Groups failing the Bechdel test are not always different from each other, but they all have a lower female ratio compared to movies passing the test. The positive correlation between on-screen and off-screen metrics is quite salient. That is, the higher percentage of female members in the cast and crew, the more likely the movie is to pass the Bechdel Test, and vice versa. <strong>More female on set can indeed translate into a better female representation on screen.</strong></p><p>And that’s the end of this fun analysis.</p><h3>Conclusions</h3><p>In this article, we have talked about:</p><ul><li>how to use an API to collect data</li><li>how to make an animated pie chart</li><li>what population effect/size effect is</li></ul><p>We have answered these questions:</p><ol><li>How do Bechdel Test scores change over time? Are movies doing better at passing the Bechdel Test?</li></ol><blockquote>Yes! The mean Bechdel score and the percentage of passing movie are rising. For the movies failing the Bechdel Test, more are closer to passing the test now.</blockquote><p>2. How does the Bechdel Test compare with other benchmarks of off-screen representation?</p><blockquote>There is a positive correlation between the Bechdel score and the female ratios in cast, crew, directing and writing. More females in the workplace can translate into a more feminist output.</blockquote><p>The quantitative work here focuses more on data acquisition, data analysis, and visualization because this project is originally designed to explore the human-centeredness in Data Science. What’s important is learning to <strong>ask the right questions, identify biases and limitations, and be aware of why each decision was made on the dataset</strong>. I don’t think it makes much sense to, for example, predict the Bechdel score based on gender ratios and involve Machine Learning models in this project. Nor do I want to overcomplicate things by introducing statistical concepts like Tukey’s HSD for pairwise comparison if the visualization already says it all. But you are most welcome to do so if it suits your need.</p><p>My wonderful teammates <strong>JB</strong>, <strong>Min Jie</strong> and <strong>Fatima</strong> went through the comments on the Bechdel website and did the qualitative analysis that made the project whole. Please check <a href="https://github.com/AlisonYao/HCDS-Bechdel-Test-Final-Project/blob/main/Project%20Report%20%26%20Presentation/HCDS%20A4%20Report.pdf">here</a> if you are interested!</p><blockquote><em>Code in this post can be found in this </em><a href="https://github.com/AlisonYao/HCDS-Bechdel-Test-Final-Project"><em>GitHub repo</em></a><em>. Check </em><a href="https://www.kaggle.com/alisonyao/movie-bechdel-test-scores"><em>Kaggle</em></a><em> for dataset.</em></blockquote><h3>References &amp; Related Readings</h3><p>Here are some articles that I found extremely helpful and inspirational when working on this project. They explore relationship between the Bechdel scores and other interesting aspects such as rating, budget, etc. Enjoy the fun read!</p><p>[1] <a href="https://fivethirtyeight.com/features/the-dollar-and-cents-case-against-hollywoods-exclusion-of-women/">https://fivethirtyeight.com/features/the-dollar-and-cents-case-against-hollywoods-exclusion-of-women/</a><br>[2] <a href="https://towardsdatascience.com/the-bechdel-test-analyzing-gender-disparity-in-hollywood-263cd4bcd9d">https://towardsdatascience.com/the-bechdel-test-analyzing-gender-disparity-in-hollywood-263cd4bcd9d</a></p><p>Special thanks to TDS editor <a href="https://medium.com/u/e6ad8abedec9">Ben Huberman</a> who is so incredibly helpful with getting the data license permission and guiding me through every step of publishing this article.</p><p>Thank you for reading! I hope this has been helpful to you. Please leave a comment if you have any feedback :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cbade15010f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/bechdel-test-comparing-female-representation-metrics-in-movies-6cbade15010f">Bechdel Test: Comparing Female Representation Metrics in Movies</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Time I Coded a Biased Algorithm]]></title>
            <link>https://medium.com/data-science/the-time-i-coded-a-biased-algorithm-4ae4fba62bf6?source=rss-17016fd04e22------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ae4fba62bf6</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[bias]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ethics]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Alison Yuhan Yao]]></dc:creator>
            <pubDate>Sat, 18 Dec 2021 23:12:16 GMT</pubDate>
            <atom:updated>2021-12-18T23:12:16.195Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Data Science ethical issues that haunt me at night and keep me responsible in practice</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UbVhe_G0D2kivZ56" /><figcaption>Photo by <a href="https://unsplash.com/@madesolobymariah?utm_source=medium&amp;utm_medium=referral">Mariah Krafft</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I often see people talking about AI and Data Science biases and solutions from an objective perspective, while biases are highly subjective. Every time the model implementor makes a decision to include or exclude something, potential biases may arise. Therefore, I hope to tell a story from the perspective of a Data Science practitioner.</p><p>I recently confirmed that I am free to share a personal story from <a href="https://medium.com/codex/ds-undergrad-journey-part3-my-internship-research-experience-907aaa57c497">my past internship</a>. Sad to admit, but I have accidentally designed and coded a Computer Vision algorithm that later turned out to be biased.</p><h3>Background</h3><p>I was working at a Chinese IT company as an AI intern and one of the clients was an international wedding photography studio. I was quite surprised at this unusual pair because I did not expect photographers to need AI. But you see, it takes little effort to take thousands of photos at a wedding. One can keep pressing the shutter on the camera and there guarantees a perfect photo somewhere that captures the perfect moment.</p><p>But that’s where it gets tricky. A wedding photo album cannot fit this many photos. It is very <strong>time-consuming and labor-heavy</strong> to go through so many photos for so many weddings manually, so my job was to <strong>automate the photo selection process</strong> as much as I could.</p><p>According to the client, a wedding photo album typically features 3 types of photos:</p><ul><li>the ones with only the bride or the groom (1 person),</li><li>the ones with both the bride and the groom (2 people), and</li><li>group photos of more than 2 people.</li></ul><p>Unfortunately, algorithms could not select the one perfect photo for each category because computers have no aesthetic sense, but they could get rid of the absolutely useless photos. For example, we do not need photos where nobody is in the frame. So, the computer can help us narrow down to a couple hundred, instead of a couple thousand photos, to lighten the workload.</p><p>So how do we do this?</p><h3>Implementation</h3><h4>Data</h4><p>I needed to start with a lot of image data. Wedding photos have high resolutions, so I obtained a few thousand photos from around 20 couples on my computer that took up all of my storage space.</p><h4>Algorithm Design</h4><p>To process image data, Computer Vision algorithms and deep learning are the way to go. To be more specific, since I was classifying images based on the number of people in them, I needed an object detection algorithm to count occurrences. I tried counting human torsos and counting faces. Face detection did not work too well when people are not facing the camera.</p><p>If I counted 3 people, the image would definitely be a group photo. If I counted 2, the photo was very likely to be a couple photo. The occasions where the two people are not the couple is quite rare. When I counted 1, I also implemented a gender classification so that I could separate the bride’s photos from the groom’s. The prototype worked well on the test set I had and we were ready for a larger-scale test for our client.</p><p>Now, do you sense anything wrong? Because if you do, you would have been a better Data Scientist than I was. As I said, our client was an international wedding photo studio, but <strong>we failed to consider the cases of same-sex couples</strong>.</p><p>The algorithm had a glitch when it encountered any couple of the same gender. Since it ran a gender classification to distinguish the bride from the groom, it malfunctioned when encountering 2 brides or 2 grooms.</p><h4>Algorithm Re-design</h4><p>To resolve this issue, I used facial recognition instead. With facial recognition, I could command the model to check who exactly belongs to the newly-wed couple and increase the accuracy to a whole new level. Since facial recognition does not involve gender, which is not a simple binary concept, I thought it would have been effective for more cases other than same-sex couples as well.</p><p>But the inconvenient thing about facial recognition is that someone needed to manually identify who the couples are and log their faces into a database. If I did not have their info in the database, facial recognition would fail. In a way, facial recognition re-introduced human elements into what was supposed to be automated. Our client didn’t think this was good enough to cut significant costs and did not follow through.</p><h3>Reflection</h3><p>It has been one and a half years since that internship, but I still think about this project very often. I wonder why I did not think about more cases outside of my test data, why my team did not realize the potential bias in my design either, and what I could have done differently to avoid the bias from the get-go.</p><blockquote>“In order to train AI to benefit humanity, the creators of AI need to represent humanities.” — — Fei-Fei Li</blockquote><p>I am scared to say this, but I think if I were to do this again, I could have made the exact same mistake in that situation and coded the biased algorithm all over again.</p><p>Sometimes, biases and mistakes are made because of unconscious human choices. And I was in a homogeneous team where everyone else’s brain was wired the same way as mine. Even though I did briefly consider facial recognition instead of gender classification when I first designed my model, I discarded the idea of the more complex facial recognition due to the costs of human labor. But in the end, it turned out that human involvement was essential. After I tried to rectify the problem, it was very difficult to actually automate everything. Humans are always closely intertwined with algorithm implementation. Sometimes the ramification of automation is simply not worth it.</p><p>Moreover, I believe Data Science and AI will benefit hugely from a diverse team of practitioners. It is impossible for any single Data Scientist to think the way his/her users think and feel what his/her user feel, but together, different perspectives from different minds stand a better chance.</p><p>This experience has kept me extra wary about every single decision in my future Data Science implementation. I truly hope that you can take away something from it too.</p><p>Thank you for reading! I hope this has been helpful to you.</p><p>PS: I would have used a better image for this blog given the context of this blog, but I could not give away the big twist too early on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ae4fba62bf6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-time-i-coded-a-biased-algorithm-4ae4fba62bf6">The Time I Coded a Biased Algorithm</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 ways to Increase Statistical Power]]></title>
            <link>https://medium.com/data-science/5-ways-to-increase-statistical-power-377c00dd0214?source=rss-17016fd04e22------2</link>
            <guid isPermaLink="false">https://medium.com/p/377c00dd0214</guid>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[statistical-power]]></category>
            <category><![CDATA[power-analysis]]></category>
            <category><![CDATA[ab-testing]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Alison Yuhan Yao]]></dc:creator>
            <pubDate>Mon, 29 Nov 2021 20:02:43 GMT</pubDate>
            <atom:updated>2021-12-02T10:02:07.699Z</atom:updated>
            <content:encoded><![CDATA[<h4>Statistical Power in A/B testing visualized</h4><p>In Data Science, we often need to run A/B tests and interpret the results using statistical power. In the blog, I will explain what power is and how to increase power using visualization. And I emphasize that these methods have nothing to do with p-hacking.</p><p>Before we start, I’m assuming you have some basic knowledge about:</p><ol><li><a href="https://en.wikipedia.org/wiki/Statistical_hypothesis_testing">Hypothesis Testing</a> (p-value)</li><li><a href="https://en.wikipedia.org/wiki/Type_I_and_type_II_errors">Type I and Type II errors, or false negative and false positive</a></li></ol><h3>What is Power</h3><p>In a binary hypothesis test, either the null hypothesis H0 is true, or the alternative hypothesis HA is true. Typically, we set the null as not having any effect or things staying the same, such as two means being the same (mu1 = mu2). And we set the alternative hypothesis as having some sort of effect or things change after you introduce a variable into the experiment, such as two means are not the same (mu1 ≠ mu2).</p><p>And for us testers, we don’t want H0 to be true. We don’t want to go through all the trouble implementing tests only to find out the variables we introduced are useless. Instead, we care about HA being true because we want to find significant variables, so we need to care about the probability that we are right: the probability that we reject H0 and therefore accept HA when HA is indeed true. And that is called statistical power, your ability to detect an effect when it is there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dkKvi9NdJloUdna_01wEyQ.png" /><figcaption>Image by Author</figcaption></figure><p>In this graph, we visualize power in darker green. In a hypothesis test, we always determine the alpha value beforehand, which is usually set at 0.05, so the Type I error rate is set in stone before we even begin the test. Then, we can calculate the minimum critical value we need to reject H0. We can draw a line from the null hypothesis distribution down to the alternative hypothesis distribution and separate the area under curve into two pieces. If our calculated t or z value falls on the left of the dashed line, we fail to reject H0 when HA is true and we make a Type II error. If the calculated value falls on the right, we reject H0 when HA is true and we make the right call. Therefore, the area on the right of the curve is our power.</p><p>Please note that we only talk about power when HA is true. If unfortunately, H0 is true and there is no effect whatsoever, no amount of power is going to help us. As you can see in the graph, when H0 is true, we deal with alpha only. But in real life, we have no idea if H0 or HA is true and we cannot change the ground truth. All we can control is to reject or not reject H0 while hoping HA is true. Despite that, we still want to increase our statistical power, so that we have the best chance of detecting an effect when it is indeed there.</p><h3>How to Increase Power</h3><p>Let’s take a closer look at the visualization and understand what kind of information we know in the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*9JmIG7tKACTmWmGNZ0Kacg.png" /><figcaption>Image by Author</figcaption></figure><p>We know before start: (1) alpha level, (2) whether we use a 1-tailed or a 2-tailed test, (3) shape of the distribution (t or z). After doing the test, we know: (4) sample size, (5) means of the distributions M0 and MA (or the difference between them), (6) standard deviation of the distributions and therefore (7) standard error (SE) and (8) min critical value, aka the value of dashed line X (using M0, min critical value and SE).</p><p>An <strong>example</strong> can be testing if doing every SAT question in a practice book actually makes a difference. The population mean for SAT is M0 = 500 and population SD = 100. Since we know the population mean, we can use a z distribution. We can set the test as 2-tailed (alpha = 0.05) as usual. Now, we do our test and check the test data. Let’s say N = 100, mean for the HA distribution is MA = 530. Since we assume the two distributions are the same, we can calculate that SE = SD/√N = 100/√100 = 10 and therefore X = z_crit * SE + M0 = 1.96 (we know that from a z table) * 10 + 500 = 519.6. Okay, now we are finally ready to calculate the power. The critical value for HA distribution is z_crit2 = (X-MA )/SE = (519.6-530)/10 = -1.04. We can check the <a href="https://www.dummies.com/wp-content/uploads/451654.image0.jpg">z table</a> and see that the corresponding p(x ≤ -1.04) = 0.1492, so the power is 1-0.1492 = 0.8508.</p><p>Okay, now the big question. How do we increase power?</p><p>I believe it’s easier to <strong>think visually</strong>. How would you increase the area in green? We can shift the dashed line (method 0 &amp; 1), move the mean MA (method 2), or change the shape of the distribution (method 3–5).</p><h4>0. Raise significance level alpha (the WRONG way)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*fgWZGQf_Twb2u7-HjXEHIQ.gif" /><figcaption>GIF by Author</figcaption></figure><p>Keeping everything else in place, one straightforward method is moving the dashed line to the left. By increasing alpha or switching from a 2-tailed test to a 1-tailed test, we can decrease the min critical value X.</p><p>Easy peasy, but one big <strong>caveat</strong> is that increasing alpha is going to result in a higher probability of making a type I error, so we never tamper with the value of alpha.</p><h4>1. Switch from a 2-tailed test to a 1-tailed test</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*cL2a-aqT7_a0MAZcVUb86Q.gif" /><figcaption>GIF by Author</figcaption></figure><p>Similarly, switching from a 2-tailed test to a 1-tailed test can move the dashed line to the left. In a 2-tailed test, the critical p value for each tail is half of alpha, while the critical p equals alpha in a 1-tailed test.</p><p>Whether we use a 2-tailed or a 1-tailed test depends on test design and is set before running the experiment, so we need to keep in mind from the beginning to favor a 1-tailed test.</p><h4>2. Increase mean difference</h4><p>Another way is to increase the difference between the two means. Since the H0 distribution is fixed because the null hypothesis generally doesn’t change, we can only hope that the HA distribution can shift to the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*cfFd6EOaZIEae8fdQin5tg.gif" /><figcaption>GIF by Author</figcaption></figure><p>However, we cannot manually achieve that. We need to report the distribution we get from the test data as it is (otherwise, it is data manipulation!). But this quantifies why we like a bigger mean difference, in that it gives us more power.</p><p>Special Note: <br>Mean difference is one type of effect size, so we can say increasing the effect size can increase power.</p><h4>3. Use z distribution instead of t distribution</h4><p>Starting from this method, we focus on modifying the shape of the distributions. Using a z distribution will make it easier to reach statistical significance. Why?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*RpQFm6HZDThA4Hrntb7LbA.gif" /><figcaption>GIF by Author</figcaption></figure><p>Because a z distribution has a larger kurtosis (z is taller than t distribution) and has thinner tails. By changing the shape, X decreases as well, so the two effects increase power. In the previous example of the SAT score, using z distribution is appropriate because we know the population mean. Although this does not happen often in real life, we can use z to approximate a t distribution when the sample size is large.</p><p>This change in shape is not going to be very significant though. I exaggerated a bit in the GIF so that it is easier to see.</p><h4>4. Decrease standard deviation</h4><p>Another method to modify the shape of the distribution is to reduce SE by decreasing SD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*G-KJaRJ3AMfTS--LeJtJHg.gif" /><figcaption>GIF by Author</figcaption></figure><p>We can use more precise measurements like asking clear questions instead of vague ones in user feedback surveys. That way, our data is going to have less error and less noise.</p><p>Also, we can try to run a <a href="http://mlwiki.org/index.php/Paired_t-test">paired samples t-test</a> if it applies. The gist of why it works is that paired groups have a higher correlation and the difference in scores between paired samples are smaller.</p><h4>5. Increase sample size (the most practical way)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*q0WMA_Xp9gtF5tIWBesABA.gif" /><figcaption>GIF by Author</figcaption></figure><p>Finally, the one method we can always rely on is increasing sample size. If SD remains the same, an bigger sample size N increases the denominator, then SE will decrease.</p><p>This is also the most practical way in real business scenarios. It is much easier to collect data from more users or send out more surveys than following the methods listed above.</p><h3>This is not p-hacking</h3><p>If your first thought of reading this blog is p-hacking, congratulations! You are a well-trained statistics practitioner aware of experimental ethics.</p><p>Indeed, the word “increase” gives us the illusion that we are in control of the experiment outcome, while in fact we are not. Method (2) increase mean difference, for example, is outside of our control, but I think it is still great to understand the mechanism of why a bigger mean difference lead to a larger power. So I put it here, as do <a href="https://netflixtechblog.com/interpreting-a-b-test-results-false-negatives-and-power-6943995cf3a8">other</a> <a href="https://support.minitab.com/en-us/minitab/19/help-and-how-to/statistics/power-and-sample-size/supporting-topics/increase-power/">posts</a>.</p><p>Although we cannot control the test data, <strong>we can control the experimental design</strong>. Methods 0, 1, 3, 4 and 5 are all pre-determined <strong>before</strong> we conduct the tests and see the test data. We never ever manipulate test data!</p><p>For example, let’s talk about (5) increasing sample size. Do we increase sample size during or after experiments? No! We calculate the sample size in advance based on a desired power (eg: power=0.85). If N=50, then let’s get 50 people, conduct the experiment, check the test data and report the p-value as it is.</p><p>If I were to p-hack, I will first check my p-value = 0.053 after getting 50 people. Oh no. p&gt; 0.05, so close. What do I do? I increase the sample size after conducting the test and find another 2 participants. I check my p-value again. Now p = 0.049 and I stop everything and report that I have found an effect. This is very wrong! If I check my p-value every time I add a new participant, anything has the probability of getting a p &lt; 0.05 and I will always find an effect.</p><p>Therefore, the meaning of increasing sample size is using N=50 instead of 20 or 40 <strong>before</strong> conducting the test. The same applies to methods 1, 3 and 4.</p><p>It is important to know that there is more than one way to increase statistical power because sometimes increasing sample size is simply unaffordable. Speaking from the perspective of a university student, if my fundings have been approved and all I can afford is 50 test subjects, I will have to resort to a smarter experimental design in other ways to increase statistical power.</p><p>(This section was added 2 days after publishing the original blog. I see some confusion in the comment section, so hopefully this is clearer.)</p><h3>Conclusion</h3><p>In this post, we talked about what statistical power is using visualization, went through an example to understand the graph better, and talked about 5 ways (6 ways really) to increase power:</p><ul><li>Raise significance level alpha (the WRONG way)</li><li>Switch from a 2-tailed test to a 1-tailed test</li><li>Increase mean difference</li><li>Use z distribution instead of t distribution</li><li>Decrease standard deviation (by using precise measurements &amp; paired samples t-test)</li><li>Increase sample size (the most practical way)</li></ul><p>Thank you for reading! I hope this blog has been helpful to you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=377c00dd0214" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/5-ways-to-increase-statistical-power-377c00dd0214">5 ways to Increase Statistical Power</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>