<?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 TRAN Ngoc Thach on Medium]]></title>
        <description><![CDATA[Stories by TRAN Ngoc Thach on Medium]]></description>
        <link>https://medium.com/@thachngoctran?source=rss-fe5661177636------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*KB2ILfxSj7nMIcx0JHH5QQ.jpeg</url>
            <title>Stories by TRAN Ngoc Thach on Medium</title>
            <link>https://medium.com/@thachngoctran?source=rss-fe5661177636------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:47:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thachngoctran/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Essence of BLIP-2 — Vision-Language Model — Explained]]></title>
            <link>https://thachngoctran.medium.com/the-essence-of-blip-2-vision-language-model-explained-0985b64a1115?source=rss-fe5661177636------2</link>
            <guid isPermaLink="false">https://medium.com/p/0985b64a1115</guid>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vision-language-model]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[TRAN Ngoc Thach]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 15:24:11 GMT</pubDate>
            <atom:updated>2025-07-07T21:44:27.177Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Essence of BLIP-2 — Vision-Language Model — Explained</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yv_9hvG5fYr6tFQRRIfIfw.jpeg" /><figcaption>(courtesy: from the Paper)</figcaption></figure><p>“<em>BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models</em>” (Li et al., 2023) (<a href="https://arxiv.org/abs/2301.12597">link</a>) is the Research Paper to discuss in this article.</p><p>Having read several reviews on this paper, I noticed that they simply <em>paraphrased what is already said</em>, or just mentioned the trivial, rather than providing insightful perspectives. Understanding why it is designed, as what it is, is <em>decisive</em>. Otherwise, any paper idea would be mindless calculations of numbers. <em>Caveat: all based on my interpretation</em>. 😊</p><h3><strong>Intro</strong></h3><ul><li>The task is, given an Image and possibly an additional prompt (e.g. “this is the picture of”, “how much does it cost?”), to generate text tokens, using the info from the Image (and Prompt).</li><li>LLM generates (or <em>completes</em>) meaningful tokens when given the <em>right</em> context (the beginning part of the prompt). Therefore, the idea is to insert a <a href="https://huggingface.co/docs/peft/en/conceptual_guides/prompting#soft-prompts">Soft Prompt</a> <em>reflecting the features of the Image</em>. This Soft Prompt should be in the same <em>numerical space</em> as the <em>supposed</em> inputs of the <em>target</em> <em>frozen </em>LLM, but <em>not necessarily</em> in <em>human-readable</em> language forms.</li><li>We can train end-to-end a LLM with inputs including texts and/or images and outputs being text. But an immediate concern arises: extremely costly! (all the texts in the Internet, plus all the images) ➔ The idea is now to <strong><em>re-use</em></strong><em> already</em> <em>trained</em> Vision Transformer <em>and</em> <em>already</em> <em>trained </em>LLM. However, we need something more in between: a <strong><em>bridge</em></strong>! Why? The Visual Features space and Textual Features space don’t automatically match. The LLM is not familiar (or <em>trained</em>) with inputs following Visual Features space.</li><li>The training data: images and <em>their corresponding Captions</em>. The architecture of the bridge (called Q-Former): <em>greatly influenced</em> by Transformer (but not identical). Specifically, leverage BERT. The training takes place in two phases: “<strong>Vision-Language-Represetation Learning</strong>” — learn the visual representation most relevant to the text; “<strong>Vision-To-Language Generative Learning</strong>” — output visual representation can be interpreted by the frozen LLM. According to the Paper Authors, two phases are seperate to avoid the frozen LLM from <em>cheating (</em><a href="https://youtu.be/zTr5vDjEy2I?t=3300"><em>link</em></a><em>)</em>. Put it plainly, we should have good representation of the data first (with whatever Loss functions); then <em>afterwards</em>, we figure out what to do with such representation for a downstream task (in our case: downstream task is a <em>frozen </em>LLM generating text).</li></ul><h3>1st Training Phase: Vision-Language-Represetation Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hwgWeCJHCdCunipDcOY1sA.jpeg" /><figcaption>1st Training Phase (courtesy: from the Paper)</figcaption></figure><h4>1st Loss Function: Image-Text Contrastive Learning</h4><ul><li>We start with a Soft Prompt <em>placeholder </em>(random values initially) (aka. <strong>Learned Queries</strong> in the paper): 32 tokens, 768 dimensions each. Given an Image, the Image goes through a <em>frozen pre-trained</em> Vision Transformer to extract Visual Features. The Soft Prompt placeholder above goes through BERT, along which it attends to the Visual Features (<em>but only every other block</em>). Now we end up with context-aware Soft Prompt placeholder output (1). Context <em>here</em> means: the tokens within the Soft Prompt placeholder itself <em>plus</em> the Visual Features.</li><li>The caption goes through another BERT, outputting context-aware tokens. Context <em>here</em> means: the tokens within the caption. Note: in addition, there is a special token CLS in the output. This special neutral token is used to represent the entire Caption (2).</li><li>What to do with (1) and (2), in regard to Loss function? <em>Not all Vision tokens are equally relevant to the caption</em>. That’s why the Paper Authors do Cosine Similarity pair-wise between (1) and (2), and<em> choose the highest value</em>. For a positive Image-Caption pair, the similarity should be close to 1. Creating negative Image-Caption pairs is easy (just randomly choose captions for a specific Image, instead of the caption <em>coupled </em>with the Image in the training Data).</li><li><strong>Intuition</strong>: in this step, we feel that the Soft Prompt placeholder is kind of an extractor: given Visual Features (from the frozen Vision Transformer), it learns how to extract Features <em>in the direction of the Caption</em>. Later, in Inference phase, when inputting an Image, we assume that the Soft Prompt placeholder <em>output </em>should reflect the <em>implicit </em>caption, whose image <em>more or less</em> corresponds to the current image. The use of Cosine Similarity says that “the representation should more or less resemble the caption (rather than exact match)”. Contrastive Learning enables similar things to move closer to each other (in high-dimensional space), while different things should move further away. Choosing the highest value makes sense as when they (Image/Caption) don’t match, even the highest value is still far from 1. In another sense, the Caption may describe only parts of images, so we should iterate Vision tokens and choose the highest value of Cosine Similarity.</li></ul><h4>2nd Loss Function: Image-Grounded Text Generation</h4><ul><li>In the 1st Loss function part, we can direct the Soft Prompt placeholder <em>output</em> toward a good representation between Visual Features (from the Image) and Textual Features (from the Caption). This is not enough; as it doesn’t guarantee that such Prompt is usable in a LLM (“usable” means: similar to distribution of the input Embeddings in a LLM).</li><li>To fix this issue, we actually use it to train. Remember the earlier BERT where Caption goes through? Now we use the same BERT as a <em>Decoder </em>(in Transformer architecture): its Cross-Attention will be carried out against Soft Prompt placeholder output. Here we expect to generate the Caption! The Loss function in this part is, thus, clear.</li><li>In the paper, it says “<em>The queries can attend to each other but not the text tokens. Each text token can attend to all queries and its previous text tokens</em>” — This is what a Decoder does (in the context of Transformer architecture).</li><li><strong>Intuition</strong>: The representation is… representative for a corresponding thing when it helps distinguish that thing from other things. E.g. a specific picture is different from other pictures. But to use such representation in a LLM (i.e. <em>usable</em> in a LLM), the representation should be aligned with the distribution of embeddings where the LLM was trained on. That’s why we need this 2nd Loss function.</li></ul><h4>3rd Loss Function: Image-Text Matching</h4><ul><li>Now comes the question: what if <em>all tokens</em> in Soft Prompt Placeholder and Text (the Caption!) attend each other? Although not said in the Paper, I think this is influenced by <em>Cross-Encoder</em> concept (<a href="https://osanseviero.github.io/hackerllama/blog/posts/sentence_embeddings2/">link</a>). We just put those tokens together and allow them to attend every other. So each resulting token is aware of both Visual and Textual Features. The most visible task for this approach is to check if they (Image+Caption Features) <em>match or not</em>.</li><li>In the Paper, the output is fed into two-class linear Classifier to obtain the logit, and then average the logit across all queries as the output matching score. The <em>averaging</em>, instead of choosing max like in 1st Loss function, is <em>self-explainable</em>.</li><li><strong>Intuition</strong>: Describing an Image can be challenging as different people see different things in the same Image. Worse, the description is non-exhausting. Description can also be partially wrong (or correct), given the corresponding Image. Therefore, this Loss function hopes the model learns to exploit this challenging aspect. Intuitively, if a Caption describes an Image perfectly (diverse, correct, concise), then the Match score should be super high!</li></ul><h3>2nd Training Phase: Vision-To-Language Generative Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKgWUuSr-vD9McntvTuxgQ.jpeg" /><figcaption>2nd Training Phase (courtesy: from the Paper)</figcaption></figure><ul><li>The frozen LLM can be different than the one (BERT) used in Q-Former. For example, in the paper, OPT and FlanT5 LLM families were used.</li><li>The Soft Prompt placeholder output (as the ultimate output of Q-Former) is supposed to be representative. To make it usable in a specific LLM, it needs further alignment because the input embedding of every LLM is simply different (due to its own Training Data and the way it trains). The alignment here is realized through a “Fully Connected” layer. The result will be the Soft Prompt <em>prepended </em>into the prompt for the frozen LLM.</li><li><strong>Intuition</strong>: As said, we need two separate Training phases so that the frozen LLM doesn’t cheat. The 1st Training phase creates representations that are representative <em>in certain ways</em>, and possibly usable in a LLM. The 2nd Training phase enables the alignment between the aforementioned representation and the final Soft Prompt that makes the frozen LLM describe in a way similar to its <em>should-be</em> Caption.</li></ul><h3>My comments</h3><ul><li>The SOTA in this Paper was achieved likely due to the clever use of different Loss functions. One can have +5 Loss functions if they really want to. When a Loss function is defined, during training, the values of Weight and Embeddings are supposed to move toward <em>more sensible</em> numbers following directions oriented by the Loss functions. Reasonably, the more Loss functions, the better! A Loss function captures a different aspect of how the values <em>should</em> end up.</li><li>The concept of Soft Prompt should be appreciated. In LLM, everything is <em>eventually </em>series of numbers. We humans interpret a specific series of numbers as a token, e.g. “book”, and understand it.</li><li>The point of attending to Visual Features (from a frozen pre-trained Vision Transformer) only in every other block is because of compute efficiency (aka. less computation), and more chances for the Soft Prompt placeholder to self-attend each other.</li><li><strong>The quality of Captions can’t be stressed enough</strong> as visibly it heavily influences the Learned Queries in extracting <em>relevant</em> Visual Features.</li><li>The source code (implementation): <a href="https://github.com/salesforce/LAVIS/tree/main/lavis/models/blip2_models">https://github.com/salesforce/LAVIS/tree/main/lavis/models/blip2_models</a> ➔ worth checking as in Image-Text Matching task, they adopt the <em>hard negative mining strategy</em> from Li et al. (2021; 2022). What is it?! Furthermore, in 2nd Training phase, does the Learned Queries also get updated?</li><li>In Machine Learning, we have a list of tools (tricks), e.g. Contrastive Learning, Cosine Similarity, Concatenation vs. Averaging vs. Max. None of them is perfect in solving a task, but every tool brings certain <em>desirable effects</em> as well as its <em>uncertainty</em>. We all hope that by using a collection of <em>appropriate tools</em>, we can achieve high performance for a downstream task.</li><li>Last but not least, a few remarks in AI/ML: “<em>Every model is wrong, but some are useful</em>” (George Box). ML advances are mainly based on empirical evidence (from time to time, we have some mathematical proofs). As a result, we pay attention to architectures or techniques that are <em>showed to work well,</em> and put them into our arsenal! 🚀</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RInGvjUtPudrgRDigFGAdA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0985b64a1115" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Knowledge-aware predictions with LSTM]]></title>
            <link>https://thachngoctran.medium.com/knowledge-aware-predictions-with-lstm-6ed8064b3c1d?source=rss-fe5661177636------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ed8064b3c1d</guid>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[knowledge-graph-embedding]]></category>
            <category><![CDATA[named-entity-recognition]]></category>
            <category><![CDATA[rnn]]></category>
            <dc:creator><![CDATA[TRAN Ngoc Thach]]></dc:creator>
            <pubDate>Fri, 13 Jun 2025 18:38:11 GMT</pubDate>
            <atom:updated>2025-06-13T18:38:11.171Z</atom:updated>
            <content:encoded><![CDATA[<p>The Research Paper to be reviewed: “<em>Leveraging Knowledge Bases in LSTMs for Improving Machine Reading</em>” (Yang et al., 2017) (<a href="https://arxiv.org/abs/1902.09091">link</a>)</p><h4>TL;DR (for the Impatient)</h4><ul><li>The <strong><em>last hidden State </em></strong>of LSTM is used to make predictions. To enable Knowledge-aware predictions, instead of using only the Hidden State, it is complemented with Background Knowledge and Context Knowledge, <strong><em>proportionally </em></strong>in an <strong><em>additive </em></strong>manner (*).</li><li>In each LSTM iteration, based on the <strong><em>currently processed word</em></strong>, fetch relevant Background Knowledge as a series of <strong><em>pretrained </em></strong>vectors from some Database (let’s call KB Vectors). Each is of the same size as the Hidden State. Add them to Hidden State, but at which proportions (ratio)? Proportion for <strong>each </strong>(α)<strong>, </strong>is calculated using the corresponding KB Vector and the latest Hidden State. All α sum up to 1.</li><li>Wait, there is more: the authors argue that forced-upon KB synthesization into the Hidden State may not be desirable in some case as the searched KB Vectors rely on the current word, whose meaning varies in different contexts. Thus, a Sentinel Vector is <strong><em>introduced; its computation is similar to the Hidden State</em></strong> (with a different Weight matrix). This is added to (*) <strong><em>with proportion</em></strong> β. Now, all α and one β must sum up to 1. This design:</li></ul><blockquote>…allow for better <strong>tradeoff</strong> between the impact of background knowledge and information from the context.</blockquote><h4>Long Version</h4><p>The task at hand is “Entity Extraction” (aka. Named Entity Recognition/NER) (<a href="https://en.wikipedia.org/wiki/Named-entity_recognition">link</a>). The input data is a long text, in which we find interested entities. LSTM (<a href="https://en.wikipedia.org/wiki/Long_short-term_memory">link</a>) is well suited for processing sequential data. At this point, one can just proceed to training LSTM model with marker scheme such as BIO labels (<strong>B</strong>egin, <strong>I</strong>nside, and <strong>O</strong>utside) (<a href="https://aclanthology.org/W09-1119/">link</a>). The data for training include ACE2005 (<a href="https://catalog.ldc.upenn.edu/LDC2006T06">link</a>), and OntoNotes 5.0 (<a href="https://aclanthology.org/N06-2015/">link</a>). The embedding scheme for text is Pretrained Paraphrastic Embeddings (<a href="https://arxiv.org/abs/1511.08198">link</a>). Note: those embeddings also get fine-tuned during training.</p><p>However, it is worth trying to improve LSTM prediction performance by injecting additional Knowledge. In LSTM, the Hidden State is called “Working Memory”; the Cell State “Long-Term memory”. The last Hidden State of LSTM is used to make predictions, thus, depending entirely on the inputs (from time 0). Here one can make a difference: add more Knowledge into the Hidden State. Where to get the Knowledge? The Knowledge Graph comes from WordNet (WordNet, 2010) and NELL (Mitchell et al., 2015).</p><p>In each LSTM iteration (loop), <strong><em>based on the currently processed word</em></strong>, extract relevant Knowledge from such Graphs, as Vectors (of course, same size as the Hidden State), called <strong>KB</strong> Vectors (<strong>K</strong>nowledge <strong>B</strong>ase). The remaining question is how to combine such Vectors with the Hidden State? If just adding, one may end up with a situation where a lot of additional Knowledge can suppress signal from the Hidden State ➔ we have to constrain it somehow. In the paper, <strong>each</strong> Vector is added at proportion <strong>α</strong> (a scalar). To avoid the aforementioned situation, all those α must sum up to 1. Reasonably, the α is computed, using the Vector itself and the latest Hidden State (make sense!) The complemented Hidden State now can be used to make prediction as usual, but this time, with additional Knowledge.</p><p>However, the Paper Authors noticed that the extracted KB Vectors sometime are misleading due to words, whose meanings vary in different contexts. To alleviate this situation, another Sentinel Vector composed similarly to the Hidden State (of course, with a different Weight matrix). This is supposed to serve the role as Context Knowledge (versus Background Knowledge as extracted from Knowledge Graph). Again, this must be added proportionally (with proportion <strong>β —</strong> a scalar).<strong><em> Now, all α and one β must sum up to 1</em></strong>.</p><p>The final complemented Hidden State is now used to make predictions. The rest of LSTM process moves on as usual.</p><p>The architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4XTrahhbNwVvsMQFq9GXPA.jpeg" /><figcaption>Architecture (Courtesy: from the Paper)</figcaption></figure><p>In comparison to bidirectional Long Short-Term Memory neural networks<br>(BiLSTMs) (Hochreiter and Schmidhuber, 1997; Graves et al., 2005), there are increased performances:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qKk-haFvPhjhn3kPuQ52IQ.jpeg" /><figcaption>Benchmark (Courtesy: from the Paper)</figcaption></figure><h4>My comments</h4><ul><li>The synthesization of additional knowledge can help share learning across different examples, via their relation in Knowledge Graph/Knowledge Base.</li><li>It is worth exploring to fetch relevant additional Knowledge using the whole input (from timestep 0 to the current), instead of using only the current word.</li><li>I’m still not convinced about the part involving Sentinel Vector to balance between Background Knowledge and Context Knowledge. The Hidden State already contains some Context Knowledge? Maybe one can somehow adjust the Hidden State at a proportion dynamically, in relation to Background Knowledge? (instead of using Sentinel Vector)</li><li>The more I investigate Machine Learning model architectures, the more I come to appreciating the saying: “<strong><em>Every model is wrong, but some are useful</em></strong>”. (George Box) 😉</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ed8064b3c1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One way to encode Knowledge Graph for Predictive modeling]]></title>
            <link>https://thachngoctran.medium.com/one-way-to-encode-knowledge-graph-for-predictive-modeling-4f5bc302c5ba?source=rss-fe5661177636------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f5bc302c5ba</guid>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[knowledge-graph-embedding]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <dc:creator><![CDATA[TRAN Ngoc Thach]]></dc:creator>
            <pubDate>Wed, 11 Jun 2025 10:12:22 GMT</pubDate>
            <atom:updated>2025-06-11T10:12:22.901Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we summarize the Research paper “<strong><em>Explainable Reasoning over Knowledge Graphs for Recommendation</em></strong>” (Wang et al., 2018) (<a href="https://arxiv.org/abs/1811.04540">link</a>)</p><h4><strong>TL;DR (for the impatient)</strong></h4><ul><li>Supposed there is a Knowledge Graph (KG) describing user interactions, e.g. <strong><em>Alice</em></strong> listens to the song <strong><em>Shape of You</em></strong>. This Song is written by <strong><em>Ed Sheeran</em></strong>. He in turn writes <strong><em>I See Fire</em></strong>. Prediction Problem: Will <strong><em>Alice</em></strong> also want to listen to <strong><em>I See Fire</em></strong>?</li><li>There can be many Paths leading from <strong><em>Alice</em></strong> to <strong><em>I See Fire</em></strong>. Encode <strong>each</strong> of those Paths using LSTM: each Node/NoteType/Edge in KG is an Embedding; those Embeddings are concatenated to represent one Input for one Iteration of LSTM. The last State of LSTM goes through MLP with one hidden Layer, generating a Score. As there are many Paths, we must aggregate those scores somehow.</li><li>Thanks to the works of Das et al., 2016 (<a href="https://arxiv.org/abs/1607.01426">link</a>), and Chen et al., 2017 (<a href="https://dl.acm.org/doi/10.1145/3077136.3080797">link</a>), Weighted Pooling Layer is leveraged for Score-Aggregation. The pooled value goes through Sigmoid function for final Prediction.</li></ul><h4>Long Version</h4><p>Today, a lot of data are collected, based on which we can build a KG, as the following example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7LUesi-kbnyhkHvU2KrHnw.jpeg" /><figcaption>A Knowledge Graph (Courtesy: From the paper)</figcaption></figure><p>The question to answer is e.g. how probable <strong><em>Alice</em></strong> is interested in listening to <strong><em>I See Fire</em></strong>. Given the many Paths in between, our intuition tells us that they can contribute to that probability. Some Paths are likely more essential than others in such decision. The more Paths, probably the better. A history of User-Entity-Interactions can help us train a Machine Learning (ML) model to predict if a User likes to interact with an Entity, thus, suggesting it to the User (context: Recommendation System (<a href="https://en.wikipedia.org/wiki/Recommender_system">link</a>)).</p><p>There can be infinite Paths between User-Entity, especially if <strong><em>loops</em></strong> are allowed. So it was decided to limit the Length of the Paths up to six. Each User/Entity/Edge (i.e. Interaction) is all Embedding, meaning they are represented as a vector with a specific number of dimensions.</p><p>LSTM (<a href="https://en.wikipedia.org/wiki/Long_short-term_memory">link</a>) is good at modeling sequenced data. The Paths are clearly a sequence. The remaining question is how to contruct an Input for each Iteration (Loop) of LSTM. The Paper suggests the <strong>Triplet </strong>of (Name, Node Type, Edge Type). E.g. (Alice, User, Interact) or (Shape of You, Song, SungBy). The corresponding Embeddings are concatenated, to contruct a single Input for each LSTM Iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3amsIidOI71Agqoz_HXvA.jpeg" /><figcaption>Encoding with LSTM (Courtesy: From the paper)</figcaption></figure><p>The hidden State of LSTM, after going through a Path (sequence of above-mentioned Triplets), <em>represents the Path</em>. Here, we need some magic of MLP (<a href="https://en.wikipedia.org/wiki/Multilayer_perceptron">link</a>) to map the State to a sensible Score. Many Paths (between a User and an Entity at hand) result in many such Scores. The Paper authors suggest using Weighted Pooling Layer to aggregate them. The formula has an Hyperparameter γ (γ = {0.01, 0.1, 1, 10}), that together brings an interesting property: “<em>When setting γ → 0, the pooling function can degenerate to max-pooling; whereas, it can degrade to mean-pooling by setting γ → ∞</em>”.</p><p>The aggregated value (pooled value) will be put through a Sigmoid function (<a href="https://en.wikipedia.org/wiki/Sigmoid_function">link</a>) to produce one final Prediction, as a probability between [0, 1].</p><p>The <strong>data</strong> for training come from MovieLens-1M (<a href="https://grouplens.org/datasets/movielens/1m/">link</a>) and IMDb (<a href="https://www.imdb.com/">link</a>), creating the KG for Movies. For Music, KKBox (<a href="https://wsdm-cup-2018.kkbox.events/">link</a>) was used. The split between Training/Testing is 80/20. The <strong>baseline </strong>models to compare to are MF (Rendle et al. 2009), NFM (He and Chua 2017), CKE (Zhang et al. 2016), FMG (Zhao et al. 2017). The <strong>Evaluation Metrics</strong> are Top-K recommendation (hit@K) and preference ranking (ndcg@K) where K = {1, 2, …, 15}. It is clear the model achieved a new SOTA (at the point of publishing the Paper).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5_DQ123HfXtTciZ2g94Mw.jpeg" /><figcaption>Benchmark on Movie dataset (Courtesy: From the paper)</figcaption></figure><h4>My comments</h4><ul><li>Encoding specific Users, e.g. Alice, may restrict the sharing of Information across different Interactions; in turn, hindering the Learning Process of the Model. Said in other words, one pattern learned from a User may be shared across other Users. Using specific names makes this harder for such patterns to be recognized.</li><li>The found Paths between User-Entity may contribute greatly to the Predictive Performance. Putting more attentions on certain Paths may be beneficial. The Bahdanau Attention (<a href="https://arxiv.org/pdf/1409.0473">link</a>) may come in handy here.</li><li>The positive examples in the data are clear (User interacts with an Entity). But for negative examples, the Paper Authors chose “the user has not interacted with”, which may not be optimal as the user may have not interacted with the entity <strong><em>yet</em></strong>. Some uncertainties here.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f5bc302c5ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring PrimeKG — A Knowledge Graph for Medicine & Healthcare]]></title>
            <link>https://thachngoctran.medium.com/exploring-primekg-a-knowledge-graph-for-medicine-healthcare-0f183669ad62?source=rss-fe5661177636------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f183669ad62</guid>
            <category><![CDATA[knowledge-graph-embedding]]></category>
            <category><![CDATA[neo4j]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[graph-embedding]]></category>
            <category><![CDATA[neo4j-graph-database]]></category>
            <dc:creator><![CDATA[TRAN Ngoc Thach]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 01:01:02 GMT</pubDate>
            <atom:updated>2024-07-24T07:49:13.196Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring PrimeKG — A Knowledge Graph for Medicine &amp; Healthcare</h3><p>This article will take a glance at the paper “Building a knowledge graph to enable precision medicine” (Chandak et al, 2023) [1] (aka. PrimeKG), load the graph data and visualize it, using <a href="https://neo4j.com/download/">Neo4j Desktop</a> — A Graph Database.</p><h3>Introduction</h3><p>Everything is connected. Modeling the world with graphs is, thus, a natural choice. For example, MONDO Disease Ontology [2] — a knowledge graph, composed of millions of entities, from genes to diseases; or the Gene Ontology [4] — describing molecular functions, cellular components, and biological processes. In addition, there are also data banks, e.g. Disease Gene Network (DisGeNet) [3] — exploring gene-disease associations; Orphanet — an encyclopaedia of rare diseases. As showed, such medicine and healthcare knowledge is fragmented. PrimeKG [1] is an attempt to…</p><blockquote>…integrates 20 high-quality resources to describe 17,080 diseases with 4,050,249 relationships representing ten major biological scales, including disease-associated protein perturbations, biological processes and pathways, anatomical and phenotypic scales, and the entire range of approved drugs with their therapeutic action, considerably expanding previous efforts in disease-rooted knowledge graphs.</blockquote><p>Let’s get started! 😀</p><h3>Preparing &amp; Loading</h3><h4>Preparing</h4><ol><li>Follow the link to PrimeKG raw data [5]. Download “edges.csv” (368.6 MB) and “nodes.csv” (7.5 MB). Why? → There are other files, e.g. “kg.csv” which contains the full graph (formatted as node1-relation-node2 for each line). But importing graph with separate nodes and edges files is the <em>quickest and most efficient way</em> [8].</li><li>Download and install an Open JDK. I often use Eclipse Temurin [7]. Choose version 17 (LTS) or 21 (LTS). After installation, check that JAVA_HOME environment variable is pointed to the correct JDK location. Why? → We need JDK later to run “neo4j-admin.bat” in Neo4j.</li><li>Use <a href="https://notepad-plus-plus.org/downloads/">Notepad++</a> to change the header of “edges.csv” to :TYPE,display_relation,:START_ID,:END_ID. Change the header of “nodes.csv” to node_index:ID,node_id,:LABEL,node_name,node_source. Why? → The Neo4j Import Tool [8] requires CSV files to have their headers follow certain guidelines, e.g. which column is ID.</li><li>Use Notepad++ to search and replace “/” for “__” in “nodes.csv”. Why? → Neo4j Node Name must follow certain restrictions.</li><li>Download and install <a href="https://www.anaconda.com/download">Anaconda</a>, or at least Python with Pandas library. Why? → Unfortunately, I found that the “edges.csv” contain double edges, meaning we have a CSV row saying “Node A is pointed to Node B with <em>relation X</em>”, and another row saying “Node B is pointed to Node A with <em>relation X</em>”. <strong>We intend to build an </strong><a href="https://www.mathworks.com/help/matlab/math/directed-and-undirected-graphs.html"><strong>undirected graph</strong></a><strong> in Neo4j</strong>. Therefore, we must remove duplicate edges. I only know how to do that with Python/Pandas! 😅</li></ol><pre>import pandas as pd<br>df = pd.read_csv(r&quot;edges.csv&quot;, header=&quot;infer&quot;, sep=&quot;,&quot;, encoding=&quot;utf-8&quot;, dtype=str, keep_default_na=False)<br>                 <br>group = df[[&quot;:START_ID&quot;, &quot;:END_ID&quot;, &quot;:TYPE&quot;, &quot;display_relation&quot;]].agg(frozenset, axis=1)<br>df_result = df.groupby(group).first()<br>df_result.to_csv(r&quot;edges2.csv&quot;, sep=&#39;,&#39;, encoding=&#39;utf-8&#39;, index=False)</pre><h4>Loading</h4><ol><li>Open Neo4j Desktop. Create a New Project. Add “Local DBMS”. Look for the triple dots: click on it, then “Open Folder”, then “DBMS”.</li><li>Windows Explorer will open the location where the DBMS is located. In my case, it is C:\Users\[Username]\.Neo4jDesktop\relate-data\dbmss\dbms-886ac993–25d9–493a-922b-2d41e29b6446.</li><li>Open CMD right there. Now use the command below. Remember to change the [path] appropriately.</li></ol><pre>.\bin\neo4j-admin database import full primekg --nodes=&quot;D:\[path]\nodes.csv&quot; --relationships=&quot;D:\[path]\edges2.csv&quot; --trim-strings=true</pre><ol><li>Within Neo4j Desktop, click button “Start” according to the DBMS having been created. Then click on “Open” to open Neo4j Browser.</li><li>Create the database “primekg”. Then change to using the database as <em>the</em> active one. (Those are <a href="https://neo4j.com/docs/cypher-manual/current/introduction/">Cypher query</a>)</li></ol><pre>CREATE DATABASE primekg<br>:use primekg</pre><p>Within Neo4j Browser, type a command to verify if everything is good:</p><pre>MATCH (n) RETURN COUNT(n)</pre><p>The command should return 129375. This is the number of nodes within the graph. Then further testing with the command:</p><pre>MATCH ()-[r]-() RETURN COUNT(DISTINCT r)</pre><p>It should return 4050249. On page 2 of the paper [1], we read:</p><blockquote>Across <strong>129,375</strong> nodes and <strong>4,050,249</strong> relationships, PrimeKG captures information on ten major biological scales.</blockquote><p>Everything is set up!</p><h3>Visualizing &amp; Exploring</h3><h4>Visualizing</h4><p>To get the Database Schema, we can use CALL db.schema.visualization() in Neo4j Browser. A visual graph is displayed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*ush2K0nx1JttoZBagLn9_w.jpeg" /><figcaption>PrimeKG Schema</figcaption></figure><h4>Exploring</h4><p>To get all the Node Types, use CALL db.labels(). Result:</p><pre>╒════════════════════╕<br>│label               │<br>╞════════════════════╡<br>│&quot;anatomy&quot;           │<br>├────────────────────┤<br>│&quot;gene__protein&quot;     │<br>├────────────────────┤<br>│&quot;disease&quot;           │<br>├────────────────────┤<br>│&quot;effect__phenotype&quot; │<br>├────────────────────┤<br>│&quot;drug&quot;              │<br>├────────────────────┤<br>│&quot;biological_process&quot;│<br>├────────────────────┤<br>│&quot;molecular_function&quot;│<br>├────────────────────┤<br>│&quot;cellular_component&quot;│<br>├────────────────────┤<br>│&quot;exposure&quot;          │<br>├────────────────────┤<br>│&quot;pathway&quot;           │<br>└────────────────────┘</pre><p>On page 5 of the paper [1], we can see the list of Nodes, and they match!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gYHIOsplcWB1wvIDCifC1g.jpeg" /></figure><p>To get all the Relationship Types, use CALL db.relationshipTypes(). Result:</p><pre>╒════════════════════════════╕<br>│relationshipType            │<br>╞════════════════════════════╡<br>│&quot;protein_protein&quot;           │<br>├────────────────────────────┤<br>│&quot;anatomy_protein_present&quot;   │<br>├────────────────────────────┤<br>│&quot;molfunc_protein&quot;           │<br>├────────────────────────────┤<br>│&quot;cellcomp_protein&quot;          │<br>├────────────────────────────┤<br>│&quot;drug_effect&quot;               │<br>├────────────────────────────┤<br>│&quot;bioprocess_bioprocess&quot;     │<br>├────────────────────────────┤<br>│&quot;anatomy_anatomy&quot;           │<br>├────────────────────────────┤<br>│&quot;bioprocess_protein&quot;        │<br>├────────────────────────────┤<br>│&quot;exposure_disease&quot;          │<br>├────────────────────────────┤<br>│&quot;exposure_protein&quot;          │<br>├────────────────────────────┤<br>│&quot;exposure_exposure&quot;         │<br>├────────────────────────────┤<br>│&quot;exposure_bioprocess&quot;       │<br>├────────────────────────────┤<br>│&quot;pathway_protein&quot;           │<br>├────────────────────────────┤<br>│&quot;pathway_pathway&quot;           │<br>├────────────────────────────┤<br>│&quot;exposure_molfunc&quot;          │<br>├────────────────────────────┤<br>│&quot;exposure_cellcomp&quot;         │<br>├────────────────────────────┤<br>│&quot;molfunc_molfunc&quot;           │<br>├────────────────────────────┤<br>│&quot;cellcomp_cellcomp&quot;         │<br>├────────────────────────────┤<br>│&quot;anatomy_protein_absent&quot;    │<br>├────────────────────────────┤<br>│&quot;drug_drug&quot;                 │<br>├────────────────────────────┤<br>│&quot;indication&quot;                │<br>├────────────────────────────┤<br>│&quot;off-label use&quot;             │<br>├────────────────────────────┤<br>│&quot;contraindication&quot;          │<br>├────────────────────────────┤<br>│&quot;drug_protein&quot;              │<br>├────────────────────────────┤<br>│&quot;disease_phenotype_positive&quot;│<br>├────────────────────────────┤<br>│&quot;disease_phenotype_negative&quot;│<br>├────────────────────────────┤<br>│&quot;phenotype_phenotype&quot;       │<br>├────────────────────────────┤<br>│&quot;disease_disease&quot;           │<br>├────────────────────────────┤<br>│&quot;disease_protein&quot;           │<br>├────────────────────────────┤<br>│&quot;phenotype_protein&quot;         │<br>└────────────────────────────┘</pre><p>On page 9 of the paper [1], we see the list of Relation Types, and they (likely) match! 😅</p><p>Although the graph is complex and full-fledged, I am interested in Associations “Disease-Exposure” and “Disease-Disease”. For example, I wonder what could be the environmental risk factors for Diabetes. The query:</p><pre>MATCH (e:exposure)-[:exposure_disease]-(d:disease)<br>WHERE d.node_name CONTAINS &#39;diabetes&#39;<br>RETURN d.node_name, e.node_name<br>ORDER BY d.node_name, e.node_name</pre><p>Result:</p><pre>╒═════════════════════════════╤══════════════════════════════════════╕<br>│d.node_name                  │e.node_name                           │<br>╞═════════════════════════════╪══════════════════════════════════════╡<br>│&quot;diabetes mellitus (disease)&quot;│&quot;2,4,4&#39;,5-tetrachlorobiphenyl&quot;        │<br>...<br>├─────────────────────────────┼──────────────────────────────────────┤<br>│&quot;diabetes mellitus (disease)&quot;│&quot;bisphenol A&quot;                         │<br>├─────────────────────────────┼──────────────────────────────────────┤<br>│&quot;diabetes mellitus (disease)&quot;│&quot;cyanazine&quot;                           │<br>...</pre><p>Some sanity check with the association between “bisphenol A” (BPA — a chemical used in the production of polycarbonate plastics) and “diabetes”: the paper [9] shows:</p><blockquote>Several epidemiological studies reveal <strong>a significant association between BPA</strong> and <strong>the development of insulin resistance</strong> and impaired glucose homeostasis…</blockquote><h3>Remarks</h3><p>The <em>original</em> Knowledge Graphs as well as databanks, from which PrimeKG is composed, definitely change overtime. How to recreate PrimeKG from crash (i.e. update it) is advised in [6].</p><p>“<em>The devil is in the details</em>.” Synthesizing multiple data sources may pose challenges because different data sources could use (slightly) different names for diseases. Even in the same source, “<em>MONDO contains many repetitive disease entities with no apparent clinical correlation. For this reason, we were motivated to group diseases in MONDO into medically relevant entities</em>”, as noted by the Chandak et al [1]. Then the authors moved to leveraging ClinicalBERT embeddings with cutoff threshold of 0.98 to determine similarity. This is just among many other steps in processing raw data coming from various sources.</p><p>The original “edges.csv” contains directed edges. At first, I thought there could be some assumption about this as directed edges allow to meaningfully indicate “A affects B” (but not the other way around). However, when loading full “edges.csv” into Pandas Dataframe, the number of rows is <em>perfectly double</em> of the intended rows in the paper (8,100,498 vs. 4,050,249). So I think the authors happened to have directed edges, rather than a careful consideration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TaVzOplRGknnC-jUNCafAQ.jpeg" /><figcaption>Directed Edges (in “edges.csv”) — An example. The left-most numbers are row index.</figcaption></figure><p>In summary, PrimeKG is beneficial to not only medical researchers but also to Machine Learning developers because they can make use of such graphs for feature engineering, or <a href="https://medium.com/@thachngoctran/incorporate-knowledge-graph-with-attention-in-ehr-a-case-study-8f0772cad510">graph embedding</a>. 🧐</p><h3>References</h3><p>[1] Building a knowledge graph to enable precision medicine. Chandak et all (2023) (<a href="https://www.nature.com/articles/s41597-023-01960-3">https://www.nature.com/articles/s41597-023-01960-3</a>)</p><p>[2] MONDO Disease Ontology (<a href="https://monarchinitiative.org/">https://monarchinitiative.org/</a>)</p><p>[3] DisGeNET (<a href="https://disgenet.com/">https://disgenet.com/</a>)</p><p>[4] Gene Ontology (<a href="https://geneontology.org/">https://geneontology.org/</a>)</p><p>[5] PrimeKG Data (<a href="https://dataverse.harvard.edu/dataset.xhtml?persistentId=doi:10.7910/DVN/IXA7BM&amp;version=2.1">https://dataverse.harvard.edu/dataset.xhtml?persistentId=doi:10.7910/DVN/IXA7BM&amp;version=2.1</a>)</p><p>[6] PrimeKG SourceCode (<a href="https://github.com/mims-harvard/PrimeKG">https://github.com/mims-harvard/PrimeKG</a>)</p><p>[7] Eclipse Temurin (<a href="https://adoptium.net/temurin/releases/">https://adoptium.net/temurin/releases/</a>)</p><p>[8] Neo4j Import (<a href="https://neo4j.com/docs/operations-manual/current/tools/neo4j-admin/neo4j-admin-import/#import-tool-syntax">https://neo4j.com/docs/operations-manual/current/tools/neo4j-admin/neo4j-admin-import/#import-tool-syntax</a>)</p><p>[9] Bisphenol A and Type 2 Diabetes Mellitus: A Review of Epidemiologic, Functional, and Early Life Factors (<a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7830729/">https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7830729/</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f183669ad62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Incorporate Knowledge Graph with Attention in EHR — A Case Study]]></title>
            <link>https://thachngoctran.medium.com/incorporate-knowledge-graph-with-attention-in-ehr-a-case-study-8f0772cad510?source=rss-fe5661177636------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f0772cad510</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[knowledge-graph-embedding]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[attention-mechanism]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[TRAN Ngoc Thach]]></dc:creator>
            <pubDate>Mon, 15 Jul 2024 23:43:35 GMT</pubDate>
            <atom:updated>2024-07-15T23:43:35.989Z</atom:updated>
            <content:encoded><![CDATA[<h3>Incorporate Knowledge Graph with Attention in EHR — A Case Study</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X15OYRWZi5snBhkJnzbWfw.png" /></figure><p>In this article, the main idea of the paper “<em>GRAM: Graph-based Attention Model for Healthcare Representation Learning</em>” (2017) [1] is explained (its Source Code [8]). I read it, investigated it, made sense out of it. So you don’t have to. 😊 <em>Disclaimer</em>: There is <strong>no</strong> <a href="https://en.wikipedia.org/wiki/Graph_neural_network">Graph Neural Network</a> to be discussed.</p><h3>Introduction</h3><p>EHR (Electronic Health Record) is everywhere. As I know, originally it was created to facilitate the billing purpose, but now it is an essential tool to keep track of health information on individuals. Challenges still remain due to different formats and terminology systems as well as data exchange and interoperability [2]. EHR can contain anything, from Blood Test result, to X-Ray images; but we focus on Diagnose Codes for patients, noted down in every of their visits to doctors. Such (concise) Diagnose Codes are actually standardized: ICD [3]. Imaging that for every doctor visit, the patient ends up with a series of Diagnose Codes for that <em>specific</em> visit. Overtime, the patient has a collection of such codes, and an idea comes up: for <em>the</em> patient, can we predict their future Diagnose Codes based on the code history? That makes sense. For example, the Diagnose Code I10 [4] for Hypertension and E78.00 for High Cholesterol Level [5] may predict the chance of I63.9 for Stroke [6] <em>in the future</em>, as the relation is well known [7].</p><p>This can be framed as a prediction task for RNN (Recurrent Neural Network). Despite being powerful in mapping arbitrary Input to arbitrary Output, Neural Network needs our help in feature-engineering so that it can converge faster and generalize better. Paper [1] proposes enriching the Diagnose Codes, as Input to a RNN, with <a href="https://en.wikipedia.org/wiki/Knowledge_graph">Knowledge Graph</a> and <a href="https://en.wikipedia.org/wiki/Attention_(machine_learning)">Attention</a>.</p><h3>Paper Summary</h3><p>We start with the Knowledge Graph. Where does it come from? And how does it fit in the whole scheme here? The ICD Codes [3] are structured as <em>tree</em>, schematically encoding the parent-child-sibling relations between dieseases. Doctors are advised to note down the patient’s diagnosed dieases <em>at the as much granular level as possible</em>: typically the <em>leaf nodes</em>. For example, Hypertension (I10) has the parent “Hypertensive diseases” and grandparent “Diseases of circulatory system”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AO08vjo9nKM6RWTewDG4Dw.jpeg" /><figcaption>Figure 1: ICD Code Browser [9], version ICD-10, 2019</figcaption></figure><p>Based on this ICD tree, we have a Knowledge Graph. The missing piece of this graph is the Nodes’ Features, which is not available in ICD. So, <em>how do we create the Node Feature in a meaningful way</em>? The paper leveraged the technique GloVe [11], which prerequires the construction of a Co-occurrence matrix for Diagnose Codes. As an example, assuming that in a Visit Vₜ, the patient is diagnosed with Codes cd, cᵢ, cₖ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jSxLbNPlqvGcy9q4WepBjQ.jpeg" /></figure><p>Those Codes are Leaf Nodes within ICD Tree. For each, we also collect <em>all the Codes corresponding to their Ancestor Nodes</em>. Thus, end up with V’ₜ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSFM0UaHc-WO6FCKbpZkEg.jpeg" /></figure><p>The Co-occurrence measure for cᵢ and cⱼ within V’ₜ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v2KM-dh8FV-BQ__7-exYjA.jpeg" /></figure><p>This process is repeated for all pairs of Codes in all augmented visits of all patients to obtain the co-occurrence matrix. Then follow the guidance in [11] for training the embedding vectors for Feature Nodes.</p><p><strong>Implication of <em>this setup</em></strong>: Diagnose Codes of more general medical concepts (i.e. the Ancestor Nodes in ICD) appear more frequently than the others, thus contributing higher to medical events (i.e. Visit).</p><p>We now have the Knowledge Graph (Nodes with Connections and Node Features). It’s worth pointing out that we do <strong>not</strong> intend to use <a href="https://en.wikipedia.org/wiki/Graph_neural_network">Graph Neural Network</a>; but instead, embed the Knowledge Graph into the Input of our Model, which is currently as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2ErvIifNxgxlZ73o1tSwA.jpeg" /><figcaption>Figure 2: Model Input (for one patient) without Knowledge Graph and Attention (<em>yet</em>).</figcaption></figure><p>The paper’s proposal of embedding Knowledge Graph is as followed:</p><ul><li>In each Visit, there are a series of Diagnose Codes, which are among Leaf Nodes in ICD. Encoded as multi-hot vector (image above).</li><li>For each Leaf Node, gather <em>all of their</em> Ancestor Nodes. E.g. Leaf Node (aka. Diagnose Code) c₁ has parent-of-c₁ and grandparent-of-c₁ Nodes, each of which has its own Feature vectors, thanks to GloVe [11] as aforementioned.</li><li>A summation of these Feature Vectors corresponding to c₁, parent-of-c₁, grandparent-of-c₁… can <em>better represent</em> the Diagnose Code c₁. However, <em>sum at what ratio</em>? This is where Attention comes into play.</li><li>The attention technique is called <em>Additive Attention</em>, influenced by the paper Bahdanau et al. (2016) [13]. To make sure all the Attention Weights summed to 1, Softmax is used. Each weight is computed as the output of a Feed-Forward Network with one hidden layer, which in turn accepts input as a concatenation vector between c₁ and its Ancestor. Note: We consider c₁ <em>itself</em> is among its Ancestors.</li></ul><p>Let’s call these steps as <em>the construction of the </em><strong><em>Embedding Matrix G</em></strong> (below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*beuizjRrYFSLmbRUmU35bQ.jpeg" /><figcaption>Figure 3: Embed Knowledge Graph with Attention (image from the paper).</figcaption></figure><p>The embedding matrix G: G ∈ Rᵐ ˣ ᶜ, where C is the number of Diagnose Codes (i.e. Leaf Nodes), and m is the number of dimensions of Feature Nodes in Knowledge Graph. The Model Input (as in Figure 2): x ∈ Rᶜ ˣ ᵀ. Doing the matrix multiplication, we got the Input for our RNN. And the rest of operation is nothing special.</p><p><strong>Implication of <em>this setup</em></strong>:</p><ul><li>The Model Input is now more <em>expressive</em> (instead of just a multi-hot vector like in Figure 2): it contains not only information about the direct Diagnose Code, but also information of more general medical concepts through the parent/grandparent relations in ICD. The proportional contribution of child/parent/grandparent is determined via Attention.</li><li>The possibility of transfer knowledge from one patient to another. Intuitive example: Considering Patient L, M and N, respectively diagnosed with Codes cₗ, cₘ, cₙ. Those codes share their parent node or grandparent node (in ICD). Patient L and M are later diagnosed with Code cₓ. Reasonably, Patient N may later also get cₓ! Without embedding the Knowledge Graph, this <em>can-be-transferred knowledge</em> is <em>buried</em>.</li></ul><p>Some other details not discussed so far:</p><ul><li>The Diagnose Code in EHR follows ICD, but in the paper, they convert such ICD Codes (Leaf Node) to CCS Codes because the former is too fine-grained, which may hinder performance while the latter can provide a better summary. Find out more in [10].</li><li>The data used in the paper is of ICD-9, but the Diagnose Code example in this Medium article is of ICD-10.</li><li>The basic embeddings of Diagnose Codes, initialized with GloVe, are also fine-tuned during model training via backpropagation.</li><li>The <em>final hidden state</em> of RNN is put through a FC (Fully Connected Layer) and Softmax to make prediction.</li><li>RNN can be either LSTM, GRU or IRNN…</li><li>Instead of GloVe [11], Skip-gram [12] may be used.</li><li>The loss function is binary cross entropy. In actual implementation, the author takes the average of the individual loss for <em>multiple patients</em> due to batch operation.</li><li>From time to time, as noted in the paper, the real-life EHR data still contain Diagnose Code not at the most granular level, but at the parent level (in ICD tree). In this case, the paper treats the Diagnose Code as just other Leaf Node.</li></ul><h3>Final Remark</h3><p>In my observation, the majority of papers usually try to solve specific narrow tasks, given specific constraints (e.g. data, computation, assumption). One may wonder if age and sex or even BMI (Body mass index) can be also relevant in predicting Diagnose Codes for a specific patient <em>in their future</em>. But the model in this paper [1] did not factore in such. Nevertheless, we have learned one technique in making Model Input more expressive, and enabling transfer knowledge across data points. All these improvements potentially facilitate the Learning to converge faster and generalize better.</p><p>Last but not least, reading papers is great; at some point, one can come to the realization that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XdR4URp--YvaN-P5uxVBLA.jpeg" /></figure><h3>References</h3><p>[1] GRAM: Graph-based Attention Model for Healthcare Representation Learning (2017) (<a href="https://arxiv.org/abs/1611.07012">https://arxiv.org/abs/1611.07012</a>)</p><p>[2] Attention-based neural networks for clinical prediction modelling on electronic health records (2023) (<a href="https://bmcmedresmethodol.biomedcentral.com/articles/10.1186/s12874-023-02112-2">https://bmcmedresmethodol.biomedcentral.com/articles/10.1186/s12874-023-02112-2</a>)</p><p>[3] International Statistical Classification of Diseases (ICD) (<a href="https://www.who.int/standards/classifications/classification-of-diseases">https://www.who.int/standards/classifications/classification-of-diseases</a>)</p><p>[4] ICD I10 (<a href="https://www.icd10data.com/ICD10CM/Codes/I00-I99/I10-I1A/I10-/I10">https://www.icd10data.com/ICD10CM/Codes/I00-I99/I10-I1A/I10-/I10</a>)</p><p>[5] E78.00 (<a href="https://www.icd10data.com/ICD10CM/Codes/E00-E89/E70-E88/E78-/E78.00">https://www.icd10data.com/ICD10CM/Codes/E00-E89/E70-E88/E78-/E78.00</a>)</p><p>[6] I63.9 (<a href="https://www.icd10data.com/ICD10CM/Codes/I00-I99/I60-I69/I63-/I63.9">https://www.icd10data.com/ICD10CM/Codes/I00-I99/I60-I69/I63-/I63.9</a>)</p><p>[7] Risk Factors for Stroke (<a href="https://www.cdc.gov/stroke/risk-factors/index.html">https://www.cdc.gov/stroke/risk-factors/index.html</a>)</p><p>[8] GRAM Source Code (<a href="https://github.com/mp2893/gram">https://github.com/mp2893/gram</a>)</p><p>[9] ICD Code Browser (<a href="https://icd.who.int/browse10/2019/en#/I10">https://icd.who.int/browse10/2019/en#/I10</a>)</p><p>[10] Representing EHR data: ICD codes vs. CCS codes (<a href="https://glassboxmedicine.com/2018/11/13/representing-ehr-data-icd-codes-vs-ccs-codes/">https://glassboxmedicine.com/2018/11/13/representing-ehr-data-icd-codes-vs-ccs-codes/</a>)</p><p>[11] GloVe: Global Vectors for Word Representation (<a href="https://nlp.stanford.edu/pubs/glove.pdf">https://nlp.stanford.edu/pubs/glove.pdf</a>)</p><p>[12] Efficient Estimation of Word Representations in Vector Space (<a href="https://arxiv.org/abs/1301.3781">https://arxiv.org/abs/1301.3781</a>)</p><p>[13] Neural Machine Translation by Jointly Learning to Align and Translate (<a href="https://arxiv.org/abs/1409.0473">https://arxiv.org/abs/1409.0473</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f0772cad510" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spatial Temporal Graph Convolutional Networks (ST-GCN) — Explained]]></title>
            <link>https://thachngoctran.medium.com/spatial-temporal-graph-convolutional-networks-st-gcn-explained-bf926c811330?source=rss-fe5661177636------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf926c811330</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[graph-convolution]]></category>
            <category><![CDATA[graph-neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[graph-convolution-network]]></category>
            <dc:creator><![CDATA[TRAN Ngoc Thach]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 00:05:11 GMT</pubDate>
            <atom:updated>2024-06-30T00:05:11.454Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spatial Temporal Graph Convolutional Networks (ST-GCN) — Explained</h3><p>Explaination for the paper “<em>Spatial Temporal Graph Convolutional Networks for Skeleton-Based Action Recognition</em>” [1] (aka. ST-GCN) as well as key findings in its source code [2].</p><h3>Introduction</h3><p>Graph Neural Network and Knowledge Graph have been my research interest. During Literature Review, there were some noteable papers that opened up new directions or enabled new techniques. Among those is the paper “<em>Spatial Temporal Graph Convolutional Networks for Skeleton-Based Action Recognition</em>” [1]. Its source code is also publicly available [2], which is beneficial as <a href="https://www.kdnuggets.com/2023/06/importance-reproducibility-machine-learning.html">reproducibility</a> is highly appreciated. I have spent some time on this paper, and hope that my short article can get like-minded people to comprehend the paper quicker. Time is our precious asset. 😀</p><h3>Paper Summary</h3><h4>Inspiration</h4><p>The paper itself is an extension of another paper: “<em>Semi-Supervised Classification with Graph Convolutional Networks</em>” [3], which defined the formula for convolving nodes within a graph to create Node Embeddings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*suAC8QAsmTo8ZhaZp9ZEzw.jpeg" /><figcaption>Figure 1: Graph Convolution Formula</figcaption></figure><p>It looks scary at first, but thanks to [4], interpreting this formula can be untangled step-by-step. Its main idea is, given a specific node, to aggregate features from its neighbor nodes with its own’s, then embed the aggregated features into another latent space. The new features becomes <em>that node</em>’s features. Due to matrix multiplication, all the nodes’ features get updated at once . This is <em>one way</em> how convolution is carried out in graph. Notice that the above neighbors are direct ones; what if we are also interested in convolving neighbors at a further distance? In this case, the same process is repeated. Every repetition allows to convolve the neighbor nodes at an one-step further distance. The <em>deeper</em> representation a node ends up with through the convolution, the more representative it can be: it is not only aware of itself, but also the surrounding nodes near it. Typical tasks can be: 1). Node classfication, 2). Graph classfication. For 1), the node features are put through a Fully Connected layer with appropriate outputs, e.g. Softmax for multiclass classification. For 2), all the nodes’ features can be concatenated into one Tensor, and we apply the same processing.</p><h4>ST-GCN</h4><p>The above described convolution is <em>spatial</em>. When adding another dimension to the nodes, such as <em>time</em>, it is motivating to convolve in <em>both spatial and temporal dimensions</em>. That is the idea behind the paper ST-GCN [1]. The task to be solved is <em>Human Action Recognition</em>, using skeleton sequence, denoted with body joints, each of which is a triplet of (Coordinate-X/Coordinate-Y/Confidence-Level):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VCyF86Ag8IRs7mXcjADaPQ.jpeg" /><figcaption>Figure 2: Skeleton sequence in space and time (source: [1])</figcaption></figure><p>ST-GCN’s archiecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8MwnBuSizz7-eUhrQcri5g.jpeg" /><figcaption>Figure 3: Architecture (image by me, made with GraphViz). Left: the Forward function. Right: ST-GCN Block.</figcaption></figure><ul><li>N: batch size.</li><li>C: original node features, i.e. triplet of (Coordinate-X/Coordinate-Y/Confidence-Level).</li><li>T: time steps.</li><li>V: number of nodes in Graph.</li><li>M: number of skeletons in a data record.</li></ul><h4>Code Explanation</h4><p>First and foremost, where is the formula in Figure 1 applied? Here is it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZxJrjNHXUCk0uhzvd5E97w.jpeg" /><figcaption>Figure 4: This is where GCN Formula is applied (file: st_gcn.py [7])</figcaption></figure><p>Matrices multiplication is not <em>commutative</em>, but surely <em>associative</em>. Originally, it was thought that one would first aggregate the features between the current nodes and its neighbors, then proceed to embedding the result to another latent space. But the code was implemented in a way that the embedding takes place first, then the aggregation.</p><p>After convolving Node spatially, it moved to convolving temporally <em>for each node separately</em>. We notice here the tuple kernel=(temporal_ker, 1), where temporal_ker was hardcoded with 9 (9 time steps).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*riMhvJvCiGufs1s2mc3gLw.jpeg" /><figcaption>Figure 5: Temporal Convolution for each node (file: st_gcn.py [7])</figcaption></figure><p>The main training loop is defined in file “recognition.py” [5], the content of which is typical. <em>Although not discussed in the paper</em>, the implementation made use of Residual Connection (aka. Skip Connection) <em>in each ST-GCN Block</em> to deal with Gradient Degradation. Because of different input-output channels, the Connection is indeed a mini-Neural Network (instead of Identity connection):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*45z4diuT4J4kb-AvHvW9_w.jpeg" /></figure><p>Within ST-GCN block, to prevent Gradient explosion and achieve a more stable convergence, BatchNorm is used before and after non-linear layers, as often advised [6]. The DropOut layer also helps in reducing overfitting [8]. But the code uses default setting for Dropout (meaning: probability of 0.5) while recommended value for Convolution layer is 0.1 or 0.2 [9].</p><p>Similarly to Convolution Layers for images, <em>10</em> ST-GCN Blocks are chained to hopefully generate high-level feature maps on skeleton sequences.</p><p>Another worthy point to mention is the Adjacency Matrix, constructed as a Tuple (spatial_ker, V, V). The neighbors of a specific node can be grouped into subsets. The easiest way is to just treat all of them equally (“Uni-labeling” as per paper), or the node connected to itself has distance 0 while its direct neighbors have distance of 1 (“Distance partitioning”). The number of such subsets is denoted as spatial_ker; each subset has its own Adjacency matrix to describe which nodes are considered neighbor, <em>given a specific node</em>. Each subset also has its own (o_channel, T, V). Thanks to einsum(), those datapoints are afterwards aggregated neatly.</p><h3>Final Remark</h3><p>I must admit that when first reading the paper [1], I got a certain perception about its main idea. For example, section “Spatial Temporal Modeling” page 4 [1], the authors extended the spatial modeling in temporal dimension by tweaking the Neighboring Function B(vₜᵢ) to include temporal neighbors (of the same node (joint)). I imagined we would have a dedicated function like this, but through the real implementation, it turned out to be just matrices multiplication. This once again reinforces my preference in focusing on papers that have code available. Otherwise, one would take the paper with a grain of salt. 😕</p><p>Hopefully, my effort in summarizing ST-GCN could help other people understand it quicker and more reliably. 💪 The spatial temporal convolution in this paper can be framed as generic multi-dimensional convolution with one dimension denoting nodes within a graph, from where the Graph Convolution formula (Figure 1) is applicable.</p><h3>References</h3><p>[1] Spatial Temporal Graph Convolutional Networks for Skeleton-Based Action Recognition, Yan et al., 2018 (<a href="https://arxiv.org/abs/1801.07455">https://arxiv.org/abs/1801.07455</a>)</p><p>[2] st-gcn (<a href="https://github.com/yysijie/st-gcn">https://github.com/yysijie/st-gcn</a>)</p><p>[3] Semi-Supervised Classification with Graph Convolutional Networks, Kipf et al., 2017, (<a href="https://arxiv.org/abs/1609.02907">https://arxiv.org/abs/1609.02907</a>)</p><p>[4] Graph convolutional neural networks (<a href="https://mbernste.github.io/posts/gcn/">https://mbernste.github.io/posts/gcn/</a>)</p><p>[5] ST-GCN training loop (<a href="https://github.com/yysijie/st-gcn/blob/master/processor/recognition.py#L78">https://github.com/yysijie/st-gcn/blob/master/processor/recognition.py#L78</a>)</p><p>[6] Where do I call the BatchNormalization function in Keras? (<a href="https://stackoverflow.com/questions/34716454/where-do-i-call-the-batchnormalization-function-in-keras">https://stackoverflow.com/questions/34716454/where-do-i-call-the-batchnormalization-function-in-keras</a>)</p><p>[7] st_gcn.py (<a href="https://github.com/yysijie/st-gcn/blob/master/net/st_gcn.py">https://github.com/yysijie/st-gcn/blob/master/net/st_gcn.py</a>)</p><p>[8] Dropout: A Simple Way to Prevent Neural Networks from Overfitting, Srivastava et al., 2014 (<a href="https://jmlr.org/papers/v15/srivastava14a.html">https://jmlr.org/papers/v15/srivastava14a.html</a>)</p><p>[9] Where should I place dropout layers in a neural network? (<a href="https://stats.stackexchange.com/questions/240305/where-should-i-place-dropout-layers-in-a-neural-network">https://stats.stackexchange.com/questions/240305/where-should-i-place-dropout-layers-in-a-neural-network</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf926c811330" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using GPU-enabled CoLab (free version) even when usage limit is already exceeded]]></title>
            <link>https://thachngoctran.medium.com/using-gpu-enabled-colab-free-version-even-when-usage-limit-is-already-exceeded-e4a5dd812284?source=rss-fe5661177636------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4a5dd812284</guid>
            <category><![CDATA[colab-notebook]]></category>
            <category><![CDATA[gpu-computing]]></category>
            <category><![CDATA[colab]]></category>
            <category><![CDATA[google-drive]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[TRAN Ngoc Thach]]></dc:creator>
            <pubDate>Sat, 18 May 2024 20:37:09 GMT</pubDate>
            <atom:updated>2024-05-22T11:32:30.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sDuEwONmMVTswxGRDq_NTQ.jpeg" /></figure><p><strong>Scenario</strong>: You have a GPU-required CoLab Notebook, given to you by someone, or created by you. Despite efficient utilization (i.e. only connecting when a piece of code needs to run, otherwise, disconnecting), you exceed the imposed usage limit, much sooner with the free version of CoLab. Now you must decide: either pay for the Pro version to keep things going on, or wait for sometime (days?) until the quota is available again.</p><h3>Workaround/Bypass</h3><p>I may have found this trick that allows you to bypass this restriction and continue working with the GPU-required CoLab Notebook in spite of the restriction, of course, <em>without paying or waiting</em>.</p><ol><li>Put the CoLab Notebook into a shared Google Drive folder.</li><li>The aforementioned folder is shared with Edit Permission to a few other Google/Gmail users, who are <em>preferably unrelated to the current user</em>.</li><li>When GPU computation quota runs out, the current user just <strong><em>saves</em></strong><em> and closes</em> the Notebook. One of the other users opens the Notebook separately elsewhere, and keeps up the work: the Notebook can be now run with GPU, using <em>the other user</em>’s GPU computation quota.</li><li>When this new user unfortutanely runs out of quota sooner or later, then another user repeats the cycle.</li><li>As you can guess, all those Google/Gmail users actually <em>belong to one real person</em>. 😀</li></ol><h3>Comments &amp; Caveats</h3><p>Google never reveals what they do behind the scene to detect abuse and keep users adhering to the imposed limit, as discussed <a href="https://stackoverflow.com/questions/61126851/how-can-i-use-gpu-on-google-colab-after-exceeding-usage-limit">here</a>. But if they make this process <em>too strictly</em>, they risk more complicated system designs as well as possible extensive user annoyance. At the end of day, would it be worth it for Google?</p><p>I believe advanced users are already in possess of a few Gmail accounts. For example, one for work, one for personal things. To make sure Google can’t detect the connection between those accounts, we : 1). avoid using one account as the Recovery email in the others; 2). Use Igcognito mode (I can’t stress this enough!); 3). Turn off and on again the Router so that it gets a new IP address. Google surely knows these users share the same Notebook, but is not sure if they are actually <em>one single real person</em>.</p><p>The main thing to keep in mind is that the Notebook should be stored in an <em>editable Google Drive folder</em> so that any users can save at any moment, and the others can later re-open and continue the work.</p><p>Last but not least, cross your fingers as Google may patch this hole at some point in the future, when they want to incentivize more users to opt for the Pro version. 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4a5dd812284" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading Delta Lake tables in Power BI]]></title>
            <link>https://thachngoctran.medium.com/reading-delta-lake-tables-in-power-bi-1bee1e64dcc6?source=rss-fe5661177636------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bee1e64dcc6</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[power-query]]></category>
            <category><![CDATA[data-lake]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[delta-lake]]></category>
            <dc:creator><![CDATA[TRAN Ngoc Thach]]></dc:creator>
            <pubDate>Tue, 01 Nov 2022 12:26:52 GMT</pubDate>
            <atom:updated>2022-11-01T12:26:52.856Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Connect Power BI to Delta Lake. Make it easy!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2N6oRa-x21KJ7BRs-vAggg.jpeg" /></figure><h3>Introduction</h3><p><a href="https://www.databricks.com/product/delta-lake-on-databricks">Delta Lake</a>, as the terminology <em>Lake</em> suggests, is designed to be a unified place for storing structured, semi-structured and unstructured data, as well as friendly to both streaming and batch operations. Under the hood, Delta Lake is empowered by <a href="https://spark.apache.org/">Apache Spark</a>, with additional support for <a href="https://en.wikipedia.org/wiki/ACID">ACID</a> transactions (aka. fully succeeds or fully aborts). Even more appealing, one can easily save a DataFrame as a Delta Lake table by simply indicating the saving format:</p><pre>a_spark_dataframe<br>  .write<br>  .format(&quot;<strong>delta</strong>&quot;)<br>  .mode(&quot;overwrite&quot;)<br>  .saveAsTable(&quot;test_table&quot;)</pre><p>After being saved, it can be made use of, e.g. spark.sql(&quot;SELECT COUNT(*) FROM test_table&quot;) right away, <em>assuming Hive support is enabled</em>. However, if you already establish Microsoft <a href="https://powerbi.microsoft.com/en-us/what-is-power-bi/">Power BI</a> as the platform for Business Intelligence, it is tempted to fetch the Delta Lake tables, whose data are stored <em>somewhere</em>, such as <a href="https://hadoop.apache.org/docs/r1.2.1/hdfs_design.html">HDFS</a> or <a href="https://azure.microsoft.com/en-us/products/storage/blobs/">Azure Blob Storage</a>, into Power BI and visualize the data, or even do some transformation beforehand with <a href="https://learn.microsoft.com/en-us/power-query/power-query-what-is-power-query">Power Query</a>, e.g. <a href="https://learn.microsoft.com/en-us/powerquery-m/table-selectrows">Table.SelectRows()</a> for filtering.</p><p>The writer is going to show <a href="https://delta.io/integrations/">two recommended ways</a> to load Delta Lake tables into Power BI Desktop, and pros/cons in each approach.</p><h3>From Delta Lake to Power BI</h3><h4>Method 1: via a pure Power Query function and another File Listing Connector</h4><p>Thanks to this <a href="https://github.com/delta-io/connectors/tree/master/powerbi">user guide</a>, we first import (<em>New Source</em> &gt; <em>Blank Query</em> &gt; <em>Advanced Editor</em>) the Power Query function <a href="https://github.com/delta-io/connectors/blob/master/powerbi/fn_ReadDeltaTable.pq">fn_ReadDeltaTable()</a> into Power BI, making it <em>re-usable </em>in other Power Query script of the same Power BI file. The function ends up in Queries panel as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*jH5-8n9Fy4NU_3A4R2x6ng.jpeg" /></figure><p>Do another import, but this time, we start using the aforementioned function. To simplify, let’s assume the Delta Lake table data are <em>stored in HDFS</em>:</p><pre>let<br>    test_table = fn_ReadDeltaTable(Hdfs.Files(&quot;[an_ip]:50070/test_table&quot;), [UseFileBuffer=true])<br>in<br>    test_table</pre><p>The <em>test_table</em> output is the desired Delta Lake table. Here come the pros and cons:</p><ul><li><strong>Pros</strong>: simple because the Power Query function fn_ReadDeltaTable() is lightweight. Relying on another File Listing Connector, e.g. Hdfs, here is a blessing: off-load the connection complexity to another 3rd party Connector.</li><li><strong>Cons</strong>: However, relying on another File Listing Connector also brings a hidden limitation: the data loading (before interpreting it as a Delta Lake table) depends on the capability of the 3rd-party Connector. For example, <a href="https://github.com/delta-io/connectors/issues/430#issuecomment-1241145668">there is no Power BI Connector to fetch data in AWS S3</a>!</li></ul><h4>Method 2: via the official Connector for Delta Lake</h4><p>There is actually such an <em>official</em> Connector. The reader can start leveraging this Connector directly through Power Query:</p><pre>let<br>    Source = DeltaSharing.Contents(&quot;[an_ip]:60000/delta-sharing&quot;),<br>    deltalake = Source{[Name=&quot;deltalake&quot;]}[Data],<br>    schema = deltalake{[Name=&quot;schema&quot;]}[Data],<br>    test_table = schema{[Name=&quot;test_table&quot;]}[Data]<br>in<br>    test_table</pre><p>Or they may opt for a step-by-step Wizard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*T4c0FkZxMfC9zuZyV-83BQ.jpeg" /></figure><p>Pros and cons:</p><ul><li><strong>Pros</strong>: official Power BI Connector, by DataBricks.</li><li><strong>Cons</strong>: This Connector is made possible, thanks to <a href="https://github.com/delta-io/delta-sharing">Delta Sharing</a> — an Open Protocol for Secure Data Sharing. The <a href="https://github.com/delta-io/delta-sharing#delta-sharing-reference-server">Delta Sharing Reference Server</a>, which is a reference implementation server for the Protocol, only supports <a href="https://github.com/delta-io/delta-sharing/issues/112#issuecomment-1024766411">AWS S3, Azure Blog Storage, Azure Data Lake Gen2, and Google Cloud Storage</a> (<em>not HDFS or some networked/shared disk</em>). The author thinks this is <em>by design</em> because the Server serves as an Authentication and Management point, but the clients, e.g. Power BI, will then need to contact the Storage Provider, e.g. S3, to <em>actually</em> fetch the data through <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/ShareObjectPreSignedURL.html">presigned URL</a>. Otherwise, the Server would become a bottle neck! Another limitation: in some encryption schemes, e.g. S3 with SSE-C, it is required that the http requests against presigned URLs, must include <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/ServerSideEncryptionCustomerKeys.html#ssec-and-presignedurl">additional http headers</a>, indicating the key and its hash. But the author found no way to specify such headers in the official Connector.</li></ul><h3>Conclusion</h3><p>We have learned two methods to load Delta Lake tables into Power BI. Depending on specific use-cases, we may prefer one way to another.</p><p>For example, if using HDFS, the 1st Connector is more convenient. If intending to share Delta Lake tables to a larger audience on the Internet, the data provider may opt for Delta Sharing protocol; therefore, we shall use the 2nd Connector.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bee1e64dcc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building custom Apache Spark]]></title>
            <link>https://thachngoctran.medium.com/building-custom-apache-spark-df1dd0fc6310?source=rss-fe5661177636------2</link>
            <guid isPermaLink="false">https://medium.com/p/df1dd0fc6310</guid>
            <category><![CDATA[distributed-computing]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[custom-build]]></category>
            <dc:creator><![CDATA[TRAN Ngoc Thach]]></dc:creator>
            <pubDate>Mon, 17 Oct 2022 21:20:20 GMT</pubDate>
            <atom:updated>2022-10-17T21:20:20.316Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FuFQiLBjujoTS2q81ditPw.jpeg" /></figure><h3>Introduction</h3><p>Typically, we want to <a href="https://spark.apache.org/downloads.html">download Apache Spark</a> pre-built for a specific version of Hadoop, in which Hadoop libraries are readily included for <a href="https://spark.apache.org/docs/latest/hadoop-provided.html">HDFS and YARN</a>. However, there are situations when this pre-built is less favored. For example:</p><ul><li>An Hadoop infrastructure has been already set up and well-maintained with all parts fit together. In that case, a <a href="https://spark.apache.org/docs/latest/hadoop-provided.html">Hadoop-free</a> Spark Build is a good choice, enabling Users to refer to and re-use the desired Hadoop libraries via Spark’s Environmental Variable SPARK_DIST_CLASSPATH.</li><li>A <em>minimum</em> Spark Build, in which irrelevant libraries, e.g. hadoop-aws, are excluded. Users then indicate what exact libraries are used in their Spark application, via e.g. — packages argument in PySpark shell. Spark will download the packages and their dependencies automatically. This approach maximizes Users’ freedom of library choice.</li><li>A <em>convenient</em> Spark Build, in which often-used libraries are included, relieving Users from manually indicating additional libraries. This approach also brings a hidden benefit: let Administrator manage the default libraries, e.g. security update, dependency consistency. It’s true that Spark takes precedence in loading its default libraries over User libraries, when looking for classes. (<em>note</em>: this behavior can be overridden by <a href="https://spark.apache.org/docs/latest/configuration.html">setting </a><a href="https://spark.apache.org/docs/latest/configuration.html">spark.driver.userClassPathFirst</a>. However, it’s an Experimental setting. Use at one’s own risk!)</li><li>In <a href="https://stackoverflow.com/questions/60484693/how-to-configure-spark-2-4-correctly-with-user-provided-hadoop">certain cases</a>, it is troublesome for Hadoop-free Spark Build to integrate some libraries, e.g. Hive. This issue can be overcome by building Spark from source code with the desired Hadoop version <em>and</em> a switch for Hive. (-Phive -Phive-thriftserver)</li></ul><p>The latter three cases involve building Spark from Source code. There can be many variations from combining different switches, but the author is going to show at least <em>one approach that works</em>, and the readers can go further from there.</p><h3>Steps</h3><p>In Terminal:</p><ol><li>Increase the memory of Maven.<br>+ export MAVEN_OPTS=”-Xss64m -Xmx2g -XX:ReservedCodeCacheSize=1g”</li><li>Ensure JAVA_HOME is pointed to a valid JDK 8 or 11, regardless of <a href="https://www.oracle.com/java/technologies/downloads/">Oracle</a> or <a href="https://adoptium.net/">Temurin</a>. Example:<br>+ export JAVA_HOME=/usr/lib/jvm/temurin-11-jdk-amd64</li><li>Download the Spark Source code, and extract it.<br>+ tar -xvzf spark-3.2.2.tgz</li><li><em>Just in case</em>, change the file mode recursively (assuming the OS is Ubuntu) to grant read-write-execute to anyone.<br>+ chmod -R gou+rwx spark-3.2.2</li><li>Move to the just extracted folder, and type:<br>+ ./dev/make-distribution.sh --name custom-spark --pip --tgz -Pyarn -Phive -Phive-thriftserver -Phadoop-cloud -Dhadoop.version=3.3.4 -e -DskipTests<br>Explanation: --name specifies the name of the final packaged Spark folder, e.g. spark-3.2.2-bin-custom-spark.tgz. -Phive -Phive-thriftserver indicates the inclusion of Hive functionality. -Phadoop-cloud integrates <a href="https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-aws">Hadoop AWS</a> libraries (not sure if other Cloud vendors are also supported). -e helps output more information in case of build errors.</li><li>We end up with spark-3.2.2-bin-custom-spark.tgz, which is similar in terms of structure, compared to <a href="https://spark.apache.org/downloads.html">other Spark Download options</a>. This Spark Build is ready to deploy.</li></ol><h3>Environment</h3><ul><li>Ubuntu 22.04 LTS (64 bit).</li><li>OpenJDK 11.0.16.1 Temurin (64 bit).</li><li>Target Spark version: v3.2.2.</li><li>Target Hadoop version: v3.3.4.</li></ul><h3>References</h3><ul><li><a href="https://spark.apache.org/docs/latest/building-spark.html">https://spark.apache.org/docs/latest/building-spark.html</a></li><li><a href="https://spark.apache.org/docs/latest/hadoop-provided.html">https://spark.apache.org/docs/latest/hadoop-provided.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df1dd0fc6310" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Tensorflow’s Object-Detection Validation a true Post-Process]]></title>
            <link>https://thachngoctran.medium.com/make-tensorflows-object-detection-validation-a-true-post-process-c45785f08d3a?source=rss-fe5661177636------2</link>
            <guid isPermaLink="false">https://medium.com/p/c45785f08d3a</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[colab]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[tensorflow2]]></category>
            <dc:creator><![CDATA[TRAN Ngoc Thach]]></dc:creator>
            <pubDate>Thu, 17 Feb 2022 00:55:12 GMT</pubDate>
            <atom:updated>2022-02-17T00:55:12.485Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aktsIec8Uq2_tQ1sEEd9Tw.png" /></figure><p>In Tensorflow 2, <a href="https://github.com/tensorflow/models/tree/master/research/object_detection">Object Detection API</a> separated Training and Validating into <a href="https://stackoverflow.com/questions/64510791/tf2-object-detection-api-model-main-tf2-py-validation-loss">two different processes</a>. Even more, they are supposed to run <em>simultaneously</em>, monitoring the <em>same directory</em> where Checkpoints are saved. This article will explain a trick enabling Users to run Validation as a <em>true</em> Post-process, which is, as far as I know, not available in the current implementation of Object Detection API.</p><p><strong>Table of Contents</strong></p><pre><a href="#a91c">1). By default, how is Training and Validation supposed to intertwine?</a><br><a href="#bf47">2). The Pros &amp; Cons of the aforementioned approach</a><br><a href="#c66e">3). Make Validation a true Post-process</a><br><a href="#0fb8">4). Verify</a><br><a href="#ee40">5). Conclusion</a></pre><h3>By default, how is Training and Validation supposed to intertwine?</h3><p>Assuming all things are well set up, from preparing data as <a href="https://www.tensorflow.org/tutorials/load_data/tfrecord">TFRecord</a>, to downloading the Git repo <a href="https://github.com/tensorflow/models">models</a>, to compiling the protos, to installing Tensorflow Object Detection API’s <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/packages/tf2/setup.py">setup.py</a>as well as configuring the pipeline.config, the Training proccess is then executed, using the command:</p><pre>python model_main_tf2.py \<br>  --pipeline_config_path=&quot;some_path/pipeline.config&quot; \<br>  --model_dir=&quot;some_path&quot; \<br>  --checkpoint_every_n=100 \<br>  --num_train_steps=1000 \<br>  --alsologtostderr</pre><p><em>At the same time</em>, the Validation is started, as followed:</p><pre>python model_main_tf2.py \<br>  --pipeline_config_path=&quot;some_path/pipeline.config&quot; \<br>  --model_dir=&quot;some_path&quot; \<br>  --<strong>checkpoint_dir=&quot;some_path&quot;</strong> \<br>  --eval_timeout=60</pre><p>Whenever the Training saves a Checkpoint file, e.g.ckpt-1(ckpt-1.data-00000-of-00001 and ckpt-1.index), the Validation detects, ingests the file, starts validating, and saves the result as e.g.events.out.tfevents.1645005144.6403b50c5b59.912.0.v2. These processes keep going on until the Training is complete, and the Validation is then timed-out (found no new Checkpoint).</p><h3>The Pros &amp; Cons of the aforementioned approach</h3><p>The reader may have a different resource set-up scheme for training and validating. For example, they may have one or two strong PCs with plenty of CPU/GPU. But in my case, <a href="https://colab.research.google.com/">Google Colab</a> is used. Unfortunately, CoLab’s Notebook executes cells one-after-another; in one cell, one command after another, e.g. !python model_main_tf2.py…. If running Validation after Training, the Validation will only consider the <strong>latest Checkpoint</strong>, as proven below:</p><pre># 1). module &quot;model_main_tf2.py&quot;, <a href="https://github.com/tensorflow/models/blob/e38e2e8eaeacb6fbaa8ec1449bfc5621e1b6671d/research/object_detection/model_main_tf2.py#L81">line 81</a>.<br>if FLAGS.checkpoint_dir: # if checkpoint_dir argument is used.<br>  model_lib_v2.eval_continuously(...</pre><pre># 2). module &quot;model_lib_v2.py&quot;, function eval_continuously(), <a href="https://github.com/tensorflow/models/blob/e38e2e8eaeacb6fbaa8ec1449bfc5621e1b6671d/research/object_detection/model_lib_v2.py#L1136">line 1136</a>:<br>for latest_checkpoint in tf.train.checkpoints_iterator(<br>  checkpoint_dir, timeout=timeout, min_interval_secs=wait_interval):</pre><pre># 3). module &quot;checkpoint_utils.py&quot;, function checkpoints_iterator(), <a href="https://github.com/tensorflow/tensorflow/blob/3f878cff5b698b82eea85db2b60d65a2e320850e/tensorflow/python/training/checkpoint_utils.py#L194">line 194</a>:<br>while True:<br>  new_checkpoint_path = wait_for_new_checkpoint(<br>    checkpoint_dir, checkpoint_path, timeout=timeout)</pre><pre># 4). same module, function wait_for_new_checkpoint(), <a href="https://github.com/tensorflow/tensorflow/blob/3f878cff5b698b82eea85db2b60d65a2e320850e/tensorflow/python/training/checkpoint_utils.py#L139">line 139</a>:<br>while True:<br>  checkpoint_path = <strong>checkpoint_management.latest_checkpoint(checkpoint_dir)</strong></pre><p>There may be a few tricks to get multiple cells running at the same time, such as <a href="https://stackoverflow.com/questions/21248345/is-there-a-way-to-run-multiple-cells-simultaneously-in-ipython-notebook">ipyparallel</a> (But I am not experienced on this technique, and not sure if it can work with CoLab at all).</p><p>To the best of my knowledge, the pros and cons of Training and Validation <em>running in parallel</em>):</p><ul><li><strong>Pros</strong>:<br>- No need to keep all Checkpoints (In my case, one Checkpoint costs 42.5 MB). Indeed, Training only maintains the <a href="https://github.com/tensorflow/models/blob/e38e2e8eaeacb6fbaa8ec1449bfc5621e1b6671d/research/object_detection/model_lib_v2.py#L451">last 7 Checkpoints</a>. This configuration is not changeable from outside. <br>- Combining with <a href="https://www.tensorflow.org/tensorboard">Tensorboard</a> in real-time, one can stop the Training early if e.g. loss is no longer substantially reduced.</li><li><strong>Cons</strong>:<br>- Resources must be shared between Training and Validation, which can slow down the Training. The Validation <em>could</em> also use GPU (Picture [1]).<br>- Validation process only takes into account the <strong>latest</strong> Checkpoint. In some cases, e.g. large Validation set and more granular checkpoint_every_n, the Validation may miss some Checkpoints, resulting in less fine-grained Visualization for Validation data.<br>- Complexity: In CoLab, it’s not straightforward to run multiple cells in parallel (i.e. one cell for Training, one cell for Validation).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*JdFViTTCm_G45sKu_CEY0A.jpeg" /><figcaption>Picture 1: GPU is used during Validation</figcaption></figure><p>Therefore, there may be a need for Validation process to be carried out <strong>after</strong> Training process. This would be particularly handy in case of using CoLab.</p><h3>Make Validation a true Post-process</h3><p>The code for Validation, specifically: ingesting a Checkpoint, restoring the model, validating it against Validation set, must be scattered in multiple places in the Git Repo <a href="https://github.com/tensorflow/models">models</a>. Assembling all of the pieces can be time-consuming as well as possibly introducing new subtle issues.</p><p>The safe and quick approach should be to maintain the current way of executing, i.e. calling model_main_tf2.py with checkpoint_dir argument, but modify <em>a few</em> places in the code, where, instead of continuously watching over the directory for a new Checkpoint, it would just enumerate over <em>all Checkpoints in the directory,</em> and process each of them <em>as if</em> each is the single latest Checkpoint. Through this way, the <em>correctness</em> of the entire Validation process is kept intact. Every artifact produced should be then well-formatted and feedable to, e.g. Tensorboard.</p><p><strong>First thing first</strong>, the Training only saves the last 7 Checkpoints:</p><pre># 1). module &quot;model_main_tf2.py&quot;, <a href="https://github.com/tensorflow/models/blob/e38e2e8eaeacb6fbaa8ec1449bfc5621e1b6671d/research/object_detection/model_main_tf2.py#L105">line 105</a>:<br>with strategy.scope():<br>  model_lib_v2.train_loop(<br>    pipeline_config_path=FLAGS.pipeline_config_path,<br>    model_dir=FLAGS.model_dir,<br>    train_steps=FLAGS.num_train_steps,<br>    use_tpu=FLAGS.use_tpu,<br>    checkpoint_every_n=FLAGS.checkpoint_every_n,<br>    record_summaries=FLAGS.record_summaries)</pre><pre># 2). module &quot;model_lib_v2.py&quot;, function train_loop(), <a href="https://github.com/tensorflow/models/blob/e38e2e8eaeacb6fbaa8ec1449bfc5621e1b6671d/research/object_detection/model_lib_v2.py#L443">line 443</a>:<br>def train_loop(<br>  pipeline_config_path,<br>  model_dir,<br>  config_override=None,<br>  train_steps=None,<br>  use_tpu=False,<br>  save_final_config=False,<br>  checkpoint_every_n=1000,<br>  <strong>checkpoint_max_to_keep=7,</strong><br>  record_summaries=True,<br>  performance_summary_exporter=None,<br>  num_steps_per_iteration=NUM_STEPS_PER_ITERATION,<br>  **kwargs):</pre><p>Unfortunately, this argument can’t be changed from outside. It’d be best to add checkpoint_max_to_keep=<em>some_big_number</em> to the calling of train_loop(), within module model_main_tf2.py (the module used for Training and Validation).</p><p><strong>Next</strong>, within module model_lib_v2.py, function eval_continuously(), <a href="https://github.com/tensorflow/models/blob/e38e2e8eaeacb6fbaa8ec1449bfc5621e1b6671d/research/object_detection/model_lib_v2.py#L1136">line 1136</a>:</p><pre>for latest_checkpoint in tf.train.checkpoints_iterator(<br>    checkpoint_dir, timeout=timeout, min_interval_secs=wait_interval):<br>  ...</pre><pre>ckpt.restore(latest_checkpoint).expect_partial()</pre><p>Considering variable latest_checkpoint, it is a string describing the full path to the <strong>latest</strong> Checkpoint file, e.g. absolute_path/ckpt-33. After identifying the path, it moves on to Validation, i.e. restoring the Model with the Checkpoint saved at the path, then start validating.</p><p>If we replace the use of tf.train.checkpoints_iterator() with some code that enumerates <strong>all</strong> the Checkpoints, and feed each into the body of the for-loop, everything should proceed as usual! The correctness would be maintained. Below is what I did: replace the iterator with the code in <strong>bold text</strong>. (beside, some additional libraries (regex, glob) and a utility function (natural_sort) are also needed)</p><pre>import regex as re<br>import glob</pre><pre>def natural_sort(l): <br>  convert = lambda text: int(text) if text.isdigit() else text.lower() <br>  alphanum_key = lambda key: [ convert(c) for c in re.split(&#39;([0-9]+)&#39;, key) ] <br>  return sorted(l, key = alphanum_key)</pre><pre>for latest_checkpoint in <strong>natural_sort(list(set(map(lambda n: n[:n.index(&quot;.&quot;)], glob.glob(f&quot;{checkpoint_dir}/ckpt-*.*&quot;)))))</strong>:</pre><p>Last but not least, all of the changes above should take place <strong>after</strong> the <a href="https://github.com/tensorflow/models">Github Repo models</a> is cloned, and <strong>before</strong> we do !cp object_detection/packages/tf2/setup.py . and !pip install ..</p><h3>Verify</h3><p>I think the argument checkpoint_every_n should be divisible by 100, which is <a href="https://github.com/tensorflow/models/blob/e38e2e8eaeacb6fbaa8ec1449bfc5621e1b6671d/research/object_detection/model_lib_v2.py#L43">NUM_STEPS_PER_ITERATION</a>. The reason why can be seen <a href="https://github.com/tensorflow/models/blob/e38e2e8eaeacb6fbaa8ec1449bfc5621e1b6671d/research/object_detection/model_lib_v2.py#L711">here</a>: after one iteration, Training tries to save a Checkpoint only if the <em>just</em> accumulated steps is larger than checkpoint_every_n. By making it divisible by 100, we can easily estimate how many Checkpoints will be generated, given a num_train_steps.</p><p>The Training now starts first. <em>After it is complete</em>, following is the Validation. All are in a sequential manner. At the end, within the checkpoint_dir, there will be eval and train folders, containing data for Visualization with Tensorboard:</p><pre>tensorboard --logdir=<em>checkpoint_dir</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MPjX-o1w2lf5XCQIDmX2Dw.jpeg" /><figcaption>Picture 2: Visualization for Training &amp; Validation</figcaption></figure><h3>Conclusion</h3><p>We have learned how to make Validation a true Post-process for Tensorflow’s Object-Detection API. This trick is at least helpful in my case: a simple set-up within CoLab, for both Training and Validation, runs sequentially.</p><p><em>P.s: If this article is useful, please consider being a follower of my Medium.</em> 😋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c45785f08d3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>