<?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 Dushyant Mahajan on Medium]]></title>
        <description><![CDATA[Stories by Dushyant Mahajan on Medium]]></description>
        <link>https://medium.com/@dummahajan?source=rss-46f5fe7d5425------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*H_ZpjVA5Bf1VS7SdFceFEA@2x.jpeg</url>
            <title>Stories by Dushyant Mahajan on Medium</title>
            <link>https://medium.com/@dummahajan?source=rss-46f5fe7d5425------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:24:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dummahajan/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[The Blueprint to Autonomous AI Systems: Agentic Design Patterns Explained]]></title>
            <link>https://medium.com/@dummahajan/the-blueprint-to-autonomous-ai-systems-agentic-design-patterns-explained-10877627713a?source=rss-46f5fe7d5425------2</link>
            <guid isPermaLink="false">https://medium.com/p/10877627713a</guid>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Dushyant Mahajan]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 23:43:00 GMT</pubDate>
            <atom:updated>2025-01-12T23:43:00.778Z</atom:updated>
            <content:encoded><![CDATA[<h4>Design Smarter AI Systems That Plan, Collaborate, and Deliver</h4><p>LLMs are still far from making complex decisions, they easily hallucinate and this cannot be avoided. However, LLMs are quite consistent when making very simple decisions. Hence, to overcome these weaknesses we define Agents that help break down complex tasks efficiently into smaller specific objectives. When these smaller objectives are combined along with the collaboration of multiple agents they create a symphony of intelligence, orchestrating agents, tools and workflows into seamless systems that think, plan and act.</p><p>An AI agent is like a smart digital assistant that needs certain key features to function. Here’s are the features that AI agents have:</p><ul><li><strong>Awareness of Its Environment:</strong> Just like humans use their senses, an AI agent can take in information from its surroundings — mainly through text and images.</li><li><strong>Memory and Learning Ability:</strong> The agent doesn’t just work with what it was originally programmed to know. It maintains a memory bank that combines its base knowledge with new information it picks up along the way.</li><li><strong>Clear Purpose and Goals:</strong> Every AI agent has specific objectives it works toward — whether that’s helping with writing, managing schedules, or solving problems. These goals guide every decision it makes.</li><li><strong>Smart Decision-Making Brain:</strong> At its core, it uses a large language model (LLM). This helps it process information and make intelligent decisions about how to help you best.</li><li><strong>Independent Decision Making:</strong> Unlike simple programs that just follow fixed rules, an AI agent can evaluate situations and choose the best course of action based on what it knows and what it’s trying to achieve.</li><li><strong>Real-World Impact:</strong> The agent’s actions create actual changes in its environment, whether that’s generating new content, providing useful information, or collaborating with other AI tools to complete tasks.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VeuZvh0-8C_tpO_v.png" /></figure><p>In an Agentic workflow, a large language model (LLM) with general-purpose capabilities serves as the main brain, agent module, or coordinator of the system. The Agent component is activated using a prompt template that entails important details about how the agent will operate, and the tools it will have access to (along with tool details).</p><p>While not mandatory, an agent can be profiled or be assigned a persona to define its role. This profiling information is typically written in the prompt which can include specific details like role details, personality, social information, and other demographic information.</p><p>Here is an example of how an agent is defined using AutoGen.</p><pre>cathy = ConversableAgent(<br>    &quot;cathy&quot;,<br>    system_message=&quot;Your name is Cathy and you are a part of a duo of comedians.&quot;,<br>    llm_config={&quot;config_list&quot;: [{&quot;model&quot;: &quot;gpt-4&quot;, &quot;temperature&quot;: 0.9, &quot;api_key&quot;: os.environ.get(&quot;OPENAI_API_KEY&quot;)}]},<br>    human_input_mode=&quot;NEVER&quot;,  # Never ask for human input.<br>)<br><br>joe = ConversableAgent(<br>    &quot;joe&quot;,<br>    system_message=&quot;Your name is Joe and you are a part of a duo of comedians.&quot;,<br>    llm_config={&quot;config_list&quot;: [{&quot;model&quot;: &quot;gpt-4&quot;, &quot;temperature&quot;: 0.7, &quot;api_key&quot;: os.environ.get(&quot;OPENAI_API_KEY&quot;)}]},<br>    human_input_mode=&quot;NEVER&quot;,  # Never ask for human input.<br>)</pre><p>To build better Agentic systems the design paradigms play a major role in effectively creating agent strategies, the design flows and making the systems purpose-driven. In this blog, I am going to dive deep and explore the various agentic design patterns.</p><h4>What are Agentic Design Patterns?</h4><p>At the core, Agentic Design Patterns help structure the AI agents to perform tasks, make decisions, and communicate with other tools in a more human-like and autonomous manner, ultimately creating teams that can help build dependable applications. Each design pattern empowers the LLMs to behave more autonomously and effectively.</p><h4>Why use Agentic Design Patterns?</h4><p>Agentic Design patterns help us overcome the AI systems design challenges of building <strong>scalable</strong> and <strong>adaptable </strong>systems.</p><p>Using design patterns one can:</p><ul><li>Build <strong>collaborative</strong> agents to share context, divide tasks and use tools to reduce redundancies and maximizing outcomes.</li><li>Create reusable templates that provide <strong>streamlined architecture</strong> for managing multiple agents, tools and workflows.</li><li><strong>Scale </strong>the modular workflows seamlessly with growth in the demand.</li><li><strong>Adapt</strong> to new tools, data or goals to update the current workflows dynamically without changing the complete systems.</li></ul><h4>4 Key Agentic Design Patterns</h4><h3><strong>1. Reflection pattern</strong></h3><p>A lot of times while prompting LLMs like ChatGPT, you may receive unsatisfactory output, this output can be improved using critical feedback for the LLM. Reflection pattern emphasizes on automating this feedback loop and reflecting on the outputs generated by the LLM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r-4cSoUdGmLJZYHnfe12pg.png" /><figcaption>Source: <a href="https://www.analyticsvidhya.com/blog/2024/10/agentic-design-patterns/#h-frequently-asked-questions">Blog</a> from Analytics Vidhya</figcaption></figure><p>To implement reflection pattern we can use two different agents, one that generates good outputs and other that can give constructive criticism for the outputs generated by the first agent. This conversation between two agents can drastically improve the responses generated by the LLMs. (Based on the studies form <a href="https://arxiv.org/abs/2303.17651">Madaan et al. (2023)</a>, <a href="https://arxiv.org/abs/2305.11738">Gou et al. (2024)</a>.)</p><h4>Design Flow</h4><ol><li><strong>Action:</strong> Agent one performs an action and generates output.</li><li><strong>Reflection:</strong> The output is fed as input to another agent which criticizes the output based on predefined metrics or goals</li><li><strong>Refinement: </strong>The feedback from the second agent is fed into the first agent, the agent then generates new refined output based on the reflection.</li></ol><h3>2. Tool Use Pattern</h3><p>When working with LLMs, their capabilities can be significantly enhanced by giving them access to external tools and APIs. The Tool Use pattern focuses on enabling LLMs to effectively use these tools to accomplish complex tasks that would be impossible with the LLM alone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NudBL7nfqLBcQhcrJvvalw.png" /><figcaption>Source: <a href="https://www.analyticsvidhya.com/blog/2024/10/agentic-design-patterns/#h-frequently-asked-questions">Blog</a> from Analytics Vidhya</figcaption></figure><p>Based on research from papers like <a href="https://arxiv.org/abs/2401.17464">Gao et al. (2024)</a> and <a href="https://arxiv.org/abs/2305.15334">Patil et al. (2023)</a>, integrating tools with LLMs can bridge the gap between language understanding and real-world actions. The LLM acts as a coordinator, deciding when and how to use different tools to achieve the desired outcome. Examples of tools can be Search APIs like Tavily, Claude 3.5 Sonnet Computer Use, a code executor and many more.</p><h4>Design Flow:</h4><ol><li><strong>Tool Selection:</strong> Agent analyzes the task and determines which tools are needed</li><li><strong>Tool Execution:</strong> Agent uses the selected tools with appropriate parameters</li><li><strong>Result Integration:</strong> Agent processes tool outputs and incorporates them into its response</li></ol><h3>3. Planning Agents Pattern</h3><p>Complex tasks often require breaking down problems into smaller, manageable steps. The Planning pattern enables LLMs to create and execute structured plans rather than trying to solve everything at once. Studies (<a href="https://arxiv.org/pdf/2402.02716">Huang et al. 2024</a>) show that agents with planning capabilities perform significantly better on complex, multi-step tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qtxfx5-v--34NEvIL1aESw.png" /><figcaption>Source: <a href="https://www.analyticsvidhya.com/blog/2024/10/agentic-design-patterns/#h-frequently-asked-questions">Blog</a> from Analytics Vidhya</figcaption></figure><p>For example, imagine you want an agent to analyze a company’s customer reviews and create a visually appealing summary report. The task would be decomposed into distinct steps: (i) analyze sentiment and key themes from the reviews, and (ii) generate data visualizations of the findings. An LLM might be prompted to specify a plan by outputting a string like</p><pre>{tool: sentiment-analyzer, input: reviews.csv, output: sentiment_data} <br>{tool: theme-extractor, input: reviews.csv, output: key_themes} <br>{tool: data-viz, input: [sentiment_data, key_themes], output: final_report.pdf}</pre><p>The above structured output specifies what steps to take, then triggers the relevant functions that can perform the individuals tasks. The planning helps the LLM to handle complex tasks by breaking them down and executing them according to a plan.</p><h4>Design Flow:</h4><ol><li><strong>Task Analysis:</strong> The agent breaks down the main task received as input from the user into subtasks</li><li><strong>Plan Creation:</strong> An agent creates a structured sequence of steps to be executed, required tools and expected outputs for each step</li><li><strong>Execution &amp; Monitoring:</strong> Agents follows the plan while adapting to new information</li></ol><h3>4. Multi agent Collaboration</h3><p>Sometimes a single agent isn’t enough to handle complex tasks effectively. The Multi-agent Collaboration pattern involves multiple specialized agents working together, each bringing their unique capabilities to solve a problem. The work by <a href="https://arxiv.org/abs/2308.08155">Wu et al. (2023)</a> and <a href="https://arxiv.org/abs/2308.00352">Hong et al. (2023)</a> demonstrates how multiple agents can achieve better results than a single agent working alone.</p><p>There are several types of multi-agent patterns:</p><ol><li><strong>Collaborative Agents</strong>: Multiple agents work together on different parts of a task, sharing progress and building toward a unified result. Each agent may specialize in a different domain.</li><li><strong>Supervised Agents</strong>: A central supervisor agent manages other agents, coordinating their activities and verifying results to ensure quality.</li><li><strong>Hierarchical Teams</strong>: A structured system where higher-level agents oversee lower-level agents, with decision-making cascaded through levels to accomplish complex tasks.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mI8rhQSqEScvaq51Qj_s1Q.png" /><figcaption>Source: <a href="https://www.analyticsvidhya.com/blog/2024/10/agentic-design-patterns/#h-frequently-asked-questions">Blog</a> from Analytics Vidhya</figcaption></figure><h4>Design Flow:</h4><ol><li><strong>Task Analysis &amp; Planning: </strong>The agent starts by analyzing the user’s request and available tools and agents, then creates a structured sequence of steps needed to complete the task. It’s like a project manager creating a detailed roadmap before starting work.</li><li><strong>Task Generation &amp; Decomposition: </strong>The agent breaks down the complex task into smaller, manageable pieces and assigns specific tools or functions to each step. In this step complex tasks are turned into a series of smaller, actionable tasks.</li><li><strong>Task Execution: </strong>The agent works through each subtask in sequence, using the assigned tools and monitoring progress throughout. This is where the actual work happens.</li><li><strong>Replanning &amp; Iteration: </strong>Based on results from each step, the agent can adjust its approach if needed. This flexibility ensures the final goal is reached even if things don’t go exactly as planned initially.</li></ol><p>Emerging frameworks like AutoGen, Crew AI, and LangGraph, provide rich ways to build multi-agent solutions to problems. I would be exploring the agentic design patterns using the agentic frameworks in my next blog.</p><h3>References</h3><ul><li><a href="https://www.promptingguide.ai/techniques/react">https://www.promptingguide.ai/techniques/react</a></li><li><a href="https://www.promptingguide.ai/research/llm-agents#llm-agent-evaluation">https://www.promptingguide.ai/research/llm-agents#llm-agent-evaluation</a></li><li><a href="https://dzone.com/articles/agentic-design-patterns">https://dzone.com/articles/agentic-design-patterns</a></li><li><a href="https://www.analyticsvidhya.com/blog/2024/10/agentic-design-patterns/#h-frequently-asked-questions">https://www.analyticsvidhya.com/blog/2024/10/agentic-design-patterns/#h-frequently-asked-questions</a></li><li><a href="https://www.deeplearning.ai/the-batch/how-agents-can-improve-llm-performance/?ref=dl-staging-website.ghost.io">https://www.deeplearning.ai/the-batch/how-agents-can-improve-llm-performance/?ref=dl-staging-website.ghost.io</a></li><li><a href="https://microsoft.github.io/autogen/0.2/docs/tutorial/introduction">https://microsoft.github.io/autogen/0.2/docs/tutorial/introduction</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10877627713a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Train Your Own LLM on MacBook: A Finetuning Guide with MLX]]></title>
            <link>https://medium.com/@dummahajan/train-your-own-llm-on-macbook-a-15-minute-guide-with-mlx-6c6ed9ad036a?source=rss-46f5fe7d5425------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c6ed9ad036a</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llm-training]]></category>
            <category><![CDATA[llm-finetuning]]></category>
            <category><![CDATA[llm-applications]]></category>
            <dc:creator><![CDATA[Dushyant Mahajan]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 01:46:12 GMT</pubDate>
            <atom:updated>2025-11-18T16:17:28.719Z</atom:updated>
            <content:encoded><![CDATA[<h3>Train Your Own LLM on MacBook: A Fine-tuning Guide with MLX</h3><h4>Guide to fine tune LLMs on custom dataset on Apple silicon Macs</h4><p>Fine-tuning represents a strategic approach to model development, where we take a pre-trained LLM — already equipped with broad language understanding from training on vast datasets — and further train it on a smaller, specialized dataset. The model retains its foundational knowledge while developing expertise in your target domain.</p><p>For certain custom tasks, fine-tuning can give better results than just using an LLM model. Whether you’re working with patient medical records to generate treatment summaries, analyzing historical diagnosis patterns, or want to build a model that understands specific medical terminology and hospital protocols to generate standardized reports, you might think of fine-tuning an LLM model.</p><p>Fine tuning holds significance as you cannot train an entire large language model from the ground up as it is highly resource intensive in terms of both computational power but also time. So utilizing the existing knowledge embedded in the pre-trained model allows for achieving high performance on niche tasks with less data and computational requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1-wRIpbYieAG0fDChuBZg.png" /></figure><h4>Steps involved in fine-tuning:</h4><ol><li><strong>Gather relevant dataset:</strong> Collect high-quality, domain-specific data that aligns with your target task and desired model behavior.</li><li><strong>Select a pre-trained model</strong>: Choose a base LLM that best matches your requirements in terms of size, performance, and licensing.</li><li><strong>Preprocess the dataset: </strong>Format your data into input-output pairs and convert them into the model’s expected training format.</li><li><strong>Fine-tuning: </strong>Train the selected model on your preprocessed dataset while carefully monitoring for overfitting and performance.</li></ol><h3>Fine-tuning Methods</h3><h4><strong>Instruction fine tuning:</strong></h4><p>Instruction fine-tuning about training the machine learning model using examples that demonstrate how the model should respond to the query. The dataset you use for fine-tuning large language models has to serve the purpose of your instruction. For example, suppose you fine-tune your model to improve its summarization skills. In that case, you should build up a dataset of examples that begin with the instruction to summarize, followed by text or a similar phrase. In the case of translation, you should include instructions like “translate this text.” These prompt completion pairs allow your model to “think” in a new niche way and serve the given specific task. This is how most of the foundation models are trained in the step called Post-training.</p><h4>Full fine-tuning</h4><p>Instruction fine-tuning, where all of the model’s weights are updated, is known as full fine-tuning. The process results in a new version of the model with updated weights. It is important to note that just like pre-training, full fine-tuning requires enough memory and compute budget to store and process all the gradients, optimizers, and other components being updated during training.</p><h4>Parameter-efficient fine-tuning</h4><p>Training a language model is a computationally intensive task. For a full LLM fine-tuning, you need memory not only to store the model, but also the parameters that are necessary for the training process.</p><p>This is where PEFT is crucial. While full LLM fine-tuning updates every model’s weight during the supervised learning process, <strong>PEFT methods only update a small set of parameters</strong>. This transfer learning technique chooses specific model components and “freezes” the rest of the parameters. PEFT also helps dealing with catastrophic forgetting.</p><p>Two key PEFT methods transforming efficient LLM fine-tuning are <strong>LoRA (Low-Rank Adaptation)</strong> and <strong>QLoRA (Quantized LoRA)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/0*bL17QpACzY1d1Egq.png" /><figcaption>Source: <a href="https://arxiv.org/pdf/2305.14314">https://arxiv.org/pdf/2305.14314</a></figcaption></figure><p><strong>LoRA</strong> works by adding small trainable rank decomposition matrices alongside the model’s original weights. Instead of modifying the full weight matrix, LoRA decomposes the weight updates into two smaller matrices (A and B) that, when multiplied, approximate the full update. This dramatically reduces memory requirements while maintaining performance.<br><strong>QLoRA</strong> enhances LoRA’s efficiency through 4-bit quantization of the base model. It uses NormalFloat data type for stable quantized training while keeping LoRA parameters in 16-bit precision. Memory management is optimized through paged optimizers, enabling training on consumer GPUs with minimal performance loss compared to higher-precision approaches.</p><p>Key benefits of these approaches:</p><ul><li>Memory efficiency: 65% reduction with LoRA, up to 95% with QLoRA</li><li>Faster training: Fewer parameters to update</li><li>Modular: Multiple fine-tuned versions can share base model</li><li>Quality preservation: Minimal performance loss vs full fine-tuning</li></ul><p>This <a href="https://medium.com/@dillipprasad60/qlora-explained-a-deep-dive-into-parametric-efficient-fine-tuning-in-large-language-models-llms-c1a4794b1766">blog</a> provides a good in-depth review of the QLoRA technique.</p><h3>Fine-tuning LLMs on Mac with MLX</h3><p>MLX is a framework for machine learning with Apple silicon from Apple Research.</p><blockquote>MLX is designed by machine learning researchers for machine learning researchers. The framework is intended to be user-friendly, but still efficient to train and deploy models. <a href="https://github.com/ml-explore/mlx">https://github.com/ml-explore/mlx</a></blockquote><p>The MLX library, developed by Apple, is equivalent to Tensorflow and PyTorch and supports GPU-backed tasks. This library allows for the fine-tuning of LLMs on the new Apple Silicon (M-Series) chips. Additionally, MLX supports the use of the LoRA method for LLM fine-tuning.</p><p>I was able to successfully fine-tune multiple smaller LLMs with MLX and LoRA on my MacBook pro with the M2 pro chip with 16GB RAM.</p><p>Below is the guide of how you can train LLMs using MLX on your mac system.</p><p>In this tutorial, I am going to fine tune the Ministral-8B-Instruct model on a patients symptoms and diagnosis dataset in natural language. By fine-tuning the model on the dataset the model responds with accurate and concise responses. All the code and data can be found on my <a href="https://github.com/Dushyantm/mlx-finetuning">GitHub</a></p><h4>1. Setup</h4><p>First create a python environment and install all the required libraries.</p><pre># create and activate virtual environment<br>&gt; python -m venv .venv<br>&gt; source .venv/bin/activate<br><br># ML package optimized for Apple Silicon<br>&gt; pip install -U mlx-lm<br><br># install other required libraries<br>&gt; pip install - upgrade pip<br>&gt; pip install pandas<br>&gt; pip install huggingface_hub<br>&gt; pip install &quot;huggingface_hub[cli]&quot;<br><br># create access token to read/write data from hugging-face through the cli<br># this token required when login to huggingface cli<br>https://huggingface.co/settings/tokens<br><br># login into huggingface-cli with access token to download LLM models<br>&gt; huggingface-cli login</pre><h4>2. Dataset Preprocessing</h4><p>MLX requires data to be in specific formats. Three main formats are discussed within MLX: chat, completion, and text. You can read more about these data formats <a href="https://github.com/ml-explore/mlx-examples/blob/main/llms/mlx_lm/LORA.md#Data">here</a>.</p><p>For this example, we’ll use text format data combining context, question, and response in natural language sequences. This format simplifies the input by merging all information into a single text field. The quality of the generated dataset directly impacts the fine-tuned model’s performance.</p><p>For example:</p><pre>{‘text’: “You are a medical diagnosis expert. You will be give patient symptoms: ‘I have been experiencing increased urination, abdominal pain, nausea.’. Question: ‘What is the diagnosis I have?’. Response: You may be diagnosed with Pneumonia.”}</pre><p>The original dataset is structured as a .csv file. For fine-tuning with Apple MLX, I converted it into a text-based format. Each text record combines context, question, and response information into a single, cohesive natural language phrase.</p><pre>import pandas as pd<br>import random<br><br># Load CSV dataset<br>file_path = &#39;dataset/symptoms_diagnosis.csv&#39;<br>df = pd.read_csv(file_path)<br>print(df.head())<br><br>#reformat the csv data into text data<br>csv_data = []<br>for _, row in df.iterrows():<br>    diagnosis = row[&#39;label&#39;]<br>    symptoms = row[&#39;text&#39;]<br>    prompt = f&quot;You are a medical diagnosis expert. You will give answer to patient&#39;s question based on the symptoms they have. Symptoms: &#39;{symptoms}&#39;. Question: &#39;What is the diagnosis I have?&#39;. Response: You may be diagnosed with {diagnosis}.&quot;<br>    csv_data.append({&quot;text&quot;: prompt})<br>random.shuffle(csv_data)<br>csv_data[:10]</pre><p>The MLX requires three sets of datasets: train, test, and valid for fine-tuning. The data files should be in <a href="https://jsonlines.org/">JSONL</a> format. The script below converts data from a CSV file into a JSONL format.</p><pre># calculate split indices<br>total_records = len(csv_data)<br>train_split = int(total_records * 2 / 3)<br>test_split = int(total_records * 1 / 6)<br>print(train_split, test_split)<br><br># split the data<br>train_data = csv_data[:train_split]<br>test_data = csv_data[train_split:train_split + test_split]<br>valid_data = csv_data[train_split + test_split:]<br><br># save the split data to jsonl files<br>import json<br>with open(&#39;train.jsonl&#39;, &#39;w&#39;) as train_file:<br>    for entry in train_data:<br>        train_file.write(json.dumps(entry) + &#39;\n&#39;)<br><br>with open(&#39;test.jsonl&#39;, &#39;w&#39;) as test_file:<br>    for entry in test_data:<br>        test_file.write(json.dumps(entry) + &#39;\n&#39;)<br><br>with open(&#39;valid.jsonl&#39;, &#39;w&#39;) as valid_file:<br>    for entry in valid_data:<br>        valid_file.write(json.dumps(entry) + &#39;\n&#39;)</pre><p>Now the data is ready in the format required by MLX. You may need extra processing to format your dataset according to the MLX data formats.</p><h4>3. LLM setup and selection</h4><p>Based on your dataset and the task, some LLMs can perform better which are pre-trained on similar data. Also, your MacBook specifications should also be considered when choosing an LLM.</p><p>After trying multiple models from the <a href="https://huggingface.co/meta-llama">Meta Llama</a>, <a href="https://huggingface.co/mistralai">Mistral AI</a> and <a href="https://huggingface.co/mlx-community">MLX community</a>, the quantized models from the mlx community work best on the Apple silicon GPUs. The model directory contains almost all the major LLMs from small to big ones.</p><p>For this tutorial I decided to use the Ministral-8B-Instruct model. Use the command below and replace the model repository name with the model you want to use.</p><pre>&gt; huggingface-cli download mlx-community/Ministral-8B-Instruct-2410-4bit<br><br># Output<br>...<br>...<br>...<br>model.safetensors: 100%|██████████████████▉| 4.50G/4.51G [01:46&lt;00:00, 42.0MB/s][A[A<br><br>model.safetensors: 100%|███████████████████| 4.51G/4.51G [01:46&lt;00:00, 42.2MB/s][A[A<br>Download complete. Moving file to /Users/dushyant/.cache/huggingface/hub/models--mlx-community--Ministral-8B-Instruct-2410-4bit/blobs/7049798d4a6002e3d8df810b9a31c4fe4846d35a88c7b947abe6ce5222498b16<br>Fetching 9 files: 100%|███████████████████████████| 9/9 [01:47&lt;00:00, 11.95s/it]<br>/Users/dushyant/.cache/huggingface/hub/models--mlx-community--Ministral-8B-Instruct-2410-4bit/snapshots/ac59869ee8c0b25c94b7cf2ed72f5814d5ed092b</pre><p>To check all the models in the huggingface cache use the command below. Huggingface cli documentation can be found <a href="https://huggingface.co/docs/huggingface_hub/en/guides/cli">here</a>.</p><pre>&gt; huggingface-cli scan-cache<br><br># Output<br>REPO ID                                       REPO TYPE SIZE ON DISK NB FILES LAST_ACCESSED LAST_MODIFIED     REFS   LOCAL PATH                                                                                    <br>--------------------------------------------- --------- ------------ -------- ------------- ----------------- ------ --------------------------------------------------------------------------------------------- <br>BAAI/bge-large-en-v1.5                        model             1.3G        6 6 months ago  6 months ago      main   /Users/dushyant/.cache/huggingface/hub/models--BAAI--bge-large-en-v1.5                        <br>BAAI/bge-reranker-large                       model            801.0        1 3 weeks ago   3 weeks ago       main   /Users/dushyant/.cache/huggingface/hub/models--BAAI--bge-reranker-large                       <br>HuggingFaceH4/zephyr-7b-beta                  model            14.5G       16 7 months ago  7 months ago      main   /Users/dushyant/.cache/huggingface/hub/models--HuggingFaceH4--zephyr-7b-beta                  <br>ds4sd/docling-models                          model           559.9M        9 2 months ago  2 months ago      v2.0.1 /Users/dushyant/.cache/huggingface/hub/models--ds4sd--docling-models                          <br>meta-llama/Llama-2-7b-chat-hf                 model            614.0        1 7 months ago  7 months ago      main   /Users/dushyant/.cache/huggingface/hub/models--meta-llama--Llama-2-7b-chat-hf                 <br>mixedbread-ai/mxbai-embed-large-v1            model           671.4M       11 3 weeks ago   3 weeks ago       main   /Users/dushyant/.cache/huggingface/hub/models--mixedbread-ai--mxbai-embed-large-v1            <br>mlx-community/Llama-3.2-3B-Instruct-4bit      model             1.8G        8 19 hours ago  19 hours ago      main   /Users/dushyant/.cache/huggingface/hub/models--mlx-community--Llama-3.2-3B-Instruct-4bit      <br>mlx-community/Meta-Llama-3.1-8B-Instruct-4bit model             4.5G        8 2 days ago    2 days ago        main   /Users/dushyant/.cache/huggingface/hub/models--mlx-community--Meta-Llama-3.1-8B-Instruct-4bit <br>mlx-community/Ministral-8B-Instruct-2410-4bit model             4.5G        9 2 minutes ago a few seconds ago main   /Users/dushyant/.cache/huggingface/hub/models--mlx-community--Ministral-8B-Instruct-2410-4bit <br>openai/clip-vit-large-patch14                 model             1.5M        5 5 months ago  5 months ago      main   /Users/dushyant/.cache/huggingface/hub/models--openai--clip-vit-large-patch14                 <br>runwayml/stable-diffusion-v1-5                model             1.6M       11 5 months ago  5 months ago      main   /Users/dushyant/.cache/huggingface/hub/models--runwayml--stable-diffusion-v1-5                <br>sentence-transformers/all-MiniLM-L6-v2        model            91.6M       11 3 weeks ago   6 weeks ago       main   /Users/dushyant/.cache/huggingface/hub/models--sentence-transformers--all-MiniLM-L6-v2        <br>stabilityai/stable-diffusion-2-1              model             1.6M       10 5 months ago  5 months ago      main   /Users/dushyant/.cache/huggingface/hub/models--stabilityai--stable-diffusion-2-1 </pre><h4>4. Model Fine-tuning</h4><p>Once the data is ready in the MLX data format, and the LLMs model to be fine-tuned is downloaded we can start the model fine-tuning.</p><p>Use the command below to start the fine-tuning/training.</p><pre>&gt; python -m mlx_lm.lora \<br>    --model mlx-community/Ministral-8B-Instruct-2410-4bit \<br>    --data data \<br>    --train \<br>    --fine-tune-type lora \<br>    --batch-size 4\<br>    --num-layers 16\<br>    --iters 1000 \<br>    --adapter-path adapters<br><br># To check GPU usage during training<br>&gt; sudo powermetrics --samplers gpu_power -i500 -n1</pre><p>Parameter Breakdown:</p><ul><li>--model: Specifies the pre-trained model from HuggingFace hub</li><li>--data: Directory with {train, valid, test}.jsonl files or the name of a Hugging Face dataset (e.g., ‘mlx- community/wikisql’)</li><li>--train: Activates training mode</li><li>--fine-tune-type: Type of fine-tuning to perform: lora, dora, or full</li><li>--batch-size: Mini batch size</li><li>--num-layers: Number of layers to fine-tune. Default is 16, use -1 for all</li><li>--iters: Iterations to train for</li><li>--adapter-path: Saves trained LoRA weights to specified directory</li></ul><h4>5. Evaluate the fine-tuned LLM</h4><p>The LLM is now trained, and the LoRA adapters have been generated. Now, using these adapters together with the original LLM, we can test whether the fine-tuned LLM works or not. First of all, I tested the LLM using MLX with the -test argument. Then I asked the same question to the original LLM and the fine-tuned LLM.</p><p>The comparison shows how fine-tuning LLM has been optimized based on the dataset provided for the medical diagnosis prediction use case. However, it can be further improved in the fine-tuning process by modifying prompts, datasets, and other parameters, etc.</p><pre># test the llm with the test data<br><br>&gt; python -m mlx_lm.lora \<br>    --model mlx-community/Ministral-8B-Instruct-2410-4bit \<br>    --adapter-path adapters \<br>    --data data \<br>    --test<br><br># Output<br>Loading pretrained model<br>Fetching 7 files: 100%|███████████████████████| 7/7 [00:00&lt;00:00, 124936.71it/s]<br>Loading datasets<br>Testing<br>Test loss 0.696, Test ppl 2.007.</pre><p>Testing the original LLM model on a test prompt.</p><pre># testing without the adapters<br>&gt; python -m mlx_lm.generate \<br>    --model mlx-community/Ministral-8B-Instruct-2410-4bit \<br>    --max-tokens 500 \<br>    --prompt &quot;Symptoms: I have been experiencing memory loss, stiffness and difficulty walking. Question: What could be the diagnosis I have?&quot;<br><br># Output<br>Fetching 7 files: 100%|███████████████████████| 7/7 [00:00&lt;00:00, 109552.72it/s]<br>==========<br>Prompt: &lt;s&gt;[INST]Symptoms: I have been experiencing memory loss, stiffness and difficulty walking. Question: What could be the diagnosis I have?[/INST]<br>The symptoms you&#39;re describing—memory loss, stiffness, and difficulty walking—could be indicative of several conditions. Here are a few possibilities:<br><br>1. **Dementia**: This is a broad term that refers to a decline in cognitive function, including memory loss. It can be caused by various conditions, such as Alzheimer&#39;s disease, vascular dementia, or Lewy body dementia.<br><br>2. **Parkinson&#39;s Disease**: This is a neurological disorder that affects movement. It can cause stiffness, difficulty walking, and memory problems.<br><br>3. **Multiple Sclerosis (MS)**: This is an autoimmune disease that can affect the brain and spinal cord. It can cause a wide range of symptoms, including memory loss, stiffness, and difficulty walking.<br><br>4. **Normal Pressure Hydrocephalus (NPH)**: This is a condition where there is an excess of cerebrospinal fluid (CSF) in the brain. It can cause memory loss, difficulty walking, and stiffness.<br><br>5. **Brain Tumor**: While less common, a brain tumor can cause these symptoms.<br><br>6. **Infection or Inflammation**: Conditions like encephalitis or meningitis can cause similar symptoms.<br><br>Given the severity and nature of your symptoms, it&#39;s crucial to consult with a healthcare professional for a thorough evaluation. They can perform tests and examinations to determine the cause of your symptoms and recommend appropriate treatment.<br>==========<br>Prompt: 29 tokens, 155.215 tokens-per-sec<br>Generation: 272 tokens, 38.735 tokens-per-sec<br>Peak memory: 4.595 GB</pre><p>Testing the new finetuned LLM with adapters loaded</p><pre>&gt; python -m mlx_lm.generate \<br>    --model mlx-community/Ministral-8B-Instruct-2410-4bit \<br>    --max-tokens 500 \<br>    --adapter-path adapters \<br>    --prompt &quot;Symptoms: I have been experiencing memory loss, stiffness and difficulty walking. Question: What could be the diagnosis I have?&quot;<br><br># Output<br>Fetching 7 files: 100%|████████████████████████| 7/7 [00:00&lt;00:00, 21732.15it/s]<br>==========<br>Prompt: &lt;s&gt;[INST]Symptoms: I have been experiencing memory loss, stiffness and difficulty walking. Question: What could be the diagnosis I have?[/INST]<br>Based on the symptoms you&#39;ve described, you could be diagnosed with Parkinson&#39;s disease. Memory loss, stiffness, and difficulty walking are common symptoms of this condition. However, it&#39;s important to note that symptoms can vary from person to person. If you&#39;re concerned about your health, it&#39;s best to consult with a healthcare professional for a proper diagnosis.<br>==========<br>Prompt: 29 tokens, 157.481 tokens-per-sec<br>Generation: 71 tokens, 34.942 tokens-per-sec<br>Peak memory: 4.583 GB</pre><p>There is a clear difference in outputs of the fine-tuned LLM, as it gives a precise response similar to the training data. We can conclude that the model was trained well on our custom dataset.</p><h4>6. Fusing the adapters and building our new fine-tuned LLM</h4><p>After fine-tuning with LoRA, the next step is the merging of adapter weights with the base model. MLX provides tools for fusing LoRA parameters directly into the original model’s weights for creating a standalone fine-tuned model. This would solidify the adaptations we’ve done toward our specific task while retaining the general capabilities of the base model. Afterwards, the model can be deployed independently and will not require the added management of the adapters.</p><pre>&gt; python -m mlx_lm.fuse \<br>    --model mlx-community/Ministral-8B-Instruct-2410-4bit \<br>    --adapter-path adapters \<br>    --save-path model/fine-tuned_Ministral-8B</pre><p>Testing the new saved fine-tuned model.</p><pre>&gt; python -m mlx_lm.generate \<br>    --model model/fine-tuned_Ministral-8B \<br>    --max-tokens 500 \<br>    --prompt &quot;Symptoms: I have been experiencing memory loss, stiffness and difficulty walking. Question: What could be the diagnosis I have?&quot;<br><br># Output<br>==========<br>Prompt: &lt;s&gt;[INST]Symptoms: I have been experiencing memory loss, stiffness and difficulty walking. Question: What could be the diagnosis I have?[/INST]<br>Based on the symptoms you&#39;ve described, you could be diagnosed with Parkinson&#39;s disease. Memory loss, stiffness, and difficulty walking are common symptoms of this condition. However, it&#39;s important to consult with a healthcare professional for a proper diagnosis.<br>==========<br>Prompt: 29 tokens, 156.028 tokens-per-sec<br>Generation: 49 tokens, 35.081 tokens-per-sec<br>Peak memory: 4.583 GB</pre><h4>References</h4><ol><li><a href="https://huggingface.co/mlx-community">https://huggingface.co/mlx-community</a></li><li><a href="https://github.com/ml-explore/mlx-examples/tree/main/lora">https://github.com/ml-explore/mlx-examples/tree/main/lora</a></li><li><a href="https://arxiv.org/abs/2106.09685">https://arxiv.org/abs/2106.09685</a></li><li><a href="https://lightning.ai/pages/community/tutorial/lora-llm/">https://lightning.ai/pages/community/tutorial/lora-llm/</a></li><li><a href="https://medium.com/@mustangs007/mlx-building-fine-tuning-llm-model-on-apple-m3-using-custom-dataset-9209813fd38e">https://medium.com/@mustangs007/mlx-building-fine-tuning-llm-model-on-apple-m3-using-custom-dataset-9209813fd38e</a></li><li><a href="https://apeatling.com/articles/part-3-fine-tuning-your-llm-using-the-mlx-framework/">https://apeatling.com/articles/part-3-fine-tuning-your-llm-using-the-mlx-framework/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c6ed9ad036a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Rethinking E-commerce: A study of Seamless Shopping Cart Experience”]]></title>
            <link>https://medium.com/@dummahajan/rethinking-e-commerce-a-study-of-seamless-shopping-cart-experience-2cfcc1b8b17e?source=rss-46f5fe7d5425------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cfcc1b8b17e</guid>
            <dc:creator><![CDATA[Dushyant Mahajan]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 18:15:16 GMT</pubDate>
            <atom:updated>2024-09-25T18:44:18.120Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/899/0*eCuAULKaxKTvEtiL.png" /></figure><h3>Introduction: Understanding the Shopping Cart Experience</h3><p>Online shopping cart abandonment rates remain as high as 70%, leading to substantial revenue losses. This post explores how user experience (UX) optimizations can reduce abandonment and improve the checkout process on e-commerce sites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WyWnDM30nIK0i0wAkfXhSQ.png" /><figcaption>Source: <a href="https://baymard.com/lists/cart-abandonment-rate">Baymard</a></figcaption></figure><h4>Key Stats:</h4><ul><li><strong>Extra Costs Too High (Shipping, Tax, Fees) — 48%</strong>: Nearly half of the survey respondents abandon their shopping carts when faced with unexpected additional costs. This highlights a significant sensitivity to price increments, including shipping charges, taxes, and other fees that weren’t clear at the beginning of their shopping process. This is often the result of a lack of transparency from e-commerce sites about the total cost of a purchase until the final stages of checkout, which can lead to customer dissatisfaction and lost sales.</li><li><strong>Site Required Account Creation — 24%</strong>: A quarter of the users reported abandoning their shopping carts because the site required them to create an account before proceeding with their purchase. This suggests that mandating account creation can be a barrier for customers who prefer a quick and hassle-free checkout experience. E-commerce sites might consider offering a guest checkout option to accommodate users looking to make a purchase without the commitment of account creation.</li><li><strong>Slow Delivery — 22%</strong>: Over a fifth of respondents list slow delivery times as a deterrent to completing their purchase. In an age where same-day or next-day delivery is becoming more common, slow shipping times can be a competitive disadvantage. This statistic underscores the importance for e-commerce businesses to evaluate their logistics and delivery options to meet consumer expectations for fast and efficient service.</li><li><strong>Credit Card Security Concerns — 18%</strong>: Nearly one-fifth of the participants did not trust the site with their credit card information, which underscores the critical importance of establishing trust and ensuring robust security measures are in place. E-commerce sites need to invest in secure platforms and communicate their security measures effectively to reassure customers that their financial information is safe.</li><li><strong>Complicated Checkout Process — 17%</strong>: A significant number of users (17%) abandon their carts due to a long or complicated checkout process. This indicates that a streamlined, simple, and intuitive checkout process is crucial for keeping customers engaged and willing to complete a purchase. Minimizing the number of steps and simplifying forms can help reduce the friction that leads to cart abandonment.</li></ul><p>Below we take a look at the factors that mostly affect a users shopping experience on an e-commerce website.</p><h3>1: Simplifying the User Journey</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSDfB4QrVP6If2Azp3L3cg.png" /><figcaption>Source: <a href="https://www.marinelayer.com/">Marine Layer</a></figcaption></figure><p>The first challenge many users face is a <strong>complex checkout process</strong>. Reducing friction is key to enhancing UX and decreasing cart abandonment.</p><ul><li><strong>Streamlined Navigation</strong>: Poor navigation between product pages and the cart can confuse customers. Simple, intuitive pathways from browsing to checkout help reduce frustration​</li><li><strong>Guest Checkout Options</strong>: Users dislike being forced to create an account. Offering guest checkout, as seen with brands like Lululemon, allows first-time users to quickly complete their purchases without committing to an account​</li></ul><h3>2: Building Trust and Transparency</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVUuyXRTHxKCsyuS3hnKVg.png" /><figcaption>Source: <a href="http://nativeunion.com/cart">Native Union</a></figcaption></figure><p>A seamless journey isn’t just about easy navigation — it’s also about ensuring <strong>trust</strong> at every step. Users abandon carts when they are unsure about costs or security.</p><ul><li><strong>Transparent Costs</strong>: Surprises during checkout, like unexpected shipping fees, lead to high abandonment rates. Be upfront about all costs, using real-time calculators that show shipping and taxes early in the process​</li><li><strong>Security Reassurances</strong>: Payment security is a common concern. Make use of trusted, widely recognized payment processors and clearly communicate encryption and security measures​</li></ul><h3>3: Creating a Frictionless Checkout Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QkJPM2VAWWgTYB5pFfFUvA.png" /><figcaption>Source: <a href="https://www.crossnetgame.com/">Crossnet</a></figcaption></figure><p>Once users reach the cart, reducing complexity becomes critical to avoid second thoughts. A <strong>smooth, fast checkout</strong> can significantly improve conversions.</p><ul><li><strong>Progress Indicators</strong>: A step-by-step visual progress bar can reassure users by showing them how far they are in the process, preventing frustration and abandonment from unclear steps</li><li><strong>Minimal Forms</strong>: Only ask for essential information during checkout. Long and confusing forms are major friction points​</li></ul><h3>4: Enhancing Convenience and Flexibility</h3><p>Today’s shoppers often engage in <strong>multi-device research</strong>, adding items to carts without immediate intent to purchase. Cater to these behaviors with flexibility.</p><ul><li><strong>Wishlist and Save-for-Later Options</strong>: Many users abandon carts as a placeholder, intending to return later. A wishlist feature provides a more structured way for users to save items, improving both user satisfaction and return purchase likelihood​</li><li><strong>Cart Reminders</strong>: Follow up with automated email reminders for users who leave items in their carts. Consider offering discounts or incentives in these emails to bring them back​</li></ul><h3>5: Leveraging Automation and Personalization</h3><p>Personalized interactions help users feel more connected to your brand and can <strong>boost conversion rates</strong>.</p><ul><li><strong>Auto-Apply Coupons</strong>: Shoppers often search for discount codes during checkout, which can lead them to abandon the site. Auto-applying available coupons removes this distraction and encourages checkout completion</li><li><strong>Personalized Cart Recovery Emails</strong>: Use personalized follow-up emails that show abandoned cart contents with a friendly reminder, and include a discount or free shipping to encourage the purchase</li></ul><h3>Case study: Understanding the Zara’s Shopping Cart Experience</h3><h3>Main Website Interface</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JA6UwkNwTniFrlxikp06xQ.png" /><figcaption>Source: <a href="https://www.zara.com/us/">Zara</a></figcaption></figure><ul><li><strong>Streamlined Design</strong>: The homepage showcases a clean and modern aesthetic that aligns with Zara’s brand identity, but it could benefit from clearer navigation cues for new users unfamiliar with the layout.</li><li><strong>Ease of Access</strong>: The shopping categories are well-segmented (e.g., Woman, Man, Kids), which aids in browsing but might need more prominent display of options such as sales or new arrivals to guide user interaction.</li></ul><h3>Shopping Cart Pop-up</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tz1QsptZqBMKDinNtz5dTw.png" /></figure><ul><li><strong>Immediate Feedback</strong>: The pop-up notification when an item is added to the cart is a good UX practice as it provides instant feedback to the user about their action. However the pop-up is missing the final price tag on the page for the user to finalize the amount they will be paying.</li><li><strong>Cross-Selling</strong>: The section “You might like” is strategically placed to encourage additional purchases, but ensuring it doesn’t distract from the checkout process is crucial.</li></ul><h3>Shipping Information Page</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yTtf8R1r5EJpOL4Pva_1zg.png" /></figure><ul><li><strong>Information Clarity</strong>: Missing individual item prices at the shipping selection stage can confuse customers who want to verify the details of their purchase before finalizing.</li><li><strong>Cumbersome Process</strong>: The requirement to go back to check item details could deter users from proceeding with the checkout due to added friction.</li></ul><h3>Payment Method Selection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_nNz0iuUBJWqPl08_h7kw.jpeg" /></figure><ul><li><strong>Diverse Options</strong>: Offering multiple payment methods caters to a broad customer base, which is a positive aspect. However, the interface appears too simple, offering no view of the cart or the place to enter the card details.</li><li><strong>User Interface</strong>: The user has to go to the next page in order to add the card details. Simplifying the presentation and reducing the number of steps to finalize the payment could enhance the user experience.</li></ul><h3>Checkout Review Page</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVdko6vnzvTLssaGTZ64wg.png" /></figure><ul><li><strong>Final Confirmation</strong>: Users have the chance to review their order, which is good practice, but the page lacks options such as editing item sizes directly from this view, forcing users to navigate back, adding unnecessary steps.</li><li><strong>Promotional Code</strong>: No visible option to apply promo codes at this stage could be a missed opportunity to increase conversion rates, as discounts can incentivize users to complete a purchase.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urmIL9xiAhhAtIVGMFqGTg.png" /></figure><h3>General Recommendations for Zara’s Website Checkout Experience:</h3><ol><li><strong>Minimize Clicks</strong>: Each additional click or step in the checkout process can increase the likelihood of cart abandonment. Streamlining the process to require fewer actions from adding an item to completing a purchase can significantly enhance user experience.</li><li><strong>Clarity and Transparency</strong>: Displaying all costs upfront, including item prices and total cart cost at every step of the checkout process, avoids surprises and builds trust with customers. Transparency regarding delivery times and costs is also crucial.</li><li><strong>Responsive Design Adjustments</strong>: Ensuring that all interactive elements are easy to navigate on different devices, including mobile, tablets, and desktops, can improve accessibility and satisfaction.</li><li><strong>Prominent Save for Later</strong>: Incorporating an easily accessible ‘save for later’ option allows users to store items without immediate commitment, which can reduce pressure and potentially increase the likelihood of future purchases.</li><li><strong>Efficient Navigation</strong>: Reducing the need to navigate backwards to edit cart items (like size and quantity) can decrease user frustration and streamline the checkout process.</li></ol><h3>Conclusion</h3><p>The examination of shopping cart experiences across various e-commerce platforms, with a focused case study on Zara, reveals significant insights into the intricacies of online shopping behaviors and user interface design. This study underscores the critical importance of user experience in the shopping cart process, highlighting that the ease and intuitiveness of navigating the checkout flow directly influence customer satisfaction and retention rates.</p><p>Overall, this study acts as a catalyst for ongoing improvements in the e-commerce sector, encouraging businesses to continually assess and refine their user experiences to meet evolving consumer expectations. By prioritizing user-centric design and operational transparency, retailers can significantly enhance the effectiveness of their online platforms.</p><h3>References</h3><ul><li><a href="https://www.gorgias.com/blog/shopping-cart-best-practices">https://www.gorgias.com/blog/shopping-cart-best-practices</a></li><li><a href="https://baymard.com/lists/cart-abandonment-rate">https://baymard.com/lists/cart-abandonment-rate</a></li><li><a href="https://www.identixweb.com/how-to-reduce-the-shopping-cart-abandonment-of-your-ecommerce-store/">https://www.identixweb.com/how-to-reduce-the-shopping-cart-abandonment-of-your-ecommerce-store/</a></li><li><a href="https://www.outerboxdesign.com/conversion-rate-optimization/cart-ux">https://www.outerboxdesign.com/conversion-rate-optimization/cart-ux</a></li><li><a href="https://bandzoogle.com/help/articles/621-shopping-cart">https://bandzoogle.com/help/articles/621-shopping-cart</a></li><li><a href="https://www.zara.com/us/">https://www.zara.com/us/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cfcc1b8b17e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Causal Inference]]></title>
            <link>https://medium.com/aiskunks/exploring-causal-inference-89767db28d2d?source=rss-46f5fe7d5425------2</link>
            <guid isPermaLink="false">https://medium.com/p/89767db28d2d</guid>
            <category><![CDATA[causal-inference]]></category>
            <dc:creator><![CDATA[Dushyant Mahajan]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 20:57:07 GMT</pubDate>
            <atom:updated>2023-04-28T20:57:07.308Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GZjIxbqFGsyjJVg3O6byCA.png" /></figure><h3><strong>Introduction</strong></h3><p><strong>Causal inference</strong> lies at the heart of data-driven decision-making and is crucial for many applications in machine learning, such as recommendation systems, medical treatment planning, and policy evaluation. While traditional machine learning algorithms excel at identifying patterns and correlations within data, they often fall short when it comes to establishing causal relationships. Understanding causality, as opposed to mere correlation, enables us to make informed predictions about the consequences of interventions and helps avoid drawing erroneous conclusions that can have significant real-world implications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*56DbFQKqLugCAduiO-26jg.jpeg" /><figcaption>Image from Markfabiain’s blog</figcaption></figure><p>As machine learning models are increasingly being used to inform high-stakes decisions, the importance of incorporating causality into these models cannot be overstated. By developing a better understanding of causal inference, we can ensure that the insights derived from our models are not only accurate but also meaningful and actionable. This, in turn, can lead to more reliable and robust decision-making processes in various domains, such as healthcare, finance, marketing, and public policy.</p><p>In this article, we will explore the critical concept of causal inference in machine learning, diving into the distinction between causality and correlation and discussing various causal inference techniques. By the end, you’ll be better equipped to build robust models that capture causal relationships, enabling more informed decision-making across a range of domains.</p><h3><strong>Understanding Causality and Causal Inference in Machine Learning</strong></h3><h4>1. Causality and its role in machine learning and data-driven decision-making:</h4><p>Causality refers to the relationship between two variables where a change in one variable directly results in a change in the other. In other words, causality implies that an intervention in one variable can cause a predictable effect in another variable. Establishing causal relationships is essential in machine learning and data-driven decision-making, as it allows us to make reliable predictions about the consequences of actions and interventions. While traditional machine learning techniques are primarily focused on identifying patterns and correlations, understanding causality enables us to build models that can provide meaningful and actionable insights in various domains.</p><h4>2. The difference between causality and correlation:</h4><p>Correlation is a statistical measure that describes the degree to which two variables change together. While correlation can indicate a potential causal relationship, it does not imply causation. In other words, just because two variables are correlated does not mean that one causes the other. It is crucial to recognize this distinction, as confusing correlation with causation can lead to erroneous conclusions and misguided actions. Common pitfalls and misconceptions include assuming causality based on correlation alone or overlooking the possibility of hidden confounders that influence both variables.</p><h4>3. Causal inference techniques:</h4><p>Causal inference is the process of determining the causal effect of a treatment or intervention on an outcome of interest. Various techniques have been developed to estimate causal relationships, each with its own set of assumptions and limitations. Some of the most widely-used methods include:</p><ol><li><strong>Randomized Controlled Trials (RCTs):</strong> RCTs are considered the gold standard in causal inference. In an RCT, subjects are randomly assigned to either a treatment or control group, ensuring that any differences in outcomes can be attributed to the treatment rather than confounding factors. However, RCTs can be expensive, time-consuming, and sometimes unethical or infeasible.</li><li><strong>Propensity Score Matching (PSM):</strong> PSM is a statistical technique that aims to estimate the causal effect by comparing treated and control subjects with similar propensity scores, which are estimated probabilities of receiving treatment based on observed characteristics. This method helps to control for confounding variables, although it relies on the assumption that all relevant confounders have been measured.</li><li><strong>Instrumental Variables (IV):</strong> IV is an approach used when treatment assignment is not random and there may be unmeasured confounders. An instrumental variable is a variable that is correlated with the treatment but not with the outcome or any confounders. By using the variation in the instrumental variable, we can estimate the causal effect of the treatment on the outcome. However, finding a valid instrumental variable can be challenging and requires strong assumptions.</li></ol><h4><strong>Dataset Introduction:</strong></h4><p>The <a href="https://archive.ics.uci.edu/ml/datasets/Bank+Marketing">UCI Bank Marketing dataset</a> offers valuable insights into a real-world bank’s direct marketing campaign, presenting an ideal opportunity for causal inference. Originally designed for a classification task to predict if a client will open a term deposit account, the dataset contains several variables that can be considered interventions or treatments for increasing the number of clients making term deposits.</p><p>The dataset features information on client credit characteristics, contact mode, date and duration of the last contact during the campaign, and variables related to previous marketing campaigns. Additionally, it includes economic indicators such as the employment rate and consumer price index.</p><p>In the notebook <a href="https://colab.research.google.com/drive/16Fe-sr0c_zJSOR_hjBbT_K4sidHyw8nv?usp=sharinghttps://colab.research.google.com/drive/16Fe-sr0c_zJSOR_hjBbT_K4sidHyw8nv?usp=sharing">here</a>, we analyzed the Bank Marketing Dataset to evaluate the impact of marketing decisions, focusing on understanding the causal relationships between various interventions and the likelihood of clients opening term deposit accounts.</p><h3>Understanding Treatment Variables and Potential Confounders</h3><p>In causal inference, treatment variables and potential confounders play a crucial role in estimating the causal effect of interventions on the outcome of interest. In this section, we will define these terms and discuss their importance in the context of causal analysis.</p><h4>1. Treatment Variables:</h4><p>Treatment variables, also known as interventions, are factors that decision-makers can manipulate to influence the outcome. They are the primary focus of causal analysis, as we aim to understand their causal effect on the outcome. For example, in a marketing campaign, treatment variables might include the mode of communication (e.g., email or phone), the timing of the campaign, or the promotional offers being presented.</p><h4>2. Potential Confounders:</h4><p>Potential confounders are variables that can affect both the treatment assignment and the outcome, creating a spurious association between the treatment and the outcome. In order to isolate the true causal effect of the treatment, it is essential to adjust for these confounding variables. For instance, in a marketing campaign, a potential confounder could be the customer’s income, as it may influence both the bank’s decision to target the customer and the customer’s likelihood of responding positively to the campaign.</p><h4>Identifying Treatment Variables and Potential Confounders in Causal Inference</h4><h4>1. Importance of correctly identifying treatment variables and potential confounders:</h4><p>Correctly identifying treatment variables (interventions) and potential confounders are crucial in causal inference, as it isolates interventions’ causal effect on the outcome of interest. By adjusting for confounding variables, we can eliminate bias in the estimated causal effect, leading to more accurate and reliable results.</p><h4>2. Identifying treatment variables and potential confounders in the bank dataset:</h4><p>In the bank dataset, variables associated with the current marketing campaign serve as potential interventions, as the bank can directly control them. From there, we will investigate the effects of <strong><em>‘contact’</em></strong> (mode of communication) and <strong><em>‘campaign’</em></strong> (number of contacts). <strong><em>‘contact’</em></strong> will be encoded as a binary variable (0 for cellular, 1 for telephone).</p><p>To identify potential confounders, we follow two considerations: avoiding post-intervention variables and putting ourselves in the shoes of the hypothetical bank employee making the decision. For this dataset, potential confounders include:</p><p><strong>Client characteristics</strong> <em>(</em><strong><em>‘age’-’loan’</em></strong><em>)</em>: These affect the client’s decision to invest in a term deposit and may be consulted by the bank employee when contacting the client.</p><p><strong>Previous campaigns</strong> <em>(</em><strong><em>‘pdays’, ‘previous’, ‘poutcome’</em></strong><em>)</em>: These indicate the client’s previous receptiveness to the bank’s products and would be part of the client’s record.</p><p><strong>Economic indicators</strong> (<strong><em>‘emp.var.rate’-‘nr.employed’</em></strong>): These conditions may influence the client’s decision as well as the bank’s practices.</p><p>For the ‘contact’ intervention, we also include <strong><em>‘month’</em></strong> to account for seasonality effects and ‘campaign’ to consider the number of contacts up until this point. By correctly identifying these variables, we can better estimate the causal effect of the interventions on the outcome, leading to more informed decision-making.</p><h3><strong>Causal Inference Techniques and Their Application</strong></h3><h4>1. Causal Inference Techniques:</h4><p>Various causal inference techniques can help control for potential confounders and isolate the causal impact of treatment variables, such as contact mode. Some popular techniques include:</p><p><strong>Propensity Score Matching:</strong> This method involves estimating the propensity scores, which represent the probability of receiving a particular treatment given the observed characteristics (confounders). Then, individuals with similar propensity scores are matched, allowing for a comparison of the treatment outcome between the groups that received different treatments while controlling for confounders.</p><p><strong>Inverse Propensity Weighting (IPW): </strong>IPW estimates causal effects by weighting observations based on their propensity scores. Each observation is assigned a weight that is inversely proportional to the probability of receiving the treatment they actually received, given their observed characteristics. This technique aims to create a pseudo-population where the treatment assignment is independent of the confounders, allowing for an unbiased causal effect estimation.</p><p><strong>Instrumental Variables (IV):</strong> IV analysis is a technique that utilizes an external variable (the instrument) that is related to the treatment variable but not directly related to the outcome, except through the treatment. This method allows for consistent estimation of causal effects when unobserved confounding may be present.</p><h4>2. Analyzing the Effect of Contact Mode on Treatment Outcome:</h4><p>Applying these techniques to the analysis of contact mode’s effect on the treatment outcome, such as customer conversion rates, can help us understand the effectiveness of different communication methods in driving marketing campaign success.</p><p><strong>Propensity Score Matching (PSM): </strong>For example, when comparing the effectiveness of phone calls and emails, PSM would involve matching individuals who received phone calls with those who received emails based on their propensity scores. This method allows us to estimate the causal effect of contact mode on the outcome (e.g., conversion rate) by controlling for confounders.</p><p><strong>Inverse Propensity Weighting (IPW)</strong>: Using IPW, we can create a weighted pseudo-population where the assignment of contact mode is independent of confounders. This allows us to estimate the causal effect of contact mode on the treatment outcome by comparing weighted averages of the outcomes for different contact modes (e.g., phone calls vs. text messages).</p><p><strong>Instrumental Variables (IV)</strong>: In the case of IV analysis, we could use an external variable, such as the geographic region, as an instrument if it influences the choice of contact mode but is not directly related to the treatment outcome. Through this approach, we can estimate the causal effect of contact mode on the outcome while accounting for potential unobserved confounding.</p><p>By employing these causal inference techniques, we can better understand the causal relationship between different contact modes and their impact on marketing campaign outcomes, informing data-driven decision-making for marketing strategies.</p><h3><strong>Inverse Propensity Weighting</strong></h3><p>Inverse Propensity Weighting (IPW) is a popular method used in causal inference to estimate the causal effect of a treatment or intervention on an outcome of interest while accounting for potential confounding variables. The key idea behind IPW is to reweight the observed data to create a pseudo-population in which the treatment assignment is independent of the confounders.</p><h4>The IPW method involves the following steps.</h4><p><strong>a. Estimation of Propensity Scores:</strong> The propensity score is the conditional probability of receiving a particular treatment given the observed confounders. These scores can be estimated using logistic regression or other suitable models.</p><p><strong>b. Calculation of Inverse Propensity Weights:</strong> After estimating propensity scores, inverse weights are calculated for each individual in the dataset. Given the observed confounders, these weights are the inverse of the probability of receiving the treatment that was actually received. For treated individuals, the weight is the inverse of the propensity score, whereas, for control individuals, the weight is the inverse of one minus the propensity score.</p><p><strong>c. Estimation of Causal Effects:</strong> The causal effect of the treatment on the outcome is estimated by comparing the weighted average outcomes of the treated and control groups in the pseudo-population. The difference in these weighted averages corresponds to the estimated causal effect, also known as the <strong><em>average treatment effect</em></strong><em> (ATE)</em>.</p><p>IPW has several advantages, such as its ability to handle continuous treatments, missing data, and censoring. However, it is sensitive to the accuracy of the propensity score model and may yield biased estimates if the model is misspecified. In practice, IPW is often combined with other methods, such as matching or regression adjustment, to improve the robustness and efficiency of causal effect estimation.</p><p>The IPW model implementation is performed in the notebook <a href="https://colab.research.google.com/drive/16Fe-sr0c_zJSOR_hjBbT_K4sidHyw8nv#scrollTo=4UPF3C6KqOoV&amp;line=1&amp;uniqifier=1">here</a> using the Causallib library in Python.</p><h3><strong>Standardization</strong></h3><p>Standardization, also known as the G-formula or the adjustment formula, is a method used to estimate the causal effect of a treatment or intervention on an outcome of interest while accounting for potential confounding variables. It involves directly adjusting the observed data by standardizing the outcome variable within strata or levels of the confounding variables.</p><p>Here’s an outline of the standardization process:</p><ol><li><strong>Stratification:</strong> Divide the dataset into strata based on the levels or categories of the confounding variables.</li><li><strong>Estimation of Conditional Outcomes:</strong> Within each stratum, estimate the average outcome for each treatment group (e.g., treated and control).</li><li><strong>Weighted Averaging:</strong> Compute the weighted average of the conditional outcomes across strata, using the distribution of the confounding variables in the target population.</li><li><strong>Causal Effect Estimation: </strong>Calculate the difference in the weighted average outcomes between the treatment groups to estimate the causal effect, also known as the average treatment effect (ATE)</li></ol><h4>Comparison with Non-Causal Analysis</h4><p>In a non-causal analysis, we might have simply used correlations or regression techniques to understand the relationships between variables, without considering the underlying causal mechanisms. This could lead to misleading conclusions, as we would not account for confounding factors or the effects of interventions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*MkrI8NSET1qzRkB0SA9xtw.jpeg" /><figcaption><a href="https://twitter.com/rlmcelreath/status/1436344384069509128">https://twitter.com/rlmcelreath/status/1436344384069509128</a></figcaption></figure><p>By contrast, causal analysis allows us to estimate the true causal effects of interventions, providing a more accurate and reliable understanding of the relationships between variables. In our example, we were able to estimate the causal effect of marketing decisions on client behavior, which could inform more effective marketing strategies for the bank.</p><h3>Conclusion</h3><p>In conclusion, understanding causality is essential in machine learning and data-driven decision-making, as it allows us to draw more accurate and reliable conclusions from our analyses. By using causal inference techniques like IPW and standardization, we can better understand the true relationships between variables and make more informed decisions based on the insights gained from our analyses.</p><p>For those interested in learning more about causality and causal inference, I recommend the following resources-</p><ol><li>Judea Pearl’s book, “The Book of Why: The New Science of Cause and Effect,” — This book provides an accessible introduction to the theory of causality and its applications in various domains</li><li>Miguel Hernán and Jamie Robins’ book, “Causal Inference: What If” — This comprehensive textbook covers the concepts and methods of causal inference in depth, including potential outcomes, directed acyclic graphs, and various estimation techniques</li></ol><h3>References</h3><ol><li><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC9991894/">https://www.ncbi.nlm.nih.gov/pmc/articles/PMC9991894/</a></li><li><a href="https://matheusfacure.github.io/python-causality-handbook/01-Introduction-To-Causality.html">https://matheusfacure.github.io/python-causality-handbook/01-Introduction-To-Causality.html</a></li><li><em>Wenwen Ding, “Causal Inference: Connecting Data and Reality”, The Gradient, 2022.</em></li><li><a href="https://www.yuan-meng.com/posts/causality/">https://www.yuan-meng.com/posts/causality/</a></li><li><a href="https://github.com/BiomedSciAI/causallib">https://github.com/BiomedSciAI/causallib</a></li><li><a href="https://www.pywhy.org/dowhy/v0.9.1/index.html">https://www.pywhy.org/dowhy/v0.9.1/index.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89767db28d2d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/exploring-causal-inference-89767db28d2d">Exploring Causal Inference</a> was originally published in <a href="https://medium.com/aiskunks">AI Skunks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series Forecasting- Predicting coffee prices]]></title>
            <link>https://medium.com/aiskunks/time-series-forecasting-predicting-coffee-prices-5f94b0c6021a?source=rss-46f5fe7d5425------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f94b0c6021a</guid>
            <category><![CDATA[timeseries-forecasting]]></category>
            <category><![CDATA[modeling]]></category>
            <category><![CDATA[fbprophet]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <dc:creator><![CDATA[Dushyant Mahajan]]></dc:creator>
            <pubDate>Sat, 15 Apr 2023 14:57:19 GMT</pubDate>
            <atom:updated>2023-04-15T14:57:19.697Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ALQuh0ALR5k7BTnF1oVXw.jpeg" /><figcaption>Photo by<a href="https://unsplash.com/@jontyson?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Jon Tyson</a> on<a href="https://unsplash.com/photos/FlHdnPO6dlw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Unsplash</a></figcaption></figure><h3><strong>Introduction</strong></h3><p><strong>Formal Definition</strong>: Time series forecasting is the process of analyzing time series data using statistics and modeling to make predictions and inform strategic decision-making. It’s not always an exact prediction, and the likelihood of forecasts can vary wildly, especially when dealing with the commonly fluctuating variables in time series data and factors outside our control.</p><p>In the simplest terms, time-series forecasting is a technique that utilizes historical and current data to predict future values over a period of time or a specific point in the future.</p><p><strong>Picture this</strong>: you’re a coffee shop owner, and you’re trying to forecast the demand for your coffee products over the next few months. You know that historical sales data can provide valuable insights, but how can you use that data to predict future trends? This is where time series forecasting comes in. It’s a powerful tool that can help you make informed decisions based on the patterns and trends you’ve observed in your data.</p><p>At its core, time series forecasting involves analyzing sequential data to identify patterns and trends over time. By using historical data to predict future values, you can gain insights into future trends, identify potential risks and opportunities, and optimize resource allocation. And it’s not just coffee shops that can benefit from time series forecasting. It’s a technique that can be applied to a wide range of industries, from finance and economics to healthcare and retail.</p><p>There are various time series modeling techniques, such as ARIMA, SARIMA, and Prophet, each with its own advantages and limitations. But regardless of the technique used, time series forecasting requires careful data preprocessing and exploratory data analysis to ensure the accuracy and reliability of the models. And while time series forecasting is not perfect, and there are limitations to its accuracy, it’s a rapidly growing field with ongoing research and development of new techniques and tools.</p><p>So if you’re a business owner, analyst, or data scientist looking to gain insights into future trends and patterns, time series forecasting is essential to add to your toolkit. With its ability to provide valuable insights into future trends, it has the potential to transform various industries and help businesses make data-driven decisions that can lead to better outcomes and higher profitability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QzWlnudjkY6lp5Y_" /><figcaption>Photo by<a href="https://unsplash.com/@lukechesser?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Luke Chesser</a> on<a href="https://unsplash.com/photos/JKUTrJ4vK00?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Unsplash</a></figcaption></figure><h3><strong>Dataset</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DD_ayClEjkGfs90j" /><figcaption>Photo by<a href="https://unsplash.com/@itfeelslikefilm?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> 🇸🇮 Janko Ferlič</a> on<a href="https://unsplash.com/images/food/coffee?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Unsplash</a></figcaption></figure><p>The dataset used is going to be the daily coffee price dataset from Kaggle. Link to dataset: <a href="https://www.kaggle.com/datasets/psycon/daily-coffee-price?resource=download">https://www.kaggle.com/datasets/psycon/daily-coffee-price?resource=download</a></p><p>The Daily Coffee Price dataset is a collection of historical coffee prices from various markets around the world. With data spanning several decades, the dataset provides a valuable resource for analyzing trends and patterns in the coffee market and for forecasting future prices and demand. The dataset includes variables such as opening, closing, high, and low prices, as well as trading volume and currency exchange rates. By understanding the underlying time series components of the data, such as trends, seasonality, and cyclical patterns, we can build accurate and reliable time series models that can be used for decision-making in the coffee industry.</p><p>We begin by loading the dataset, visualizing the ‘Close’ prices, and analyzing the data’s basic properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*FwM5pl-3Y7K6QPocEqV_Tg.png" /><figcaption>That’s how the Daily Coffee Price Dataset looks like</figcaption></figure><p>Our primary objective is to forecast the <strong>‘Close’ </strong>prices of coffee.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*16A7HugLLHBNKU3bSa6Q2g.png" /><figcaption>Candlestick Plot for the input data</figcaption></figure><h4>Resampling data</h4><p>One typical task when doing analysis with time series data is to <em>resample</em> the time series from one frequency to another, such as aggregating the Yearly price observations to daily or monthly averages. Here we sample the data from daily frequency to monthly, quarterly, and annual frequency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zmewk4JYONCxEiTY2297JQ.png" /><figcaption>Daily data was Resampled to monthly, quarterly, and annual frequency.</figcaption></figure><h3>Understanding Patterns in Data</h3><h4>Analyzing Autocorrelation and Partial Autocorrelation:</h4><p>Autocorrelation (ACF) and partial autocorrelation (PACF) are vital tools for understanding the underlying patterns in our time series data. ACF measures the correlation between a time series and its lagged version, while PACF measures the exact correlation while accounting for the effect of other lags. By examining the ACF and PACF plots, we can identify the appropriate lags for our forecasting models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*JP_zc7ZV4BJ2kJCUwoXDbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYQZys17ZMRf7ObiSdnCTw.png" /></figure><h4>Decomposing the Time Series:</h4><p>To gain further insights into our data, we can decompose the time series into its constituent components: trend, seasonality, and residual. This helps us understand the underlying patterns and improve our forecasting models.</p><h4><strong>Stationarity</strong></h4><p>Stationary data refers to the time series data that mean and variance does not vary across time. The data is considered non-stationary if there is a strong trend or seasonality observed from the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E8uBuOM4GdeCsBNE" /><figcaption>picture from <a href="https://otexts.com/fpp2/stationarity.html">Forecasting: Principles and Practice</a></figcaption></figure><p><strong>Which of these series are stationary?</strong></p><p>(a) Google stock price for 200 consecutive days; (b) Daily change in the Google stock price for 200 consecutive days; © Annual number of strikes in the US; (d) Monthly sales of new one-family houses sold in the US; (e) Annual price of a dozen eggs in the US (constant dollars); (f) Monthly total of pigs slaughtered in Victoria, Australia; (g) Annual total of lynx trapped in the McKenzie River district of north-west Canada; (h) Monthly Australian beer production; (i) Monthly Australian electricity production.</p><p>Consider the nine series plotted in the Figure above. Which of these do you think is stationary?</p><p>Obvious seasonality rules out series (d), (h), and (i). Trends and changing levels rule out series (a), ©, (e), (f), and (i). Increasing variance also rules out (i). That leaves only (b) and (g) as stationary series.</p><p>At first glance, the strong cycles in series (g) might appear to make it non-stationary. But these cycles are aperiodic — they are caused when the lynx population becomes too large for the available feed so that they stop breeding and the population falls to low numbers, then the regeneration of their food sources allows the population to grow again, and so on. In the long term, the timing of these cycles is not predictable. Hence the series is stationary.</p><p><strong>Is Stationarity important for time series analysis?</strong></p><p>In most cases, it is essential. This is because much statistical analysis or model is built upon the assumption that means and variance are consistent over time.</p><p>When we fit a stationary model to the time series data that we want to analyze, we should detect the stationarity of the data and remove the trend/seasonality effect from the data.</p><p>Many current time series models like ARIMA have options to include steps to convert the original data into stationary data or which makes our life more convenient. However, it would still be beneficial if we could understand the stationarity of the data so that we can give better input to the model.</p><p><strong>Checking for Stationarity</strong>:</p><p>Stationarity is an essential assumption in time series analysis. A stationary time series exhibits constant statistical properties like mean and variance over time. If our data is non-stationary, our models may produce unreliable predictions.</p><p>To test for stationarity, we can plot the ‘Close’ prices and observe if there’s an apparent trend or seasonality. Additionally, we can perform the Dickey-Fuller test, which statistically evaluates stationarity. If the test’s p-value is below a predetermined threshold (e.g., 0.05), we can reject the null hypothesis that the time series is non-stationary.</p><p><strong>Making the Data Stationary</strong>:</p><p>If our data is non-stationary, we need to apply techniques like differencing or transformations (e.g., log, square root) to make it stationary. For example, if the first-order differencing (subtracting the previous value from the current value) results in a stationary series, we can proceed with this transformed data.</p><h3><strong>Model Selection and Parameter Tuning</strong></h3><p>Various time series forecasting models exist, such as ARIMA, SARIMA, and Prophet.</p><p><strong>ARIMA (Autoregressive Integrated Moving Average):</strong> A linear model that combines the autoregressive (AR), moving average (MA), and differencing (I) components.</p><p><strong>SARIMA (Seasonal Autoregressive Integrated Moving Average):</strong> An extension of ARIMA that includes seasonal components, making it suitable for time series with seasonal patterns.</p><p><strong>Prophet:</strong> A forecasting model developed by Facebook, which is robust to outliers and missing data, automatically handles seasonality and trend components.</p><h4><strong>Model Selection using AIC and BIC</strong>:</h4><p>After analyzing the autocorrelation and partial autocorrelation, it’s time to select an appropriate forecasting model and its optimal parameters. AIC (Akaike Information Criterion) and BIC (Bayesian Information Criterion) are two widely used criteria for model selection in time series analysis.</p><p>AIC and BIC balance model complexity and goodness-of-fit, helping us avoid overfitting. Lower AIC and BIC values indicate better models, considering both fit and parsimony.</p><p>For example, when working with ARIMA models, we search over various combinations of (p, d, q) parameters, where p represents the order of the autoregressive term, d is the differencing order, and q is the moving average term. We can choose the combination with the lowest AIC and BIC scores, as it likely represents the best trade-off between model complexity and fit.</p><p>Similarly, for other time series models, such as SARIMA or VAR, we can use AIC and BIC to guide our search for the best model and its parameters.</p><p>We will use the AIC (Akaike Information Criterion) and BIC (Bayesian Information Criterion) to compare these models and select the best one. AIC and BIC balance model complexity and goodness-of-fit, helping us avoid overfitting.</p><p>For example, using the ARIMA model, we can search over various combinations of (p, d, q) parameters, where p represents the order of the autoregressive term, d is the differencing order, and q is the moving average term. We can choose the combination with the lowest AIC and BIC scores.</p><h3><strong>Model Evaluation</strong></h3><p>One of the most important things you need to do when evaluating a time series machine learning model is to perform error analysis. This involves calculating the error between the predicted and actual values for each data point. You can then use this information to determine how accurate the model is. There are a few different ways that you can perform error analysis. The following is a list of steps that you can use to check the accuracy of your time series models or perform error analysis:</p><ul><li><strong>Seasonality impact:</strong> Time series models are impacted by time cycles such as daily, weekly, monthly, or any recurring cycle. It is recommended to analyze prediction errors across different cycles. If the errors are seen across different cycles, one can add more time-based features to the training data set. Recall that seasonality is defined as a repeating pattern of events occurring at fixed intervals.</li><li><strong>Trends analysis:</strong> Make sure your model is capable of tracking broad rises and falls. In other words, it does not outperform or underperform in rising or declining trends.</li><li><strong>Model reactiveness:</strong> This is the model’s ability to react quickly to changes in data distribution that aren’t caused by a trend or cycle. Try adding short-term rolling or lagging features if the model is slow to react to sudden data distribution changes. If the model predictions change very swiftly, try adding longer-term rolling or lagging features.</li><li><strong>Evaluation metrics choice:</strong> It is important to decide which metrics to use out of mean squared error (MSE) or mean absolute error (MAE). Performing error analysis with mean squared error loss is appropriate for models that can react to sudden changes in the data distribution. On the other hand, metrics such as mean absolute error are most appropriate for models that don’t change swiftly based on changes in data distribution. If the data distribution changes are unexpected and ignorable, MAE may be a good idea. If it’s important to be reactive to the changes in data distribution, you can as well consider using MSE.</li><li><strong>Holidays consideration:</strong> Make sure to check the effect of holidays on the day and the period around them, AND not just the day or holiday. If the model struggles to perform just before and after holidays, try adding features that tell your model that it’s close to a holiday.</li><li><strong>Model bias analysis:</strong> Make sure that your model is not over-forecasting or under-forecasting in a consistent manner. If that is happening, try adding more data. In addition, try checking the data quality, as this has been found to be a common issue that can cause the model to be consistently over-forecast or under-forecast. Sometimes the data you’re working with is not in a clean format. This can cause your machine-learning model to perform poorly. Make sure you clean up your data before training your model.</li><li><strong>Different machine learning algorithms:</strong> If you’ve already tried different feature engineering and your data doesn’t seem to be responding, you can try switching machine learning algorithms. Different algorithms have different strengths and weaknesses, so this could be your data’s solution.</li><li><strong>Model performance in production:</strong> Make sure to check the time-series model deployed in production continues to perform well. If the model performance starts to vary too quickly, it is a good idea to consider increasing the length of the roll-forward evaluation windows.</li></ul><h3><strong>Exploring Advanced Models — Facebook Prophet</strong></h3><p>Facebook Prophet is an open-source algorithm for generating time-series models using a few old ideas with new twists. It is particularly good at modeling time series that have multiple seasonalities and doesn’t face some of the above drawbacks of other algorithms. At its core is the sum of three functions of time plus an error term: growth g(t), seasonality s(t), holidays h(t), and error e_t :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/0*_IlsNCPDae9zLJPv" /></figure><h4>The Growth Function (and change points):</h4><p>The growth function models the overall trend of the data. The old idea should be familiar to anyone with a basic knowledge of linear and logistic functions. The new idea incorporated into Facebook Prophet is that the growth trend can be present at all data points or altered at what Prophet calls “changepoints.”</p><p>Changepoints are moments in the data where the data shift direction. Using new COVID-19 cases as an example, it could be due to new cases beginning to fall after hitting a peak once a vaccine is introduced. Or it could be a sudden pick up of cases when a new strain is introduced into the population, and so on. Prophet can automatically detect change points or you can set them yourself. You can also adjust the change points’ power in altering the growth function and the amount of data taken into account in automatic changepoint detection.</p><p>The growth function has three main options:</p><ul><li><strong>Linear Growth: </strong>This is the default setting for Prophet. It uses a set of piecewise linear equations with differing slopes between change points. When linear growth is used, the growth term will look similar to the classic y = mx + b from middle school, except the slope(m) and offset(b) are variable and will change value at each changepoint.</li><li><strong>Logistic Growth: </strong>This setting is useful when your time series has a cap or a floor in which the values you are modeling becomes saturated and can’t surpass a maximum or minimum value (think carrying capacity). When logistic growth is used, the growth term will look similar to a typical equation for a logistic curve (see below), except it the carrying capacity © will vary as a function of time and the growth rate (k) and the offset(m) are variable and will change value at each change point.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/0*B6aSaxm0so5g1l-A" /></figure><ul><li><strong>Flat:</strong> Lastly, you can choose a flat trend when there is no growth over time (but there still may be seasonality). If set to flat the growth function will be a constant value.</li></ul><h4>The Seasonality Function:</h4><p>The seasonality function is simply a Fourier Series as a function of time. If you are unfamiliar with Fourier Series, an easy way to think about it is the sum of many successive sines and cosines. Each sine and cosine term is multiplied by some coefficient. This sum can approximate nearly any curve or, in the case of Facebook Prophet, the seasonality (cyclical pattern) in our data. All together it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*H2FCscEPVwveh15j" /></figure><p>If the above is difficult to decipher, I recommend this <a href="https://www.mathsisfun.com/calculus/fourier-series.html">simple breakdown of the Fourier Series</a> or this <a href="https://www.youtube.com/watch?v=r6sGWTCMz2k">video on the intuition behind the Fourier series</a>.</p><p>If you are still struggling to understand the Fourier series, do not worry. You can still use Facebook Prophet because Prophet will automatically detect an optimal number of terms in the series, also known as the Fourier order. Or if you are confident in your understanding and want more nuance, you can also choose the Fourier order based on the needs of your particular data set. The higher the order the more terms in the series. You can also choose between additive and multiplicative seasonality.</p><h4>The Holiday/Event Function:</h4><p>The holiday function allows Facebook Prophet to adjust forecasting when a holiday or major event may change the forecast. It takes a list of dates (there are built-in dates of US holidays, or you can define your own dates), and when each date is present in the forecast adds or subtracts value from the forecast from the growth and seasonality terms based on historical data on the identified holiday dates. You can also identify a range of days around dates (think the time between Christmas/New Year&#39;s, holiday weekends, thanksgiving’s association with Black Friday/Cyber Monday, etc.).</p><h3><strong>Forecasting Future Coffee Prices</strong></h3><p>Once we have chosen the best model, we can use it to forecast future coffee prices. Visualizing these predictions alongside historical data is essential to interpret the forecasts better.</p><p>Moreover, providing confidence intervals for our predictions can help communicate the uncertainty associated with the forecasts. Most time series models, including ARIMA and Prophet, offer functionality to generate confidence intervals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*spaD7lZx7HK75DRi" /></figure><h3><strong>Conclusion</strong></h3><p>In this blog post, we walked you through a comprehensive, step-by-step tutorial on time series forecasting using the Daily Coffee Price dataset. We discussed various aspects of forecasting, including data preparation, stationarity, model selection, and evaluation.</p><p>Remember that time series forecasting is an iterative process; there’s always room for improvement. Keep experimenting with different models, parameters, and techniques to refine your forecasts further. Happy forecasting!</p><p><strong>Colab notebook Link:</strong></p><p><a href="https://colab.research.google.com/drive/136WNAwoZ0D5zoMkkU5B8QcAiU6mjeR5c#scrollTo=yp7L4nv-M3K4&amp;uniqifier=1"><strong>https://colab.research.google.com/drive/136WNAwoZ0D5zoMkkU5B8QcAiU6mjeR5c#scrollTo=yp7L4nv-M3K4&amp;uniqifier=1</strong></a></p><h3><strong>References</strong></h3><ol><li><a href="https://www.kaggle.com/datasets/psycon/daily-coffee-price?resource=download">https://www.kaggle.com/datasets/psycon/daily-coffee-price?resource=download</a></li><li><a href="https://otexts.com/fpp2/stationarity.html">https://otexts.com/fpp2/stationarity.html</a></li><li><a href="https://towardsdatascience.com/stationarity-assumption-in-time-series-data-67ec93d0f2f#:~:text=What%20is%20stationary%20data%3F,seasonality%20observed%20from%20the%20data.">https://towardsdatascience.com/stationarity-assumption-in-time-series-data-67ec93d0f2f#:~:text=What%20is%20stationary%20data%3F,seasonality%20observed%20from%20the%20data.</a></li><li><a href="https://colab.research.google.com/drive/1FyhK0hhscSQqHfo227QvarzcWJAlIDDy?usp=sharing#scrollTo=ON9zL6SEdIhD">https://colab.research.google.com/drive/1FyhK0hhscSQqHfo227QvarzcWJAlIDDy?usp=sharing#scrollTo=ON9zL6SEdIhD</a></li><li><a href="https://vitalflux.com/steps-for-evaluating-validating-time-series-models/">https://vitalflux.com/steps-for-evaluating-validating-time-series-models/</a></li><li><a href="https://towardsdatascience.com/time-series-analysis-with-facebook-prophet-how-it-works-and-how-to-use-it-f15ecf2c0e3a">https://towardsdatascience.com/time-series-analysis-with-facebook-prophet-how-it-works-and-how-to-use-it-f15ecf2c0e3a</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f94b0c6021a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/time-series-forecasting-predicting-coffee-prices-5f94b0c6021a">Time Series Forecasting- Predicting coffee prices</a> was originally published in <a href="https://medium.com/aiskunks">AI Skunks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Crash Course in DATA: Control your charts like an expert with Altair]]></title>
            <link>https://medium.com/aiskunks/a-crash-course-in-data-control-your-charts-like-an-expert-with-altair-76de7837a87b?source=rss-46f5fe7d5425------2</link>
            <guid isPermaLink="false">https://medium.com/p/76de7837a87b</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[altair]]></category>
            <dc:creator><![CDATA[Dushyant Mahajan]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 14:50:30 GMT</pubDate>
            <atom:updated>2023-03-02T19:36:31.995Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide to instantly boost your charting skills</h4><p>The demand for data skills in employees is a mandatory factor in today’s data-driven world. It’s more important than ever to have accessible ways to view and understand data to obtain useful insights.</p><blockquote>One of the best ways to understand data is to see it.</blockquote><p>Data visualization can allow you to get an instant understanding of the data that is just not possible by observing rows of data in a table.</p><p><strong>There are two main approaches to creating data visualizations:</strong></p><p><strong>1. Imperative </strong>- involves writing code to manually create charts. It’s used in libraries such as Matplotlib or Seaborn, where you specify the data, chart type, and appearance details. This approach offers more control but can be more complex and take longer.</p><p><strong>2. Declarative - </strong>you define what information you want to display in a visualization rather than how to display it. This approach is simpler and more intuitive, as the libraries like Altair or GGplot handle the technical details of generating the chart. You can concentrate on telling the story with your data.</p><p>It is up to you to decide which one is more suitable for your data and the one you feel comfortable with. Most of the libraries require you to refer to their long and tiring documentation for syntax.</p><p>This is where <strong>Altair </strong>comes in. Its syntax is clean and easy to understand, as we will see in the examples. I believe after reading this post, and you will feel confident about making charts.</p><h4>Why Altair?</h4><p>Altair offers a powerful and concise visualization grammar for quickly building a wide range of statistical graphics. The declarative approach is often more intuitive, as you can focus on the story you want to tell rather than the technical details of how to create the visualization. Altair can be used to create a variety of beautiful plots, such as bar charts, pie charts, histograms, scatterplots, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*l5092wz3cpC3hGo_Ek5msA.png" /><figcaption>Altair-logo</figcaption></figure><p>The advantage of Altair lies in its API capabilities. As a Python API to Vega-Lite, Altair’s main purpose is to convert plot specifications to a JSON string that conforms to the Vega-Lite schema and then render the visualization inline inside the browser using <a href="https://vega.github.io/vega-lite/">Vega and Vega-Lite</a>.</p><h4>Fundamentals of Charting with Altair</h4><p>The key elements we will need to remember are</p><ol><li><strong>Chart object</strong> - It takes the dataframe as a single argument. It knows how to emit a JSON dictionary representing the data and visualization encodings.</li><li><strong>Chart marks - </strong>These decide what sort of mark we would like to use to represent our data. Eg., point, line, bar, area, tick, circle, and <a href="https://colab.research.google.com/drive/1Rxg87Pn9Crpd0Kg8VhHFdtxp4EWkYIqY?authuser=2#scrollTo=Imovkowgnc_C">more</a></li><li><strong>Chart Encodings - </strong>An encoding channel specifies how a given data column should be mapped onto the visual properties of the visualization.</li></ol><p><strong>Installing required packages:</strong></p><pre>$ pip install altair jupyter vega pandas</pre><h4>Basic Plotting</h4><p>Let’s move ahead and get the dataset from vega_datasets and perform some simple analysis to understand it better. You can also import your data using pandas; for now, I’m using the built-in dataset.</p><pre>from vega_datasets import data<br>import altair as alt<br>cars = data.cars()<br>cars.sample(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*Cdnh1DhbjXvNN13Nmzj5Gw.png" /></figure><p>In this case, let’s begin by looking at the relationship between mileage (Miles_per_Gallon) and engine power (Horsepower) in a scatter plot.</p><p>For that, we’ll want to make a chart with points. So we use mark_point()<em> </em>and encode the x-axis with “Miles_per_Gallon” and the y-axis with “Horsepower.”</p><pre>alt.Chart(cars).mark_point().encode(<br>    x=&quot;Miles_per_Gallon&quot;, <br>    y=&quot;Horsepower&quot;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*pHL2QMJL8DALg0Af7W20Nw.png" /><figcaption>Voila! It’s as simple as that.</figcaption></figure><p>Want to add colors and shapes? Just mention the visual encodings, color and shape.</p><pre>alt.Chart(cars).mark_point().encode(<br>    x=&#39;Horsepower&#39;,<br>    y=&#39;Miles_per_Gallon&#39;,<br>    color=&#39;Origin&#39;,<br>    shape=&#39;Origin&#39;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*Z8ag-BjRH2XlyJ3LOnoiww.png" /><figcaption>The shapes and colors are automatically mapped based on the data column(here- ‘Origin’).</figcaption></figure><blockquote>The key to creating meaningful visualizations is to map properties of the data to visual properties in order to effectively communicate information</blockquote><p>Do you need a bar chart? change mark_point() to mark bar()<em>. </em>Adding color to the bar chart (by using the color attribute) creates a stacked bar chart by default.</p><pre>alt.Chart(cars).mark_bar().encode(<br>    x=alt.X(&#39;Miles_per_Gallon&#39;, bin=True), #binning the columns<br>    y=&#39;count()&#39;,  #aggregating the data<br>    color=&#39;Origin&#39;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*qHmGxNaFPIB96Y6pqzsIGg.png" /><figcaption>mapping a binned quantitative field to x and aggregate count to y produces a histogram.</figcaption></figure><p>Need a line plot for your data? Use the mark_line</p><pre>alt.Chart(stocks).mark_line().encode(<br>    x=&#39;date&#39;,<br>    y=&#39;price&#39;,<br>    color=&#39;symbol&#39;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*dqaMFlpLPEZhG77XjXfo6A.png" /></figure><p>Here are some of the more commonly used mark_*() methods supported in Altair and Vega-Lite:</p><ul><li>mark_area()</li><li>mark_bar()</li><li>mark_circle()</li><li>mark_line()</li><li>mark_point()</li><li>mark_rule()</li><li>mark_square()</li><li>mark_text()</li><li>mark_tick()</li></ul><h3>Encoding</h3><p>The key to creating meaningful visualizations is to map the properties of the data to visual properties in order to communicate information effectively. In Altair, this mapping of visual properties to data columns is referred to as <strong>Encoding.</strong></p><h4>Encoding Data types</h4><p>The details of any mapping depend on the type of data. Altair recognizes five main data types:</p><ul><li><strong><em>quantitative — </em></strong><strong><em>Q(a continuous real-valued quantity)</em></strong></li><li><strong><em>ordinal — </em></strong><strong><em>O (a discrete ordered quantity)</em></strong></li><li><strong><em>nominal — </em></strong><strong><em>N (a discrete unordered category)</em></strong></li><li><strong><em>temporal — </em></strong><strong><em>T (a time or date value)</em></strong></li><li><strong><em>geojson — </em></strong><strong><em>G (a geographic shape)</em></strong></li></ul><p>If types are not specified for data input as a DataFrame, Altair defaults to quantitative for any numeric data, temporal for date/time data, and nominal for string data.</p><p><strong>How Data Type affects Color Scales</strong></p><p>Specifying the correct type for your data is important, as it affects the way Altair represents your encoding in the resulting plot.</p><p>Below is an example that shows how the data type influences the way Altair decides on the color scale to represent the value and also influences whether a discrete or continuous legend is used.</p><pre>base = alt.Chart(cars).mark_point().encode(<br>    x=&#39;Horsepower:Q&#39;,<br>    y=&#39;Miles_per_Gallon:Q&#39;,<br>).properties(<br>    width=250,<br>    height=250<br>)<br><br># Plotting the same chart with different data types<br>base.encode(color=&#39;Cylinders:Q&#39;).properties(title=&#39;quantitative&#39;) |   base.encode(color=&#39;Cylinders:O&#39;).properties(title=&#39;ordinal&#39;) |   base.encode(color=&#39;Cylinders:N&#39;).properties(title=&#39;nominal&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKVMfEJcsKQkokcDq12ZGQ.png" /><figcaption>Notice the different legends and colors based on the data type</figcaption></figure><h4>Encoding Channels</h4><p><strong>What is a channel? </strong>In data visualization, a visual variable used to represent data is called a channel. A channel is typically mapped to a specific aspect of the data, such as its value, position, or color.</p><p>Examples of channels include<strong> position (e.g., x and y axes), size, shape, color, texture, and orientation</strong>.</p><p>Each encoding channel allows for a number of additional options to be expressed; these can control things like <strong>axis properties, scale properties, headers and titles, binning parameters, aggregation, sorting</strong>, and many more.</p><p><strong>Binning data</strong></p><p>One of the most common uses of binning is the creation of histograms. One interesting thing is that Altair’s declarative approach allows us to start assigning these values to different encodings to see other views of the exact same data.</p><p>So, for example, if we assign the binned miles per gallon to the color, we get this view of the data:</p><pre>alt.Chart(cars).mark_bar().encode(<br>    color=alt.Color(&#39;Miles_per_Gallon&#39;, bin=True),<br>    x=&#39;count()&#39;,<br>    y=&#39;Origin&#39;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*lb9iWTAFNi3Ow0pHjqYozg.png" /><figcaption>This gives us a better appreciation of the proportion of MPG within each country. We see that well over half of US cars were in the “low mileage” category.</figcaption></figure><p>Changing the encoding again, let’s map the color to the count instead:</p><pre>alt.Chart(cars).mark_rect().encode(<br>    x=alt.X(&#39;Miles_per_Gallon&#39;, bin=alt.Bin(maxbins=20)),<br>    color=&#39;count()&#39;,<br>    y=&#39;Origin&#39;,<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*DUOxbiCsvKB-ItdRe6hJxQ.png" /><figcaption>The result is a heatmap</figcaption></figure><p>This is one of the beautiful things about Altair: it shows you through its API grammar the relationships between different chart types.</p><p>For example, a 2D heatmap encodes the same data as a stacked histogram!</p><p><strong>Aggregation of Data</strong></p><p>Beyond simple channel encodings, Altair’s visualizations are built on the concept of database-style <strong>grouping and aggregation</strong>, that is, the split-apply-combine abstraction that underpins many data analysis approaches.</p><p>One key operation in data exploration is the<strong> group-by</strong>; the group-by splits the data according to some condition, applies some aggregation within those groups, and then combines the data back together.</p><p>For the car data, you might split by Origin, compute the <strong>mean </strong>of the miles per gallon, and then combine the results. In Pandas, the operation looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*6vwQJJ4RzCXayIYVA-B4gw.png" /></figure><p>In Altair, this sort of split-apply-combine can be performed by passing an aggregation operator within a string to any encoding.</p><p>For example, we can display a plot representing the above aggregation as follows:</p><pre>alt.Chart(cars).mark_bar().encode(<br>    x=&#39;mean(Miles_per_Gallon)&#39;,<br>    y=&#39;Origin&#39;,<br>    color=&#39;Origin&#39;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*h8pOIlfUS9982Iz4fNa2fA.png" /><figcaption>Mean of Miles_per_Gallon based on Origin</figcaption></figure><p>Aggregates can also be used with data that is only implicitly binned. For example, look at this plot of MPG over time:</p><pre>alt.Chart(cars).mark_point().encode(<br>    x=&#39;Year:T&#39;,<br>    y=&#39;Miles_per_Gallon&#39;,<br>    color=&#39;Origin&#39;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*sOak6_qQNU4qtHPXNKQdEQ.png" /><figcaption>Without aggregation, it’s difficult to follow the data.</figcaption></figure><p>The fact that the points overlap so much makes it difficult to see important parts of the data; we can make it clearer by plotting the mean in each group (here, the mean of each Year/Country combination):</p><pre>alt.Chart(cars).mark_line().encode(<br>    x=&#39;Year:T&#39;,<br>    y=&#39;mean(Miles_per_Gallon)&#39;,<br>    color=&#39;Origin&#39;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*C8Tigj4Jr4EWGfJxcXlyvQ.png" /><figcaption>Each line traces the mean per year for each country.</figcaption></figure><p>The mean aggregate only tells part of the story, though: Altair also provides built-in tools to compute the lower and upper bounds of confidence intervals on the mean.</p><p>We can change the mark to area() here, and specify the lower and upper bounds of the area using y and y2, and use the ci0 and ci1 mark to plot the confidence interval of the estimate of the mean:</p><pre>alt.Chart(cars).mark_area(opacity=0.3).encode(<br>    x=&#39;Year:T&#39;,<br>    color=&#39;Origin&#39;,<br>    y=&#39;ci0(Miles_per_Gallon)&#39;,<br>    y2=&#39;ci1(Miles_per_Gallon)&#39;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*g0kUHNT603JFx0Kn3WyEtg.png" /></figure><h3>3. Compounding charts</h3><p>Creating multi-panel and layered charts is an essential property to have for a data visualization library. Altair provides a concise API for creating multi-panel and layered charts. Let’s explore a few of them:</p><ul><li><strong>Layering</strong></li><li><strong>Horizontal Concatenation</strong></li><li><strong>Vertical Concatenation</strong></li></ul><h4>Layering</h4><p>Layering lets you put layer multiple marks on a single Chart. One common example is creating a plot with both points and lines representing the same data. Let’s use the stocks data for this example:</p><pre>stocks = data.stocks()<br>stocks.head()<br><br>alt.Chart(stocks).mark_line().encode(<br>    x=&#39;date&#39;,<br>    y=&#39;price&#39;,<br>    color=&#39;symbol&#39;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*dqaMFlpLPEZhG77XjXfo6A.png" /><figcaption>Line chart</figcaption></figure><p>And here is the same plot with a circle mark:</p><pre>alt.Chart(stocks).mark_circle().encode(<br>    x=&#39;date:T&#39;,<br>    y=&#39;price:Q&#39;,<br>    color=&#39;symbol:N&#39;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*y332XwmZhRzWl9PWxLF54Q.png" /><figcaption>Circle Chart</figcaption></figure><p>We can layer these two plots together using the + Operator. One pattern we can use often is to create a <strong>base chart</strong> with the common elements and add together two copies with just a single change:</p><pre>base = alt.Chart(stocks).encode(<br>    x=&#39;date:T&#39;,<br>    y=&#39;price:Q&#39;,<br>    color=&#39;symbol:N&#39;<br>)<br><br>base.mark_line() + base.mark_circle()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*o6X7X5Sj5NgtgRymWUHi9w.png" /><figcaption>Layered chart with Circle and Line chart</figcaption></figure><h4>Horizontal Concatenation</h4><p>Just as we can layer charts on top of each other, we can concatenate horizontally using alt.hconcat, or equivalently the | operator:</p><pre>alt.hconcat(base.mark_line(), base.mark_circle())<br># Another way of writing the same thing<br># base.mark_line() | base.mark_circle()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*qoVCk1SIuqyoobLyDr4yZg.png" /><figcaption>Horizontal Concatenation</figcaption></figure><h4>Vertical Concatenation</h4><p>Vertical concatenation looks a lot like horizontal concatenation but uses either the alt.vconcat() function, or the &amp; operator:</p><pre>base.mark_line() &amp; base.mark_circle()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*Y6PnhMV-fLDKyFuFfrbZ2w.png" /></figure><h3>4. Grammar of interaction</h3><p>The grammar of interaction allows the building of interactive features of the plot from components. Using our scatter plot from above and adding some interaction to it.</p><h4>Interactivity and Selections</h4><p>Altair’s interactivity and grammar of selections are one of its unique features among available plotting libraries.</p><p>Just adding .interactive() fires up the Vega power, and the chart becomes interactable in the browser allowing it to zoom and pan.</p><pre>alt.Chart(cars).mark_point().encode(<br>    x=&#39;Horsepower&#39;,<br>    y=&#39;Miles_per_Gallon&#39;,<br>    color=&#39;Origin&#39;,<br>    shape=&#39;Origin&#39;<br>).interactive()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*BVAHE-hcdQ-SpD4ZJHQ19A.gif" /></figure><p>Let me walk you through the variety of selection types that are available, and begin to practice creating interactive charts and dashboards.</p><p>There are three basic types of selections available:</p><ul><li>Interval Selection: alt.selection_interval()</li><li>Single-Selection: alt.selection_single()</li><li>Multi Selection: alt.selection_multi()</li></ul><h4>Interval Selection</h4><p>As an example of a selection, let’s add an interval selection to a chart. We’ll start with our canonical scatter plot:</p><pre>interval = alt.selection_interval()<br><br>alt.Chart(cars).mark_point().encode(<br>    x=&quot;Miles_per_Gallon&quot;, <br>    y=&quot;Horsepower&quot;,<br>    color =&quot;Origin&quot;<br>).properties(<br>    selection = interval<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*-Du2XUzAUmKzBgQ-x9nrRg.gif" /></figure><p>The interval selection is a way you can click and drag; the encodings add properties to the selection. We can do selection in 2D as well as 1D. To make the chart more interesting, we can use conditional arguments for the selections, such as changing color using conditions.</p><pre>interval = alt.selection_interval(encodings=[&#39;x&#39;])<br><br>alt.Chart(cars).mark_point().encode(<br>    x=&quot;Miles_per_Gallon&quot;, <br>    y=&quot;Horsepower&quot;,<br>    color =alt.condition(interval,&quot;Origin&quot;,alt.value(&quot;lightgray&quot;))<br>).properties(<br>    selection = interval<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*0l5J8baBYERDKWfVnD0_oQ.gif" /></figure><p>We can stack the interactive charts using Compounding; the selection between them is also tied. Let’s encode the selection with different variables on the x-axis.</p><pre>interval = alt.selection_interval(encodings=[&#39;x&#39;,&#39;y&#39;])<br><br>chart = alt.Chart(cars).mark_point().encode(<br>    x=&quot;Miles_per_Gallon&quot;, <br>    y=&quot;Horsepower&quot;,<br>    color =alt.condition(interval,&quot;Origin&quot;,alt.value(&quot;lightgray&quot;))<br>).properties(<br>    selection = interval<br>)<br><br>chart | chart.encode(x=&#39;Acceleration&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*DGwggjI9AqwRaFouib1adA.gif" /></figure><h4>Tooltips</h4><p>When a user hovers over a mark, the tooltip displays relevant data and details from another visualization filtered to that mark. You can show related vizzes in tooltips to help your audience engage with the data at a different or deeper level while keeping them in the current context and maximizing the space available for the current view.</p><p>Considering the encodings in just the x-direction and adding tooltips we get more details about the different relationships in data points.</p><pre>interval = alt.selection_interval(encodings=[&#39;x&#39;])<br><br>chart = alt.Chart(cars).mark_point().encode(<br>    x=&quot;Miles_per_Gallon&quot;, <br>    y=&quot;Horsepower&quot;,<br>    color =alt.condition(interval,&quot;Origin&quot;,alt.value(&quot;lightgray&quot;)),<br>    tooltip =[&#39;Name&#39;, &#39;Origin&#39;, &#39;Horsepower&#39;, &#39;Miles_per_Gallon&#39;]<br>).properties(<br>    selection = interval<br>)<br><br>chart | chart.encode(x=&#39;Acceleration&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*JC3j1eq3efkYKtUmAZozmg.gif" /></figure><p>We can do even more sophisticated things with selections as well. For example, let’s make a histogram of the number of cars by Origin and stack it on our scatterplot:</p><pre>interval = alt.selection_interval()<br>base = alt.Chart(cars).mark_point().encode(<br>    y=&#39;Horsepower&#39;,<br>    color=alt.condition(interval, &#39;Origin&#39;, alt.value(&#39;lightgray&#39;)),<br>    tooltip=&#39;Name&#39;<br>).add_selection(<br>    interval<br>)<br>hist = alt.Chart(cars).mark_bar().encode(<br>    x=&#39;count()&#39;,<br>    y=&#39;Origin&#39;,<br>    color=&#39;Origin&#39;<br>).properties(<br>    width=800,<br>    height=80<br>).transform_filter(<br>    interval<br>)<br>scatter = base.encode(x=&#39;Miles_per_Gallon&#39;) | base.encode(x=&#39;Acceleration&#39;)<br>scatter &amp; hist</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*0wyDu994qWpPSgqSJJ2ANA.gif" /></figure><h3>5. Saving Altair Charts</h3><p>It will all be a waste if these cool interactive charts only run in a python notebook. Because Altair produces Vega-Lite specifications, it is relatively straightforward to export charts and publishes them on the web as Vega-Lite plots.</p><h4>HTML format</h4><p>All that is required is to load the Vega-Lite javascript library and pass it the JSON plot specification output by Altair. For convenience, Altair provides a Chart.save() method, which will save any chart to HTML.</p><p><strong>This HTML file can be transferred and loaded into any browser without the requirement to load the data.</strong></p><pre>base.save(&#39;chart.html&#39;)</pre><h4>JSON format</h4><p>The fundamental chart representation output by Altair is a JSON string format; one of the core methods provided by Altair is, which returns a JSON string that represents the chart content. Additionally, you can save a chart to a JSON file using Chart.save(), by passing a filename with a .json extension.</p><p>The JSON format can be useful for sharing and loading the Chart in a notebook. This imported chart can then be viewed easily.</p><pre>base.save(&#39;chart.json&#39;)</pre><p>The Altair charts can also be saved in PNG, SVG, and PDF format. To save an Altair chart object as a PNG, SVG, or PDF image, you can use</p><pre>chart.save(&#39;chart.png&#39;)<br>chart.save(&#39;chart.svg&#39;)<br>chart.save(&#39;chart.pdf&#39;)</pre><p><strong>Notebook to refer to for code and explanations:</strong> <a href="https://colab.research.google.com/drive/1Rxg87Pn9Crpd0Kg8VhHFdtxp4EWkYIqY?usp=sharing#scrollTo=9odJ7cqKHipQ">https://colab.research.google.com/drive/1Rxg87Pn9Crpd0Kg8VhHFdtxp4EWkYIqY?usp=sharing#scrollTo=9odJ7cqKHipQ</a></p><h3><strong>Final words</strong></h3><p>And there you have it — from basic data visualization to beautiful interactive visualizations in just a couple of minutes and a couple of lines of code. Altair requires some time to get used to the syntax, but that’s true for all visualization libraries.</p><p>At the end of the day, the visualizations look much better than the equivalent produced with Matplotlib and Seaborn.</p><p><em>But what about Plotly?</em> Well, that’s a topic for another time. Stay tuned for more content like this.</p><p>Thanks for reading.</p><h4>References:</h4><ol><li><a href="https://altair-viz.github.io/index.html">https://altair-viz.github.io/index.html</a></li><li><a href="https://www.practicaldatascience.org/html/plotting_altair_part1.html">https://www.practicaldatascience.org/html/plotting_altair_part1.html</a></li><li><a href="https://robinlinacre.medium.com/why-im-backing-vega-lite-as-our-default-tool-for-data-visualisation-51c20970df39">https://robinlinacre.medium.com/why-im-backing-vega-lite-as-our-default-tool-for-data-visualisation-51c20970df39</a></li><li><a href="https://www.nersc.gov/assets/Uploads/09-Python-Vis-with-Altair.pdf">https://www.nersc.gov/assets/Uploads/09-Python-Vis-with-Altair.pdf</a></li><li><a href="https://medium.com/codex/creating-presentable-data-visualization-with-altair-5a3286e697ab">https://medium.com/codex/creating-presentable-data-visualization-with-altair-5a3286e697ab</a></li><li><a href="https://github.com/altair-viz/altair">https://github.com/altair-viz/altair</a></li><li><a href="https://www.analyticsvidhya.com/blog/2021/10/exploring-data-visualization-in-altair-an-interesting-alternative-to-seaborn/">https://www.analyticsvidhya.com/blog/2021/10/exploring-data-visualization-in-altair-an-interesting-alternative-to-seaborn/</a></li><li><a href="https://www.datacamp.com/tutorial/altair-in-python">https://www.datacamp.com/tutorial/altair-in-python</a></li><li><a href="https://www.geeksforgeeks.org/introduction-to-altair-in-python/">https://www.geeksforgeeks.org/introduction-to-altair-in-python/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76de7837a87b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/a-crash-course-in-data-control-your-charts-like-an-expert-with-altair-76de7837a87b">A Crash Course in DATA: Control your charts like an expert with Altair</a> was originally published in <a href="https://medium.com/aiskunks">AI Skunks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combating Data Drift: The Fight for Model Accuracy]]></title>
            <link>https://medium.com/@dummahajan/combating-data-drift-the-fight-for-model-accuracy-2c619ee1e33a?source=rss-46f5fe7d5425------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c619ee1e33a</guid>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-drift]]></category>
            <dc:creator><![CDATA[Dushyant Mahajan]]></dc:creator>
            <pubDate>Fri, 10 Feb 2023 13:52:50 GMT</pubDate>
            <atom:updated>2023-02-10T14:00:33.965Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DJmWr0gKcGxRwGl1jySQhw.jpeg" /><figcaption>Source: Photo by <a href="https://unsplash.com/@antistalgia?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Gian Gomez</a> on <a href="https://unsplash.com/photos/MiFI1E23z2k?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Data drift is one of the biggest challenges that machine learning models face in today’s fast-paced world. It occurs when changes in the input data lead to model performance degradation and can result in poor performance or even model failure. In this article, we’ll take a closer look at what data drift is, the different types of data drift, and what measures you can take to mitigate its effects.</p><p><strong>Understanding Data Drift</strong></p><p>Data drift is a change in the input data that leads to model performance degradation. It can be caused by changes in the underlying data, such as new data points, changes in feature values, or changes in the target variable. Data drift can also be caused by changes in the environment, such as changes in user preferences or resource availability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pnLZKMWY2QCAkI8ejhCNtQ.png" /><figcaption>Source: <a href="https://www.evidentlyai.com/blog/machine-learning-monitoring-data-and-concept-drift">https://www.evidentlyai.com/blog/machine-learning-monitoring-data-and-concept-drift</a></figcaption></figure><p><strong>Types of Data Drift</strong></p><p>There are several types of data drift that can occur in machine learning:</p><ol><li><strong>Concept drift</strong><em>:</em> This occurs when the relationship between the input features and the output label changes over time.</li><li><strong>Virtual drift</strong>: This type of drift occurs when the model is deployed in a different context than it was trained in.</li><li><strong>Covariate shift</strong>: This occurs when the distribution of the input features changes over time, but the relationship between the input features and the output label remains the same.</li><li><strong>Prior probability shift</strong>: This occurs when the proportion of different classes in the data changes over time.</li><li><strong>Annotator drift</strong>: This happens when there is a change in the way the data is labeled or annotated.</li><li><strong>Data poisoning</strong>: This occurs when malicious actors deliberately introduce data that is designed to mislead the model.</li></ol><p>These types of data drift can occur alone or in combination and can cause a model to perform poorly or make inaccurate predictions.</p><p><strong>Measures to Mitigate Data Drift</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8VxYSnqxCjbRRnnu2syR8g.png" /><figcaption>Source: <a href="https://www.evidentlyai.com/blog/machine-learning-monitoring-data-and-concept-drift">https://www.evidentlyai.com/blog/machine-learning-monitoring-data-and-concept-drift</a></figcaption></figure><p>There are several measures you can take to mitigate the effects of data drift:</p><ol><li><strong>Regular retraining</strong>: One way to avoid data drift is to retrain the model on new data regularly.</li><li><strong>Data preprocessing</strong>: Data preprocessing techniques such as normalization, standardization, and feature scaling can help make the data more robust to changes in distribution.</li><li><strong>Data augmentation</strong>: This technique can be used to artificially generate more training data, making the model more robust to changes in the data distribution.</li><li><strong>Monitoring</strong>: Regular monitoring of the model’s performance on new data can help detect data drift early and take action before it becomes a problem.</li><li><strong>Online learning</strong>: Instead of retraining the model on new data, you can update the model incrementally as new data becomes available.</li><li><strong>Domain adaptation</strong>: This technique can help adapt a model trained on one dataset to work well on a different dataset.</li><li><strong>Annotator and data quality control</strong>: Establishing a good quality control process for data labeling and annotation can help prevent annotator drift.</li></ol><p><strong>Techniques for Detecting Data Drift</strong></p><p>There are several techniques currently available for detecting data drift in machine learning:</p><ol><li><strong>Data visualization tools</strong>: Tools such as scatter plots, histograms, and box plots can be used to visually inspect the data and identify changes in the distribution.</li><li><strong>Model performance monitoring</strong>: Regular monitoring of the model’s performance on new data can also help detect data drift.</li><li><strong>Drift detection methods</strong>: Algorithms specifically designed to detect changes in the data distribution, such as the chi-squared test, the Kolmogorov-Smirnov test, and the CUSUM test.</li><li><strong>Data quality control techniques</strong>: Techniques like data validation, outlier detection, and anomaly detection can help identify data drift early.</li><li><strong>Drift detection libraries</strong>: Libraries available in multiple programming languages, such as TorchDrift for PyTorch</li><li><strong>Auto-ML tools</strong>: Some auto-ML tools can automatically detect and handle data drift like Google AutoML and Amazon SageMaker</li></ol><p><strong>Conclusion</strong></p><p>Data drift is a silent killer of machine learning models, but with the right tools and techniques, it can be effectively addressed. Whether you are a seasoned machine learning expert or a newcomer to the field, it is essential to be aware of data drift and the steps you can take to mitigate its effects.</p><p>For further reading, I have included a list of extra resources in the article.</p><p><a href="https://labelstud.io/blog/data-labeling-the-unsung-hero-combating-data-drift/">https://labelstud.io/blog/data-labeling-the-unsung-hero-combating-data-drift</a>/</p><p><a href="https://arxiv.org/pdf/2004.05785.pdf">https://arxiv.org/pdf/2004.05785.pdf</a></p><p><a href="https://arxiv.org/pdf/2012.09258v2.pdf">https://arxiv.org/pdf/2012.09258v2.pdf</a></p><p><a href="https://towardsdatascience.com/detecting-semantic-drift-within-image-data-6a59a0e768c6">https://towardsdatascience.com/detecting-semantic-drift-within-image-data-6a59a0e768c6</a></p><p><a href="https://torchdrift.org/index.html">https://torchdrift.org/index.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c619ee1e33a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>