<?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 Aaron Zellner on Medium]]></title>
        <description><![CDATA[Stories by Aaron Zellner on Medium]]></description>
        <link>https://medium.com/@a2zdeveloper?source=rss-46ade27052f6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*lAFq16nWWYpveBIC.jpg</url>
            <title>Stories by Aaron Zellner on Medium</title>
            <link>https://medium.com/@a2zdeveloper?source=rss-46ade27052f6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:37:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@a2zdeveloper/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[No Shot, One Shot, Few Shot More]]></title>
            <link>https://medium.com/@a2zdeveloper/no-shot-one-shot-few-shot-more-8c882e6c913e?source=rss-46ade27052f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c882e6c913e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Aaron Zellner]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 01:26:40 GMT</pubDate>
            <atom:updated>2026-11-30T15:24:17.939Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7MLkBeftehtpZxmMNyMN0A.png" /></figure><p>The purpose of this article is to provide an introductory tutorial on three fundamental prompt engineering techniques: zero-shot, one-shot, and few-shot prompting. We will begin by introducing a scenario to demonstrate how each technique is used. This will be followed by an experiment using the BANKING77 dataset to establish a performance baseline for understanding how smaller LLMs perform when utilizing these prompt engineering techniques. The experiment will demonstrate how different example selection techniques can influence the models&#39; classifications performance.</p><p>Experiment Objective: As previously mentioned, this experiment will use the BANKING77 dataset. This dataset contains a total of 13,083 banking queries with 10,003 training samples and 3,080 test samples distributed across 77 unique labels. The goal is to evaluate how three LLMs perform when classifying the test samples using zero-shot, one-shot, and few-shot prompt engineering techniques. For more information about the BANKING77 dataset refer to the reference below.</p><p>Prompt engineering involves designing and refining prompts to guide LLM’s responses and improve its performance on specific business tasks. While LLMs possess extensive general knowledge, they often lack the specialized domain expertise and business context that employees develop through experience. Effective prompt engineering helps bridge this gap by incorporating domain-specific knowledge, instruction and context into the model’s decision-making process. Below each prompt engineering technique will be defined and deep definition will follow. I used a different use case for defining these techniques to provide a different perspective when reading these.</p><p>Here is a definition for each prompt engineering technique:</p><ul><li><strong>Zero-Shot Prompting</strong>: the model classifies the prompt based on the provided instruction</li><li><strong>One-Shot Prompting</strong>: the model classifies the prompt based on the provided instruction and one example</li><li><strong>Few-Shot Prompting</strong>: the model classifies the prompt based on the provided instruction and N examples (N = number of examples</li></ul><h3><strong>Ollama</strong></h3><p>This section will provide a practical example using Ollama, Ollama is a library that runs LLMs locally. It can implement a variety of different models that can be trained and applied to different types of applications.</p><p>For this project an Ollama API was created to handle each prompt engineering technique.</p><pre>@app.get(&quot;/zero_shot_prompt/ollama&quot;)<br>def zero_shot_prompt_ollama(prompt: str, model_name: str = &quot;llama3.2&quot;):<br>    client = OllamaClient(model_name=model_name)<br>    response = client.generate(prompt=prompt, max_tokens=100, temp=0, top_p=0.9)<br>    return {&quot;response&quot;: response}<br><br>@app.post(&quot;/one_shot_prompt/ollama&quot;)<br>def one_shot_prompt_ollama(request: PromptOneShot, model_name: str = &quot;llama3.2&quot;):<br>    prompt = create_one_shot_prompt(request)<br>    client = OllamaClient(model_name=model_name)<br>    response = client.generate(prompt=prompt, max_tokens=100, temp=0, top_p=0.9)<br>    return {&quot;response&quot;: response}<br><br>@app.post(&quot;/few_shot_prompt/ollama&quot;)<br>def few_shot_prompt_ollama(request: PromptFewShot, model_name: str = &quot;llama3.2&quot;):<br>    client = OllamaClient(model_name=model_name)<br>    prompt = create_few_shot_prompt(request.instruction, request.examples, request.prompt)<br>    response = client.generate(prompt=prompt, max_tokens=100, temp=0, top_p=0.9)<br>    return {&quot;response&quot;: response}</pre><p>This api will pass each prompt (with examples) to the ollama client and it will generate a classification response. Since one-shot and few-shot prompts take examples, the request is set to their respective objects:</p><pre>class OneShotExample(BaseModel):<br>    example_text: str<br>    example_output: str<br><br><br>class PromptOneShot(BaseModel):<br>    instruction: str<br>    example: OneShotExample<br>    prompt: str<br><br>class PromptFewShot(BaseModel):<br>    instruction: str<br>    examples: list[OneShotExample]<br>    prompt: str</pre><p>For one-shot and few-shot prompting each sample will be represented like the following:</p><pre>{<br>      &quot;id&quot;: &quot;train-00001&quot;,<br>      &quot;input&quot;: &quot;I am still waiting on my card?&quot;,<br>      &quot;expected_output&quot;: &quot;card_arrival&quot;<br>    }</pre><p>Every sample will have an id, input and expected output. These will be extracted and then passed to the model.</p><p>The embedding methodology can be found in the embedding folder in github. For this project, it will use a simple model from hugging face:</p><pre>sentence-transformers/all-MiniLM-L6-v2</pre><p>This model will be used to embed both the prompts and the examples. I will not go into how embeddings are created because it is out of the scope of this article.</p><p>For one-shot and few-shot prompting, this study will evaluate two different approaches to example selection: random sampling and similarity based selection. Earlier it was mentioned there is 10,003 training prompts. These prompts will serve as pool of labeled examples for classifying the testing prompts.</p><p>The two approaches are defined as follows:</p><ul><li>Random Sampling: Examples are randomly selected from the training data without considering the semantic relationship with the prompt</li><li>Similarity Based Selection: Examples will be selected based on the cosine similarity between the prompt and the examples embedding vectors. Embedding vectors will be created for each using a transformer model from hugging face.</li></ul><p>The purpose of this comparison is to see how sample selection affects the models inference performance.</p><p>The three models that will be used are listed below</p><ul><li>Llama 3.2</li><li>Gemma 3</li><li>Mistrial</li></ul><p>These models were chosen because the test is being ran locally and they seemed most suitable for this experiment.</p><h3>Results</h3><h4>Accuracy and F1 Scores</h4><p>The models accuracy and F1 score for each technique can be found below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dIrcajT7EWzAusLRW9T2w.png" /><figcaption>Zero-Shot Comparisons</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtZBSyPDmtPmnBhXYjH-VQ.png" /><figcaption>Zero-Shot F1 Comparisons</figcaption></figure><p>Zero-Shot showed low perfomances for all three models on both F1 and accuracy metrics. The Gemma model performed the best with an accuracy of 58.4% and an F1 score of 56.7%. The Llama model performed the worst with a 41.3% accuracy and a 38% F1 score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8-c7VBf9ib71DpHo6DL0DA.png" /><figcaption>One Shot Top K vs Random Sampling</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXX8omNGluQ8658J9MMuUw.png" /><figcaption>One Shot Top K vs Random Sampling (F1 Score)</figcaption></figure><p>The one-shot prompting showed a clear edge to the top example enhancing the performance of the model vs a random sample. All three models performed better using the top example with an average % increase of 27%. The Mistrial model performed the best with an 86.6% accuracy. The random sampling only provides a slight increase in performance vs zero-prompting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bh39mOXnDzCaiK3U655EVw.png" /><figcaption>Few-Shot Top K vs Random Sampling (Accuracy</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWvfa-Md6LNTV7OIgtYwbA.png" /><figcaption>Few-Shot Top K vs Random Sampling (F1 Score)</figcaption></figure><p>Few-Shot top-k (top 3) sampling performed significantly better than the random samples. Between random sampling and similarity based examples, there was an average 35.12% accuracy increase. Additionally, few-shot prompting similarity based metric performed better than the one-shot prompting similarity based metric. The same pattern can be found with F1 score as well. All three models using the similarity based approached outperformed random sampling by 36%.</p><p>For Github please visit:</p><p><a href="https://github.com/a2zcoder1022/RAG_Pipeline/tree/main">a2zcoder1022/RAG_Pipeline</a></p><h3><strong>Conclusion</strong></h3><p>The findings from this baseline experiment suggest that few-shot and one-shot prompting with similarity based examples are effective for classification tasks involving large number of distinct labels. Zero-shot prompting could have struggled because of there being so many labels, it was harder to distiguish based on just the instruction and the prompt. With that said, that does not mean these methodologies will always outperform zero-shot prompting and the other prompting techniques using random sampling. Just for this specific business problem they proved the ones to be used.</p><h3>References</h3><p>Casanueva, I., Temcinas, T., Gerz, D., Henderson, M., &amp; Vulic, I. (2020). Efficient intent detection with dual sentence encoders. <em>Proceedings of the 2nd Workshop on NLP for Conversational AI, ACL 2020</em>. <a href="https://arxiv.org/abs/2003.04807?utm_source=chatgpt.com">https://arxiv.org/abs/2003.04807</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c882e6c913e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Low Rank Adapation (LoRA) From Scratch with Python]]></title>
            <link>https://medium.com/data-and-beyond/low-rank-adapation-lora-from-scratch-with-python-part-1-ee04c8093370?source=rss-46ade27052f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee04c8093370</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Aaron Zellner]]></dc:creator>
            <pubDate>Fri, 11 Sep 2026 17:21:22 GMT</pubDate>
            <atom:updated>2026-09-16T17:57:03.091Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TLttLffN0jLAmhcbo51UGQ.png" /></figure><h3>Low Rank Adaptation (LoRA) From Scratch with Python</h3><h3><strong>Introduction</strong></h3><p>This article will explore a well know finetuning technique known as Low-Rank Adaptation( LoRA). It will provide a thorough breakdown with math included. Parameters are the LLMs brains of the operation, they are stored in large matrices which are collected using extensive training on vast amounts of data. LLM development can be broken down into two stages: pre-training and fine-tuning.</p><p>Pre-training is a long learning process using large amounts of data and high powered processing. It is similar to going to a library and reading every book within a few hours. Fine-tuning then takes that acquired knowledge and adapts it to a specific task, such as question answering. Only then is the model ready to try out for Jeopardy!</p><p>Fine-tuning originally focused on updating all the weights within the LLM to achieve an objective. This can potentially be computationally equivalent to the pre-training process which requires extreme amounts of computational power. In addition, the cost of training large language models is quite expensive. In a technical review of ChatGPT 3 by lambda , it was estimated that ChatGPT costed over 4.6 million to train[2] In practice, this means that retraining all the models weights is impractical, and this is where LoRA comes in.</p><p>LoRA is part of a broader concept known as Parameter-Efficient Fine-Tuning, or PEFT. Instead of retraining all of a model’s weights, LoRA creates a smaller number of additional weights that are trained for the specific task at hand. These new weights are then combined with the model’s existing weights.</p><p>The way this article is going to be broken down is first we are going to dive into the mathematical core of LoRA, then we will build out LoRA using python and testing it on a Question and Answering dataset.. In addition, the LoRA code is going to be configured for sequence classification only. The LoRA library from peft takes in a parameter called task_type (SEQ_CLS, TOKEN_CLS, etc), I plan to adjust my LoRA library to handle these types of tasks for future work but for now it will only deal with classification. Three LoRA models will be created based on the Bert based models three attention weights (key, value, query), this will then be compared to the original Bert base model.</p><h4>The Math Behind LoRA</h4><p>Math brings out the best of every AI model and understanding the inner workings allows for us to appreciate these models. Thankfully, LoRA does not incorporate too much math into its algorithm.</p><p>Everything mathematically stays the same with LoRA in terms of the model learning. LoRA introduces two matrices and two parameters to add a little flavor to it. There are two matrices called A and B, the matrices are smaller than the original weight matrix that the model is trained on but the product of both of them will equal the size of the original matrix . One important thing to note, the original model weights are frozen and are not updated in this training process. The formula for LoRA can be defined below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/89/1*lcFgkn8pX8xBfmUZhSRKfQ.png" /></figure><p>The A and B weights are defined below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/79/0*TbsUYj8f0M44vqZE" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/87/0*sBhkHPk2Or2UeDUa" /></figure><p>r represents the rank hyper parameter that determines the dimensions of matrices A and B.</p><p>What does rank actually mean in respect to training? Rank is a linear algebra concept that represents the number of independent directions there are within rows and columns of a matrix. For LoRA, r represents the amount of new information the model will learn in respect to its downstream task. The larger r is , the more learning the model will consume. Remember, r ≤ min(d_in, d_out), so if you make it too big it will eventually have almost the same number of parameters of the initial model which we do not want.</p><p><strong>What are the advantages and disadvantages of choosing r?</strong></p><p>Choosing r involves balancing computational efficiency with the model’s ability to learn information. A smaller r introduces a smaller number of trainable parameters, allowing the model to be more computationally efficient, but it can potentially reduce the amount of information the model learns. If r is set to 0, there is no LoRA update, meaning the model cannot learn through the LoRA parameters. In the LoRA paper, it did a comparitive analysis using different ranks (1, 2, 4, 8, 16, 64) and attention layers (query, key, value, and output) to see how the LoRA model performed on the WikiSql and MultiNLI dataset. Interestingly , there was no rank that demonstrated a significant advantage over the others except if only a single attention weight matrix was adjusted, it performed better with r set to 64[1], You can see the table in [1] section 7.1.</p><p><strong>Lets Begin building withPython</strong></p><p>For this exercise we are going to use the movie review dataset from Standford and try to classify the review of movies, if they are good or bad. To know more about the dataset, feel free to go check it out here: <a href="https://ai.stanford.edu/~amaas/data/sentiment/">Large Movie Review Dataset (IMDB) — Andrew Maas</a> . For the model, we are going to use the standard bert-base-uncased model from the transformers library. To begin, here are the initial imports you will need to move forward into this tutorial. The github repository can be found here:</p><p><a href="https://github.com/a2zcoder1022/LoraFromScratch">a2zcoder1022/LoraFromScratch: The purpose of this repository is to provide what coding LoRA from scratch looks like.</a></p><pre>import torch<br>from datasets import load_dataset<br>from transformers import AutoModelForSequenceClassification, AutoTokenizer, TrainingArguments, Trainer<br><br>model_name = &quot;bert-base-uncased&quot;<br>dataset = load_dataset(&quot;stanfordnlp/imdb&quot;)<br>train_data = dataset[&quot;train&quot;].shuffle(seed=42)<br>test_data = dataset[&quot;test&quot;].shuffle(seed=42)<br><br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br><br>def tokenize(batch):<br>    return tokenizer(batch[&quot;text&quot;], padding=True, truncation=True, max_length=256)<br><br>train_data = train_data.map(tokenize, batched=True)<br>test_data = test_data.map(tokenize, batched=True)</pre><p>After initializing this, we will review the LoRA python class. The purpose of the LoRA class is to transform the existing model and update its architecture to incorporate the new adapter weights.</p><pre>import torch.nn as nn<br>import torch<br>import torch.nn.functional as F<br>from LoraModel import LinearLayer<br><br>class Lora(nn.Module):<br>    def __init__(self, model, r: int, alpha: int, dropout: float, target_weights: list):<br>        super().__init__()<br>        self.target_weight_modules = []<br>        self.model = model<br>        self.r = r<br>        self.alpha = alpha<br>        self.dropout = dropout<br>        self.target_weights = target_weights<br>        self.freeze_model_weights()<br>        self.review_weight_tree()<br><br><br>    def review_weight_tree(self):<br>         if len(self.target_weights) == 0:<br>             raise ValueError(&quot;Target weights must be a list of one or more names&quot;)<br>         <br>         for name, model in self.model.named_modules():<br>             abbrev_name = name.split(&quot;.&quot;)[-1]<br>             if isinstance(model, nn.Linear) and abbrev_name in self.target_weights:<br>                 self.target_weight_modules.append((name, model))<br><br><br>    def validate_rank(self, original_weights):<br>        if self.r &lt;= 0 or self.r &gt; min(original_weights.in_features, original_weights.out_features):<br>            raise ValueError(&quot;Rank is not valid&quot;)<br><br><br>    def freeze_model_weights(self):<br>        for name, param in self.model.named_parameters():<br>                param.requires_grad = False<br><br><br>    def update_module(self):<br>        for name, module in self.target_weight_modules:<br>            original_weights = self.model.get_submodule(name)<br>            self.validate_rank(original_weights)<br>            lora_module = LinearLayer(original_weights, self.r, self.alpha, self.dropout)<br>            self.model.set_submodule(name, lora_module)<br>        return self.model</pre><p>The first part is the class variables.</p><pre>self.target_weight_modules = []<br>self.model = model<br>self.r = r<br>self.alpha = alpha<br>self.dropout = dropout<br>self.target_weights = target_weights<br>self.freeze_model_weights()<br>self.review_weight_tree()</pre><p>→ target_weight_modules is a list that will collect all the model modules associated with the designated target weights (key, value, etc). Make sure to look at all the names of the modules for the model prior to passing it into the LoRA program. The weight names can differ across models. Here is how you can do that for hugging face transformer models:</p><pre>for name, module in base_model.named_modules():<br>   if (isinstance(module, torch.nn.Linear)):<br>         print(f&quot;Module name: {name}&quot;)</pre><p>This will provide an output like this:</p><pre>Module name: bert.encoder.layer.0.attention.self.query<br>Module name: bert.encoder.layer.0.attention.self.key<br>Module name: bert.encoder.layer.0.attention.self.value<br>Module name: bert.encoder.layer.0.attention.output.dense<br>Module name: bert.encoder.layer.0.intermediate.dense<br>Module name: bert.encoder.layer.0.output.dense<br>Module name: bert.encoder.layer.1.attention.self.query<br>Module name: bert.encoder.layer.1.attention.self.key</pre><p>validate_ranks makes sure the rank is in line with the models dimensions. Therefore rank cannot be less than or equal to zero nor can it be greater the the models lowest dimension size.</p><pre>def validate_rank(self, original_weights):<br>        if self.r &lt;= 0 or self.r &gt; min(original_weights.in_features, original_weights.out_features):<br>            raise ValueError(&quot;Rank is not valid&quot;)</pre><ul><li>review_weight_tree grabs all the module names associated with the weights listed in the target weights list.</li></ul><pre>def review_weight_tree(self):<br>         if len(self.target_weights) == 0:<br>             raise ValueError(&quot;There are no target weights&quot;)<br>         <br>         for name, model in self.model.named_modules():<br>             if isinstance(model, nn.Linear) and name in self.target_weights:<br>                 self.target_weight_modules.append((name, model))</pre><ul><li>freeze_model_weights freezes all the existing parameters in the model</li></ul><pre>def freeze_model_weights(self):<br>        for name, param in self.model.named_parameters():<br>                param.requires_grad = False</pre><p>The update_module function will replace the existing model weights with the revised LoRA weights.</p><pre>  def update_module(self):<br>        for name, module in self.target_weight_modules:<br>            original_weights = self.model.get_submodule(name)<br>            lora_module = LinearLayer(original_weights, self.r, self.alpha, self.dropout)<br>            self.model.set_submodule(name, lora_module)<br>        return self.model</pre><p>In the update_module function, it updates each target weight with a new LinearLayer which performs the LoRA operation for each of the target weights specificed.</p><pre>import torch.nn as nn<br>import torch<br><br>import torch.nn.functional as F<br><br>class LinearLayer(nn.Module):<br>    def __init__(self, original_layer, rank, alpha, dropout=0):<br>        super().__init__()<br>        self.original_layer = original_layer<br>        self.rank = rank<br>        self.alpha = alpha<br>        self.dropout = nn.Dropout(dropout)<br><br>        self.A = nn.Parameter(torch.randn(self.rank, self.original_layer.in_features), requires_grad=True)<br>        self.B = nn.Parameter(torch.zeros(self.original_layer.out_features, self.rank), requires_grad=True)<br><br><br>    def forward(self, x):<br>        output = self.original_layer(x)<br><br>        a_output = F.linear(self.dropout(x), self.A)<br>        b_output = F.linear(a_output, self.B)<br><br>        return output + (self.alpha / self.rank) * b_output</pre><p>The trainable matrices A and B are initialized as parameters, with A assigned as a random gaussian distribution and B initialized to a zero matrix, following the initialization strategy described in the LoRA paper [1].</p><h3>Results</h3><p>For the LoRA experiement, I used a rank of 64. 64 was chosen because [1] proved that a higher rank was slighly more accurate in some instances. Additionally, I experimented with all 3 attention heads . There was a total number of 3 runs with 2 epochs each. Each run added one additional attention layer, it started with one attention head then the last experimental run was with all 3 attention layers. This was then compared against the original model, the F1 Scores can be found below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*MF7rQzdoZ-yR5B8G29r8Wg.png" /><figcaption>F1 Score and Parameter Counts For Each Model</figcaption></figure><p>From the image above, the original Bert base model performed slightly better than all three lora models with adjusted attention weights. That being said, all the models performed with an f1 score greater than 90%. The LoRA model with three adjustment (KVQ) attention heads performed the best of the three LoRA models with an f1 score of 93%. This is a 1% decrease from the original Bert base model and the KVQ model parameters made up only 3% of the the original Bert model. This strongly aligns with the idea that LoRA is an effective fine tuning methodology that can help larger models train more efficiently on downstream tasks and give comparable results to a fully trained model.</p><p><strong>Final Remarks</strong></p><p>Thank you for reading my article, if you have any questions or concerns feel free to comment. I am always open to constructive criticism. I look to continue to build on top of this LoRA concept and expand it further than just a sequence classification use case.</p><h3><strong>References</strong></h3><p>[1] Hu, E. J., Shen, Y., Wallis, P., Allen-Zhu, Z., Li, Y., Wang, S., Wang, L., &amp; Chen, W. (2021). <em>LoRA: Low-rank adaptation of large language models</em>. arXiv. <a href="https://arxiv.org/abs/2106.09685">https://arxiv.org/abs/2106.09685</a></p><p>[2] Lambda. (2023, June 20). <em>OpenAI’s GPT-3 language model: A technical overview</em>. <a href="https://lambda.ai/blog/demystifying-gpt-3">https://lambda.ai/blog/demystifying-gpt-3</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee04c8093370" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-and-beyond/low-rank-adapation-lora-from-scratch-with-python-part-1-ee04c8093370">Low Rank Adapation (LoRA) From Scratch with Python</a> was originally published in <a href="https://medium.com/data-and-beyond">Data And Beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graph Embeddings]]></title>
            <link>https://medium.com/data-and-beyond/graph-embeddings-98749d110010?source=rss-46ade27052f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/98749d110010</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[graph-embedding]]></category>
            <dc:creator><![CDATA[Aaron Zellner]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 01:03:03 GMT</pubDate>
            <atom:updated>2026-09-08T12:12:07.150Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What is a Graph?</strong></h3><p>Graphs provide a unique way of displaying relationships between entities. An entity can be people on a social media platform, research papers, or even IP addresses on a network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*wVXS8K50nfK2gdy2jhmtKw.png" /><figcaption>Graph Example</figcaption></figure><p>Entities are represented by nodes, and these nodes have relationships with other nodes. This relationship is denoted by an edge which is a line connecting one node to the other. If we take a look at the graph above there is 7 nodes and 6 edges. Node A has an edge shared with nodes F, B, C and Node B has an edge shared with E and A.</p><p>In graph theory there is first order proximity and second order proximity. First order proximity are all the current nodes direct neighbors (shared edge) and second order proximity are the neighbors of the nodes neighbors. For C its first order neighbors would be D, A and G and second order neighbors would be F and B. This will not be mentioned throughout this tutorial, it was just to provide additional graph definitions that might be relevant to your train of thought.</p><h3><strong>What is an Embedding?</strong></h3><p>An embedding is the product of taking a sparse and large piece of information and condensing it to a smaller and meaningful representation. It is commonly used in the field of natural language processing (NLP) and a foundational component to the modern day LLMs (ChatGPT, Claude, etc).</p><p>There are many algorithms for creating embeddings, for graph embeddings a common algorithm used is based on an NLP model called Word2Vec. The Word2Vec algorithm creates embeddings on the bases of co-occurrent relationships between words. This is based on the distribution hypothesis where words that appear in similar context can have similar meaning. The same principle can be applied to graph embeddings as well: nodes that appear near each other can have similar meaning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lKDSgPQd-lVmAQVOEHVX3A.png" /><figcaption>Table 1: Embeddings Example</figcaption></figure><p>To give a general example of what an embedding looks like, table 1 provides two words and a three-dimensional vector for each. For the purpose of trying to simplify the embedding concept, the embeddings were made to be smaller than usual. In most research embeddings are larger with embedding sizes going up by 64 (64, 128, 256, etc). Deciding on the size depends on a variety of factors such as the business problem, data size, etc. The two embeddings appear to be close in value per dimension, if we were to take the similarity between the two they would have a high similarity (how the similarity is calculated will be discussed further along this tutorial).</p><h3><strong>Lets Combine Graph with Embedding</strong></h3><p>Now that we know what a graph and an embedding is, lets combine the two. Remember the purpose of an embedding is to provide a meaningful representation of something sparse and large. Graphs can be a perfect example of this because graphs can grow exponentially with data. There are four type of embeddings: node embeddings, edge embeddings, subgraph embeddings and graph embeddings. Deciding on which embedding is based on the business problem at hand. Node embeddings are useful for PubMed paper topic prediction. Where each node was a paper and the goal was to predict the topic of the paper based on the nodes features and the surrounding nodes features. Edge embeddings can be used to predict whether two people on a social media website are friends or not. Subgraph and Graph embeddings can apply to anomaly detection across ip addresses on a network.</p><h3><strong>DeepWalk</strong></h3><p>Deep Walk creates node embeddings by applying a random walk method to create the node sequences and then feeds the sequences into a Word2Vec model that will then create the embeddings.[3]</p><p><strong>Random Walk</strong></p><p>Random walk is a simple algorithm, it is used to create the representation of the nodes to feed into the model. It randomly selects a node on the graph and then from that node it randomly chooses one of its neighbors. This keeps going until a walk length is met. A walk length is a parameter that determines the length of the walks that will be passed into the word2vec model. The number of walks is another parameter that is implemented that gives the number of random walks that will occur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*wVXS8K50nfK2gdy2jhmtKw.png" /><figcaption>Graph Example</figcaption></figure><p>Lets take a look at the original graph and do a random walk. Lets say we have a walk length of 4 and the first node randomly assigned is A. Then after A it goes to C, then D then back to C. The result is sequence is [A, C, D, C]. After creating N walks each of the sequences is converted to an N x M (number of unique nodes) matrix. For our example above there are a total of seven distinct nodes. Each vector in the matrix is going to be a length of seven. For example: A, C, D, C will be as follows:</p><p>[[1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0]]</p><p>One important point to note, if you are familiar with one hot encoding it is understandable that over time the larger the graph gets the more expensive this operation can be. After building out this dataset a word2vec model is then used to convert the one hot encodings into embedding. For the purpose of focusing on graph embeddings this article will give a brief description of what a word2vec model is.</p><p>A word2vec model is a model used frequently in the field of natural language processing and focuses on the idea of creating word embeddings based on the co-occurrence of words. Words that appear frequently together can have similar context. The same principle can be applied to graph nodes, nodes that appear in similar context have similar meaning.</p><p><strong>How is the model applied to graph embeddings?</strong></p><p>Initially, all the random walk sequences will be collected and these will be passed through the word2vec model. The intial step would be to generate a hidden layer with a size (n x m) matrix. The n is the number of nodes in total within the graph and m is the dimension size of the hidden layer. This hidden layer will represent the embeddings. There is a total of 7 nodes so the lenght of the matrix will be of size 7. In order to pick a good dimension size for M, I would refer you to go to research papers below. For our example and to provide a understand we are only going to do a embedding dimension of 2. Is this practical? absolutely not. But for the sake of understanding, we are going to use 2. Lets get our randomly intialized embeddings for the nodes:</p><pre>Node A: [0.30471707975443135, -1.0399841062404955]<br>Node B: [0.7504511958064572, 0.9405647163912139]<br>Node C: [-1.9510351886538364, -1.302179506862318]<br>Node D: [0.12784040316728537, -0.3162425923435822]<br>Node E: [-0.016801157504288795, -0.85304392757358]<br>Node F: [0.8793979748628286, 0.7777919354289483]<br>Node G: [0.06603069756121605, 1.1272412069680329]<br></pre><p>Each node is provided with its own embedding, these embeddings will be updated throughout training.</p><p>How will these embedding be updated?</p><p>Returning to the Word2Vec model, it offers two training approaches: <strong>Skip‑Gram</strong> and <strong>Continuous Bag of Words (CBOW)</strong>. Skip‑Gram predicts the surrounding context words (based on a chosen window size) from a single target word, while CBOW does the opposite by predicting the target word from its surrounding context. I will give a brief description of how the skip gram model works. There is some math to it, but that is out of the scope of this tutorial.</p><p>The context window defines how many words before and after the target word the model considers. For example, with a window size of 2 and a sequence length of 5, the target word can only look two positions ahead and two positions behind. At the start of the sequence, the first target word has no previous words available, so its context only includes the next two words.</p><p>For this experiment, we’ll use the Skip‑Gram approach. Skip‑Gram training consists of two main steps: the forward pass and backpropagation. In the forward pass, the target node is fed into a shallow neural network with a single hidden layer, producing a 1×N softmax distribution over the entire node graph. Each value in this vector represents the probability that a given node is the correct context node. This process is repeated for every context node in the window. Using the cross‑entropy loss for each prediction, the model updates the weights associated with the target node. Over time, these updates reduce the cross entropy, and nodes that frequently appear together in sequences develop embeddings that move closer to one another.</p><p><strong>Results</strong></p><p>Simple note: The embeddings you seen above are not the same ones used for the results. Those above were an example of showing what the inputs will look like.</p><p>For this example, we will take two nodes: A and B and identify which nodes are the most similar to them. After running the word2vec model we take the embeddings of all the nodes and apply cosine similarity which shows how similar two nodes are to one another. For node A, the top 3 most similar nodes can be found below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRyZWIhw72ffWFmKFksMkw.png" /></figure><p>If you refer back to the graph above, it makes sense that F and B have the highest similarity score to A because they both appear closest to it in the graph. It is interesting that E has a higher similarity score than C but this is because of randomess of the random walk algorithm. There were more sequences that were randomly generated with E and A than there were with C and A. Now lets look at node B:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6a2EPB93lPdsaFnaoxDSgA.png" /></figure><p>Node B’s most related nodes are E and A which structurally aligns with the graph because node E and A are both direct neighbors to B.</p><h3><strong>Conclusion</strong></h3><p>Overall, the purpose of the introduction was to provide a simple explanation on how graph embeddings work. My goal for this tutorial was to be broad and expand not just to technical folks, but to non technical as well. I hope you enjoyed this read and all feedback is appreciated :) .</p><h3>References</h3><p>[1] Cai, H., Zheng, V. W., &amp; Chang, K. C.-C. (2018). <em>A comprehensive survey of graph embedding: Problems, techniques and applications</em>. <em>arXiv</em>. <a href="https://arxiv.org/abs/1709.07604">https://arxiv.org/abs/1709.07604</a></p><p>[2] Velickovic, P., Cucurull, G., Casanova, A., Romero, A., Lio, P., &amp; Bengio, Y. (2018). <em>Graph Attention Networks</em>. In <em>Proceedings of the International Conference on Learning Representations (ICLR)</em>. arXiv:1710.10903.</p><p>[3] Perozzi, B., Al‑Rfou, R., &amp; Skiena, S. (2014). <em>DeepWalk: Online learning of social representations</em>. arXiv:1403.6652.</p><p>[4] Kipf, T. N., &amp; Welling, M. (2017). <em>Semi-supervised classification with graph convolutional networks</em>. arXiv:1609.02907. <a href="https://arxiv.org/abs/1609.02907">https://arxiv.org/abs/1609.02907</a></p><p>[5] Bruna, J., Zaremba, W., Szlam, A., &amp; LeCun, Y. (2014). <em>Spectral networks and deep locally connected networks on graphs</em>. arXiv:1312.6203. <a href="https://arxiv.org/abs/1312.6203">https://arxiv.org/abs/1312.6203</a></p><p>[6] Kipf, T. N., &amp; Welling, M. (2017). <em>Semi-supervised classification with graph convolutional networks</em>. arXiv:1609.02907. <a href="https://arxiv.org/abs/1609.02907">https://arxiv.org/abs/1609.02907</a></p><p>[7] Liang, A. (2025). A graph attention-based recommendation framework for sparse user-item interactions. <em>Journal of Computer Science and Software Applications</em>, <em>5</em>(4).</p><p>[8] Liu, Y., Yang, S., Xu, Y., Miao, C., Wu, M., &amp; Zhang, J. (2023). Contextualized graph attention network for recommendation with item knowledge graph. <em>IEEE Transactions on Knowledge and Data Engineering, 35</em>(1), 181–195. <a href="https://doi.org/10.1109/TKDE.2021.3082948">https://doi.org/10.1109/TKDE.2021.3082948</a></p><p>[9] Wang, X., He, X., Cao, Y., Liu, M., &amp; Chua, T.-S. (2019, August). <em>KGAT: Knowledge Graph Attention Network for Recommendation</em>. In <em>Proceedings of the 25th ACM SIGKDD International Conference on Knowledge Discovery &amp; Data Mining</em> (pp. 950–958). ACM. <a href="https://doi.org/10.1145/3292500.3330989">https://doi.org/10.1145/3292500.3330989</a></p><p>[10] Tao, Z., Wei, Y., Wang, X., He, X., Huang, X., &amp; Chua, T.-S. (2020). <em>MGAT: Multimodal Graph Attention Network for Recommendation</em>. <em>Information Processing &amp; Management, 57</em>(5), Article 102277. <a href="https://doi.org/10.1016/j.ipm.2020.102277">https://doi.org/10.1016/j.ipm.2020.102277</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98749d110010" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-and-beyond/graph-embeddings-98749d110010">Graph Embeddings</a> was originally published in <a href="https://medium.com/data-and-beyond">Data And Beyond</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chi-Square Feature Selection Deep Dive]]></title>
            <link>https://medium.com/@a2zdeveloper/chi-square-feature-selection-deep-dive-18167d4c408c?source=rss-46ade27052f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/18167d4c408c</guid>
            <dc:creator><![CDATA[Aaron Zellner]]></dc:creator>
            <pubDate>Mon, 07 Oct 2024 11:26:06 GMT</pubDate>
            <atom:updated>2024-10-15T13:02:13.911Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>Feature engineering is crucial for uncovering relationships among various variables in a dataset. It simplifies the detection of ambiguities and redundancies that may not be immediately obvious. The Chi-Square test, a widely utilized method, aids in discovering correlations between categorical features. It assesses the independence of two variables by contrasting the expected and observed values. This document will offer a concise explanation of the Chi-Square test, followed by an illustrative example.</p><p><strong>Hypothesis Testing</strong></p><p>The null hypothesis for the chi square test can be defined below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*7Ds9QWg-e4hv8bkAraPh6w.png" /></figure><p>For this tutorial I am using a well-known bank marketing dataset used to determine whether customers will commit to a term deposit based on multiple variables (age, marital status, occupation, etc).</p><p>For this walk through, I am going to identify the relationship between marital status and whether it is dependent or independent from determining whether the individual will commit to a term deposit. Now, let’s lay out the steps to solve this problem using the <strong>Chi-Square</strong> test.</p><p>I. Identify the observed values for each Marital Status</p><p>II. Identify the Expected values for each Marital Status</p><p>III. Calculate the Chi Square statistic</p><p>IV. Calculate the p value using the Chi Square Probability density function</p><p><strong>Observed vs Expected Values</strong></p><p>To perform a chi-square test, it’s important to distinguish between observed and expected values. The observed values represent the actual count of instances for each feature’s category in relation to the target labels. For example, consider the feature “Marital Status,” which has three categories: Divorced, Married, and Single. To determine the observed values for each category, we construct a contingency table, which shows the frequency of each marital status across the different target label values. An example of such a table is provided in Table 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*kaczJQJDsi4aPblw8kCaZQ.png" /></figure><p>Now that we have our observed values we must identify the expected values. Expected values are the values that are expected to be seen if the null hypothesis is true. To calculate the expected values, we use the formula below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*5t4RbznzQz-VDpd1j7Pnkw.png" /></figure><p>To get the expected values matrix we take the product of each row and column and divide it by the overall dataset total. Here is a brief walk through:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*4Ciy-fJ6jK9jhFXc3eiikQ.png" /></figure><p>The calculations will produce the expected value matrix, as presented in Table 2. For example, the expected value for someone who is divorced and does not subscribe is 680, while the expected value for someone who is married and subscribes is 3,009.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*tq9kt8xtc67AwuN8ALIWcQ.png" /></figure><p><strong>Chi Square Test</strong></p><p>Now that we have the expected values and the observed values we can calculate perform the chi square analysis. The chi square analysis can be defined by the following formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/107/1*tZRYONXhV86I3xmToXD9nA.png" /></figure><p>Using this formula, you will obtain the chi statistic which is 110. In addition, you will need to get the degrees of freedom to calculate the p-value. The p value will tell whether we reject the null hypothesis. If p &lt;= 0.05 reject the null hypothesis; else the null hypothesis is true. The degrees of freedom can be calculated as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*XY9a-ARK7j8UxCe-Oi7gdw.png" /></figure><p>In our case, the degrees of freedom are 2. Using both the degrees of freedom and the chi-square statistic, we can apply the chi-square probability density function (pdf) to calculate the p-value. The p-value indicates the likelihood that the null hypothesis is true. If the p-value is greater than 0.05, we fail to reject the null hypothesis, meaning there is no significant relationship. However, if the p-value is less than or equal to 0.05, we reject the null hypothesis.</p><p>For this tutorial, we will not delve deeply into the chi-square pdf, but using it, we calculated a p-value of 1.6 * 10, which is extremely small and less than 0.05. Therefore, we reject the null hypothesis and conclude that there is a significant relationship between marital status and the likelihood of committing to a term deposit. The graph showing the p-value and chi-square statistic is displayed in Figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*8DvnQmx5wlnFFj94jiqd5Q.png" /></figure><p>The graph illustrates the significance of the p-value. The more skewed the graph is to the right, the stronger the evidence against the null hypothesis, leading to its rejection.</p><p>For comparison, we want to now understand how it would look like if the two variables were independent. Interestingly, all the categorical variables in the dataset have an extremely small p value with the deposit variable. Look at Table 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*263H1jn_3KmgPCzPsVa2RA.png" /></figure><p>Table 3 shows all the p values for the categorical columns to be very small in relation to the label column deposit. The deposit column has a dependent relationship with each of the categorical variables. Now since that is the case, lets investigate the relationships between the categorical columns to see if there are any have an independent relationship. During the analysis we found that default and marital had a p-value of .1149 this is greater than 0.05 therefore these two variables will prove the null hypothesis to be true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*0qqciJNaHgJyeYiR6xJpKg.png" /></figure><p>Both Figure 1 and Figure 2 show right-skewed distributions. The p-value in Figure 1 is significantly smaller, essentially zero, highlighting the visual difference between the plots in terms of statistical significance. In contrast, the p-value in Figure 2 is 0.11, indicating an 11% chance that marital status and default are independent, supporting the null hypothesis.</p><p>The Chi-Square test helps identify important relationships between categorical variables in your dataset. It’s a valuable metric for detecting correlations with your target variable that can help make decisions for feature selection. This test is straightforward, both mathematically and in terms of implementation, making it easy to apply.</p><p>Feel free to go to this UCI Machine Learning link to obtain the dataset. <a href="https://archive.ics.uci.edu/dataset/222/bank+marketing">Bank Marketing — UCI Machine Learning Repository</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18167d4c408c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>