<?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 Samrawit Asfaw on Medium]]></title>
        <description><![CDATA[Stories by Samrawit Asfaw on Medium]]></description>
        <link>https://medium.com/@samrawitasfaw8?source=rss-60bcb03b762e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*J6dOKfAjeX_xFhxog_V3Kg.jpeg</url>
            <title>Stories by Samrawit Asfaw on Medium</title>
            <link>https://medium.com/@samrawitasfaw8?source=rss-60bcb03b762e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:55:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samrawitasfaw8/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[What Is This RAG Everyone Is Talking About? ]]></title>
            <link>https://medium.com/@samrawitasfaw8/what-is-this-rag-everyone-is-talking-about-b8165d5a715d?source=rss-60bcb03b762e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8165d5a715d</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[intro-to-rag]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[what-is-rag]]></category>
            <category><![CDATA[rag-evaluation]]></category>
            <dc:creator><![CDATA[Samrawit Asfaw]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 17:22:39 GMT</pubDate>
            <atom:updated>2026-09-10T17:22:39.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*gDy858DMsHnK_H-I" /></figure><p>As part of our daily life, we use LLMs, like ChatGPT, but if you want to get a summary or some information from a book, if you copy paste the whole book, now it is full context.</p><p>Okay, another thing is, let’s say you want to have a chatbot that works as customer service, you have to train a language model or fine-tune it to have knowledge about your company but that is pretty costly.</p><p>Retrieval-Augmented Generation (RAG) fixes this. Instead of hoping the model memorized the right information during training or fine-tuning with extra cost, you fetch the relevant documents first and hand them to the model as context. The model generates an answer grounded in your actual data.</p><p>There is three stages of rag</p><p>1, Indexing : take the document and split it in to small pieces and convert it to vector embedding ( you can read my blog in <a href="https://medium.com/@samrawitasfaw8/why-and-how-embeddings-come-a38c106fbb37">embedding</a> if you are new to this concept ) , and every embedding is stored along with it’s text.</p><p>2, Retrieval : when we ask a question , the question got converted to a vector embedding and then using similarity search through indexed db for similar vector embedded chunk.</p><p>3, Generation : the retrieved chunk and the question is sent to LLM and using the information the llm generate organized answer.</p><h3>Building the RAG</h3><p>To understand how these three stages work together, let’s build a simple RAG system using pdf.</p><p><strong>1. Document ingestion</strong></p><p>The first step is extracting the data from pdf.</p><p>The PDF I am using is a collection of image texts. I could not extract the text directly, so I extracted the text using OCR (Optical Character Recognition), which is used to get readable text from an image.</p><pre>PDF_PATH = &quot;/kaggle/input/datasets/samriasfaw/art-of-programming/Donald-Knuth---The-Art-of-Computer-Programming-Vol-1-Fundamental-Algorithms.pdf&quot;<br><br>doc = pymupdf.open(PDF_PATH)<br><br>pages = []<br><br>for page_number in range(len(doc)):<br>    page = doc[page_number]<br><br>    pix = page.get_pixmap(<br>        matrix=pymupdf.Matrix(2, 2)<br>    )<br>    image = Image.open(<br>        io.BytesIO(pix.tobytes(&quot;png&quot;))<br>    )<br><br>   text = pytesseract.image_to_string(image)<br><br>   if text.strip(): pages.append({ &quot;page&quot;: page_number + 1, &quot;text&quot;: text })</pre><p><strong>2. Chunking</strong></p><p>We split the extracted text into smaller pieces. Look here, we might lose the full context if the next chunk is a continuation of the information left from the first, so we use overlap.</p><pre>words = text.split()<br><br>chunks = []<br><br>start = 0<br><br>overlap = 20<br><br>chunk_size = 50<br><br>while start &lt; len(words):<br>        end = start + chunk_size<br><br>        chunk = &quot; &quot;.join(words[start:end])<br>        chunks.append(chunk)<br><br>        start += chunk_size - overlap</pre><p>Look, the numbers we use for chunk size and overlap depend on the data we are using, and they impact our RAG performance a lot.</p><p>If the chunk is big, each retrieved chunk might have a lot of irrelevant information. If the chunk is small, the LLM won’t have enough context.</p><p>If the overlap is small, information might get lost at the chunk boundary. If the overlap is big, it increases the embeddings we store, which makes retrieving less efficient.</p><p><strong>3. Generate embeddings</strong></p><p>Now let’s convert the chunk to a vector representation using an embedding model.</p><pre>embedding_model = SentenceTransformer(<br>    &quot;sentence-transformers/all-MiniLM-L6-v2&quot;<br>)<br><br>embeddings = embedding_model.encode(<br>    texts,<br>    show_progress_bar=True,<br>    convert_to_numpy=True<br>)</pre><p><strong>4. Store them in a vector database</strong></p><p>We can now store these embeddings in a vector database. The choice you make here, which vector DB to use, highly depends on the application you are building and your requirements.</p><p>I used FAISS because it is an efficient and simple library to demonstrate.</p><pre>dimension = embeddings.shape[1]<br><br>index = faiss.IndexFlatL2(dimension)<br><br>index.add(embeddings.astype(&quot;float32&quot;))</pre><p><strong>5. Retrieve relevant chunks</strong></p><p>Now, when a user asks a question, we first convert the question into an embedding using the same embedding model and get a chunk that has a closer vector distance to the question.</p><pre>query_embedding = embedding_model.encode(<br>        [query],<br>        convert_to_numpy=True<br>    )<br><br>distances, indices = index.search(<br>        query_embedding.astype(&quot;float32&quot;),<br>        top_k<br> )<br><br>results = []<br><br>for distance, idx in zip(distances[0], indices[0]):<br>        results.append({<br>            &quot;text&quot;: chunks[idx][&quot;text&quot;],<br>            &quot;page&quot;: chunks[idx][&quot;page&quot;],<br>            &quot;distance&quot;: float(distance)<br>        })</pre><p><strong>6. Generate the answer</strong></p><p>Finally, we send the user’s question with the retrieved context to the LLM.</p><pre> prompt = f&quot;&quot;&quot;<br>Answer the question using only the provided context.<br><br>If the answer cannot be found in the context, say:<br>&quot;I could not find the answer in the document.&quot;<br><br>Context:<br>{context}<br><br>Question:<br>{query}<br><br>Answer:<br>&quot;&quot;&quot;<br><br>context = &quot;\n\n&quot;.join(<br>        [<br>            f&quot;[Page {result[&#39;page&#39;]}]\n{result[&#39;text&#39;]}&quot;<br>            for result in results<br>        ]<br>    )<br><br>// pass the prompt to any model</pre><h3>RAG Evaluations</h3><p>As mentioned RAG has two parts, retriever and the generator. Evaluating is just checking if retriever is finding the right chunk and how well our generator utilized the retrieved context to write answer.</p><p>Generally , the metric of RAG evaluation :</p><ul><li>Correctness : we measure if final answer is correct</li><li>Latency : we measure response time</li><li>Hallucination Rate : if the facts are not true according to the document</li><li>Context utilization : if the model used the retrieved data</li></ul><h3>At the end …</h3><p>The interesting part is, basic RAG is not enough for real-world data.</p><p>Real-world data is much more complicated. For instance, the relevant information might be across a lot of chunks. For production, we use different chunking strategies to make the RAG reliable and accurate.</p><p>So this is just an introduction to RAG , I hope you found this helpful.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8165d5a715d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why and How Embeddings come?]]></title>
            <link>https://medium.com/@samrawitasfaw8/why-and-how-embeddings-come-a38c106fbb37?source=rss-60bcb03b762e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a38c106fbb37</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[embedding]]></category>
            <dc:creator><![CDATA[Samrawit Asfaw]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 00:36:23 GMT</pubDate>
            <atom:updated>2025-12-31T12:32:09.365Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HaE5OYF3_eDcV1OG.jpg" /></figure><p>Think of the last time you searched for something online. Even if you typed something unclear, the search engine still figured it out. How does it do that? That’s where embeddings come in.</p><p>In this blog, we’ll explore foundational concept of embeddings<br>Let’s dive in</p><p><strong>Table of content</strong></p><ol><li>Introduction</li><li>Vectors</li><li>What is Embedding</li><li>Similarity Measures</li><li>How Embeddings Are Learned</li><li>Embedding vs Tokenization</li></ol><h3><strong>Introduction</strong></h3><p>In Natural Language Processing (NLP), embeddings form the foundation of many applications; for instance, they are widely used in search engines, virtual assistants, and recommendation systems.</p><h3><strong>Vectors</strong></h3><p>A vector is basically an arrow in space, and it’s typically described by a list of numbers.</p><p><em>ν</em>= (x1, x2, x3, ……….., xn)</p><p>n is the dimension of the vector</p><p>Two key components of vector are magnitude and direction.</p><p>The magnitude of a vector is length of the arrow and, it is calculated by a mathematical formula known as the Euclidean norm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*uHrCNQD37S-2DLUm-Kleew.png" /></figure><p>The direction is arrow’s orientation in space.</p><p>For two dimensional vectors , we can get direction using</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*zXhAy0wf71yenvxcoH_v1g.png" /></figure><p>In embeddings, we care more about direction, why?, we will see it soon.</p><h3>What is an Embedding?</h3><p>An <em>embedding</em> is a specific type of vector that maps data into a numerical space.</p><p><em>Embedding </em>is a technique used in machine learning to represent objects like text, images, audio, or graphs as continuous numerical vectors in a multi-dimensional space.</p><p>For example, the word ‘cat’ might be represented using vector [0.8, 0.1]</p><p>Why do we really need to represent data in vector form? 🙂 Well machines can only learn from numbers, and vectors are how we turn meaning into numbers.</p><p>We now know that we can represent language as vectors but there are two options we can take with this. We can either use dense or sparse vectors.</p><p>Let’s consider the make-up of both dense vs sparse vectors.</p><p>Dense vectors have very few elements inside them that are zero. Meaning these vectors are populated with <em>dense</em> numerical information:</p><p>v = [ 0.4, 1, 3, 2, 0.1, 5 ……]</p><p>On the other hand, sparse vectors have many elements inside them that are zero. Meaning they are <em>sparse</em> with numerical information.</p><p>v = [ 1, 2, 0, 1, 0, 0,0…...]</p><h3>Similarity Measures</h3><p>Similarity measures quantify how closely related words or entities are in meaning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bV6TfGZYhCQOYGYB.png" /></figure><p>Notice how words with similar meaning (semantically similar) are clustered together. In this case, we have the names of animals and also name of fruits clustered together.</p><p>So, the orientation in space determines similarity. Now you can see why the direction of a vector is important 😁.</p><p>One of the most common similarity measures is cosine similarity. This measures the cosine of the angle between two vectors, u and v. The smaller the angle, the more similar the vectors are, and the larger the angle, the less similar they become.</p><p>To visualize:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*zQT9mEgOqsgT9aBTNBSY7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*IAuvjVpJDtu0885jkvU0Sg.png" /></figure><p>Computing the cosine similarity will return a value in the range [ -1, 1], where a value of 1 implies perfectly aligned vectors, 0 indicates no similarity and -1 indicates maximum dissimilarity.</p><h3>How Embeddings Are Actually Learned</h3><p>Let’s start from the earliest method and see how text representation evolved.</p><p><strong>N-gram </strong>were the first representations to be used for search engines, and it is simply a small chunk of text of length n.</p><p>For example, let’s consider a sentence ‘ I like AI’</p><p>Unigram: if n = 1, ‘I’, ‘like’, ‘AI’</p><p>Bigram: if n = 2, ‘I like’, ‘like AI’</p><p>To see how it works let’s take two sentences:</p><ol><li>I like banana</li><li>I like apple</li></ol><p>The choice of n determines whether we focus on word-level, phrase-level, or more general embeddings.</p><p>We take bi-gram and then assign numbers to them:</p><p>0 — ‘I like’</p><p>1 — ‘like banana’</p><p>2 — ‘like apple’</p><p>Then the computer creates a list with one number per n-gram. In our case, since we have three n-grams, the list has length three: [0,0,0]</p><p>Basically, it counts each occurrence in the sentences and updates each value in the list.</p><p>For the first sentence:</p><ul><li>‘I like ‘— appear ones</li><li>‘like banana’ — appear ones</li><li>‘like apple’ — it doesn&#39;t appear</li></ul><p>so, it became [ 1, 1, 0]</p><p>In the same way for sentences two [1, 0, 1]</p><p>In n-gram, sentences are considered similar if they share the same values in the same positions. In this case, similarity is about how many n-grams the texts have in common.</p><p>Notice that n-grams are represented as sparse vectors. For grams that don’t appear, there are many zeros in the vector.</p><p>The problem with n-grams is common phrases dominate similarity, and rare informative phrases get ignored. To address this, researchers began weighting n-grams by importance, which led to the development of TF-IDF.</p><p><strong>Term Frequency–Inverse Document Frequency (TF-IDF) </strong>is a method to evaluate how important a word is to a document in relation to a larger collection of documents.</p><p>TF-IDF combines two components :</p><p>TF — measures how often words appear in a document</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z83lSEIjNtnxnb8Pws3AAA.png" /></figure><p>IDF — reduces the weight of the words that appear in many documents</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*4rqzuiPc_wJWAOQ5EU9_GA.png" /></figure><p>N: total number of documents</p><p>df : number of documents containing t</p><p>TF-IDF is basically the multiplication of two.</p><p>For example, we have three documents</p><p>0. I like banana</p><ol><li>I like apple</li><li>Banana is sweat</li></ol><p>For the first sentence</p><ul><li>TF(“I like”) = 1 / 2 = 0.5</li><li>TF(“like banana”) = 1 / 2 = 0.5</li></ul><p><strong>“i like”</strong> appears in Doc 1 and Doc 2 (DF=2)</p><ul><li>IDF = ln(3 / 2) = 0.405</li></ul><p><strong>“like banana”</strong> appears <strong>only</strong> in Doc 1 (DF=1)</p><ul><li>IDF = ln(3 / 1) = 1.098</li></ul><p>TF-IDF(‘I like’) = 0.5 * 0.405 = 0.202</p><p>TF-IDF(‘like banana’) = 0.5 * 1.098= 0.549</p><p>Notice how common words have lower weight than the other. TF-IDF improved similarity computation by reducing the weight of generic phrases.</p><p>The drawback of TF-IDF is that it does not learn meaning; it treats <em>girl</em> and <em>female</em> as completely different words. So, the next big jump after TF-IDF was dense word embedding, the first was LSA</p><p><strong>Latent Semantic Analysis </strong>tries to understand the context and relationship between words by turning text into a big table of word counts and then using math to shrink that table down keeping only the most important parts.</p><p>Instead of tracking every detail in the n-gram matrix, we compress everything into a smaller set of meaningful patterns using Singular Value Decomposition (SVD) to uncover hidden patterns.</p><p>In the earlier example, both sentences 1 and 2 share the phrase “I like,” so <em>banana</em> and <em>apple</em> appear in similar contexts. Because of this, LSA places them close together in the reduced semantic space.</p><p>Generally, LSA understands meaning only because words with similar meanings are used in similar contexts.</p><p>As we saw, in the early days, text was embedded using simple occurrence-based methods: n-grams, TF-IDF, and even LSA all relied on counting how often words appeared together, but they didn’t truly <em>learn</em> meaning. Then<strong> </strong>Word2Vec changed everything.</p><p><strong>Word2Vec</strong></p><p>Word2Vec uses Gradient Descent to learn word embeddings. It trains neural network to position words in a vector space using prediction by using their neighbor words</p><p>There are two primary ways to train Word2Vec:</p><ol><li><strong>CBOW (Continuous Bag of Words): </strong>predict a word based on the context.</li></ol><p>First, assign numbers to each word. Then, remove the target word and, using the weights, predict that word. It looks at the prediction, and if it is not correct, it backpropagates the error and updates the weights.</p><p>This process repeats for all words in the sentence. Over time, the weights adjust so that words that appear in similar contexts get similar vector embedding such as <em>banana</em> and <em>apple</em> in the context “I like.”</p><p><strong>2. Skip-gram: </strong>predicts context words using a word.</p><p>The problem with Word2Vec is that the word “Bank” gets one vector. It’s a messy average of “Money Bank” and “River Bank.”</p><p>After Word2Vec, models kept getting better at capturing meaning, and the next huge leap came with <strong>BERT and Transformer models</strong>.</p><p>Sentence transformers models can understand every word in a sentence in relation to every other word. This meant embeddings were no longer just about a single word’s meaning, but its meaning in context.<strong><br></strong> So “apple” in <em>“I ate an apple”</em> and “Apple released a new iPhone” get different vectors automatically.</p><h3>Embedding vs Tokenization</h3><p><strong>Tokenization </strong>is the process of taking the input text and partitioning it into small, secure, manageable units called tokens. These units can be words, phrases, sub-words, punctuation marks, or characters</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*YDVs0DwqlcdjgxitG74h-Q.png" /></figure><p><strong>Tokenization </strong>breaks text into individual tokens, while <strong>Embeddings </strong>convert those tokens into numerical vectors that capture semantics and relationships.</p><h3>Conclusion</h3><p>In this blog post, we explored the concepts of embeddings and how they transform raw text into meaningful numerical vectors that machines can understand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a38c106fbb37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Neural Network from Scratch (using NumPy Only)]]></title>
            <link>https://medium.com/@samrawitasfaw8/building-neural-network-from-scratch-using-numpy-only-e825fcaac454?source=rss-60bcb03b762e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e825fcaac454</guid>
            <category><![CDATA[mathmatics]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Samrawit Asfaw]]></dc:creator>
            <pubDate>Tue, 18 Nov 2025 00:26:03 GMT</pubDate>
            <atom:updated>2025-12-20T05:42:49.245Z</atom:updated>
            <content:encoded><![CDATA[<p>First let’s understand the structure of a Neural Network</p><p>A<strong> neural network </strong>is a machine learning model that makes decisions in a manner similar to the human brain, by using processes that mimic the way biological neurons work together to identify phenomena, weigh options and arrive at conclusions.</p><p>Every neural network consists of layers of nodes, or artificial neurons an input layer, one or more hidden layers, and an output layer. Each node connects to others and has its own associated weight and threshold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*idGSEELVQRHlUsOLe0ZcUA.png" /></figure><p>So simply here is how it works:</p><p>For example, let’s say there is a girl called hana and we want to predict whether she go out today or not. We have the following pieces of information that influence her decision: day of the week, whether she went out yesterday, and the weather.</p><p>[Day_of_week , Went_out_yesterday ,Weather] are input features (X’s).</p><p>Each feature contributes differently to her decision about going out. Weather might have a stronger influence than the other. In another word each inputs have weight.</p><p>What we’re trying to predict, whether Hana goes out or not, is the output (y).</p><p>Hana can be an introvert, so even when everything seems perfect for going out, she might choose to stay at home. We call that <strong>bias</strong>. It is an extra value added before deciding the output (to make that decision we use an <strong>activation function</strong>).</p><p><strong>Activation function</strong> takes the total score (from the weighted inputs + bias) and converts it into a clear output using probability function.</p><p>When we train the model, the model learns the correct values (weight and bias), but how?</p><p><strong>First </strong>each input feature is given a small random weight (w1, w2…) and bias (b)<strong> </strong>is also initialized randomly. The weighted sum will be calculated like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*f3jtagN3LT4aeXhIsQGI5g.png" /><figcaption>Building Neural Network from Scratch (using NumPy Only)</figcaption></figure><p>Then using activation function the model makes a prediction: a=σ(z)</p><p>Where:</p><ul><li>xi = input feature,</li><li>wi = weight,</li><li>b = bias,</li><li>z = weighted sum,</li><li>σ = activation function,</li><li>a = output,</li></ul><p>It then checks how wrong it was. This is done by comparing the network’s prediction a to the true label Y and measuring the error using a loss function.</p><p>Then, it adjusts both the weights and bias slightly to in the direction that reduces the error, using optimization techniques like gradient descent.</p><p>Simply, gradient descent is a way to find a point where the function has its lowest value, or highest, but in our case, it helps us find an optimal position of the weight where the loss is lowest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*NU64q2SSx39IRodpVO8MOg.png" /></figure><p>We now have little understanding of how it works … Let’s dive into the maths and the code.</p><h3>Dataset</h3><p>Let’s use the Iris flower dataset, which is already cleaned, so we don’t need to spend time on preprocessing.</p><p>The structure of the dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*pT1WWCox2VAFwL1q11gwGA.png" /></figure><p>I have converted the species labels to numbers and normalized the data.</p><h3>Feed Forward</h3><p>In feed forward, we compute weighted sum and then apply activation function.</p><pre>def feed_forward(inputs , weight , bias , activation ):<br>    inputs = np.array(inputs)<br>    output = np.dot( inputs  ,  weight)+ bias<br>    if activation == &#39;Sigmoid&#39;:<br>        prediction = sigmoid(output)<br>    elif activation == &#39;Softmax&#39;:<br>        prediction = softmax(output)<br>    else:<br>        print(activation , &#39;Not found&#39;)<br>    return prediction</pre><p>Before that we need to initialize the weights:</p><pre>def initiate_random_weight(inputs_num , neurons_num):<br>    weights = np.random.randn(inputs_num , neurons_num)<br>    return weights<br>def initiate_bias(neurons_num):<br>    return (np.zeros(neurons_num)) </pre><pre>weight_1 = initiate_random_weight(X_train.shape[1] , 3)<br>bias_1 = initiate_bias(3)<br>weight_2 = initiate_random_weight(weight_1.shape[1] , 3)<br>bias_2 = initiate_bias(3)</pre><p><strong>Activation function</strong></p><p>Sigmoid Function helps convert numerical data into probabilities output between 0 and 1.</p><p>σ = 1 / 1 + e^-x</p><ul><li>To visualizes:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*GjqBnhb8jBQhkhHp.png" /></figure><p>On the other hand, SoftMax converts outputs into a probability distribution over multiple classes.</p><h3>Loss Function</h3><p>There are many types of loss functions each suited for different tasks. Here are some common methods for each regression and classification:</p><p><strong>Mean Squared Error (MSE) </strong>Loss calculates the average of the squared differences between the predicted values and the actual values.</p><p>It can be calculated like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/0*kuTBRiDfrFLky9ar" /></figure><ul><li>yi is the ith observed value.</li><li>ŷi is the corresponding predicted value.</li><li>n = the number of observations.</li></ul><p>It is sensitive to outliers because the errors are squared and big errors become<strong> </strong><em>much</em> bigger which can affect the loss.</p><p><strong>Mean Absolute Error (MAE) </strong>Loss calculates the average of the absolute differences between the predicted values and the actual values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*vSqPIpZp1braCGmJyzvCxw.png" /></figure><p>It is not differentiable at zero which can cause issues for some optimization algorithms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AXNSKsqybmMIKNCKJ6N-UQ.png" /></figure><p>Since the left-hand derivative and the right-hand derivative must be the same to have derivative at one point 🤷‍♀️.</p><p>Note: n is the number of data points.</p><p>Both MAE and MSE are commonly used for regression tasks</p><p><strong>Binary cross entropy loss</strong> function measures the difference between the predicted probabilities and the true labels. Given a binary classification problem with labels Y ∈ 0,1 and predicted probabilities y ∈ [0,1], the binary cross entropy loss is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*OMPdTS-s9A0LnMitJwUAiQ.png" /></figure><p>where:</p><ul><li>N is the number of observations</li><li>yi<em> </em>is the actual binary label (0 or 1) of the <em>i th</em> observation.</li><li>pi is the predicted probability of the <em>i th</em> observation being in class 1.</li></ul><p><strong>Categorical Cross Entropy Loss </strong>is used for multiclass classification problems. It measures the performance of a classification model whose output is a probability distribution over multiple class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*sjuYHEwAPYKKYaNgIMzxqw.png" /></figure><p>Where:</p><ul><li>y is the true label (0 or 1 for each class) from the one-hot encoded target vector.</li><li>ŷ is the predicted probability for class i.</li><li>C is the number of classes.</li></ul><p>Both Binary Cross Entropy and Categorical Cross Entropy are derived from probability distribution functions. We might look at how in another time.</p><p>Since we are predicting multiple classes, we use categorical cross entropy, and I don’t want the shapes to be complicated, so I don’t use one-hot encoding for now.</p><pre>def categorical_cross_entropy(y_true, y_pred):<br>    N = len(y_true)<br>    loss = -np.mean(np.log(y_pred[np.arange(N), y_true]))<br>    return loss</pre><h3>Backpropagation</h3><p>This is core of learning process.</p><p>It is used computed error to figure out how much each weight and bias contributed to the error.</p><p>So, we need error derivative, but the thing is we can’t directly compute error derivatives. Because</p><p>The error function depends on the prediction which depends on the activation which depends on the weighted sum which depends on the weights and biases.</p><p>Let’s see the maths behind the back propagation</p><p>Backpropagation (for one neuron) :</p><p>Notations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*ToVZLk_BXaeBKRu3e-3Saw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*EIfWn9r7CHpDSR6hhNc7cQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*Mz7XRNcu29792LN0nWRznA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*bfYILSbkEeMsqlAQGjmwGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RSz0jpLwoSGAMt_9z22bRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*sUNWtUQaCgzKlfeUgUB5bQ.png" /></figure><p>Learning rate controls how big each weight updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oBZh-ZNZaYD6u5WUAcvJFg.png" /></figure><p>Here, you can visualize the effect of a big versus small learning rate on weight updates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*qWjj7prvPZwkIWSdFMhHEg.png" /></figure><p>As I mentioned, the weight update we have seen above is for a single neuron. In our network, since we have multiple neurons and multiple outputs, we need to use vectorization</p><pre>def gradient(y_true, y_pred):<br>    N = len(y_true)<br>    grad = y_pred.copy()<br>    grad[np.arange(N), y_true] -= 1<br>    grad /= N<br>    return grad</pre><pre>grad_y2 = gradient(y_train.values, y2)    <br>grad_y1 = (grad_y2 @ weight_2.T) * (y1 * (1 - y1))<br>weight_2 -= learning_rate * (y1.T @ grad_y2)<br>bias_2   -= learning_rate * np.sum(grad_y2, axis=0)<br>weight_1 -= learning_rate * (X_train.T @ grad_y1)<br>bias_1   -= learning_rate * np.sum(grad_y1, axis=0)</pre><p>We iteratively update our weights till we get good accuracy or minimize our loss, but we have to be careful about overfitting, which happens when the weights become too specific to the training data and don’t work well with unseen data.</p><p>Here, each iteration is called an epoch.</p><p>You can find the notebook here: <a href="https://www.kaggle.com/code/samriasfaw/neural-net">www.kaggle.com/code/samriasfaw/neural-net</a></p><p>I hope you got something out of this 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e825fcaac454" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Financial News & Impact on Stock Price Prediction]]></title>
            <link>https://medium.com/@samrawitasfaw8/financial-news-impact-on-stock-price-prediction-ee7d9999a6b6?source=rss-60bcb03b762e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee7d9999a6b6</guid>
            <dc:creator><![CDATA[Samrawit Asfaw]]></dc:creator>
            <pubDate>Tue, 19 Aug 2025 18:58:14 GMT</pubDate>
            <atom:updated>2025-08-19T18:58:14.728Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The forces that move a stock up or down generally fall into three categories: fundamental factors, technical factors, and market sentiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*DJ2Eiqw8XNz8BCYu4M_MWQ.png" /></figure><p>While fundamentals and technical provide structured analysis, it is market sentiment often shaped by news and events that can cause sudden, unpredictable movements. For investors, understanding this relationship is crucial for anticipating price changes and developing strategies that balance accuracy with reliability.</p><p>In this blog, I will demonstrate how financial news, and events influence sentiment and stock movements, providing predictive insights and actionable, data-driven investment strategies for investors.</p><h3>Dataset Overview</h3><h4>Financial News and Stock Price Integration Dataset</h4><p>A custom-constructed dataset built from two primary sources:</p><p><strong>1. News Headlines Dataset</strong></p><ul><li><strong>Fields</strong>: Timestamp, Headline Text, Publisher/Source</li><li><strong>Time Span</strong>: 2010 — Jan 2020</li></ul><p>2. <strong>Stock Market Data</strong></p><ul><li><strong>Fields</strong>: Timestamp, Open, High, Low, Close, Volume</li><li><strong>Frequency</strong>: Daily candles</li></ul><h3>Data Preprocessing and Exploratory Data Analysis (EDA) Summary</h3><p>Ticker Selection: I chose NVDA because it had the highest news coverage in my dataset.</p><p><strong>Topic Modeling &amp; Sentiment</strong></p><ul><li>Normalize text</li><li>Extract themes via keyword sets</li><li>Assign sentiment labels (positive, neutral, negative)</li></ul><p><strong>Sentiment Distribution</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*ulbVn9Ae2vP6kNBB3DeHuQ.png" /></figure><p>From the bar plot, most news is distributed with neutral headline sentiment</p><p><strong>Topic Distibution</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*J0FVcERUHxGCq4m3rKM85w.png" /></figure><p>Many news article headlines are categorized under ‘Other’ topics.</p><h4>Feature Engineering</h4><p>I quantified the daily sentiment of news headlines and aligned it with the corresponding daily stock returns.</p><p><strong>Correlation between return and sentiment score</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6tcpER-08ahygNkMOE6X1w.png" /></figure><p>This scatter plot shows a nonlinear relationship between daily returns and sentiment scores.</p><p><strong>Relation between return and sentiment label</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h16MNig_OblhOla0757FBg.png" /></figure><p>Positive news sentiment is associated with higher daily returns, while negative news sentiment corresponds to below-zero daily returns.</p><p><strong>Relation between return and news topic</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YaegE86nQRm1WwXjO8yIjA.png" /></figure><p>This plot shows a strong relationship between news topics and daily returns in the EDA. Days with FDA approval news tends to have high daily returns, whereas news related to operations or production is associated with negative daily returns, even if other topics have high frequency.</p><p><strong>Publishers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Pg-7CE2OG2bS5rvN1D9LA.png" /></figure><p>This plot indicate that some publishers are consistently associated with stronger or weaker market reactions.</p><p>Even the Headlines from top news publishers (e.g., Lisa Levin) corresponded to lower returns.</p><p>Top publishers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*x56SKFmOe8SPq71sMxAUWg.png" /></figure><h4>Technical analysis</h4><p>The Sharpe Ratio of NVDA, with zero excess return, is 0.83. This indicates that the investment’s return does not fully compensate for the risk taken.</p><p><strong>Closing price trend</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*useeTuHIGmtnAnsNBn6_yg.png" /></figure><p>The trend shows a long period of stagnation followed by a sudden and substantial increase in the closing price</p><p><strong>Value at Risk (VaR) at 95% Confidence: -5.28%</strong></p><ul><li>Suggests moderate risk, with potential 1-day losses of up to 5.28% in extreme cases.</li></ul><h3>Modeling</h3><p>After identifying the most relevant features, I am all set to modeling. I first trained an <strong>LSTM model</strong> using only historical closing prices as input.</p><p><strong>Metrics:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*MvZDDo0XB0Ow-KRhz-WSRg.png" /></figure><p>Next, I trained an LSTM model that incorporated both historical stock prices, sentiment label and news topic from financial news headlines.</p><p><strong>Metrics:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*1lmci2AmNXoP1jI93q_j0w.png" /></figure><p>The reduction in error from a validation RMSE of 0.0206 and MAE of 0.0256 in the baseline model to a validation RMSE of 0.0134 and MAE of 0.0166 in the enhanced model indicate a substantial improvement in predictive performance. This translates into represents a <strong>35–40% improvement in predictive accuracy</strong>.</p><p><strong>Investor Implications:</strong></p><ul><li>Improved <strong>forecast reliability</strong> for short-term price movements.</li><li>Enables more <strong>informed buy/sell decisions</strong>.</li><li>Supports <strong>risk-aware portfolio management</strong>, considering both Sharpe Ratio and VaR metrics.</li></ul><h3>Deployment</h3><ul><li>Built <strong>Flask API</strong> for serving predictions.</li><li>Designed <strong>Streamlit dashboard</strong> for real-time predictions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*imlJuD2E_Ld-wWSypaMGUA.png" /></figure><p>Investors can leverage this setup to react promptly to breaking news, rather than relying solely on historical price trends.</p><h3>Discussion</h3><p>The results of this analysis provide several actionable insights for investors seeking to enhance their trading strategies:</p><ol><li><strong>Sentiment Adds Predictive Value</strong><br> Incorporating financial news sentiment into an LSTM model led to a <strong>35–40% reduction in prediction error</strong> compared to a price-only baseline. For investors, this means that <strong>tracking news sentiment can materially improve the accuracy of short-term price forecasts</strong>, allowing for more informed buy/sell decisions.</li><li><strong>Topic-Specific Insights</strong><br> Certain news topics, such as <strong>FDA approvals</strong>, consistently align with <strong>positive daily returns</strong>, while operational or production issues correlate with <strong>negative returns</strong>. By monitoring topic-specific news, investors can <strong>anticipate potential stock movements</strong> beyond what price trends alone would suggest.</li><li><strong>Publisher Influence Matters</strong><br> Analysis showed that headlines from certain publishers, including some top sources like Lisa Levin, are associated with <strong>weaker returns</strong>. This indicates that <strong>not all news sources carry equal weight</strong>, and investors can gain an edge by prioritizing more influential or predictive news sources.</li><li><strong>Risk Management Enhancement</strong><br> Technical metrics like <strong>Sharpe Ratio (0.83)</strong> and <strong>VaR at 95% confidence (-5.28%)</strong> highlight that NVDA carries <strong>moderate risk</strong>, with potential one-day losses above what might be expected in a diversified portfolio. By combining <strong>price trends with sentiment signals</strong>, investors can improve <strong>risk-adjusted decision-making</strong>, identifying when a stock may move sharply in response to news events.</li></ol><h3>Conclusion</h3><p>Combining <strong>historical prices, technical analysis, and sentiment driven insights</strong> provides a more <strong>holistic and actionable forecasting approach</strong>. While no model can completely eliminate uncertainty, integrating news sentiment offers a <strong>competitive edge in anticipating sudden market shifts</strong>.</p><p>Project GitHub <a href="https://github.com/Samri-A/Stock_RiskLens">link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee7d9999a6b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>