<?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 Anh Khoa NGO HO on Medium]]></title>
        <description><![CDATA[Stories by Anh Khoa NGO HO on Medium]]></description>
        <link>https://medium.com/@ngohoanhkhoa?source=rss-9391b4bf3dd0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*diyQycjCjkZk8DqBqrF6VA.jpeg</url>
            <title>Stories by Anh Khoa NGO HO on Medium</title>
            <link>https://medium.com/@ngohoanhkhoa?source=rss-9391b4bf3dd0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:37:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ngohoanhkhoa/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[RAG Test Sets and Where to Find them]]></title>
            <link>https://pub.towardsai.net/rag-test-sets-and-where-to-find-them-01dcd5de2398?source=rss-9391b4bf3dd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/01dcd5de2398</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[ai-generative-models]]></category>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[evaluation]]></category>
            <dc:creator><![CDATA[Anh Khoa NGO HO]]></dc:creator>
            <pubDate>Wed, 28 Aug 2024 20:01:40 GMT</pubDate>
            <atom:updated>2024-08-28T20:01:40.755Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>RAG Test Sets and Where to Find Them</strong></h3><blockquote>In the field of Question-Answering (QA) chatbot development, Retrieval-Augmented Generation (RAG) seems to be the best option at the moment. It combines the strengths of retrieval-based and generation-based models to improve the quality of generated text. However, a significant hurdle is the evaluation of RAG systems, which begins with the task of finding appropriate test sets. Through this article, I aim to disseminate a collection of RAG test sets that I’ve recently collected online. This work mainly concentrates on the set sets that we can easily download and quickly use for our experiments and benchmarks. Each dataset has a link to its download page and a link to its original paper.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zCL13Uvbp2FBaE9S" /><figcaption>Photo by <a href="https://unsplash.com/@emilianovittoriosi?utm_source=medium&amp;utm_medium=referral">Emiliano Vittoriosi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The compilation is categorized into three groups: open-domain dataset, closed-domain dataset, and dataset generation framework. An open-domain dataset is not restricted to any specific domain. Its question-answer pairs are sourced from a wide range of texts, such as Wikipedia articles. In contrast, a closed-domain dataset is limited to a specific domain or area of knowledge, such as legal, medical, or technical documents. It can be used to fine-tune the large language models (LLMs) in RAG for a specific task. Another option for a test set is the dataset generation framework, where we can create easily a test set based on a text corpus. Moreover, another way of categorizing those datasets is based on the use of an external source of knowledge. A closed-book QA dataset consists of a source of knowledge (e.g., a text corpus supporting the ground-truth answers) whereas an open-book dataset does not need one (<a href="https://arxiv.org/abs/2008.02637">Lewis et al., 2020</a>)</p><h3>Open-domain datasets</h3><p>Open-domain datasets are readily available within the NLP research community, with many derived from Wikipedia and other web content. Below, I highlight several datasets frequently used in various RAG/QA studies.</p><ul><li><a href="https://nlp.cs.washington.edu/triviaqa/">TriviaQA</a> of <a href="https://arxiv.org/abs/1705.03551">Joshi et al., (2017)</a> is a reading comprehension dataset with over 650,000 question-answer-evidence sets. It includes 95,000 question-answer pairs created by trivia fans, with six evidence documents per question on average. TriviaQA stands out because it has complex questions, varied language between questions and evidence, and requires reasoning across multiple sentences to find answers.</li><li>A Wikipedia-based dataset is <a href="https://hotpotqa.github.io/">HotpotQA</a> of <a href="https://arxiv.org/abs/1809.09600">Yang et al., (2018)</a> with 113,000 question-answer pairs. Its questions require finding and reasoning over multiple documents. They are diverse and not limited to specific knowledge bases. It provides sentence-level supporting facts for reasoning and explanations and includes fact comparison questions to test the ability to extract and compare facts.</li><li>A well-known dataset is <a href="https://rajpurkar.github.io/SQuAD-explorer/">SQuAD</a> and its versions of <a href="https://arxiv.org/abs/1806.03822">Rajpurkar et al., (2018)</a>. The latest version SQuAD 2.0 combines the 100,000 questions from SQuAD 1.1 with over 50,000 unanswerable questions that look like answerable ones, written by crowdworkers. To succeed, QA systems must answer questions when possible and recognize when no answer is supported by the text, choosing not to answer in those cases.</li><li>The most popular dataset for open-domain QA is <a href="https://ai.google.com/research/NaturalQuestions">Natural Questions</a> of <a href="https://aclanthology.org/Q19-1026/">Kwiatkowski et al., (2019)</a>. It includes real, anonymized questions from Google searches. Annotators review a question and a Wikipedia page from the top 5 search results. They provide a long answer (usually a paragraph) and a short answer (one or more entities) if available, or mark it as null if no answers are present. The dataset contains 323,045 pairs of question-answer.</li><li><a href="https://github.com/Alab-NII/2wikimultihop">2WikiMultiHopQA</a> of <a href="https://aclanthology.org/2020.coling-main.580/">Ho et al., (2020)</a> includes evidence information that shows the reasoning path for multi-hop questions. They designed a process to ensure questions require multi-hop reasoning and are of high quality. Using Wikidata and logical rules, they created natural questions that need multi-hop reasoning. Their dataset consists of 192,606 examples.</li><li>A multi-domain dataset is <a href="https://github.com/sylinrl/TruthfulQA">TruthfulQA</a> in <a href="https://arxiv.org/abs/2109.07958">Lin et al., (2022)</a>. It includes 817 questions across 38 categories like health, law, finance, and politics. Some questions are designed to be tricky, as people might answer them incorrectly due to false beliefs. QA systems need to avoid giving false answers learned from human texts. You can download the dataset from <a href="https://huggingface.co/datasets/truthfulqa/truthful_qa">Hugging Face</a>.</li><li>A multi-language dataset is <a href="https://github.com/google-research-datasets/tydiqa">TyDi QA</a> of <a href="https://arxiv.org/abs/2003.05002">Clark et al., (2020)</a>. It consists of 204,000 question-answer pairs in 11 diverse languages. These languages have different linguistic features, so QA systems that do well on TyDi QA should work well across many languages. We analyzed the data quality and unique language features not found in English-only datasets. To make the task realistic, questions are written by people who don’t know the answers and are collected directly in each language without translation.</li><li><a href="https://github.com/facebookresearch/KILT">KILT</a> of <a href="https://arxiv.org/abs/2009.02252">Petroni et al., (2021)</a> provides a dataset for several tasks e.g., open-domain question answering, fact-checking, slot filling, and entity linking require access to large, external knowledge sources. For QA, the authors provide an intensive knowledge source for many open-domain datasets such as Natural Questions, HotpotQA, TriviaQA, and ELI5. This means that they added the paragraphs supporting the ground-truth answers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8nOBXY5DWHne9cba-m33lQ.png" /><figcaption>Image in the paper of <a href="https://arxiv.org/abs/2009.02252">Petroni et al., (2021)</a></figcaption></figure><ul><li><a href="https://github.com/google-research-datasets/Attributed-QA">Attributed QA</a> of <a href="https://arxiv.org/abs/2212.08037">Bohnet et al., (2023)</a> consists of the 83,030 triplets (question, answer, and supporting texts). In this case, a QA system generates an answer to a given question and provides an attribution, which is a reference to a specific source within a fixed corpus that supports the answer. This dataset is well suited for the task of evaluating RAG.</li><li>Some nice data collections are <a href="https://huggingface.co/spaces/hallucinations-leaderboard/leaderboard">Hugging Face Hallucination Leaderboard</a>, <a href="https://mrc-datasets.github.io/datasets/">MRC dataset</a>, <a href="https://github.com/ad-freiburg/large-qa-datasets">large QA datasets</a> of Freiburg University, <a href="https://www.tensorflow.org/datasets">Tensorflow collection</a>, <a href="https://llamahub.ai/?tab=llama_datasets">Llama Hub</a>.</li></ul><h3>Closed-domain datasets</h3><p>The closed-domain datasets below are mainly in finance, with one in medicine. They must include questions, answers, and evidence, along with a corpus specific to the domain. For the financial datasets, a QA system requires numerical reasoning such as addition, subtraction, multiplication, division, counting, comparison, and composition, to answer questions.</p><ul><li><a href="https://github.com/czyssrs/FinQA">FinQA</a> of <a href="https://arxiv.org/abs/2109.00122">Chen et al., (2021)</a> is a new large-scale dataset featuring question-answer pairs over financial reports written by experts. The dataset includes annotated reasoning programs for full explainability. Analyzing financial statements is challenging due to their volume and the need for robust numerical reasoning. A QA system can answer complex questions about the tables and the texts (e.g., captions) in financial reports. Unlike general tasks, the finance domain requires numerical reasoning and an understanding of diverse representations. The financial corpus comes from <a href="https://developer.ibm.com/exchanges/data/all/fintabnet/">IBM’s FinTabNet</a>, which includes earnings reports of S&amp;P 500 companies from 1999 to 2019. Each report is a PDF file with pages outlining a company’s financials, typically containing tables and text. Note that it has annotated the tables in these reports.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQqgvPxqzBsuVmpNjCd3wA.png" /><figcaption>Statistics of FINQA. Image in the paper of <a href="https://arxiv.org/abs/2109.00122">Chen et al., (2021)</a></figcaption></figure><ul><li><a href="https://arxiv.org/abs/2210.03849">Chen et al., (2022)</a>, followed their previous work and introduced <a href="https://github.com/czyssrs/ConvFinQA">ConvFinQA</a>. It is designed to study numerical reasoning in conversational question answering. Its 3,892 conversations are challenges in modeling long-range, complex numerical reasoning in real-world conversations.</li><li>Another finance dataset is <a href="https://github.com/NExTplusplus/TAT-QA">TAT-QA</a> of <a href="https://arxiv.org/abs/2105.07624">Zhu et al., (2021)</a>. It is based on 500 financial reports released in 2019–2020 from <a href="https://www.annualreports.com/">annualreports.com</a>. This dataset consists of 16,552 questions associated with 2,757 hybrid contexts from those financial reports. Since it is not easy to obtain those 500 financial reports, I suggest extracting the texts from the hybrid contexts to create the corpus for the RAG database.</li><li><a href="https://github.com/patronus-ai/financebench">FinanceBench</a> of <a href="https://arxiv.org/abs/2311.11944">Islam et al., (2023)</a> is designed to evaluate the performance of LLMs in answering financial questions. It includes 10,231 questions about publicly traded companies, along with answers and evidence. It covers 40 companies that are publicly traded in the USA and 361 public filings, released between 2015 and 2023, including 10Ks, 10Qs, 8Ks, and Earnings Reports. The questions are realistic and cover various scenarios, aiming to be straightforward to set a minimum performance standard. On their GitHub page, only 150 triplets are published. It also contains 360 PDF reports to create a database for our QA systems. The rest of the dataset can be accessed by request via email at <a href="/service/mailto:contact@patronus.ai">contact@patronus.ai</a>.</li><li>The medical dataset comes from the <a href="http://www.bioasq.org/">BioASQ</a> challenge (<a href="https://bmcbioinformatics.biomedcentral.com/articles/10.1186/s12859-015-0564-6">Tsatsaronis et al., 2015</a>), which focuses on biomedical semantic indexing and QA. These challenges cover a variety of tasks, including hierarchical text classification, machine learning, information retrieval, QA from texts and structured data, multi-document summarization, etc. To access this dataset, we need to register for the challenge. However, you can easily download its subset on <a href="https://huggingface.co/datasets/rag-datasets/rag-mini-bioasq">Hugging Face</a>. It includes 4,720 examples and a text corpus of 40,200 paragraphs.</li><li><a href="https://github.com/night-chen/ToolQA">ToolQA</a>, created by <a href="https://arxiv.org/abs/2306.13304">Zhuang et al. (2023)</a>, is a new way to evaluate RAG. LLMs often struggle with hallucinations and numerical reasoning. The authors suggest using external tools to improve LLMs’ question-answering abilities. Current evaluations don’t distinguish between questions that LLMs can answer on their own and those that need external tools. ToolQA addresses this by providing a dataset to test LLMs’ use of external tools. It includes data from 8 domains and defines 13 types of tools for gathering information, with different knowledge formats (e.g., tabular database, professional ability, graph, and pure-text corpus).<br>- We all know that LLMs are trained on a lot of internet data, including encyclopedic sources like Wikipedia. This can overlap with test data, leading to misleading evaluations. To improve this, <a href="https://arxiv.org/abs/2406.11811v1">Monteiro et al., (2024)</a> propose a new test dataset called <a href="https://huggingface.co/datasets/ServiceNow/repliqa">RepLiQA</a>. It has five test sets, four of which were available online after. Each sample includes a human-made reference document with an imaginary scenario, a question about the document, a ground-truth answer from the document, and a paragraph containing the answer. Accurate answers require finding relevant content in the provided document.</li><li>At the end of this list, I put a nice collection of Hugging Face which aims to collect the RAG test sets: <a href="https://huggingface.co/rag-datasets">rag-datasets</a>.</li></ul><h3>Dataset generation framework</h3><p>This section presents several attempts to automatically generate a dataset for RAG evaluation. We only need to find a corpus of your choice or extract text from the raw source of knowledge.</p><ul><li>RAGEval of <a href="https://arxiv.org/abs/2408.01262">Zhu et al., (2024)</a> is a new framework that creates evaluation datasets to test LLMs in different scenarios. It generates diverse documents and question-answer pairs from seed documents. RAGEval uses three metrics (e.g., Completeness, Hallucination, and Irrelevance) to evaluate LLM responses. This helps better assess LLMs’ knowledge usage in specific domains, avoiding confusion about the source of knowledge in existing QA datasets. Just one thing there is no code available for this framework.<br>- <a href="https://github.com/Giskard-AI/giskard">Giskard</a> is an open-source Python library designed to automatically identify performance, bias, and security issues in AI applications. In RAG evaluation, an LLM automatically generates 6 different questions (complex questions, conversational questions, distracting questions, double questions, simple questions, situational questions) types for an evaluation dataset. The text corpus must be in the dataframe format where each row is a paragraph.<br>- <a href="https://docs.ragas.io/en/latest/getstarted/testset_generation.html">RAGAS</a> also provides a nice LLM-based framework to generate a synthetic evaluation dataset.</li></ul><p>Through this work, I hope that my collection of test sets provides a valuable resource for researchers and developers in the field of QA chatbot development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01dcd5de2398" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/rag-test-sets-and-where-to-find-them-01dcd5de2398">RAG Test Sets and Where to Find them</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips you must known before jumping into any PySpark project]]></title>
            <link>https://blog.stackademic.com/tips-you-must-known-before-jumping-into-any-pyspark-project-b6f04c4aa399?source=rss-9391b4bf3dd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6f04c4aa399</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[Anh Khoa NGO HO]]></dc:creator>
            <pubDate>Wed, 03 Jul 2024 10:39:58 GMT</pubDate>
            <atom:updated>2024-07-08T02:30:43.538Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uelE0IzDfe6MUGuv" /><figcaption>Photo by <a href="https://unsplash.com/@lucabravo?utm_source=medium&amp;utm_medium=referral">Luca Bravo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Lately, I completed a machine learning project utilizing PySpark on Databricks. The project involved building a standard data pipeline for a classification task, which included tasks such as data processing, implementing various classification models, and evaluating their effectiveness. Initially, working with PySpark posed more challenges than I had anticipated. Allow me to elaborate on the reasons behind this.</blockquote><ul><li>After writing code to transform a dataframe, I eagerly anticipated checking the output using my trusty <em>print()</em> function. However, PySpark made me wait anxiously for what felt like an eternity before finally revealing the results. Sometimes, even simple transformations like <em>count</em> or <em>shape</em> would take over 5 minutes to process. While I understand that Spark is incredibly efficient when handling large datasets, especially when compared to Pandas, coding in Spark was far from a seamless experience for me. The sluggishness could be attributed to factors such as Spark’s lazy transformation mechanism and the configuration of my virtual machine on Databricks.</li><li>Another hurdle in this Spark project was the difficulty of integrating other libraries into the Spark pipeline. Additionally, the machine learning library of Spark, MLlib (Dataframe-based), lacks many features and requires better documentation.</li></ul><p>If you are facing similar challenges with Spark at the moment, let’s take a look at my findings.</p><h3>Remember to use cache()</h3><p>When working with PySpark and facing challenges like long wait times for output and difficulty integrating other libraries into the pipeline, one useful technique to improve performance is using the <em>cache()</em> method.</p><p>The <em>cache()</em> method in PySpark allows you to persist intermediate results in memory across multiple actions, which can significantly speed up subsequent computations by avoiding unnecessary re-evaluation of transformations. By caching dataframes that are reused in your pipeline, you can reduce the computational overhead and improve overall performance.</p><p>To use the <em>cache()</em> method, simply call it on the dataframe that you want to cache. For example:</p><pre>df_cached = df.cache()</pre><p>By caching the dataframe <em>df</em>, subsequent operations that depend on it will run faster as the data is stored in memory and readily available for reuse. It’s important to note that caching is lazy in Spark, meaning that the actual caching operation will only occur when an action is triggered.</p><p>In your machine learning project on Databricks, leveraging the <em>cache() </em>method strategically can help optimize the performance of your data pipeline, especially when dealing with repeated computations or transformations on large datasets. This can lead to faster iteration times and a more efficient workflow overall.</p><h3>Write a UDF</h3><p>Another useful technique in PySpark for custom data processing tasks is User-Defined Functions (UDFs). UDFs allow you to apply custom Python functions to individual or multiple columns in a dataframe, enabling you to perform complex transformations that are not directly supported by built-in Spark functions.</p><p>To create a UDF in PySpark, you can define a regular Python function and then register it as a UDF using the <em>udf()</em> function from the <em>pyspark.sql.functions</em> module. Here’s an example of how you can create and apply a UDF to a dataframe:</p><pre>from pyspark.sql.functions import udf<br>from pyspark.sql.types import StringType<br><br># Define a Python function<br>def custom_function(value):<br>    # Perform custom transformation<br>    return value.upper()<br><br># Register the function as a UDF<br>custom_udf = udf(custom_function, StringType())<br><br># Apply the UDF to a dataframe column<br>df = df.withColumn(&#39;new_column&#39;, custom_udf(df[&#39;existing_column&#39;]))</pre><p>In the above example, we define a custom Python function <em>custom_function</em> that converts a string to uppercase. We then register this function as a UDF using <em>udf()</em> and apply it to a column in the dataframe <em>df</em>, creating a new column with the transformed values.</p><p>UDFs are particularly useful when you need to apply complex logic or transformations to your data that cannot be easily expressed using built-in Spark functions. However, it’s important to use UDFs carefully as they can impact performance, especially when working with large datasets.</p><h3>Customize a PySpark transformer</h3><p>To customize a PySpark transformer, you can create a custom transformer class by extending the <em>Transformer</em> class from the <em>pyspark.ml</em> module. This allows you to define your own data transformation logic and encapsulate it within a reusable component that can be integrated into your machine learning pipelines.</p><p>Here’s an example of how you can create a custom transformer in PySpark:</p><pre>from pyspark.ml import Transformer<br>from pyspark.ml.param.shared import HasInputCol, HasOutputCol<br>from pyspark.sql import DataFrame<br>from pyspark.sql.functions import col<br><br>class CustomTransformer(Transformer, HasInputCol, HasOutputCol):<br>    def __init__(self, inputCol=None, outputCol=None):<br>        super(CustomTransformer, self).__init__()<br>        self.setInputCol(inputCol)<br>        self.setOutputCol(outputCol)<br><br>    def _transform(self, df: DataFrame) -&gt; DataFrame:<br>        # Custom transformation logic<br>        df_transformed = df.withColumn(self.getOutputCol(), col(self.getInputCol()) * 2)<br>        return df_transformed</pre><p>In the above example, we define a custom transformer class <em>CustomTransformer</em> that multiplies the values in the input column by 2 and stores the result in the output column. The class extends the <em>Transformer</em> class and includes <em>HasInputCol</em> and <em>HasOutputCol</em> traits to specify the input and output columns for the transformation. Note that if there are more than one input or output, you can use <em>HasInputCols</em> or <em>HasOutputCols</em> (with a <em>s</em>).</p><p>Within the <em>_transform</em> method, which is a required method to implement in custom transformers, we define the custom transformation logic using PySpark DataFrame operations. In this case, we simply multiply the values in the input column by 2 to create the transformed dataframe.</p><p>Once you have defined your custom transformer class, you can incorporate it into your PySpark machine learning pipeline like any other built-in transformer. Here’s an example of how you can use the custom transformer in a pipeline:</p><pre>from pyspark.ml.pipeline import Pipeline<br>from pyspark.ml.feature import VectorAssembler<br><br># Create an instance of the custom transformer<br>custom_transformer = CustomTransformer(inputCol=&quot;input_column&quot;, outputCol=&quot;output_column&quot;)<br><br># Define a pipeline with the custom transformer<br>pipeline = Pipeline(stages=[custom_transformer])<br><br># Fit the pipeline on your data<br>pipeline_model = pipeline.fit(data)<br><br># Transform the data using the pipeline<br>transformed_data = pipeline_model.transform(data)</pre><p>By creating custom transformers in PySpark, you can tailor your data processing steps to specific requirements and enhance the flexibility and extensibility of your machine learning pipelines. This allows you to encapsulate complex data transformations in a modular and reusable manner, making your code more maintainable and scalable.</p><p>With these tips in hand, you will be well-equipped to tackle any PySpark project with confidence and achieve your desired outcomes.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <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://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6f04c4aa399" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/tips-you-must-known-before-jumping-into-any-pyspark-project-b6f04c4aa399">Tips you must known before jumping into any PySpark project</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</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 quickly set up a benchmark for deep learning models with Kedro ?]]></title>
            <link>https://pub.towardsai.net/how-to-quickly-set-up-a-benchmark-for-deep-learning-models-with-kedro-4490c1bf00b2?source=rss-9391b4bf3dd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4490c1bf00b2</guid>
            <category><![CDATA[kedro]]></category>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[experiment]]></category>
            <dc:creator><![CDATA[Anh Khoa NGO HO]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 16:01:44 GMT</pubDate>
            <atom:updated>2024-01-11T16:01:44.205Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Quickly Set up a Benchmark for Deep Learning Models With Kedro?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*alSpdedVFUYVcsVU" /><figcaption>Photo by <a href="https://unsplash.com/@altumcode?utm_source=medium&amp;utm_medium=referral">AltumCode</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>As a data scientist, I used to struggle with experiments involving the training and fine-tuning of large deep-learning models. For each experiment, I had to carefully document its hyperparameters (usually embedded in the model’s name, e.g., </em><em>model_epochs_50_batch_100), the training dataset used, and the model&#39;s performance. Managing and reproducing experiments became highly complex during this time. Then, I discovered Kedro, which resolved all my issues. If you are conducting experiments in machine learning, I believe this article will prove immensely beneficial.</em></p><h3>What do we need to know about Kedro?</h3><p><a href="https://kedro.org/">Kedro</a>, an open-source toolbox, provides an efficient template for conducting experiments in machine learning. It facilitates the creation of various data pipelines, including tasks such as data transformation, model training, and the storage of all pipeline outputs. Kedro revolves around three crucial concepts:</p><ul><li>Data catalog: the data catalog acts as a registry for all sources that the project can use to manage loading and saving data. It includes input datasets, processed datasets, and models. These sources are stored as dictionaries, referred to names (strings), in Yaml files. E.g., in the code below, when we call input_dataset, Kedro returns the csv file in filepath.</li></ul><pre>input_dataset:<br>  type: pandas.CSVDataSet<br>  filepath: data/01_raw/dataset.csv<br>  <br> processed_dataset:<br>  type: pandas.CSVDataSet<br>  filepath: data/02_intermediate/dataset.csv</pre><ul><li>Node: a node serves as a wrapper for a <a href="https://docs.kedro.org/en/stable/resources/glossary.html#node">pure Python function</a> that defines the inputs and outputs of that function. It represents a small step in the pipeline. For example, in data processing, nodes can be defined for tasks like concatenating dataframes or creating new features. Inputs and outputs are sourced from the data catalog.</li></ul><pre>from kedro.pipeline import node<br> <br> def process_data(df1, df2):<br>  return df1 + df2<br> <br> node_process_data = node(func=process_data, inputs=[”input_data”, ”input_data”], outputs=“processed_data”</pre><ul><li>Pipeline: a pipeline consists of a list of nodes where inputs and outputs are interconnected.</li></ul><pre>from kedro.pipeline import pipeline<br> <br> pipeline_process_data = pipeline([node_process_data])</pre><p>Kedro also boasts several valuable plugins: <a href="https://docs.kedro.org/projects/kedro-viz/en/stable/">kedro-viz</a> for visualizing data pipelines, <a href="https://github.com/Galileo-Galilei/kedro-mlflow">kedro-mlflow</a> for facilitating MLflow integration, and <a href="https://github.com/getindata/kedro-sagemaker">kedro-sagemaker</a> for running a Kedro pipeline with Amazon SageMaker, etc., (<a href="https://docs.kedro.org/en/stable/extend_kedro/plugins.html">read more</a>).</p><h4>Kedro-viz</h4><p>This <a href="https://docs.kedro.org/projects/kedro-viz/en/stable/">plugin</a> serves as an interactive development tool for visualizing pipelines built with Kedro. It allows the display of dataframes and charts generated through the pipeline, facilitating the comparison of different experiment runs with a single click. In this article, we’ll explore how to track hyperparameters and performance scores of deep learning models using kedro-viz.</p><p>Now, let’s delve into creating a benchmark in three steps.</p><h3>Step 1: set up our experiment</h3><p>The initial step involves installing the required library, Kedro, along with additional dependencies like PyTorch (build a deep learning model) and kedro-viz, using pip install. For detailed instructions, refer to <a href="https://docs.kedro.org/en/stable/get_started/install.html">installing kedro</a>, <a href="https://github.com/kedro-org/kedro-viz">installing kedro-viz</a>. It&#39;s important to note that there are variations between Kedro versions, so we specifically set the version to 0.19.1. Additionally, it is advisable to create a Python environment (consider using conda with the command conda create --name environment_name).</p><pre>pip install kedro==0.19.1<br>pip install kedro-viz<br><br>pip3 install torch</pre><p>Creating a project template with necessary files and folders is achieved with the following command (<a href="https://docs.kedro.org/en/stable/get_started/new_project.html#">read more</a>):</p><pre>kedro new</pre><p>After providing the project name and configuring options, the resulting folder structure includes:</p><ul><li>conf: This folder keeps our configuration settings for different stages of our data pipeline (e.g., development, testing, and production stage). By default, Kedro has a base and a local environment. <a href="https://docs.kedro.org/en/stable/configuration/configuration_basics.html#">Read more</a>.<br>- base contains the default settings that are used across our pipelines:(a)catalog.yml: this is a default yaml file to describe our data catalog. If we want to create more catalog files, their names must have the format catalog_*.yml. (b)parameters.yml: this is a default yaml file to describe our default parameters. A general format for naming these files is parameters_*.yml.<br>- local is used for configuration that is either user-specific (e.g. IDE configuration) or protected (e.g. security keys). These local settings can override the settings in the folder base.</li><li>data: it contains all inputs/outputs of our pipeline (see Data Catalog). Kedro proposes a list of sub-folders to store these inputs/outputs e.g., raw data in 01_raw, pre-processed data in 02_intermediate, trained models in 06_models, predicted data in 07_model_output, performance scores and figures in 08_reporting.<br>- 01_raw <br>- 02_intermediate <br>- 03_primary <br>- 04_feature <br>- 05_model_input <br>- 06_models <br>- 07_model_output <br>- 08_reporting</li><li>docs: this is for documentation. You can use Sphinx to quickly build documentation.</li><li>logs: we use this folder to keep all logs.</li><li>notebooks: we put our jupyter notebooks here.</li><li>src: houses code, including functions, nodes, and pipelines.</li></ul><p>To initiate an empty pipeline, utilize the command kedro pipeline create pipeline_name. Subsequently, a folder named pipeline_name is generated, and all created pipeline folders are stored in the directory src/project_name/pipelines. Within a pipeline folder pipeline_name, two essential files are present:</p><ul><li>nodes.py: contains node functions contributing to data processing.</li><li>pipeline.py: used for constructing the pipeline.</li></ul><p>Furthermore, a configuration settings file, parameters_&lt;pipeline_name&gt;.yml, is established in conf/base/ to store parameters specific to the created pipeline. In the subsequent step, we will customize these files to define our pipeline.</p><h3>Step 2: define our data pipeline</h3><p>Utilizing a small dataset (sklearn.datasets.load_digits), we define a simple pipeline that involves getting data and storing it locally.</p><ul><li>In nodes.py, we define a function to get the dataset.</li></ul><pre>import pandas as pd<br>from sklearn.datasets import load_digits<br><br>def get_dataset() -&gt; pd.DataFrame:<br> data = load_digits()<br> df_data = pd.DataFrame(data[&#39;data&#39;], columns=data[&#39;feature_names&#39;])<br> df_data[&#39;target&#39;] = data[&#39;target&#39;]<br> return df_data</pre><ul><li>In the file src/project_name/pipelines/pipeline_name/pipeline.py, we generate a list of nodes named pipeline_example. Each node comprises func (the function&#39;s name, e.g., get_dataset), inputs, and outputs. The nature of inputs and outputs can be a string, a list of strings, or None, depending on the inputs/outputs of the corresponding function. It&#39;s important to note that a string denotes a data name that we can later utilize in the subsequent node of our pipeline.</li></ul><pre>from kedro.pipeline import Pipeline, pipeline, node<br><br>from .nodes import get_dataset<br><br>def create_pipeline(**kwargs) -&gt; Pipeline:<br> pipeline_example = [node(<br>       func=get_dataset,<br>       inputs=None,<br>       outputs=&quot;raw_data&quot;<br>       )<br>      ]<br> return pipeline(pipeline_example)</pre><ul><li>We define data names in conf/base/catalog.yml and specify their storage details (filepath). There are many options for storing data: local file systems, network file systems, cloud object stores, and Hadoop. <a href="https://docs.kedro.org/en/stable/data/data_catalog.html">Read more</a>.</li></ul><pre>raw_data:<br> type: pandas.CSVDataset<br> filepath: data/01_raw/raw_data.csv</pre><h3>Step 3: define our model</h3><p>Now, we create our neural network model with PyTorch. We build a simple neural network with 2 feed-forward layers. Recall that the dataset Digits has 64 features and 10 classes. Therefore, the input dimension of our first layer is 64, and the output dimension of our last layer is 10. We add a softmax layer for returning probabilities.</p><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br>class NeuralNetwork(nn.Module):<br>    def __init__(self, dimension):<br>        super(NeuralNetwork, self).__init__()<br>        self.linear_1 = nn.Linear(64, dimension)<br>        self.linear_2 = nn.Linear(32, dimension)<br>        self.softmax = nn.Softmax(dim=1)<br><br>    def forward(self, x):<br>        x = F.relu(self.linear_1(x))<br>        x = F.relu(self.linear_2(x))<br>        x_prob = self.softmax(x)<br>        return x_prob</pre><p>The associated functions for the pipeline (e.g., splitting dataset, fitting model, predicting data and evaluating model) are defined in nodes.py.</p><pre>def split_dataset(df: pd.DataFrame, test_size: float) -&gt; Tuple[pd.DataFrame]:<br>    y = df.pop(&#39;target&#39;)<br>    X = df<br><br>    df_X_train, df_X_test, df_y_train, df_y_test = train_test_split(X, y, test_size=test_size)<br><br>    return df_X_train, df_X_test, df_y_train, df_y_test<br><br>def fit_model(df_X: pd.DataFrame, df_y: pd.DataFrame, epochs: int, batch_size: int, dimension: int) -&gt; Tuple[nn.Module, dict]:<br>    model = NeuralNetwork(dimension=dimension)<br>    optimizer = torch.optim.SGD(model.parameters(), lr=0.002)<br>    tensor_X = torch.from_numpy(df_X.to_numpy()).float()<br>    tensor_y = torch.from_numpy(df_y.to_numpy().squeeze())<br><br>    dataloader = DataLoader(<br>        TensorDataset(tensor_X, tensor_y),<br>        batch_size=batch_size,<br>        shuffle=True<br>    )<br><br>    for epoch in range(epochs):<br>        for x, y in dataloader:<br>            optimizer.zero_grad()<br>            y_prob = model.forward(x)<br>            loss = nn.NLLLoss()(torch.log(y_prob), y)<br>            loss.backward()<br>            optimizer.step()<br>    <br>    hyperparams = {<br>        &#39;epochs&#39;: epochs, <br>        &#39;batch_size&#39;: batch_size,<br>        &#39;dimension&#39;: dimension<br>    }<br>    <br>    return model, hyperparams<br><br>def predict_data(model: nn.Module, df_X: pd.DataFrame, batch_size: int) -&gt; pd.DataFrame:<br>    model = NeuralNetwork()<br>    tensor_X = torch.from_numpy(df_X.to_numpy()).float()<br><br>    dataloader = DataLoader(<br>        tensor_X,<br>        batch_size=batch_size,<br>    )<br>    <br>    y_predict = []<br>    for x in dataloader:<br>        y_prob = model.forward(x)<br>        y_predict += list(torch.argmax(y_prob, dim=1).detach().numpy())<br><br>    df_y_predict = pd.DataFrame(y_predict, index=df_X.index, columns=[&#39;predict&#39;])<br>    <br>    return df_y_predict<br><br>def evaluate_model(df_y_test: pd.DataFrame, df_y_predict: pd.DataFrame) -&gt; dict:<br>    f1_score = metrics.f1_score(df_y_test, df_y_predict, average=&quot;macro&quot;)<br>    precision_score = metrics.precision_score(df_y_test, df_y_predict, average=&quot;macro&quot;)<br>    recall_score = metrics.recall_score(df_y_test, df_y_predict, average=&quot;macro&quot;)<br>    <br>    scores = {<br>        &quot;f1_score&quot;: f1_score,<br>        &quot;precision_score&quot;: precision_score,<br>        &quot;recall_score&quot;: recall_score,<br>    }<br>    <br>    return scores</pre><p>Our pipeline.py becomes:</p><pre>from kedro.pipeline import Pipeline, pipeline, node<br>from .nodes import get_dataset, split_dataset, fit_model, predict_data, evaluate_model<br><br>def create_pipeline(**kwargs) -&gt; Pipeline:<br>    pipeline_example = [node(<br>        func=get_dataset,<br>        inputs=None,<br>        outputs=&quot;raw_data&quot;),<br>        node(<br>            func=split_dataset,<br>            inputs=[&quot;raw_data&quot;, &quot;params:test_size&quot;],<br>            outputs=[&quot;X_train&quot;, &quot;X_test&quot;, &quot;y_train&quot;, &quot;y_test&quot;]<br>        ),<br>        node(<br>            func=fit_model,<br>            inputs=[&quot;X_train&quot;, &quot;y_train&quot;, &quot;params:epochs&quot;, &quot;params:batch_size&quot;, &quot;params:dimension&quot;],<br>            outputs=[&quot;model&quot;, &quot;hyperparams&quot;]<br>        ),<br>        node(<br>            func=predict_data,<br>            inputs=[&quot;model&quot;, &quot;X_test&quot;, &quot;params:batch_size&quot;],<br>            outputs=&quot;y_predict&quot;<br>        ),<br>        node(<br>            func=evaluate_model,<br>            inputs=[&quot;y_test&quot;, &quot;y_predict&quot;],<br>            outputs=&quot;scores&quot;<br>        )]<br><br>    return pipeline(pipeline_example)</pre><p>The nodes split_dataset, predict_data, and evaluate_model yield the following dataframes: X_train, X_test, y_train, y_test, y_predict, and scores. These are specified in conf/base/catalog.yml with a structure analogous to that of raw_data. Additionally, parameters such as test_size, epochs, batch_size, and dimension (the dimension of the hidden layer) are stored in conf/base/parameters.yml.</p><pre>test_size: 0.2<br>epochs: 5<br>batch_size: 10<br>dimension: 32</pre><p>The fit_model function produces the trained model, represented as a PyTorch <a href="https://pytorch.org/docs/stable/generated/torch.nn.Module.html">module</a>, which is not a standard component in the Kedro data catalog. Consequently, an AbstractDataset must be defined in this case. Within the src/project_name/pipelines/pipeline_name/ directory, we create a subfolder named extras. Inside this subfolder, a Python file, for instance, torch_model.py, is added. It&#39;s essential to include an empty file named __init__.py to enable Kedro&#39;s access to torch_model.py. Below is an example of an AbstractDataSet with three crucial functions: _exists, _save, and _load. For the latter two functions, we follow the <a href="https://pytorch.org/tutorials/beginner/saving_loading_models.html">PyTorch tutorial</a> on saving and loading models under pickle format. While the <a href="https://github.com/Galileo-Galilei/kedro-mlflow">kedro-mlflow</a> plugin for Kedro can be used to store trained models, this work opts not to employ any additional plugins.</p><pre>from os.path import isfile<br>from typing import Any, Dict<br>import torch<br>from kedro.io import AbstractDataset<br><br>class TorchModel(AbstractDataset):<br><br>    def _describe(self) -&gt; Dict[str, Any]:<br>        return dict(filepath=self._filepath)<br><br>    def __init__(<br>        self,<br>        filepath: str,<br>    ) -&gt; None:<br>        self._filepath = filepath<br><br>    def _exists(self) -&gt; bool:<br>        return isfile(self._filepath)<br><br>    def _save(self, model) -&gt; None:<br>        torch.save(model, self._filepath)<br><br>    def _load(self):<br>        model = torch.load(self._filepath)<br>        return model</pre><p>The corresponding catalog entry in conf/base/catalog.yml is:</p><pre>model:<br>    type: project_name.pipelines.pipeline_name.extras.torch_model.TorchModel<br>    filepath: data/06_models/NeuralNetwork.pickle</pre><p>Tracking hyperparameters and scores is achieved by storing them as JSON files with tracking dataset type. This is for our benchmark.</p><pre>hyperparams:<br>  type: tracking.JSONDataset<br>  filepath: data/08_reporting/hyperparams.json<br><br>scores:<br>  type: tracking.MetricsDataset<br>  filepath: data/08_reporting/scores.json</pre><p>Now, simply enter kedro run in our terminal, and Kedro will execute all discovered pipelines. For larger projects, it is advisable to create distinct pipelines for each task, such as pre-processing data, fitting models, evaluating models, reporting benchmarks, etc. However, in this example, we have chosen to create a single pipeline with all these tasks.</p><h3>Tracking with Kedro-viz</h3><p>To activate tracking with Kedro-viz, the following lines of code must be added to setting.py:</p><pre>from kedro_viz.integrations.kedro.sqlite_store import SQLiteStore<br>from pathlib import Path<br><br>SESSION_STORE_CLASS = SQLiteStore<br>SESSION_STORE_ARGS = {&quot;path&quot;: str(Path(__file__).parents[2] / &quot;data&quot;)}</pre><p>Subsequently, executing kedro viz run in the terminal initializes Kedro-viz. The pipeline is visually represented as a tree structure in Figure 1. This visualization proves beneficial when dealing with large and intricate pipelines, aiding in easily verifying the logic of the pipeline and serving as a valuable tool for explanations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZV1ug_Z45kTR5cditjjUGg.png" /><figcaption>Figure 1: Visualisation of a data pipeline by Kedro-viz</figcaption></figure><p>Kedro also offers the ability to display generated dataframes within the pipeline by incorporating specific properties into the data catalog. When dealing with substantial dataframes, it is essential to adjust the number of rows displayed in the preview tab (<a href="https://docs.kedro.org/projects/kedro-viz/en/stable/preview_datasets.html">learn more</a>).</p><pre>raw_data:<br>    type: pandas.CSVDataset<br>    filepath: data/01_raw/raw_data.csv<br>    metadata:<br>    kedro-viz:<br>      layer: raw<br>      preview_args:<br>          nrows: 5</pre><p>For experiment tracking, accessing the “chemistry bottle” icon reveals all experiment runs. The “Compare runs (max. 3)” option, situated at the top left of the screen, facilitates quick comparisons between 2 or 3 runs. Additionally, simple metric charts are visible in the “Metrics” tab. In Figure 2, we can see how performance scores of the model change if its dimension changes (from 16 to 32).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q_PPzF_DYZaNeJTdhiEi8w.png" /><figcaption>Figure 2: Experiment tracking. We can see how our scores changent with our hyperparameters (the dimension is changed from 16 to 32).</figcaption></figure><p>It is noteworthy that hyperparams and scores are stored as JSON files (refer to Figure 3). These files can be directly accessed to create more intricate charts for benchmarking. Each run is uniquely identified by a specific name, denoting the date and time of the run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*G1OVKfffE3jLsgFhDFtedQ.png" /><figcaption>Figure 3: Tracking files in json format</figcaption></figure><h3>Conclusion</h3><p>Kedro offers a robust solution for managing and reproducing experiments in machine learning. The integrated kedro-viz plugin provides visualizations of data pipelines, aiding in the tracking of experiment runs and facilitating comparisons between them. The three-step process outlined in this article demonstrates how to quickly set up a benchmark for deep learning models using Kedro. Experiment tracking with Kedro-viz further enhances the visibility and understanding of the entire pipeline. The code of this project is found in <a href="https://github.com/ngohoanhkhoa/DeepLearningNotebook/tree/master/medium_kedro/experiments-deep-models">this repo of github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4490c1bf00b2" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/how-to-quickly-set-up-a-benchmark-for-deep-learning-models-with-kedro-4490c1bf00b2">How to quickly set up a benchmark for deep learning models with Kedro ?</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative AI: a guide to evaluate synthetic tabular data]]></title>
            <link>https://medium.com/@ngohoanhkhoa/generative-ai-a-guide-to-evaluate-synthetic-tabular-data-6751f20a8663?source=rss-9391b4bf3dd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6751f20a8663</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[synthetic-data]]></category>
            <dc:creator><![CDATA[Anh Khoa NGO HO]]></dc:creator>
            <pubDate>Tue, 26 Sep 2023 13:30:51 GMT</pubDate>
            <atom:updated>2025-10-08T10:00:40.642Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7mFryoBMD_XAq2Ip" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Synthetic tabular data has become increasingly popular in recent years, as it offers a cost-effective answer to data augmentation for machine learning model improvement and sensitive data privacy. However, it is important to ensure that the synthetic data generated is of high quality and accurately represents the real data. To achieve this, it is essential to use reliable evaluation metrics that can assess the similarity and the distance between the synthetic and real data. In this article, we will discuss several widely used evaluation metrics for synthetic tabular data. We will explore how these metrics work, and how they can be applied to evaluate the quality of synthetic data for different types of data features. Understanding these evaluation metrics is crucial for anyone working with synthetic tabular data, as it ensures that the generated data is reliable and effective for training machine learning models.</p><p>My original article is published in the link below.</p><p><a href="https://web.archive.org/web/20240421232941/https://www.quantmetry.com/blog/generative-ai-a-guide-to-evaluate-synthetic-tabular-data/">Generative AI: a guide to evaluate synthetic tabular data</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdocs.google.com%2Fdocument%2Fd%2Fe%2F2PACX-1vSpkgTTWvK82u7SKNn5u6j4naMieVS4Yf6L-OKTSs0Up444Gb7cRq0BrCWelxddSk_JWQh3TSdaZdde%2Fpub%3Fembedded%3Dtrue&amp;display_name=Google+Docs&amp;url=https%3A%2F%2Fdocs.google.com%2Fdocument%2Fd%2Fe%2F2PACX-1vSpkgTTWvK82u7SKNn5u6j4naMieVS4Yf6L-OKTSs0Up444Gb7cRq0BrCWelxddSk_JWQh3TSdaZdde%2Fpub&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=google" width="700" height="530" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb6a205641c5185f52a8771813f4a53e/href">https://medium.com/media/bb6a205641c5185f52a8771813f4a53e/href</a></iframe><p><strong>Thanks for reading my article. Feel free to comment if you have any feedback and please hit the 👏 button below if you enjoyed it. Follow me if you want to read more about machine learning.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6751f20a8663" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Five amazing plugins for Obsidian]]></title>
            <link>https://medium.com/@ngohoanhkhoa/five-amazing-plugin-for-obsidian-b6a0a80af058?source=rss-9391b4bf3dd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6a0a80af058</guid>
            <category><![CDATA[writing-tips]]></category>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[obsidian]]></category>
            <category><![CDATA[note-taking-app]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Anh Khoa NGO HO]]></dc:creator>
            <pubDate>Sat, 08 Apr 2023 14:17:13 GMT</pubDate>
            <atom:updated>2023-04-12T08:40:46.176Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Obsidian is an application (available for Windows, Linux, mobile, and other platforms) that allows you to take notes and write. It is based on Markdown, an easy-to-use markup language that you need to know to use this application. However, learning this language only takes several hours. This article will not explain in detail how to use Obsidian; everything about this application can be found in this </em><a href="https://help.obsidian.md/Obsidian/Index"><em>link</em></a><em>.</em></p><p><em>As a data scientist and an Ipad user, I prefer Obsidian over other applications such as Notion, OneNote, and Evernote for two reasons:</em></p><ul><li><em>Local data: All of your notes and writings are stored locally on your computer or mobile device. You do not need an internet connection to use Obsidian. Writing without an internet connection (while traveling, for example) is uncomfortable in other applications like Notion. Local data does not mean that you cannot sync your notes on different devices and platforms. You can use any cloud storage provider, such as Dropbox, Google Drive, OneDrive, or iCloud, to sync your data. Obsidian also offers a charged option for this feature. In the next section, I will show another option, specifically for programmers.</em></li><li><em>Community-provided plugins: The Obsidian community provides numerous plugins that help to make your writing experience with Obsidian quicker and more pleasant.</em></li></ul><p><em>This article discusses five plugins that I use every day for my work: Obsidian Git, Mind Map, Pandoc Plugin, Dynamic Table of Content and Attachment Name Formatting.</em></p><p><strong>Table of contents<br>- </strong><a href="#3cde">How to install and enable plugins ?</a><br>- <a href="#4b1b">Obsidian git</a><br>- <a href="#852e">Mind Map</a><br>- <a href="#918d">Pandoc Plugin</a><br>- <a href="#e8eb">Dynamic Table of Content</a><br>- <a href="#5e10">Attachment Name Formatting</a></p><h3>How to install and enable plugins ?</h3><p>In Settings, you select Community plugins tab. You need to turn off the restricted mode to use community plugins. You can now browse a hundred of plugins (or you can go to this <a href="https://obsidian.md/plugins">link</a>). After selecting a plugin, you only need to click the «install» button and then the «enable» button. All installed plugins are listed in the Community plugins tab and also the left sidebar (see Figure 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V7KD4cFknk1TF9MfDUb-Hg@2x.jpeg" /><figcaption>Figure 1: Setting panel with Community plugins. Photo by the author.</figcaption></figure><h3>Obsidian git</h3><p>Obsidian Git is a plugin that allows you to sync your Obsidian notes with a Git repository (e.g., GitHub or GitLab). This is a great feature for programmers who are already familiar with Git and want to keep their notes version-controlled. With this plugin, you can easily push your updated notes to the repository and pull them down to any other device. This gives you the ability to work on your notes in Obsidian, even if you’re away from your main computer, and still have access to all of your changes. Additionally, you can use Git to view the history of your notes and revert back to previous versions if needed. This plugin and its documentation are found in this <a href="https://github.com/denolehov/obsidian-git">link</a>.</p><h3>Mind Map</h3><p>The <a href="https://github.com/lynchjames/obsidian-mind-map">Mind Map</a> is a helpful plugin for visualizing your notes in a mind map format. This plugin allows you to create a mind map from your notes and provides a great way to see the connections between them. The Mind Map plugin is a great tool for brainstorming, planning, and organizing your ideas.</p><h3>Pandoc Plugin</h3><p>The Pandoc Plugin is a great tool for converting your Markdown notes into various file formats such as PDF, DOCX, and HTML. This plugin allows you to customize your output files by providing a wide range of configuration options. You can use it to create professional-looking documents from your Obsidian notes, which can be especially useful for sharing your notes with others who may not be familiar with Markdown. To use this plugin, you need to have Pandoc installed on your computer. You can find the plugin and installation instructions at this <a href="https://github.com/OliverBalfour/obsidian-pandoc">link</a>.</p><h3>Dynamic Table of Content</h3><p>This plugin helps to create quickly and automatically a table of content (TOC) for your article. Since the table is dynamic, it provides links to the article sections. You only need to add the code below to obtain a TOC.</p><pre>&#39;&#39;&#39;toc<br>&#39;&#39;&#39;</pre><p>Moreover, we can change the appearance of our table of contents, several properties are table style (i.e., bullet, number, inline), minimum and maximum depth, title, etc.</p><h3>Attachment Name Formatting</h3><p>Obsidian only provides a simple way to keep attachment files (e.g., image, audio, video files): all files are stored in a single folder. You have two options: the same folder as the note you are working on or the sub-folder under the current folder. This leads to the problem that all attachment files of different notes are saved in the same folder. A solution is to name these files in a format that helps group these files, e.g., «note_name file_1.png». The plugin <a href="https://github.com/JYC333/obsidian-attachment-name-formatting">Attachment Name Formatting</a> automatically renames these files while you add them into your notes. One of the most interesting properties of this plugin is that it renames your files in the same order in your article.</p><p><strong>Thanks for reading my article. Feel free to comment if you have any feedback and please hit the 👏 button below if you enjoyed it. Follow me if you want to read more about machine learning.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6a0a80af058" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Augmentation: How do GANs synthesize tabular data in recent studies?]]></title>
            <link>https://medium.com/@ngohoanhkhoa/data-augmentation-how-do-gans-synthesize-tabular-data-in-recent-studies-8f34c184ce42?source=rss-9391b4bf3dd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f34c184ce42</guid>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[data-augmentation]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Anh Khoa NGO HO]]></dc:creator>
            <pubDate>Tue, 14 Feb 2023 23:40:22 GMT</pubDate>
            <atom:updated>2025-10-08T10:06:54.289Z</atom:updated>
            <content:encoded><![CDATA[<p>“Data is the new oil” by Clive Humby highlights the importance of data in the 21st century. In this context, data augmentation is one of the AI trends which solves the lack of data for machine learning tasks. It is even more critical when collecting large amounts of data is difficult, especially for tabular data. Moreover, synthetic data help to protect private information contained in the original data (e.g., medical records) while sharing it with other parties and the research community. Existing applications of synthetic data include deepfake[1], oversampling for imbalanced data, and public healthcare records.</p><p>More recently, generative models have emerged as the state-of-the-art technique in generating synthetic data, by discovering the pattern of the original data and generating new samples similar to the original data. In this article, we explore several recent studies on one of the most popular generative architectures, i.e., Generative Adversarial Network (GAN), for generating synthetic tabular data. We also discuss the challenges of the tabular data generation task and how GANs overcome these obstacles.</p><p>My original article is published in the link below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdocs.google.com%2Fdocument%2Fd%2Fe%2F2PACX-1vRzBbGCqR55l361kXsqmyIZsBurGDD8KsP7_7GBP8I2vJs8MEsEY5YerHLAjFMpDhjvnI0H3lxHrlH4%2Fpub%3Fembedded%3Dtrue&amp;display_name=Google+Docs&amp;url=https%3A%2F%2Fdocs.google.com%2Fdocument%2Fd%2Fe%2F2PACX-1vRzBbGCqR55l361kXsqmyIZsBurGDD8KsP7_7GBP8I2vJs8MEsEY5YerHLAjFMpDhjvnI0H3lxHrlH4%2Fpub&amp;image=https%3A%2F%2Flh7-rt.googleusercontent.com%2Fdocsz%2FAD_4nXcqug2WxeQ3WdffKlRE8nYQAbfVj1t60nyQOI8TJxqtjZ6HB9S4YUqzXm8fYS4EAkYgzL4381uWsjKrxSb7c_6KON3vjWzXf8vI09aVZR803DQ-UAH8eyjM7f-gdugyMRuWUuGwoc9uWxdChNidR5cHH5nabA%3Fkey%3DSOTqIm3hnA-Tocf1g2W8tw&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=google" width="700" height="530" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dec4acd6457c8b46ff4c258b30a2888/href">https://medium.com/media/7dec4acd6457c8b46ff4c258b30a2888/href</a></iframe><p><strong>Thanks for reading my article. Feel free to comment if you have any feedback and please hit the 👏 button below if you enjoyed it. Follow me if you want to read more about machine learning.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f34c184ce42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sequence-to-sequence models with attention mechanism from a to z]]></title>
            <link>https://medium.com/@ngohoanhkhoa/sequence-to-sequence-models-with-attention-mechanism-from-a-to-z-349b81d02169?source=rss-9391b4bf3dd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/349b81d02169</guid>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Anh Khoa NGO HO]]></dc:creator>
            <pubDate>Mon, 21 Mar 2022 17:51:18 GMT</pubDate>
            <atom:updated>2022-05-31T13:22:55.264Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4M7PIvO2YIWppQF-uDDSQ.png" /></figure><p>In this article, we observe an evolution in sequence-to-sequence models, from shallow recurrent networks to transformers and Bert.</p><p><strong>Table of contents</strong></p><p><em>I. Sequence-to-sequence models</em></p><p><em>II. Attention mechanism</em></p><p><em>III. Transformers</em></p><p><em>IV. Bert — Bidirectional encoder representations from transformers</em></p><h3>Sequence-to-sequence models</h3><p>A sequence-to-sequence (seq2seq) model is a neural network model introduced by <a href="https://arxiv.org/abs/1409.3215">Sutskever et al., [2014]</a> and <a href="https://arxiv.org/abs/1406.1078">Cho et al., [2014]</a>. It receives a sequence of symbols and returns another sequence of symbols. E.g., in the case of machine translation, it takes a sentence (i.e., a sequence of words) in a language and outputs a translated sentence in another language.</p><p>The model includes an encoder and a decoder. The encoder maps a variable-length source sequence to a fixed-length vector, and the decoder maps the vector representation back to a variable-length target sequence. The encoder and the decoder are often based on recurrent neural networks (RNNs). Note that different architectures can be used for seq2seq models such as convolutional encoders, and fully connected feed-forward networks (e.g., transformers).</p><ul><li>Input sequence: x with I symbols</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*Blg8vbFPemKyIP3BV2owSg.gif" /></figure><ul><li>Output sequence: y with J symbols</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/145/1*ODWoyP7rrafYi0TwDnHbTQ.gif" /></figure><h4>Recurrent neural networks (RNNs) and their variants</h4><p><strong>Recurrent neural networks (RNNs)</strong></p><p>RNN, a neural network architecture helps to process a sequence of symbols: the information of a symbol depends not only on this symbol but also on the previous symbols. This also means that RNN includes a memory containing the information of the previous symbol in the sequence. E.g., a language model helps to finish a sentence (i.e., predict the next word) by observing the known part of this sentence (i.e., all previous words of this predicted word). These sequences are typically represented by a fixed-size vector of symbols which are fed sequentially (one by one) to a recurrent unit.</p><p>At each time step i, the hidden state hᵢ of the symbol xᵢ is based on the previously hidden state h (at time step i-1) and the current symbol xᵢ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*P3B6kobk3yxWJyWXVMR-Hg.gif" /></figure><p><strong>Sequence-to-sequence model</strong> <a href="https://arxiv.org/abs/1406.1078">[Cho et al., 2014]</a>: an <strong>RNN-encoder</strong> encodes the input sequence x and generates a context vector c (i.e., the summary of the input sequence)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/49/1*BEBgkvY3hcmR0NfBiqMryw.gif" /></figure><p>An <strong>RNN-decoder</strong> computes its hidden states by using this context vector c. At each time step j, the target hidden state hⱼ is updated by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*UkmUlCx7JKgDGTiRni33-g.gif" /></figure><p>and the target symbol yⱼ is predicted by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*GbxU9uldES0i_fZLcDax7Q.gif" /></figure><p>Note that the hidden state of the initial target h₀ can be computed by using the context vector c and a special initial symbol y₀ e.g., “&lt;sos&gt;” (start of a sentence), a random vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/96/1*0ZkW0r0vpxhAzCX6mRnxVw.gif" /></figure><p><strong>Long-short term memory networks (LSTMs)</strong></p><p>LSTM is a particular case of RNN where it can control the memory for each symbol of a sequence [<a href="https://direct.mit.edu/neco/article-abstract/9/8/1735/6109/Long-Short-Term-Memory?redirectedFrom=fulltext">Hochreiter and Schmidhuber, 1997</a>, <a href="https://arxiv.org/abs/1308.0850">Graves, 2013</a>, <a href="https://direct.mit.edu/neco/article-abstract/12/10/2451/6415/Learning-to-Forget-Continual-Prediction-with-LSTM?redirectedFrom=fulltext">Gers et al., 2000</a>]. LSTM contains several gates (e.g., input gate, forget gate, output gate) controlling how information is kept and forgotten <a href="https://arxiv.org/abs/1412.3555">[Chung et al., 2014]</a>.</p><ul><li>The input gate regulates how the much new input changes the memory state. This value at time step i depends on the symbol x at i, the previously hidden state h (at time step i-1), and the previous context c (at time step i-1).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*urjyDqZ7rK2Dmj6aIjKjMw.gif" /></figure><ul><li>The forget gate regulates how much of the prior memory state is retained (or forgotten). This value at time step i depends on the symbol at i, the previously hidden state h (at time step i-1), and the previous context c (at time step i-1).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*0xCwsRbOcWtBXbYa78pZEQ.gif" /></figure><ul><li>The output gate regulates how strongly the memory state is passed on to the next layer. This output gate value at time step i depends on the symbol at i, the previously hidden state h (at time step i-1), and the context cᵢ. This context at time step i is computed by: (a) the previous context c (at time step i-1) weighted by the forget gate value at i. (b) the pair (xᵢ and h at time step i-1) weighted by the input gate value at i.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/171/1*zkmGPAfYEWRI8MPx7g9Kxw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*c1zJt5jg1KKHiQlH-ACn3g.gif" /></figure><ul><li>The hidden state hᵢ at time step i is based on the context cᵢ weighted by the output gate value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/84/1*JPVcCne3kCieBJSTbkbARA.gif" /></figure><p>Note that the input, forget, and output gate range in [0,1] (by using the sigmoid function), meaning the percentages of information allowed to be passed these gates.</p><p><strong>Gated recurrent unit networks (GRUs)</strong></p><p>GRU <a href="https://arxiv.org/abs/1406.1078">Cho et al., [2014]</a> share the same concept of LSTM i.e., using gates to control the memory for each symbol. It has fewer parameters than LSTM since it removes the output gate.</p><ul><li>The input gate (also called the update gate in GRU):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/141/1*iwiJuIOuYJzFhbpSPl-aAA.gif" /></figure><ul><li>The forget gate (also called the reset gate in GRU):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/1*EBbtxz1-TJ1t2ezrKP-pcg.gif" /></figure><ul><li>The context cᵢ at time step i (also called candidate hᵢ in GRU):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*DWfC3Gb6Tw4p4-BNsvainA.gif" /></figure><ul><li>The hidden state hᵢ at time step i is based on the context cᵢ and the previously hidden state h (at time step i-1):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*vSXqvqYFDL3wpNW0BEiUVg.gif" /></figure><p>Note that in the case of LSTMs and GRUs, there are several variants based on how the context and the gates are updated.</p><p><strong>Bidirectional recurrent neural networks (BiRNNs)</strong></p><p>BiRNNs are introduced by <a href="https://ieeexplore.ieee.org/document/650093">Schuster and Paliwal [1997]</a>. A variant of this neural network architecture is the BiLSTM, presented in <a href="https://link.springer.com/chapter/10.1007/11550907_126">[Graves and Schmidhuber, 2005]</a>. RNN is applied in both directions starting from the first symbol to the last symbol (forward mode) and from the last symbol to the first symbol (backward mode). The forward and backward hidden states of the same time step are then combined. Note that there are different methods to combine these two hidden state vectors e.g., concatenating, summing, or averaging.</p><p>The hidden state hᵢ at time step i depends on the hidden state in forward mode and backward mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/99/1*0aHEy7u_Z4fTnVkwonWizw.gif" /></figure><h3>Attention mechanism</h3><p><a href="https://arxiv.org/abs/1409.0473">Bahdanau et al., [2015]</a> extend RNN Encoder-Decoder by: (a) using BiRNN for the encoder; (b) adding an alignment model into the decoder to generate the context c_j for each target symbol y_j.</p><ul><li>The target hidden state hⱼ at time step j (for predicting the target symbol yⱼ) depends not only on the previous target hidden state h (at time step j-1) and the previous target symbol y (at time step j-1) but also the context cⱼ.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*XQXvCbxatBSntdZq4fGNBw.gif" /></figure><ul><li>The context cⱼ of the target symbol yⱼ is computed as a weighted sum of the source hidden states h (I states) of the source symbols. Note that in <a href="https://arxiv.org/abs/1409.0473">[Bahdanau et al., 2016]</a>, these hidden states (called the annotations) are made by a concatenation of the source hidden state vectors in both forward and backward modes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*-6_Zp19Hiv9Bjm4L1pqe7g.gif" /></figure><ul><li>The weight αⱼᵢ of each target hidden state hⱼ is updated by a softmax function. It scores how well the target symbol yⱼ and the source symbols x (I symbols) match.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/119/1*TV90F18Sy4Wqk35SxhlgbA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/132/1*BavtFnru_GUKskZAwosFHQ.gif" /></figure><p><a href="https://arxiv.org/abs/1508.04025">Luong et al., [2015]</a> propose two categories: global and local attention mechanisms. The approach of <a href="https://arxiv.org/abs/1409.0473">Bahdanau et al., [2015]</a> is considered a global attention mechanism. Note that <a href="https://arxiv.org/abs/1508.04025">Luong et al., [2015]</a> use LSTM for their encoder (instead of BiRNN) and their decoder (instead of RNN).</p><h4>Global attention mechanism</h4><ul><li>The target hidden state hⱼ at time step j (not ready for predicting the target symbol yⱼ) depends on the previous target hidden state h (at time step j-1) and the previous target symbol y (at time step j-1). Note that they also propose an input-feeding approach where the target hidden state hⱼ also depends on the previous attentional target hidden state \tilde{h}_<em>{j-1} (i.e., the attentional vector \tilde{h}_</em>{j-1} are concatenated with the input y_{j-1} at the next time steps). This means that alignment decisions should be made jointly taking into account past alignment information.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/132/1*8PH7Cyb2xbu0OL9Bzqs-Fg.gif" /></figure><ul><li>The attentional target hidden state \tilde{h}_j at time step j (for predicting the target symbol yⱼ) depends on the target hidden state hⱼ and the context vector cⱼ.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/98/1*X4hzq_5K-CcJemR39WaTkw.gif" /></figure><ul><li>The context cⱼ of the target symbol yⱼ is also computed as a weighted sum of the source hidden states h (I states) of the source symbols, as can be seen in <a href="https://arxiv.org/abs/1409.0473">[Bahdanau et al., 2015]</a>.</li><li>The weight αⱼᵢ is also computed by a softmax function. aⱼᵢ depends on the target hidden state hⱼ and the source hidden state hᵢ. This is different from the method of <a href="https://arxiv.org/abs/1409.0473">Bahdanau et al., [2015]</a> where aⱼᵢ depends on the previously hidden state h (at time step j-1). Note that the target hidden state notion hⱼ in <a href="https://arxiv.org/abs/1409.0473">[Bahdanau et al., 2015]</a> and in <a href="https://arxiv.org/abs/1508.04025">[Luong et al., 2015]</a> is not computed in the same way. <a href="https://arxiv.org/abs/1508.04025">Luong et al., [2015]</a> consider three different alignment functions f to compute this score aⱼᵢ.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/102/1*rwEKfrgAYgrWsrhy3-D-Kg.gif" /></figure><h4>Local attention mechanism</h4><p>This mechanism is to focus only on a small subset (i.e., a window) of the source symbols per target symbol. This means that the context cⱼ is computed as a weighted sum of a set of source hidden states within a window [pⱼ — D, pⱼ+D]. Note that pⱼ is an aligned position (a real number) in the source sequence for each target symbol at time j and D is empirically selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*L2p2U05H_mXSnMP-jppbUg.gif" /></figure><p>where the standard deviation is empirically set as σ = D/2, s is an integer within the window centered at pⱼ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/53/1*F8sQFU76kL-BwxZ1Dx5i3Q.gif" /></figure><p>The aligned position pⱼ can be predicted by:</p><ul><li>Monotonic alignment: they assume that source and target sequences are roughly monotonically aligned.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/45/1*QgXEFB9TxLhkYCut93A7Ww.gif" /></figure><ul><li>Predictive alignment: the model predicts this position pⱼ, based on the source sequence length I and the target hidden state hⱼ.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*aqFi7IK3o_q4n3UOEGvfuA.gif" /></figure><h3>Transformers</h3><p><a href="https://arxiv.org/abs/1706.03762">Vaswani et al., [2017]</a> propose an approach that gives up recurrent neural networks and relies entirely on an attention mechanism by using fully feed-forward neural networks.</p><p>We observed an alignment between the source and the target sequence in the previous sections. Transformers include another alignment called self-attention: an alignment between a single sequence and itself. E.g., a word in the source sentence links with other neighbor words of this sentence.</p><p>There are three attention mechanisms:</p><ul><li>A self-attention mechanism for a source sequence (in the encoder): generate a representation of a source symbol based on the source symbols in the source sentence.</li><li>A self-attention mechanism for a target sequence (in the decoder): predicting a target symbol based on the known target symbols.</li><li>An attention mechanism for relationships between the source and target symbols: predicting a target symbol based on the representation of the source symbols.</li></ul><p>Note that an input of the encoder and the decoder for a symbol (e.g., xᵢ, yᵢ) is a combination (e.g., summing) of two vectors, a symbol embedding and a positional embedding (i.e., position of this symbol).</p><h4>Attention mechanism in Transformers</h4><p>The attention mechanism includes three elements:</p><ul><li>Query: a representation vector of a “query” symbol that we need to know how it relates to other symbols.</li><li>Key: a representation vector of a symbol that helps to identify the relationship (i.e., αⱼᵢ in the previous section) between this symbol and the “query” symbol.</li><li>Value: a representation vector of the same symbol (also represented by a “key” vector). This value plays the same role as hᵢ in the computation of the context cⱼ <a href="https://arxiv.org/abs/1409.0473">[Bahdanau et al., 2015]</a>.</li><li>Output: the final representation vector of the “query” symbol, e.g., a context vector cⱼ.</li></ul><h4>Encoder self-attention mechanism for a source sequence</h4><ul><li>The query of the source symbol xᵢ at time step i:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/71/1*epepIZF3kvuK4GQFnynzMw.gif" /></figure><ul><li>The key of another source symbol x at time step i’:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/80/1*ROV7HHqc3wh5LSCBbUs_zg.gif" /></figure><ul><li>The value of this source symbol x at time step i’:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/80/1*Iyasygb1u3JyLMVhyTnweQ.gif" /></figure><ul><li>The output of the source symbol xᵢ:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/104/1*nkEFMnFGkXgNxb8npPJPbQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/133/1*6ENLMkzIeVV8pftVOuxYxg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*mlpPzOWVNhadnb4E9yqMWw.gif" /></figure><p>We recognize that a pair key-value is based on one symbol. However, keys are used for computing weights α and values are ingredients for outputs.</p><h4>Masked decoder self-attention mechanism for a target sequence</h4><p>This mechanism shares the same components as the self-attention mechanism for a source sequence. The only difference is found in the computation of the output where the model only observes a part of the target sequence. Let’s observe the case that the model only knows the previous symbols (y from the first time step to the time step j-1) to predict yⱼ.</p><ul><li>The output can be computed by:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/127/1*IET1TP4ncO2bTEfTU_PS0Q.gif" /></figure><p>Note that unknown symbols are masked (i.e., in practice, they are replaced by a special symbol &lt;mask&gt;), which leads to a = 0, then their weights α = 0.</p><ul><li>The query of the predicted target symbol yⱼ at time step j.</li><li>For training, the model uses the ground-truth symbol yⱼ:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/73/1*zA_lCYVTQ9Qg5iq9bFE33Q.gif" /></figure><ul><li>For testing, the model uses a special symbol “&lt;mask&gt;”. It can be seen as a random vector and the only information in qⱼ is the position j. Recall that yⱼ is a combination of two vectors, an embedding of the symbol yⱼ and an embedding of its position j.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/131/1*sy-WrSojnb1j_Z2B7t2JGw.gif" /></figure><h4>Encoder-decoder attention mechanism for an alignment between a source and a target sequence</h4><ul><li>The query of the predicted symbol yⱼ at time step j:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/78/1*h53YlYC4-Okf_0CuY_Gbtg.gif" /></figure><ul><li>The key of a source symbol xᵢ at time step i:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/75/1*30if3g6Sv3Vf-LiLlYuQLg.gif" /></figure><ul><li>The value of this source symbol xᵢ:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/76/1*YbH51E-EIZlEi5GvshZmBQ.gif" /></figure><ul><li>The output of the predicted target symbol yⱼ:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/106/1*lzSmQ-40CW6ZFShxRXBEQg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*dK-YNm0JjpjSH2ykkr4haQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/104/1*kkrsPQxlPN3BM_ppgdoJWQ.gif" /></figure><h4>Multi-head attention and transformer block, wider and deeper</h4><p>Attention can be seen as a sub-model that receives a query, a pair key-value, and returns output for this query at each time step. <strong>Multi-head attention</strong> includes more than one attention sub-model (e.g., 8 parallel attention sub-models in the original paper). For each time step, they receive the same set including a query, a key, and a value, and all outputs of the attention sub-models are finally concatenated. This means that we can make a transformer wider.</p><p>These outputs can go through other sub-models, e.g., another multi-head attention or a group of layers including a position-wise fully connected feed-forward network, a residual connection, and a layer normalization. Combining all of these sub-models creates a <strong>transformer block</strong>. A transformer can include more than one block (6 blocks in the original paper). This means that we can make a transformer deeper.</p><h3>Bert — Bidirectional encoder representations from transformers</h3><p><a href="https://arxiv.org/abs/1810.04805">Devlin et al., [2019]</a> demonstrate two things for pre-training a model:</p><ul><li>The importance of a bidirectional encoder for learning representations (of symbols).</li><li>Pre-trained representations are helpful for downstream tasks (i.e., fine-tuning BERT)</li></ul><p>There are two steps in their framework: pre-training and fine-tuning.</p><ul><li><strong>Pre-training</strong> Bert is an unsupervised learning (based on unlabeled data). This helps to learn representations of these unlabeled data. In the case of language models, Bert learns word representations from sequences of words.</li><li>Pre-trained parameters of Bert are used for downstream tasks in the <strong>fine-tuning</strong> step. Note that we can modify the architecture of this pre-trained model (e.g., adding more layers) according to the downstream task. This step is much less expensive than the pre-training step. In practice, we mostly reuse the pre-trained Bert models by Google and fine-tune these models for our tasks.</li></ul><h4>Pre-training Bert</h4><p><a href="https://arxiv.org/abs/1810.04805">Devlin et al., [2019]</a> pre-train Bert using two unsupervised tasks: masked language model and next sentence prediction. In this work, we only discuss a masked language model.</p><p>Let’s recall a transformer decoder, it only observes a part of the target sequence (e.g., the left or right part of a sequence) and predicts the rest. Therefore, there are two traditional training styles: left-to-right models and right-to-left models. In the case of the language model, a left-to-right model learns a word representation in a sentence based on its left (known) part.</p><p>Note that a standard conditional language model can only be trained left-to-right or right-to-left. A better approach is a combination of these two training styles:</p><ul><li><a href="https://arxiv.org/abs/1802.05365">Peters et al. [2018]</a> use a simple concatenation of the two representations trained in the two training styles to obtain a representation of a word.</li><li>Bert uses masked language models to obtain bidirectional representations.</li></ul><p>Bert is a stack of encoder transformer blocks, which receives a sequence of words and returns representations of these words. It masks the words that need to be predicted (i.e., these words are replaced by the special token “&lt;mask&gt;”) and the self-attention mechanism helps to identify this “&lt;mask&gt;” based on all other words in the same sentence. We observe again the encoder self-attention mechanism.</p><ul><li>The query of the word x_i at time step i:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/76/1*ol8FXm8hYBIW78vIw-xevw.gif" /></figure><ul><li>Note that x_i is a combination of two vectors, a word embedding and a positional embedding of the word “&lt;mask&gt;”.</li><li>The key of another word x at time step i’:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/85/1*ktd2TVtWCDBRkRP4XdTV6Q.gif" /></figure><ul><li>The value of this word x at time step i’:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/85/1*R0yL-wKsa0r3Q3WEJWXIpw.gif" /></figure><ul><li>The output of the word xᵢ:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/111/1*4zewVHaMXjSVak0SwufC2g.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*eXbnAfhBOh-SP8slsgWeTw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/108/1*Bn84nJHc7NT_WtLzD2y_IA.gif" /></figure><ul><li>In a standard language model, oᵢ is fed into an output softmax over the vocabulary. Bert uses these masked words to compute loss for the pre-training step. Note that the task is masked word prediction rather than sequence reconstruction of denoising auto-encoders <a href="https://dl.acm.org/doi/10.1145/1390156.1390294">[Vincent et al., 2008]</a>.</li></ul><p><strong>Thanks for reading my article. Feel free to comment if you have any feedback and please hit the 👏 button below if you enjoyed it. Follow me if you want to read more about machine learning.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=349b81d02169" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An overview of alignment models]]></title>
            <link>https://medium.com/@ngohoanhkhoa/an-overview-of-alignment-models-8bdeed340aea?source=rss-9391b4bf3dd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bdeed340aea</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[word-alignment]]></category>
            <dc:creator><![CDATA[Anh Khoa NGO HO]]></dc:creator>
            <pubDate>Thu, 10 Mar 2022 15:05:00 GMT</pubDate>
            <atom:updated>2023-01-09T14:54:09.703Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*OVXF_j0UnAcO6Ocp" /></figure><p>We introduce the task of alignment for bitext at various levels from document-level to subword-level. This task aims to uncover the hidden patterns between a text in a source language and its translation in another language. We describe the generic bitext alignment problem, then discuss the three main levels of bitext alignment and also their applications: document-level, sentence-level, and sub-sentential-level. We also present in detail word alignment, the most common level in sub-sentential alignment. Generative word alignment modes IBMs and HMM are described in the final part of this note.</p><h3>Bitext alignment</h3><p>The term bitext refers to the parallel resources which in our study are the original documents and their translations in another language. Collections of bitexts also called parallel corpus, share the same domain related to a specific socio-cultural context. The text on each side could be a collection of documents, a single document, a paragraph, or a sentence. The alignment task identifies correspondences between the elements of the text in the source language and their translation in the target language. This equivalence is hierarchically structured at multiple levels: alignments can exist between documents, paragraphs, sentences, phrases, clauses, words, and also subwords. This process allows us to discover hidden patterns in the original texts and also the translated texts, which is important in many research areas such as word sense disambiguation, terminology extraction, computer-aided language learning, translation memory cleaning, and especially machine translation.</p><h3>Alignment granularity</h3><p>The task of alignment exposes the correspondence decomposed in multiple levels from document level to character level. We discuss in this section the three main levels: document, sentence, and word alignment.</p><h3>Document alignment</h3><p>The first alignment task is to link corresponding documents with one another. This task depends mainly on the source and the meta-information available for the data collection. In some cases, this kind of mapping is provided by multilingual institutions and agencies such as the Canadian Hansard and the United Nations. Resnik [1999], Resnik and Smith [2003] propose ways to Patry and Langlais [2005] documents from multilingual websites. Extracting parallel documents from comparable corpora is also the potential approach shown in [Steinberger et al., 2002, Pouliquen et al., 2004, Fung and Cheung, 2004a,b, Paetzold et al., 2017]. Patry and Langlais [2005] align documents across parallel corpora. Tao and Zhai [2005] propose a general method to extract comparable bilingual text without using any linguistic resources. Their method is based on an assumption that words in different languages should have similar frequency correlation if they are actually translations of each other. Vu et al. [2009] present a feature-based method to align documents with similar content across two sets of bilingual comparable corpora from daily news texts. Munteanu and Marcu [2013] use a word-by-word translation of each source document as a query to retrieve similar content target documents. A more recent project along these lines is Paracrawl, which aims for the development of parallel corpora for all EU languages [Esplà et al., 2019]. One of the outputs of these projects is a free/open-source pipeline. This pipeline covers fives stages from crawling data from websites on the Internet to delivering a clean parallel corpus: (a) downloading HTML documents from the Internet; (b) pre-processing, normalizing, and augmenting information from these documents; © aligning documents that are parallel; (d) aligning the segments in each of the document pairs identified; (e) filtering noisy data, deduplicating and formatting the output.</p><h3>Sentence alignment</h3><p>The next important level is the sentence level. A linguistics sentence expresses various functions based on a meaningful grammatical structure such as statement, question, exclamation, request, or command. The result of this task, called also parallel sentences, is nowadays known as the most important resource of many applications in machine translation. A sentence is not always translated into a single sentence. For instance, a long sentence could be broken up, or many short sentences could be merged. Moreover, the boundary of a sentence is hard to determine in some languages because there is no clear indication of a sentence end,e.g. Thai. Note that most of the sentence alignments are one-to-one mappings (monotonous alignment), which requires some simple constraints to obtain reasonably good alignment results. This level of alignment could be improved by the information of higher levels such as paragraphs, sections, chapters, or lower levels such as word/subword alignment. The models of Brown et al. [1991], Gale and Church [1993] are exclusively based on sentence length. Simard et al. [1993] examine the weaknesses of Gale and Church [1993] and discuss how ``cognates’’ would help to overcome them. In fact, for related languages, cognates provide reliable, low-cost word-level alignments, thus they can help sentence-level alignment in various ways. Cognates can be used as anchor points. Simard et al. [1993] use (word-level) cognates as an indicator of sentence alignment link quality. In addition, Chen [1993], Kay and Roscheisen [1993], Dagan et al. [1993], Utsuro et al. [1994], Wu [1994], Kueng and Su [2002] follow this line of research, discovering lexical information to improve the sentence alignment. A study by Li et al. [2010] employs a combination of both length-based and lexicon-based algorithms. Other features are also considered in the sentence alignment algorithm such as spelling similarity, geometric and pattern recognition [Melamed, 1996b, 1999]. This geometric property of the alignment map notably exploits the fact that alignment links are almost always monotonous and tend to lie near the diagonal. Singh and Husain [2005] analyze several open-source sentence alignment packages developed by Brown et al. [1991], Gale and Church [1993], Melamed [1999], Moore [2002]. Xu [2016] discusses some more recent models such as Hunalign [Varga et al., 2007], Gargantua [Braune and Fraser, 2010], Bleualign [Sennrich and Volk, 2011], Yasa [Lamraoui and Langlais, 2013], etc. Note that there are other alignment tools such as UPlug [Tiedemann, 2003], Champollion Tool Kit (CTK), Align. The recent research of Schwenk [2018], using neural networks, explores a joint multilingual sentence representation and uses the distance between sentences in different languages to filter noisy parallel data and to mine for parallel sentences in huge monolingual texts. Note that they do not use any additional feature or classifier and that they apply the same approach to all language pairs. Based on this work, Artetxe and Schwenk [2019] propose the Laser which generates multilingual sentence representations for 93 languages, belonging to more than 30 different families and written in 28 different scripts. This model uses a single Bi-LSTM encoder with a shared BPE vocabulary for these languages. They also introduce a new test set of aligned sentences in 112 languages and their approach yields a strong result in multilingual similarity search even for low-resource languages.</p><h3>Sub-sentential alignment</h3><p>Sub-sentential alignment is the task of exploring translational correspondences below the sentence level. It requires sentence-aligned parallel texts as its input and aims to align translational correspondences at the sub-sentential level: words, phrases clauses, and expressions. It can also rely on a bilingual dictionary to retrieve lexical correspondences.</p><h4>Word alignment</h4><p>We explore the most common level for sub-sentential alignment: Word alignment. The term ``word’’ refers to a meaningful unit (token) such that a sequence of these units represents a sentence. This term could be different, depending on the language-specific definition of a word boundary. Word alignment is used to learn bilingual dictionaries, to train statistical machine translation (SMT) systems, to filter out noise from translation memories or in quality estimation applications [Specia et al., 2018]. Given a pair of sentences consisting of a sentence in a source language and its translation in a target language, word alignment aims to identify translational equivalences at the level of individual tokens [Och and Ney, 2003]. There are two main types of tasks: supervised and unsupervised learning. Until recently, the most successful generative alignment models were statistical, as represented by the IBM Models [Brown et al., 1993b] and the HMM model Vogel et al. [1996]. These models use unsupervised estimation techniques to build asymmetrical alignment links at the word level, relying on large collections of parallel sentences. Melamed [2000] proposes a monolink alignment model that the noisy-channel assumption is ignored. Note that this model only considers one-to-one and null links. Cromières and Kurohashi [2009] suggest a training and a decoding procedure for this model and consider the use of syntactic trees for alignment and translation. Lardilleux et al. [2012, 2013] propose Anymalign relying on association scores between words or phrases, based on recursive binary segmentation and on document clustering. This model allows the processing of multiple languages simultaneously without any distinction between source and target. This means that this model is amenable to massive parallelism, scales easily, and is very simple to implement. Several remarkable tools for word alignment tasks are Moses, Giza++ [Och and Ney, 2003], Fastalign [Dyer et al., 2013], Twente, The PLUG Word Aligner (PWA), Kvec++, UPlug, SWIFT Aligner [Gilmanov et al., 2014], etc. Moreover, there are tools for alignment visualization such as Alpaco, Lingua-AlignmentSet, UMIACS Word Alignment Interface, Yawat [Germann, 2008], SWIFT Aligner, Cairo [Smith and Jahr, 2000], Hand Align14, ILink, UPlug, etc. A tool recently proposed is Eflomal [Ostling and Tiedemann, 2016], an efficient low-memory aligner. This tool helps a phrase-based statistical machine translation to produce translations of higher quality. Ostling and Tiedemann [2016] through this tool, suggest that Monte Carlo sampling should actually be the method of choice for the SMT practitioner and others interested in word alignment.</p><p><strong>Supervised discriminative alignment models: </strong>word alignment can be viewed as a supervised structured prediction task solved with discriminative machine learning techniques which usually require labeled training data. These models avoid the (potentially) complicated generation process (compared to unsupervised generative models) and can accommodate rich feature sets. The simplest approach is to directly estimate, for each target word, the probability of the alternative alignment decisions which range over the source positions. This can be done using a popular multi-class classification framework called MaxEnt. Ittycheriah and Roukos [2005] propose to model the conditional alignment distribution using a log-linear model. Ayan and Dorr [2006] discuss an approach to combining outputs of existing word alignment systems. They reduce the combination problem to the level of alignment links and use a maximum entropy model to learn whether a particular alignment link is included in the final alignment. Tomeh [2012] proposes a maximum entropy framework for statistical machine translation. Another approach is to use Conditional Random Fields (CRF). This approach is explored in the discriminative sequence labeling model of Blunsom and Cohn [2006] that directly encodes the alignment distribution. The model consists of a structure similar to the HMM alignment mode and efficient learning algorithms are available through adaptations of the Viterbi and forward-backward algorithms [Getoor and Taskar, 2007]. In addition, CRFs incorporate a rich set of features, even including alignment scores of complicated generative models such as IBM 4. Note that as the HMM, the CRFs alignment model encodes asymmetrical word alignments. Therefore, we have to use standard heuristics to perform the symmetrization. Liu et al. [2005] present a log-linear framework for symmetric word alignment. In this model, they consider three types of features: IBM 3 scores, cross-lingual POS transition scores, and dictionary-based word match scores. Their decoding step uses greedy search and they compute marginals using N-best lists. Moore [2005] considers a similar model where features strongly rely on word co-occurrence and alignment link frequencies. However, in this work, their decoding step is performed using beam-search with a modified version of an averaged perceptron. These two models operate at the alignment level and make no structural assumptions, thus they both face difficult inference problems. Niehues and Vogel [2008] show that integrating a multitude alignment matrix can be represented by a two-dimensional CRF. They show that a multitude of features using the various knowledge sources does help to improve the performance. We also refer to Tomeh [2012] for an exhaustive presentation of supervised word alignment methods.</p><h4>Phrase alignment</h4><p>The phrase alignment task takes contiguous word sequences, called phrases, as translation units. In other words, a phrase alignment allows for multiple words to be grouped and linked as if they would represent a single text unit. Compared with word alignment, this task can explicitly represent a many-to-many translation relationship. A phrase pair represents an association between a source and a target phrase. For phrase alignment, the sequences of words considered are not necessarily linguistically motivated, allowing the translation of non-compositional phrases [Lin, 1999], e.g. “spass am” and “fun with the”. Moreover, this task naturally captures the local context for translation. Phrase alignments can be learned in an unsupervised way without any linguistic resource, which makes the methodology generally applicable to any language pair. This means that the more data is used in the training procedure, the longer phrases can be learned. Phrase-based statistical machine translation systems typically require a phrase translation table, which provides a list of foreign translations and their probabilities for phrases of the original language. Such models are induced from word alignments, which means that phrase pairs are heuristically extracted from alignments between words. Koehn et al. [2003] learn phrase pairs by collecting all aligned groups of words that are consistent with word alignments generated by the Giza++ [Och and Ney, 2000]. Och and Weber [1998], Och et al. [1999], Och and Ney [2004] replace phrase pairs with alignment templates. These templates describe the alignment between word classes rather than words. Venugopal et al. [2003] also extract phrase pairs from word alignment models by leveraging the maximum approximation as well as the word lexicon. In addition, there is a work of Wisniewski et al. [2010] that explores a methodology for analyzing the errors of a phrase-based translation system. Phrase translation models can be learned directly from phrase alignment models. Marcu and Wong [2002] propose the joint phrase model with a generative story: (a) creating a number of concepts; (b) generating a foreign and English phrase from each concept; © reordering the English phrases. This concept can be considered as an abstraction of phrase types. The model jointly generates both foreign and English words from a concept, which explicit phrase alignments. Analysis for this is in [DeNero et al., 2008]. Zhang and Vogel [2005] describe a model efficiently processing arbitrarily long phrases because they capture more contexts than short phrases and result in better translation qualities. They demonstrate that their model is efficient in both time and space, yielding better translations. A phrase can contain gaps and overlap arbitrarily or in some nested structure. Yamamoto et al. [2003] use sequential pattern mining algorithms from parallel strings through co-occurrence analysis, which uniformly generates both rigid and gapped sequences simultaneously. Tambouratzis et al. [2011] introduce a phrase-alignment approach involving the processing of a small bilingual corpus in order to extract suitable structural information. Pal et al. [2011], Tomeh [2012] propose a framework using the information of multiword expressions to boost the performance of phrase-based SMT. In [Junczys-Dowmunt, 2012], they develop a method for the compression of the word-aligned target language in phrase tables. Cuong and Sima’an [2014] develop a phrase-based model directly trained on mix-of-domain corpora. In order to reduce the size of a phrase translation table, Nishino et al. [2016] propose an effective approach that removes the least useful phrase pairs from this table. A recent study by Bogoychev and Hoang [2016] presents a new standalone phrase table, optimized for query speed and memory locality.</p><h4>Structure alignment</h4><p>Structure alignment provides matching between grammatical components of a sentence pair. It requires a compositional analysis for the sentences which creates segments. The purpose of this task is to build parallel treebanks, corpora including mappings between linguistically motivated analyses across languages. It is clear that any tree alignment approach is also a natural way of generating phrase correspondences. These treebanks hence can be used in cross-linguistic research[Cyrus, 2006, Rios et al., 2009], bilingual transfer rule induction [Lavoie et al., 2001, Buch-Kromann, 2007, Graham and van Genabith, 2009] and especially machine translation. Structure alignment assumes that a structure over a sentence can be decomposed into smaller units with relations between them, yielding constituents or substructures. They refer to either single tokens or several tokens from a sentence. In this scenario, constituents can overlap. Tree alignment is a special case of structural alignment. In this case, a tree alignment is strictly compositional and hierarchical [Indurkhya and Damerau, 2010]. In other words, segments within two linked sub-trees align only with each other and there is a root segment spanning the entire sentence. Constituents within a tree are called nodes with one special node at the root of the tree. Labeled constituents are called non-terminals and single tokens are referred to as terminal nodes. Edges connecting these nodes can be also labeled. Note that word alignment needs to only be fed a sentence pair whereas a tree alignment also needs the structural annotation of this sentence. We can consider this type of alignment as a phrase alignment using additional structural constraints. These structural constraints help to control the overlap between segments. A number of algorithms for this structure alignment consider one fixed disjoint segmentation of each monolingual sentence. This means that the segments in this segmentation do not overlap and cover the whole sentence. We can join neighbor disjoint phrases to form a tree, which helps to enrich authorized segments. Note that we can use monolingual syntactic parsers to obtain a grammatical tree, which implies that each segment represents a grammatical phrase. For word alignment, a disjoint fixed segmentation is implied while a tree alignment considers structural constraints on both sides. It should be mentioned that alignment constraints are applied to the set of links between authorized segments. To sum up, the task of alignment is to link tree nodes from one source sentence to corresponding units in the target sentence. This is based on an assumption that there is a similar structure in the target sentence. Tree alignment requires that both sides of the parallel corpus are analyzed syntactically. These analyses are based on entirely automatic annotation using monolingual hand-crafted or statistical parsers. This yields a problem of consistency between independent syntactic analyses where it is difficult to find a common representation describing a complete mapping from one tree to another. Therefore, generative tree alignment models are not very successful because they are based on the strong constraints given by the monolingual parses. This is why most approaches apply heuristic or discriminative models for this task of alignment. The approach of Wu [1997] considers the crossing constraint for lexical mappings: Aligning two subtrees means that words in the yield of the first can be aligned only to words in the yield of the second. Several benefits are (a) the crossing constraint greatly reduces the space of possible alignments and thereby reduces the search complexity; (b) this constraint is accurate most of the time thanks to its relation to syntax.; © large-distance reordering can easily be modeled while avoiding the complexity of arbitrary permutations. Other algorithms are used to search the best alignment such as greedy top-down search algorithm [Matsumoto et al., 1993], bottom-up beam search algorithm [Grishman, 1999], and greedy best-first alignment strategies [Menezes and Richardson, 2001, Groves et al., 2004]. The approach of [Tinsley et al., 2007, Zhechev and Way, 2008] allows minor corrections in case of blocking links using various search heuristics. Lavie et al. [2008] propose an approach where alignment decisions are greedily propagated from leaf nodes to the root. Another study about the relationship between alignments and monolingual structures of sentences is discussed in Cromières [2010]. There exist two alternatives for crossing constraints: (a) separately parsing each sentence using two distinct Context-Free Grammars (CFG) with parse-match strategy. (b) simultaneously parsing both of the sentences using a synchronous CFG, producing parses for both sides along with the alignment. Indurkhya and Damerau [2010] discuss the lack of appropriate, robust, and monolingual grammars of the former approach. It also suffers a mismatch of the grammars across languages and inaccurate selection between multiple possible constituent matchings. The major disadvantage of the latter alternative is the difficulty of obtaining the grammar. Inversion transduction grammars (ITGs), introduced by Wu [1995, 1997], aim at a symmetric generative explanation of translated texts. The generation of sentence pairs is based on a common structure with permutations in one language allowed. In other words, ITG is a special case of syntax-directed transduction of a context-free language. It is equivalent to binary or ternary syntax-directed transduction whose rules are restricted to straight and inverted permutations only. ITG can be used to induce symmetric word alignments [Saers and Wu, 2009] and to restrict the search space of other alignment models [Cherry and Lin, 2006].</p><p>The full version is found in this <a href="https://ngohoanhkhoaprojects.blogspot.com/2021/04/neural-word-alignment.html">work</a>.</p><p><strong>Thanks for reading my article. Feel free to comment if you have any feedback and please hit the 👏 button below if you enjoyed it. Follow me if you want to read more about machine learning.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bdeed340aea" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>