<?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 Kunal Kushwaha on Medium]]></title>
        <description><![CDATA[Stories by Kunal Kushwaha on Medium]]></description>
        <link>https://medium.com/@kunalkushwahatg?source=rss-e43672a1c885------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nGjPrmSJY5ilFnfgtiMVMA.jpeg</url>
            <title>Stories by Kunal Kushwaha on Medium</title>
            <link>https://medium.com/@kunalkushwahatg?source=rss-e43672a1c885------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 11:16:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kunalkushwahatg/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[Mem0]]></title>
            <link>https://medium.com/@kunalkushwahatg/mem0-bd7467fef9ba?source=rss-e43672a1c885------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd7467fef9ba</guid>
            <dc:creator><![CDATA[Kunal Kushwaha]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 13:04:07 GMT</pubDate>
            <atom:updated>2025-08-06T10:58:10.466Z</atom:updated>
            <content:encoded><![CDATA[<h4>History and Problems</h4><p>The biggest issue that current LLMs face is memory. They don’t know anything that is not in their context. By context, I mean:</p><p><strong>context = formality string + formality string + formality string + past data + question.</strong></p><p>So, by a brute-force approach, we can say that we need to paste conversation data in the prompt and question, and then we are done, right? It is true to some extent, but what if the chat is 1M tokens long? The context window of LLMs will not be able to hold and process it.</p><p>Before going further, the context window is the number of tokens a specific LLM can process in one go.</p><p>Now, another suggestion could be a RAG-based approach, which means it stores the past info in a vector DB and retrieves it as per the user’s query. In this way, we can get the top 100 or 200 conversations relevant to the user and feed them as a prompt with the current question. But this is not efficient again:</p><ul><li>It will store very raw chat data that may or may not be useful for LLMs. There are many conversations where we talk about the same thing, but in different contexts. The context info will be lost, and the chat, without any understanding of the past context, will be passed to the prompt.</li><li>Retrieval quality degrades over time with every conversation increment. As the database grows, more similar vectors come into the picture. The old information might get suppressed and lose its relevancy.</li><li>No learning or update on memory. Let’s say I told my LLM that I am vegetarian 1 year ago, and after 6 months I said that I am non vegetarian. Now, two conflicting memories are created.</li></ul><p>From time to time, people have come up with various solutions to the memory problem. Every approach has some flaws and some advantages over others (obviously, this is what research is all about). Recently, I came across a paper called <a href="https://arxiv.org/pdf/2504.19413"><strong>Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory</strong></a>. Its agent is available for public use. It solves almost every problem mentioned above with uniqueness and efficiency.</p><p>I recently completed its basic implementation in code. We will walk through it, and I will also explain its architecture and how it works.</p><h4>Extraction Phase</h4><p>First, we will understand each of its components, and then walk through the overall workflow.</p><h4>Extraction Phase components</h4><p><strong>Summary</strong></p><p>This refers to the user’s complete past information. But how is it different from RAG? In Mem0, it is written entirely as a paragraph think of it like writing your past, but including only the important information, without any unnecessary details. It’s short, precise, and to the point. For now, don’t worry about <em>how</em> we get this we’ll discuss that later. Just understand that it’s a paragraph that holds your “karm kundli.”</p><p><strong>Last M Conversations</strong></p><p>This refers to the last M message pairs of the user and the bot, going from the most recent back to M conversations ago. This is used to understand the current chat context, what the user is talking about, and what the conversation is actually about.</p><p><strong>T1m and Tm</strong></p><p>T1m is the question that the user asked, and Tm is the response that the bot gave to the user. These are the strings from which new information will be extracted.</p><p>Okay, so now you have enough information to understand the phases.</p><h4>Phases</h4><p>The complete Mem0 architecture is divided into two phases:</p><ul><li>Extraction Phase</li><li>Update Phase</li></ul><p>So let’s go for the extraction phase here</p><h4>Extraction Phase</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WeAuSvw6Sd14h0LbQQ_Pjg.png" /></figure><p>In the extraction phase, the model takes the summary and the last conversation, along with (mt, mt1), and combines all of these into an optimized prompt. The model then extracts the new information that it thinks is important and should be considered. One thing to remember: the new information will be extracted only from m and mt1 the summary and last conversation are used as extra context.</p><pre><br>def form_extraction_prompt(summary, recent_messages, mt_1, mt):<br>    &quot;&quot;&quot;<br>    Forms the prompt for the LLM, directing it to extract new, salient,<br>    factual information exclusively from the LATEST message exchange,<br>    rephrase them concisely, and return &lt;none&gt; if no such information exists.<br>    &quot;&quot;&quot;<br>    prompt = (<br>        &quot;You are an AI assistant designed to extract **CRUCIAL, NEW, ACTIONABLE FACTS** from conversations for memory storage.\n&quot;<br>        &quot;Your goal is to identify and extract *only* facts that are essential to remember for future interactions, focusing on user-specific details, preferences, instructions, or significant updates.\n&quot;<br>        &quot;**Your primary directive is to be precise and useful, capturing important details while avoiding noise.**\n\n&quot;<br>    )<br><br>    # Place the core data directly with the strictest instructions<br>    prompt += &quot;### Primary Source for Facts (Analyze ONLY This Section for Extraction):\n&quot;<br>    prompt += f&quot;User: {mt_1}\nAssistant: {mt}\n\n&quot;<br>    prompt += &quot;### End Primary Source\n\n&quot;<br><br><br>    # Provide context, but with clear boundaries<br>    prompt += &quot;### Contextual Information (For Background ONLY - DO NOT Extract Facts From Here):\n&quot;<br>    prompt += &quot;--- General Conversation Summary (Provides historical context; DO NOT EXTRACT FACTS):\n&quot;<br>    prompt += f&quot;{summary}\n\n&quot;<br>    prompt += &quot;--- Recent Conversation History (Provides immediate context; DO NOT EXTRACT FACTS):\n&quot;<br>    if not recent_messages:<br>        prompt += &quot;No recent messages.\n&quot;<br>    else:<br>        for msg in recent_messages:<br>            if &#39;content&#39; in msg and &#39;role&#39; in msg:<br>                prompt += f&quot;- {msg[&#39;role&#39;].capitalize()}: {msg[&#39;content&#39;]}\n&quot;<br>            elif &#39;user&#39; in msg and &#39;assistant&#39; in msg:<br>                prompt += f&quot;- User: {msg[&#39;user&#39;]}\n- Assistant: {msg[&#39;assistant&#39;]}\n&quot;<br>            elif &#39;content&#39; in msg:<br>                prompt += f&quot;- {msg[&#39;content&#39;]}\n&quot;<br>    prompt += &quot;### End Contextual Information\n\n&quot;<br><br>    # Final, balanced task instructions<br>    prompt += (<br>        &quot;## Task: Extract CRUCIAL, NEW, ACTIONABLE Facts\n&quot;<br>        &quot;1.  Your sole focus is to analyze **EXCLUSIVELY** the &#39;Primary Source for Facts&#39; section (the latest User-Assistant exchange) to identify new facts.\n&quot;<br>        &quot;2.  **DO NOT** extract any facts or information from the &#39;Contextual Information&#39; sections (Summary or Recent Conversation History). These are for understanding the ongoing conversation, not for new fact extraction.\n&quot;<br>        &quot;3.  Extract only **specific, verifiable, and important details** that establish **user preferences, explicit instructions, or new factual information** directly relevant to the user or task. This includes things like:\n&quot;<br>        &quot;    - User&#39;s name, age, location, or contact info if provided.\n&quot;<br>        &quot;    - Stated preferences (e.g., &#39;I prefer coffee&#39;, &#39;I like dark mode&#39;).\n&quot;<br>        &quot;    - Direct instructions or requirements (e.g., &#39;Remind me tomorrow&#39;, &#39;I need the report by Friday&#39;).\n&quot;<br>        &quot;    - Key information relevant to a specific ongoing task.\n&quot;<br>        &quot;4.  **Concise Rephrasing:** If a fact is extracted, **rephrase it to be as short, simple, and informative as possible.** Eliminate all filler words. Focus on keywords and direct statements. Grammar is secondary to conciseness. For example, turn &#39;The user mentioned that their name is John&#39; into &#39;User name: John&#39;. Combine related facts into a single, concise sentence.\n&quot;<br>        &quot;5.  **When to return &lt;none&gt;:** If the &#39;Primary Source for Facts&#39; contains *only* content that is not a crucial, new, actionable fact, you **MUST** output `&lt;none&gt;` and nothing else. This applies to content types such as:\n&quot;<br>        &quot;    - **Conversational Overhead:** Greetings, small talk, pleasantries, or simple acknowledgments (e.g., &#39;Hi&#39;, &#39;Hello&#39;, &#39;How are you?&#39;, &#39;Okay&#39;, &#39;Got it&#39;, &#39;Thanks&#39;, &#39;You&#39;re welcome&#39;).\n&quot;<br>        &quot;    - **General Information Queries:** Questions about general knowledge, current events, or topics that do not reveal specific user preferences, instructions, or personal facts (e.g., &#39;What is the capital of France?&#39;, &#39;Tell me about AI&#39;, &#39;What&#39;s the weather like?&#39;).\n&quot;<br>        &quot;    - **Redundant Information:** Information that is already known and does not provide a new update or clarification about the user or task.\n&quot;<br>        &quot;    - **Unactionable Statements:** Statements that don&#39;t require any memory or follow-up action.\n&quot;<br>        &quot;    Do not explain why you returned `&lt;none&gt;`.\n\n&quot;<br>        &quot;**Example Output Format for Extracted Facts:**\n&quot;<br>        &quot;- User&#39;s name: John.\n&quot;<br>        &quot;- Prefers: dark theme.\n&quot;<br>        &quot;- Needs: report by Friday.\n&quot;<br>        &quot;- Task: book flight to Delhi on Monday.\n&quot;<br>        &quot;\n&quot;<br>        &quot;Extracted Facts (or &lt;none&gt;):\n&quot;<br>    )<br><br>    return prompt</pre><p>we will get the list of new info and will take the all info for further processing that is the update phase now. For the update phase you need to understand some more terms Let’s go line by line.</p><h4>Memories Database:</h4><p>This is what we can call the main memory. What it does is store all the important and most relevant memories. I have used a JSON file that works as a memory database. We also maintain a vector DB of the memories so that we can perform <strong>similarity search</strong>.</p><p>I have a Database class that handles all the DBMS operations and holds everything. By <em>everything</em>, I mean:</p><ul><li>Conversation summary as a string</li><li>Vector DB</li><li>Recent M messages</li><li>Memories as a dictionary</li></ul><p>It has the following functions:</p><ul><li><strong>Delete Index</strong>: Deletes an index from database.memories.</li><li><strong>Update Index</strong>: Updates an index in database.memories.</li><li><strong>Add Index</strong>: Adds new data to database.memories.</li><li><strong>Create Vector DB</strong>: Not exactly a DBMS operation, but a basic operation to create a vector DB from database.memories.</li><li><strong>Similarity Search</strong>: Perform vector similarity search (FAISS database)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c8qPz97FNCT-QpMrdSN8jA.png" /></figure><p>Now I think you got some context of what is going on here if not, no issues as the dots will be linked as you move on. Lets start with the Update phase.</p><h4>Update Phase</h4><p>Do you remember that in the <strong>extraction phase</strong>, we got the extracted data as a list? Now we will be using that here. We’ll take one element of the new info from the list… let’s say:</p><p><strong>“I am veg on Mondays only”</strong> and retrieve the <strong>k most similar sentences</strong> from the vector DB.</p><p>These <em>k</em> elements, along with the extracted element, are then prompted to the model, asking it to judge what kind of data it is and, based on that, suggest a database operation:</p><ul><li><strong>ADD</strong>: This operation adds a new element to the database. And guess what? It’s not the exact same element that was extracted, but a <strong>more compact and accurate</strong> representation of it.</li><li><strong>DELETE</strong>: If the model determines that some information needs to be removed, it triggers this operation. The LLM returns the ID of the memory to be deleted, and that memory is then removed from the database.</li><li><strong>UPDATE</strong>: If the LLM finds that an existing memory needs to be updated for example, if the current memory says <em>“I am veg”</em>, but the new info adds <em>“on Mondays only”</em> — it updates the memory index with the new info.</li><li><strong>NOOP</strong>: This is a no-operation command. It means: do nothing, just skip it.</li></ul><p>Below are the prompts for the update phase.(<em>Don’t judge me by my prompts it’s AI-generated as the models are very small so prompt needed to well defined😄</em>)</p><pre>def create_update_prompt(candidate_fact: str, similar_memories) -&gt; str:<br>    print(&quot;similar_memories:&quot;)<br>    print(similar_memories)<br>    prompt = f&quot;&quot;&quot;You are an intelligent memory management system designed to process new information into a knowledge base. Your task is to analyze a &#39;Candidate Fact&#39; and compare it meticulously with a list of &#39;Existing Similar Memories&#39; to determine the precise operation required.<br><br>**Your Guiding Principle:** Be extremely selective. **Avoid adding redundant information.** Only add if the &#39;Candidate Fact&#39; introduces a truly unique and previously unrecorded piece of information. Prioritize updating existing memories if the candidate fact refines or replaces them, even with slight wording differences.<br><br>---<br>## Candidate Fact to Evaluate<br>**Candidate Fact:** {candidate_fact}<br><br>---<br>## Existing Similar Memories (for comparison)<br>&quot;&quot;&quot;<br><br>    if similar_memories:<br>        for i, memory in enumerate(similar_memories, 1):<br>            prompt += f&quot;Memory ID: {memory.get(&#39;memory_id&#39;, &#39;N/A&#39;)}\n&quot; \<br>                      f&quot;Content: {memory.get(&#39;content&#39;, &#39;&#39;)}\n&quot; \<br>                      f&quot;Similarity Score: {memory.get(&#39;score&#39;, 0):.3f}\n&quot; \<br>                      f&quot;---\n&quot; # Separator for clarity between memories<br>    else:<br>        prompt += &quot;No similar memories found. This is highly likely a new fact. Proceed with ADD.\n---\n&quot; # Strengthen &quot;new fact&quot;<br><br>    prompt += &quot;&quot;&quot;<br>---<br>## Defined Operations<br><br>* **ADD:** Choose this operation **ONLY IF** the &#39;Candidate Fact&#39; introduces a genuinely **NET-NEW CONCEPT or PIECE OF INFORMATION** that is not mentioned, implied, or contradicted by *any* of the &#39;Existing Similar Memories&#39;. This should be used sparingly, as a last resort, after ruling out UPDATE, DELETE, and NOOP.<br>    * **Condition:** The candidate fact represents a distinct, never-before-recorded piece of actionable intelligence.<br>    * **Example:** Existing: &quot;User prefers coffee.&quot; Candidate: &quot;User wants a new phone.&quot; -&gt; ADD.<br>    * **Output for ADD:** {&quot;operation&quot;: &quot;ADD&quot;, &quot;target_memory_id&quot;: &quot;&quot;, &quot;updated_content&quot;: null}<br><br>* **UPDATE:** Choose this operation **PRIORITIZE THIS** if the &#39;Candidate Fact&#39; provides **additional, refined, or slightly different details** about an existing, highly similar memory. This includes cases where the wording is different but the core meaning or subject is the same. It enhances, clarifies, or subtly modifies an existing record without outright contradicting it.<br>    * **Condition:** The candidate fact adds specific, complementary, or slightly rephrased information to an existing memory, making the existing memory more complete or accurate.<br>    * **Example 1 (Refinement):** Existing: &quot;User lives in New York.&quot; Candidate: &quot;User lives in New York, specifically in Brooklyn.&quot; -&gt; UPDATE. New content: &quot;User lives in New York, Brooklyn.&quot;<br>    * **Example 2 (Rewording/Completion):** Existing: &quot;User is 30 years old.&quot; Candidate: &quot;My age is 30.&quot; -&gt; UPDATE. New content: &quot;User is 30 years old.&quot; (Even if semantically same, rephrase to standard).<br>    * **Example 3 (Small detail added):** Existing: &quot;User wants pizza.&quot; Candidate: &quot;I want a large pepperoni pizza.&quot; -&gt; UPDATE. New content: &quot;User wants a large pepperoni pizza.&quot;<br>    * **Output for UPDATE:** {&quot;operation&quot;: &quot;UPDATE&quot;, &quot;target_memory_id&quot;: &quot;ID_OF_MEMORY_TO_UPDATE&quot;, &quot;updated_content&quot;: &quot;Revised combined and concise content&quot;}<br><br>* **DELETE:** Choose this operation **ONLY IF** the &#39;Candidate Fact&#39; *directly and unequivocally contradicts or invalidates* an *existing, highly similar memory*. The new information makes an old memory factually incorrect or completely irrelevant.<br>    * **Condition:** The candidate fact makes an existing memory explicitly false or obsolete.<br>    * **Example:** Existing: &quot;User&#39;s name is John.&quot; Candidate: &quot;My name is actually Mike, not John.&quot; -&gt; DELETE &quot;User&#39;s name is John&quot;.<br>    * **Output for DELETE:** {&quot;operation&quot;: &quot;DELETE&quot;, &quot;target_memory_id&quot;: &quot;ID_OF_MEMORY_TO_DELETE&quot;, &quot;updated_content&quot;: null}<br><br>* **NOOP:** Choose this operation **ONLY IF** the &#39;Candidate Fact&#39; is **EXACTLY THE SAME (or near-exact semantic duplicate)** as an existing memory, provides **NO NEW INFORMATION WHATSOEVER**, or is **insignificant/redundant** given existing memories. This means no action is required because the memory already exists in a sufficient form.<br>    * **Condition:** The candidate fact offers no meaningful addition or change to an existing memory. It&#39;s a true repetition or irrelevant detail.<br>    * **Example 1:** Existing: &quot;User likes coffee.&quot; Candidate: &quot;I really like coffee.&quot; -&gt; NOOP.<br>    * **Example 2:** Existing: &quot;User lives in Berlin.&quot; Candidate: &quot;The user&#39;s residence is Berlin.&quot; -&gt; NOOP. (Same fact, different phrasing, no new info).<br>    * **Output for NOOP:** {&quot;operation&quot;: &quot;NOOP&quot;, &quot;target_memory_id&quot;: &quot;&quot;, &quot;updated_content&quot;: null}<br><br>---<br>## Instructions for Decision Making<br><br>1.  **Prioritize Operations (in order): NOOP &gt; DELETE &gt; UPDATE &gt; ADD.** If a &#39;Candidate Fact&#39; fits the criteria for NOOP, choose NOOP. If not, check DELETE. If not, check UPDATE. Only if none of the above apply, choose ADD.<br>2.  **Strict Comparison:** Carefully compare the &#39;Candidate Fact&#39; with *each* &#39;Existing Similar Memory&#39;. Consider semantic meaning, not just exact wording.<br>3.  **Combine and Condense for UPDATE:** For **UPDATE**, you *must* generate a new, `updated_content` string that thoughtfully combines the information from the `Candidate Fact` and the `target_memory`. This `updated_content` should be **as concise and informative as possible**, removing redundancy, similar to the fact extraction process. (e.g., combine &quot;User lives in New York&quot; and &quot;User lives in Brooklyn&quot; into &quot;User lives in New York, Brooklyn&quot;).<br>4.  **Target ID for UPDATE/DELETE:** If **UPDATE** or **DELETE**, you *must* identify the `target_memory_id` of the specific memory to be acted upon.<br>5.  **Output Format Adherence:** Provide your response **ONLY as a JSON object**. Do not include any other text, explanations, or conversational fillers outside the JSON.<br><br>---<br>Extracted JSON operation:<br>&quot;&quot;&quot;<br>    return prompt</pre><p>These operations will be called for every element extracted from the extraction phase simultaneously.</p><p>Okay, now you might be thinking: <em>What is the use of updating memories? Where are we using this updated memory?</em></p><p>The first use is in similarity search<strong>,</strong> which we already used in the update phase.</p><p>The second and most important use is for<strong> </strong>summary generation<strong>.</strong></p><p>Now, let’s move to <strong>summary generation</strong>. What we do here is take the updated memories from the database and ask the model to generate a completely new summary based on them.</p><pre>def create_summary_prompt(memories_list):<br>    # This initial instruction is good, sets the role<br>    memories_section = &quot;You are a summary writer focused on extreme brevity and key facts.\n&quot;<br>    memories_section += &quot;Extract only critical, actionable information from the following memories:\n&quot;<br>    memories_section += &quot;\n--- Memories Start ---\n&quot;<br>    for memory in memories_list:<br>        memories_section += f&quot;- {memory[&#39;content&#39;].strip()}\n&quot; # Added hyphen for bullet, strip for clean lines<br>    memories_section += &quot;--- Memories End ---\n\n&quot;<br><br>    prompt = (<br>        f&quot;{memories_section}&quot;<br>        &quot;Rules for Summary:\n&quot;<br>        &quot;1. **Crucial Facts Only:** Include only facts that absolutely *must* be remembered for future interactions (e.g., user preferences, explicit instructions, names, important decisions).\n&quot;<br>        &quot;2. **Minimalist:** Eliminate all filler words, greetings, small talk, and conversational flow. Get straight to the point.\n&quot;<br>        &quot;3. **Short Phrases/Keywords:** Use short phrases, keywords, or bullet points (if natural) instead of full sentences. Grammar is secondary to conciseness.\n&quot;<br>        &quot;4. **No Introduction/Conclusion:** Start directly with the facts. Do not write &#39;Here is a summary&#39; or similar.\n&quot;<br>        &quot;5. **Paragraph Format:** Despite brevity, output as a single, dense paragraph.\n&quot;<br>        &quot;6. **Example of desired style: &#39;User name: John. Prefers dark mode. Needs report by Friday.&#39;**\n\n&quot;<br>        &quot;Generate the extremely concise summary based on these rules. If no crucial facts exist, output &#39;No key info yet.&#39;\n&quot;<br>        &quot;Summary:&quot;<br>    )<br>    return prompt</pre><p>Again, this is a minimalist operation. There are many ways you can approach this problem for example, you could use the old summary along with new memories, or combine updated and deleted memories to revise the summary. That could also be an effective method.</p><h4>Complete Workflow</h4><p>Now, let’s zoom out and walk through the actual process again. There can be <em>n</em> number of ways to design your workflow, depending on your limitations and requirements. Here’s what I did:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VD_hZ3RvNJFUUjBX--aw6g.png" /><figcaption>workflow credit : <a href="https://arxiv.org/abs/2504.19413">https://arxiv.org/abs/2504.19413</a></figcaption></figure><p>At the initial start, the summary is generated from the memories database. Once the summary is generated, you’re good to go for chatting.</p><p>Now, when the user sends a message, the prompt (user input) is passed along with the summary and the recent conversation so that a correct and relevant answer can be generated. Once the answer is generated, the <strong>extraction phase</strong> is triggered.</p><p>Since I’m running this locally, I haven’t used a multithreading approach where the extraction and update phases run in parallel otherwise, the memory processing time could be reduced. After the extraction phase, the <strong>update phase</strong> comes into play to update the database. Then, the chat loop continues.</p><p>You can configure summary generation to run on every <strong>K-th iteration</strong>, or even asynchronously, so that you don’t have to wait for summary generation every time.</p><p>This is basically how I implemented Mem0. You can find it on my GitHub and run it on your local system. You might even improve it further or optimize it in your own way. The paper is genuinely fun to read and full of valuable insights the official implementation also includes a graph based approach which has improved results than traditional vector db based approach.</p><h4>Credits :</h4><p><a href="https://github.com/mem0ai/mem0">Official Mem0 repo</a></p><p><a href="https://arxiv.org/pdf/2504.19413">Official paper</a></p><h4>My Repo :</h4><p><a href="https://github.com/kunalkushwahatg/mem0">https://github.com/kunalkushwahatg/mem0</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd7467fef9ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Sound: Exploring Frequency Domain Features for Machine Learning]]></title>
            <link>https://medium.com/@kunalkushwahatg/unlocking-sound-exploring-frequency-domain-features-for-machine-learning-ef1d6fcbbb36?source=rss-e43672a1c885------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef1d6fcbbb36</guid>
            <dc:creator><![CDATA[Kunal Kushwaha]]></dc:creator>
            <pubDate>Fri, 11 Oct 2024 05:12:13 GMT</pubDate>
            <atom:updated>2025-10-01T15:08:33.001Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous blog, we covered <strong>MFCCs</strong> as key features for machine learning with audio. In this new blog, we’re going to dive into more frequency-domain audio features to expand our toolkit.</p><p>Extracting frequency-domain features looks something like this visually</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NQgtOi6J7auOLkjn6AiPmA.png" /></figure><p>Before we dive deeper, let’s quickly clear up a couple of <strong>mathematical conventions</strong> we’ll be using:</p><ul><li><strong>mt(n)</strong>: This represents the <strong>magnitude</strong> of the signal at frequency bin <strong>n</strong> and frame <strong>t</strong>.</li><li><strong>N</strong>: This is the total number of <strong>frequency bins</strong>.</li></ul><p>So let’s jump to the audio features………………………</p><h3><strong>Band Energy Ratio</strong></h3><p>This feature helps us compare the <strong>energy</strong> in the lower and higher frequency bands of a signal. It’s basically a way to measure how dominant the <strong>low frequencies</strong> are in comparison to the higher ones.</p><p>The formula we’ll be using for calculating the <strong>Band Energy Ratio</strong> is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*iBcJtr8fOu3UmHehKk1FoA.png" /></figure><p>Here mt(n) square represents power at particular time at particular frame , F represents split frequency so let’s talk about in detail ….</p><p><strong>Split Frequency </strong>is the frequency threshold above which frequency are considered as Higher frequency and below which are called as lower frequency. We generally choose f to be 2000 because it makes a lot of sense 🙂. Let&#39;s visualize the split frequency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZqTRsWR1u5OIAak-l3it4Q.png" /></figure><p>The purple line is the split frequency threshold value .</p><p>So actually we are taking one frame at a time and in the numerator we take power in the lower frequency band and in the denominator we take the higher frequency band and after calculation we get the actual value per frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xugIRQ01fxB-W0sssmx64Q.png" /></figure><h4>Applications</h4><p>This feature can be useful in various audio tasks, such as:</p><ul><li><strong>Distinguishing between music and speech</strong></li><li><strong>Classifying music genres</strong> based on frequency characteristics</li></ul><h3><strong>Spectral Centroid</strong></h3><p>The <strong>spectral centroid</strong> is like the <strong>center of gravity</strong> for the magnitude spectrum. It shows where most of the energy in the frequency band is concentrated. This feature is often used to measure the <strong>“brightness”</strong> of a sound — whether it feels more open and sharp or dull and soft.</p><p><strong>Formula : Weighted mean of the frequencies</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*EnEnufKUtidU8KKyybo1ew.png" /></figure><h4>Application</h4><ul><li><strong>Audio classification</strong>: Helps distinguish between different types of audio.</li><li><strong>Music classification</strong>: Useful for grouping music based on its frequency characteristics.</li></ul><p>Now that we’ve covered the spectral centroid, let’s build on that idea and dive into <strong>bandwidth</strong>, which is derived from this concept.</p><h3><strong>Bandwidth</strong></h3><ul><li>Bandwidth is <strong>derived from the spectral centroid</strong>.</li><li>You can think of it as the <strong>variance</strong> or spread of frequencies around the spectral centroid.</li><li>It helps describe the <strong>timbre</strong> or tone quality of a sound — whether it’s sharp, rich, or more mellow.</li></ul><p><strong>Formula : </strong>Weighted mean of the distances of frequency bands from spectral centroid</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*UZzzfuF7d6sdqlMw_UmpuA.png" /></figure><p>We can call bandwidth as energy variance as more spread in graph more variance value and vice versa .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*wmOU8wQG5vAoNXdl2SO6pA.png" /></figure><p>Bandwidth plays a key role in tasks like <strong>music genre classification</strong>, helping differentiate between different styles based on the spread of frequencies.</p><p>In this blog, we explored various frequency domain features, including <strong>Band Energy Ratio</strong>, <strong>Spectral Centroid</strong>, and <strong>Bandwidth</strong>. These features can enhance your machine learning models by improving tasks like audio classification and music genre recognition. Understanding and utilizing these characteristics will help you achieve better results in your audio processing projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef1d6fcbbb36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Mel to MFCCs: Understanding Audio Features for Machine Learning]]></title>
            <link>https://medium.com/@kunalkushwahatg/from-mel-to-mfccs-understanding-audio-features-for-machine-learning-1d6be522a345?source=rss-e43672a1c885------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d6be522a345</guid>
            <dc:creator><![CDATA[Kunal Kushwaha]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 13:38:24 GMT</pubDate>
            <atom:updated>2025-10-01T15:10:00.191Z</atom:updated>
            <content:encoded><![CDATA[<p>You are familiar with the words mel frequency but cepstral might be knew word , <strong>Cepstral</strong> refers to anything related to the <strong>cepstrum</strong> , for you if try to see it its is none other than spectrum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*Jq2D6O3DsunAULULyYsyug.png" /></figure><p>Here’s a quick historical note on <strong>cepstrum</strong>:</p><ul><li>It was first developed in the 1960s while studying echoes in seismic signals.</li><li>In the 1970s, it became the go-to feature for <strong>speech recognition</strong> and identification.</li><li>By the 2000s, it also found its place in <strong>music processing</strong>.</li></ul><p>If you see the mathematical formula of cesptrum it will more define its name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*qiRj3MRif_ccOZfhYQDBpw.png" /></figure><p>Here we are taking the time domain to frequency domain, by fourier transform , then calculating the log of frequency amplitudes then taking the inverse fourier transform of output values.</p><p>Lets visualize what i have written there</p><h3>Visualization of cepstrum</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*-lrm8AWfwzDsmBzbBM5WnA.png" /></figure><p>Here we calculate the DFT of signal to convert the data from time domain to freq domain to get power spectrum .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*03ijkkJfsYmcGemNhYdGRQ.png" /></figure><p>When you look at the <strong>log power spectrum</strong>, it appears as a continuous signal with a periodic structure. This structure comes from the harmonic components in the original time-domain signal. Now, if we want to analyze which frequencies are present in this periodic structure, we can apply the Fourier Transform. In simple terms, we treat the log power spectrum like a time-domain signal and apply the Fourier Transform to it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*KonuzXxkk1-DaOwg6gDjkA.png" /></figure><p>You’ve probably heard about the vocal tract — it works like a natural filter for the sounds we make, especially impacting higher-pitched sounds. But it doesn’t stop there! The vocal tract shapes the entire range of frequencies, boosting some while softening others, giving us the unique tones of speech.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*6wKF6XA2Hp8PtSaMdsiDyg.png" /></figure><p>How do you think speech is generated?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*Q9ZVDQQM0V6dkKZnBVH6Kw.png" /></figure><p>The <strong>vocal tract</strong> compresses and expands in different ways, creating various filters that help generate different sounds.</p><p>Now, let’s dive deeper and understand what <strong>cepstrum</strong> really is!</p><p>Initially we have log spectrum that we can plot like this usually represent the speech indirectly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*x6zkuxNAN8d5ww4Oe59pxQ.png" /></figure><p>If we try to take envelop(mentioned in past blogs) of this we just smoothened the plot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*0qP3kIFjI1JQBRpf1_ixhQ.png" /></figure><p>The <strong>vocal tract frequency response</strong> refers to how the vocal tract shapes the sound produced by the vocal cords by boosting certain frequencies and attenuating others. The vocal tract, which includes the throat, mouth, and nasal passages, acts as a resonant filter.A <strong>resonant filter</strong> is a type of filter that amplifies certain frequencies while reducing others.</p><p>As air passes through it, different configurations of the vocal tract (e.g., tongue position, mouth shape) create resonances at specific frequencies called <strong>formants</strong>. These formants are peaks in the frequency response that define the unique sound of different vowels and other speech sounds<strong>.Formants carry the identity of sound .</strong></p><p>In other words spectral envelope provide the information about timbre(refers to the quality or color of a sound that distinguishes it from other sounds with the same pitch and loudness.) of sound .</p><p>Now let’s try to kind of subtract log spectral by spectral envelope</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*Jjh_q9cOVTWVyNi47K0W4Q.png" /></figure><p>A <strong>glottal pulse</strong> is the sound produced when your vocal cords (vocal folds) come together and then open, letting out a tiny burst of air. This happens repeatedly when you speak or sing, creating a series of pulses that form the basic sound of your voice.</p><p>The speed at which these pulses occur determines the pitch of your voice — faster pulses mean a higher pitch, and slower pulses mean a lower pitch. These pulses are then shaped by your mouth and throat to create different sounds, like vowels and consonants, giving your voice its unique character.It is like carrier of pitch information</p><p>So finally we can say mathematically that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*dJpUu24MpJdExA8jznqIDQ.png" /></figure><p>Let’s say we have a signal, <strong>x(t)</strong>, which represents the sound produced. The <strong>glottal pulse</strong> is represented by <strong>e(t)</strong>, and the <strong>vocal tract frequency response</strong> by <strong>h(t)</strong>. When we convolve these two functions (e(t) and h(t)), we get <strong>x(t)</strong>, which is the final sound output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*MMutwvhYS3eOsjuw8_UL5w.png" /></figure><p>On frequency domain, we can write it as by using the properties of Fourier transforms</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*WlQ8g5iN-ietRW9BMwYnbQ.png" /></figure><p>On taking log both the sides</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*hm5O9jwLU5u02XGtKDCRyw.png" /></figure><p>Using the properties of log</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*zOlbTx483AqyHLGSQINMag.png" /></figure><p>If we formalize everything and try to link it with the earlier graphs we can represent</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*r3a4OXS6-VFQLOGXnbFG1w.png" /></figure><p>But what is the actual use of doing this separation , we are doing this because we do not need one of the components for our feature for deep learning model that do not contribute in the identity of that sound.</p><h3>Separating components</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-nnFnDMbpiaMWv7pp9V_cA.png" /></figure><p>In speech processing we not really care about glottal pulse . What we do care about is the identity of the sound the timbre the formants and all of this components is carried by vocal tract frequency response .</p><h3>How we separate components actually?</h3><p>We start with a curve that results from applying the Discrete Fourier Transform (DFT) and taking the logarithm of the values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*I3n7Vm2olqzylVdow0xMFg.png" /></figure><p>What we’ll do next is apply the <strong>Inverse Discrete Fourier Transform (IDFT)</strong> to plot the frequency components of our curve. The process will be similar to what we did before — starting from lower frequencies, we’ll assess the similarity of each sine wave and plot it according to its magnitude. This new representation will be called the <strong>quefrency domain</strong>. If you take a look at the vocal tract frequency response graph, you’ll see how this works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*rMt6-FqU9HmI4PnpKbK_Kg.png" /></figure><p>Here the frequency of sine wave are somewhat low like we can see sine of 4hz</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*OE-MNHCbWaeBrP0DTovD-Q.png" /></figure><p>On going to glottal pulse plot the frequency of the sine wave used wil be high like 100 hz and above</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*xSoSG9JacIWI-QBa66c-2Q.png" /></figure><p>We can see the complete as this</p><p>Now if we want to remove the higher frequency (quefrency) we can use some filter in the signal that will only allow signal lower that give threshold frequency we can call it low pass filtering but we will call it as liftering and after liftering the image is like</p><p>If we combine all the process we flow chart like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*o5gYYlDNG8fwsLeHRts9HA.png" /></figure><p>We have used the discrete cosine transform not the Inverse Discrete Fourier transform.</p><p><strong>Why discrete cosine transform is used</strong></p><ul><li><strong>Discrete Cosine Transform (DCT)</strong> is often used because it simplifies things compared to the Fourier Transform.</li><li>Unlike the <strong>Discrete Fourier Transform (DFT)</strong>, which gives complex numbers (with real and imaginary parts), the <strong>DCT</strong> produces only real-valued coefficients. For many applications, including audio processing, these real values are sufficient.</li><li>DCT also helps <strong>decorrelate</strong> the energy across different mel bands, meaning it spreads out the information more evenly across the spectrum.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*W_mjpIA_q6PgOi-dj8AxHQ.png" /></figure><p>When I say <strong>decorrelate</strong>, I mean that the different filters in the mel spectrogram overlap with each other as shown in upper image. This overlap isn’t ideal for machine learning because we want each feature to be independent, not influenced by other features. The <strong>Discrete Cosine Transform (DCT)</strong> helps with that by reducing this overlap. It also reduces the dimensionality of the data, making it a great tool for compressing information and acting like a <strong>dimensionality reduction algorithm</strong> for the spectrum.</p><p>To apply the <strong>Discrete Cosine Transform (DCT)</strong> and move from the log spectrum to <strong>MFCCs</strong> (Mel-Frequency Cepstral Coefficients), here’s what happens:</p><p>We take several cosine waves, each with a different frequency, and compare them to the <strong>log spectrum</strong>. The idea is to see how well each cosine wave matches the original log spectrum. The better the fit, the higher the value. These values form the <strong>MFCCs</strong> — they essentially capture how much each cosine frequency contributes to the overall sound. Visually represented in below image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*dQB9umlHhQPj2gr0alGl1w.png" /></figure><h4><strong>How many coefficients do we use?</strong></h4><p>Traditionally, we take the first <strong>12–13 MFCCs</strong> because they carry the most important information, like <strong>formants</strong>, <strong>timbre</strong>, and the <strong>spectral envelope</strong>. These capture the key details for tasks like speech recognition. Higher coefficients tend to pick up on things like <strong>glottal</strong> information, which is often treated as noise and less relevant for such tasks. However, if we want more detail in sound, those higher coefficients can still be useful.</p><ul><li>The <strong>first few coefficients</strong> contain the bulk of the important information (like the shape of the sound).</li><li>We can further enhance MFCCs by calculating the <strong>first and second derivatives</strong> — known as <strong>delta</strong> and <strong>delta-delta</strong> coefficients. For delta, we subtract the current MFCC from the previous frame, and for delta-delta, we use the delta values.</li></ul><p>So, if we take <strong>13 MFCCs</strong>, adding delta and delta-delta coefficients gives us a total of <strong>39 coefficients</strong> per frame (13 original, 13 delta, and 13 delta-delta).</p><p>We have learnt everything about MFCCs now let look its advantages and disadvantages from our machine learning point of view</p><h4>Advantages of MFCCs:</h4><ul><li>They capture the <strong>big picture</strong> of the sound spectrum, ignoring fine details and noise, and focus on the important features like <strong>formants</strong>.</li><li><strong>Fine spectral structures</strong> (small details in the sound) are ignored, which is helpful because we usually don’t need them for tasks like speech recognition.</li><li>MFCCs perform well in both <strong>speech</strong> and <strong>music processing</strong>.</li></ul><h4>Disadvantages:</h4><ul><li>They are <strong>not robust to additive noise</strong>, meaning background noise can affect their accuracy.</li><li>MFCCs rely on <strong>feature engineering</strong>, which means we’re manually selecting the features rather than letting the model learn them on its own.</li><li>They aren’t great for <strong>sound synthesis</strong> — we can’t recreate the original sound from MFCCs.</li><li>In modern <strong>deep learning</strong>, we often use the <strong>mel spectrogram</strong> instead, as it offers more flexibility and better results.</li></ul><p>These features, like MFCCs, are manually designed for specific tasks, focusing on the information we think is most important. We choose features that fit our needs. However, if we want our machine learning model to <strong>automatically extract</strong> the features it needs, we can turn to <strong>deep learning</strong>. Deep learning models learn these features directly from the data, without us having to manually define them.</p><p>We can visualize the MFCCs as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*1DXaXHkpQJhcHlnQjKanYg.png" /></figure><h4>Applications of MFCCs</h4><h4><strong>Speech Processing</strong></h4><ul><li><strong>Speech Recognition</strong>: Used to identify spoken words.</li><li><strong>Speaker Recognition</strong>: Helps in identifying or verifying individual speakers.</li></ul><h4>Music Processing:</h4><ul><li><strong>Music Genre Classification</strong>: Classifying songs into genres like rock, jazz, etc.</li><li><strong>Mood Classification</strong>: Recognizing the mood or emotion conveyed by the music.</li><li><strong>Automatic Tagging</strong>: Assigning descriptive tags to music automatically based on its characteristics.</li></ul><p>As we finish our look at MFCCs, we’ve learned how these features help us understand sound the way we do. They are important for things like speech recognition and music classification. But there’s still a lot more to explore in audio processing! In the next blog, we’ll check out more <strong>frequency domain features</strong> that can help us learn even more about sound. Stay tunedthere’s plenty more to discover on our journey into audio features!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d6be522a345" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Mel Spectrograms: A Powerful Feature Extraction Tool for Audio Signals]]></title>
            <link>https://medium.com/@kunalkushwahatg/exploring-mel-spectrograms-a-powerful-feature-extraction-tool-for-audio-signals-3b68ff6fcf96?source=rss-e43672a1c885------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b68ff6fcf96</guid>
            <dc:creator><![CDATA[Kunal Kushwaha]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 13:38:01 GMT</pubDate>
            <atom:updated>2025-10-01T15:09:33.168Z</atom:updated>
            <content:encoded><![CDATA[<p>In the last blog, we explored the Short-Time Fourier Transform (STFT), which breaks down a signal into small frames, applies the Fourier Transform to each, and represents it in a time-dependent form. The result is a frequency vs. time heatmap, often called a “vanilla” plot. This shows frequency in a linear scale, measured in hertz.</p><p>However, humans don’t perceive sound in a linear way — we actually hear things more logarithmically. To better match how we hear, we can perform an experiment to explore this further.</p><h4>Psychoacoustic experiment</h4><p>We took two sound samples:</p><ul><li><strong>1st sample:</strong> C2 to C4 (65Hz — 262Hz)</li><li><strong>2nd sample:</strong> G6 to A6 (1568Hz — 1760Hz)</li></ul><p>Both have a frequency difference of about 200Hz. Now, you might think the difference between C2 and C4 would sound the same as the difference between G6 and A6. But when you listen, the gap in the first sample is much more noticeable, while the sounds in the second sample are much closer together.</p><p>This happens because humans perceive frequency in a logarithmic way — meaning, the lower the frequency, the more detail (or resolution) we can hear.</p><p>So, while the “vanilla” frequency representation (in Hertz) works well for showing amplitude, it doesn’t match how we hear frequency. To make it more perceptual, the <strong>mel scale</strong> was introduced.</p><h3>Mel spectrogram</h3><p>The <strong>mel scale</strong> works on a logarithmic basis, which means equal distances on the scale reflect the same “perceptual” difference in sound. For example, a frequency of 1000 Hz is equivalent to 1000 mels. This makes it easier to represent frequencies in a way that aligns with how we actually hear them and yes guess what mel means melody :).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*L0OBU5LuHHBPNmEYF8E1NA.png" /></figure><p>The experimental formula for this is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*mfB1Mxnrc7PpG3p0k5weEw.png" /></figure><h4>Recipe to extract Mel spectrogram:</h4><ol><li><strong>Extract the STFT</strong></li><li><strong>Convert the amplitude to decibels (dB)</strong></li><li><strong>Convert frequencies to the mel scale</strong></li></ol><ul><li>Choose the number of mel bands</li><li>Construct mel filter banks</li><li>Apply the mel filter banks to the spectrogram</li></ul><p>The first two steps are the same for a “vanilla” spectrogram. The new addition is the third step used for converting to the mel scale.</p><p>First, let’s break down what the <strong>mel scale</strong> is. It’s a way to represent perceived pitch, designed to match how our ears naturally interpret different frequencies. Unlike the standard frequency scale, which is measured in Hertz (Hz) and follows a linear pattern, the mel scale is nonlinear and better reflects how we actually hear sound. It compresses higher frequencies and stretches out the lower ones, because we perceive pitch differences more clearly at lower frequencies than at higher ones.</p><h4>A. Mel Band</h4><p>A <strong>mel band</strong> is a group of frequencies that aligns with how we perceive sound. When we divide the frequency spectrum into mel bands, we’re organizing it based on how we actually hear, rather than using the physical difference in Hertz. For instance, the gap between two low-pitched notes feels larger to us than the same gap between two high-pitched notes, even though the frequency difference might be identical.</p><p>Each mel band represents one of these perceptual divisions on the mel scale, grouping frequencies that sound close to each other. The number of mel bands you choose depends on the specific problem you’re solving, much like how you tune hyperparameters in deep learning models. Typically, people use anywhere from 50 to 130 mel bands.</p><h4>B. Construct mel filter banks</h4><p>The process of creating <strong>mel filter banks</strong> involves using the Fourier Transform. You can apply the standard Fourier Transform for this, where you use a single filter bank on frequency domain data. However, if you’re using the Short-Time Fourier Transform (STFT), you’ll need different filter banks for each frame, since the data is split over time.</p><p>To create mel filter banks from Fourier Transform data, you follow these steps:</p><p><strong>Decide on the frequency range</strong> you want to cover, typically from 0 Hz to the Nyquist frequency (half the sample rate of the audio). For example, if your sample rate is 44.1 kHz, your Nyquist frequency would be 22.05 kHz.</p><p><strong>Convert the frequency limits</strong> (the lowest and highest frequencies) to the mel scale using the mel frequency formula we mentioned earlier.</p><p><strong>Choose the number of mel filters</strong> you want. For example, you might use 6 filters for something like speech processing.</p><p><strong>Calculate the center frequencies for each filter</strong>:</p><ul><li>First, divide the mel range into equally spaced points based on the number of filters.</li><li>Convert those points back into regular frequencies (in Hz) using the inverse mel formula.</li><li>Since we’re working with discrete data, round those values to the nearest frequency bin.</li><li>Now, you have the center frequencies for each filter in Hz.</li></ul><p><strong>Design triangular filters</strong> for each mel band:</p><ul><li>Each filter is shaped like a triangle and covers a specific range of frequencies, with the peak of the triangle at the center frequency.</li><li>The filters overlap, so for each one, the triangle starts at zero from the previous filter, peaks at its center frequency, and drops back to zero at the next filter’s center frequency.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*L3S9b2ekGtg0zEykUp1Mdw.png" /></figure><p>By this process we get six triangular filters and the shape of filters will be let’s say M the frequency domain data we got by stft its shape be Y</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*_SO_p6Vvp3pB4jMT0A2AZQ.png" /></figure><p>By seeing this the shape we can say we have to do matrix multiplication of both the matrices and after that we will get Mel Spectrogram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*mzJo_CXWVKGhhOfD7u6Ujg.png" /></figure><p>Its shape is given by<strong> (#bands , #frames)</strong></p><p>After all the calculation we get the mel spectrogram which will be plotted as heatmap maps</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*_n1Ieks_1BasOMXb4oUMbw.png" /></figure><p>The only difference here from vanilla spectrogram is the y axis is not linearly represented it is represented in a ebay how humans hear that we earlier talked about in experiment.</p><p>If we extract and plot mel spectrogram in python for 10 bands it looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*-PbICoP3mZViNhQUbZdq8Q.png" /></figure><p>As we finish up our look at mel spectrograms, it’s clear how they give us a better understanding of sound by matching how we actually hear it. But we’re not done yet! In the next blog, we’ll explore the interesting concept of <strong>cepstrum</strong>, which helps us learn even more about sound. So, stick around to see how this cool tool can help us dig deeper into audio processing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b68ff6fcf96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zooming In: Understanding the Short-Time Fourier Transform]]></title>
            <link>https://medium.com/@kunalkushwahatg/zooming-in-understanding-the-short-time-fourier-transform-27c58f6a08ee?source=rss-e43672a1c885------2</link>
            <guid isPermaLink="false">https://medium.com/p/27c58f6a08ee</guid>
            <dc:creator><![CDATA[Kunal Kushwaha]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 13:37:45 GMT</pubDate>
            <atom:updated>2025-10-01T15:09:17.492Z</atom:updated>
            <content:encoded><![CDATA[<p>The Fourier Transform (FT) is a powerful tool for analyzing the frequency components of a signal. However, when applied to sound data, it has a limitation — it doesn’t tell us how the frequency content changes over time. Instead, it provides an average of each sine wave frequency over the entire time period. To overcome this, we introduce the Short-Time Fourier Transform (STFT), which helps us analyze frequency changes over time.</p><p>The Short-Time Fourier Transform (STFT) solves this problem by analyzing small segments of the signal over time. It takes a small window of the signal (with a specified window size) and computes the Fourier Transform for just that segment. By sliding this window across the entire signal, we can see how the frequency content changes over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/0*34xqBflFaEKNDryR" /></figure><p>To apply a window to the main signal x(k)x(k)x(k), we use the following formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/0*91iIvjZZ6KUh6u2R" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/0*TXOUSjMH3t7BLuK4" /></figure><p>There are two important terms to understand: window_size and frame_size. These may or may not be equal, but for simplicity, let’s assume they are equal for now. The window_size determines the portion of the signal we analyze at each step, and the frame_size controls how much we move the window as we slide it across the signal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/0*rXLgJfhz0jvlsW56" /></figure><p>We also encounter the term <strong>hop size</strong>, which refers to how far we move the window forward in time for the next segment of data. Essentially, it determines the step size between consecutive windows. We’ve discussed more about hop size in earlier sections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*b29_y3b5gJgkNsPs" /></figure><h4>Mathematical formula for DFT to STFT</h4><p>Earlier, for the full sine wave, we used the Discrete Fourier Transform (DFT) formula, which is expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*4754wb-gBctQHM4-" /></figure><p>The DFT helps us break down a signal into its frequency components over the entire time period.</p><p>For the Short-Time Fourier Transform (STFT), we use a new formula that depends on both the current frame m and the frequency k. The output of the STFT, denoted by S(m,k) is the result of applying the Fourier Transform to a specific frame of the signal. S(m,k) is the STFT output, where m represents the current frame and k represents the current frequency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*m9XYyY5sTn0QXejr" /></figure><p>The term x(n+mH) refers to the segment of the signal we are working on for that frame, where H is the hop size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*zt95RrdUvn1pJsZx" /></figure><p>Further x(n+mH).w(n) represents the windowed portion of the signal. w(n)is the window function applied to the signal segment at frame m.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*tGe8om0hWgO5zIio" /></figure><p>Finally, the exponential term is multiplied by the windowed signal to compute the Fourier Transform for that frame. This gives the complex coefficients, which contain both the magnitude and phase information for that specific frame and frequency.</p><p>Okay so now lets talk about what output we get</p><p><strong>DFT (Discrete Fourier Transform):</strong></p><ul><li>Outputs a <strong>spectral vector</strong> with a number of frequency bins.</li><li>Produces <strong>N complex Fourier coefficients</strong>, where N is the number of samples in the signal.</li></ul><p><strong>STFT (Short-Time Fourier Transform):</strong></p><ul><li>Outputs a <strong>spectral matrix</strong> with dimensions (# frequency bins, # frames), representing frequency content over time.</li><li>Produces <strong>complex Fourier coefficients</strong> for each frame and frequency bin.</li></ul><h4>Frequecy bins</h4><p>Frequency bins are used to represent different ranges of frequencies in a signal. They range from 0 to half of the sampling rate (sr/2). In the frequency domain, these bins act like the x-axis on a plot. For instance, if you have 501 frequency bins, each bin represents a specific frequency range.</p><p>Imagine a 30 cm ruler where each mark represents a frequency bin. Between two marks, say bin 367 and bin 368, there is a specific range of frequencies, like 5678 Hz to 5976 Hz (just an example).</p><p>We only need to consider frequencies up to sr/2 because frequencies beyond this point are a mirror image of those below it. This means that the range from 0 to sr/2 contains all the unique frequency information we need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/0*XgqmDzGWHUYUigYJ" /></figure><h4>Frames</h4><p>To calculate the number of frames we do it by formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*YYjRFsFSPAdS2hjk" /></figure><p>Mostly we take frame size to be multiple of 2 like 512 , 1024 …………… for efficiency</p><p>Lets take some example calculation</p><ul><li>Signal = 10K samples</li><li>Frame size = 1000 ●</li><li>Hop size = 500</li></ul><p># frequency bins = 1000 / 2 + 1 = 501</p><p># frames = (10000–1000) / 500 + 1 = 19</p><p>So, if you have a signal with these parameters, your Short-Time Fourier Transform (STFT) will result in a matrix of size (501, 19).</p><h4><strong>Frequency-Time Trade-Off</strong></h4><p>In the Short-Time Fourier Transform (STFT), there’s a trade-off between frequency and time resolution.</p><ul><li><strong>Increasing Frame Size</strong>: If you use a larger frame size, you get better frequency resolution. This means you can distinguish between closely spaced frequencies more clearly. However, the downside is that you lose some accuracy in timing, making it harder to pinpoint exactly when those frequencies change.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*9T5XcGPvisO9LouG" /></figure><ul><li><strong>Decreasing Frame Size</strong>: On the other hand, a smaller frame size improves time resolution. This lets you track changes in the signal more precisely over time. But with a smaller frame size, the frequency details become less clear.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*lWqRVotnurpA8WK-" /></figure><p>The choice of frame size depends on whether you need more precise frequency details or better time tracking for your analysis.</p><h3>Hann Winow</h3><p>We do not take rectangle window as it creates discontinuity at the edges rather we 90 percent of the time we use bell shape curve called hann window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/0*9Eoe07PsGbLdDB88" /></figure><p>It is given by formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*QZYv2mC2STXus9dz" /></figure><p>Lets try to apply hann window visually</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*oePcCRpwpI3LzYuV" /></figure><p>The edge data is fading and not completely wiping off which makes the curve of actual sound smooth.</p><p>On visualising the short time fourier transform plotting the depth of sound ie energy as decibels we get this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/0*G3JdCatpKFfC81Ey" /></figure><p>You need to remember this image in the next blog we will dive deep into this and mel spectrogram .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27c58f6a08ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Basics: The Complex Math of Fourier Transforms in Sound Analysis]]></title>
            <link>https://medium.com/@kunalkushwahatg/beyond-basics-the-complex-math-of-fourier-transforms-in-sound-analysis-75648d0aac5c?source=rss-e43672a1c885------2</link>
            <guid isPermaLink="false">https://medium.com/p/75648d0aac5c</guid>
            <dc:creator><![CDATA[Kunal Kushwaha]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 13:37:17 GMT</pubDate>
            <atom:updated>2025-10-01T15:08:48.687Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous post, we explored the visual side of the Fourier Transform. In this blog, we’ll dive into the mathematical aspect. We’ll be working with complex numbers, a concept you might remember from high school math. So, let’s get started and break down the math behind this powerful tool!</p><p>A complex number can also be represented in exponential form as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/0*C4J1BOMqG5vM0__E" /></figure><p>where ∣c∣ is the magnitude (or modulus) of the complex number, and γ is the phase angle. In this form, the complex number is expressed in terms of its magnitude and phase, making it easier to represent on the complex (imaginary) plane.</p><p>Now, we’ll take the phase and magnitude equations we discussed earlier and encode them into the same complex equation format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*x9xKT89Rxa8rrOMt" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/0*fT6StGA7uRKHT4bU" /></figure><p>We’ll represent each frequency with a complex number, denoted as Cf​, where f stands for each specific frequency. This allows us to express both the phase and magnitude of each frequency component in a compact, efficient way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/0*mDHy2iuJID3GyW4x" /></figure><p>Where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/0*V8CmwjzVabkY8DeJ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/0*17Nf7yMax0Ubur2O" /></figure><p>The pink box represents the magnitude of the complex equation .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/0*tfNRrQBGnMnfv9yl" /></figure><p>The blue box represents the phase of the equation .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/0*L4sQQNjK9J6m5dfw" /></figure><p>Root(2) divided by df for its normalization and — ve sign is used for rotation of phase in clockwise direction.</p><p>Continuous audio signals are typically represented as functions from time to the set of real numbers where time is real number and amplitude of signal is also real number</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/0*-VTjeHY3Rrh2xy39" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*ngUWRSgY37pVDg4I" /></figure><p>When working with the complex Fourier Transform, the representation changes to incorporate complex numbers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/0*ecy71-gxnmZFlaMC" /></figure><p>In the complex Fourier Transform, g^(f) takes a frequency f as input and produces a complex number cf for that frequency. This shows how our representation shifts from the time domain to the frequency domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/0*FkZwkcl9fdoe34Qy" /></figure><p>We can also visualize this by plotting a specific frequency f1​ in the complex plane. This plot shows the complex number cf1 ​​, illustrating the magnitude and phase of the frequency component f1 in the frequency domain.</p><p>Okay so now it’s time for some different way of representation. We earlier represented this equation as g^(f) which was</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*QctBPcOHjnF6B5Dulo0IZg.png" /></figure><p>We can represent the equation as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/0*L-voePAxEJMQR131" /></figure><p>Lets try to decode this formula</p><p>We know that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/0*cWV9_VQrDL9m8jIm" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/0*fPkzif7h6nR2C2d3" /></figure><p>So it contains real and imaginary part</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*Ibc-zy-Fr-mYgwrE" /></figure><p>Where magnitude can be represented by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*RogHrx6qiegvichy" /></figure><p>Which is equal to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/78/0*PahBCv1PN8jPb5vq" /></figure><p>If we compare them both we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/0*cbOMFKft8Iu4vqhR" /></figure><p>Similarly, phase can also be represented as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/0*80z6vI33OLhA8xPA" /></figure><p>Okay so now lets do visualize the equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/0*G1oQDpi_lq07Ris8" /></figure><p>Let’s break down how we represent our signal g(t)g(t)g(t) using a specific frequency.</p><p>Suppose g(t) is our original signal, which could be represented as an array of values at discrete time steps, like [0.3, 0.6, 0.23, …]. For example, if the time gap between samples is 0.001 seconds, we have values like 0.3 at 0.001 seconds, 0.6 at 0.002 seconds, and so on. The time array is [0.001, 0.002, …].</p><p>Consider a frequency of 2 Hz. This frequency might represent one of the sine waves that contributed to the overall signal. To analyze its contribution, we use the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*JrF5qDV1xbKSbJmRxRaIYg.png" /></figure><p>Here, we replace the integral with a summation over very small time intervals of 0.001 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*8iXhoEL6uF7h7XJnkLt3yQ.png" /></figure><p>represents how the signal at each time step aligns with a sine wave of 2 Hz.</p><p>This process generates an array of values in the complex plane for the 2 Hz frequency, represented by the blue line in the image below. The summation of these values gives the net magnitude and phase of the 2 Hz frequency component in the entire signal, which is shown as a green dot. This green dot represents the similarity of the sine wave with a frequency of 2 Hz to the original signal or sound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/0*7EPcWEUS2fZHmZnj" /></figure><p>If a particular frequency is not present in the signal, the summation for that frequency will be zero. In this case, when plotted, the green dot representing the net magnitude and phase of that frequency will be at the center of the complex plane. This indicates a symmetric figure around the origin, and the net similarity of that frequency with the signal will be zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/0*6WK74Iuj5vlK0oj9" /></figure><p>Finally, if we plot all the frequencies on the x-axis, ranging from 0 Hz to 22,100 Hz (or the maximum frequency in our signal), and on the y-axis we plot the magnitude of ghat(f) for each frequency, we get a frequency domain representation. This plot shows how much each frequency contributes to the overall signal, providing a clear picture of the signal’s frequency components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/0*YXPEaC9BcBbJ8SbZ" /></figure><p>Having understood how to move from the time domain to the frequency domain, let’s look at how to go in the reverse direction. To convert a signal from the frequency domain back to the time domain, we use the Inverse Fourier Transform. This process reconstructs the original signal by combining all the frequency components with their respective magnitudes and phases.</p><h4><strong>Inverse Fourier transform</strong></h4><p>If I represent inverse Fourier transform in one formula it is something like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*T3xQyCcrbpEKl5a8" /></figure><p>If I represent it as image its some thing like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*Vu5sfzcDXwCi1SwD" /></figure><p>Let’s break down the formula</p><p>f represents the pure tone frequency one frequency that helped in making the main signal and the exponential term</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/87/0*f9PILluWZwCuXgWl" /></figure><p>It will represent a sine wave with f frequency a normal sine wave</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/0*yUTBfJyKkme5emwg" /></figure><p>To determine the contribution of each sine wave to the overall signal, we use its weight cf. This weight adjusts the amplitude and phase of the sine wave. By multiplying the pure tone (sine wave) by its weight cf which includes both the magnitude and phase information, we can assess how much that specific sine wave contributes to the entire signal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/0*scNcol_YTrMQ0-GC" /></figure><p>Finally, we sum up the contributions from all the frequencies by integrating them. This process combines all the weighted sine waves to reconstruct the original signal in the time domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SUZpo6n7DaQVRjQ8" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75648d0aac5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fourier Transform Unveiled: A Visual Journey into Sound Signals]]></title>
            <link>https://medium.com/@kunalkushwahatg/fourier-transform-unveiled-a-visual-journey-into-sound-signals-70e8bf233214?source=rss-e43672a1c885------2</link>
            <guid isPermaLink="false">https://medium.com/p/70e8bf233214</guid>
            <dc:creator><![CDATA[Kunal Kushwaha]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 12:51:51 GMT</pubDate>
            <atom:updated>2024-10-09T13:36:33.211Z</atom:updated>
            <content:encoded><![CDATA[<p>We have worked on the time domain of sound in past series , in this blog we will be diving into frequency domain and to go to frequency domain from time domain you need a magic of mathematics called<strong> Fourier transform. </strong>This blog will be more story type in paragraphs with so many plots.</p><p>The <strong>Fourier Transform </strong>is a mathematical tool that converts a signal from the time domain into the frequency domain. It takes a complex signal and breaks it down into simple sine waves, revealing the signal’s amplitude and phase at various frequencies.</p><p>Simply put, the Fourier Transform lets you see which frequencies are in a signal and how strong each one is.</p><p>So we will be going through how can we convert a full fledged signal on time domain to frequency domain .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*egabc7ekljbM6LcD" /></figure><p>A sound is made up of a combination of various frequencies. Sometimes, a sound is dominated by one frequency or a narrow range of frequencies, but it’s actually the combination of all these frequencies at different magnitudes that creates the complete sound.</p><p>You can experiment with combining different frequencies to create sounds from <a href="https://teropa.info/harmonics-explorer/">here</a>. It is pretty good website for visualization of sound waves.</p><p>We can plot sound wave like this which is combination of various sine waves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dSuiWxu74hdXQmAK" /></figure><p>The specifications of the sound wave plot are as follows:</p><ul><li>The total duration of the sound is about 1.5 seconds.</li><li>The length of the signal (or the size of the magnitude array) is 33,968 samples.</li><li>The duration of each individual value in the array is approximately 4.53 × 10⁻⁵ seconds, calculated using the formula d=1/sampling rated.</li><li>For 400 values combined, the total duration is 0.0019 seconds.</li></ul><p>If we zoom in the 400 samples around 0.0019 sec duration from earlier graph from 10000 to 10400 from whole signal we get this graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MHixO0J8dNoefLcA" /></figure><p>Now, let’s consider plotting a sine wave on top of the previous sound wave. If we use a sine wave with a frequency of 200 Hz and a phase shift of 0.55 radians, it will look like a smooth, repeating curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lH-YPC1PtaT2N1Fp" /></figure><p>It seems that the contribution of the sine wave with a frequency of 200 Hz and phase of 0.55 radians isn’t significant in shaping the sound, as its frequency and phase don’t align closely with the main components of the sound.</p><p>Let’s adjust the sine wave to better match the signal. If we try a frequency of 523 Hz (which is closer to the dominant frequencies) and keep the phase at 0.55 radians, the sine wave should better contribute to the overall structure of the sound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DUpAhXLT33oj1Tvq" /></figure><p>This new sine wave looks very close to the original sound, so we can say its contribution is significant. We can judge this visually, but how does a computer determine if the waves are similar?</p><p>To do this, we calculate the area between the two curves. If the area is positive and large, it means the waves are similar and the sine wave’s contribution or amplitude is high for that part of the signal.</p><p>In the image below, there’s a negative area, which indicates that the waves are not very similar. The current frequency is 300 Hz, so adjustments may be needed to better match the signal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aFy0rhN1f0jMt1iR" /></figure><p>Let take other sine wave the below image shows a positive and large area between the curves, which indicates a high similarity between the sine wave and the original signal. With a frequency of 523 Hz and a phase of 0.55 radians, this sine wave contributes significantly to the signal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GPazckSfXKqTFzu9" /></figure><p>To determine the contribution of each sine wave to the signal, we need to calculate the area between the sine wave and the original signal for different frequencies. The larger the positive area, the greater the magnitude or contribution of that sine wave to the signal.</p><p>By doing this for various frequencies, we can create a plot of the signal in the frequency domain, showing which frequencies are most prominent.</p><p>While we’ve discussed how to visualize this process graphically, we also need a mathematical approach for computation and calculation. Let’s dive into the mathematical expressions and techniques used to determine the contribution of each sine wave more precisely.</p><p><strong>Understanding the formula behind Area</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/0*eNK9ou67CKVBKjFA" /></figure><p>In mathematical terms, if<strong> S(t)</strong> represents our signal and <strong>sin⁡(2πft+ϕ)</strong> represents the sine wave, multiplying these two functions and integrating the result helps us calculate the area between them. If the signal and the sine wave have different signs at a given point, the product will be negative. By integrating over time, we find the total area, which tells us how much the sine wave contributes to the signal.</p><p>To determine the best phase for the sine wave, we need to maximize the area calculated between the signal and the sine wave. We do this by testing different phase values from 0 to 1. By finding the phase that gives us the largest positive area, we can identify the phase that best aligns the sine wave with the signal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*1ci-jaM4iZR-w8A-" /></figure><p>We test frequencies ranging from 0 to the sample rate. The frequency that results in the largest positive area indicates the frequency that best matches the signal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/0*u4leQuWUi7WQ_LK_" /></figure><p>By finding the optimal frequencies and phases, we generate multiple sine waves that represent different components of the signal. Each sine wave corresponds to a specific frequency and phase. When we combine (or superimpose) these sine waves, we reconstruct the complete sound signal , something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9acHwFavPQPryxPU" /></figure><p>we created the red signal by superimposing all the blue signal you can play we this by a website link I gave you earlier.</p><p>Okay so lets go back to no. 523 :) , the earlier sound wave we took whose freq 523 wave was highly correlating with our signal and lets talk more about it. If we plot the frequency domain of that sound it looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9yjRu_AFphfR4kJR" /></figure><p>For our signal, the plot indicates that the sine wave at 523 Hz has a higher contribution compared to the 1046 Hz frequency and its other harmonic components. That is actually what we saw in visualization the 523hz frequency was the most similar curve.</p><p>We’ve covered some visualization of the Fourier Transform, but now it’s time to dive into the mathematical approach. Buckle up, because we’re about to explore the complex world of Fourier analysis. Before you move on to the next article, make sure to brush up on your high school complex numbers , and yes do not forget upper two formulas as we will be using it later. See you soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70e8bf233214" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking Down Signals: A Guide to Time and Frequency Domains]]></title>
            <link>https://medium.com/@kunalkushwahatg/breaking-down-signals-a-guide-to-time-and-frequency-domains-970e6dd883d5?source=rss-e43672a1c885------2</link>
            <guid isPermaLink="false">https://medium.com/p/970e6dd883d5</guid>
            <dc:creator><![CDATA[Kunal Kushwaha]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 12:51:35 GMT</pubDate>
            <atom:updated>2024-10-09T13:35:27.232Z</atom:updated>
            <content:encoded><![CDATA[<p>From our previous discussions, you should now have a good grasp of what sound is and how it’s stored in electronic devices, represented as signals. Now, let’s move a bit closer to machine learning.</p><p>When training a machine learning model with audio data, you might think of using the discrete time-domain amplitude values as features — basically feeding the raw time-series data directly to the model. While this can work with time-series models like RNNs or LSTMs, there are some challenges.</p><p>First, consider the size of the dataset: with a sampling rate of 44 kHz, one second of audio produces 44,000 data points. That’s a massive amount of data for just one sample. Even if you can handle this large dataset, models like LSTMs or even large transformers might struggle to make sense of it all. They won’t easily pick up on key features like timbre or other characteristics of the sound.</p><p>To address this, we use different representations of audio data, such as MFCCs (Mel-frequency cepstral coefficients). These provide the essential features needed for the model, making the data much more manageable and meaningful for learning.</p><p>To dive deeper into these features, we’ll start by exploring the Signal Domains — frequency and time domains in detail in this blog.</p><h4><strong>Time Domain</strong></h4><p>The time domain refers to the analysis of a signal’s amplitude or intensity as it varies over time. The time domain is all about looking at how a signal’s amplitude or intensity changes over time. It’s like watching the ups and downs of a wave as it moves across a timeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*GTqfmSzZtd_PJEjNV41O8A.png" /></figure><h4><strong>Frequency Domain</strong></h4><p>The frequency domain represents a signal by analyzing its frequency components, showing how much of the signal’s energy is distributed across different frequencies. It’s like taking the signal apart to see which frequencies are present and how strong they are. There is whole process for conversion of time to frequency domain we will talk about it later</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*V4WWDPO_chv-CX-dILyPPw.png" /></figure><h4><strong>Time Domain Feature Representation</strong></h4><p>When sound is sampled at 44,100 Hz, it means that 1 second of audio is represented by an array with 44,100 samples. Each sample captures about 0.0227 milliseconds of sound, which is much shorter than what humans can typically perceive (we generally perceive sounds longer than 10 milliseconds).</p><p><strong>Frames:</strong> In audio processing, frames refer to short, fixed-duration segments of the audio signal used for analysis. Each frame usually spans a small portion of the sound, typically between 10 to 40 milliseconds. This allows for a more detailed examination of the signal’s characteristics in that moment, breaking it down into perceivable chunks. The duration of a frame is often represented as “df” and can be calculated using a specific formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*YDQ_t3tq2vwgiEVmPspteg.png" /></figure><p>K represents the number of samples per frame. For a sampling rate of 44.1 kHz (44,100 samples per second) and K=512 samples per frame, the duration of one frame can be calculated using the formula and will be 11.6 ms. This means each frame lasts for about 11.6 milliseconds. This duration is around the threshold of human hearing perception, as sounds shorter than this are generally harder for humans to discern.</p><p>With framing some problems arise one of that is spectral leakage so lets look into it</p><h4><strong>Spectral Leakage</strong></h4><p>This happens because the signal isn’t perfectly repeating within the time we’re observing it, which creates abrupt changes at the edges. As a result, some of the signal’s energy spreads into nearby frequencies, making the frequency representation less accurate. This can make it harder to accurately analyze the true frequency components of the signal. Its visual representation is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*SinGf_YdcVVqr1RS" /></figure><p>Endpoints are Discontinuous and these discontinuities appear as high frequency components not present in the original signal .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/0*peP2CDV0iJV5BOeY" /></figure><p>The 6000 frequency signal arises due to spectral leakage only , so we can fix this problem by the process called windowing</p><h4><strong>Windowing</strong></h4><p>Windowing is a technique used in signal processing to improve the accuracy of frequency analysis. It works by smoothing the edges of a signal to reduce distortions. This helps to get a clearer view of the signal’s true frequency components. By smoothing the edges, windowing limits how signal energy spreads across frequency ranges, leading to a more precise frequency representation.</p><ul><li><strong>Apply the windowing function to each frame</strong>: This means using a specific mathematical function to adjust the signal’s edges in each segment of data you’re analyzing.</li><li><strong>Eliminates samples at both ends of the frame</strong>: This is because the windowing function makes the signal values at the edges close to zero, which reduces distortion caused by abrupt changes.</li><li><strong>Generates a periodic signal</strong>: The result is that the signal appears smoother and more periodic, which helps in better frequency analysis.</li></ul><p>Lets understand it mathematically</p><p>There is a function defined as Hann window function w(k) for its operation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/0*Q4G-gDDWn-heHXs2" /></figure><p>It looks graphically like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/0*zUIEnOYlUOg3rquI" /></figure><p>The process of Hann Windowing involves the multiplication of sample s(k) with window function w(k)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*uef5S1uSyWZ4WyS6kDHX2A.png" /></figure><p><strong>For graphical point of view</strong></p><p><strong>S(k)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*v8jMrheAQPeLn3JT" /></figure><p><strong>W(k)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*ITKgATTGHcclopWw" /></figure><p><strong>S(k)*W(k)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*-8wIArk3d6nh9fwi-vNNJA.png" /></figure><p>After windowing when we join them together the huge amount of data between every sample is missing given in fig so in this way of feature will have lots of empty data or null data that can impact teh data in bad way</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/0*fU3lbncMt66EqgHg" /></figure><p>The solution for this is overlapping frame it means we can overlap the initial part of k sample with the ending part of k-1 sample which leads to less data loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*w5EDv3blSJKjzMyzHmqFtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*_UGvbeb2TbTnRBVXUHHw6g.png" /></figure><p>There are few terms related to above figures</p><ul><li>Hop length : Length of part of frame that is not overlapped.</li><li>Frame size : hop length + overlapped part</li></ul><p>To extract features from signals in the time domain, you need to follow a sequence of steps that is called time domain feature pipeline. A visual representation of time domain feature pipeline looks something like this finally</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*6YmKjPGflkRoY5Cj" /></figure><p>Do you know that we can go from time domain to frequency domain by a magic called Fourier transform well we are going to learn about it later</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*Oq3J6NS1rKW884If40OaUg.png" /></figure><p>Frequency domain also follows some pipeline to extarct features from it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*GKEjWRJ7zbfmBVkg2xjxWA.png" /></figure><p>We got everything to extract features from time domain let us ignore frequency domain features for now as we will study about Fourier transform first , so in time domain there are some features that a simple ml model can use like Amplitude envelop , zero crossing rate etc</p><h4>Amplitude Envelope</h4><p>Max amplitude value of all samples in a frame , means max value of amplitude in respective frame.</p><ul><li>Gives rough idea of loudness</li><li>Sensitive to outliers</li><li>Onset detection, music genre classification</li></ul><p>Outliers : it means if the frame contains all the value as zero but the one data value will be very high so the Amplitude representation of that frame will be high but that is not the case.</p><p>as always lets see its mathematical formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/0*twLa5H0kHfSebmBm" /></figure><p>graphically it looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*Lo2SgNxiEr51_j9M" /></figure><h4><strong>Root Mean Square Enegry</strong></h4><p>Rms value of all the values in frame to get the one single energy representation of the frame.</p><ul><li>indicator of loudness</li><li>Less sensitive to outliers</li><li>Audio Segmentation , music genre classification</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/0*mTu8531UaR65hcUX" /></figure><h4>Zero Crossing rate</h4><p>Number of times a signal crosses the horizontal axis in sgn is sign function it gives 1 if +ve 0 if zero and -1 if negative so by simple algo we can get if it touches x axis.</p><p>graphical</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*Qo2BnANQF9SbvQiLHst_Ew.png" /></figure><p>Mathematical Formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/0*n6eduSER0WAa4mv_" /></figure><ul><li>Recognition of percussive(zero crossing rate is very random) vs pitched sound(stable)</li><li>Monophonic pitch estimation</li><li>Voice/unvoiced decisions for speech signal.</li></ul><p>So finally we came to end of this blog we looked into how to get time domain its problems and its features i next blog we will learn about Fourier transform because of which we will move to the frequency domain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=970e6dd883d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding audio signals]]></title>
            <link>https://medium.com/@kunalkushwahatg/understanding-audio-signals-8f078dc3f6bc?source=rss-e43672a1c885------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f078dc3f6bc</guid>
            <dc:creator><![CDATA[Kunal Kushwaha]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 12:51:18 GMT</pubDate>
            <atom:updated>2024-10-09T13:35:03.512Z</atom:updated>
            <content:encoded><![CDATA[<p>In the last blog, we talked about the basics of sound and its terminologies the link to the blog is here, so in this blog, we will dive deep into signals as computers transfer sound in terms of signals and its processing .</p><p>Until now, we know that sound is a variation in air pressure that our ears perceive. Let’s dive into how these sounds are captured and reproduced digitally.</p><p><strong>How Sound is Recorded and Played.</strong></p><ul><li><strong>Sound Capture</strong>: A microphone converts sound waves into an electrical analog signal.</li><li><strong>Pre-amplification</strong>: The analog signal is amplified to a usable level.</li><li><strong>Analog-to-Digital Conversion (ADC)</strong>: The amplified signal is sampled and quantized to convert it into a digital signal.</li><li><strong>Digital Storage</strong>: The digital signal is stored on a recording device or computer.</li><li><strong>Playback</strong>: During playback, the digital signal is converted back to an analog signal and output through speakers.</li></ul><h3>How We Record Sound</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/0*Cn0aMkdoLXvyiFoX" /></figure><h3>How We Play Sound</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/0*v0NkZgU1KARoSQ0c" /></figure><p>This was some basic structure showing how we record or play sound we do not need to dive deep into it as our aim is to create features from signal but wait what is signal .</p><p>A <strong>signal</strong> is any kind of data or information that varies over time and is used to convey information. It can be in different forms, such as electrical, sound, light, or radio waves. There are two types of signal analog and digital .</p><h4><strong>Analog Signal</strong></h4><p>Analog signals are continuous signals that change smoothly over time, with an infinite number of values within a given range. This means they can represent data with a lot of detail because the signal flows without any jumps or steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*v-IbwGV7omv05SBUDux33Q.png" /></figure><p>However, because there are so many possible values — even within just one nanosecond — it can become difficult to process and manage these signals efficiently. That’s why we often convert analog signals into <strong>digital signals</strong>, which are easier to handle and process with modern technology.</p><p>Now you might be thinking what is a digital signal</p><h4><strong>Digital Signal</strong></h4><p>Digital signals are sequence of discrete signals that represent data using some amplitude value . Unlike analog signals, which can have an infinite number of values, digital signals have a finite set of distinct values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*lVhldLESPyjYKaKHpWTZug.png" /></figure><p>Here the dots are only called digital signal the the whole curve is analog signal now lets learn how can we convert analog to digital signal.</p><h4><strong>Analog to Digital Conversion</strong></h4><p>There is a term called as sampling for this conversion ,</p><p><strong>Sampling</strong> is the process of converting a continuous analog signal into a discrete digital signal by measuring the signal’s amplitude at regular intervals.So what we are doing is taking the the amplitude points from the analog signal as a regular interval <strong>T ( </strong>this T is not the time period of sine curve it is time period of sampling rate ).</p><p>The rate at which the signal is sampled is called the <strong>sampling rate</strong>, measured in samples per second or Hertz (Hz). You must remember the term sampling rate ( sr ) as this will be used whole in this series .</p><p>By this formula to can locate samples .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/0*w_qOE-WGoZrqbm-9" /></figure><p>Sampling rate is generally inverse of time period</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/0*t5E_AuBvwDu8sRag" /></figure><p>We lose lot of info if sample rate is low . Higher the sampling rate higher the details of signal .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*lLVrNT4IKLx7rGMB" /></figure><p>I hope you got a clear understanding of how sounds are represented in signals and how analog signals are converted to digital signals. So let&#39;s talk about some words and their definitions that we will be using further in the series.</p><h4><strong>Nyquist frequency</strong></h4><p>Nyquist frequency is used to avoid aliasing so lets talk about aliasing first</p><p>Aliasing occurs when a continuous analog signal is sampled at a rate lower than twice its highest frequency, causing different signals to become indistinguishable from each other in the sampled data.This effect results in distortions or artifacts in the reconstructed signal, as high-frequency components are incorrectly represented as lower frequencies.</p><p>In the below image, the frequency of the actual signal is very high, let’s say 10 kHz, but the sampling rate is around 1000 Hz. So, the Nyquist frequency(half of sr) will be 500 Hz. All the frequencies above this Nyquist frequency will be misrepresented as lower frequencies, leading to distortions or artifacts in the sampled signal. This effect is known as aliasing, where high-frequency components are incorrectly mapped to lower frequencies, making the reconstructed signal inaccurate. To prevent aliasing, it’s crucial to sample at a rate at least twice the highest frequency of the original signal or to use a low-pass filter to remove frequencies above the Nyquist frequency before sampling.</p><p>Orange line is real sound while voilet line is digital sound.Here sound is completely misinterpreted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/0*Sax2-nKL4Q3ZVkYc" /></figure><p>The Nyquist frequency is half of the sampling rate of a digital signal and represents the highest frequency that can be accurately captured when converting an analog signal to digital. According to the Nyquist-Shannon sampling theorem, to avoid aliasing (where different signals become indistinguishable) and to accurately reconstruct the original analog signal, the sampling rate must be at least twice the highest frequency present in the signal.</p><p>For example, if the sampling rate is 44.1 kHz (commonly used in audio CDs), the Nyquist frequency is 22.05 kHz. This means that frequencies above 22.05 kHz cannot be accurately captured or represented in the digital signal, as they would cause aliasing and distort the reproduced sound.</p><h4>Quantization</h4><p>Quantization is the step in analog-to-digital conversion where the continuous amplitude values of an analog signal are rounded to the nearest discrete level, creating a digital representation. After the signal is sampled at regular intervals, each sample is assigned to the closest value within a set of predetermined levels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/0*w3XeDie0hG74oi9I" /></figure><p><strong>Resolution and Bit Depth:</strong> The resolution, or bit depth, determines the number of possible values (levels) on the y-axis that a signal can take. Higher resolution means more levels and a more accurate representation of the original analog signal. For instance, a CD typically has a resolution of 16 bits, which allows for 2^16 = 65,536 discrete levels.</p><p><strong>Memory Calculation for Audio:</strong> To calculate the memory needed for 1 minute of audio sr =44100hz , bit = 16</p><p>Memory for 1 second = Sampling Rate × Bit Depth × Number of Channels</p><p>= 44,100×16×1=705,600bits</p><p>MBs = (1 sec sample bits X 60 sec) / ( 1024 x 1024 bits )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/0*Yhl23hAv2v3KUP7T" /></figure><p>This was the formula that we need to get the size of any sound signal stored in cd or memory .</p><p>In this blog we understand about conversion of sound to signals digital signals analog signals its terms etc so our basics is almost ready for working with mathematics in signal processing .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f078dc3f6bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to sound and its basic features]]></title>
            <link>https://medium.com/@kunalkushwahatg/introduction-to-sound-and-its-basic-features-d8623489623e?source=rss-e43672a1c885------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8623489623e</guid>
            <category><![CDATA[audio-processing]]></category>
            <category><![CDATA[sound]]></category>
            <category><![CDATA[signal-processing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kunal Kushwaha]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 12:50:27 GMT</pubDate>
            <atom:updated>2024-10-09T13:34:34.210Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello and welcome to this series of blogs on audio processing for machine learning! Whether you’re a beginner or looking to deepen your understanding, this guide is here to help you navigate the fundamentals and practical aspects of audio processing. This blog is inspired from a detailed YouTube course from A<a href="https://youtube.com/playlist?list=PL-wATfeyAMNqIee7cH3q1bh4QJFAaeNv0&amp;feature=shared">udio Signal Processing for Machine Learning playlist</a> <a href="https://www.youtube.com/@ValerioVelardoTheSoundofAI">by Valerio Velardo — The Sound of AI</a>, and most of the images used here are taken from there, here in this series we will learn audio processing, and building feature for machine learning models.</p><p>Before we jump into the more complex stuff, let’s start with the basics and get familiar with some key sound terms. Sound is basically a mechanical wave that happens when particles in a medium (like air, water, or even solids) vibrate. This wave has certain properties — frequency, amplitude, and timbre — that determine things like pitch, loudness, and the unique quality of the sound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*HtAM5muUQS6GTDKd" /><figcaption>how sound travels</figcaption></figure><p>Now, let’s talk about waveforms. A waveform is just a visual representation of how an audio signal changes over time. It shows the ups and downs in air pressure or electrical signals that match the sound you’re hearing or recording. By looking at a waveform, you can get a sense of the sound’s frequency, intensity, and timbre, which are all important for understanding the sound’s pitch, how loud it is, and its overall vibe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/0*1RTQ5n7lgk7cwmDc" /><figcaption>A plot of sound in the time domain in Python</figcaption></figure><p>Waveforms can be classified into two main types: periodic and aperiodic. Periodic waveforms repeat at regular intervals and are associated with musical tones, while aperiodic waveforms do not have a repeating pattern and are often related to noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/0*8VgzqmIlCJK6pRbq" /></figure><p>Let’s break down some important sound concepts.</p><p><strong>Frequency</strong> is all about how often a waveform completes a cycle in one second, and it’s measured in Hertz (Hz). In simpler terms, frequency determines the pitch of a sound — higher frequencies mean higher pitches, like a bird chirping, while lower frequencies are more like the rumble of thunder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*m6m51TDMJZgTLkr-_IYfLA.png" /></figure><p><strong>Amplitude</strong> is about how big or small those waves are. It reflects the strength or intensity of the sound, which directly relates to how loud it is. Bigger waves (higher amplitude) mean louder sounds and smaller waves (lower amplitude) mean quieter sounds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*shubiBAMqn1XFXHsGj1yQQ.png" /></figure><p><strong>Phase</strong> might sound a bit technical, but it’s just about where a waveform is at any point in time compared to a reference point. Phase is crucial when we have multiple sound waves interacting because it affects how they align and mix, which can change the sound’s quality and spatial feel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*Hd8ey0uLSaocjCUIzn6dOA.png" /></figure><p>Speaking of loudness and pitch, just remember: larger amplitude means a louder sound and higher frequency means a higher-pitched tone. Most humans can hear sounds ranging from 20 Hz to 20,000 Hz (20 kHz). Anything below 20 Hz is infrasound — think of really deep, low rumbles — and above 20 kHz is ultrasound, which is too high-pitched for us to hear but perfect for animals like dog whistles!</p><p>Here is the frequency chart of different animals</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/0*TuzpsjsOCimt6-h-" /></figure><p>Now let&#39;s dive into some mathematical relation of pitch with frequecny</p><p>The pitch of a sound is mathematically related to its frequency by the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*Ug9ZGQb5Lxv8jCZkQgdBnQ.png" /></figure><p>where:</p><ul><li>f is the frequency of the note,</li><li>n is the MIDI number of the note,</li><li>440 Hz is the frequency of the A4 note, which is the standard tuning pitch.</li></ul><p>This formula helps convert the MIDI note number n into its corresponding frequency in Hertz. For example, MIDI note 69 corresponds to A4, which has a frequency of 440 Hz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*07AtbKCyV-nrEC7DJ4cCIQ.png" /><figcaption>pitch frequency chart</figcaption></figure><p><strong>Sound Power:</strong> Sound power is all about the total energy a sound source puts out per unit of time, and it’s measured in watts (W). Sound power is the total energy emitted by a sound source per unit of time, measured in watts (W). Think of it as the sound source’s inherent ability to generate sound energy, regardless of where you’re standing in relation to it. It’s an important concept when evaluating how effective audio equipment is and making sure we’re getting accurate sound level readings. Unlike sound intensity, sound power doesn’t change with distance from the source.</p><p><strong>Sound Intensity:</strong> Sound intensity, on the other hand, refers to the sound power distributed over a specific area, measured in watts per square meter (W/m²).Intensity helps us understand how energy is spread out in space. For instance, the sound power of heavy thunder can be about 1 watt, which is pretty powerful. At the other end of the spectrum, the quietest sound humans can hear, known as the threshold of hearing, is around</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*Sx19142OLpvfFM0qUu-NXg.png" /></figure><p>Thereshold of pain is the sound intensity level at which sound becomes physically painful for humans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*T_F9mGctsmGufeJImIJpFw.png" /></figure><p>To convert intensity to decibels we use threshold of hearing as the base and if we use I = TOH then the ratio will be one and dB will be zero so we can say that Intensity of threshold of hearing is zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*qsnoGRVa0a2Bl7grNrXVlQ.png" /></figure><p>Here is the table on the intensity level of different sounds to get you some real-world idea</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*kUDCnCJrbadcqg-i6RWqrg.png" /></figure><p><strong>Loudness</strong> is a perceptual quality of sound that relates to how we perceive its intensity. Unlike sound intensity, which is a physical measurement of energy per unit area.It is the subjective perception of sound intensity, or how loud a sound seems to us, can vary based on several factors:</p><ul><li>Duration / Frequency of Sound</li><li>Age of listener</li><li>Measurement in Phones</li></ul><h4>Timbre</h4><p>Timbre is the quality or color of a sound that distinguishes it from other sounds of the same pitch and intensity. What does it mean when we say it is color of sound , It’s what makes a piano sound different from a guitar, even when both are playing the same note at the same volume. It is influenced by the harmonic content, attack, decay, sustain, and release of the sound.</p><ul><li><strong>Attack:</strong> How quickly the sound reaches its peak.</li><li><strong>Decay:</strong> How the sound reduces in volume after the peak.</li><li><strong>Sustain:</strong> How the sound maintains its level while it lasts.</li><li><strong>Release:</strong> How the sound fades away when you stop playing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*S8ERE_H7dwQqRikt_21bJg.png" /></figure><p>Timbre allows us to differentiate between different musical instruments and voices, even when they play the same note at the same volume.</p><p>So till now, we have learned about the basic terminologies used in sound and audio processing but now let&#39;s talk about how sounds are made of or complex representations of sound.</p><h4>Complex Sound</h4><p>A complex sound is made up of multiple simple waves, or sinusoids, combined. This is known as superposition. Each of these sinusoids is called a <strong>partial</strong>, and they work together to create the overall sound we hear.</p><ul><li><strong>Fundamental Frequency:</strong> The lowest partial is called the fundamental frequency. It sets the base pitch of the sound. For example, if the fundamental frequency is 440 Hz (like the musical note A4), it’s the main tone we recognize.</li><li><strong>Harmonic Partials:</strong> Other partials can be whole-number multiples of the fundamental frequency, and these are called harmonic partials. For example, if the fundamental frequency is 440 Hz (f1), the first harmonic (f2) would be 2×440=880 Hz and so on. These harmonics add richness and complexity to the sound, helping to shape its timbre.</li></ul><p>This combination of the fundamental frequency and its harmonics is what gives complex sounds their unique characteristics, making them more interesting and distinguishable from pure tones.</p><p><strong>Inharmonic</strong> frequencies are those that do not follow the whole-number multiples of the fundamental frequency. Unlike harmonics, which are neatly spaced and contribute to a harmonious sound, inharmonics create a more complex and less predictable sound pattern. The example inharmonic ae Instruments like bell , metals instruments often produce inharmonic sounds, where the overtones do not align perfectly as harmonics.</p><h4>Modulation</h4><p>Modulation refers to varying a property of a sound signal using another signal.</p><ul><li><strong>Amplitude Modulation (AM):</strong> This involves varying the amplitude (loudness) of a carrier signal in response to changes in a modulating signal.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*yZPjJzAuN1nuzYgz_UZJOQ.png" /></figure><ul><li><strong>Frequency Modulation (FM):</strong> This type changes the frequency of the carrier signal based on the modulating signal. FM is used in FM radio and synthesizers to create complex and evolving sounds.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*rje-Ok4JxwFePWnZpP7vfg.png" /></figure><p>So basically we can say in modulation, one signal is superimposed onto another based on a sine wave. For amplitude modulation (AM), the amplitude of the carrier signal increases when the modulating signal is higher. In frequency modulation (FM), the frequency of the carrier signal increases when the modulating signal is higher.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*9OMsEYtWPHU-Kr1d" /></figure><p>So these were the basic terminologies that we will use throughout the whole process some are left we will talk about throughout this course if you want a video lecture for these topics do follow the playlist mentioned on top.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8623489623e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>