<?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 samuel chazy on Medium]]></title>
        <description><![CDATA[Stories by samuel chazy on Medium]]></description>
        <link>https://medium.com/@samuelchazy?source=rss-53a14a703de9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gXnFNNYVlRhRyA6wJ_qIrA@2x.jpeg</url>
            <title>Stories by samuel chazy on Medium</title>
            <link>https://medium.com/@samuelchazy?source=rss-53a14a703de9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:13:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samuelchazy/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[OpenAI GPT-OSS Structure & Experimentation]]></title>
            <link>https://medium.com/@samuelchazy/openai-gpt-oss-structure-experimentation-861eb5798ed7?source=rss-53a14a703de9------2</link>
            <guid isPermaLink="false">https://medium.com/p/861eb5798ed7</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[samuel chazy]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 04:33:12 GMT</pubDate>
            <atom:updated>2025-08-25T04:33:12.930Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Vtre7hZ-hCbamxo0QZY5A.jpeg" /></figure><p>OpenAI launched gpt-oss-120b &amp; gpt-oss-20b, two open source reasoning models under the Apache 2.0 license. Those models are designed to be used within agentic workflows, are customizable, and they provide chain-of-thought (CoT), and support Structured Outputs.</p><h3>Architecture</h3><p>Both models are autoregressive Mixture-of-Experts (MoE), Decoder-only Transformers with Pre-LN (RMSNorm before each sub-block).</p><ul><li>gpt-oss-120b, consists of 36 layers (116.8B total parameters and 5.1B active parameters per token per forward pass).</li><li>gpt-oss-20b consists of 24 layers (20.9B total and 3.6B active parameters per token per forward pass).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SdjO4lsDHbUhtGl63HiueA.png" /><figcaption>The table shows a comparison between the components of the two models.</figcaption></figure><h3>Model components</h3><ol><li><strong>Layers:</strong> Number of hidden layers (Transformer blocks).</li><li><strong>MOE (Mixture-of-Experts):</strong> Count of MLP experts inside each MoE feed-forward block.</li><li><strong>Total Parameters:</strong> Total count of trainable weights in the model.</li><li><strong>Active Parameters:</strong> The number of parameters used per forward pass.</li><li><strong>Attention mechanism:</strong> Weights in the attention sub-layers (Query/Key/Value projections and output projection)</li><li><strong>MLP (Multi-Layer Perceptron):</strong> Weights in the feed-forward sublayers.</li><li><strong>Embed + Unembed:</strong> Combined size of the token embedding matrix (Mapping tokens to vectors, and back to logits).</li><li><strong>Checkpoint Size:</strong> The disk space needed to save the model’s weights.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9bRmBBqAzKdWE9yqALBAg.png" /><figcaption>Standard transformer vs GPT-OSS transformer</figcaption></figure><p><strong>Let’s dive into the transformer structure:</strong></p><h4>RMSNorm</h4><p>Root Mean Square Normalization (RMSNorm) is a normalization technique used in Transformer blocks to stabilize training and improve computational efficiency. It simplifies the standard Layer Normalization by removing the mean-centering operation, focusing on scaling invariance based on the root mean square of the inputs.</p><h4>Quantization</h4><ul><li>The model is post-trained with a quantization method to MXFP4 format (Mixed Exponent Floating Point 4) =&gt; weights are quantized to 4.25 bits per parameter to reduce the memory footprint.</li><li>This enables the 120b model to fit on a single 80GB GPU and the 20b model to run on systems with as little as 16GB memory.</li></ul><p>However, while this reduction is valuable on the memory side, in my opinion this is one of the reasons why GPT-OSS models under-perform compared to the closed-source OpenAI GPT models. Quantization to a 4. bit format reduces the precision (number of bits per parameter), and thus reduces the accuracy of the model.</p><h4>MOE (Mixture-of-Experts) in GPT-OSS</h4><p><strong>Experts per block:</strong></p><ul><li>gpt-oss-120b: 128 experts per MoE block</li><li>gpt-oss-20b: 32 experts per MoE block</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNLm9AxlKan8uXSLwD5Ixg.png" /></figure><p><strong>Routing mechanism:</strong></p><p>A standard linear router projection is applied to the input representation of each token.</p><ul><li>The router selects the Top-4 experts per token.</li><li>Each selected expert processes the token independently.</li><li>The outputs are combined using weights given by the softmax over the router logits, but restricted to the selected experts only.</li></ul><p><strong>Activation function:</strong></p><p>The MoE blocks use the gated SwiGLU activation, which improves stability compared to standard ReLU or GELU activation.</p><p><strong>Efficiency:</strong></p><p>Since only 4 experts are active per token, the active parameters per forward pass are smaller than the total parameters of the model.</p><h4>Attention mechanism</h4><p>The architecture alternates attention blocks between two patterns:</p><ul><li>banded window attention: Each token only attends to nearby tokens, bandwidth being 128 tokens, which saves computation compared to full self-attention.</li><li>Fully dense attention: Each token attends to all tokens in the sequence, preserving full-context awareness.</li></ul><p>This provides a balance between local efficiency (short-term dependencies) and global awareness (long-range dependencies).</p><p><strong>Head configuration:</strong></p><ul><li>Each layer uses 64 query heads, each of dimension 64.</li><li>Instead of computing 64 independent key-value heads, the model applies Grouped Query Attention with 8 key-value heads.</li><li>Multiple Q-heads share the same KV-heads.</li><li>This reduces memory footprint and speeds up inference.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eq47AzFWiLF0mnFrjHNKDg.png" /></figure><h4>RoPE (Rotary Position Embeddings)</h4><ul><li>Unlike added traditional positional embeddings, RoPE encodes positional information by rotating the query and key vectors in vector space.</li><li>This rotation depends on the relative positions of tokens.</li><li>RoPE allows relative positions to be encoded naturally and generalizes better to longer contexts.</li></ul><h4>YaRN (Yet another RoPE extension)</h4><p>YaRN Extends the usable context length of the Transformer beyond what standard RoPE supports.</p><ul><li>It pushes the dense-attention context window to 131,072 tokens (131K).</li><li>This allows the model to process entire books or long transcripts in a single forward pass.</li></ul><h4>Learned Softmax Bias (“Off-by-One Attention”)</h4><ul><li>Each head has a learned bias term added to the softmax function.</li><li>This allows the model to completely ignore specific tokens, similar to Off-by-one attention (shifting indices to adjust focus), by biasing them towards “don’t attend” or zero.</li><li>This acts like a lightweight gating mechanism.</li></ul><h4>Tokenizer</h4><ul><li>The model utilizes o200k_harmony tokenizer, which is open sourced in the TikToken library.</li><li>This is based on the Byte Pair Encoding (BPE) which extends the o200k tokenizer used for other OpenAI models.</li></ul><h3>Pretraining</h3><p><strong>Data:</strong><br>The models are trained on a text-only dataset with trillions of tokens, with a focus on STEM, coding, and general knowledge.</p><p><strong>Training:</strong></p><ul><li>The gpt-oss models are trained on NVIDIA H100 GPUs using the PyTorch framework.</li><li>The training run for gpt-oss-120b required 2.1 million H100-hours to complete, with gpt-oss-20b needing almost 10x fewer.</li><li>Example: Total number of hours for the 120b model is 2,100,000 hours / 24 hours = 87,500 days / 1000 GPU = 87.5 training days.</li><li>The number of hours was reduced because of the use of MXFP4 format, so imagine if the model was trained on 32-bit floating-point!</li><li>Both models leverage the Flash Attention algorithms. Instead of saving every step, Flash Attention processes data in chunks to reduce the memory requirements and accelerate training. This works better for long sequences.</li></ul><h3>Post-Training for Reasoning and Tool Use</h3><p>The models are post-trained using similar Chain-of-Thought (CoT) &amp; Reinforcement Learning (RL) techniques as OpenAI o3. This procedure teaches the models how to reason and solve problems.</p><h4>1- Harmony Chat Format</h4><p>OpenAI uses a custom chat format known as the harmony chat format.</p><ul><li>This format provides special tokens to delineate message boundaries and uses keyword arguments.</li><li>Example: System &gt; Developer &gt; User &gt; Assistant &gt; Tool.</li></ul><p>The format also introduces “channels” to indicate the intended visibility of each message:</p><ul><li>Examples: analysis for CoT tokens, commentary for function tool calling and final for answers shown to users.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R0QcN7z1Dngn-hvYDl1qRQ.png" /></figure><h4>2- Variable Effort Reasoning Training</h4><ul><li>The models are trained to support three reasoning levels: low, medium, and high.</li><li>These levels are configured in the system prompt by inserting keywords such as “Reasoning: low”.</li></ul><h4>3- Agentic Tool Use</h4><ul><li>A browsing tool, that allows the model to call search and open functions to interact with the web. This aids factuality and allows the models to fetch info beyond their knowledge cutoff.</li><li>A python tool, which allows the model to run code in a stateful Jupyter notebook environment.</li><li>Arbitrary developer functions, where one can specify function schemas in a Developer message similar to the OpenAI API.</li></ul><h3>GPT-OSS Inference</h3><p>If you have access to a GPU, then you can implement the below code:</p><pre>from transformers import pipeline<br>import torch<br><br>model_id = &quot;openai/gpt-oss-120b&quot;<br><br>pipe = pipeline(<br>    &quot;text-generation&quot;,<br>    model=model_id,<br>    torch_dtype=&quot;auto&quot;,<br>    device_map=&quot;auto&quot;,<br>)<br><br>messages = [<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Explain quantum mechanics clearly and concisely.&quot;},<br>]<br><br>outputs = pipe(<br>    messages,<br>    max_new_tokens=256,<br>)<br>print(outputs[0][&quot;generated_text&quot;][-1])</pre><p>If you don’t have access to a GPU, and you want to use a CPU, then you can use Ollama to run the smaller version on your laptop. However, you will still need a powerful PC to be able to run it. Most recent laptops can usually run models up to 13 billion parameters.</p><p>You can download and run Ollama using the following link:</p><p><a href="https://ollama.com/">https://ollama.com/</a></p><p>Once, Ollama is up and running, you can run the below code from the terminal to download gpt-oss:20b:</p><pre>ollama pull gpt-oss:20b</pre><p>You can then run the below code to work with GPT-OSS using langchain after installing the libraries:</p><pre>from langchain_ollama.llms import OllamaLLM<br>from langchain_core.prompts import ChatPromptTemplate<br><br>model = OllamaLLM(<br>    model=&quot;gpt-oss:20b&quot;,<br>    temperature=0.7,<br>)<br>template = &quot;&quot;&quot;<br>Question: {question}<br>Answer: Explain {question}.<br>&quot;&quot;&quot;<br>chain = prompt | model<br><br>response = chain.invoke({&quot;question&quot;: &quot;What is super intelligence?&quot;})<br>print(response)</pre><h3>References</h3><p>You can read the full model card:</p><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//cdn.openai.com/pdf/419b6906-9da6-406c-a19d-1bb078ac7637/oai_gpt-oss_model_card.pdf&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f923256b35aa59aabd1e8dbcd65b36f/href">https://medium.com/media/9f923256b35aa59aabd1e8dbcd65b36f/href</a></iframe><p>You can also download the open weights of the model:</p><p><a href="https://github.com/openai/gpt-oss">GitHub - openai/gpt-oss: gpt-oss-120b and gpt-oss-20b are two open-weight language models by OpenAI</a></p><p>Finally, you can use HuggingFace gpt-oss models:</p><p><a href="https://huggingface.co/collections/openai/gpt-oss-68911959590a1634ba11c7a4">gpt-oss - a openai Collection</a></p><p>My final note is that these open-source models advance the democratization of AI knowledge by enabling experimentation and iterative improvement by the community. A key limitation however remains, which is the computational footprint: Model inference needs multiple CPU cores and significant memory or in most cases GPU resources, which constrains accessibility for users with limited hardware.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=861eb5798ed7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhanced LLM Tabular Reasoning with Chain-of-Table for CSV Files]]></title>
            <link>https://ai.plainenglish.io/enhanced-tabular-reasoning-with-chain-of-table-for-csv-files-211abdbc728e?source=rss-53a14a703de9------2</link>
            <guid isPermaLink="false">https://medium.com/p/211abdbc728e</guid>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[groq]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[tabular-data]]></category>
            <dc:creator><![CDATA[samuel chazy]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 05:43:13 GMT</pubDate>
            <atom:updated>2024-06-11T18:12:50.035Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVAvA3Q_qzzwGGifXjeW5Q.png" /><figcaption>Figure 1</figcaption></figure><blockquote>Figure 1: Comparison of generic reasoning, program-aided reasoning, and Chain-of-Table in accurately answering questions based on a complex table.</blockquote><p><strong>Paper</strong>: arXiv:2401.04398v1 [cs.CL] 9 Jan 2024, <strong>ArXiv link</strong>: <a href="https://arxiv.org/abs/2401.04398">https://arxiv.org/abs/2401.04398</a></p><p>Table of contents:</p><ul><li>I- Introduction</li><li>II- Idea</li><li>III- Constructors</li><li>IV- Results</li><li>V- Python implementation</li><li>VI- Conclusion</li></ul><h3>I- Introduction</h3><p>Table-based reasoning with large language models is an emerging field for improving table understanding tasks, such as table-based question answering and fact verification. Unlike generic reasoning, table-based reasoning requires the extraction of underlying semantics from both free-form questions and semi-structured tabular data.</p><p>In this context, LLMs can be guided using in-context learning to iteratively generate operations and update the table, thereby creating a tabular reasoning chain. This approach allows LLMs to dynamically plan the next operation based on the results of the previous ones. The continuous evolution of the table forms a chain, which represents the reasoning process for a given tabular problem. This chain carries structured information of the intermediate results, enabling more accurate and reliable predictions.</p><p>In recent years, several approaches have been proposed to address the problem of table understanding by training language models. A series of works on prompting techniques, such as Chain-of-Thought and Tree-of-Thought, have further improved the reliability of LLMs by designing reasoning chains. While different works have explored the potential of LLMs in solving table-based problems, these approaches often represent reasoning steps in free-form text, which are not ideally suited for handling complex tables.</p><h3>II- Idea</h3><p>The Chain-of-Table methodology conducts step-by-step reasoning through sequential tabular operations, forming a chain of tables. Each table in this chain represents an intermediate result, transformed through specific tabular operations. This procedure mirrors the reasoning process found in the Chain-of-Thought techniques.</p><p>A set of table operations is defined, including actions such as adding columns, selecting rows, and grouping, which are commonly used in SQL and DataFrame development. The LLM is prompted to perform step-by-step reasoning. In each step, the LLM dynamically generates the next operation along with its required arguments and then executes the operation on the table programmatically. This operation can either enrich the table by adding detailed intermediate results or condense it by removing irrelevant information. Visualizing these intermediate results is essential for making accurate predictions. The transformed table is then passed back for the next step. This iterative process continues until an ending state is achieved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aWbP5dmnlKht_3Av1MLh6g.png" /><figcaption>Algorithm 1</figcaption></figure><blockquote>Algorithm 1: The LLM iteratively selects an operation f based on the question Q, the latest table state T, and the operation chain, generates the necessary arguments, executes the operation to transform the table, tracks the operations, and continues until the ending tag [E] is generated, then uses the final table to predict the answer.</blockquote><p>By structuring the reasoning process through these tabular operations, the Chain-of-Table enhances the LLM’s capability to handle complex tables, leading to more accurate and reliable predictions.</p><h3>III- Constructors</h3><p>Let us see how this Chain-of-Table is constructed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_7Y26-Xk96ze5YQM2V8JUA.png" /><figcaption>Figure 2</figcaption></figure><blockquote>Figure 2: Illustration of DynamicPlan (sampling the next operation) and GenerateArgs (generating arguments for the operation) in the Chain-of-Table methodology.</blockquote><h4>A- Dynamic Planning</h4><p>Chain-of-Table instructs the LLM to dynamically plan the next operation using in-context learning. As illustrated in Figure 2(a), the DynamicPlan involves three key components:</p><ul><li>Most Recent Intermediate Table (T): The current state of the table after previous operations.</li><li>History of Previous Operations (chain): A record of the operations performed so far.</li><li>Question (Q): The query or problem statement guiding the process.</li></ul><p>Given these components (T, chain, Q), the LLM selects the next operation (f) from the operation pool. This dynamic planning allows the LLM to build a tabular reasoning chain step by step.</p><h4>B- Argument Generation</h4><p>The next step, GenerateArgs, involves generating arguments for the table operation selected by the DynamicPlan. As shown in Figure 2(b), GenerateArgs consists of three main components:</p><ul><li>Most Recent Intermediate Table (T): The current state of the table.</li><li>Selected Operation with its Arguments (args): The operation chosen by DynamicPlan along with its necessary arguments.</li><li>Question (Q): The guiding query.</li></ul><p>Simple regular expressions are used to accommodate the varying number of arguments required by different operations. Finally, Python is used to execute the operation and generate the corresponding intermediate tables.</p><h4>C- Final Query</h4><p>Through the processes of dynamic planning and argument generation, a chain of operations is created, representing the tabular reasoning steps. These operations produce intermediate tables that store and present the results of each step to the LLM. Consequently, the output table from this chain of operations contains comprehensive information about the intermediate phases of tabular reasoning. This output table is then used to formulate the final query.</p><h3>IV- Results</h3><p>Chain-of-Table iteratively generates operations that act as proxies for tabular reasoning steps. These operations produce and present tailored intermediate tables to the LLM, conveying essential intermediate thoughts. With the support of Chain-of-Table, the LLM can reliably reach the correct answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tq5HY5iehXxvl7Sl6A2RGQ.png" /><figcaption>Figure 3</figcaption></figure><blockquote>Figure 3: The tabular reasoning process in Chain-of-Table involves dynamically planning an operation chain and accurately storing intermediate results in the transformed tables. These intermediate tables serve as a tabular thought process that guides the LLM to land on the correct answer more reliably.</blockquote><h3>V- Python implementation</h3><p>Let us implement a basic chain-of-table code in Python to achieve the desired results:</p><p><strong>A- Let us import all the necessary libraries:</strong></p><pre>from langchain_groq import ChatGroq<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_core.runnables import RunnablePassthrough, RunnableParallel<br>from langchain_core.output_parsers import StrOutputParser<br>import os<br>import pandas as pdDefine Groq API key and Llama model name</pre><p><strong>B- We can get a dataset about students’ results from Kaggle:</strong></p><p><a href="https://www.kaggle.com/datasets/bhavikjikadara/student-study-performance">Student Study Performance</a></p><pre># Import and Read CSV table<br><br># Path to the uploaded CSV file<br>file_path = &#39;./study_performance.csv&#39;<br><br># Read the CSV file into a DataFrame<br>T = pd.read_csv(file_path)<br>T.head(2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*skmxyF6UETzekzDgU7nxuw.png" /><figcaption>Dataset T</figcaption></figure><p><strong>C- We will use Groq from X and Llama3 from Meta as our LLM:</strong></p><pre># Define Groq API key and Llama model name<br>groq_api_key = os.environ[&quot;GROQ_API_KEY&quot;]<br>model_name = &quot;llama3-70b-8192&quot;<br>llm = ChatGroq(temperature=0.5, groq_api_key=groq_api_key, model_name=model_name)</pre><p><strong>D- Let us define the required operations, tools, and functions:</strong></p><pre># Define operations and their parameters<br>operations = {<br>    &quot;filter_column&quot;: {<br>        &quot;column&quot;: &quot;{column}&quot;,<br>        &quot;operator&quot;: &quot;{operator}&quot;,<br>        &quot;value&quot;: &quot;{value}&quot;<br>    }<br>}</pre><pre># Set the tools<br><br>def DynamicPlan(Q_, operations_):<br>    # Determine the operation based on the question<br>    for operation_name, params in operations_.items():<br>        if params[&quot;column&quot;] in Q_ and params[&quot;operator&quot;] in Q_:<br>            return operation_name<br>    <br>    return [&#39;NA&#39;]<br><br>def GenerateArgs(Q_, dynamic_plan_, operations_):<br>    # Generate arguments based on the operation<br>    if dynamic_plan_ in operations:<br>        column_ = operations_[dynamic_plan_][&quot;column&quot;]<br>        operator_ = operations_[dynamic_plan_][&quot;operator&quot;]<br>        value_ = Q_.split(operator_)[1].strip()<br>        return {&quot;column&quot;: column_, &quot;operator&quot;: operator_, &quot;value&quot;: float(value_)}<br>    <br>    return [&#39;NA&#39;]</pre><pre># Define the necessary functions<br><br>def parse_condition(Q_):<br>    if &quot;&gt;&quot; in Q_:<br>        column_, value_ = Q_.split(&quot;&gt;&quot;)<br>        return column_.strip(), &quot;&gt;&quot;, value_.strip()<br>    elif &quot;&lt;&quot; in Q_:<br>        column_, value_ = Q_.split(&quot;&lt;&quot;)<br>        return column_.strip(), &quot;&lt;&quot;, value_.strip()<br>    <br>    return None, None, None<br><br>def filter_rows_by_column(df, args):<br>    column_, operator_, value_ = args[&quot;column&quot;], args[&quot;operator&quot;], args[&quot;value&quot;]<br>    if operator_ == &quot;&gt;&quot;:<br>        return df[df[column_] &gt; value_]<br>    elif operator_ == &quot;&lt;&quot;:<br>        return df[df[column_] &lt; value_]<br>    <br>    return df<br><br>def Query(T_, Q_):<br>    # If the question asks for the count of rows, return the count<br>    if &quot;count&quot; in Q_:<br>        return len(T_)<br>    # If the question asks for a summary of a specific column, return the summary<br>    elif &quot;summary&quot; in Q_:<br>        column_ = Q_.split(&quot;summary of &quot;)[1].strip()<br>        if column_ in T_.columns:<br>            return T_[column].describe()<br>    else:<br>        return T_</pre><pre># Build the chain of table<br><br>def Chain_of_Table(T_, Q_, operations_):<br>    chain_ = [([&#39;B&#39;], None)]<br>    while True:<br>        f_ = DynamicPlan(Q_, operations_)<br>        if f_ == [&#39;NA&#39;]:<br>            break<br>        args = GenerateArgs(Q_, f_, operations_)<br>        T_ = filter_rows_by_column(T_, args)<br>        chain_.append((f_, args))<br>    A_hat = Query(T_, Q_)<br>    return A_hat<br><br># reference the columns in the dataset<br>columns = T.columns</pre><p><strong>E- Let us build a prompt template and a chain constructor:</strong></p><pre># Set the table and prompt template<br><br>def build_table_template(Q_, T_, column_, operator_, value_):<br>    template = f&quot;&quot;&quot;<br>    You are given a dataset {T_} with the following columns: {columns}.<br>    You need to answer the question: &quot;{Q_}&quot;.<br>    Follow these steps to process the dataset {T_} and answer the question {Q_}:<br>    <br>    1. Determine the operations required based on the question {Q_}.<br>    2. Generate the arguments for the operations.<br>    3. Perform the operations and the arguments on the dataset {T}.<br>    4. Repeat the process until the final answer is obtained.<br>    <br>    Steps:<br>    1. Determine the operations : filter rows where {column_} {operator_} {value_}.<br>    2. Generate arguments: column=&quot;{column_}&quot;, operator=&quot;{operator_}&quot;, value={value_}.<br>    3. Perform the operations : filter rows based on the generated arguments.<br>    4. Filter the dataset {T_} by the final answer.<br>    5. Print the final answer<br><br>    -------------------------------------------------------------------------------<br>    Answer:<br>    &quot;&quot;&quot;<br>    return template<br><br>def format_prompt(table_template_, columns_, T_, question_):<br>    prompt = table_template_.format(<br>        columns=columns_,<br>        data=T_,<br>        question=question_,<br>        column=&#39;{column}&#39;,<br>        operator=&#39;{operator}&#39;,<br>        value=&#39;{value}&#39;<br>    )<br>    prompt_template_ = ChatPromptTemplate.from_template(template=prompt,<br>                       tools={<br>                              &#39;DynamicPlan&#39;: DynamicPlan,<br>                              &#39;GenerateArgs&#39;: GenerateArgs<br>                       })<br>    return prompt_template_</pre><pre># Build the chain constructor<br><br>def build_chain(template):<br>    chain_constructor = (RunnableParallel(<br>        {&quot;query&quot;: RunnablePassthrough(),<br>         })<br>             | template<br>             | llm<br>             | StrOutputParser()<br>        )<br>    return chain_constructor</pre><p><strong>F- Example 1: Generate an answer from the query</strong></p><pre>Q = &quot;students with a score &gt; 295?&quot;<br><br>column, operator, value = parse_condition(Q)<br>table_template = build_table_template(Q, T, column, operator, value)<br>prompt_template = format_prompt(table_template, columns, T, Q)<br>chain = build_chain(prompt_template)<br><br>all_results = chain.invoke({&quot;question&quot;: Q})<br>print(all_results)</pre><p><strong>LLM response:</strong></p><blockquote>To answer the question “students with a score &gt; 295?”, we need to calculate the total score for each student and then filter the dataset to get the students with a score greater than 295.</blockquote><blockquote>Here’s the Python code to do this:<br><br>import pandas as pd</blockquote><blockquote># assume ‘df’ is the given dataset</blockquote><blockquote># calculate the total score for each student<br>df[‘total_score’] = df[‘math_score’] + df[‘reading_score’] + df[‘writing_score’]</blockquote><blockquote># filter the dataset to get the students with a score &gt; 295<br>students_with_score_gt_295 = df[df[‘total_score’] &gt; 295]</blockquote><blockquote># print the final answer<br>print(students_with_score_gt_295)<br><br>This will output the filtered dataset with the students who have a total score greater than 295.</blockquote><blockquote>Note: The `total_score` column is calculated by adding the math, reading, and writing scores for each student. Then, the dataset is filtered to get the students with a total score greater than 295.</blockquote><p><strong>Let us test the LLM response:</strong></p><pre>df = T.copy()<br>df[&#39;total_score&#39;] = (df[&quot;math_score&quot;] + df[&quot;reading_score&quot;] + df[&quot;writing_score&quot;])<br><br>students_with_score_gt_295 = df[df[&#39;total_score&#39;] &gt; 295]<br>print(students_with_score_gt_295)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wafjFhEz9wfIsf5KxtkENQ.png" /><figcaption>response for example 1</figcaption></figure><p><strong>G- Example 2: Generate an answer from the query</strong></p><pre>Q = &quot;race_ethnicity of students with a total score &gt; 250 and test_preparation_course = completed? and gender = male?&quot;<br><br>column, operator, value = parse_condition(Q)<br>table_template = build_table_template(Q, T, column, operator, value)<br>prompt_template = format_prompt(table_template, columns, T, Q)<br>chain = build_chain(prompt_template)<br><br>all_results = chain.invoke({&quot;question&quot;: Q})<br>print(all_results)</pre><p><strong>LLM response:</strong></p><blockquote>Let’s go through the steps to answer the question.</blockquote><blockquote>**Step 1: Determine the operations**<br>We need to filter the dataset based on the conditions:</blockquote><blockquote>* `test_preparation_course` equals “completed”<br>* `gender` equals “male”<br>* Total score (i.e., `math_score + reading_score + writing_score`) is greater than 250</blockquote><blockquote>**Step 2: Generate arguments**<br>We need to generate the arguments for the operations:</blockquote><blockquote>* `test_preparation_course` equals “completed”<br>* `gender` equals “male”<br>* Total score is greater than 250</blockquote><blockquote>**Step 3: Perform the operations**<br>Let’s perform the operations on the dataset:<br><br>import pandas as pd</blockquote><blockquote># assume the dataset is in a Pandas DataFrame called df</blockquote><blockquote># calculate the total score<br>df[‘total_score’] = df[‘math_score’] + df[‘reading_score’] + df[‘writing_score’]</blockquote><blockquote># filter the dataset based on the conditions<br>filtered_df = df[(df[‘test_preparation_course’] == ‘completed’) &amp;<br> (df[‘gender’] == ‘male’) &amp;<br> (df[‘total_score’] &gt; 250)]</blockquote><blockquote># extract the race_ethnicity column from the filtered dataset<br>race_ethnicity = filtered_df[‘race_ethnicity’]<br><br>**Step 4: Repeat the process until the final answer is obtained**<br>We have already obtained the final answer, which is the `race_ethnicity` column of the filtered dataset.</blockquote><blockquote>**Final answer:**<br>The race_ethnicity of students with a total score &gt; 250 and test_preparation_course = completed and gender = male is:<br><br>print(race_ethnicity)<br><br>This will output the race_ethnicity values of the students who meet the conditions.</blockquote><p>Let us test the LLM response:</p><pre>filtered_df = df[(df[&#39;test_preparation_course&#39;] == &#39;completed&#39;) &amp;<br>                  (df[&#39;gender&#39;] == &#39;male&#39;) &amp;<br>                  (df[&#39;total_score&#39;] &gt; 250)]<br><br>race_ethnicity = filtered_df[&#39;race_ethnicity&#39;]<br>print(race_ethnicity)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGfXUgj5M-tIb8gvsjrzjg.png" /><figcaption>response for example 2</figcaption></figure><h3>VI- Conclusion</h3><p>The Chain-of-Table framework enhances the capabilities of large language models in handling table-based reasoning tasks. By iteratively generating operations that transform the tables step-by-step, Chain-of-Table creates a structured reasoning process that guides the LLM towards accurate and reliable predictions.</p><p>The method dynamically plans operations and generates necessary arguments, forming a coherent chain of intermediate tables. These tables serve as visual representations of the reasoning process, enabling the LLM to better understand the underlying semantics of the data. The iterative approach ensures that each step contributes logically to solving the problem, leading to more precise outcomes.</p><p>The code implementation of Chain-of-Table is tested and works as expected, achieving good results. It is important to note that repeating the same question many times using this LLM and this technique, produces the same answers, which means that the system achieves consistency using this method. The framework’s ability to decompose complex tabular reasoning into manageable steps, coupled with the visualization of intermediate results, makes it a good tool for table understanding tasks.</p><blockquote><strong><em>For more information and to explore how my data science consulting services can benefit your company, please visit my website at </em></strong><a href="http://samuelchazy.com/"><strong><em>samuelchazy.com</em></strong></a></blockquote><blockquote><em>Explore my LLM website, offering a unique opportunity to interact with and analyze any document: </em><a href="https://gptdocanalyzer.com/"><em>https://gptdocanalyzer.com/</em></a></blockquote><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=211abdbc728e" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/enhanced-tabular-reasoning-with-chain-of-table-for-csv-files-211abdbc728e">Enhanced LLM Tabular Reasoning with Chain-of-Table for CSV Files</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moment: A Family of Open Time-Series Foundation Models]]></title>
            <link>https://ai.plainenglish.io/moment-a-family-of-open-time-series-foundation-models-80f5135ca35b?source=rss-53a14a703de9------2</link>
            <guid isPermaLink="false">https://medium.com/p/80f5135ca35b</guid>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[samuel chazy]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 05:59:39 GMT</pubDate>
            <atom:updated>2024-03-05T14:09:14.218Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iSdhTTTfYYXVEQhDDfjQgA.png" /><figcaption>Time-series Pile data splits</figcaption></figure><p>Pre-training large models on time-series data is challenging because of the absence of a large and cohesive public time-series repository. To address these challenges, MOMENT team compiled a large and diverse collection of public time-series, called the Time-series Pile to unlock large-scale multi-dataset pre-training. The code is publicly available at anonymous:</p><p><a href="https://anonymous.4open.science/r/BETT-773F/README.md">https://anonymous.4open.science/r/BETT-773F/README.md</a></p><h3><strong>Time-series analysis spans across a wide array of applications, from weather forecasting to health monitoring via electrocardiograms.</strong></h3><p>In this sense, MOMENT is:</p><ul><li>The first family of open-source, large pre-trained time-series models.</li><li>Designed to serve foundational roles across various time-series analysis tasks: forecasting, classification, anomaly detection, and imputation.</li><li>Includes high-capacity transformer models, pre-trained on diverse datasets via a masked time-series prediction task.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gg0BeSDXfGui80cKfv0poA.png" /><figcaption>MOMENT can solve multiple time-series analysis tasks</figcaption></figure><h3>Background and Insights</h3><p>Transformers have gained momentum in time-series tasks, but the self-attention mechanism introduces challenges, especially as complexity scales with input size. MOMENT leverages masked pre-training, a self-supervised learning approach, where models learn to reconstruct masked sections of their input. This technique is particularly suited to forecasting and imputation tasks, effectively predicting missing or future data points.</p><h3>Adapting Language Models for Time-Series</h3><p>MOMENT explores how to adapt large language models (LLMs) for time-series analysis through:</p><ul><li>Cross-Modality Modeling: Time-series transformers can model sequences across various modalities.</li><li>Random Initialization Benefits: Starting with random weights is more effective than using language model weights.</li><li>Superior Time-Series Pre-Training: Directly pre-trained models outperform LLM-based models across tasks and datasets.</li></ul><h3>Architectural Foundations of MOMENT</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hzQy-kMusyu7c5u2lOVarA.png" /><figcaption>Overview of MOMENT architecture</figcaption></figure><p>A time-series is broken into disjoint fixed-length sub-sequences called patches, and each patch is mapped into a D-dimensional patch embedding. During pre-training, patches are masked uniformly at random by replacing their patch embeddings using a special mask embedding [MASK]. The goal of pre-training is to learn patch embeddings which can be used to reconstruct the input time-series using a light-weight reconstruction head.</p><p><strong>1- Design Enhancements</strong></p><ul><li>Retains and refines original Transformer architecture.</li><li>Key modifications: Adjusted Layer Norm placement, removed additive bias, and included relational positional embedding.</li></ul><p><strong>2- Handling Time-Series Variability</strong></p><ul><li>Standardized input length: Adapts longer and shorter series to fit a fixed length.</li><li>Independent channel modeling: Effective for multivariate time-series analysis.</li></ul><h3>Broad Applications of MOMENT</h3><p>MOMENT demonstrates flexibility across:</p><ul><li><strong>Forecasting:</strong> Achieves near state-of-the-art in long-horizon forecasting; identifies improvement opportunities in zero-shot short-horizon forecasting.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQEvla68t-4JP19xvDK1Pw.png" /><figcaption>Long-term forecasting performance</figcaption></figure><ul><li><strong>Classification:</strong> Excels without task-specific fine-tuning.</li><li><strong>Anomaly Detection:</strong> Outperforms on multiple datasets.</li><li><strong>Imputation:</strong> Achieves lowest reconstruction error with linear probing.</li></ul><h3>Core Learning from MOMENT</h3><h4>1- Characteristics Capturing:</h4><ul><li>Principal components of the embeddings of synthetically generated sinusoids suggest that MOMENT can capture subtle trend, scale, frequency, and phase information.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eXDWuMVTOn8yNs4syDh0_g.png" /><figcaption>What is MOMENT learning?</figcaption></figure><h4>2- Representation Learning:</h4><ul><li>Distinguishes distinct representations for different classes, even without labels.</li></ul><h4>3- Advancements Through Large Time-Series Models</h4><ul><li><strong>Model Scaling:</strong> Larger models correlate with improved training efficiency.</li><li><strong>Cross-Modal Learning:</strong> Competes with models like GPT-2 and Flan-T5 in sequence learning tasks.</li><li><strong>Random Initialization:</strong> Leads to lower training losses compared to language model weight initialization.</li></ul><h4>Conclusion</h4><p>Utilizing the Time-series Pile for pre-training transformer models of varied sizes, MOMENT sets a new standard for minimal fine-tuning requirements and superior performance in tasks, especially in anomaly detection and classification. This shows MOMENT’s impact on time-series analysis, surpassing traditional statistical methods.</p><p>Read the paper at:</p><p><a href="https://arxiv.org/abs/2402.03885">MOMENT: A Family of Open Time-series Foundation Models</a></p><blockquote><strong>For more information and to explore how my data science consulting services can benefit your company, please visit my website at </strong><a href="http://samuelchazy.com/"><strong>samuelchazy.com</strong></a></blockquote><blockquote>Explore my LLM website, offering a unique opportunity to interact with and analyze any document: <a href="https://gptdocanalyzer.com/">https://gptdocanalyzer.com/</a></blockquote><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80f5135ca35b" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/moment-a-family-of-open-time-series-foundation-models-80f5135ca35b">Moment: A Family of Open Time-Series Foundation Models</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transfer Learning in NLP: Introducing ‘Adapters’, The Unified Library]]></title>
            <link>https://ai.plainenglish.io/transfer-learning-in-nlp-introducing-adapters-the-unified-library-1a1fcab62e73?source=rss-53a14a703de9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a1fcab62e73</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[lora]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[samuel chazy]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 05:39:07 GMT</pubDate>
            <atom:updated>2023-12-08T01:53:00.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hOrLLmgIvXDNix3D_R6NGA.jpeg" /><figcaption>‘Adapters’, a unified library</figcaption></figure><p>In the evolving world of Natural Language Processing (NLP), the introduction of ‘Adapters’ marks a significant milestone. This open-source library bridges the gap in parameter-efficient and modular transfer learning for large language models (LLMs), offering a solution to the challenges imposed by the sheer size and complexity of these models.</p><h4><strong>The Challenge with Large Language Models</strong></h4><p>The growth of LLMs has made the traditional approach of fine-tuning all model parameters for downstream tasks increasingly resource-intensive. This method is not only costly but also prone to issues such as negative interference, catastrophic forgetting, and poor generalization, particularly in multi-task learning scenarios.</p><h4><strong>Emerging Solutions in Transfer Learning</strong></h4><p>Addressing these challenges, two key research approaches have gained traction:</p><ol><li><strong>Parameter-Efficient Fine-Tuning:</strong> This focuses on computational efficiency by fine-tuning a minimal number of parameters for specific tasks.</li><li><strong>Modular Transfer Learning:</strong> This emphasizes knowledge transfer through self-contained network modules, enhancing multi-task performance and generalization.</li></ol><h4><strong>Introducing ‘Adapters’</strong></h4><p>‘Adapters’ is a revolutionary library that unifies these two approaches. It offers:</p><ol><li><strong>Integration of Diverse Adapter Methods:</strong> The library consolidates 10 different adapter methods into a single, user-friendly interface.</li><li><strong>Modular Composition Blocks:</strong> These blocks enable complex adapter setups, enhancing flexibility in defining adapter configurations.</li><li><strong>Wide Model Compatibility:</strong> ‘Adapters’ is integrated with 20 Transformer-based models across NLP, vision, and multi-modal applications.</li><li><strong>Performance Evaluation:</strong> The library’s adapter implementations are benchmarked against traditional full fine-tuning across various tasks.</li></ol><h4><strong>Python Implementation</strong></h4><p>Implementing ‘Adapters’ in Python is straightforward, involving simple import and initialization steps, followed by adding and training adapters as per requirement:</p><blockquote>import adapters</blockquote><blockquote>from transformers import AutoModel</blockquote><blockquote>model = AutoModel.from_pretrained(“”..””)</blockquote><blockquote>adapters.init(model)</blockquote><blockquote>model.add_adapter(“”a””, config=””seq_bn””)</blockquote><blockquote>model.add_adapter(“”b””, config=””seq_bn””)</blockquote><blockquote>model.train_adapter(Parallel(“”a””, “”b””))”</blockquote><p>How to train an ‘Adapters’ model:</p><pre>!pip install -U adapters, datasets, accelerate -U<br><br>from datasets import load_dataset<br>dataset = load_dataset(&quot;rotten_tomatoes&quot;)<br><br>from transformers import RobertaTokenizer<br>tokenizer = RobertaTokenizer.from_pretrained(&quot;roberta-base&quot;)<br><br>def encode_batch(batch):<br>  return tokenizer(batch[&quot;text&quot;], max_length=80, truncation=True, padding=&quot;max_length&quot;)<br><br># Encode the input data<br>dataset = dataset.map(encode_batch, batched=True)<br># The transformers model expects the target class column to be named &quot;labels&quot;<br>dataset = dataset.rename_column(original_column_name=&quot;label&quot;, new_column_name=&quot;labels&quot;)<br># Transform to pytorch tensors and only output the required columns<br>dataset.set_format(type=&quot;torch&quot;, columns=[&quot;input_ids&quot;, &quot;attention_mask&quot;, &quot;labels&quot;])<br><br>from transformers import RobertaConfig<br>from adapters import AutoAdapterModel<br><br>config = RobertaConfig.from_pretrained(&quot;roberta-base&quot;, num_labels=2,)<br>model = AutoAdapterModel.from_pretrained(&quot;roberta-base&quot;, config=config,)<br><br># freeze all weights of the pre-trained model<br># only the adapter weights are updated during training<br><br># Add a new adapter<br>model.add_adapter(&quot;rotten_tomatoes&quot;)<br># Add a matching classification head<br>model.add_classification_head(&quot;rotten_tomatoes&quot;, num_labels=2, id2label={ 0: &quot;👎&quot;, 1: &quot;👍&quot;})<br># Activate the adapter<br>model.train_adapter(&quot;rotten_tomatoes&quot;)<br><br>import numpy as np<br>from transformers import TrainingArguments, EvalPrediction<br>from adapters import AdapterTrainer<br><br>training_args = TrainingArguments(<br>    learning_rate=1e-4,<br>    num_train_epochs=6,<br>    per_device_train_batch_size=32,<br>    per_device_eval_batch_size=32,<br>    logging_steps=200,<br>    output_dir=&quot;./training_output&quot;,<br>    overwrite_output_dir=True,<br>    remove_unused_columns=False,<br>)<br><br>def compute_accuracy(p: EvalPrediction):<br>  preds = np.argmax(p.predictions, axis=1)<br>  return {&quot;acc&quot;: (preds == p.label_ids).mean()}<br><br>trainer = AdapterTrainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=dataset[&quot;train&quot;],<br>    eval_dataset=dataset[&quot;validation&quot;],<br>    compute_metrics=compute_accuracy,<br>)<br><br># Train the model<br>trainer.train()<br># Evaluate the model<br>trainer.evaluate()<br><br># Save the adapter model<br>model.save_adapter(&quot;./final_adapter&quot;, &quot;rotten_tomatoes&quot;)</pre><p>How to use ‘Adapters’ for Q&amp;A inference:</p><pre>!pip install -Uq adapters<br>from transformers import AutoTokenizer<br>from adapters import AutoAdapterModel<br><br>tokenizer = AutoTokenizer.from_pretrained(&quot;bert-base-uncased&quot;)<br>model = AutoAdapterModel.from_pretrained(&quot;bert-base-uncased&quot;)<br><br>adapter_name = model.load_adapter(&quot;qa/squad1@ukp&quot;, config=&quot;houlsby&quot;)<br>model.set_active_adapters(adapter_name)<br><br>from transformers import QuestionAnsweringPipeline<br>qa = QuestionAnsweringPipeline(model=model, tokenizer=tokenizer)<br><br>context = &quot;&quot;&quot;<br>The current modus operandi in NLP involves downloading and fine-tuning pre-trained models consisting of millions or billions of parameters.<br>Storing and sharing such large trained models is expensive, slow, and time-consuming, which impedes progress towards more general and versatile NLP methods that learn from and for many tasks.<br>Adapters -- small learnt bottleneck layers inserted within each layer of a pre-trained model -- ameliorate this issue by avoiding full fine-tuning of the entire model.<br>However, sharing and integrating adapter layers is not straightforward.<br>We propose AdapterHub, a framework that allows dynamic &quot;stitching-in&quot; of pre-trained adapters for different tasks and languages.<br>The framework, built on top of the popular HuggingFace Transformers library, enables extremely easy and quick adaptations of state-of-the-art pre-trained models (e.g., BERT, RoBERTa, XLM-R) across tasks and languages.<br>Downloading, sharing, and training adapters is as seamless as possible using minimal changes to the training scripts and a specialized infrastructure.<br>Our framework enables scalable and easy access to sharing of task-specific models, particularly in low-resource scenarios.<br>AdapterHub includes all recent adapter architectures and can be found at AdapterHub.ml.<br>&quot;&quot;&quot;<br><br>def answer_questions(questions):<br>  for question in questions:<br>    result = qa(question=question, context=context)<br>    print(question)<br>    print(result[&quot;answer&quot;])<br><br>answer_questions([<br>  &quot;What are Adapters?&quot;,<br>  &quot;What do Adapters avoid?&quot;,<br>  &quot;What is proposed?&quot;,<br>  &quot;What does AdapterHub allow?&quot;,<br>  &quot;Where can I find AdapterHub?&quot;,<br>])</pre><p>And here are the answers to the above questions:</p><p><strong>What are Adapters?</strong><br>small learnt bottleneck layers inserted within each layer of a pre-trained model.</p><p><strong>What do Adapters avoid?</strong><br>full fine-tuning of the entire model.</p><p><strong>What is proposed?</strong><br>AdapterHub.</p><p><strong>What does AdapterHub allow?</strong><br>dynamic “stitching-in”.</p><p><strong>Where can I find AdapterHub?</strong><br>AdapterHub.ml</p><h4><strong>Two-Fold Approach</strong></h4><p>‘Adapters’ can be utilized in two ways:</p><ol><li><strong>Attaching to Existing Models:</strong> By using the init() method, adapters can be integrated post-hoc with existing model classes.</li><li><strong>Using Specialized Model Classes:</strong> The library also offers optimized model classes named XXXAdapterModel for different architectures.</li></ol><h4><strong>Adapter Methods and Composition</strong></h4><p>The library supports both single and complex adapter methods, including bottleneck adapters, prefix tuning, LoRA, and more. It also introduces a set of composition blocks like Stack, Fuse, Split, and Parallel, enabling dynamic and complex adapter setups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7evyml7RpJ476K618Svusg.png" /><figcaption>adapter composition blocks</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i4Hic9eUlQn6hRAQIlDtvQ.png" /><figcaption>adapter composition blocks</figcaption></figure><ul><li>Stack: The Stack block allows stacking multiple adapters sequentially within a Transformer layer.</li><li>Fuse: The Fuse block can be used to activate an AdapterFusion layer.</li><li>Split: The Split block can be used to split an input sequence between multiple adapters.</li><li>BatchSplit: The BatchSplit block splits inputs along the batch size dimension between several adapters.</li><li>Parallel: This block can be used to enable independent parallel training and inference on different adapters, where each adapter has its own prediction head.</li><li>Average: This includes averaging adapter output representations as well as averaging adapter parameters.</li><li>Nesting: It is possible to nest composition blocks within other composition blocks to create deeper and more complex compositions.</li></ul><h4><strong>Supported Models</strong></h4><p>Adapters tightly integrates into the HuggingFace and AdapterHub ecosystems and its adapter implementations show performances competitive to full fine-tuning.</p><p>‘Adapters’ is compatible with a range of models such as BERT, DeBERTa, GPT-2, BART, T5, ViT, and CLIP, and integrates seamlessly with the HuggingFace and AdapterHub ecosystems.</p><h4><strong>Conclusion</strong></h4><p>‘Adapters’ presents a novel and efficient way to leverage transfer learning in NLP, offering a scalable solution to the challenges posed by large language models. Its integration with popular ecosystems and competitive performance makes it a promising tool for NLP developers.</p><h4>GitHub code:</h4><p>Experience the capabilities of ‘Adapters’ with a python code at:</p><p><a href="https://adapterhub.ml/adapters">https://adapterhub.ml/adapters</a>.</p><h4>Paper:</h4><p><a href="https://arxiv.org/abs/2311.11077v1">Adapters: A Unified Library for Parameter-Efficient and Modular Transfer Learning</a></p><blockquote><strong><em>For more information and to explore how my data science consulting services can benefit your company, please visit my website at </em></strong><a href="http://samuelchazy.com/"><strong><em>samuelchazy.com</em></strong></a></blockquote><blockquote><em>Explore my LLM website, offering a unique opportunity to interact with and analyze any document: </em><a href="https://gptdocanalyzer.com/"><em>https://gptdocanalyzer.com/</em></a></blockquote><h3><a href="https://plainenglish.io/">PlainEnglish.io</a> 🚀</h3><p><em>Thank you for being a part of the In Plain English community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer</em><strong>️</strong></li><li><em>Learn how you can also </em><a href="https://plainenglish.io/blog/how-to-write-for-in-plain-english"><strong><em>write for In Plain English</em></strong></a><em>️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>X</em></strong></a><strong><em> | </em></strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em> | </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em> | </em></strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em> | </em></strong><a href="https://newsletter.plainenglish.io/"><strong><em>Newsletter</em></strong></a></li><li><em>Visit our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><strong><em> | </em></strong><a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a><strong><em> | </em></strong><a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a1fcab62e73" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/transfer-learning-in-nlp-introducing-adapters-the-unified-library-1a1fcab62e73">Transfer Learning in NLP: Introducing ‘Adapters’, The Unified Library</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forecasting sales using Meta’s Neural Prophet]]></title>
            <link>https://ai.plainenglish.io/forecasting-sales-using-metas-neural-prophet-5a69ca195100?source=rss-53a14a703de9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a69ca195100</guid>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[samuel chazy]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 06:49:39 GMT</pubDate>
            <atom:updated>2023-10-26T11:32:25.845Z</atom:updated>
            <content:encoded><![CDATA[<h3>Forecasting Sales Using Meta’s Neural Prophet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUD5_zAEy_RJ_q66RO9ggA.jpeg" /><figcaption>Explainable Forecasting at Scale</figcaption></figure><h3><strong>Introduction</strong></h3><p>In today’s fast-paced business landscape, accurate sales forecasting is the heart of strategic decision-making. Organizations rely on data-driven insights to make critical choices related to inventory management, resource allocation, and revenue projections. To tackle this challenge, data scientists harness advanced techniques, one of which is Neural Prophet.</p><p>Neural Prophet is a powerful tool for time series forecasting that combines the flexibility of neural networks with the intuitive modeling of traditional forecasting methods. Neural Prophet was developed by Meta. In this article, I’ll guide you through the process of harnessing Neural Prophet to predict sales, from installing the necessary libraries to interpreting model parameters and generating forecasts. By following the steps outlined in this article, you’ll be equipped to take your sales forecasting to a new level of accuracy and sophistication.</p><blockquote>“Neural Prophet is a hybrid forecasting framework based on PyTorch and trained with standard deep learning methods, making it easy for developers to extend the framework. Local context is introduced with auto-regression and covariate modules, which can be configured as classical linear regression or as Neural Networks.”</blockquote><p>The mathematical formula behind Neural Prophet is:</p><p><strong>y_hat(t) = T(t) +S(t) +E(t) +F(t) +A(t) +L(t)</strong></p><p>where,</p><ul><li>T(t) = Trend at time t</li><li>S(t) = Seasonal effects at time t</li><li>E(t) = Event and holiday effects at time t</li><li>F(t) = Regression effects at time t for future-known exogenous variables</li><li>A(t) = Auto-regression effects at time t based on past observations</li><li>L(t) = Regression effects at time t for lagged observations of exogenous variables</li></ul><p>We’ll start by installing the required libraries and then proceed to the critical steps of data preparation, understanding Neural Prophet’s parameters, and building a model tailored to your specific needs. Finally, we’ll explore how to use the model to make predictions and visualize the results, allowing you to gain valuable insights into your sales data.</p><p>Whether you’re an experienced data scientist or a Python developer looking to enhance your forecasting capabilities, this article will provide a comprehensive roadmap to harnessing Neural Prophet for sales forecasting.</p><p><strong>Start by installing the required libraries:</strong></p><pre># Make sure you have python 3.9 or 3.10 installed<br>!pip install neuralprophet<br><br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from neuralprophet import NeuralProphet</pre><h3>Data Preparation</h3><p><strong>Download the sales data from Kaggle:</strong><br>https://www.kaggle.com/datasets/muratsikli/online-retailxlsx/</p><pre># read the excel file<br>df = pd.read_excel(&#39;data/online_retail_II.xlsx&#39;, engine=&#39;openpyxl&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRVmj4BNO0Z9jIzwug6tDg.png" /><figcaption>Original dataframe</figcaption></figure><p><strong>Check null values and feature types in the dataframe:</strong></p><pre># Check null values<br>df.isna().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N6K-hkxaG7G5JTXLVwpUEQ.png" /><figcaption>Sum of null values</figcaption></figure><pre># Check data type<br>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFae11NNFzztS2LIZuevXA.png" /><figcaption>Data types of features</figcaption></figure><p><strong>Transform the features:</strong></p><p>We have null values in the Description column which we will replace with ‘NA’, and set the type to string. Some customer IDs are missing, so we will replace them with the number 9999, and set the type to integer. We will then set the type of the Invoice date column to datetime, and set the type of the country column to string.</p><pre>df_modified = df.copy()<br>df_modified[&#39;Description&#39;] = df_modified[&#39;Description&#39;].fillna(&#39;NA&#39;).astype(&#39;string&#39;)<br>df_modified[&#39;InvoiceDate&#39;] = pd.to_datetime(df_modified[&#39;InvoiceDate&#39;]).dt.strftime(&quot;%Y-%m-%d&quot;)<br>df_modified[&#39;Customer ID&#39;] = df_modified[&#39;Customer ID&#39;].fillna(&#39;9999&#39;).astype(&#39;int&#39;)<br>df_modified[&#39;Country&#39;] = df_modified[&#39;Country&#39;].astype(&#39;string&#39;)<br>df_modified.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9BRL9DDWf0AdQ9kKmCGkPw.png" /><figcaption>Transformed dataframe</figcaption></figure><p><strong>Check for duplicate rows:</strong></p><p>We can check for duplicate rows and delete them from the dataframe.</p><pre>df_modified.duplicated().sum()<br><br>print(f&#39;Length of data before: {len(df_modified)}&#39;)<br>df_modified = df_modified[df_modified.duplicated() == False]<br>print(f&#39;Length of data after: {len(df_modified)}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uFcK-9wLZBpLixM9-2P_SA.png" /><figcaption>Cleaned dataframe</figcaption></figure><p><strong>Aggregate the data:</strong></p><p>At this point we need to get the sales returns, which can be aggregated by multiplying the Price column by the Quantity column. We then group the results by date, and set the new column to be named Monetary.</p><pre>df_timeline = df_modified.copy()<br>df_timeline = df_timeline.rename(columns={&#39;InvoiceDate&#39;: &#39;date&#39;})<br>df_timeline[&#39;Monetary&#39;] = df_timeline[&#39;Price&#39;] * df_timeline[&#39;Quantity&#39;]<br>df_timeline = df_timeline.groupby([&#39;date&#39;])[[&#39;Monetary&#39;]].sum()<br>df_timeline = df_timeline.reset_index()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgwye4KoLCDNmQz-1L_HGA.png" /><figcaption>dataframe with date and sales data</figcaption></figure><p><strong>Plot the timeline:</strong></p><p>Let’s plot the sales column vs the monetary column to get an overview of the sales over time. It is advisable to zoom on various date ranges to check the fluctuation, the outliers, or anomalies in the timeline.</p><pre>ax, fig = plt.subplots(figsize=(15, 4), dpi=300)<br>ax = sns.lineplot(x=&#39;date&#39;, y=&#39;Monetary&#39;, data=df_timeline, color=&#39;cyan&#39;, alpha=1, size=1)<br>plt.xticks(fontsize=2, rotation=90)<br>plt.yticks(fontsize=8, rotation=0)<br>ax.grid(color=&#39;lightgrey&#39;, linewidth=0.5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZoGHRD1UP7Ijw_60Z7k2zg.png" /><figcaption>Past sales data graph</figcaption></figure><p><strong>Prepare the timeline for the Neural Prophet Network:</strong></p><p>The neural prophet model needs a minimum of two variables to work; A date of type datetime and a value of type numerical, and these have to be named exactly ‘ds’ and ‘y’ respectively.</p><pre>df_timeline = df_timeline.rename(columns={&#39;date&#39;: &#39;ds&#39;, &#39;Monetary&#39;: &#39;y&#39;})<br>df_timeline = df_timeline.loc[:, [&#39;ds&#39;, &#39;y&#39;]]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPqSnDhPNPbSvqD1nS2Vjw.png" /><figcaption>Prophet dataframe with time and past sales</figcaption></figure><h3>Understanding some of the hyper-parameters of the Neural Prophet model.</h3><blockquote><a href="https://github.com/ourownstory/neural_prophet">NeuralProphet</a> provides a solution to some of users’ most common needs, based on Meta’s own internal data scientists, as well as the requests of external industry practitioners, aiming to maximize the scalability and flexibility of time series forecasts.</blockquote><p><strong>Growth:</strong><br>growth ({‘off’ or ‘linear’}, default ‘linear’)</p><p><strong>Changepoints:</strong><br>changepoints ({list of str, list of np.datetimes or np.array of np.datetimes}, optional)</p><p><strong>Number of changepoints:</strong><br>n_changepoints (int) — Number of potential trend changepoints to include.</p><p><strong>Range of changepoints:</strong><br>changepoints_range (float)<br>Proportion of history in which trend changepoints will be estimated.<br>Example: set to 0.8 to allow changepoints only in the first 80% of training data.</p><p><strong>Trend regularization:</strong><br>trend_reg (float, optional)<br>Parameter modulating the flexibility of the automatic changepoint selection.</p><p><strong>Trend regularization threshold:</strong><br>trend_reg_threshold (bool, optional)<br>Allowance for trend to change without regularization.</p><p><strong>Global trend:</strong><br>trend_global_local (str, default ‘global’)<br>Modeling strategy of the trend when multiple time series are present.</p><p><strong>Yearly seasonality:</strong><br>yearly_seasonality (bool, int)<br>Fit yearly seasonality.</p><p><strong>Weekly seasonality:</strong><br>weekly_seasonality (bool, int)<br>Fit monthly seasonality.</p><p><strong>Daily seasonality:</strong><br>daily_seasonality (bool, int)<br>Fit daily seasonality.</p><p><strong>Seasonality mode:</strong><br>seasonality_mode (str)<br>Specifies mode of seasonality</p><p><strong>Seasonality regularization:</strong><br>seasonality_reg (float, optional)<br>Parameter modulating the strength of the seasonality model.</p><p><strong>Local vs global seasonality:</strong><br>season_global_local (str, default ‘global’)<br>Modeling strategy of the seasonality when multiple time series are present.</p><p><strong>number of lags:</strong><br>n_lags (int)<br>Previous time series steps to include in auto-regression.</p><p><strong>Auto-regressive regularization:</strong><br>ar_reg (float, optional)<br>how much sparsity to induce in the AR-coefficients<br>Large values (~1–100) will limit the number of nonzero coefficients dramatically.<br>Small values (~0.001–1.0) will allow more non-zero coefficients.<br>default: 0 no regularization of coefficients.</p><p><strong>Auto-regressive layers:</strong><br>ar_layers (list of int, optional)<br>array of hidden layer dimensions of the AR-Net.<br>Specifies number of hidden layers (number of entries) and layer dimension (list entry)</p><p><strong>Number of forecasts:</strong><br>n_forecasts (int)<br>Number of steps ahead of a prediction time step to forecast.</p><p><strong>Lagged regressive layers:</strong><br>lagged_reg_layers (list of int, optional)<br>array of hidden layer dimensions of the Covar-Net.<br>Specifies number of hidden layers and layer dimension.</p><p><strong>Learning rate:</strong><br>learning_rate (float)<br>Maximum learning rate setting for 1cycle policy scheduler.</p><p><strong>Number of epochs:</strong><br>epochs (int)<br>Number of epochs (complete iterations over dataset) to train model.</p><p><strong>Batch size:</strong><br>batch_size (int)<br>Number of samples per mini-batch.</p><p><strong>New samples weight:</strong><br>newer_samples_weight (float, default 2.0)<br>Sets factor by which the model fit is skewed towards more recent observations.</p><p><strong>New samples start weight:</strong><br>newer_samples_start (float, default 0.0)<br>Sets beginning of ‘newer’ samples as fraction of training data.</p><p><strong>Metrics:</strong><br>loss_func (str, torch.nn.functional.loss)<br><em>Options:</em><br>(default) Huber: Huber loss function<br>MSE: Mean Squared Error loss function<br>MAE: Mean Absolute Error loss function<br>torch.nn.functional.loss.: loss or callable for custom loss, example: L1-Loss</p><p><strong>Import country holidays:</strong></p><p>The neural prophet model allows us to add holidays that are country specific. This is beneficial as the sales can fluctuate during holidays in a positive or negative direction. This allows the model to factor this fluctuation. We start by importing the holidays for the US.</p><pre>import holidays<br><br>country_holidays = holidays.country_holidays(country=&#39;US&#39;, years=[2009, 2010], language=&#39;english&#39;)<br>print(country_holidays)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ExakfFFXKikkuQBZXxz2g.png" /><figcaption>US holidays</figcaption></figure><h3><strong>Build &amp; Fit the model:</strong></h3><p>This is the core of the neural prophet model with its hyper-parameters that we explained before. The hyper-parameters should be adjusted according to the use case at hand.</p><pre>model = NeuralProphet(growth=&#39;off&#39;,<br>                      yearly_seasonality=True,<br>                      weekly_seasonality=True,<br>                      daily_seasonality=True,<br>                      seasonality_mode=&#39;additive&#39;,<br>                      n_forecasts=3,<br>                      learning_rate=0.1,<br>                      epochs=500,<br>                      batch_size=128,<br>                      loss_func=&#39;MSE&#39;,<br>                      trainer_config={&#39;accelerator&#39;: &#39;mps&#39;, &#39;devices&#39;: 1},<br>                      )</pre><p><strong>Add the holidays to the model:</strong></p><pre>model = model.add_country_holidays(country_name=&#39;UnitedArabEmirates&#39;, mode=&quot;additive&quot;,<br> lower_window=0, upper_window=0, regularization=0)</pre><p><strong>Split the data into train and validation to train the model:</strong></p><p>We split the data into training and validation to train and test the model. This will allow us to see if the model is capable of well predicting the validation data, before going into predicting the future timeline.</p><pre>df_train, df_test = model.split_df(df_timeline, valid_p=0.15, freq=&#39;D&#39;)</pre><p><strong>Fit the model:</strong></p><p>At this point the model needs to be fit so that the training of the model could start.</p><pre>metrics = model.fit(df=df_train,<br>                    freq=&#39;D&#39;,<br>                    validation_df=df_test,<br>                    metrics=True,<br>                    early_stopping=True,<br>                    progress=&#39;bar&#39;,<br>                    )</pre><p><strong>Build the future timeline with the desired forecast period:</strong></p><p>Once we have trained the model, we need to build a future timeline with null values and with a range of dates that we would like to forecast. This will be used by the model to fill the null values with its prediction values.</p><pre>future_timeline = model.make_future_dataframe(df_timeline,<br>                                              events_df=None,<br>                                              regressors_df=None,<br>                                              n_historic_predictions=True,<br>                                              periods=(7 * 30 * 2))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vf72fu63z-2iGviP77iXYQ.png" /><figcaption>Future timeline with new dates to be projected</figcaption></figure><p><strong>Predict the future timeline:</strong></p><p>Using the previously built future timeline with null values, we ask the model to forecast the unknown values.</p><pre>forecast = model.predict(future_timeline)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JbrNwnXKfUg37H6YARH5xQ.png" /><figcaption>Full dataframe after forecast</figcaption></figure><h3><strong>Plot the forecast:</strong></h3><p>At this point, the model has been trained and has filled its prediction of sales into the new timeline. All we need to do now is to visualize the new timeline with a forecast power of one year ahead: 2011 till 2012.</p><pre>fig, ax = plt.subplots(figsize=(15, 8), dpi=300)<br>ax1 = sns.lineplot(x=df_train.ds, y=df_train.y, ax=ax, color=&#39;magenta&#39;, alpha=0.7, linewidth=0.5)<br>ax2 = sns.lineplot(x=df_test.ds, y=df_test.y, ax=ax, color=&#39;magenta&#39;, alpha=0.7, linewidth=0.5)<br>ax3 = sns.lineplot(x=forecast.ds, y=forecast.yhat1[0:], ax=ax, color=&#39;cyan&#39;, alpha=0.8, linewidth=1)<br>ax.grid(color=&#39;lightgrey&#39;, linewidth=0.5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n2eun8mI95GqoC0b0M97ug.png" /><figcaption>Projected sales graph</figcaption></figure><h3>Moving forward with this project:</h3><p>What we’ve accomplished so far is just the initial phase of harnessing the powerful sales forecasting capabilities of Neural Prophet. There’s a world of possibilities to enhance our analysis:</p><ol><li><strong>Fine-Tune Model Hyper-parameters:</strong> We can further refine our model by adjusting its hyper-parameters to achieve even more accurate and reliable results.</li><li><strong>Visualize Model Parameters:</strong> Dive deeper into the model by visualizing its core components. This will provide us with valuable insights through graphs showing trends, trend rate changes, and seasonality over time.</li><li><strong>Explore Model Components:</strong> Delve into the model’s components to gain a deeper understanding. Visualize trends and auto-regressive variables, giving us a clearer picture of what’s driving our forecasts.</li><li><strong>Create a Dynamic Dashboard:</strong> Take your analysis to the next level by developing a comprehensive dashboard. This dashboard can include all the variables from your dataset, historical sales trends, seasonality patterns, and live model forecasts. It’s a powerful tool for seamless and interactive visualization.</li></ol><p>The journey doesn’t stop here. These steps provide a roadmap for advancing your project and maximizing the insights you can gain from Neural Prophet.</p><h3><strong>Conclusion</strong></h3><p>In the world of data science and business analytics, the ability to forecast sales accurately is more critical than ever. It empowers companies to make informed decisions, optimize resource allocation, and stay ahead of market dynamics. Neural Prophet, a fusion of neural networks and classical forecasting methods, is a game-changer in this arena.</p><p>Throughout this article, we went through the process of leveraging Neural Prophet to forecast sales. We started by setting up the necessary libraries, dived into data preparation, explored the significance of various model parameters, and constructed a predictive model tailored to your unique requirements. By the end we witnessed how Neural Prophet can be used to predict future sales trends and visually interpret the results.</p><p>This article served as a simple guide for professionals in the realms of data science, machine learning, and statistical analysis, as well as Python developers, who are keen to enhance their forecasting capabilities. Neural Prophet opens doors to a world of advanced forecasting techniques, and with this knowledge, you’re well-equipped to unlock the full potential of your sales data.</p><p>Remember that sales forecasting is not a one-time task but an ongoing process. Regularly revisiting your models and adapting them to changing market conditions is key to maintaining predictive accuracy. Neural Prophet provides a versatile platform for this continuous improvement, making it an invaluable asset for businesses looking to thrive in the data-driven age.</p><blockquote><strong>For more information and to explore how my data science consulting services can benefit your company, please visit my website at </strong><a href="http://samuelchazy.com/"><strong>samuelchazy.com</strong></a></blockquote><blockquote>Explore my LLM website, offering a unique opportunity to interact with and analyze any document: <a href="https://gptdocanalyzer.com/">https://gptdocanalyzer.com/</a></blockquote><p><strong>References:</strong></p><p><a href="https://neuralprophet.com/">NeuralProphet</a></p><p><a href="https://arxiv.org/abs/2111.15397?fbclid=IwAR2vCkHYiy5yuPPjWXpJgAJs-uD5NkH4liORt1ch4a6X_kmpMqagGtXyez4">https://arxiv.org/abs/2111.15397?fbclid=IwAR2vCkHYiy5yuPPjWXpJgAJs-uD5NkH4liORt1ch4a6X_kmpMqagGtXyez4</a></p><p><a href="https://github.com/ourownstory/neural_prophet">https://github.com/ourownstory/neural_prophet</a></p><ul><li><a href="https://ai.meta.com/blog/neuralprophet-the-neural-evolution-of-facebooks-prophet/">NeuralProphet: The neural evolution of Meta&#39;s Prophet</a></li><li><a href="https://neuralprophet.com/contents.html">NeuralProphet documentation</a></li></ul><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li><li><em>Check out our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a>, <a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a>, <a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a69ca195100" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/forecasting-sales-using-metas-neural-prophet-5a69ca195100">Forecasting sales using Meta’s Neural Prophet</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Code a Machine Learning Model to Detect Freezing of Gait]]></title>
            <link>https://ai.plainenglish.io/how-to-code-a-machine-learning-model-to-detect-freezing-of-gait-fog-on-kaggle-c37b45c6fe7b?source=rss-53a14a703de9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c37b45c6fe7b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[parkinson-disease]]></category>
            <category><![CDATA[lightgbm]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[samuel chazy]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 08:16:12 GMT</pubDate>
            <atom:updated>2023-10-26T11:32:41.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KD6fBDz-obAZtNZRQdiSVg.jpeg" /></figure><h3>I- Introduction</h3><p>The objective of this article is to use ML techniques to identify FOG episodes by analyzing data collected from a wearable 3D lower back sensor. This is a competition that was posted on Kaggle (<a href="https://www.kaggle.com/competitions/tlvmc-parkinsons-freezing-gait-prediction/overview">https://www.kaggle.com/competitions/tlvmc-parkinsons-freezing-gait-prediction/overview</a>).</p><h3>II- Understanding the Problem</h3><h4><strong>What is Freezing of Gait (FOG)?</strong></h4><p>Freezing of gait (FOG) is a debilitating symptom often associated with Parkinson’s disease. FOG can severely affect the mobility and quality of life of individuals with this condition. During a FOG episode, a person’s feet seem to be “glued” to the ground, making it extremely difficult for them to move forward, despite their attempts to walk. FOG has significant negative effects on the quality of life of affected individuals, leading to depression, an increased risk of falling, reduced independence, and often the need for a wheelchair.</p><h4>The Challenge</h4><p>The challenge is to develop a machine learning model that can accurately detect FOG episodes based on data collected from a wearable 3D lower back sensor. Detecting FOG accurately is crucial for improving the evaluation, understanding, and treatment of this debilitating symptom.</p><h4>The Dataset</h4><p>The dataset for this competition comprises three distinct data series:</p><ul><li>tDCS FOG (tdcsfog) dataset: This dataset contains data series collected in a laboratory setting as subjects completed a FOG-provoking protocol.</li><li>The DeFOG (defog) dataset:This dataset includes data series collected in the subject’s home, also as they completed a FOG-provoking protocol.</li><li>The Daily Living (daily) dataset: This dataset consists of one week of continuous 24/7 recordings from sixty-five subjects. Forty-five of these subjects exhibit FOG symptoms and also have series in the defog dataset, while the other twenty subjects do not exhibit FOG symptoms and do not have series elsewhere in the data.</li></ul><h3>III- Developing the Machine Learning Model</h3><p>Let’s dive into the steps involved in developing the machine learning model for FOG detection:</p><h4>1. Data Preprocessing</h4><p>Before building the model, it’s crucial to preprocess the data. This includes:</p><ul><li>Combining data from different sources, such as tdcsfog and defog datasets.</li><li>Handling missing values and converting data types.</li><li>Feature engineering, which involves creating new features or transforming existing ones.</li></ul><h4>2. Importing Libraries</h4><p>We’ll be using various Python libraries for this task. Some of the key libraries include:</p><ul><li>numpy and pandas for data manipulation.</li><li>scikit-learn for machine learning.</li><li>lightgbm for gradient boosting.</li><li>MultiOutputRegressor for handling multiple target variables simultaneously</li><li>PCA for Principal Component Analysis.</li></ul><pre>import numpy as np<br>import pandas as pd<br>import os<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import average_precision_score<br>import lightgbm as lgb<br>from sklearn.multioutput import MultiOutputRegressor<br>from sklearn.decomposition import PCA</pre><h4>3. Function for building the Training model</h4><p>We build a MultiOutputRegressor model using LightGBM regressors. This allows us to predict three types of FOG events: Start Hesitation, Turn, and Walking. The steps include:</p><ul><li>Splitting the data into training and validation sets.</li><li>Creating the MultiOutputRegressor model based on LGBMRegressor</li><li>Training the model on the training data.</li><li>Predicting the validation data.</li><li>Evaluating the model using Mean Average Precision (MAP) score and feature importance.</li></ul><pre>def build_model(file):<br>    <br>    ############ split the file in X &amp; y ############    <br>    X = file.drop([&#39;StartHesitation&#39;,&#39;Turn&#39;,&#39;Walking&#39;,&#39;Id&#39;],axis=1)<br>    y = file[[&#39;StartHesitation&#39;,&#39;Turn&#39;,&#39;Walking&#39;]]<br>    <br>    ############ split the data using train test split ############    <br>    X_train,X_val,y_train,y_val = train_test_split(X,y,test_size=0.2,random_state=42)<br><br>    ############ Create MultiOutputRegressor model ############<br>    model = MultiOutputRegressor(lgb.LGBMRegressor())<br><br>    ############ Train the model on the training data ############<br>    model.fit(X_train,y_train)<br><br>    ############ Predict the Validation data ############<br>    y_pred = model.predict(X_val)<br><br>    ############ Scoring models ############<br><br>    # Compute average precision for each event class<br>    ap_start_hesitation = average_precision_score(y_val[&#39;StartHesitation&#39;], y_pred[:, 0])<br>    ap_turn = average_precision_score(y_val[&#39;Turn&#39;], y_pred[:, 1])<br>    ap_walking = average_precision_score(y_val[&#39;Walking&#39;], y_pred[:, 2])<br><br>    # Calculate the overall score as the average of the average precision scores for each event class<br>    map_score = (ap_start_hesitation + ap_turn + ap_walking) / 3<br><br>    print(&quot;Mean Average Precision (MAP) score: {:.2f}&quot;.format(map_score))<br>    print(&#39;-&#39;*80)<br>    feature_importances = []<br>    for regressor in model.estimators_:<br>        if isinstance(regressor, lgb.LGBMRegressor):<br>            feature_importances.append(regressor.feature_importances_)<br><br>    feature_importance_avg = np.mean(feature_importances, axis=0)<br><br>    # Sort feature importances in descending order<br>    sorted_importances = sorted(zip(X.columns, feature_importance_avg), key=lambda x: x[1], reverse=True)<br><br>    print(&quot;Sorted Feature Importances:&quot;)<br>    for feature_name, importance in sorted_importances:<br>        print(f&quot;{feature_name}: {round(importance,0)}&quot;)<br>    print(&#39;-&#39;*80)<br>    print(&#39;Done!...&#39;)<br><br>    return model</pre><h4>4. Function for building the Testing Model</h4><p>We build the final machine learning model that utilizes the full dataset after fine-tuning the model.</p><pre>def build_model_final(file):<br><br>    ############ split the file in X &amp; y ############<br>    X = file.drop([&#39;StartHesitation&#39;,&#39;Turn&#39;,&#39;Walking&#39;,&#39;Id&#39;],axis=1)<br>    y = file[[&#39;StartHesitation&#39;,&#39;Turn&#39;,&#39;Walking&#39;]]<br><br>    ############ Create MultiOutputRegressor model ############<br>    model = MultiOutputRegressor(lgb.LGBMRegressor())<br><br>    ############ Train the model on full data ############<br>    model.fit(X,y)<br><br>    return model</pre><h4>5. Function for predicting the Test Data</h4><p>We build the function that will predict the unseen dataset, which is not included in the original data.</p><pre> def predict_test_data(file,model):<br>        <br>    X_test = file.drop([&#39;Id&#39;],axis=1).copy()<br>    y_pred = model.predict(X_test)<br>    <br>    X_test = pd.DataFrame(y_pred,columns=[&#39;StartHesitation&#39;, &#39;Turn&#39;, &#39;Walking&#39;])<br>    X_test[&#39;Id&#39;] = file[&#39;Id&#39;]<br>    <br>    return X_test</pre><h4>6. Preparing the datasets</h4><p><strong>A- tdcsfog data: </strong>We need to read the train data and metadata and combine them together in one file.</p><pre>tdcsfog_path=&#39;data/train/tdcsfog&#39;<br><br>tdcsfog_list =[]<br>for file_name in os.listdir(tdcsfog_path):<br>    if file_name.endswith(&#39;.csv&#39;):<br>        file_path = os.path.join(tdcsfog_path, file_name)<br>        file = pd.read_csv(file_path)<br>        file[&#39;Id&#39;] = file_name[:-4]<br><br>        file[&#39;Time_frac&#39;]=(file.index/file.index.max()).values<br>        tdcsfog_list.append(file)<br><br>tdcsfog = pd.concat(tdcsfog_list, axis = 0)<br><br>tdcsfog_metadata = pd.read_csv(&#39;data/tdcsfog_metadata.csv&#39;)<br>tdcsfog_metadata[&#39;Medication&#39;] = tdcsfog_metadata[&#39;Medication&#39;].factorize()[0]<br>tdcsfog_metadata = tdcsfog_metadata.drop([&#39;Test&#39;],axis=1)<br><br>tdcsfog = pd.merge(left=tdcsfog,right=tdcsfog_metadata,left_on=&#39;Id&#39;,right_on=&#39;Id&#39;,how=&#39;left&#39;)</pre><p><strong>B- Defog data: </strong>We need to read the train data and metadata and combine them together in one file. The Medication column needs to be factorized because it is a categorical column. We also need to filter the data by Valid = True and Task = True as advised in the challenge data description.</p><pre>defog_path=&#39;data/train/defog&#39;<br><br>defog_list =[]<br>for file_name in os.listdir(defog_path):<br>    if file_name.endswith(&#39;.csv&#39;):<br>        file_path = os.path.join(defog_path, file_name)<br>        file = pd.read_csv(file_path)<br>        file[&#39;Id&#39;] = file_name[:-4]<br><br>        file[&#39;Time_frac&#39;]=(file.index/file.index.max()).values<br>        defog_list.append(file)<br><br>defog = pd.concat(defog_list, axis = 0)<br><br>defog_metadata = pd.read_csv(&#39;data/defog_metadata.csv&#39;)<br>defog_metadata[&#39;Medication&#39;] = defog_metadata[&#39;Medication&#39;].factorize()[0]<br><br>defog = pd.merge(left=defog,right=defog_metadata,left_on=&#39;Id&#39;,right_on=&#39;Id&#39;,how=&#39;left&#39;)<br><br>defog_true = defog[(defog[&#39;Valid&#39;] == True) &amp; (defog[&#39;Task&#39;] == True)]<br>defog_true<br><br>defog_true = defog_true.drop([&#39;Task&#39;,&#39;Valid&#39;],axis=1)</pre><p><strong>C. Combine tdcsfog &amp; defog dataframes:</strong></p><pre>complete_dataset = pd.concat([tdcsfog,defog_true],axis=0)</pre><p><strong>D. Tasks data:</strong></p><p>Read the tasks file and perform feature engineering and data manipulation on it by doing the following:</p><ul><li>Add a duration column (begin time - end time)</li><li>Pivot the table to align it with the complete dataset</li><li>Apply a PCA to reduce the number of columns to 3 axis</li></ul><pre># Read tasks file<br>tasks = pd.read_csv(&#39;data/tasks.csv&#39;).fillna(0)<br>tasks[&#39;Duration&#39;] = tasks[&#39;End&#39;] - tasks[&#39;Begin&#39;]<br>tasks = tasks.drop([&#39;Begin&#39;,&#39;End&#39;],axis=1)<br>tasks = pd.pivot_table(data=tasks,index=&#39;Id&#39;,columns=&#39;Task&#39;,values=&#39;Duration&#39;,aggfunc=&#39;median&#39;,fill_value=0)<br>tasks = tasks.reset_index(drop=False)<br><br># Apply PCA<br>pca = PCA(n_components=3)<br>tasks_pca = pca.fit_transform(tasks.iloc[:,1:-1])<br>print(pca.explained_variance_ratio_)<br>print(f&#39;Cumulative sum = {np.round(np.cumsum(pca.explained_variance_ratio_)[-1]*100,2)}%&#39;)<br><br># Change the name of the columns and add the Id<br>tasks_pca = pd.DataFrame(tasks_pca,columns=[&#39;pca_1&#39;,&#39;pca_2&#39;,&#39;pca_3&#39;])<br>tasks_pca[&#39;Id&#39;] = tasks[&#39;Id&#39;]</pre><p><strong>E- Combine all the files:</strong></p><pre>complete_dataset_extended = pd.merge(left=complete_dataset,right=tasks_pca,left_on=&#39;Id&#39;,right_on=&#39;Id&#39;,how=&#39;left&#39;).fillna(0)<br>complete_dataset_extended = complete_dataset_extended.drop(&#39;Subject&#39;,axis=1).fillna(0)</pre><h4>7- Feature Engineering</h4><p>We train two linear regression models (model_1 and model_2) to predict three target variables: StartHesitation, Turn, and Walking. The features used for prediction are stored in the multiple_variables list, which includes &#39;AccV,&#39; &#39;AccML,&#39; and &#39;AccAP.&#39; The code iterates through each target variable in a loop and trains both model_1 and model_2 on different subsets of features. model_1 uses only &#39;AccV&#39; and &#39;AccAP&#39; as features, while model_2 uses &#39;AccV,&#39; &#39;AccML,&#39; and &#39;AccAP.&#39;</p><p>After training the models, two new features, ‘new_feat_1’ and ‘new_feat_2,’ are created by making predictions using the respective models. These new features are intended to capture the relationships between the accelerometer measurements and the target variables.</p><p>To assess how well these new features correlate with the target variables, the code calculates and prints the correlation coefficients between ‘new_feat_1,’ ‘new_feat_2,’ and the three target variables: ‘StartHesitation,’ ‘Turn,’ and ‘Walking.’ The correlation coefficients provide insights into how strongly these new features are related to the targets.</p><p>Additionally, the code utilizes the SplineTransformer from scikit-learn to perform cubic spline transformations on the &#39;AccV,&#39; &#39;AccML,&#39; and &#39;AccAP&#39; features, creating a set of new features with the prefix &#39;AccV_sp,&#39; &#39;AccML_sp,&#39; and &#39;AccAP_sp.&#39; These spline-transformed features are then concatenated with the existing dataset (complete_dataset_extended) for further analysis or modeling.</p><pre>from sklearn.linear_model import LinearRegression<br>from tqdm import tqdm<br><br># Build 2 Liner Regression Models<br>model_1 = LinearRegression()<br>model_2 = LinearRegression()<br><br># Assign the variables for the output<br>multiple_variables = [&#39;AccV&#39;,&#39;AccML&#39;,&#39;AccAP&#39;]<br>ys = complete_dataset_extended[[&#39;StartHesitation&#39;,&#39;Turn&#39;,&#39;Walking&#39;]]<br><br># Iterate through the output varaibles and fit &amp; predict the data<br>for y in tqdm(ys.columns):<br><br>    model_1 = model_1.fit(complete_dataset_extended[[&#39;AccV&#39;,&#39;AccAP&#39;]], complete_dataset_extended[y])<br>    complete_dataset_extended[&quot;new_feat_1&quot;] = model_1.predict(complete_dataset_extended[[&#39;AccV&#39;,&#39;AccAP&#39;]])<br><br>    model_2 = model_2.fit(complete_dataset_extended[[&#39;AccV&#39;,&#39;AccML&#39;,&#39;AccAP&#39;]], complete_dataset_extended[y])<br>    complete_dataset_extended[&quot;new_feat_2&quot;] = model_2.predict(complete_dataset_extended[[&#39;AccV&#39;,&#39;AccML&#39;,&#39;AccAP&#39;]])<br><br><br># Check correlations with the target<br>for var in multiple_variables + [&#39;new_feat_1&#39;] + [&#39;new_feat_2&#39;]:<br>    corr = np.corrcoef(complete_dataset_extended[var],complete_dataset_extended[&#39;StartHesitation&#39;])[0, 1]<br>    corr = np.round(corr, 3)<br>    print(f&quot;Correlation between {var} and the target: {corr}&quot;)<br>    corr = np.corrcoef(complete_dataset_extended[var],complete_dataset_extended[&#39;Turn&#39;])[0, 1]<br>    corr = np.round(corr, 3)<br>    print(f&quot;Correlation between {var} and the target: {corr}&quot;)<br>    corr = np.corrcoef(complete_dataset_extended[var],complete_dataset_extended[&#39;Walking&#39;])[0, 1]<br>    corr = np.round(corr, 3)<br>    print(f&quot;Correlation between {var} and the target: {corr}&quot;)<br><br># Apply Spline Transformer to get the transformatio from &#39;AccV,&#39; &#39;AccML,&#39; and &#39;AccAP&#39;<br>from sklearn.preprocessing import SplineTransformer<br><br>spl = SplineTransformer(degree=3, n_knots=3)<br>dft = spl.fit_transform(complete_dataset_extended[multiple_variables])<br>dft = pd.DataFrame(dft, columns=spl.get_feature_names_out())<br>dft.head(2)<br><br># Concat the dataframes<br>complete_dataset_extended = pd.concat([complete_dataset_extended,dft],axis=1)</pre><h4>8- Running the training model</h4><p>We run the model and real the evaluation. If we are satisfied with the results, then we run the final model on the full dataset.</p><pre># Training model<br>model = build_model(complete_dataset_extended)<br><br># Final model with full dataset to run once the results are good<br># model = build_model_final(complete_dataset_extended)</pre><h4>9- Build the Test Data</h4><p>The following code collects and prepares test data as follows:</p><ul><li>It reads test data from ‘tdcsfog’ and ‘defog’ scenarios, adding identifiers and processing time-related columns.</li><li>The data from both scenarios is combined into a single dataset.</li><li>Subject metadata is merged into the dataset.</li><li>It merges additional task-related data.</li><li>Two linear regression models generate new features based on accelerometer data.</li><li>Cubic spline transformations are applied to specific columns.</li><li>The final test dataset is organized to match the training data format for model predictions.</li></ul><pre># get tdcsfog test data<br>tdcsfog_test_path = &#39;data/test/tdcsfog&#39;<br>tdcsfog_test_list = []<br>for file_name in os.listdir(tdcsfog_test_path):<br>    if file_name.endswith(&#39;.csv&#39;):<br>        file_path = os.path.join(tdcsfog_test_path, file_name)<br>        file = pd.read_csv(file_path)<br>        file[&#39;Id&#39;] = file_name[:-4] + &#39;_&#39; + file[&#39;Time&#39;].apply(str)<br>        file[&#39;Id_original&#39;] = file_name[:-4]<br><br>        file[&#39;Time_frac&#39;]=(file.index/file.index.max()).values<br>        tdcsfog_test_list.append(file)<br><br>tdcsfog_test = pd.concat(tdcsfog_test_list, axis = 0)<br>print(tdcsfog_test.shape)<br>tdcsfog_test.head(2)<br><br># get defog test data<br>defog_test_path = &#39;data/test/defog&#39;<br>defog_test_list = []<br>for file_name in os.listdir(defog_test_path):<br>    if file_name.endswith(&#39;.csv&#39;):<br>        file_path = os.path.join(defog_test_path, file_name)<br>        file = pd.read_csv(file_path)<br>        file[&#39;Id&#39;] = file_name[:-4] + &#39;_&#39; + file[&#39;Time&#39;].apply(str)<br>        file[&#39;Id_original&#39;] = file_name[:-4]<br><br>        file[&#39;Time_frac&#39;]=(file.index/file.index.max()).values<br>        defog_test_list.append(file)<br>defog_test = pd.concat(defog_test_list, axis = 0)<br><br># Combine all test data<br>all_test_data = pd.concat([tdcsfog_test,defog_test],axis=0).reset_index(drop=True)<br>print(all_test_data.shape)<br>all_test_data.head(2)<br><br># get metadata subject Id<br>meta_data = pd.concat([tdcsfog_metadata,defog_metadata],axis=0)<br><br># Merge the datasets<br>all_test_data_combined = pd.merge(left=all_test_data,right=meta_data,left_on=&#39;Id_original&#39;,right_on=&#39;Id&#39;,how=&#39;left&#39;)<br><br># Combine with subjects_file<br>all_test_data_combined = all_test_data_combined.drop([&#39;Id_original&#39;,&#39;Id_y&#39;,&#39;Subject&#39;],axis=1).rename(columns=({&#39;Id_x&#39;:&#39;Id&#39;}))<br><br># Combine with tasks data<br>all_test_data_combined_tasks = pd.merge(left=all_test_data_combined,right=tasks_pca,left_on=&#39;Id&#39;,right_on=&#39;Id&#39;,how=&#39;left&#39;).fillna(0)<br><br># Apply the same Feature Engineering<br>for y in tqdm(range(0,2)):<br>    all_test_data_combined_tasks[&quot;new_feat_1&quot;] = model_1.predict(all_test_data_combined_tasks[[&#39;AccV&#39;,&#39;AccAP&#39;]])<br>    all_test_data_combined_tasks[&quot;new_feat_2&quot;] = model_2.predict(all_test_data_combined_tasks[[&#39;AccV&#39;,&#39;AccML&#39;,&#39;AccAP&#39;]])<br><br>dft = spl.transform(all_test_data_combined_tasks[multiple_variables])<br>dft = pd.DataFrame(dft, columns=spl.get_feature_names_out())<br><br># Combine the data<br>all_test_data_combined_tasks = pd.concat([all_test_data_combined_tasks,dft],axis=1)<br><br># Filter the columns and arrange them to be similar to the Train Data<br>all_test_data_combined_tasks = all_test_data_combined_tasks[[&#39;Time&#39;, &#39;AccV&#39;, &#39;AccML&#39;, &#39;AccAP&#39;,<br>       &#39;Id&#39;, &#39;Time_frac&#39;, &#39;Visit&#39;, &#39;Medication&#39;, &#39;pca_1&#39;, &#39;pca_2&#39;, &#39;pca_3&#39;,<br>       &#39;new_feat_1&#39;, &#39;new_feat_2&#39;, &#39;AccV_sp_0&#39;, &#39;AccV_sp_1&#39;, &#39;AccV_sp_2&#39;,<br>       &#39;AccV_sp_3&#39;, &#39;AccV_sp_4&#39;, &#39;AccML_sp_0&#39;, &#39;AccML_sp_1&#39;, &#39;AccML_sp_2&#39;,<br>       &#39;AccML_sp_3&#39;, &#39;AccML_sp_4&#39;, &#39;AccAP_sp_0&#39;, &#39;AccAP_sp_1&#39;, &#39;AccAP_sp_2&#39;,<br>       &#39;AccAP_sp_3&#39;, &#39;AccAP_sp_4&#39;]]</pre><h4>10- Predict the Test Data</h4><pre># Predict the data<br>X_test = predict_test_data(all_test_data_combined_tasks,model)<br><br># Get the absolute values<br>X_test[&#39;StartHesitation&#39;] = np.abs(X_test[&#39;StartHesitation&#39;])<br>X_test[&#39;Turn&#39;] = np.abs(X_test[&#39;Turn&#39;])<br>X_test[&#39;Walking&#39;] = np.abs(X_test[&#39;Walking&#39;])<br><br># Ensure that id is an object value<br>X_test[&#39;Id&#39;] = X_test[&#39;Id&#39;].astype(&#39;object&#39;)</pre><h4>11- Generate a Submission file</h4><p>Finally, we generate a submission file containing the predictions of FOG events.</p><pre>submission = X_test[[&#39;Id&#39;,&#39;StartHesitation&#39;,&#39;Turn&#39;,&#39;Walking&#39;]]<br>submission.to_csv(&quot;submission.csv&quot;, index = False)</pre><h4>12- Conclusion</h4><p>Developing a machine learning model to detect freezing of gait (FOG) is a critical step towards improving the lives of individuals with Parkinson’s disease. By accurately identifying FOG episodes, medical professionals can better evaluate, monitor, and ultimately prevent these events. This article has outlined the steps involved in building such a model, from data preprocessing to model training and prediction.</p><blockquote><strong><em>For more information and to explore how my data science consulting services can benefit your company, please visit my website at </em></strong><a href="http://samuelchazy.com/"><strong><em>samuelchazy.com</em></strong></a></blockquote><blockquote><em>Explore my LLM website, offering a unique opportunity to interact with and analyze any document: </em><a href="https://gptdocanalyzer.com/"><em>https://gptdocanalyzer.com/</em></a></blockquote><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li><li><em>Check out our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a>, <a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a>, <a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c37b45c6fe7b" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/how-to-code-a-machine-learning-model-to-detect-freezing-of-gait-fog-on-kaggle-c37b45c6fe7b">How to Code a Machine Learning Model to Detect Freezing of Gait</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[METAGPT: The Path to Artificial General Intelligence]]></title>
            <link>https://ai.plainenglish.io/metagpt-af6fbb23d3a7?source=rss-53a14a703de9------2</link>
            <guid isPermaLink="false">https://medium.com/p/af6fbb23d3a7</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gpt]]></category>
            <dc:creator><![CDATA[samuel chazy]]></dc:creator>
            <pubDate>Mon, 21 Aug 2023 06:11:59 GMT</pubDate>
            <atom:updated>2023-10-26T11:32:49.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSPRZ6AnpTL3rDMg82Y8dA.jpeg" /></figure><h3><strong>I- Introduction</strong></h3><p>Remarkable progress has been made in automated task-solving through the use of multi-agent driven by large language models (LLMs). However, existing LLM-based multi-agent works primarily focus on solving simple dialogue tasks, and complex tasks are rarely studied, mainly due to the LLM hallucination problem. This leads to challenges such as achieving coherent interactions, mitigating unproductive feedback loops, and guiding meaningful collaborative engagements.</p><p>In parallel, humans have developed widely accepted Standardized Operating Procedures (SOPs) across many domains through prolonged collaborative practice. These SOPs play a critical role in supporting task decomposition and efficient coordination. SOPs outline responsibilities among team members and set standards for component outputs, ensuring that tasks are executed consistently and accurately, in alignment with the defined roles and quality standards.</p><p>MetaGPT, is an innovative framework that incorporates efficient human workflows as a meta programming approach into LLM-based multi-agent collaboration. MetaGPT equips the agent with the ability to generate standard actions output, such as high-quality requirements documents, design artifacts, flowcharts, and interface specifications. These intermediate standardized outputs significantly increase the success rate of the final code execution. by combining standardized procedures with a coordinated multi-agent system, meta programming can be used to leverage agent cooperation in dynamically constructing functions for programming tasks, such as code generation.</p><p>Firstly, each agent is identified by descriptive information, which allows the system to initialize with an appropriate role-specific prompt prefix. This approach integrates domain knowledge into agent definitions.</p><p>Secondly, efficient human workflows are analyzed to encapsulate procedural knowledge required for collaborative tasks. These SOPs are encoded into the agent architecture using role-based action specifications.</p><p>Finally, a shared environment connects agents, providing visibility into their actions and enabling them to collaborate, access tools, and share resources. Agents produce standardized action outputs to facilitate knowledge sharing.</p><p>In code generation benchmarks, MetaGPT achieves a new state-of-the-art with 81.7% and 82.3% in Pass@1 over direct methods. When compared to other LLM-based programming frameworks, such as AutoGPT, LangChain, and AgentVerse, MetaGPT can handle significantly higher levels of software complexity and distinguishes itself through its extensive functionality.</p><p><strong>The significant contributions of MetaGPT are:</strong></p><ul><li>Introduction of a meta programming framework:<br> An advanced framework for LLMs- based multi-agent collaboration. This provides teams with an accessible platform to easily develop and validate collaborative multi-agent systems.</li><li>Integration of human SOP process design:<br> This integration empowers our LLM-based agents to generate diverse, high-quality, structured intermediary designs and documentation. It significantly enhances robustness by reducing errors in LLM-based multi-agent collaboration.</li><li>Achieving state-of-the-art performance:<br> Have achieved new state-of-the-art performance on HumanEval and MBPP benchmarks through rigorous experiments.</li></ul><p>Figure.1<br>A comparative depiction of the software development SOP between MetaGPT and real-world human team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9XJYAXFiQYh1DO68nyfnjQ.png" /><figcaption>Fig.1</figcaption></figure><h3><strong>II- Framework</strong></h3><p>The design of MetaGPT framework is based on two essential layers.</p><p><strong>A- Foundational Components Layer:</strong></p><p>This layer has the building blocks of the framework including Environment, Memory, Roles, Actions, and Tools.</p><ul><li>Environment: It enables shared workspace and communications.</li><li>Memory: It stores and retrieves historical messages.</li><li>Roles: It encapsulate domain-specific skills and workflows.</li><li>Actions: It execute modular sub-tasks.</li><li>Tools: It provide common services and utilities.</li></ul><p><strong>B- Collaboration Layer</strong></p><p>This layer enables individual agents to collaborate in resolving complex problems using two mechanisms:</p><ul><li>Knowledge sharing: Agents exchange information by storing, retrieving, and sharing data to increase operational efficiency.</li><li>Encapsulating Workflows: This mechanism breaks down tasks into sub-tasks using standard operating procedures (SOP) to make the problem manageable.</li></ul><p>The combination of both mechanisms enhances the agents capabilities and increase their efficiency as illustrated in Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DA90eVhiHeLycBLIbwEz2Q.png" /><figcaption>Fig.2</figcaption></figure><h3><strong>III- Role Definitions</strong></h3><p><strong>MetaGPT allows the creation of role-based classes for LLM-based agents with key attributes:</strong></p><ul><li>Profile: It refers to the domain expertise.</li><li>Goal: It refers to the task associated to the profile.</li><li>Constraints: It refers to the limitations or boundaries linked to the goal.</li><li>Description: It refers to the extensive description of the task, responsibilities, and constraints.</li></ul><p><strong>Once the role and attributes are assigned to agents, the agents will follow specific behaviors and workflows:</strong></p><ul><li>Think &amp; Reflect: Agents receive their tasks and reflect on what needs to be the next actions.</li><li>Observe: Agents check their environment and save in their memory the important observations for later use.</li><li>Broadcast Messages: Agents broadcast messages into their environment about the current task that is being executed.</li><li>Knowledge precipitation &amp; Act: Agents can receive information from their environment, analyze it, and act upon it.</li><li>State management: Agents can monitor and updates the sub-tasks by creating a to-do-list. At each state or sub-task, agents can lock specific states until the desired sub-task is completed, allowing sequential processing of actions, or barrel ones if required.</li></ul><h3><strong>IV- Actions</strong></h3><p>Using natural language, Action serve as the atomic unit for agents to execute tasks.</p><p><strong>Actions have many attributes:</strong></p><ul><li>Prefix: A role prefix is injected into the prompt to establish a role context.</li><li>LLM proxy: To enrich action details, each Action contains an LLM proxy. This allows the extraction of important information from the inputs to the LLMs, keeping the process focused on what matters.</li><li>Standardized outputs schema: LLM results are parsed into structured outputs by defining an expected output schema.</li><li>Instruct content: The structured outputs are encapsulated as messages and published into the environment.</li><li>Retry mechanism: The agents will keep on trying to execute the actions as per the defined mechanism: Number of attempts and waiting time.</li></ul><p>Figure 3 shows a schematic diagram of the discussed standard operating procedures (SOP).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pcem5UEFhr94_XOmo8Or_g.png" /><figcaption>Fig.3</figcaption></figure><h3><strong>V- Standardized Outputs</strong></h3><p>MetaGPT workflows rely on standardized outputs of each action. These outputs ensure consistency in LLM results and maintain focus on the target task. Although MetaGPT workflows were inspired by game design workflows, they go way beyond this domain. These workflows can be implemented in content recommendation engines, search algorithm frameworks, and LLM-based operating systems.</p><p>Figure. 4 shows an example of a Collaborative Filtering Recommendation System Model, where the system interface design is automatically generated by the agent in MetaGPT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NHlr2BKTjvXw_ewV_b6cMA.png" /><figcaption>Fig.4</figcaption></figure><p>The agent also creates a sequence flow diagram based on the system interface design as shown in Figure 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f0szKPHv15JzFnCxNgvTSQ.png" /><figcaption>Fig.5</figcaption></figure><p>It is clear that the implementation of standard operating procedures (SOP) in this case improves the code quality by reducing ambiguity, misinterpretations, and confusion that can arise from freeform natural language.</p><h3><strong>VI- Knowledge Sharing &amp; Management</strong></h3><p>MetaGPT agents actively gather personalized knowledge by retrieving historical messages from a shared environment. Agents use role-based interests to extract relevant information, subscribing to meaningful message types. Messages are replicated in a unified data repository, allowing agents to register subscriptions and receive pertinent messages. Each agent’s memory cache indexes subscribed messages by content, source, and attributes, enabling contextual retrieval. This approach mirrors how human teams access shared records while customizing their views based on roles. MetaGPT’s decentralized, personalized knowledge structure enhances autonomous agent access to relevant information.</p><ul><li>Message Sharing: Messages generated by agents are replicated in the shared environment log.</li><li>Role-Based Subscriptions: Agents can subscribe based on their roles and relevant message types.</li><li>Message Dispatch: New messages meeting subscription criteria are automatically dispatched.</li><li>Memory Caching and Indexing: Agents maintain internal memory cache, while subscription messages are stored and indexed by content, senders, and recipients.</li><li>Contextual Retrieval: Shared memory pool supports caching and indexing.</li><li>Updates Synchronization: Message updates synchronize across linked agent memories.</li></ul><p>This process empowers autonomous agents to efficiently provide relevant knowledge. It also reduces irrelevant data to focus on the important tasks.</p><h3><strong>VII- Conclusion</strong></h3><p>The use of standardized outputs within MetaGPT presents a great solution for managing complex tasks. Converting complex natural language tasks into standardized outputs fosters collaborative consistency, diminishing the need for excessive dialogues that may lead to confusion. These structured and standardized outputs foster comprehension of tasks for diverse agents, streamlining communication, and bolstering the capability of LLM-based multi-agent systems in efficiently executing complex tasks.</p><p>The MetaGPT framework introduces an innovative method for addressing challenges like large language models and hallucinations. It also provides a comprehensive solution for handling intricate tasks by dividing them into manageable sub-tasks, allowing agents to focus and manage efficiently. This is achieved interactively through natural language and prompts. The evolution of the MetaGPT framework and its potential as a step toward achieving general artificial intelligence is worth exploring.</p><blockquote><strong>For more information and to explore how my data science consulting services can benefit your company, please visit my website at </strong><a href="http://samuelchazy.com/"><strong>samuelchazy.com</strong></a></blockquote><blockquote>Explore my LLM website, offering a unique opportunity to interact with and analyze any document: <a href="https://gptdocanalyzer.com/">https://gptdocanalyzer.com/</a></blockquote><h3><strong>References</strong></h3><p><strong>Paper:</strong><br>METAGPT: META PROGRAMMING FOR MULTI-AGENT COLLABORATIVE FRAMEWORK.<br>arXiv:2308.00352v3 [cs.AI] 7 Aug 2023</p><p><a href="https://arxiv.org/pdf/2308.00352.pdf">https://arxiv.org/pdf/2308.00352.pdf</a></p><p><strong>GitHub:</strong></p><p>The GitHub repository of this project is publicly available on:</p><p><a href="https://github.com/geekan/MetaGPT">GitHub - geekan/MetaGPT: 🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming</a></p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li><li><em>Check out our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a>, <a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a>, <a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af6fbb23d3a7" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/metagpt-af6fbb23d3a7">METAGPT: The Path to Artificial General Intelligence</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential Clustering Techniques in Machine Learning.]]></title>
            <link>https://ai.plainenglish.io/essential-clustering-techniques-in-machine-learning-c27e653f706d?source=rss-53a14a703de9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c27e653f706d</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[samuel chazy]]></dc:creator>
            <pubDate>Tue, 06 Jun 2023 06:22:28 GMT</pubDate>
            <atom:updated>2023-10-26T11:32:55.653Z</atom:updated>
            <content:encoded><![CDATA[<h3>Essential Clustering Techniques in Machine Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RIDv9lKU_aqmOIsaF6imSw.jpeg" /><figcaption>Image generated using Adobe Firefly</figcaption></figure><h3>I. Data Clustering Methods</h3><p>Data clustering is a powerful technique that uncovers patterns within unlabeled data, and it plays an essential role in various fields, including data analysis, pattern recognition, and machine learning. By identifying similar patterns and grouping them together, clustering helps in gaining insights, discovering hidden relationships, and making sense of complex datasets. Data clustering identifies heterogeneous morphological patterns in continuous functions underlying its discrete measurements (Ref.1).</p><p>Data clustering methods can be categorized according to the definition of cluster, and/or algorithmic features. Clustering can be considered the most important unsupervised learning problem, because It deals with finding a structure in a collection of unlabeled data (Ref.2). Clustering aims at partitioning a set of subjects into homogeneous groups so that the subjects within a group are similar to each other and are dissimilar to any member of any other group. (Ref.1).</p><p>Clustering is an unsupervised learning problem, meaning that it does not rely on predefined labels or categories. Instead, it explores the inherent structure and relationships within the data itself. This makes clustering a valuable tool for exploring and understanding complex datasets, identifying outliers or anomalies, segmenting customer groups, image segmentation, and many other applications.</p><p>In all the following examples, we will use a retail oriented dataset from Kaggle. This dataset contains Date, Customer ID, Invoice Number, Unit Price, and Quantity as features. We will be using this set to code and visualize the various clustering algorithms in Python, and to demonstrate how each algorithm cluster the data in a different manner. Please note that the Elbow Method is used to determine the number of clusters = 3, in the examples below.</p><h3>II. Hierarchical Clustering</h3><p>Hierarchical algorithms find successive clusters using previously explored clusters. Hierarchical algorithms can be Agglomerative (bottom-up) or Divisive (top-down). Agglomerative algorithms begin with each element as a separate cluster and merge the clusters in a successive manner, forming larger clusters. Divisive algorithms begin with the entire data set and then divide it into smaller clusters. A key step in a hierarchical clustering is to select a distance measure (Ref.2).</p><p>The <strong>Manhattan distance</strong> function computes the distance from one data point to the other if a grid-like path is followed. The Manhattan distance between two items is the sum of the differences of their corresponding components. The formula for this distance between a point X=(X1, X2, etc.) and a point Y=(Y1, Y2, etc.) is:</p><p><strong><em>d = n ∑i =1 | Xi — Yi |</em></strong></p><p>The <strong>Euclidean distance</strong> function measures the shortest distance between two points. The formula for this distance between a point X(XI, X2, etc.) and a point Y(Y1, Y2, etc.) is:</p><p><strong><em>d = √ ( n ∑i =1 ( Xi — Yi )**2 )</em></strong></p><h4>A- Top-Down Hierarchical Clustering (Divisive)</h4><p>Top-down hierarchical clustering, also known as divisive hierarchical clustering, is a hierarchical clustering algorithm that starts with all data points in a single cluster and recursively splits them into smaller clusters until a stopping criterion is met. It follows a top-down approach where clusters are divided based on a chosen criterion. Here’s how the Top-Down Hierarchical Clustering algorithm works (Ref.3):</p><ul><li>Start with all data points in a single cluster</li><li>Compute the dissimilarity or distance matrix between all pairs of data points using a chosen distance metric</li><li>Choose a criterion to determine the best split in each step. This could be based on distance, variance, or any other measure of dissimilarity</li><li>Split the current cluster into two sub-clusters based on the chosen criterion</li><li>Update the dissimilarity matrix to reflect the dissimilarity between the new sub-clusters and the remaining data points</li><li>Recursively apply steps 3–5 to each sub-cluster until a stopping criterion is met, such as reaching a desired number of clusters or a predefined threshold</li></ul><h4>B- Bottom-Up Hierarchical Clustering (Single-Link)</h4><p>The Agglomerative Single-Link Clustering Algorithm, also known as the nearest-neighbor or single-linkage algorithm, is a hierarchical clustering algorithm that merges clusters based on the minimum distance between any two points in the clusters. It follows a bottom-up approach where each data point starts as its own cluster, and then clusters are successively merged based on their proximity. Here’s how the Agglomerative Single-Link Clustering Algorithm works (Ref.3):</p><ul><li>Start with each data point as a separate cluster</li><li>Compute the distance between all pairs of clusters using a chosen distance metric, such as Euclidean distance</li><li>Merge the two clusters that have the smallest distance between any two points</li><li>Update the distance matrix to reflect the new distances between the merged cluster and the remaining clusters</li><li>Repeat steps 3 and 4 until all data points belong to a single cluster or until a stopping criterion is met</li></ul><h4>C- Bottom-Up Hierarchical Clustering (Complete-Link)</h4><p>The Agglomerative Complete-Link Clustering Algorithm, also known as the farthest-neighbor or complete-linkage algorithm, is another hierarchical clustering algorithm that merges clusters based on the maximum distance between any two points in the clusters. It follows a bottom-up approach similar to the single-linkage algorithm. Here’s how the Agglomerative Complete-Link Clustering Algorithm works (Ref.3):</p><ul><li>Start with each data point as a separate cluster</li><li>Compute the distance between all pairs of clusters using a chosen distance metric</li><li>Merge the two clusters that have the maximum distance between any two points</li><li>Update the distance matrix to reflect the new distances between the merged cluster and the remaining clusters</li><li>Repeat steps 3 and 4 until all data points belong to a single cluster or until a stopping criterion is met</li></ul><p><strong>Conclusion:</strong></p><p>Pros:</p><ul><li>More informative through the Dendrogram tree structure</li><li>Easier to decide on the number of clusters by looking at the Dendrogram</li></ul><p>Cons:</p><ul><li>Once a decision to combine 2 sets is made, it can not be undone</li><li>not suitable for large datasets</li><li>very sensitive to outliers</li></ul><pre>from scipy.cluster.hierarchy import dendrogram,linkage<br><br># Perform hierarchical clustering<br>linked = linkage(data[[&#39;CustomerID&#39;,&#39;Quantity&#39;]], method=&#39;single&#39;)<br><br># Plot the dendrogram<br>plt.figure(figsize=(25,10))<br>dendrogram(linked,labels=data.index,leaf_rotation=90)<br>plt.xlabel(&#39;CustomerID&#39;)<br>plt.ylabel(&#39;Distance&#39;)<br>plt.xticks(rotation=90,fontsize=8)<br>plt.title(&#39;Hierarchical Clustering Dendrogram&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HKAkQthoBrTI1KakD84xUg.jpeg" /><figcaption>Hierarchical Clustering</figcaption></figure><p>We notice that the Hierarchical Clustering can quickly become cumbersome because it is not suitable for large datasets.</p><pre>from sklearn.cluster import AgglomerativeClustering<br><br># Set the number of clusters as desired<br>agg_cluster = AgglomerativeClustering(n_clusters=3,linkage=&#39;ward&#39;)<br><br># Predict the state (cluster) for each data point<br>labels = agg_cluster.fit_predict(data[[&#39;CustomerID&#39;, &#39;Quantity&#39;]])<br><br># Add the states (clusters) to the DataFrame<br>data[&#39;Cluster&#39;] = labels<br><br># Plot the clusters using seaborn<br>plt.figure(figsize=(25,10))<br>sns.scatterplot(data=data, x=&#39;CustomerID&#39;, y=&#39;Quantity&#39;, hue=&#39;Cluster&#39;, palette=&#39;cool&#39;)<br>plt.xlabel(&#39;Customer ID&#39;)<br>plt.ylabel(&#39;Quantity&#39;)<br>plt.title(&#39;Agglomerative Clustering&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZDkiA9xJDSzwE_CKpdQTA.jpeg" /><figcaption>Agglomerative Clustering</figcaption></figure><p>We notice that the Agglomerative Clustering is better fit to cluster this dataset than the Hierarchical Clustering.</p><h3>III. Density-based Clustering</h3><p>Density-based clustering algorithms are devised to discover arbitrary-shaped clusters (Ref.2). Density-based clustering methods are a type of clustering algorithm that identify clusters based on the density of data points in the feature space. Unlike distance-based algorithms that rely on proximity measures, density-based methods consider the density of data points within a neighborhood to determine cluster assignments. These methods are particularly useful when dealing with complex cluster shapes, varying densities, and noise in the data.</p><h4>DBSCAN (density-based spatial clustering of applications with noise)</h4><p>Clusters are identified by looking at the density of points. Regions with a high density of points depict the existence of clusters whereas regions with a low density of points indicate clusters of noise or clusters of outliers. This algorithm is particularly suited to deal with large datasets, with noise, and is able to identify clusters with different sizes and shapes. The key idea of the DBSCAN algorithm is that, for each point of a cluster, the neighborhood of a given radius has to contain at least a minimum number of points, that is, the density in the neighborhood has to exceed some predefined threshold (Ref.2).</p><p>DBSCAN defines clusters as dense regions of data points separated by sparser regions. It works by defining a neighborhood around each data point and expanding it until a minimum number of points are found within the neighborhood. The algorithm categorizes data points as core points (sufficiently dense regions), border points (in the vicinity of core points but with lower density), or noise points (isolated points with insufficient density). DBSCAN does not require specifying the number of clusters in advance and can handle clusters of arbitrary shape. This algorithm needs three input parameters:</p><ul><li>eps, the radius that delimitate the neighborhood area of a point (eps neighborhood)</li><li>min_samples, the minimum number of points that must exist in the eps neighborhood</li><li>metric to be used such as Euclidean or Manhattan</li></ul><p><strong>Conclusion</strong>:</p><p>Pros:</p><ul><li>No need to estimate the number of clusters (DBSCAN will infer this)</li><li>It efficiently separates clusters of high density vs clusters of low density</li></ul><p>Cons:</p><ul><li>if the dataset has data records of varying density then it fails because eps &amp; min_samples can not be chosen separately for each of the clusters</li><li>setting up eps &amp; min_samples is very tricky</li></ul><p><strong>Here are some popular density-based clustering algorithms:</strong></p><ul><li>OPTICS (Ordering Points To Identify the Clustering Structure)</li><li>DENCLUE (Density-based Clustering)</li><li>HDBSCAN (Hierarchical Density-based Spatial Clustering of Applications with Noise)</li><li>Mean Shift Clustering</li><li>ST-DBSCAN (Spatio-Temporal Density-based Clustering of Applications with Noise)</li><li>SUBCLU (Subspace Clustering)</li><li>VDBSCAN (Variational Density-based Spatial Clustering of Applications with Noise)</li></ul><pre>from sklearn.cluster import DBSCAN<br><br>eps = 10  # Adjust this value as desired<br>min_samples = 2  # Adjust this value as desired<br>dbscan = DBSCAN(eps=eps, min_samples=min_samples,metric=&#39;euclidean&#39;)<br>clusters = dbscan.fit_predict(data[[&#39;CustomerID&#39;,&#39;Quantity&#39;]])<br><br># Add the cluster labels to the DataFrame<br>data[&#39;Cluster&#39;] = clusters<br><br># Plot DBSCAN Model using seaborn<br>plt.figure(figsize=(25,10))<br>sns.scatterplot(data=data, x=&#39;CustomerID&#39;, y=&#39;Quantity&#39;, hue=&#39;Cluster&#39;, palette=&#39;cool&#39;)<br>plt.xlabel(&#39;Customer ID&#39;)<br>plt.ylabel(&#39;Quantity&#39;)<br>plt.title(&#39;DBSCAN Model Clustering&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jshGqJbWVe-8wXt_PkxGWw.jpeg" /><figcaption>DBSCAN Model Clustering</figcaption></figure><p>We notice that DBSCAN is having a hard time clustering this dataset, because the dataset has records of varying densities. As mentioned before, finding the ideal eps and min_samples is very tricky.</p><h3>VI. Model-based Clustering</h3><p>Model-Based Clustering methods attempt to optimize the fit between the given data and some mathematical model. Such methods are often based on the assumption that the data are generated by the mixture of underlying probability distributions (Ref.2). It aims to find clusters in data by assuming a specific probabilistic model that represents the underlying distribution of the data. These algorithms estimate the parameters of the model to identify clusters based on the fit of the data to the model.</p><h4>A- Gaussian Mixture Models (GMM) or Expectation-Maximization Algorithm (EM)</h4><p>GMM is a popular algorithm for clustering data based on the assumption that the data points are generated from a mixture of Gaussian distributions. It is a probabilistic model that assigns each data point to one of the Gaussian components, representing a cluster. The algorithm estimates the parameters of the Gaussian components (mean, covariance, and weights) to determine the cluster assignments. The GMM algorithm follows an iterative approach to estimate the parameters of the Gaussian components and determine the cluster assignments. The main steps in the GMM algorithm are as follows (Ref.2):</p><ul><li><strong>Initialization:</strong> Initialize the parameters of the Gaussian components, including the mean, covariance, and weights (prior probabilities)</li><li><strong>Expectation step</strong> (E-step): Calculate the responsibility of each Gaussian component for generating each data point. This is done by computing the posterior probability of each component given the data point, using Bayes’ theorem. The responsibility represents the probability that a data point belongs to a specific cluster</li><li><strong>Maximization step</strong> (M-step): Update the parameters of the Gaussian components based on the responsibilities calculated in the E-step. This involves computing the weighted means and covariance using the data points and their responsibilities. The weights are updated based on the average responsibilities of the components</li><li><strong>Repeat</strong> steps 2 and 3 until convergence: Iterate between the E-step and M-step until the parameters of the Gaussian components and cluster assignments stabilize. Convergence is typically determined by a threshold or when the change in the log-likelihood function falls below a certain tolerance</li></ul><p><strong>Expectation Maximization Algorithm:</strong></p><ul><li>EM algorithm is implemented when the Gaussian distribution is known but the parameters mu &amp; sigma are not known</li><li>EM is an iterative method to find the max likelihood estimates of mu &amp; sigma to get the best fit model</li></ul><p><strong>Conclusion:</strong></p><p>Pros:</p><ul><li>Great for complex shapes</li></ul><p>Cons:</p><ul><li>slow because it has to find the probability distribution for each record</li><li>can get stuck in a local minimum of the log-likelihood function</li></ul><h4>B- Latent Dirichlet Allocation (LDA)</h4><p>LDA is a probabilistic generative model commonly used for topic modeling. It assumes that documents are generated from a mixture of latent topics, and each topic corresponds to a cluster. LDA estimates the topic distribution and the word distribution for each topic to identify the cluster assignments for documents. In the context of clustering, LDA can be used to discover underlying topics or themes in a collection of documents and group similar documents together. The algorithm works as follows (Ref.2):</p><ul><li><strong>Initialization</strong>: Specify the desired number of topics K, which represents the number of clusters to be formed. Also, define the hyper-parameters α and β that control the prior distributions of topics and words, respectively.</li><li><strong>Topic assignment</strong>: Randomly assign each word in each document to one of the K topics</li><li><strong>Iterative inference</strong>: Iterate through each word in each document and compute the probability that the word belongs to each topic, given the current assignments of other words in the document and the current topic-word distribution</li><li><strong>Update topic-word distribution</strong>: Based on the topic assignments and word probabilities, update the distribution of words for each topic</li><li><strong>Repeat</strong> steps 3 and 4 until convergence: Iterate the inference and update steps until the topic assignments and topic-word distributions stabilize</li></ul><p>Once the algorithm converges, each document is associated with a distribution of topics, and words are associated with a distribution of topics. This allows for clustering documents based on the similarity of their topic distributions.</p><p><strong>Conclusion:</strong></p><p>Pros:</p><ul><li>LDA is a flexible model, which means that it can be used to model a variety of different corpora</li><li>This makes it a versatile tool for a variety of different tasks</li></ul><p>Cons:</p><ul><li>can be computationally expensive, especially for large corpora</li><li>can be difficult to interpret, especially for large corpora</li></ul><h4>C- Hidden Markov Models (HMM)</h4><p>Hidden Markov Models (HMM) is a statistical model widely used in various fields, including clustering, time series analysis, speech recognition, natural language processing, and bioinformatics. HMM is a generative model that represents a sequence of observable variables as a sequence of hidden states, where the underlying states are not directly observed but inferred from the observed variables.</p><p>In the context of clustering, HMM can be used to discover underlying patterns or clusters in sequential data. The key idea behind HMM is that the observed data is generated by a probabilistic process with hidden states that evolve over time. Each hidden state represents a specific cluster or pattern, and the transitions between states capture the dynamics or dependencies among the clusters. The main components of an HMM are (Ref.2):</p><ul><li><strong>Hidden States</strong>: The hidden states represent the underlying clusters or patterns. Each state has a probability distribution over the observed variables</li><li><strong>Observations</strong>: The observed variables represent the data points or features that are available for analysis. The observed variables are generated from the hidden states according to their respective probability distributions</li><li><strong>Transition Probabilities</strong>: The transition probabilities represent the likelihood of transitioning from one hidden state to another. These probabilities capture the temporal dependencies among the hidden states</li><li><strong>Emission Probabilities</strong>: The emission probabilities represent the likelihood of observing a particular variable given a hidden state. These probabilities define the probability distribution of the observed variables for each hidden state</li></ul><p>Given an HMM, the goal in clustering is to infer the hidden states that generated the observed data. This is typically done using the Viterbi algorithm or the forward-backward algorithm, which involve estimating the most likely sequence of hidden states given the observed data.</p><p><strong>Conclusion:</strong></p><p>Pros:</p><ul><li>can capture the temporal dependencies and patterns in the data</li><li>allows for different model complexities by adjusting the number of hidden states</li><li>can handle large datasets and has efficient algorithms for learning the model parameters and performing inference</li></ul><p>Cons:</p><ul><li>assumes that the observed variables are conditionally independent given the hidden states</li><li>selecting the appropriate number of hidden states is a challenging task in HMM-based clustering</li><li>designed for modeling sequential data and may not be well-suited for non-sequential data or data without clear temporal dependencies</li><li>may lack interpretability, as the hidden states represent abstract clusters that may not have direct semantic meaning</li></ul><pre>from sklearn.mixture import GaussianMixture<br><br># Adjust the number of components as desired<br>gmm = GaussianMixture(n_components=3)<br>gmm.fit(data[[&#39;CustomerID&#39;,&#39;Quantity&#39;]])<br><br># Predict cluster labels<br>labels = gmm.predict(data[[&#39;CustomerID&#39;,&#39;Quantity&#39;]])<br><br># Add the cluster labels to the DataFrame<br>data[&#39;Cluster&#39;] = labels<br><br># Plot Gaussian Mixture Model using seaborn<br>plt.figure(figsize=(25,10))<br>sns.scatterplot(data=data, x=&#39;CustomerID&#39;, y=&#39;Quantity&#39;, hue=&#39;Cluster&#39;, palette=&#39;cool&#39;)<br>plt.xlabel(&#39;Customer ID&#39;)<br>plt.ylabel(&#39;Quantity&#39;)<br>plt.title(&#39;Gaussian Mixture Model Clustering&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kh_xxzwq_-d5BXz7SyljGQ.jpeg" /><figcaption>Gaussian Mixture Model Clustering</figcaption></figure><p>We notice that GMM clusters well this dataset similar to Agglomerative Clustering.</p><pre>from sklearn.discriminant_analysis import LinearDiscriminantAnalysis<br><br>lda = LinearDiscriminantAnalysis(n_components=1)  # Reduce to 1 dimension<br>lda_data = lda.fit(data[[&#39;CustomerID&#39;]], data[&#39;Quantity&#39;])<br><br># Add the LDA projection to the DataFrame<br>data[&#39;LDA&#39;] = lda_data<br><br># Plot LDA clusters using seaborn<br>plt.figure(figsize=(25,10))<br>sns.scatterplot(data=data, x=&#39;CustomerID&#39;, y=&#39;Quantity&#39;, hue=&#39;Cluster&#39;, palette=&#39;cool&#39;)<br>plt.xlabel(&#39;LDA Dimension&#39;)<br>plt.ylabel(&#39;Customer ID&#39;)<br>plt.title(&#39;LDA Clustering&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8V5yvH6RlFLbpPsXIhTQYg.jpeg" /><figcaption>LDA Clustering</figcaption></figure><p>We notice that LDA Clustering works well for this dataset similar to GMM Clustering.</p><pre>from hmmlearn import hmm<br><br># Set the number of components as desired<br>hmm_model = hmm.GaussianHMM(n_components=3)<br>hmm_model.fit(data[[&#39;CustomerID&#39;, &#39;Quantity&#39;]])<br><br># Predict the state (cluster) for each data point<br>labels = hmm_model.predict(data[[&#39;CustomerID&#39;, &#39;Quantity&#39;]])<br><br># Add the states (clusters) to the DataFrame<br>data[&#39;Cluster&#39;] = labels<br><br># Plot the HMM clusters using seaborn<br>plt.figure(figsize=(25,10))<br>sns.scatterplot(data=data, x=&#39;CustomerID&#39;, y=&#39;Quantity&#39;, hue=&#39;Cluster&#39;, palette=&#39;cool&#39;)<br>plt.xlabel(&#39;Customer ID&#39;)<br>plt.ylabel(&#39;Quantity&#39;)<br>plt.title(&#39;Hidden Markov Models Clustering&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-_nPq7f0EgmH_sqGAcAmw.jpeg" /><figcaption>Hidden Markov Models Clustering</figcaption></figure><p>We notice that Hidden Markov Models Clustering is trying hard to separate the data points, but fails to mark a clear separation. This is because HMM is designed for modeling sequential data and may not be well-suited for non-sequential data or data without clear temporal dependencies.</p><h3>V. Centroid-based Clustering</h3><p>Centroid-based clustering is a type of clustering algorithm that relies on the concept of centroids, which represent the center points of clusters. In this approach, clusters are formed around the centroids by assigning data points to the nearest centroid based on a distance metric. The centroid is updated iteratively until convergence, resulting in well-defined clusters. The main idea behind centroid-based clustering is to minimize the intra-cluster distances while maximizing the inter-cluster distances. By finding the centroids that optimize these criteria, the algorithm aims to group similar data points together and separate dissimilar ones.</p><h4>A- K-Means</h4><p>One of the most popular centroid-based clustering algorithms, K-Means partitions the data into a predefined number of clusters. It iteratively assigns data points to the nearest centroid and updates the centroids based on the mean of the assigned points. K-Means seeks to minimize the within-cluster sum of squares.</p><p>The k-means algorithm is popular because it is easy to implement, and its time complexity is O(n), where n is the number of patterns. A major problem with this algorithm is that it is sensitive to the selection of the initial partition and may converge to a local minimum of the criterion function value if the initial partition is not properly chosen. The algorithm works as follows (Ref.3):</p><ul><li>Choose k cluster centers to coincide with k randomly-chosen patterns or k randomly defined points inside the hyper volume containing the pattern set</li><li>Assign each pattern to the closest cluster center</li><li>Recompute the cluster centers using the current cluster memberships</li><li>If a convergence criterion is not met, go to step 2</li><li>Typical convergence criteria are: no (or minimal) reassignment of patterns to new cluster centers, or minimal decrease in squared error</li></ul><p><strong>Conclusion:</strong></p><p>Pros:</p><ul><li>Simple to understand and implement</li><li>it is an efficient algorithm, especially for large datasets</li><li>it is relatively robust to noise, which means that it can still perform well even if the data contains some outliers</li></ul><p>Cons:</p><ul><li>It is sensitive to the initial cluster centroids. This means that the results of the algorithm can vary significantly depending on how the centroids are initialized</li><li>It is not suitable for all data types. It is best suited for data that is continuous and spherical</li><li>It can create clusters that are arbitrary shapes and sizes. This can make it difficult to interpret the results of the algorithm</li></ul><h4>B- K-Medoids</h4><p>Similar to K-Means, K-Medoids aims to find representative points (medoids) within each cluster. Instead of using the mean as the centroid, K-Medoids selects the actual data points from the cluster as the medoids. It minimizes the sum of dissimilarities between the data points and their respective medoids. The basic strategy of k-medoids algorithm is each cluster is represented by one of the objects located near the center of the cluster. PAM (Partitioning around Medoids) was one of the first k-medoids algorithm is introduced. K-medoids method is more robust than k-mean in presence of noise and outliers because a medoids is less influenced by outliers or other extreme values than a mean (Ref.2).</p><h4>C- K-Means++</h4><p>K-Means++ is an improved initialization technique for the K-Means clustering algorithm. It addresses the issue of poor initialization in K-Means, where the choice of initial centroids can significantly impact the final clustering results. The K-Means++ algorithm aims to select initial centroids that are well-spaced and representative of the underlying data distribution, leading to more accurate and stable clustering outcomes. By utilizing a smart initialization strategy, K-Means++ enhances the effectiveness and robustness of the K-Means clustering algorithm. It is widely used in practice to improve the quality and efficiency of K-Means clustering, especially when dealing with complex datasets or when a high level of clustering accuracy is desired.</p><h4>D- Fuzzy C-Means</h4><p>Fuzzy C-Means (FCM) is a clustering algorithm that extends the K-Means algorithm by introducing a soft assignment of data points to clusters. Unlike K-Means, which assigns each data point to a single cluster with a binary membership value, FCM allows for partial membership of data points to multiple clusters. This fuzzy assignment reflects the degree of similarity or belonging of a data point to each cluster. FCM provides a soft assignment of data points to clusters, allowing for the representation of uncertainty and overlapping membership. This is particularly useful when dealing with datasets that exhibit ambiguity or when there is no clear separation between clusters. FCM is widely used in various domains, including pattern recognition, image segmentation, and data mining, where the flexibility of soft clustering is desired. It allows for a more nuanced understanding of the underlying data structure by considering partial memberships and can provide valuable insights into complex datasets.</p><pre>from sklearn.cluster import KMeans<br><br># Set the number of clusters as desired<br>kmeans = KMeans(n_clusters=3,n_init=&#39;auto&#39;)<br>kmeans.fit(data[[&#39;CustomerID&#39;, &#39;Quantity&#39;]])<br><br># Predict the cluster for each data point<br>labels = kmeans.predict(data[[&#39;CustomerID&#39;, &#39;Quantity&#39;]])<br><br># Add the clusters to the DataFrame<br>data[&#39;Cluster&#39;] = labels<br><br># Plot the KMeans clusters using seaborn<br>plt.figure(figsize=(25,10))<br>sns.scatterplot(data=data, x=&#39;CustomerID&#39;, y=&#39;Quantity&#39;, hue=&#39;Cluster&#39;, palette=&#39;cool&#39;)<br>plt.xlabel(&#39;Customer ID&#39;)<br>plt.ylabel(&#39;Quantity&#39;)<br>plt.title(&#39;KMeans Clustering&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdIZjfEbty2tF_ds4RYW8Q.jpeg" /><figcaption>K-Means Clustering</figcaption></figure><p>We notice that K-Means clusters the dataset well in a similar way to Agglomerative Clustering, Gaussian Mixture Model Clustering, and Latent Drichlet Allocation Clustering.</p><h3>VI. Conclusion</h3><p>This is but an overview of some of the existing data clustering methods. We discussed four main commonly used clustering techniques: hierarchical clustering, density-based clustering, model-based clustering, and centroid-based clustering, where each method has its unique characteristics and is suitable for different types of datasets and clustering objectives. The choice of clustering method depends on the specific characteristics of the dataset, the desired level of interpretability, and the clustering objectives. It is often beneficial to experiment with multiple techniques and assess their performance using appropriate evaluation metrics.</p><p>In summary, data clustering methods play a crucial role in unsupervised learning, enabling the discovery of meaningful patterns and structures within unlabeled data. The selection of the most suitable clustering method depends on various factors, and understanding the strengths and limitations of different techniques is essential for successful clustering analysis.</p><blockquote><strong>For more information and to explore how my data science consulting services can benefit your company, please visit my website at samuelchazy.com</strong></blockquote><h3>References:</h3><p>Ref.1</p><p>Review of Clustering Methods for Functional Data. Mimi Zhang and Andrew Parnell. 2023. Review of Clustering Methods for Functional Data. ACM Trans. Knowl. Discov. Data. 17, 7, Article 91 (April 2023), 34 pages. <a href="https://doi.org/10.1145/3581789">https://doi.org/10.1145/3581789</a></p><p>Ref.2</p><p>AN OVERVIEW ON CLUSTERING METHODS. T. Soni Madhulatha. Associate Professor, Alluri Instituteof Management Sciences, Warangal. IOSR Journal of Engineering. Apr. 2012, Vol. 2(4) pp: 719–725.</p><p>Ref.3</p><p>Data Clustering: A Review. A.K. JAIN, M.N. MURTY, P.J. FLYNN. ACM Computing Surveys, Vol. 31, №3, September 1999</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li><li><em>Check out our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a>, <a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a>, <a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c27e653f706d" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/essential-clustering-techniques-in-machine-learning-c27e653f706d">Essential Clustering Techniques in Machine Learning.</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Recommender Systems]]></title>
            <link>https://ai.plainenglish.io/modern-recommender-systems-6105cb23e3fb?source=rss-53a14a703de9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6105cb23e3fb</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[rankings]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[matrix]]></category>
            <dc:creator><![CDATA[samuel chazy]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 06:07:05 GMT</pubDate>
            <atom:updated>2023-10-26T11:33:03.259Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5HiHGTYQCmmbV-03FLNWA.jpeg" /></figure><h3><strong>I. Introduction</strong></h3><p>Recommender systems are gaining momentum and are spreading to many domains. They are utilized by many companies to create personalized experiences for users using machine learning algorithms. Recommender systems suggest and recommend items that are likely to be of interest to consumers based on data analysis. They are considered as effective tools to automate the personalized journey of a consumer and drive sales (Ref. 1). Recommender systems come in a variety of types and utilize a wide range of techniques such as Decision Trees, Singular Value Decomposition, and Deep Learning Techniques.</p><p>Recommender systems are implemented in a wide range of applications and industries such as E-commerce, Streaming Services, Social Media, Travel and Hospitality, Retail, Education, Healthcare, Real Estate, Beauty, and Job Search. For example, a recommender system can recommend beauty products to consumers based on their skin type, age, gender, and favorite brand. It can recommend properties to consumers based on their budget, their distance from work, the distance from the kids’ school and community. Recommender system can recommend vacation destinations, hotels, and restaurants based on consumers’ preferences, budget, style, and interests.</p><h3><strong>II. How do Recommender Systems work?</strong></h3><p>Recommender systems utilize the consumer product relationship by gathering background data to recommend or suggest a product using a statistical, machine learning, or neural algorithm. These systems work inherently to rank the product in question with respect to the consumer preference in order to output a recommendation. This consumer product relationship can be in the form of a user-product type or a product-product type. In the former, it is a direct or explicit preference of a consumer for a product, and in the latter, it is a similarity of a product to a product that the consumer prefers or in other words similar purchased products.</p><p>Moreover, recommender systems utilize two types of data, explicit and implicit data. The former is the direct information provided by the consumer such as product reviews, ratings, and likes. The latter is extracted from the consumer interaction with the product or the platform that provided the product such as purchases, search history, clicks, and views. The implicit and explicit data are combined to provide the consumer with a powerful and more accurate recommendation system (Ref. 1).</p><p>Recommender systems have always been associated with the field of information retrieval (IR), because both entities retrieve consumer data and attempts to rank the items in the data. Both entities utilize similar machine learning algorithms to train and evaluate the constructed models, but they differ in many ways as well. IR depend on interactive queries, which is implicit data, to extract consumer information, while recommender systems depend on consumer profile, which is explicit data. Going back to recommender systems, their main utility is to simplify the search and purchase process for the consumer by reducing the problem of information overload. On the other hand, it is the ability to achieve specific KPIs such as sales and consumer retention for the provider (Ref. 3).</p><p>The objective function of recommender systems is to compute an estimate of relevance of a product to a certain consumer. This estimate can be formulated as in Fig.1 (Ref. 3):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gC8qIF7X0h3PLwVo7igGwg.png" /><figcaption>Fig.1</figcaption></figure><ul><li>a set of users U</li><li>a set of items I</li><li>a utility function ƒ : U × I → R, mapping consumers and products to a utility value, and recommending the item i′ ∈ I, maximizing the utility function.</li></ul><p>The utility function ƒ returns a rating prediction, whereby the information that is used within ƒ is the consumer-product matrix of ratings. As show in the table of Fig.2, the objective of this table is to make a recommendation for consumer u1 which is computed by predicting the ratings of consumer u1 for the unrated product i4 and i5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ld-iCFj5fkwSmzQBalfdhg.png" /><figcaption>Fig.2</figcaption></figure><p>While the above consumer-product matrix is quite efficient as a utility function, it has the potential of being stronger by adding a third dimension to it which is context. Context adds impact to the recommendation of any utility by being specific to the current situation at hand. In that sense, the utility ƒ can be modified to accommodate this context variable:</p><blockquote>ƒ : U x I x C → R</blockquote><p>where C denotes the context in which a recommendation should be made (Ref. 3).</p><h3><strong>III. Recommendation Algorithms Approaches</strong></h3><p>The recommendation process can be sub-divided into three categories which are candidate generation, scoring, and ranking. Each one of these categories acts as a recommendation system based on a personalized or non-personalized tool. The first utilizes a user-based approach such as this user is similar to other users in terms of preferences, while the latter utilizes a product similarity approach such as identifying products that match or goes in the same basket as the chosen product.</p><p>Furthermore, we can identify three main approaches (Fig.3) of recommender system algorithms which are collaborative filtering, content-based filtering, and a hybrid approach (Ref. 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3TYF4SmIFzbhvRwvfgyVBQ.png" /><figcaption>Fig.3</figcaption></figure><p><strong>3.1. Collaborative Filtering:</strong></p><p>This technique, which is based on users and items similarities, is the most used technique today. By utilizing a nearest neighbors approach through a user-item or item-item matrix rating, it is capable of identifying items from similar users’ choices, interactions, and behaviors (Ref. 1).</p><p>Collaborative filtering utilizes k-nearest-neighbor (KNN algorithm) which is a weighted average of the interactions defined previously. KNN predicts the preference of a user u for an item I as a linear combination of the observed preferences for I in a subset of selected users. Items are ranked based on the utility function:</p><blockquote>ƒ(u,i) = Ci ∑ W(u,v) r(v,i)</blockquote><p>Where Ci is a normalizing term, and r(v,i) is the interaction data of v &amp; i. The weights are based on pairwise similarity W(u,v) which could be a cosine similarity or a Pearson correlation between the vectors u &amp; v. KNN is a rather old technique but still popular because it is simple to implement and inexpensive to execute (Ref. 3).</p><p><strong>3.1.1. Collaborative filtering is classified into two categories (Fig. 4):</strong></p><ul><li>memory-based or user-based collaborative filtering (Fig.4): It utilizes user-based collaborative filtering (UBCF) and item-based collaborative filtering (IBCF) algorithms. The UBCF algorithm defines the users that have the most similar ratings to the target user, while the IBCF algorithm defines the items that have the most similar ratings to the target user.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rpsMKQVnNEOPXn7P6Hp_rw.png" /><figcaption>Fig.4</figcaption></figure><ul><li>model-based collaborative filtering (Fig.5): It builds a model the represents the user’s behavior and then predicts the rating of the items. It tries to locate similar users with similar interests.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TEC4-L9HvVfcpRBOo7g5fA.png" /><figcaption>Fig.5</figcaption></figure><p><strong>3.1.2. Matrix Factorization:</strong></p><p>The most common algorithm for finding similarities between users and items using collaborative filtering is the Matrix Factorization algorithm. It utilizes historical data from the client to construct a matrix with rows that represent users and columns that represent items. Cosine similarity or Pearson correlation is then calculated between rows and columns to determine users with the highest similarity in order to make recommendations (Ref. 1).</p><p>Matrix factorization converts the space between users and items into a latent factor vector space that describes the relationship between both in a low-dimension space using the dot matrix technique. In other words, the relationship between users and items are embedded into this latent space with a hyper-parameter that dictates the number of factors just like in Principle Component Analysis (PCA). In this case, we need to minimize the cost function or error R obtained by predicting the training data after adding a regularization element such as an L2 norm to ovoid over-fitting:</p><blockquote>R (p,q;λ) = ∑(r(u,i)−q(t,i) Pu)**2 +λ(||p||+||q||)</blockquote><p>This minimization is solved by alternating the least squares or using a gradient descent. To obtain a ranking function for recommendation, a dot product ƒ(u,i) = q(t,i) Pu is used (Ref. 3).</p><p><strong>3.1.3. Ranking:</strong></p><p>Unlike point-wise rating which rates the strength of a recommendation with respect to what the user would like, ranking relies on a different metric named learning to rank or LTR. Ranking depends on the order of items rather than on a prediction error to maximize the order-wise arrangement of items for the available observations.</p><p>LTR takes a pairwise approach to define the ranking error: R(θ) = ∑∑∑ L(u,i, j | θ), where θ is the parameter of the recommendation model, and the loss L(u,i, j|θ), quantifies the difference in ranking with respect to the true labels where θ ranks i and j for u. This is summed over all pairs of items i, j that u has available training data for.</p><p>Other methods of ranking are:</p><ul><li>RankALS: It takes L(u,i, j) = ((r(u,i) − r(u, j)) − (q(t,i) Pu − q(t,j) Pu))**2 as the core pairwise ordering error to be ij minimized, and alternating least squares instead of gradient descent as the minimization procedure.</li><li>Target ranking: It introduces an evaluation metric in the objective function, such as nDCG, Mean Average Precision (MAP), or Mean Reciprocal Rank (MRR). These rankings are referred to as listwise ranking because it reflects a ranking goodness function (Ref. 3).</li></ul><p><strong>3.2. Content-based filtering:</strong></p><p>This kind of recommender system (Fig.6) is based on a single user’s past preference or past interaction with items. It collects information from the user and recommends similar items that match their preferences. In this case, a matrix is formed with the user’s features &amp; items and interactions whereby the dot product indicates similarities. The similarities are then scored and ranked to narrow down the options (Ref. 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ktki79tiuzomE5k9FCi_Pw.png" /><figcaption>Fig.6</figcaption></figure><p>Content-based filtering was based in the beginning on techniques extracted from information retrieval, where the objective was to identify and rank relevant documents. The relevance of this filtering is described as:</p><ul><li>f (u, i) = score(ContentBasedProfile(u,Content(i)), where f is the relevance factor for a given user u and item i. This scoring function matches a content-based profile of u with the content features of an item i. In a similar way to the information retrieval techniques, items can be represented using TF-IDF (Term-Frequency Inverse Document Frequency) encoding. As such, each element of the vector corresponds to a word term, and the output value gives us the importance of the term which is determined by multiplying TF and IDF.</li><li>TF is the occurrence of the word in a document i, while IDF is how relative a term is with respect to all the documents. Thus we can encode items that the user liked with TF-IDF encoding, average the vectors of the liked items, and then calculate the score using functions such as cosine similarity (Ref. 3).</li></ul><p>Generally speaking, Content-based filtering is utilized in cases where user information is sparse or data is continuously streaming.</p><p><strong>3.3. Hybrid Recommender Systems:</strong></p><p>These are systems that don’t rely on a single technique such as collaborative filtering or content-based filtering, but rather combine both by taking the advantages from each. An example would be applying quality filtering to the recommendations of a content-based filtering before collecting the final output. We can identify three major categories of Hybrid Recommender Systems (Ref. 3):</p><ul><li>Monolithic: The recommender system is built by combining a collaborative filtering approach and a user-based approach.</li><li>Parallelized (Fig.7 top): Several recommender systems are built in parallel, and then combined to get a final score through a weighted approach or to present multiple scores to the user. An example of the later is one system recommending items based on user’s preferences while the other system recommending trending items.</li><li>Pipelined (Fig.7 bottom): This recommender system is built simultaneously where the first system outputs a score that is used by the following system to rank the items. For example, the first system can rank items based on their popularity, and then the second system rates the previous items based on the preferences of the user.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a7fJZm4TvTeU-0qZQhDFNA.png" /><figcaption>Fig.7</figcaption></figure><h3><strong>IV. Recommender Systems Issues</strong></h3><p>Generally, recommender systems focus on item recommendations and so they are referred to as single-domain recommender systems. These systems face many challenges (Ref. 1):</p><ul><li>Cold-start: A major drawback to recommender systems is the cold-start problem which refers to new-users or new items. This happens when systems can’t find similar users or user preferences that would help in making recommendations to new users, because of insufficient information.</li><li>Scalability: It refers to the ability of recommender systems in handling a growing amount of information.</li><li>Data sparsity: For these recommender systems to work properly, labels need to be provided such as ratings or rankings. The labels allow the system to determine the similarity between users and items. Many users don’t leave ratings for example, which makes the recommender systems render weak or less accurate predictions.</li><li>Spammers: Many spammers try to influence the rating of some items in twisted ways. To avoid this issue, a nearest neighbor approach can be adopted. KNN, for example, can filter top users with the highest similarity to the target user, thus eliminating the spammers from the top list.</li></ul><h3><strong>V. Case studies</strong></h3><p><strong>5.1. Recommendation systems for the educational field:</strong></p><p>Recommendation systems are great tools that can be utilized in many ways in the educational field to recommend learning pathways and other educational scenarios. Educators utilize recommender systems to improve their competencies and learning practices. Here are some best practices for recommender systems in the educational field (Ref. 2):</p><ul><li>A recommendation system that uses social navigation in the context of a large distributed educational digital library.</li><li>A recommendation algorithm that recommends relevant collaborative teams of teachers to the coordinators of courses or units of learning.</li><li>A social recommender to assist young teachers to find the most suitable peers to address their problems.</li><li>A didactic social network where teachers with similar teaching styles can assist each other to find educational material.</li><li>A recommender system to assist teachers to build their courses through the Moodle learning management system.</li><li>A recommender system to support teachers to find and select suitable remote and visited labs based on core pedagogical elements of their learning designs.</li></ul><p><strong>5.2. Twitter Recommendation Engine:</strong></p><p>Twitter’s recommendation algorithm extracts latent information from Tweets, users, and engagement data. The objective of the algorithm is to answer questions such as, “What is the probability the you will interact with another user in the future?” or, “What are the communities on Twitter and what are trending Tweets within them?” (Ref. 4).</p><p>The recommendation pipeline consists of three main stages (Fig.8):</p><ul><li>Candidate sourcing: Get the best Tweets from different recommendation sources. The In-Network Source delivers the most relevant recent tweets from users that we follow, and then it ranks them using Real Graph, which predicts the likelihood of engagement between two users. The Embedding Spaces generate numerical representations of users interests and tweets content. It then calculate the similarity between any two users suing SimClusters which is derived from a custom matrix factorization algorithm. In the social Graph, candidate tweets are generated based on answers to questions such as “What Tweets did the people I follow recently engage with?” And “Who likes similar Tweets to me, and what else have they recently liked?”. These tweets are then ranked using a logistic regression model. A real-time graph processing engine using GraphJet is developed to maintain the interactions between users and tweets.</li><li>Ranking: Rank each Tweet using a machine learning model trained on Tweet interactions to optimize for positive engagement.</li><li>Heuristics and Filters: Filters such as filtering out Tweets from users we’ve blocked, NSFW content, and Tweets we’ve already seen.</li></ul><p>The Home Mixer construct the timeline just after the mentioned three stages. It is built on Product Mixer, a Scala framework that facilitates building feeds of content and acts as the software backbone that connects different candidate sources, scoring functions, heuristics, and filters. The system blends together Tweets with other non-Tweet content like Ads, Follow Recommendations, and Onboarding prompts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1OmHPCI2jzSM4IxodEhdw.png" /><figcaption>Fig.8</figcaption></figure><h3><strong>VI. Conclusion</strong></h3><p>Recommender systems are becoming crucial as more interactions between consumers and the systems is happening, thus learning more about consumers over time. Today, consumers easily get overwhelmed with the decisions that they have to make online. Recommender systems can narrow down the choices giving consumers a more personalized experience (Ref. 1).</p><p>Recommender Systems are powerful tools that can be utilized in many domains to provide personalized experiences to consumers. These systems use various techniques such as Singular Value Decomposition to suggest and recommend items based on data. Recommender systems work by utilizing consumer-product relationships and gathering explicit and implicit data to provide consumers with accurate recommendations. They utilize collaborative filtering, content-based filtering, and hybrid approaches to generate candidates, scores, and items’ ranking.</p><blockquote><strong>For more information and to explore how my data science consulting services can benefit your company, please visit my website at samuelchazy.com</strong></blockquote><h3><strong>VII. References</strong></h3><p>Ref 1:<br>Exploratory Study of Machine Learning Algorithms in Recommender Systems. Favour Onotse Momoh , Sandip Rakshit , and Narasimha Rao Vajjhala. © The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd. 2022 571 J. K. Mandal et al. (eds.), Proceedings of International Conference on Advanced<br>Computing Applications, Advances in Intelligent Systems and Computing 1406, <a href="https://doi.org/10.1007/978-981-16-5207-3_48.">https://doi.org/10.1007/978-981-16-5207-3_48.</a></p><p>Ref 2:<br>A REVIEW OF EDUCATIONAL RECOMMENDER SYSTEMS FOR TEACHERS. Mbarek Dhahri1 and Mohamed Koutheair Khribi. 18th International Conference on Cognition and Exploratory Learning in Digital Age (CELDA 2021).</p><p>Ref 3:<br>Recommender Systems: A Primer. Pablo Castellsa and Dietmar Jannach. arXiv:2302.02579v1 [cs.IR] 6 Feb 2023</p><p>Ref 4:<br>https://blog.twitter.com/engineering/en_us/topics/open-source/2023/twitter-recommendation-algorithm</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li><li><em>Check out our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a>, <a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a>, <a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6105cb23e3fb" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/modern-recommender-systems-6105cb23e3fb">Modern Recommender Systems</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Challenges and Solutions in Natural Language Processing (NLP)]]></title>
            <link>https://ai.plainenglish.io/challenges-and-solutions-in-natural-language-processing-nlp-f386787d9725?source=rss-53a14a703de9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f386787d9725</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[samuel chazy]]></dc:creator>
            <pubDate>Mon, 20 Mar 2023 06:30:44 GMT</pubDate>
            <atom:updated>2023-10-26T11:33:11.352Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8lABTy-craoQSvjChMVy3Q.jpeg" /></figure><h3>I. Introduction</h3><p><strong>Natural language processing or NLP is a sub-field of computer science and linguistics (Ref.1).</strong></p><p><strong>NLP can be generally divided into 4 major tasks:</strong></p><ul><li><strong>Syntax: </strong>It deals with syntactic features of language such as grammatical functions.</li><li><strong>Semantics: </strong>It focuses on the meaning of words and phrases.</li><li><strong>Discourse: </strong>It works with text that is longer than a single sentence.</li><li><strong>Speech: It</strong> deals with spoken languages.</li></ul><p><strong>The major challenges of NLP, which we are going to discuss in this presentation are:</strong></p><ul><li>Linguistic</li><li>Domain</li><li>Normalization</li><li>Context Challenges.</li></ul><h3>II. Linguistic Challenges</h3><p>Linguistics is a broad subject that includes many challenging categories, some of which are Word Sense Ambiguity, Morphological challenges, Homophones challenges, and Language Specific Challenges (Ref.1).</p><p><strong>II.I. Word Sense Ambiguity</strong></p><p>One of the most serious problems faced by syntactic parsers is word sense ambiguity. WSA can be divided into four categories: <strong>word senses, word sense disambiguation, POS tagging, and structural ambiguity (Ref.2).</strong></p><ul><li><strong>Word Senses: </strong>Words senses represent words as <strong>embeddings.</strong> It is defined by its co-occurrences, the counts of words that often occur nearby. But that doesn’t tell us how to define the meaning of a word sense. Words can have different senses, where sense is a discrete representation of one aspect of the meaning of the word. Dictionaries give textual definitions for each sense called <strong>glosses (Ref.2).</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f-7uz_Cd8e2Zvan1LMxfRA.png" /><figcaption>Glosses</figcaption></figure><ul><li><strong>word sense disambiguation: </strong>It is the task of selecting the correct sense of a word. An example is a small pre-selected set of target words and an inventory of senses for each word from some lexicon are chosen. With a small set we can simply use a supervised classification model to predict the correct sense. Another example is all the words in a text.<strong> </strong>This task is similar to POS tagging which I will cover in the next point, but with a much larger set of tags. This leads to a challenge referred to as data sparseness. The sparseness happens with large datasets because not all words in the vocabulary would occur in all sentences or documents. This kind of task is trained from a corpus where each word is labeled with its relevant sense (Ref.2).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nRawIiwun9RQIYv4_vdVow.png" /><figcaption>Relevant senses</figcaption></figure><ul><li><strong>POS tagging: </strong>Being a disambiguation task, the objective is to find the correct tag for the correct word. A sequence of tokenized words is given as input, and a sequence of tags corresponding exactly to each input is sorted as output. The key concept is to choose the most frequent tag in the training corpus given an ambiguous word (Ref.2).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7TBxC6CUXtR9l-_B-cHvg.png" /><figcaption>POS Tagging</figcaption></figure><ul><li><strong>structural ambiguity: </strong>When grammar can assign <strong>more than one parse to a sentence</strong>, we refer to this as structural ambiguity =&gt; The phrase in my pajamas can be part of the NP headed by elephant or a part of the verb phrase headed by shot (Ref.2).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TOoSbLwX4DRFWx3qZHn3uQ.png" /><figcaption>Structural ambiguity</figcaption></figure><p><strong>We can distinguish two kinds of structural ambiguities:</strong></p><p><strong>Attachment ambiguity: </strong>An element can be attached to the parse tree at several places =&gt; the gerundive-VP <em>flying to Paris </em>can be part of a gerundive sentence whose subject is <em>the Eiffel Tower </em>or it can be an adjunct modifying the VP headed by <em>saw.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wKeJI1_LWLCv0e9cCrAizg.png" /><figcaption>Attachment ambiguity</figcaption></figure><p><strong>Coordination ambiguity: </strong>Phrases can be joined by a conjunction such as ”and, or, etc.” =&gt; The phrase old men and women can be bracketed as [old [men and women]], referring to old men and old women, or as [old men] and [women], in which case it is only the men who are old.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CS64xXtje3bvzbAJUorZUQ.png" /></figure><p><strong>Several solutions exist to resolve structural challenges such as the CKY (Cocke-Kasami- Younger) algorithm. CKY is the most widely used dynamic-programming based approach to parsing.</strong></p><p><strong>II.II. Morphological challenges</strong></p><p>Morphology tackles the composition of words such as finding the correct lemma or stem for a word (Ref.2).</p><p><strong>Lemmatization: </strong>It is determining whether two words have the same root. This is done by figuring out if these words are built from smaller meaning-bearing units called morphemes. <strong>Stems</strong> is the essential meaning of the word, and <strong>Affixes</strong> is an addition to the stem of the word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*loheO1JD_HW92k7N6PytBQ.png" /><figcaption>Stems &amp; Affixes</figcaption></figure><p><strong>Stemming: </strong>It is removing word-final affixes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oymf307nqGCyCguaj0wqaQ.png" /><figcaption>Stemming</figcaption></figure><p><strong>II.III. Homophones challenges</strong></p><p>Several word vector representations have been proposed to describe our language (Ref.3):</p><ul><li><strong>Language modeling: </strong>predicting the next word in the sentence given a window of preceding text.</li><li><strong>Bag-of-words:</strong> the current word is predicted given both left &amp; right words. Order &amp; context are not considered.</li><li><strong>Skip-gram:</strong> predicting local context from the current word. The order of the words is considered and weighted.</li><li><strong>Log bi-linear models: </strong>combines global word co-occurrence information &amp; local context information (ex. GloVe).</li><li><strong>Bi-directional models: </strong>combines deep neural networks to model word use and its variance.</li></ul><p>Most of these models are contextual modeling techniques which leaves many of the underlying ambiguities in our language unrecognized or ignored.</p><p><strong>Spoken language:</strong> It is the ambiguity is associated with how similar the words sound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1v7U7hhEoNMOg5fIev_3fQ.png" /><figcaption>Spoken language ambiguity</figcaption></figure><p><strong>Acoustic environments: It </strong>is the ambiguity is associated with the underlying speech signal due to a wide range of acoustic environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TiMJ9QkJvrVwpQMiLe0pfQ.png" /><figcaption>Acoustic environments ambiguity</figcaption></figure><p><strong>Confusion2vec: </strong>This model estimates the hyper-space that captures the semantic and the syntax of the language. Models such as word2vec &amp; GloVe can be considered as a subspace of Confusion2vec vector space.</p><p><strong>Four methodologies based on the skip-gram model are proposed for capturing the ambiguity information:</strong></p><ul><li><strong>Top-confusion: </strong>considers the most-probable path of the confusion network and then applies skip-gram.</li><li><strong>Intra-confusion:</strong> applies skip-gram on the acoustic ambiguity dimension and ignores the contextual information.</li><li><strong>Inter-confusion: </strong>applies skip-gram on the contextual dimension &amp; over each of the acoustic ambiguous words.</li><li><strong>Hybrid model: </strong>a combination of both the intra &amp; inter-confusion models.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1rP-XZ4_l7FvWDyj3wTig.png" /><figcaption>Intra-confusion model</figcaption></figure><p><strong>II.IV. Language Specific Challenges</strong></p><p>Semitic, an Afro-Asiatic language family that includes Hebrew, Aramaic, Arabic, and Amharic, as an example, suffers from the lack of essential data. This leads to a deficiency in developing quality speech and text models. Lots of data exists on the web but they are in a row form, thus retrieving them is quite hard. Preparing data is time-consuming because it needs to be manually annotated. To overcome the above challenges, we can use transfer learning. We train a model on some of the well-resourced language using a deep neural network model which serves as a baseline system. The target language doesn’t need to be similar to the source language. Before the actual transfer learning process, feature dimension matching is done between the source languages and the target language (Ref.4).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6kj1vPVD28T8yTGVTKoM6Q.png" /><figcaption>A transfer learning model</figcaption></figure><h3>III. Domain-specific Challenges</h3><p>A model that works well in the engineering environment, might perform poorly in the medical field. A sentiment analysis task trained on product reviews might not score well on other tweets. In other words, the specificity of the input affects the abstraction or the generalization ability of the model (Ref.1).</p><p>One of the top performing models in transfer learning is the Bidirectional Encoder Representation from Transformers (BERT). It is pre-trained in two different combined and unsupervised ways using a multi-head self attention mechanism:</p><ul><li><strong>Masked language model: </strong>a sentence from the training is considered and about 15% of the words are masked. The model will predict the masked words.</li><li><strong>Next sentence prediction:</strong> two sentences are passed to the model, and it predicts which sentence comes first. The model focuses on the relationship between two sentences.</li></ul><p>Most of the General domain text is different from biomedical text and thus it negatively affect the target performance. Domain-Specific pre-training is a better option. BERT gets stuck when trained on general domain data which doesn’t contain biomedical terms. Thus, it tries to model the biomedical terms using fragmented sub-words which has no biomedical relevance. SciBERT performs better than BERT because it is trained on specific &amp; Scientific language data (Ref.5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*afLYxiWdCSk2Ilht3_EtCw.png" /><figcaption>Biomedical terms</figcaption></figure><h3>IV. Normalization Challenges</h3><p>Data needs to be consistent and normalized across the board, or else the machine learning model will find difficulty in interpreting and analyzing the given data (Ref.1).</p><p><strong>IV.I. Transforming language for processing</strong></p><p>Blogs, forums, social media posts, and customer reviews are user-generated. This data has high percentages of non-standard words. Non-standard words cause problems for text mining applications. NLP models struggle with informal language nature due to out-of-vocabulary word rates. The task of standardizing informal text is referred to as Text Normalization. It is a trade-off between maximizing the number of corrections and minimizing the number of incorrect normalization. It can include removing or adding word tokens, punctuation, and capital or lowercase letters (Ref.6).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1WqbAIlRiW2TA7vSvBQz8Q.png" /><figcaption>Non-standard language forms</figcaption></figure><p><strong>IV.</strong>II. Hybrid seq2seq(HS2S) architecture as a solution (Ref.6)</p><ul><li><strong>Hybrid model: </strong>A word-based models where the meaning is naturally preserved, else a secondary character-based model is selected.</li><li><strong>Handling unknown words: </strong>Out-of-vocab (OOV) words can be represented with a special unknown word class (UNK).</li><li><strong>Sequence-to-sequence model: </strong>seq2seq models can capture semantic meaning and long-term contextual dependencies.</li><li><strong>Adversarial Training for increased robustness: </strong>Using synthetic adversarial examples, the data is augmented.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oFN4m2Yh0DS_aXAwogMclg.png" /><figcaption>Hybrid seq2seq model</figcaption></figure><h3>V. Context Challenges</h3><p>Grasping the meaning of words, sentences, or even languages in context can be an easy task for us but can be a great challenge for machine learning algorithms (Ref.1).</p><p><strong>V.I. Improving Intent Estimation:</strong></p><p><strong>Estimation of the user intent in NLP can be difficult:</strong></p><ul><li>Identification of a connection between un-structured questions and structured data is an open problem.</li><li>A semantic characterization is needed to express sense and context of the terms.</li></ul><p><strong>WordNet:</strong></p><ul><li>WordNet, a lexical database, is the best representative semantic network.</li><li>It groups nouns, adjectives, and adverbs into relation-based synsets.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AwI6qJMtiBYKG_UledreQg.png" /><figcaption>Semantic relationships</figcaption></figure><p><strong>N-grams:</strong></p><ul><li>Fixed-size tuples of items processed by passing a sliding window on the text and giving as output a record for each token.</li><li>Useful for extracting frequent terms that surround an input word.</li></ul><p><strong>Google Books N-grams dictionaries:</strong></p><ul><li>Used for browsing and retrieving books data indexed by Google.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AhDOn4RWt6huYH5LETRjMA.png" /><figcaption>Google N-grams Viewer</figcaption></figure><p><strong>V.II. improving Intent estimation of taxonomy-driven search engines</strong></p><p>To retrieve elements indexed by a taxonomy, a procedure to extract related words through semantic relation is proposed:</p><ul><li><strong>Phase 1: </strong>Generate a bottom-line =&gt; set of files corresponding to the taxonomy categories. Make the retrieval system behave like a pattern matching system.</li><li><strong>Phase 2: </strong>Make use of Datamuse API to get related words through relations for each cluster label. Each label of the taxonomy is expanded using WordNet, Onelook dictionaries, and Google Books N-grams.</li><li><strong>Phase 3: </strong>Shape the content of the files generated. Words are trimmed by removing prefix, affix or suffix. The original lemma of each word is provided: basically =&gt; basic. Weights are assigned to non-label words (UNK class). Finally, the list of words are sorted.</li><li><strong>Phase 4: </strong>Provide the best performance in browsing files, post-processing the lists and sorting them. The procedure is scalable and can be easily applied to any context or domain.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmaeAYQa-kat8hh2j3NHcA.png" /><figcaption>Word extraction through semantic relationship</figcaption></figure><h3>VI. Summary</h3><p>In this presentation, I demonstrated the major challenges of NLP by segmenting them into four main categories, which are Linguistic, Domain, Normalization, and Context Challenges. Along this, I presented current processes, algorithms, and tools for processing the natural language content. Some of these tools are:</p><ul><li>Word Sense Disambiguation and POS Tagging</li><li>Lemmatization &amp; Stemming</li><li>Language modeling, Bag-of-words, Skip-gram, log bi-linear, and Bi-directional models.</li><li>Text Normalization</li><li>WordNet and N-grams</li></ul><p>Finally, some of the latest state of the art models were presented as an example of how to deal with these various challenges:</p><ul><li>Confusion2vec</li><li>Transfer Learning with BERT</li><li>Hybrid seq2seq(HS2S) model using adversarial networks</li><li>A procedure to improve intent estimation</li></ul><blockquote><strong>For more information and to explore how my data science consulting services can benefit your company, please visit my website at samuelchazy.com</strong></blockquote><h3>VII. Bibliography</h3><ol><li>Course Book: NLP and Computer Vision, DLMAINLPCV01. Publisher: IU Internationale Hochschule GmbH. IU International University of Applied Sciences Juri-Gagarin-Ring 152. D-99084 Erfurt. Version No.: 001–2022–0119.</li><li>Speech and Language Processing. An Introduction to Natural Language Processing, Computational Linguistics, and Speech Recognition. Third Edition. Daniel Jurafsky. Stanford University. James H. Martin. University of Colorado at Boulder. December 30, 2020.</li><li>CONFUSION2VEC 2.0: Enriching Ambiguous Spoken Language Representations With Subwords. Prashanth Gurunath Shivakumar, Panayiotis Georgiou, Shrikanth Narayanan. University of Southern California, Los Angeles, California, USA. arXiv:2102.02270v2 [cs.CL] 19 Feb 2021.</li><li>Transfer Learning for Less-Resourced Semitic Languages Speech Recognition: the Case of Amharic. Yonas Woldemariam. Dept. Computing Science, Umea ̊ University, Sweden <a href="/service/mailto:yonasd@cs.umu.se">yonasd@cs.umu.se</a>. Proceedings of the 1st Joint SLTU and CCURL Workshop (SLTU-CCURL 2020) , pages 61–69 Language Resources and Evaluation Conference (LREC 2020), Marseille, 11–16 May 2020.</li><li>Domain-Specific Language Model Pretraining for Biomedical Natural Language Processing. YU GU∗, ROBERT TINN∗, HAO CHENG∗, MICHAEL LUCAS, NAOTO USUYAMA, XIAODONG LIU, TRISTAN NAUMANN, JIANFENG GAO, and HOIFUNG POON, Microsoft Research. arXiv:2007.15779v6 [cs.CL] 16 Sep 2021.</li><li>Adapting Sequence to Sequence models for Text Normalization in Social Media. Ismini Lourentzou, Kabir Manghnani, ChengXiang Zhai. University of Illinois at Urbana-Champaign, Urbana, IL, USA {lourent2,kabirm2,czhai}@illinois.edu. arXiv:1904.06100v1 [cs.CL] 12 Apr 2019.</li><li>Automatic generation of semantic corpora for improving intent estimation of taxonomy-driven search engines. Lorenzo Massai. Università degli Studi di Firenze, Department of Mathematics and Computer Science, Firenze, Italy. arXiv:2203.16230v1 [cs.CL] 30 Mar 2022.</li></ol><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li><li><em>Check out our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a>, <a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a>, <a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f386787d9725" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/challenges-and-solutions-in-natural-language-processing-nlp-f386787d9725">Challenges and Solutions in Natural Language Processing (NLP)</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>