<?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 Rodrigo da Motta Cabral-Carvalho on Medium]]></title>
        <description><![CDATA[Stories by Rodrigo da Motta Cabral-Carvalho on Medium]]></description>
        <link>https://medium.com/@rodrigodamottacc?source=rss-d17b17427c47------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yxGzxSevh8jZ8BOBViyGow.png</url>
            <title>Stories by Rodrigo da Motta Cabral-Carvalho on Medium</title>
            <link>https://medium.com/@rodrigodamottacc?source=rss-d17b17427c47------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:03:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rodrigodamottacc/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[From My Dissertation to a Research Map using Semantic Embeddings]]></title>
            <link>https://medium.com/@rodrigodamottacc/mapping-a-research-landscape-with-semantic-embeddings-7e13c44ce1e8?source=rss-d17b17427c47------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e13c44ce1e8</guid>
            <dc:creator><![CDATA[Rodrigo da Motta Cabral-Carvalho]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 19:45:11 GMT</pubDate>
            <atom:updated>2025-07-18T19:45:22.393Z</atom:updated>
            <content:encoded><![CDATA[<h4>After completing my dissertation, I couldn&#39;t shake the idea of visualizing it within a research landscape, as part of an interdisciplinary investigation spanning various papers from multiple fields, including AI research, Neuroscience, Psychedelic Science, and Complex Systems. I wanted to check how these relate to my work.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wYzsiWDY-P1YmnEH9UwKWA.png" /></figure><h4>Introduction</h4><p>I love viewing problems from multiple perspectives, so I’m building a “literature map” that shows how my dissertation sits semantically among the papers it cites (I&#39;m not sure if the term “literature map” really exists, but I like it). The workflow is straightforward: encode each abstract of the cited papers with a state-of-the-art embedding model, locate the resulting vectors in high-dimensional meaning space, then project them into two dimensions and link documents whose cosine similarity is strongest. The sparse graph that emerges should spotlight the thematic neighborhoods and hidden connections across the bibliography.</p><blockquote>Before going into the whole article, interact with the map!</blockquote><blockquote><a href="https://rodrigo-motta.github.io/MS-literature-map/">https://rodrigo-motta.github.io/MS-literature-map/</a></blockquote><p>In practical terms, this means: <strong>Turning a BibTeX database (citation file) into an explorable landscape of research papers.</strong></p><ol><li><strong>Parse .bib</strong></li><li><strong>Text to Vector (embedding model)</strong></li><li><strong>Dimensionality reduction</strong></li><li><strong>Knowledge graph</strong></li></ol><h3>Walkthrough</h3><h4><strong>Extracting .bib</strong></h4><p>A .bib file (a.k.a. BibTeX) is a structured text file used to store references for academic writing. Think of it as your personal database or library of scholarly articles, books, conference papers, and other publications.</p><p>In a .bib file, each reference is stored in a consistent, machine-readable format. Entries typically include important metadata such as:</p><ul><li><strong>Author(s)</strong></li><li><strong>Title</strong></li><li><strong>Year of publication</strong></li><li><strong>Journal name, volume, issue, and pages</strong> (if applicable)</li><li><strong>Publisher</strong> (for books)</li><li><strong>DOI</strong> (Digital Object Identifier) or URL for easy online access</li></ul><p>The function first queries <strong>CrossRef</strong> with a DOI to fetch structured abstracts, cleans any XML/HTML tags with clean_xml, and returns the result. If CrossRef doesn’t provide an abstract, it queries <strong>Semantic Scholar</strong>, which typically returns clean, plain-text abstracts. If this also fails, it queries <strong>OpenAlex</strong>, another reliable aggregator of scholarly metadata. If all three APIs fail, it returns an empty string.</p><pre>import re, html, requests<br>from scholarly import scholarly, ProxyGenerator<br><br>def clean_xml(text: str) -&gt; str:<br>    &quot;&quot;&quot;Strip &lt;jats:...&gt; and HTML tags that Crossref sometimes returns.&quot;&quot;&quot;<br>    text = re.sub(r&#39;&lt;/?jats:[^&gt;]+&gt;&#39;, &#39;&#39;, text)     # remove JATS tags<br>    text = re.sub(r&#39;&lt;[^&gt;]+&gt;&#39;, &#39;&#39;, text)           # remove any tag<br>    return html.unescape(text).strip()<br><br>def fetch_abstract(doi):<br>    # 2) Crossref -----------------------------------------------------------<br>    r = requests.get(f&quot;https://api.crossref.org/works/{doi}&quot;, timeout=10)<br>    if r.ok:<br>        data = r.json()[&quot;message&quot;]<br>        if &quot;abstract&quot; in data:<br>            print(&#39;crossref&#39;)<br>            return clean_xml(data[&quot;abstract&quot;])<br><br>    # 3) Semantic Scholar ---------------------------------------------------<br>    r = requests.get(<br>        f&quot;https://api.semanticscholar.org/graph/v1/paper/DOI:{doi}&quot;,<br>        params={&quot;fields&quot;: &quot;title,abstract&quot;}, timeout=10<br>    )<br>    if r.ok and r.json().get(&quot;abstract&quot;):<br>        print(&#39;semanticscholar&#39;)<br>        return r.json()[&quot;abstract&quot;]<br><br>    # 4) OpenAlex -----------------------------------------------------------<br>    r = requests.get(f&quot;https://api.openalex.org/works/https://doi.org/{doi}&quot;, timeout=10)<br>    if r.ok and r.json().get(&quot;abstract&quot;):<br>        print(&#39;openalex&#39;)<br>        return r.json()[&quot;abstract&quot;]<br><br>    return &quot;&quot;</pre><h4><strong>Gemini embedding space</strong></h4><p>Conceptually, we map each paper abstract to a high-dimensional semantic vector — computed with the Gemini-004 embedding model, whose strong performance on semantic search tasks makes it ideal for this task (MMTEB: Massive Multilingual Text Embedding Benchmark 2025) — so every abstract claims its own unique coordinate in meaning space.</p><pre>def gemini_embed_batch(texts: list[str]) -&gt; list[list[float]]:<br>    &quot;&quot;&quot;Send a batch of texts to Gemini embedding API and return a list of embedding vectors.&quot;&quot;&quot;<br>    resp = client.models.embed_content(<br>        model=&quot;models/text-embedding-004&quot;,<br>        contents=texts,<br>        config=types.EmbedContentConfig(task_type=&quot;SEMANTIC_SIMILARITY&quot;)<br>    )<br>    return [emb.values for emb in resp.embeddings]</pre><h4><strong>Dimensionality reduction and paper graph</strong></h4><p>We can do two complementary things to the : (1) apply a dimensionality-reduction algorithm (i.e., t-SNE) to give each vector a 2-D that visually groups them by topical similarity, and (2) quantify pairwise affinities — most commonly with cosine similarity — to establish weighted edges that say how strongly any two abstracts are related. The result is a graph where spatial proximity highlights thematic neighborhoods while edge weights capture precise semantic overlap. Such a representation turns an unwieldy corpus into an intuitive landscape, enabling tasks like cluster discovery, influence tracing, and recommendation through straightforward network analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyyqCrQVvDsnEjtqbIEIHA.png" /></figure><p>We keep the network sparse by applying a <em>k</em>-nearest-neighbors (KNN) filter: for each abstract, we keep only its ten strongest cosine-similarity links and drop the rest. This limits node degree, cuts storage and compute costs, and preserves the local semantic structure that matters most for clustering and recommendation, without turning the graph into an unreadable hairball.</p><pre># ───────────────────────────────────────────────────────────────────────<br># 1) Cosine-similarity matrix<br>sim = cosine_similarity(all_embeddings)<br>np.fill_diagonal(sim, 0)<br><br># ───────────────────────────────────────────────────────────────────────<br># 2) Top-k edge list<br>K = 10<br>edges = [<br>    (i, j)<br>    for i in range(sim.shape[0])<br>    for j in np.argsort(sim[i])[::-1][:K]<br>    if sim[i, j] &gt; 0<br>]<br>edges = np.asarray(edges)<br>weights = sim[edges[:, 0], edges[:, 1]]          # similarity per edge<br>w_min, w_max = weights.min(), weights.max()<br>norm = (weights - w_min) / (w_max - w_min + 1e-12)<br><br># ───────────────────────────────────────────────────────────────────────<br># 3) Compute T-SNE<br># Linear pre-compression<br>X50 = PCA(n_components=50, random_state=42).fit_transform(all_embeddings)<br><br># Heuristic hyper-parameters<br>n = len(X50)<br>perp = max(5, min(100, n // 100))<br><br>tsne = TSNE(<br>    n_components=2,<br>    init=&quot;pca&quot;,<br>    perplexity=perp,<br>    learning_rate=&quot;auto&quot;,              <br>    early_exaggeration=8,<br>    method=&quot;barnes_hut&quot;,                 <br>    angle=0.3,<br>    n_iter=1000,<br>    random_state=42,<br>    verbose=1,<br>)<br>tsne_2d = tsne.fit_transform(X50)</pre><h4>My own &quot;literature map&quot;</h4><p>As mentioned, my work sits on the intersection of Neuroscience, Deep Learning, Complex Systems, and Psychedelic Science. We can consider this literary landscape on several scales. Firstly, in macrotopics or themes, for example, the ones I cited above, which tend to cluster together spatially and by cosine similarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wYzsiWDY-P1YmnEH9UwKWA.png" /></figure><p>Another interesting thing to inspect is the paper level. Here, I&#39;m doing something quite simple: I&#39;m looking at the abstracts of the most similar papers to my dissertation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8pYy5IQFaGnF8pX3sFxpxg.png" /></figure><p>However, it would be possible to check which papers are most central in the whole network, and not from the perspective of my dissertation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCpv2qyGACowGW1xuDyLog.png" /></figure><p>From this simple analysis, we see that some major players are involved in the fields of deep learning, neuroscience, and complex systems. Therefore, many investigation possibilities arise to evaluate multiple different clusters and their graph properties. This translates to even more profound questions, for example:</p><blockquote>Which paper connects more clusters together? Which papers are more clustered? Can I guess which paper is more cited just by their location? Where will my new paper fit into the existing landscape?</blockquote><p>The code and HTML are available on GitHub: <a href="https://github.com/Rodrigo-Motta/MS-literature-map">https://github.com/Rodrigo-Motta/MS-literature-map</a></p><p>Of course, this is simple, but it may reveal important insights and help to provide a deeper understanding of the literature. I&#39;m always open to any contribution you might have. Let me know!<br>I also want to acknowledge Carlos Piccoli for bringing this idea to my attention. Cheers, brother!</p><p><strong>References</strong></p><p>Enevoldsen, K., Chung, I., Kerboua, I., Kardos, M., Mathur, A., Stap, D., Gala, J., Siblini, W., Krzemiński, D., Winata, G. I., Sturua, S., Utpala, S., Ciancone, M., Schaeffer, M., Sequeira, G., Misra, D., Dhakal, S., Rystrøm, J., Solomatin, R., … Muennighoff, N. (2025). <strong>MMTEB: Massive Multilingual Text Embedding Benchmark</strong>. <em>arXiv preprint</em>arXiv:2502.13595. <a href="https://doi.org/10.48550/arXiv.2502.13595">https://doi.org/10.48550/arXiv.2502.13595</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e13c44ce1e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A ciência de dados dos dados de dados do Nerdcast de RPG: O dado é realmente justo?]]></title>
            <link>https://medium.com/@rodrigodamottacc/a-ci%C3%AAncia-de-dados-dos-dados-de-dados-do-nerdcast-de-rpg-o-dado-%C3%A9-realmente-justo-d41e8e0eaeb3?source=rss-d17b17427c47------2</link>
            <guid isPermaLink="false">https://medium.com/p/d41e8e0eaeb3</guid>
            <category><![CDATA[nerdcast]]></category>
            <category><![CDATA[rpg]]></category>
            <category><![CDATA[ciencia-de-dados]]></category>
            <category><![CDATA[estatistica]]></category>
            <category><![CDATA[inteligencia-artificial]]></category>
            <dc:creator><![CDATA[Rodrigo da Motta Cabral-Carvalho]]></dc:creator>
            <pubDate>Thu, 08 May 2025 15:35:12 GMT</pubDate>
            <atom:updated>2025-05-12T12:40:51.700Z</atom:updated>
            <content:encoded><![CDATA[<h4>Nos meados de 2011, eu com apenas 11 anos, fiquei absolutamente absorvido pelo Nerdcast podcast de RPG, esperando ansiosamente, todo ano, pelo novo episódio. Após seus surpreendentes 14 episódios, ainda me resta um mistério que assombra todos os ouvintes, mas que ninguém resolveu: Será que o dado dos integrantes do Nerdcast é realmente justo? Depois de viver todos esses anos com essa dúvida, eu decidi dar um basta e colocar isso a prova usando os episódios de Ghanor.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UP2u3kowQlWEvzo3xJJAmA.png" /><figcaption>Imagem de co-autoria minha com o chatGPT.</figcaption></figure><h4><strong>Introdução</strong></h4><p>Depois de um monte de piadas em seus vários episódios, surgiu uma lenda acerca dos resultados da rolagem dos dados no Nerdcast de RPG. Para alguns participantes, parece que o dado tem apenas 4 lados: 17, 18, 19 e 20. Agora, com conhecimentos em estatística e computação, misturado uma boa pitada de boa vontade e disposição, eu finalmente resolvi o mistério. Mas só vou contar no final. Para os curiosos, o código está livremente disponíveis no <a href="https://github.com/Rodrigo-Motta/nerdcast_transcript">GitHub</a>.</p><p>Para fazer esse projeto alguns passos foram necessários</p><ol><li>Primeiro precisamos baixar todos os Nerdcast de RPG Ghanor e transcrever para texto. Para isso será usado um modelo open-source chamado Whispers (feito pela OpenAI).</li><li>Com os textos em mãos será necessário limpar os dados. Se você é ouvinte do Nerdcast sabe muito bem que esse não será uma tarefa fácil. Esse passo é muito importante visto que somente queremos o numero referente a jogada, nem mais nem menos.</li><li>Com os dados limpos basta fazermos um teste estatístico frequentista bem simples para saber se os dados realmente vieram de uma distribuição justa, ou seja, o que é esperado de uma mesa normal de RPG. Vamos usar o imortal Chi-Quadrado.</li><li>Assim, também será analisado se há algum viés na distribuição, será que existem lados justos ou um certo viés nos lados 16–20? Para isso vamos usar o Wilson interval com correção de multiplas comparações.</li><li>Conclusões e limitações desse projeto com os devidos reconhecimentos.</li></ol><h4><strong>1. Transcrição usando OpenAI-Whisper</strong></h4><p>O Whisper é um dos melhores modelos open-source pra transcrição de áudio em texto para várias línguas. É possível usa-lo de dois jeitos:</p><ol><li><strong>API paga da </strong><a href="https://openai.com/index/whisper/"><strong>OpenAI</strong></a>;</li><li><strong>Rodando o modelo localmente</strong> na sua máquina através da lib <a href="https://github.com/openai/whisper">whisper</a>.</li></ol><p>Implementei as duas opções no código. Como o whisper somente aceita até 25 MB por input, o áudio foi divido em pedaços de 15 minutos. Além disso, é muito importante explicitar a linguagem da transcrição para o modelo, no caso português. Dessa forma, cada episódio foi transformado num .txt facilitando a leitura para o próximo passo</p><h4><strong>2. Data Cleaning</strong></h4><blockquote>”20 minutos depois, o Borna já tá carregando a mochila de todo mundo.”</blockquote><blockquote>“Porra, eu tô pelado, tomei 20 hit points de fireball, e eu não sou fighter.”</blockquote><blockquote>”Lá vai o ladrão. 20! Puta que pariu! 20!”,</blockquote><blockquote>“Tá bom, vai lá. 20! Caraca, tirou 20 mesmo.”</blockquote><p>É claro que ouvir alguém dizer “vinte” não garante que o dado tenha realmente mostrado 20. Como em muitos projetos de ciência de dados, a etapa mais demorada foi preparar os dados para a análise. Ainda assim, limpar os episódios do Nerdcast RPG teve seu lado interessante: em diversos trechos precisei voltar ao áudio para identificar quem estava falando e confirmar se o número correspondia a apenas uma rolagem.</p><p>Outro ponto complexo foram os resultados já com bônus de atributos. Muitas vezes o jogador informa somente o valor final (dado + modificador), tornando difícil determinar qual foi, de fato, o número que saiu no dado.</p><h4><strong>3. Métodos e Resultados</strong></h4><p>Um dado de 20 faces requer um número muito grande de observações para garantir uso da estatística frequentista. Embora a abordagem bayesiana seja uma alternativa, ela está fora do escopo deste artigo. Para aumentar o poder estatístico com a amostra disponível, agrupei as faces em quatro intervalos: 1–5, 6–10, 11–15 e 16–20. Esse agrupamento mantém a questão de interesse e permite análises mais robustas.</p><p>Vamos verificar se os dados são justos por episódio de podcast usando o imortal Chi-Squared <strong>(χ²)</strong>, que compara as frequências observadas das jogadas do dado com as frequências esperadas sob a hipótese de um dado perfeitamente uniforme, ou seja, justo.</p><ol><li>Contar quantas vezes cada intervalo (1–5, 6–10, 11–15, 16–20) apareceu no episódio;</li><li>Calcular o valor esperado (total de rolagens / 4);</li><li>Computar o estatístico χ² = Σ [(observado − esperado)² / esperado];</li><li>Obter o p-valor a partir da distribuição χ² com 3 graus de liberdade;</li></ol><p><strong>Se p &lt; 0,05 rejeitamos a hipótese de justiça para aquele episódio. De forma, que quanto maior o <em>χ²</em> menor o p value e portanto, menor a chance de ser justo. Isso é assumir que há 5% de chance do resultado ser significante ao acaso.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yzqj9NwRTibGxQzcd_6F3A.png" /></figure><p><strong>Podemos ver que os Nerdcast de RPG 1, 2, 6 e 7 são os únicos significativos e portanto provavelmente não vem de uma distribuição de dados justos.</strong></p><h4>Investigando vieses específicos</h4><p>O teste global diz se algum intervalo foge do esperado, mas não revela para que valores! Por isso complementamos a análise:</p><p>Jogadores podem relatar seletivamente resultados dependendo da situação.</p><blockquote>Por exemplo, ocultar um 1 ou 2 num momento crítico para evitar penalidades, ou então, mentir um 17–20 para fazer um feito heróico.</blockquote><p>A ideia será ver qual grupo está acima ou abaixo da frequência esperada. Para isso basta observar se o grupo está dentro do intervalo de confiança através do <a href="https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval">Wilson interval</a>, usando uma significância de <strong>α = 0.05</strong>, que deve ser corrigida devido as multiplas <a href="https://pt.wikipedia.org/wiki/Correção_de_Bonferroni">comparações</a>, então, <strong>α_corr = 0.0125</strong>. Se o a probabilidade observada estiver fora do intervalo de confiança, ela foi para qual lado do intervalo (acima ou abaixo)?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*kPYWBjqwGc_CR2r69g_1EQ.png" /></figure><blockquote>Não por coincidência, os mesmos episódios do Nerdcast que anteriormente se destacaram também apresentam um dado enviesado no grupo 16–20. Neste caso, o viés é positivo — ou seja, esse intervalo aparece mais vezes do que o esperado, sendo o principal responsável pela falta de justiça do dado 🤔.</blockquote><h4>Conclusão e Limitações</h4><p>Portanto, parece que o dado do nerdcast realmente não é tão justo assim! com alguns possíveis exageros para cima. <strong>Mas é importante ser cético com esses resultados</strong>, pois existem várias limitações aqui nesse projeto, por exemplo:</p><p><strong>→ A soma do multiplicador de atributo pode ser um cofator para entender a grande quantidade de 16–20.</strong></p><p>→ O transcript não separa em personagens, então, pode haver um certo viés acerca do personagem que está jogando (Não vou mencionar nomes aqui 🦖). Essa solução seria até possível mas bastante trabalhosa.</p><p>→ Além disso, os dados foram agrupados para aumentar a confiabilidade estatística, o que muda a granularidade da análise, assim não podemos olhar para lados específicos do dado como &quot;<strong>20</strong>&quot;.</p><p>→ Por fim, para a análise de viés não foi feita a correção de multiplas comparações, que é importante dado o teste de várias hipóteses simultâneas, ou seja, para os 4 grupos.</p><blockquote><strong>Esse projeto é só uma brincadeira e não deve ser levado a sério!</strong></blockquote><p>E se quiser continuar essa brincadeira, fique a vontade para colaborar como quiser. O código pode ser acessado através do <a href="https://github.com/Rodrigo-Motta/nerdcast_transcript">GitHub</a>. O projeto não tem nenhum fim lucrativo e tem caractér informativo e educacional.</p><p>Gostaria de expressar meu reconhecimento especial a todo grupo Jovem Nerd pelo trabalho incrível que eu tenho prazer de acompanhar a mais de 10 anos. Referência usada foi o site do <a href="https://jovemnerd.com.br/podcasts/nerdcast">Jovem Nerd.</a></p><h4><strong>Episódios usados</strong></h4><ul><li><strong>Ep. 251 — RPG Ghanor 1: O Bruxo, a Princesa e o Dragão</strong></li><li><strong>Ep. 291 — RPG Ghanor 2: O Duque, a Rosa e o Beholder</strong></li><li><strong>Ep. 341 — RPG Ghanor 3: O Corvo, a Periguete e o Bucentauro</strong></li><li><strong>Ep. 862 — RPG Ghanor 4: O Bardo, o Santo e o Bico de Tamanco</strong></li><li><strong>Ep. 892 — RPG Ghanor 5: O Tripa de Pedra, a Cuíca e o Pata Rachada</strong></li><li><strong>Ep. 914 — RPG Ghanor 6: O Paladino, a Auréola e o Paraíso</strong></li><li><strong>Ep. 966 — RPG Ghanor 7 (parte 1): O deserto, a desolação e o cemitério de dragões</strong></li><li><strong>Ep. 967 — RPG Ghanor 7 (parte final): O devorador, o dragão e o fim do mundo</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d41e8e0eaeb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Pre-Trained Transformers for Semantic Analysis of Self-Report measures in Psychology: A…]]></title>
            <link>https://medium.com/@rodrigodamottacc/using-pre-trained-transformers-for-semantic-analysis-of-self-report-measures-in-psychology-a-fc412d5bbb5e?source=rss-d17b17427c47------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc412d5bbb5e</guid>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Rodrigo da Motta Cabral-Carvalho]]></dc:creator>
            <pubDate>Thu, 09 Jan 2025 18:05:23 GMT</pubDate>
            <atom:updated>2025-01-09T18:19:28.441Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Using Pre-Trained Transformers for Semantic Analysis of Self-Report measures in Psychology: A tutorial</strong></h3><h4><em>In our recently published paper, my co-authors and I reviewed the landscape of self-report scales that assess subjective time. We evaluated their semantic similarities, redundancies, and desired measurement targets using advanced natural language processing (NLP), specifically the transformer-based Sentence-T5 model and hierarchical clustering methods.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cAOrnZnePtocN0PknxbrgA.png" /><figcaption><a href="https://www.flickr.com/photos/britishlibrary/11299565196/in/album-72157674484666897">Under Creative Commons Zero (CC0) (i.e., public domain).</a></figcaption></figure><p><strong>Table of Contents</strong></p><p>1. <a href="#installation">Installation</a></p><p>2. <a href="#data-description">Data Description</a></p><p>3. <a href="#usage">Usage</a></p><ul><li>3.1 Core components</li><li>3.2 A notebooks to rule them all</li></ul><p>4. <a href="#contributing">Contributing</a></p><p>5.<a href="#License and Acknowledgment"> License and Acknowledgment</a></p><h3>Introduction</h3><p><a href="https://osf.io/preprints/psyarxiv/sjwm2">Our study</a> was motivated by a known gap in the field of psychological research: the proliferation of self-report measures that are often developed without rigorous systematic validation, leading to potential construct redundancy and compromising the validity of research findings. While several studies have looked at this in different areas, none have investigated this in terms of time perception. We tackled this issue by systematically reviewing the literature to identify 30 scales that met our inclusion criteria and then employing NLP to explore the semantic relationships among these scales <a href="https://osf.io/preprints/psyarxiv/sjwm2">(Bonifácio et al., 2024)</a>.</p><p>Our approach involved calculating the cosine similarity between vector embeddings of target scales (‘A’) and others (‘B’) using the <a href="https://arxiv.org/abs/2108.08877">Sentence-T5 (ST5) model (Ni et al., 2021)</a>. ST5 maps sentences into 768-dimensional embeddings, excelling in semantic similarity tasks and outperforming models like Sentence-BERT on key benchmarks. To compare, we also assessed cosine similarity between constructs’ definitions. To ensure robustness against question order, questionnaire items were scrambled 50 times, with ST5 generating embeddings for each version. These were averaged into a final, order-agnostic representation (Fig. 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XFDcUeVFZh_-t2NrrolUFQ.png" /><figcaption>Figure 1.</figcaption></figure><p>Then we can use these embeddings to cluster multiple scales and even creating a similarity matrix–which can be also understood as a graph! but we&#39;re not going to explore this further here.</p><h3><strong>1. Installation</strong></h3><p>The project is freely available on <a href="https://github.com/Rodrigo-Motta/Timing_LLM">GitHub</a>.</p><h4><strong>Steps to Set Up the Environment</strong></h4><ol><li><strong>Clone the repository:</strong></li></ol><pre>git clone https://github.com/rodrigo-motta/Timing_LLM.git <br>cd Timing_LLM</pre><p><strong>2. Create an environment:</strong></p><pre>conda create -n time_llm python=3.9<br>activate time_llm</pre><p><strong>3. Install the required packages:</strong></p><pre>pip install -r requirements.txt</pre><h3><strong>2. Data Description</strong></h3><h3><strong>Dataset</strong></h3><p><strong>Subjective Time Scales</strong>: Data were compiled from systematic literature searches across major databases including PsycNET, PubMed, Scopus, and Web of Science, identifying 30 scales published from 1994 to 2023 that assess various aspects of subjective time.</p><h3><strong>Data Access</strong></h3><p>Publicly available in <a href="https://osf.io/rj3kx/">OSF Supplemental Materials.</a></p><h3>3. Usage</h3><h4><strong>Core Components</strong></h4><ul><li><strong>dataset.py:</strong> Class to manage data loading, preprocessing, and manipulation, equipped with features for text cleaning and sentence scrambling within scales.</li><li><strong>utils.py</strong>: Contains essential functions used in the analysis notebooks, including methods for scrambling, embedding generation, and clustering.</li></ul><h3>A notebook to rule them all</h3><h4><strong>1. Import data and define the model to:</strong></h4><p>Here we load the time scales we’ll use and the respective constructs from each scale</p><pre># 1.1 Scales items<br>data_items = DatasetLoader(time_scales)<br><br># 1.2 Constructs definitions<br>data_constructs = DatasetLoader(time_constructs)<br><br># 1.3 Sentence-t5<br>model_list = [&#39;sentence-t5-large&#39;]<br><br># 1.4 Create a joint representation of the scales<br>data_items.scales_joint()<br><br># 1.5 Scramble the sentences within each scale to create a scrambled representation<br>data_items.scramble_joint()<br><br># 1.6 Number of reference scales<br>num_refs = len(data_items.list_names)<br>print(num_refs)</pre><h4>2. Getting embeddings from scales items and construct definitions</h4><p>The following are the main parts of the script. In it, we’ll get the embeddings for each scale and construct. The output will be a dataframe with <em>num_refs</em> rows (the number of scales) and num_embeddings columns (if using sentence-t5-large that should be 768). <em>n_scrambles</em> will define how many times the order of the questions will be scrambled to look for possible order effects (notice that due to the random nature of n_scrambles, results can slightly vary each time you run the code)</p><pre>######### 2.1. Scales items #########<br><br>n_scrambles = 50 # nº of scrambles (e.g., 100)<br># Main method to extract embeddings<br>arr_items = ut.get_embedding(data_items, model_list, num_refs, n_scrambles)<br><br># There is a function to use the GPT embedding<br>#arr_items = ut.get_embedding_gpt(data_items, [&quot;text-embedding-3-small&quot;], num_refs, n_scrambles)<br><br># Model number<br>model = 0<br># Get the PCA components<br>comps_items, variance = ut.PCA_embeddings(arr_items[:, model, :], n_comp=10) # testar com n_comp = 0.9<br># Get clusters using the whole embedding<br>df_items = ut.clusters(arr_items[:, model, :], data_items, clusters=5)<br><br>######### 2.2. Scales constructs #########<br><br>arr_constructs = ut.get_embedding(data_constructs, model_list, num_refs, 1) # -&gt; there is no need to scramble here, since constructs only have one sentence<br># There is a function to use the GPT embedding<br># arr_constructs = ut.get_embedding_gpt(data_constructs, [&quot;text-embedding-3-small&quot;], num_refs, n_scrambles)<br><br>model = 0<br>comps_constructs, variance_constructs = ut.PCA_embeddings(arr_constructs[:, model, :], n_comp=10)<br>df_constructs = ut.clusters(arr_constructs[:, model, :], data_constructs, clusters=5)</pre><h4>3. 3D PCA of Embeddings and Cluster Distances</h4><pre>ut.plot_3D_PCA(comps_items, data_items.list_names, df_items[&#39;cluster&#39;].values)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nFz3mPCfLJUPHr5eB9eNFQ.png" /></figure><h4>4. Similarity Matrices Creation and Normalization</h4><pre>&quot;&quot;&quot;Compute the average and standard deviation of similarities across multiple scrambles.&quot;&quot;&quot;<br>n_scrambles = 50<br># 4.1 Repetitions over scales items<br>average_dist_items, std_dist_items = ut.similarities_average(data_items, model_list, num_refs, n_scrambles)<br><br># 4.2 Repetitions over constructs definitions<br>average_dist_constructs, std_dist_constructs = ut.similarities_average(data_constructs, model_list, num_refs, 1)<br> <br># 4.1 Scales items<br>df_distances_items = ut.convert_arr_to_pandas(average_dist_items, data_items.list_names)<br>df_distances_items = ut.min_max_norm(df_distances_items) # Min-Max Scaling<br><br># 4.2 Constructs<br>df_distances_constructs = ut.convert_arr_to_pandas(average_dist_constructs, data_constructs.list_names)<br>df_distances_constructs = ut.min_max_norm(df_distances_constructs) # Min-Max Scaling</pre><h4>5. Dendrogram</h4><p>After calculating the average embeddings for each questionnaire, a hierarchical clustering technique was applied using the nearest-neighbor chain method <a href="https://arxiv.org/abs/1109.2378">(Müllner, 2011)</a>. This approach calculates cluster distances using cosine distance, a similarity metric widely used in semantic embedding models to efficiently measure similarities between word representations in vector space <a href="https://arxiv.org/abs/1301.3781">(Mikolov et al., 2013)</a>. Hierarchical clustering grouped the questionnaires based on their pairwise distances, employing the average linkage method, which accounts for the variance in distances between clusters <a href="https://www.tqmp.org/RegularArticles/vol11-1/p008/p008.pdf">(Yim &amp; Ramdeen, 2015)</a>. This process facilitated grouping self-report measures with similar semantic content, enabling the identification of potential redundancies and overlaps in psychological constructs.</p><pre>ut.plot_dendrogram_clusters(df_distances_items_filled, threshold=0.6)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UsP8eNxJY-8VVdIjMcyJKQ.png" /></figure><h4>6. Constructs x Scales</h4><p>T o evaluate the alignment between construct definitions and scale content, we employed two strategies: (i) calculating the Spearman correlation between the average similarity matrices for construct definitions and scale content, and (ii) generating a new similarity matrix (construct definitions × scale content) using cosine similarity, followed by row-wise min-max normalization.</p><p><strong>6.1 Correlation between the similarity matrices for construct and scales</strong></p><pre>items_array = df_distances_items.where(np.triu(np.ones(df_distances_items.shape), k=1).astype(bool)).stack().tolist()<br>constructs_array = df_distances_constructs.where(np.triu(np.ones(df_distances_constructs.shape), k=1).astype(bool)).stack().tolist()<br><br>plt.figure(dpi=150)<br>sns.regplot(x=items_array, y=constructs_array);<br>plt.xlabel(&#39;Cosine Similarity of Scale Content&#39;)<br>plt.ylabel(&#39;Construct Similarity (Conceptual Alignment)&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MHNK38dzsrNwF-lNh7OyGw.png" /></figure><p><strong>6.2 Similarity matrix (construct definitions × scale content)</strong></p><pre>from sklearn.metrics.pairwise import cosine_similarity<br><br># Calculating both embeddings<br>n_scrambles = 50 # nº of scrambles (e.g., 100)<br>arr_scales = ut.get_embedding(data_items, model_list, num_refs, n_scrambles)<br>arr_constructs = ut.get_embedding(data_constructs, model_list, num_refs, n_scrambles)<br><br># Using OpenAI embedding<br># arr_scales = ut.get_embedding_gpt(data_items,[&#39;gpt&#39;], num_refs, n_scrambles)<br># arr_constructs = ut.get_embedding_gpt(data_constructs, [&#39;gpt&#39;], num_refs, n_scrambles)<br><br>model = 0 <br># Calculate cosine similarity matrix<br>similarity_matrix = cosine_similarity(arr_constructs[:,model,:], arr_scales[:,model,:])<br><br># Example: Assuming data_items.list_names contains the labels for the rows and columns<br>labels = data_items.list_names  # Replace with the actual list of names<br><br># Min-max normalization for each row<br>min_values = similarity_matrix.min(axis=1, keepdims=True)<br>max_values = similarity_matrix.max(axis=1, keepdims=True)<br>min_max_normalized_matrix = (similarity_matrix - min_values) / (max_values - min_values)<br><br># Create a heatmap for the normalized similarity matrix<br>plt.figure(figsize=(10, 8), dpi=200)<br>sns.heatmap(min_max_normalized_matrix, xticklabels=labels, yticklabels=labels, cmap=&quot;Greys&quot;, annot=False)<br><br># Add titles and labels<br>plt.title(&quot;Normalized Cosine Similarity Matrix&quot;)<br>plt.ylabel(&quot;Construct&quot;)<br>plt.xlabel(&quot;Scales&quot;)<br><br># Show the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-fRVTwwCDLWw5z4oM-yXw.png" /></figure><h3><strong>4. Contributing</strong></h3><p>We encourage community contributions! Please fork this repository, create your feature branch, and submit a pull request with your improvements. For substantial changes, we recommend opening an issue first to discuss your ideas.</p><h3><strong>5. License and Acknowledgments</strong></h3><p>This project is distributed under the MIT License, allowing free use, modification, and distribution.</p><p>We gratefully acknowledge funding from the São Paulo Research Foundation (FAPESP), which supported this study through various grants.</p><p>This article layout not only provides detailed information about the study and the repository but also guides users through setting up the environment to replicate the analyses, thereby enhancing the accessibility and applicability of the research.</p><h3><strong>References</strong></h3><p>Bonifácio, T. A. S., Cabral-Carvalho, R., &amp; Cravo, A. (2024, December 5). Self-report measures of subjective time: An overview of existing measures and their semantic similarities. <a href="https://doi.org/10.31234/osf.io/sjwm2">https://doi.org/10.31234/osf.io/sjwm2</a></p><p>Ni, J., Abrego, G. H., Constant, N., Ma, J., Hall, K. B., Cer, D., &amp; Y ang, Y. (2021). <em>Sentence-t5:Scalable sentence encoders from pre-trained text-to-text models</em>. arXiv:2108.08877. <a href="https://doi.org/10.48550/arXiv.2108.08877">https://doi.org/10.48550/arXiv.2108.08877</a></p><p>Müllner, D. (2011). <em>Modern hierarchical, agglomerative clustering algorithms</em>. arXiv:1109.2378. <a href="https://doi.org/10.48550/arXiv.1109.2378">https://doi.org/10.48550/arXiv.1109.2378</a></p><p>Mikolov, T., Chen, K., Corrado, G., &amp; Dean, J. (2013). <em>Eﬃcient estimation of word representations in vector space</em>. arXiv:1301.3781v3.<a href="https://doi.org/10.48550/arXiv.1301.3781">https://doi.org/10.48550/arXiv.1301.3781</a></p><p>Yim, O., &amp; Ramdeen, K. T. (2015). Hierarchical clustering analysis: Comparison of three linkage measures and application to psychological data. <em>The Quantitative Methods for Psychology</em>, <em>11</em>, 8–21. <a href="https://doi.org/10.20982/tqmp.11.1.p008">https://doi.org/10.20982/tqmp.11.1.p008</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc412d5bbb5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simulating Vibrations: The Advanced Physics Behind Drums and Speakers]]></title>
            <link>https://medium.com/@rodrigodamottacc/simulating-vibrations-the-advanced-physics-behind-drums-and-speakers-b350f6fb1362?source=rss-d17b17427c47------2</link>
            <guid isPermaLink="false">https://medium.com/p/b350f6fb1362</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Rodrigo da Motta Cabral-Carvalho]]></dc:creator>
            <pubDate>Wed, 05 Jun 2024 13:30:27 GMT</pubDate>
            <atom:updated>2024-06-05T13:30:27.387Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring the 2D Wave Equation Through Simulations and by Hearing Them</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1_LHrUqD67EWzTkd" /><figcaption>Photo by <a href="https://unsplash.com/@dshongphuc?utm_source=medium&amp;utm_medium=referral">Phuc H.</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Abstract</h4><p>Oscillatory movements are present in a vast range of natural phenomena and in everyday situations such as the surface of a speaker, which can be modeled as a vibrating membrane, or a drum. Therefore, the 2D wave equation is a relevant study target filled with applications. This project consists of analyzing a 2D membrane governed by the 2D wave equation in two geometries, circular and square, from the intersection between this model and sound. Thus, the use of numerical tools becomes necessary. More specifically, the solution of the partial differential equation through finite difference and other signal analysis tools like the numerical Fourier Transform.</p><h3>Introduction</h3><h4>2D Wave Equation</h4><p>The 2D wave equation is described by the partial differential equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtlOqFJyag0buXWlufGNzA.png" /></figure><p>where 𝜎<em>σ</em> is the surface mass density of the membrane (Kg/m²) and 𝑆<em>S</em> is the surface tension of the membrane (N/m). This allows us to define the speed of propagation of disturbances in the membrane as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fr1iWwwO0oC-iJaeWUFP4A.png" /></figure><h4>Solution and Normal Modes</h4><p>The normal modes of vibration are the patterns generated, where all parts of the system vibrate at the same frequency with a fixed phase relationship. The normal modes depend on the solution of the equation for each boundary condition of the system, hence, it is enough to find the solution for a square membrane of side <em>L</em> fixed at all ends, using variable separation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*mXOYl8QNwSsNue3UUPv2Hg.png" /></figure><p>Thus:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*9tfrJmhwKOUVOnVSV4VjQA.png" /></figure><p>This solution is known, as it is the same for strings fixed at the edges. Therefore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g-uzinCRh5QRyFUBJa9OTw.png" /></figure><p>where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Y3vfgVEpv706ahTMoTmRRQ.png" /></figure><p>Thus, the general solution is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Q9_AaNBZCfm-ep6knOfQA.png" /></figure><p>To discover the coefficients <em>An</em>​, it is necessary to use the initial condition.</p><p>For the case of a circular membrane with an initial Gaussian pulse condition, the analysis will be purely numerical.</p><h4>Algorithm &amp; Numerical Resolution</h4><p>To solve the 2D wave equation, the finite difference method will be employed. The method consists of approximating the second derivative:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5MPoYGG5uU88Na5Fdc7n9Q.png" /></figure><p>This applies to all variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mNxw3TQ5isO3itY7Z9H0-A.png" /></figure><p>Thus, discretizing leads to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbpNKnZkC86VF2IFW1_cgQ.png" /></figure><p>In the first step (n = 0), the term 𝑦(𝑖, 𝑗, −1) is not defined, thus</p><p>𝑢(𝑖, 𝑗, 𝑛&lt;0) = 𝑢(𝑖, 𝑗, 0).</p><p>All calculations are made in Cartesian coordinates, as the whole project will be carried out using them, even in cases where the boundary condition geometry is circular, although the use of polar coordinates might be more useful.</p><h4>The Code</h4><p>The structure of the code is simple and concise, using array slicing to execute the iterations. It receives the parameters: boundary condition format (square or circle fixed at the edges), the constant ( c ), length of the square or diameter of the circumference (L), time interval (dt), final time (Tf), length interval x (dx), length interval y (dy).</p><pre>c= 1<br>L= 1<br>dt = 0.001<br>tf = 2<br><br>dx = 0.01<br>dy = 0.01<br><br>t = np.arange(0, tf, dt)<br>x = np.arange(0, L+dx, dx)<br>y = np.arange(0, L+dy, dy)<br><br>xsize = len(x)<br>ysize = len(y)<br>tsize = len(t)<br><br>def membrane(initial_cond, c, dt, dx, dy, tsize, boundary):<br>    # Gauss is the array with the initial conditions<br>    # The function returns an array with the solution<br><br>    # Solution<br>    sol = np.zeros((len(initial_cond[0]), len(initial_cond[1]), tsize))<br><br>    # I decided to normalize the solution to improve visualizations<br>    sol[:, :, 0] = initial_cond / np.max(initial_cond)<br>    <br>    if boundary == &#39;square&#39;:<br><br>        # Boundary Condition<br>        sol[0, :, :] = 0<br>        sol[-1, :, :] = 0<br>        sol[:, 0, :] = 0<br>        sol[:, -1, :] = 0<br><br>        # First term (t=1)<br>        sol[1:-1, 1:-1, 1] = (sol[1:-1, 1:-1, 0] + (c**2 / 2) * (dt**2 / dx**2) * (sol[1:-1, 0:-2, 0] - 2 * sol[1:-1, 1:-1, 0] + sol[1:-1, 2:, 0]) +<br>             (c**2 / 2) * (dt**2 / dy**2) * (sol[0:-2, 1:-1, 0] - 2 * sol[1:-1, 1:-1, 0] + sol[2:, 1:-1, 0]))<br><br>        # Subsequent terms<br>        for t in range(2, tsize - 1):<br>            sol[1:-1, 1:-1, t + 1] = (2 * sol[1:-1, 1:-1, t] - sol[1:-1, 1:-1, t - 1] + (c**2) * ((dt / dx)**2) * (sol[1:-1, 0:-2, t]<br>                                - 2 * sol[1:-1, 1:-1, t] + sol[1:-1, 2:, t]) + (c**2) * ((dt / dy)**2) * (sol[0:-2, 1:-1, t] - 2 * sol[1:-1, 1:-1, t] + sol[2:, 1:-1, t]))<br><br>            sol[0, :, :] = 0<br>            sol[-1, :, :] = 0<br>            sol[:, 0, :] = 0<br>            sol[:, -1, :] = 0<br>            <br>    elif boundary == &#39;circle&#39;:<br><br>        # Boundary Condition<br>        for i in range(len(sol[:, 0, :])):<br>            for j in range(len(sol[0, :, :])):<br>                if (i - 50)**2 + (j - 50)**2 &gt;= (len(sol[:, 0, :]) / 2)**2:<br>                    sol[i, j, :] = 0<br><br>        # First term (t=1)<br>        sol[1:-1, 1:-1, 1] = (sol[1:-1, 1:-1, 0] + (c**2 / 2) * (dt**2 / dx**2) * (sol[1:-1, 0:-2, 0] - 2 * sol[1:-1, 1:-1, 0] + sol[1:-1, 2:, 0]) +<br>             (c**2 / 2) * (dt**2 / dy**2) * (sol[0:-2, 1:-1, 0] - 2 * sol[1:-1, 1:-1, 0] + sol[2:, 1:-1, 0]))<br><br>        # Boundary Condition<br>        for i in range(len(sol[:, 0, :])):<br>            for j in range(len(sol[0, :, :])):<br>                if (i - 50)**2 + (j - 50)**2 &gt;= (len(sol[:, 0, :]) / 2)**2:<br>                    sol[i, j, :] = 0<br><br>        # Subsequent terms<br>        for t in range(1, tsize - 1):<br>            sol[1:-1, 1:-1, t + 1] = (2 * sol[1:-1, 1:-1, t] - sol[1:-1, 1:-1, t - 1] + (c**2) * ((dt / dx)**2) * (sol[1:-1, 0:-2, t]<br>                                - 2 * sol[1:-1, 1:-1, t] + sol[1:-1, 2:, t]) + (c**2) * ((dt / dy)**2) * (sol[0:-2, 1:-1, t] - 2 * sol[1:-1, 1:-1, t] + sol[2:, 1:-1, t]))<br><br>            # Boundary Condition<br>            for i in range(len(sol[:, 0, :])):<br>                for j in range(len(sol[0, :, :])):<br>                    if (i - 50)**2 + (j - 50)**2 &gt;= (len(sol[:, 0, :]) / 2)**2:<br>                        sol[i, j, :] = 0<br>       <br>    else:<br>        print(&#39;Specify either &quot;square&quot; or &quot;circle&quot;&#39;)<br>        return None<br>        <br>    return sol<br><br># Initial conditions<br><br>X, Y = np.meshgrid(x, y)<br><br># Placing X and Y in 3D arrays<br>pos = np.empty(X.shape + (2,))<br>pos[:, :, 0] = X<br>pos[:, :, 1] = Y<br><br>#-----------------------------------------------------<br># First initial condition (Gaussian pulse)<br><br># Mean matrix and covariance matrix<br>mu = np.array([0.5, 0.5])<br>Sigma = np.array([[0.03, 0], [0, 0.03]])<br><br>def gaussian_pulse_2d(pos, mu, Sigma):<br><br>    n = mu.shape[0]<br>    Sigma_det = np.linalg.det(Sigma)<br>    Sigma_inv = np.linalg.inv(Sigma)<br>    N = np.sqrt((2 * np.pi)**n * Sigma_det)<br>    # The einsum method calculates (x-mu)T.Sigma-1.(x-mu) as matrix, array, and tensor operations<br>    fac = np.einsum(&#39;...k,kl,...l-&gt;...&#39;, pos - mu, Sigma_inv, pos - mu)<br><br>    return np.exp(-fac / 2) / N<br><br>gauss = gaussian_pulse_2d(pos, mu, Sigma)<br><br>#-----------------------------------------------------<br># Second initial condition (normal modes)<br><br>nx = 35<br>ny = 35<br><br>def normal_modes(pos, nx, ny):<br>    solution = 10 * (np.sin(nx * np.pi * (pos[:, :, 0])) * np.cos(ny * np.pi * (pos[:, :, 1] - 0.5)))<br><br>    return solution<br><br>modes = normal_modes(pos, nx, ny)<br><br>sol_gauss = membrane(gauss, c, dt, dx, dy, tsize, &#39;circle&#39;)<br><br>sol_modes = membrane(modes, c, dt, dx, dy, tsize, &#39;square&#39;)</pre><p>The code for plots and analyses is available in a Jupyter notebook on <a href="https://github.com/Rodrigo-Motta/Computational_Physics/tree/main/Wave_Membrane_%26_Sound">GitHub</a>.</p><h3>Analysis</h3><h4>Normal Modes</h4><p>At the end of the 1700s, the German scientist Ernst Chladni was the first to demonstrate that sound travels through waves, creating a way to visualize their vibrations. The Chladni plate consists of a flat metal sheet, usually circular or square, mounted on a central rod on a sturdy base. When the plate is oscillating in a certain mode of vibration, the nodes and antinodes that are configured form complex but symmetrical patterns on its surface. The positions of these nodes and antinodes can be seen by sprinkling sand on the plates; the sand will vibrate away from the antinodes and gather at the nodes. This was one of the first relationships between 2D membranes, sound, and normal modes. It is possible to visualize these patterns with an analysis of the normal modes of vibration for the rectangular boundary condition case. Fig. 1 shows an example for two different times of the membrane vibrating in the normal mode (<em>Nx</em> = <em>Ny</em> = 2 ), with the wave amplitudes shown in a color gradient for the two different times. Fig. 2 shows the membrane vibrating in the normal mode (<em>Nx</em> = <em>Ny</em> = 3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCuU0ryMkzuedaja-o1v5g.png" /><figcaption>Figure 1: Normal mode (Nx = <em>Ny</em>= 2) for two different times given the parameters (c = 2), (L = 1), (dt = 0.001), (t_f = 2), (dx = 0.01), (dy = 0.01). The units are on the International System of Units.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bpz-h5VG350xIG5Dxkc6cw.png" /><figcaption>Figure 2: Normal mode (Nx = <em>Ny</em>= 3) for two different times given the parameters (c = 2), (L = 1), (dt = 0.001), (t_f = 2), (dx = 0.01), (dy = 0.01). The units are on the International System of Units.</figcaption></figure><p>A very useful visualization is to use the z-axis with the amplitude information as shown in Fig. 3. Another interesting feature is the videos that show the temporal evolution of the membrane, which can be found on <a href="https://github.com/Rodrigo-Motta/Computational_Physics/tree/main/Wave_Membrane_%26_Sound">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1APmT4OeImMg8DoQYJlAaw.png" /><figcaption>Figure 3: Normal mode (n = 3), in 3D visualization, for two different times given the parameters (c = 2), (L = 1), \(dt = 0.001), (t_f = 2), (dx = 0.01), (dy = 0.01). The figure is normalized and the units are on the International System of Units.</figcaption></figure><h4>Gaussian Pulse</h4><p>Another interesting problem to observe is the case of a Gaussian pulse at the center of a circular membrane. In this case, the Cartesian coordinate system was adopted, changing only the boundary conditions of the membrane, i.e., setting the entire perimeter of the circumference to zero. For this scenario, two cases were analyzed: first, a Gaussian pulse at the center of the circumference and then a Gaussian pulse at the edge (Fig. 4 and Fig. 5, respectively). Videos showing the temporal evolution of the membrane for both Gaussian pulses can be found on <a href="https://github.com/Rodrigo-Motta/Computational_Physics/tree/main/Wave_Membrane_%26_Sound">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xj9fev8Ws6X9arzww7EPGQ.png" /><figcaption>Figure 4: Gaussian pulse in 3D visualization, for two different times given the parameters (c = 2), (L = 1), (r = 1), (dt = 0.001), (t_f = 2), (dx = 0.01), (dy = 0.01). The figure is normalized and the units are on the International System of Units.</figcaption></figure><p>Pulse in the edge with boundary conditions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3w6vZIW1PoOFvFOBuo4eQ.png" /><figcaption>Figure 5: Gaussian pulse at the edge in 3D visualization, for two different times given the parameters (c = 2), (L = 1), (r = 1), (dt = 0.001), (t_f = 2), (dx = 0.01), (dy = 0.01). The figure is normalized and the units are on the International System of Units.</figcaption></figure><h4>2D Membrane and Sound</h4><p>A vibrating 2D membrane can be an approximation for the surfaces of speakers or drumheads. As the analytical solution for certain boundary and initial conditions can become quite complicated, numerical resolution allows for expanding the range of possibilities for the system. Using this simplified model, it is possible to simulate the sound from just one of the vibrating points on the membrane, considering that the air molecules will propagate this movement through longitudinal waves to some receptor, as shown in Fig. 6. Using only one point is reasonable when considering a point receptor at a very short distance from the source. Additionally, in this case, it is interesting to use different values of (c), since this constant depends on the surface tension of the membrane as well as the mass density.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4-jlOehAP9O1PbY4G7nrw.png" /><figcaption>Figure 6: Diagram showing how sound propagates from a source to a receiver through a longitudinal wave in the air. The source can be considered as a vibrating membrane. Image credit: [Media College](<a href="https://www.mediacollege.com/audio/01/sound-waves.html">https://www.mediacollege.com/audio/01/sound-waves.html</a>).</figcaption></figure><p>Of course, this does not closely approximate reality, but it provides an intuition about everyday physics. Using a Python library called <em>sounddevice</em>, it was possible to simulate the sound for the two analyzed normal modes and for the Gaussian pulses, considering the sampling frequency as (t_f / dt) Hz. The simulated sounds are available on <a href="https://github.com/Rodrigo-Motta/Computational_Physics/tree/main/Wave_Membrane_%26_Sound">GitHub</a>.</p><h4>Normal Modes and Square Membrane</h4><p>It is possible to interpret the solution for the boundary condition of a square membrane fixed at all sides as the surface of a square speaker box. The normal modes of the solution generate very interesting consequences in everyday life, such as the musical notes of a guitar string. In almost all situations, the superposition of several normal modes is observed, with certain normal modes contributing more to the signal than others. For example, the A note on a guitar will have a greater contribution from the normal modes corresponding to the frequencies of A, even though it contains normal modes corresponding to other tones.</p><p>Thus, using the membrane simulation, it is possible to use a time series from one point to analyze how the signal frequency will change through a Fourier transform, with the frequency given by (t_f / dt), for a pulse on the side and another in the middle of the membrane. For the normal mode (Nx = <em>Ny </em>= 35), the expected result is observed, i.e., a periodic sound with greater intensity for lower frequencies (lower pitch) compared to the normal mode (<em>Nx</em> = <em>Ny</em> = 55), which shows greater intensity for higher frequencies (higher pitch), as shown in Fig. 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*081P6fHXUL-92ONo_VWqdw.png" /><figcaption>Figure 7: Fourier Transform for the normal modes (Nx = Ny = 55\) and (Nx = Ny = 35), given the parameters (c = 2), (L = 1), (r = 1), (dt = 0.001), (t_f = 2), (dx = 0.01), (dy = 0.01). The units are on the International System of Units.</figcaption></figure><h4>Gaussian Pulse and Circular Membrane</h4><p>It is possible to interpret the solution for the boundary condition of a circular membrane fixed around the entire circumference as the surface of a drum, with the Gaussian pulse representing a strike on the instrument. As seen when striking a drum, the edges produce a higher-pitched sound, that is, with higher frequencies, while the center produces a lower-pitched sound, that is, with lower frequencies.</p><p>For the Gaussian pulse in the center of the membrane, the expected result is observed: a periodic sound with greater intensity for lower frequencies (lower pitch) compared to the Gaussian pulse at the edge, which shows greater intensity for higher frequencies (higher pitch), as shown in Fig. 8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UX3jT9vDlIt0kK7yPuwoeQ.png" /><figcaption>Figure 8: Fourier Transform of a Gaussian pulse in the center of the membrane and another at the edge, given the parameters (c = 2), (L = 1), (r = 1), (dt = 0.001), (t_f = 2), (dx = 0.01), (dy = 0.01). The units are on the International System of Units.</figcaption></figure><p>This result reveals various contributions at different frequencies, indicating that an infinite sum of terms is necessary to solve a Gaussian pulse on a circular membrane. It is questionable how much of these contributions are of numerical origin or reveal the actual physics of the solution. However, by increasing the resolution, i.e., decreasing 𝑑𝑡 by 10 times to dt = 0.0001, the spectral analysis remains almost the same, with a spectral peak difference of 0.3%.</p><p>Another revealing analysis is to vary the parameter 𝐶. Since​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*txdsAP3Eah58BzcgUZW1Yg.png" /></figure><p>increasing the surface tension of the drum implies increasing <em>C</em>. By doing so, it is possible to observe an increase in contributions at higher frequencies, as shown in Fig. 10, which is consistent with expectations, as musicians tighten the drum skin to produce higher-pitched sounds. It is worth noting that the simulated sounds are available on <a href="https://github.com/Rodrigo-Motta/Computational_Physics/tree/main/Wave_Membrane_%26_Sound">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Be2d5HdYbpg8s_NJTjMjHA.png" /><figcaption>Figure 9: Musician demonstrating the tensioning of a drum skin. Image credit: <a href="https://www.soundonsound.com/techniques/engineers-guide-tuning-and-damping-drums">Sound on Sound</a>.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5sBaoEPfhM2IpC4xLORDRg.png" /><figcaption>Figure 10: Fourier Transform of a Gaussian pulse in the center of the membrane and another at the edge, given the parameters (c = 10), (L = 1), (r = 1), (dt = 0.0005), (t_f = 2), (dx = 0.01), (dy = 0.01). The units are in SI.</figcaption></figure><h4>Conclusion</h4><p>Although the 2D wave equation in a membrane is a quite simplified model to simulate a drum or a speaker membrane, it was possible to use it as a toy model for these everyday situations, as demonstrated in this work. Situations such as a speaker surface playing a pure normal mode or a pulse on a drum were analyzed, revealing some properties through the numerical signal analysis with the vibrating membrane model, such as the spectral difference in a pulse on the side, where the sound has higher frequencies (more acute), compared to a pulse in the middle of the membrane, where the sound has lower frequencies (more grave). Moreover, it was also possible to perceive the difference in the simulated sound for different normal modes, with the higher frequency normal modes having a greater contribution in high frequencies in the spectral analysis. Thus, the parallel between the 2D membrane model governed by the wave equation and sound can be quite rich, as even a simplified analysis already reveals observable characteristics in everyday life and nature.</p><h4>References</h4><ol><li>Chrysoula; Orphanos Yannis; Bakarezos Makis; Tatarakis Michael; Papadogiannis Nektarios A.; Dimitriou Vasilis Kaselouris, Evaggelos; Alexandraki. Acoustic analysis of impact sound on vibrating circular membranes. INTER-NOISE and NOISE-CON Congress and Conference Proceedings, InterNoise21(3378–3385(8)):2949–3943, 2021.</li><li>Michael Fowler. Libretexts: 2.5 — vibrating membrane. <a href="https://chem.libretexts.org/Bookshelves/Physical_and_Theoretical_Chemistry_Textbook_Maps/Physical_Chemistry_(LibreTexts)/02%3A_The_Classical_Wave_Equation/2.05%3A_A_Vibrating_Membrane">https://chem.libretexts.org/Bookshelves/Physical_and_Theoretical_Chemistry_Textbook_Maps/Physical_Chemistry_(LibreTexts)/02%3A_The_Classical_Wave_Equation/2.05%3A_A_Vibrating_Membrane</a>.</li><li>Michael Richmond. Waves in 2-d. <a href="http://spiff.rit.edu/classes/phys283/lectures/two_d/two_d.html">http://spiff.rit.edu/classes/phys283/lectures/two_d/two_d.html</a>.</li><li>Gabriel T. Landi. Mathematical physics. University of São Paulo, São, Paulo, 1 edition, 2020.</li><li>Thomas Forrister. How do Chladni plates make it possible to visualize sound? <a href="https://www.comsol.com/blogs/how-do-chladni-plates-make-it-possible-to-visualize-sound/">https://www.comsol.com/blogs/how-do-chladni-plates-make-it-possible-to-visualize-sound/</a>.</li><li>Princeton University Press. How sound propagates. <a href="https://assets.press.princeton.edu/chapters/s9912.pdf">https://assets.press.princeton.edu/chapters/s9912.pdf</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b350f6fb1362" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I organized a one-week university course on Deep Learning]]></title>
            <link>https://pub.towardsai.net/how-i-organized-a-one-week-university-course-on-deep-learning-3bf99432f31c?source=rss-d17b17427c47------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bf99432f31c</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rodrigo da Motta Cabral-Carvalho]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 00:02:16 GMT</pubDate>
            <atom:updated>2024-03-09T00:02:16.309Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I Organized a One-week University Course on Deep Learning</h3><p>A hot topic in Data Science is how to teach it. Therefore, if you are looking for ways to detangle this massive topic into clear fields, this article suits you as it presents my experience in organizing a 20-hour course on Deep Learning at <a href="https://www5.usp.br/#english">USP</a>, the best university in Latin America, and how I was able to successfully cover the main topics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XGtCECrswX-1UhTTzn_0aQ.png" /><figcaption>Image from the first day of the course. Image by the author.</figcaption></figure><h3>Introduction</h3><blockquote>The recency and the changing rate of topics turn Data Science, especially Artificial Intelligence, into a complicated field to teach, formulate syllabus and think of teaching approaches.</blockquote><p>The course goal was to provide an introduction to Deep Learning, exploring the most important and relevant topics in the area, as well as an introduction to PyTorch, which is the main Deep Learning framework in academia. The course was aimed at people who already have prior knowledge of programming in the Python language, mainly manipulating Numpy arrays. Furthermore, basic knowledge of linear algebra and probability will be essential.</p><p>The course covered the following topics:</p><ul><li><strong>Fundamentals</strong></li><li><strong>Computer Vision</strong></li><li><strong>Geometric Deep Learning</strong></li><li><strong>Natural Language Processing</strong></li><li><strong>Large Language Models</strong></li></ul><p>We’re going to talk more about how I selected the topics above. Each course day consisted of 4 hours. Therefore, starting with theoretical/conceptual class (1h45), coffee break (30 min), and hands-on (1h45) respectively.</p><h3>How I built the course</h3><p>I created a few steps to think about when I created the course. There is no hierarchy; the idea is to follow these steps temporally, even though each element is not independent of the others. I&#39;m presenting the steps, and then I&#39;m going to describe each one of them more.</p><ul><li><strong>Understand your motivation</strong></li><li><strong>Know your public</strong></li><li><strong>Decide a well-defined scope</strong></li><li><strong>Make the topics talk among themselves</strong></li><li><strong>Filter the right person for each topic</strong></li><li><strong>Balance theory and hands-on</strong></li><li><strong>The Real deal</strong></li></ul><h4>Understand your motivation</h4><p>I’m truly inspired by education and knowledge transfer. There is nothing better than students being excited because they understand a concept. This is important because the other steps follow your motivation. For example, if the idea is to teach Deep Learning to a Data Science team of a company, I would change the structure of the course.</p><h4>Know your public</h4><p>When designing the course, we need to understand really well who the students are. This will define the syllabus, topic depth, communication techniques, and the context of the examples. Since the course was developed for university students, grad and undergrad students were interested. Therefore, this represents people interested in applying the concepts in their research and also to create a toolbox for the Data Science &amp; AI market.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3FpVzvJLYtDKDWR6P6rvg.png" /><figcaption>Forms result of education from the participants. Image by the author.</figcaption></figure><p>Even though all of them are University students, Data Science is inside a huge range of areas. Therefore, the students can have a variety of backgrounds. Then, we need to narrow the profile of these students. Firstly, to talk about Deep Learning, people must know the basics of Linear Algebra and Probability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RzYECYBU9pz7_tmxle6Qcw.png" /><figcaption>Student distribution of Linear Algebra and Probability skills. Image by the author.</figcaption></figure><p>Moreover, knowledge of Machine Learning is also required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*39ABvZNTF5iQrB8tA1WpWA.png" /><figcaption>Student distribution of Machine Learning skills. Image by the author.</figcaption></figure><p>Finally, I am familiar with Python Data Science Frameworks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_dGhhInT21o9ChOv26dSw.png" /><figcaption>Distribution of familiarity with Python libraries. Image by the author.</figcaption></figure><p>These results indicate that students have adequate mathematical concepts of linear algebra and probability but with insufficient machine learning models. This is a clue as to which topics each instructor should explore and focus more in class. For example, there is no necessity to describe Numpy operations and matrix multiplication, however, we should focus on evaluation metrics.</p><h4>Decide a well-defined scope</h4><p>Once we already know our motivation and student profile, we need to decide the range of subjects that will be discussed, including the topics that are relevant and essential to introduce deep learning and the main areas.</p><p>There is a macro-scope, which includes macro-topics such as Gradient Descent in Fundamentals, and a micro-scope, which consists of the subjects inside of macro-topics. For example, Gradient Descent is a part of the macro-scope, but the intricate math of momentum doesn’t. We also want to teach PyTorch, so it’s important to define a scope for the framework.</p><p>With that being said, these are the sub-topics I thought for each of the macro-areas covered:</p><ul><li><strong>Fundamentals</strong></li></ul><p>Machine Learning basics, principles of Multi-Layer Perceptron, Learning Rule, Gradient Descent, Hyper-parameters, Representation learning.</p><p><em>Hands-on:</em> MLP Classification.</p><ul><li><strong>Computer Vision</strong></li></ul><p>Image structured data, Computer Vision tasks, Convolutional Operation, Filters, Auto-Encoder, Latent Space, Fine Tuning.</p><p><em>Hands-on:</em> Implementing an Auto-Encoder.</p><ul><li><strong>Geometric Deep Learning</strong></li></ul><p>Graph Basics, Message Passing Algorithm, Graph Convolutional Layer, Self-Attention, Node &amp; Graph classification.</p><p><em>Hands-on:</em> Document classification.</p><ul><li><strong>Natural Language Processing (NLP)</strong></li></ul><p>Background, Tokens, TF-IDF, Embeddings, Word2Vec, CBOW, Skip Gram, BERT.</p><p><em>Hands-on: </em>Sentiment Analysis.</p><ul><li><strong>Large Language Models (LLM)</strong></li></ul><p>Tokens, Embeddings, The curse of dimensionality, Cosine Similarity, RNN and LSTM, Self-Attention, Auto-encoder, Sentence transformers, LLMs Architecture, training LLMs.</p><p><em>Hands-on:</em> Vector Databases.</p><h4><strong>Make the topics talk among themselves</strong></h4><p>Topics in Deep Learning talk to themselves frequently. It’s very common to see intersections between subjects all the time. Therefore, exploring this interaction is very important from a didactic point of view, where an idea is repeatedly recurrent over classes. But also important to show the methodology in a macro view rather than the subject micro view. Good ideas usually come from importing concepts from different areas to your problem. A great Data Scientist must know how to abstract a methodology from its obvious applications. For example, Transformers architecture is commonly attributed only to NLP, once it’s the most remarkable contribution. However, transformers are super useful for Computer Vision and probabilistic mapping of features in autoencoders. Another good example is recurrence, usually used in the context of time series forecasting, but useful for nearly all Deep Learning topics.</p><h4><strong>Filter the right person for each topic</strong></h4><p>Once the topics and the intersections between them are established, we can start selecting the right person for each topic. The trivial choice would be people with a wide portfolio or post-graduate experience in the topic. This is extremely important, once experience creates a depth of understanding about the subject that leads to the type of results that I’m looking for in a class.</p><p><strong>For this specific course:</strong></p><ul><li><strong>Fundamentals — </strong><a href="https://www.linkedin.com/in/wedeueis-braz-da-silva-823074184/">Wed Braz</a> (currently Manager at Artefact).</li><li><strong>Computer Vision </strong>— <a href="https://www.linkedin.com/in/roberta-duarte-7313b7196/">Roberta Duarte</a> (currently PhD student at the University of São Paulo).</li><li><strong>Geometric Deep Learning — </strong><a href="https://www.linkedin.com/in/rodrigo-da-motta-c-de-carvalho-7422ba181/">Rodrigo da Motta C. Carvalho (myself)</a> (currently a Data Scientist and MS Student in Computational Neuroscience).</li><li><strong>Natural Language Processing </strong>— <a href="https://www.linkedin.com/in/mariana-mercucci/">Mariana Mercucci</a> (currently Senior Data Scientist at Serasa Experian).</li><li><strong>Large Language Models </strong>—<a href="https://www.linkedin.com/in/pedro-vaz-pimenta/"> Pedro Vaz Pimenta</a> (currently Senior Data Scientist at Willow Tree).</li></ul><h4><strong>Balance theory and hands-on</strong></h4><p>Another important step is to balance theory to introduce concepts and practical experience. Theoretical concepts are essential to understanding and using deep learning models; however, as already discussed, experience brings a new depth of understanding of theoretical concepts. This is also central to solidifying the knowledge transfer during the course. Our brain benefits from practical experience (e.g., exercises or projects) to create important neuron connections and really learn hard concepts. The idea of the course is to do an application for each topic using an open-source dataset. The task will be illustrative and explored during the theoretical sections. This is very inspired by the Kaggle challenge and practical examples from framework documentation.</p><h4><strong>The Real deal</strong></h4><p>This is the most complicated part so far. I’ve talked a lot about practical and theoretical combinations. At this point there is just theory about steps and how to accomplish them. Nevertheless, the practice will always be different from the theory. Hence, we need to be ready to adjust differences during the course. For example, the concept of autoencoders and latent space was explored in the Computer Vision class. But these concepts are really hard to digest, and the students were quite confused at the end of the class. That way, I needed to change the macro-topic in the Geometric Deep Learning class in order to cover auto encoders and latent spaces, once these concepts are key.</p><h4>What I learned</h4><p>After the course was over, I was very happy with the results and really motivated by the students. I think that instructors learn way more with the students than studying to prepare for the course. The huge variety of backgrounds was enlightening, Deep Learning is a topic that crosses nearly all fields of knowledge at this moment. Therefore, the students interactions were very enriching and valuable by the multidisciplinary aspect and diversity of ways to see the same concepts. Moreover, the students were pro-activated and interested in the classes, and they also discussed and connected with each other.</p><blockquote>In the end, some students gave me their feedback: This one-week course filled the gap that most DL courses fail to achieve: Good mathematical depth, balance between theory and practice, intersection between subjects, possibility to connect with other students and, my personal favourite, instructors who share real experiences.</blockquote><h4>Conclusion</h4><p>The organization of a one-week university course on Deep Learning at USP makes evident the real challenge that lies in the dynamic of pedagogy, especially in Deep Learning, given the variety of student backgrounds and the recency and the changing rate of topics in Deep Learning. This requires adaptability and responsiveness to address student needs and comprehension levels. This article serves as a testament to addressing difficulties, such as course motivation, knowing the students backgrounds, defining a scope, topic selection, subject intersections, and balance between theory and practice in the realm of Data Science and Artificial Intelligence education.</p><h4>Course material</h4><p><a href="https://www.youtube.com/watch?v=oWuDvjnGdvU&amp;list=PLgK8OuJjPC4Pi5rn9LmCeQuuDVuzj_6TF">The course classes are in Portuguese.</a> However, the translation of the subtitles works well. Furthermore, there is a Google Drive with slides and hands-on exercises.</p><h4>Acknowledgement</h4><p>I would like to thank the <a href="http://portal.if.usp.br/ifusp/en">Institute of Physics</a> of the <a href="https://www5.usp.br/#english">University of São Paulo </a>for the infrastructure, the instructors for kindly offering their time and effort, and <a href="https://www.linkedin.com/company/101053968/admin/feed/posts/">HackerSpace IFUSP</a>, <a href="https://www.linkedin.com/in/victor-tsutsumiuchi/">Victor Tsutsumiuchi</a> and colleagues for the support and assistance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bf99432f31c" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/how-i-organized-a-one-week-university-course-on-deep-learning-3bf99432f31c">How I organized a one-week university course on Deep Learning</a> was originally published in <a href="https://pub.towardsai.net">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From a Deep Learning Model to a Web Application]]></title>
            <link>https://pub.towardsai.net/from-a-deep-learning-model-to-a-web-application-4b289cb55452?source=rss-d17b17427c47------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b289cb55452</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[web-app-development]]></category>
            <dc:creator><![CDATA[Rodrigo da Motta Cabral-Carvalho]]></dc:creator>
            <pubDate>Fri, 16 Feb 2024 18:02:00 GMT</pubDate>
            <atom:updated>2024-02-16T18:02:00.272Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to deploy your deep learning or machine learning service for thousands of people using service into the web using just Python frameworks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jVwSj56xXPPO2sCb" /><figcaption>Photo by <a href="https://unsplash.com/@bugsster?utm_source=medium&amp;utm_medium=referral">Taras Shypka</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Overview</h3><p>It&#39;s very common to see Artificial Intelligence-based web applications in a variety of contexts. However, how to do it simply is still a mystery for many. <strong>Therefore, this article is a tutorial on one of the simplest ways to develop a web application that delivers a Deep Learning service.</strong></p><p>In order to deploy a Deep Learning model into the web, we&#39;re going to use <em>Flask</em> as a web developer framework in Python, <em>ngrok</em> to access the app running in the jupyter notebook for experimentation, <em>REST API</em> to communicate with the application, PyTorch to develop the Deep Learning model. Once the application is ready, you can choose a server to host, such as Heruko, Railway, Render, AWS. In this article, we&#39;re going to use Railway since it&#39;s simple and has a limited free tier.</p><blockquote>Our task is to create a web application that ingests an image file from the user and runs a pre-trained DenseNet to classify the image. The application must ask for the image and print the predicted class. We also want to show the percentage of confidence.</blockquote><p>Firstly, let&#39;s go through the frameworks to develop the app, then the model creation and prediction function, and finally the web deployment.</p><h3>1. Frameworks to develop the app</h3><h4>1.1 Flask</h4><p>As said in the introduction Flaks is a web development python framework, we&#39;re going to use it in order to implement the app. Flask is a micro web framework written in Python. Even though, the &quot;micro&quot; Flaks is incredibly powerful and a simple, fast, robust tool for small projects. It&#39;s very famous for many web applications, REST APIs, and socket-based services. There are other web frameworks such as Django, however, I think that Flask is the best choice for beginners.</p><h4>1.2 Ngrok</h4><p>Ngrok appears to solve a problem that emerges when the application runs in jupyter notebook. The local address for the application is the local address where the notebook is running. Therefore, ngrok turns the local address, where the application will run initially, into another URL.</p><p>To use ngrok, you will need to create a free account on <a href="https://ngrok.com/">ngrok.com</a> and copy your authtoken. Then, it&#39;s just necessary to paste it into this cell at the beginning of the notebook.</p><pre>!ngrok authtoken YOUR_NGROK_AUTHTOKEN</pre><p>Then,</p><pre># Create a Flask app object<br>app = Flask(__name__)<br><br># Define a function to be called when the user accesses the root URL (/)<br>@app.route(&quot;/&quot;)<br>def home():<br>  # application HTML response<br>  return &quot;&lt;h1&gt;That&#39;s my web application :)&lt;/h1&gt;&quot;<br><br><br># You need ngrok to expose the Flask app outside of the notebook<br>run_with_ngrok(app)<br><br># running the app<br>app.run()</pre><p>(Code partially borrowed from <a href="https://deeplearning.neuromatch.io/tutorials/Bonus_DeployModels/student/Bonus_Tutorial1.html">Neuromatch </a><a href="https://deeplearning.neuromatch.io/tutorials/Bonus_DeployModels/student/Bonus_Tutorial1.html">l</a>ecture)</p><p>Which returns locally the application UI. This usage of Flask with Jupyter Notebook by <em>ngrok </em>is super helpful for experimenting with the application UI and functionalities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-syGptoqlyBawEycvVROrg.png" /><figcaption>Preview of the simple HTML template created partially by the code borrowed from <a href="https://deeplearning.neuromatch.io/tutorials/Bonus_DeployModels/student/Bonus_Tutorial1.html">Neuromatch l</a>ecture. Image by the author.</figcaption></figure><h4>1.3 Interface (Jinja2)</h4><p>We still need to create a way for the user to interact with the application. We will define an HTML template to create the interaction. Flask uses Jinja2 framework to acess HTML code. To simplify the process here, let&#39;s use this open-source code from <a href="https://deeplearning.neuromatch.io/tutorials/Bonus_DeployModels/student/Bonus_Tutorial1.html">NeuroMatch</a> lecture*. The template allows the user to select an image from the computer in order to the model to classify it.</p><pre>index_template = &quot;&quot;&quot;<br>&lt;html&gt;<br>    &lt;head&gt;<br>        &lt;!-- Load vue.js and axois.js --&gt;<br>        &lt;script src=&quot;https://cdn.jsdelivr.net/npm/vue/dist/vue.js&quot;&gt;&lt;/script&gt;<br>        &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;!-- The APP UI --&gt;<br>        &lt;div id=&quot;app&quot; style=&quot;width: 50%; margin: 200px auto&quot;&gt;<br>            &lt;form id=&quot;imageForm&quot; enctype=&quot;multipart/form-data&quot; method=&quot;POST&quot; style=&quot;text-align: center; display: block&quot;&gt;<br>                &lt;label for=&quot;imageFile&quot;&gt;Select image to classify:&lt;/label<br>                &gt;&lt;input id=&quot;imageFile&quot; name=&quot;file&quot; type=&quot;file&quot; style=&quot;margin-left: 10px&quot; /&gt;<br><br>                &lt;img v-if=&quot;image&quot; :src=&quot;image&quot; style=&quot;width: 250px; display: block; margin: 50px auto 10px&quot; /&gt;<br>                &lt;div v-if=&quot;prediction&quot; style=&quot;font-size: 32px; font-weight: bold; text-align: center&quot;&gt;<br>                    {{ prediction }}<br>                &lt;/div&gt;<br>                &lt;input v-if=&quot;image&quot; type=&quot;submit&quot; value=&quot;Classify Image&quot; style=&quot;margin: 20px 20px&quot; /&gt;<br>            &lt;/form&gt;<br>        &lt;/div&gt;<br><br>        &lt;script&gt;<br>            &lt;!-- The Vue application --&gt;<br>            var app = new Vue({<br>                el: &quot;#app&quot;,<br>                data() {<br>                    return {<br>                        image: null,<br>                        prediction: null,<br>                    };<br>                },<br>            });<br><br>            &lt;!-- Calling the predict API when the form is submitted --&gt;<br>            document.getElementById(&quot;imageForm&quot;).addEventListener(&quot;submit&quot;, (e) =&gt; {<br>                axios<br>                    .post(&quot;/predict&quot;, new FormData(document.getElementById(&quot;imageForm&quot;)), {<br>                        headers: {<br>                            &quot;Content-Type&quot;: &quot;multipart/form-data&quot;,<br>                        },<br>                    })<br>                    .then((response) =&gt; (app.prediction = response.data));<br><br>                e.preventDefault();<br>            });<br><br>            &lt;!-- Display the selected image --&gt;<br>            document.getElementById(&quot;imageFile&quot;).addEventListener(&quot;change&quot;, (e) =&gt; {<br>                const [file] = document.getElementById(&quot;imageFile&quot;).files;<br>                if (file) {<br>                    app.image = URL.createObjectURL(file);<br>                }<br>            });<br>        &lt;/script&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;<br>&quot;&quot;&quot;</pre><p>The application must show the image to the user and return the class and the confidence of the given class. To execute this HTML template, we just need to change the function as follows. (Code partially borrowed from <a href="https://deeplearning.neuromatch.io/tutorials/Bonus_DeployModels/student/Bonus_Tutorial1.html">Neuromatch l</a>ecture)</p><pre># Serve the template with the interactive UI<br>@app.route(&quot;/&quot;)<br>def home():<br>  return index_template</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C5fuNRC4tWPWDl6dKqNgkQ.png" /><figcaption>HTML template output using the code similar to the <a href="https://deeplearning.neuromatch.io/tutorials/Bonus_DeployModels/student/Bonus_Tutorial1.html">Neuromatch l</a>ecture. Image by the author.</figcaption></figure><h3>2. Deep Learning model</h3><h4>2.1 PyTorch and DenseNet 121</h4><p>In order to implement the data transformations and the Deep Learning model, we&#39;re going to use PyTorch. The idea of this tutorial is to be really straightforward, hence, let&#39;s use a pre-trained <strong><em>densenet121</em></strong> from torchvision models with 1000 classes. This network is based on dense connections of convolutional layers, for more details read the awarded <a href="https://arxiv.org/abs/1608.06993">original article</a>. (Code partially borrowed from <a href="https://deeplearning.neuromatch.io/tutorials/Bonus_DeployModels/student/Bonus_Tutorial1.html">Neuromatch l</a>ecture).</p><pre><br>import torch<br>from torchvision import models<br>import torchvision.transforms as transforms<br><br># Load a pre-trainied DenseNet model from torchvision.models<br>model = models.densenet121(pretrained=True)<br><br># Switch the model to evaluation mode<br>model.eval()<br><br># Load the class labels from a file<br>class_labels_url = &quot;https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt&quot;<br>class_labels = urlopen(class_labels_url).read().decode(&quot;utf-8&quot;).split(&quot;\n&quot;)<br><br># Define the transformation of the input image<br>transform = transforms.Compose([<br>    transforms.Resize(256),<br>    transforms.CenterCrop(224),<br>    transforms.ToTensor(),<br>    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),<br>])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*QWtz0S27vYsDzb5luRfKSA.png" /><figcaption>DenseNet architecture. Image from the Original DenseNet paper.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2mfL-4T1bO1ci_1i6h0Lxg.png" /><figcaption>DenseNet layer details. Image from the Original DenseNet paper.</figcaption></figure><p>If you want to change to your own model, you can load the trained model simply by: (Code by the author)</p><pre># Define the model<br>model = Architecture()<br><br># Load the saved parameters<br>model.load_state_dict(torch.load(&#39;.../model.pth&#39;))<br><br># Switch the model to evaluation mode<br>model.eval()</pre><h4>1.2 Prediction function</h4><p>Now, we need to define a function to create an output for the application that goes directly through the UI.</p><pre>def predict(model, transform, image, class_labels):<br>  # Transform the image and convert it to a tensor<br>  image_tensor = transform(image).unsqueeze(0)<br><br>  ## Switch the model to evaluation mode Pass the image through the model<br>  with torch.no_grad():<br>    output = model(image_tensor)<br><br><br>  # Select the class with the higherst probability and look up the name<br>  m = torch.nn.Softmax(dim=1)<br>  class_prob = round(float(m(output).max()),3)*100<br>  class_id = torch.argmax(output).item()<br>  class_name = class_labels[class_id]<br><br>  # Return the class name<br>  return str(class_name) + &quot; - Confidence: &quot; + str(class_prob) +  &#39;%&#39;</pre><p>(Code partially borrowed from <a href="https://deeplearning.neuromatch.io/tutorials/Bonus_DeployModels/student/Bonus_Tutorial1.html">Neuromatch l</a>ecture)</p><p>This function transforms the input image, passes it to the model, extracts the highest probability with the respective class and outputs the class name and the confidence, which is the Softmax layer output for the given class.</p><p>Therefore, this function should work this way: (Code partially borrowed from <a href="https://deeplearning.neuromatch.io/tutorials/Bonus_DeployModels/student/Bonus_Tutorial1.html">Neuromatch course</a>)</p><pre># Load and display the image<br>image = Image.open(io.BytesIO(urlopen(&quot;https://unsplash.com/photos/2l0CWTpcChI/download?force=true&amp;w=480&quot;).read()))<br>display(image)<br><br># Classify the image<br>display(predict(model, transform, image, class_labels))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U8hzGjKYJNFGCMw-uA0tuA.png" /><figcaption>Function output. Image by the author.</figcaption></figure><h3>3. Incorporating the model into the application</h3><p>Now, we need to incorporate the app developed with the pre-trained model and the prediction function.</p><p>Flask makes this task really easy.</p><pre>app = Flask(__name__)<br><br># Serve the template with the interactive UI<br>@app.route(&quot;/&quot;)<br>def home():<br>  return index_template<br><br><br># Classification API<br>@app.route(&quot;/predict&quot;, methods=[&#39;POST&#39;])<br>def predict_api():<br>  # Fetch the image from the request and convert it to a Pillow image<br>  image_file = request.files[&#39;file&#39;]<br>  image_bytes = image_file.read()<br>  image = Image.open(io.BytesIO(image_bytes))<br><br>  # Predict the class from the image<br>  class_name = predict(model, transform, image, class_labels)<br><br>  # Return the result<br>  return class_name<br><br># Run the app<br>run_with_ngrok(app)<br><br>## Uncomment below to run the app<br>app.run()</pre><p>(Code partially borrowed from <a href="https://deeplearning.neuromatch.io/tutorials/Bonus_DeployModels/student/Bonus_Tutorial1.html">Neuromatch l</a>ecture).</p><p>Looking at the code, there is a core structure that make the connection between the application and the model. The core structure is the <strong><em>predict_api </em></strong>function, which relates the prediction function to the UI HTML template by</p><p><em>@app.route(“/predict”, methods=[‘POST’])</em></p><p>Thus, we already have an entire application to classify images from the user showing the name of the class and the model confidence.</p><h3>6. Deploy application into Web</h3><p>Now, our application is finished, but we also want to deploy it into the web. To deploy the Flask application to the web, you can choose any cloud Platform-as-a-Service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud using pre-configured environments. My recommendation is Railway as the simplest to deploy and has a free tier.</p><p>Once we finish the experimental phase in the notebooks, we can copy the code to a <em>main.py</em> file. We also need to create a <em>requirement.txt </em>file, in order to install all the dependencies into the cloud service, and a <em>Procfile </em>that<em> </em>executes the <em>main.py</em> to initialize the application during deployment.</p><p>The <em>Procfile</em> must contain the following:</p><pre>web: gunicorn app:app</pre><blockquote>The final structure should be in GitHub as follows: <a href="https://github.com/Rodrigo-Motta/deploy_dl.git">https://github.com/Rodrigo-Motta/deploy_dl.git</a></blockquote><h4>Railway</h4><p>This part is the easiest. You just need to create a free account and connect with a GitHub repository and click deploy. Thus, you can access your application over HTTP with the domain shown in the network settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RrvIb0RxMwwpF__26cOfPg.png" /><figcaption>Deploying in Railway. Image by the author.</figcaption></figure><p>For this specific project: <a href="http://web-production-784db.up.railway.app">web-production-784db.up.railway.app</a></p><p>(This URL may not work because sometimes I decide to turn off the application in Railway for some reason)</p><h3>Conclusion</h3><p>In this tutorial, we developed a really simple application that ingests an image from the user, runs a classification deep learning model, and shows the user the predicted class and the confidence given by the Softmax layer. For this task, we used Flask as the micro web framework, <em>ngrok</em> to access the application over the experiments inside a Jupyter Notebook, PyTorch to create the deep learning model, and Railway to deploy the application into the web.</p><h4>Acknowledgments</h4><p>This article was inspired by this amazing lecture: <a href="https://deeplearning.neuromatch.io/tutorials/Bonus_DeployModels/student/Bonus_Tutorial1.html">https://deeplearning.neuromatch.io/tutorials/Bonus_DeployModels/student/Bonus_Tutorial1.html</a>. *The content is under <a href="http://creativecommons.org/licenses/by/4.0/">Creative Commons Attribution 4.0 International License</a>, which allows the copying and redistribution of the material in any medium or format for any purpose, even commercially. In the condition of giving appropriate credit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b289cb55452" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/from-a-deep-learning-model-to-a-web-application-4b289cb55452">From a Deep Learning Model to a Web Application</a> was originally published in <a href="https://pub.towardsai.net">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to MRI: Forget the classical explanations, let's go quantum]]></title>
            <link>https://medium.com/@rodrigodamottacc/introduction-to-mri-forget-the-classical-explanations-lets-go-quantum-c2bc14273437?source=rss-d17b17427c47------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2bc14273437</guid>
            <category><![CDATA[brain]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[quantum]]></category>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[mri]]></category>
            <dc:creator><![CDATA[Rodrigo da Motta Cabral-Carvalho]]></dc:creator>
            <pubDate>Wed, 10 Jan 2024 16:38:35 GMT</pubDate>
            <atom:updated>2025-05-28T15:31:05.984Z</atom:updated>
            <content:encoded><![CDATA[<p>This article, delves into MRI fundamentals and the process to arrive at the final image. Exploring the real phenomena and, therefore, the quantum framework, but without the heavy math.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8jYKj1vSpAD6FbwZ" /><figcaption>Photo by <a href="https://unsplash.com/@nci?utm_source=medium&amp;utm_medium=referral">National Cancer Institute</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Introduction</h3><p>Investigating the brain is a complicated task and the urge for new technologies permeates the advances in Neuroscience. The most remarkable contribution is Magnetic Resonance Imaging (MRI), which is a complicated but powerful non-evasive neuroimaging method that allows structural and functional information. Even though MRI is an essential tool to study the brain, it’s also a very complex technique to understand, given its quantum nature, complicated physics, and robust signal processing. However, most of MRI explanations are based on a classical analogy to cover the quantum nature of Magnetic resonance. My idea here is to explore the real phenomena and, therefore, the quantum framework, but without the heavy math.</p><h3>2. Gentle Introduction to Quantum Mechanics</h3><p>The birth of quantum mechanics was troubled by many different interpretations of the phenomena, explanations, and equations. Despite the old discussions, quantum mechanics interpretations are well established through academia, whence, I want to introduce the basic aspects that enable us to understand what happens in MRI.</p><h4>2.1 The Wave Function and quantum states</h4><p>The Wave Function is a way to model quantum systems, more specifically it’s a mathematical description of quantum states. But what is a quantum state? Quantum particles are fundamentally different from classical particles, we’re used to see particles with a deterministic position and velocity in space. This sounds obvious since in our daily lives we don&#39;t see balls crossing volleyball nets and goals. However, that is not true at all in the subatomic world. We will need some abstraction and trust on me that nature indeed works this way.<strong> The quantum particles are not physical objects in our daily lives sense, they are a &quot;blob&quot; or cloud of probabilities, this means that a sub-atomical particle does not exist in just one coordinate in space, the particle IS in all the places in the &quot;blob&quot; but with different &quot;intensities”.</strong> Now, the wave function turns out to be important, this function is a way to describe the behaviour of this particle and the blob following this equation [1],</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0kwB8Vi_h9CBYocqZe8L_g.png" /></figure><p>But things get more interesting when we measure the property of a quantum particle. Even though the particle IS a &quot;blob&quot; of probabilities, when measured the particle assumes just one value for the given measurement. However, right after of the observation, the particles lose this &quot;deterministic” measurement and return to the &quot;blob&quot;. The value of the measure is very related to the density of the &quot;blob&quot;, if the particles are on high &quot;density” on a given range of values, the measurement is more probable to be in this interval. This means that a measurement collapses the Wave Function (blob) into a single value. Our classical minds like to understand this as ”we found that the particle was in this position”, but this is not how we should interpret quantum phenomena. <strong>The particle is the &quot;blob&quot; and the measurement collapses this blob into a single value that vanishes and the particle returns.</strong> I think that’s enough about wave function quantum states.</p><h4>2.2 Superposition and Spin</h4><p>The Wave Function consists of the existence of multiple states (blob), this is called super-position. <strong>We’re saying that the particle exists in all the possible states but with different probabilities</strong>. Let’s imagine a simple case where a particle just assumes two possible states 0 or 1, however, the particle can exist in a &quot;blob&quot; between these states. For example, the particle could be 50% in state 0 and 50% in state 1, or 22.445% in state 0 and 77.555% in state 1. This is called a two-state system. A way to visualize all possible states is the Bloch Sphere, where the particle is in multiple locations on the sphere surface [1].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*V5sjz6SanOkmRGE2eIThLA.png" /><figcaption>Figure 1: Bloch Sphere. Image from Wikipedia.</figcaption></figure><p>If we measure the particle property, the wave function collapses and the particle must be in state 0 or 1.</p><h4>2.3 Spin and Precession</h4><p>This is a key part of understanding MRI, more specifically Nuclear Magnetic Resonance (NMR), and it’s also where the classical analogy comes in, but let’s go quantum here! Spin is a sub-atomical property, such as charge, or mass, it’s related to rotation because the math follows the angular momentum algebra. However, a particle with spin IS NOT &quot;rotating” in common sense. Another interesting property of spin is that it assumes discrete values, a proton for example assumes spin 1/2 and −1/2. The Spin value is associated with the magnetic moment of the particle through</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*O5QXgLCwYYLdo8ast28DXA.png" /></figure><p>Where <strong><em>μ</em></strong> is the magnetic moment, <strong>S</strong><em> </em>is the spin, and <strong><em>γ</em></strong> is the magnetic constant dependent on the particle (gyromagnetic ratio). So, what is precession from a quantum perspective?<strong> Precession means that the probability of being in each state is changing, it can change periodically, this means to be rotating on the spin block sphere!</strong> [2].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*yLmPt-Z8bxpaEzGrCZs4tw.png" /><figcaption>Figure 2: Rotation on the Bloch Sphere. Image from Wikipedia.</figcaption></figure><h3>3. Nuclear Magnetic Resonance (NMR)</h3><p>Now that we already know that the spin is related to the magnetic moment, and we also know that precession is our Block Sphere for spin states rotating (quantum state periodically changing), then, the magnetic moment must change periodically. Therefore, suppose we place a coil next to this particle, by Len’z Law</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*XzIduSBZ9-2z_8mpuYvDBg.png" /></figure><p>the change in flux <strong>φ</strong>, created by the changing magnetic moment, must create a voltage in the coil.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*j4g7iPrv4az7XSDmFSNWOA.png" /><figcaption>Figure 3: Spining bloch sphere inducing current in the coil. Image from <a href="https://www.youtube.com/watch?v=TQegSF4ZiIQ.">https://www.youtube.com/watch?v=TQegSF4ZiIQ.</a></figcaption></figure><h4>3.1 Larmor Equation</h4><p>The signal produced in the coil follows the Larmor Equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*VoYO0Ap3w7uzBWlXfPccHQ.png" /></figure><p>where <strong>ω</strong> is the precession frequency, <strong><em>γ</em></strong> is the magnetic constant dependent on the particle (gyromagnetic ratio), and <strong><em>B</em></strong><em> </em>is the magnetic field. This current generated in the coil from the changing in quantum state is the NRM signal recorded by the MRI machine. Hence, the final signal is given by the expression</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*E1KeONomqxgJgQyF_jMLiA.png" /></figure><p>where <em>N </em>is the number of spins (considering an ensemble of particles), <strong><em>θ</em></strong> the flip angle in the spin Bloch Sphere, <strong><em>γ</em></strong> the gyromagnetic ratio, <strong><em>B</em></strong><em> </em>the magnetic field, <strong>ω</strong> the precession frequency.</p><h3>4. NMR pipeline</h3><p>The strong MRI magnetic field aligns the nuclei, we’re going to focus on the proton here. Then, the MRI sends radiofrequency (RF) pulses causing the aligned hydrogen protons to absorb energy and flip their spins away from the magnetic field knocking the nuclei out of the alignment, this is the moment where the nucleus will precess and induce the NMR signal into the coil (this is what the scanner detects). However, this precession does not last forever, this is associated with T2 relaxation, then, the nuclei will realign with the magnetic field, which is associated with T1 relaxation.</p><h4>4.1 T2 Relaxation</h4><p>Imagine an ensemble of protons precessing together, after some period of time the entropy wins and the precession alignment between particles decays exponentially. Some particles will precess faster and others slower, therefore, the mean precession is going to zero eventually. This is key to understanding since different tissues are going to experience different decay ratios. This is called the T2 relaxation process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*tUCjmfxTxmXk2xZ8ddcl4Q.png" /><figcaption>Figure 4: T2 Relaxation across tissues. Image from <a href="https://www.youtube.com/watch?v=TQegSF4ZiIQ.">https://www.youtube.com/watch?v=TQegSF4ZiIQ.</a></figcaption></figure><p>But how long should we wait to capture the signal? This is called ”Echo Time” or TE, the idea is to select a TE to maximize the contrast between tissues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*8Ph_gDsXfVa8zX8n4W6ASQ.png" /><figcaption>Figure 5: T2 weighted imaging. Each line represents the decay of tissue, therefore, different tissues have different T2 relaxation time. Image from <a href="https://www.youtube.com/watch?v=TQegSF4ZiIQ.">https://www.youtube.com/watch?v=TQegSF4ZiIQ.</a></figcaption></figure><p>If an Echo Time of zero is selected, the image is known as a ”Spin Density Image”. Hence, the measurement is not T2 anymore, but the Spin density of a given tissue.</p><h3>5. T1 Relaxation</h3><p>Radiofrequency (RF) pulses are then used to temporarily perturb this alignment by flipping the spins of these protons ensemble away from the magnetic field. After the RF pulse is turned off, the protons gradually return to their original alignment along the magnetic field. This return to alignment is known as the T1 relaxation process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*7cfg_zHKQsptqwkd6CI2cA.png" /><figcaption>Figure 6: T1 weighted imaging. Each line represents the realignment of the proton ensem- ble of a given tissue, therefore, different tissues have different T1 relaxation times. Image from <a href="https://www.youtube.com/watch?v=TQegSF4ZiIQ.">https://www.youtube.com/watch?v=TQegSF4ZiIQ.</a></figcaption></figure><p>Again, the question arises: How long should we wait to capture the signal? This is called ”Repetition Time” or TR, the idea is to select a TR to maximize the contrast between tissues. Different tissues exhibit varied T1 relaxation times. Tissues with shorter T1 times appear brighter in T1-weighted images, while tissues with longer T1 times appear darker.</p><h3>6 Magnetic Resonance Equation</h3><p>Switching the reference frame to a rotating one in the same frequency as the spin precession frequency, and sending the radiofrequency pulse, <em>B</em>1, perpendicular to <em>B</em>0 of the same Larmor frequency, ω, as our precessing spin. It’s possible to arrive at a simple equation to describe tissue contrast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*eaXYxsTXMWXdqV42bxDGLg.png" /></figure><p>To simplify</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJg9hLe5jlRv8_POgF-Dsg.png" /></figure><p>This expression has most of the information to get an MRI image. For example, if the MRI operator wants to produce a T2 image, it’s just a matter of adjusting the right parameters TR and TE in order to select the type of image as shown in Figure 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*CndZOYhgBTFMstY4rplUUg.png" /><figcaption>Figure 7: TE and TR adjustments to capture T1,T2 and Spin Density Imaging. Image from <a href="https://www.youtube.com/watch?v=TQegSF4ZiIQ.">https://www.youtube.com/watch?v=TQegSF4ZiIQ.</a></figcaption></figure><h3>7. Spatial encoding and K-space</h3><p>Even though we’ve talked a lot about the methods to capture an image, we did not talk about spatial information of the signal. Therefore, to collect the right location of each signal within the imaging volume, it’s used gradients in the magnetic field to excite differently. These gradients of magnetic fields, which are additional magnetic fields superimposed on the main magnetic field, are applied in the x, y, and z directions and create variations in the magnetic field strength across the imaging volume. To get the exact location of each signal there is a Frequency Enconding, a Phase Enconding, and a Slice selection, the procedure is the same, apply gradients over an axis. The difference between those selections is just the axis where the gradient is being applied. Thus, Frequency Encoding is associated with gradients in the x-axis, Phase Encoding is associated with gradients in the y-axis, and Slice selection is associated with gradients in the z-axis.</p><p>This encoded information is stored in the k-space, which is basically the Fourier Space. Therefore, to reconstruct the image, we just need a simple Inverse Fourier Transform to create the data in the space x,y,z coordinate system. Once all these process is made, we finally arrive at the final MRI image, where the brain is built up in 3D volumes (voxels) in different intensities.</p><h3>Conclusions</h3><p>In conclusion, the quantum world rules the Magnetic Resonance Imaging (MRI) mechanism. By delving into quantum mechanics concepts like the wave function, superposition, spin, and precession, the article explained how these quantum phenomena contribute to Nuclear Magnetic Resonance (NMR) and the subsequent generation of MRI signals. The discussion covered the NMR pipeline, emphasizing the T2 and T1 relaxation processes, the Magnetic Resonance Equation, and the importance of parameter selection. Moreover, spatial encoding and K-space are briefly discussed as essential components in obtaining spatial information for image reconstruction. Overall, this exploration enhances our understanding of the quantum underpinnings of MRI, which is the most important and prominent neuroimaging technique.</p><h3>Acknowledgement</h3><p>This article was inspired by Prof. João Ricardo Sato.</p><h3>References</h3><p>[1] Bernard Cohen-Tannoudji, Bernard Diu, and Franck Laloe. Quantum Mechanics. John Wiley &amp; Sons, New York, 1977.</p><p>[2] Stephen G. Odaibo. A quantum mechanical review of magnetic resonance imaging. 2012.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2bc14273437" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving Autocorrelation Problems in General Linear Model on a Real-World Application]]></title>
            <link>https://medium.com/data-science/solving-autocorrelation-problems-in-general-linear-model-on-a-real-world-application-0bd3eeda20a1?source=rss-d17b17427c47------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bd3eeda20a1</guid>
            <category><![CDATA[fmri]]></category>
            <category><![CDATA[general-linear-model]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[correlation]]></category>
            <dc:creator><![CDATA[Rodrigo da Motta Cabral-Carvalho]]></dc:creator>
            <pubDate>Wed, 13 Dec 2023 18:05:07 GMT</pubDate>
            <atom:updated>2023-12-13T18:05:07.718Z</atom:updated>
            <content:encoded><![CDATA[<h4>Delving into one of the most common nightmares for data scientists</h4><h4>Introduction</h4><p>One of the biggest problems in linear regression is autocorrelated residuals. In this context, this article revisits linear regression, delves into the Cochrane–Orcutt procedure as a way to solve this problem, and explores a real-world application in fMRI brain activation analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hq9ffKCky4wpVoPu" /><figcaption>Photo by <a href="https://unsplash.com/@jontyson?utm_source=medium&amp;utm_medium=referral">Jon Tyson</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><h3>General Linear Model (GLM) revisited</h3><p>Linear regression is probably one of the most important tools for any data scientist. However, it&#39;s common to see many misconceptions being made, especially in the context of time series. Therefore, let&#39;s invest some time revisiting the concept. The primary goal of a GLM in time series analysis is to model the relationship between variables over a sequence of time points. Where <strong><em>Y</em></strong> is the target data, <strong><em>X </em></strong>is the feature data, <strong><em>B</em></strong> and <strong><em>A</em></strong> the coefficients to estimate and <strong><em>Ɛ</em></strong> is the Gaussian error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*kZqyWff9083DLaNHn02BYw.png" /><figcaption>Matrix formulation of the GLM. Image by the author.</figcaption></figure><p>The index refers to the time evolution of the data. Writing in a more compact form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*TxSacFrQqdtJht_X4l1rxg.png" /><figcaption>Matrix formulation of the GLM. Image by the author.</figcaption></figure><p>by the author.</p><p>The estimation of parameters is done through ordinary least squares (OLS), which assumes that the errors, or <strong>residuals</strong>, between the observed values and the values predicted by the model, <strong>are independent and identically distributed (<em>i.i.d</em>)</strong>.</p><blockquote>This means that the residuals must be non-autocorrelated to ensure the right estimation of the coefficients, the validity of the model, and the accuracy of predictions.</blockquote><h3>Autocorrelation</h3><p>Autocorrelation refers to the correlation between observations within a time series. We can understand it as how each data point is related to lagged data points in a sequence.</p><p>Autocorrelation functions (ACF) are used to detect autocorrelation. These methods measure the correlation between a data point and its lagged values (<em>t = 1,2,…,40</em>), revealing if data points are related to preceding or following values. ACF plots (Figure 1) display correlation coefficients at different lags, indicating the strength of autocorrelation, and the statistical significance over the shade region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*MUAXauWGAtDA_Q0kpOKLXw.png" /><figcaption>Figure 1. ACF plot. Image by the author.</figcaption></figure><p>If the coefficients for certain lags significantly differ from zero, it suggests the presence of autocorrelation.</p><h3>Autocorrelation in the residuals</h3><p>Autocorrelation in the residuals suggests that there’s a relationship or dependency between current and past errors in the time series. This correlation pattern indicates that the errors are not random and may be influenced by factors not accounted for in the model. For example, autocorrelation can lead to <strong>biased parameter estimates</strong>, especially in the variance, affecting the understanding of the relationships between variables. This results in <strong>invalid inferences drawn from the model</strong>, leading to misleading conclusions about relationships between variables. Moreover, it results in <strong>inefficient predictions</strong>, which means the model is not capturing correct information.</p><h3><strong>Cochrane–Orcutt procedure</strong></h3><p>The Cochrane–Orcutt procedure is a method famous in econometrics and in a variety of areas to address issues of autocorrelation in a time series through a linear model for serial correlation in the error term [1,2]. We already know that this violates one of the assumptions of ordinary least squares (OLS) regression, which assumes that the errors (residuals) are uncorrelated [1]. Later in the article, we&#39;re going to use the procedure to remove autocorrelation and check how biased the coefficients are.</p><p>The Cochrane–Orcutt procedure goes as follows:</p><ul><li><strong>1. Initial OLS Regression: </strong>Start with an initial regression analysis using ordinary least squares (OLS) to estimate the model parameters.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*8WyjJCJGV2rUi6U-S8bc8Q.png" /><figcaption>Initial regression equation. Image by the author.</figcaption></figure><ul><li><strong>2. Residual Calculation: </strong>Calculate the residuals from the initial regression.</li><li><strong>3. Test for Autocorrelation: </strong>Examine the residuals for the presence of autocorrelation using ACF plots or tests such as the Durbin-Watson test. If the autocorrelation is not significant, there is no need to follow the procedure.</li><li><strong>4. Transformation:</strong> The estimated model is transformed by differencing the dependent and independent variables to remove autocorrelation. The idea here is to make the residuals closer to being uncorrelated.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Ya49rr_t07vZ2mmm_5_QQ.png" /><figcaption>Cochrane–Orcutt formula for autoregressive term AR(1). Image by the author.</figcaption></figure><ul><li><strong>5. Regress the Transformed Model:</strong> Perform a new regression analysis with the transformed model and compute new residuals.</li><li><strong>6. Check for Autocorrelation: </strong>Test the new residuals for autocorrelation again. If autocorrelation remains, go back to step 4 and transform the model further until the residuals show no significant autocorrelation.</li></ul><blockquote>Final Model Estimation:<strong> Once the residuals exhibit no significant autocorrelation, use the final model and coefficients derived from the Cochrane-Orcutt procedure for making inferences and drawing conclusions!</strong></blockquote><h3>Real-world application: Functional Magnetic Resonance Imaging (fMRI) analysis</h3><h4>A brief introduction to fMRI</h4><p>Functional Magnetic Resonance Imaging (fMRI) is a neuroimaging technique that measures and maps brain activity by detecting changes in blood flow. It relies on the principle that neural activity is associated with increased blood flow and oxygenation. In fMRI, when a brain region becomes active, it triggers a hemodynamic response, leading to changes in blood oxygen level-dependent (BOLD) signals. <strong>fMRI data typically consists of 3D images representing the brain activation at different time points, therefore each volume (voxel) of the brain has its own time series (Figure 2).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPFgVes2osq9wmejS6GanQ.png" /><figcaption>Figure 2. Representation of the time series (BOLD signal) from a voxel. Image by the author.</figcaption></figure><h4>The General Linear Model (GLM)</h4><p>The GLM assumes that the measured fMRI signal is a linear combination of different factors (features), such as task information mixed with the expected response of neural activity known as the Hemodynamic Response Function (HRF). For simplicity, we&#39;re going to ignore the nature of the HRF and just assume that it&#39;s an important feature.</p><p>To understand the impact of the tasks on the resulting BOLD signal <strong><em>y (dependent variable)</em></strong>, we&#39;re going to use a GLM. This translates to checking the effect through statistically significant coefficients associated with the task information. Hence, <strong><em>X1</em></strong> and <strong><em>X2</em></strong> <strong><em>(independent variables)</em></strong> are information about the task that was executed by the participant through the data collection convolved with the HRF (Figure 3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*cBCgmkGNtYmx2Xsj-W2YvA.png" /><figcaption>Matrix formulation of the GLM. Image by the author.</figcaption></figure><h4>Application on real data</h4><p>In order to check this Real-World application, we will use data collected by Prof. João Sato at the Federal University of ABC, which is available on <a href="https://github.com/Rodrigo-Motta/GLM_Orcutt">GitHub</a>. The independent variable <em>fmri_data </em>contains data from one voxel (a single time series), but we could do it for every voxel in the brain. The dependent variables that contain the task information are <em>cong </em>and <em>incong</em>. The explanations of these variables are out of the scope of this article.</p><pre>#Reading data<br>fmri_img = nib.load(&#39;/Users/rodrigo/Medium/GLM_Orcutt/Stroop.nii&#39;)<br>cong = np.loadtxt(&#39;/Users/rodrigo/Medium/GLM_Orcutt/congruent.txt&#39;)<br>incong = np.loadtxt(&#39;/Users/rodrigo/Medium/GLM_Orcutt/incongruent.txt&#39;)<br><br>#Get the series from each voxel<br>fmri_data = fmri_img.get_fdata()<br><br>#HRF function<br>HRF = glover(.5)<br><br>#Convolution of task data with HRF<br>conv_cong = np.convolve(cong.ravel(), HRF.ravel(), mode=&#39;same&#39;)<br>conv_incong = np.convolve(incong.ravel(), HRF.ravel(), mode=&#39;same&#39;)</pre><p>Visualising the task information variables (features).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yN3SC4UPnJrFJBULup6EgQ.png" /><figcaption>Figure 3. Task information mixed with Hemodynamic Response Function (features). Image by the author.</figcaption></figure><h4>Fitting GLM</h4><p>Using Ordinary Least Square to fit the model and estimate the model parameters, we get to</p><pre>import statsmodels.api as sm<br><br>#Selecting one voxel (time series)<br>y = fmri_data[20,30,30]<br>x = np.array([conv_incong, conv_cong]).T<br><br>#add constant to predictor variables<br>x = sm.add_constant(x)<br><br>#fit linear regression model<br>model = sm.OLS(y,x).fit()<br><br>#view model summary<br>print(model.summary())<br>params = model.params</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5AqR1XcKqt_3RH-4i7Jovw.png" /><figcaption>BOLD signal and regression. Image by the author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fdkLL86Q9m01gPUrvZknhw.png" /><figcaption>GLM coefficients. Image by the author.</figcaption></figure><blockquote><strong>It&#39;s possible to see that coefficient X1<em> </em>is statistically significant, once P &gt; |t| is less than 0.05. That could mean that the task indeed impact the BOLD signal. </strong>But before using these parameters to do inference, it’s essential to check if the residuals, which means <em>y </em>minus <em>prediction, </em>are not autocorrelated in any lag. Otherwise, our estimate is biased.</blockquote><h4>Checking residuals auto-correlation</h4><p>As already discussed the ACF plot is a good way to check autocorrelation in the series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*guyFQEZhkrKJrGohP8k_ZQ.png" /><figcaption>ACF plot. Image by the author.</figcaption></figure><p>Looking at the ACF plot it’s possible to detect a high autocorrelation at lag 1. Therefore, this linear model is biased and it’s important to fix this problem.</p><h4>Cochrane-Orcutt to solve autocorrelation in residuals</h4><p>The Cochrane-Orcutt procedure is widely used in fMRI data analysis to solve this kind of problem [2]. In this specific case, the lag 1 autocorrelation in the residuals is significant, therefore, we can use the Cochrane–Orcutt formula for the autoregressive term AR(1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Ya49rr_t07vZ2mmm_5_QQ.png" /><figcaption>Cochrane–Orcutt formula for autoregressive term AR(1). Image by the author.</figcaption></figure><pre># LAG 0<br>yt = y[2:180]<br># LAG 1<br>yt1 = y[1:179]<br><br># calculate correlation coef. for lag 1<br>rho= np.corrcoef(yt,yt1)[0,1]<br><br># Cochrane-Orcutt equation<br>Y2= yt - rho*yt1<br>X2 = x[2:180,1:] - rho*x[1:179,1:]</pre><h4>Fitting the transformed Model</h4><p>Fitting the model again but after the Cochrane-Orcutt correction.</p><pre>import statsmodels.api as sm<br><br>#add constant to predictor variables<br>X2 = sm.add_constant(X2)<br><br>#fit linear regression model<br>model = sm.OLS(Y2,X2).fit()<br><br>#view model summary<br>print(model.summary())<br>params = model.params</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8AlJ7dVOvsSwd38hQZz2Dg.png" /><figcaption>BOLD signal and transformed GLM. Image by the author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SQh5WMo-6PBKi35XDlbCYA.png" /><figcaption>GLM coefficients. Image by the author.</figcaption></figure><blockquote>Now the coefficient X1 is not statistically significant anymore, discarding the hypothesis that the task impact the BOLD signal. The parameters standard error estimate changed significantly, which indicates the high impact of autocorrelation in the residuals to the estimation</blockquote><h4>Checking for autocorrelation again</h4><p>This makes sense since it&#39;s possible to show that the variance is always biased when there is autocorrelation [1].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*Xer7SIQkOVwtMz3ecOYrRQ.png" /><figcaption>ACF Plot. Image by the author.</figcaption></figure><p>Now the autocorrelation of the residuals was removed and the estimate is not biased anymore. If we had ignored the autocorrelation in the residuals, we could consider the coefficient significant. However, <strong>after removing the autocorrelation, turns out that the parameter is not significant, avoiding a spurious inference that the task is indeed related to signal.</strong></p><h3>Conclusions</h3><p>Autocorrelation in the residuals of a General Linear Model can lead to biased estimates, inefficient predictions, and invalid inferences. The application of the Cochrane–Orcutt procedure to real-world fMRI data demonstrates its effectiveness in removing autocorrelation from residuals and avoiding false conclusions, ensuring the reliability of model parameters and the accuracy of inferences drawn from the analysis.</p><h4>Remarks</h4><p>Cochrane-Orcutt is just one method to solve autocorrelation in the residuals. However, there are other to address this problem such as Hildreth-Lu Procedure and First Differences Procedure [1].</p><h4>Acknowledgement</h4><p>This project was inspired by Prof. João Ricardo Sato.</p><p><strong>The notebook for this article is available </strong><a href="https://github.com/Rodrigo-Motta/GLM_Orcutt"><strong>here</strong></a><strong>.</strong></p><h4>References</h4><p>[1] <em>Applied Regression Modeling, </em>Iain Pardoe. Wileyl. 2023.<em> </em><a href="https://online.stat.psu.edu/stat462/node/189/">https://online.stat.psu.edu/stat462/node/189/</a></p><p>[2] Sato JR, Takahashi DY, Cardoso EF, Martin Mda G, Amaro Júnior E, Morettin PA. <a href="https://pubmed.ncbi.nlm.nih.gov/23165021/"><em>Intervention models in functional connectivity identification applied to FMRI</em></a>. <em>Int J Biomed Imaging</em>. 2006;2006:27483. doi:10.1155/IJBI/2006/27483</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bd3eeda20a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/solving-autocorrelation-problems-in-general-linear-model-on-a-real-world-application-0bd3eeda20a1">Solving Autocorrelation Problems in General Linear Model on a Real-World Application</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Independent Component Analysis (ICA) on Real-World Applications — EGG Example]]></title>
            <link>https://medium.com/data-science/the-power-of-independent-component-analysis-ica-on-real-world-applications-egg-example-48df336a1bd8?source=rss-d17b17427c47------2</link>
            <guid isPermaLink="false">https://medium.com/p/48df336a1bd8</guid>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[eeg]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[independent-component]]></category>
            <dc:creator><![CDATA[Rodrigo da Motta Cabral-Carvalho]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 18:08:09 GMT</pubDate>
            <atom:updated>2023-10-23T18:17:39.719Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Power of Independent Component Analysis (ICA) on Real-World Applications — EEG Example</h3><h4>Independent component analysis (ICA) is a powerful data-driven tool capable of separating linear contributions in the data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5TKSExLiAB9koTTR" /><figcaption>Photo by <a href="https://unsplash.com/@nci?utm_source=medium&amp;utm_medium=referral">National Cancer Institute</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>Independent component analysis (ICA) is usually associated with dimensionality reduction tasks. However, the technique&#39;s most prominent application is separating linear contributions from the data, finding statistically independent components. For example, ICA is widely used as a tool to separate instrument tracks from audio. The objective of this article is to introduce and motivate ICA with the famous <em>“Cocktail Party”</em>example, then, a brief introduction to how ICA extracts independent components, using the basics of probability and information theory. Then, we explore a practical example of eye blink motion identification and removal from electroencephalogram (EEG) data.</p><h4>Separating contributions from signal and ICA</h4><p>To better understand the separation of linear contributions from the data, the standard example is the <em>&quot;Cocktail Party&quot;. </em>This scenario sets the stage at a bustling cocktail where two individuals engage in conversation, represented by the red (<strong><em>Y1</em></strong>) and blue (<strong><em>Y2</em></strong>) speakers in the room. Thus, two microphones are strategically placed nearby to capture the voices of both individuals, signified by the green (<strong><em>X1</em></strong>) and yellow (<strong><em>X2</em></strong>) microphones. The audibility of these voices varies based on the proximity of the conversationalists to each microphone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*eJWQlPYpRCazIvdRWjdn7w.png" /><figcaption>Illustration of the “<em>Cocktail Party</em>”. The signals are capture by the microphones <em>X1</em> and <em>X2</em>, we want to decompose it to the original sources <em>Y1 </em>e <em>Y2</em>. Image by the author.</figcaption></figure><p>The challenge is how to effectively segregate the two distinct voices from each mixed audio file to acquire isolated audio recordings of each speaker. This enigma can be resolved through the adept application of Independent Component Analysis (ICA). Where, with the right assumptions about the data (that we&#39;re going to see in the next section), each independent component will be the sound of the blue and red spearer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qs28bqQo6bfc19UeeSWdig.png" /><figcaption>Illustration of the ICA decomposition. Image by the author.</figcaption></figure><h4>Basic mechanism of ICA</h4><p>Independent Components Analysis (ICA) seeks a representation of data <strong><em>X </em></strong>using a coordinate system <strong><em>S </em></strong>in which the components <strong><em>Si</em></strong> are independent. Such independent coordinate systems arguably form a natural representation of the data.</p><blockquote><strong>The most important part here is that ICA assume statistically independent component rather than uncorrelated </strong>(such as PCA) [1].</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*Yqz91bb2vdpbaw0FKwWv3Q.png" /><figcaption>Definition of <strong>statistical</strong> <strong>independence</strong>.</figcaption></figure><p>Principal Component Analysis (PCA) assume data and components are normally distributed, when this requirement is met PCA components are statistically independent. However, in a general case where data distribution is non-gaussian, ICA is a strong method to find independent components <strong><em>Y </em></strong><em>(sources) </em>representing the data <strong><em>X </em></strong><em>(signal)</em><strong><em>.</em></strong></p><p>The ICA transformation is given by <strong><em>Y = AX,</em></strong> where the elements of <strong><em>A</em></strong> are the coefficients that define the components. Therefore, it still is a linear method, because it assumes a linear combination between source and signals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*HjxrJC93delGU9vjxx2SiA.png" /></figure><p>We can also take the inverse, which means writing the data according to the ICA components</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*wPtdI7_CMBA_TdSt6ciegg.png" /></figure><blockquote><strong>Since we&#39;re searching for statistically independent components, we want to minimize the information shared between components</strong>.</blockquote><p>Therefore, Information theory is a natural candidate to help us solve this problem. There is a measure of information shared by two random variables <strong><em>X</em></strong> and <strong><em>Y</em></strong>, it&#39;s called Mutual Information</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*XbqiuBbtmFQfr1k2qWiiVw.png" /></figure><p>Hence, we want to minimize the information shared by components,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*Th6fUFpSvh6fyF_UQgMNfw.png" /></figure><p>This is finding <strong><em>A</em></strong> that minimizes <strong><em>I[Y] = I[ AˆT X ]</em></strong>. Thus, the resulting orthogonal vectors lead to most independent components.</p><blockquote>Once, we understand the motivation and the basic mechanism behind ICA, let’s apply it in a real-world situation.</blockquote><h4>Real-World application: Removing eye blink movement from EEG data</h4><p>Electroencephalography (EEG) data is contaminated by various motion artifacts, which occur by voluntary or involuntary patient movement during image acquisition. A common one is the eye blink movement. Thus, tools such as ICA are widely used techniques to remove these kinds of noise [2]. As already discussed, ICA is a way to separate independent contributions of the signal. Hence, intuitively we should expect an important contribution of eye blink movement in channels closer to the eyes.</p><p>EEG measures potential differences across cortical points over time. Therefore, in an EEG experiment, we will have multiple time series from different parts of the cortex with different information about the neural circuits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AtGNSdq1JMxUy59JDO2CaA.png" /><figcaption>EEG time series from multiple channels example. Image by the author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9FF3yi5h3hCMKmXKZvCHRQ.png" /><figcaption>Location of the channels from the example above. Image by the author.</figcaption></figure><p>In order to handle EEG data and apply ICA correctly, we&#39;re going to use <a href="https://mne.tools/stable/index.html"><em>MNE</em></a> ( a library for EEG data handling and analysis). Also, we will use data collected by Prof. João Sato at the Federal University of ABC, which is available on <a href="https://github.com/Rodrigo-Motta/ICA_EEG">GitHub</a>.</p><pre>import pandas as pd<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import mne as mne<br>sns.set_palette(&#39;pastel&#39;)<br><br>eeg = np.loadtxt(&#39;/Users/rodrigo/Post-Grad/Disciplines/Neural Signaling Processing/Aula_3/restEEG/OlhosAbertos.txt&#39;)<br>canais = pd.read_csv(&#39;/Users/rodrigo/Post-Grad/Disciplines/Neural Signaling Processing/Aula_3/restEEG/NOMEScanais.txt&#39;, dtype=&#39;str&#39;, header=None)<br><br># Sampling frequency 250Hz: <br>Hz = 250<br><br>eeg = pd.DataFrame(eeg, columns=canais.iloc[:,0].values)<br>eeg[&#39;Time(s)&#39;] = np.arange(0, (1/Hz)*len(eeg), 1/Hz)</pre><p>Creating MNE EEG object.</p><pre># Creating MNE object<br>mne_info = mne.create_info(<br>                    list(eeg.columns[:-1]),<br>                    Hz,<br>                    ch_types=[&#39;eeg&#39;]*len(eeg.columns[:-1]))<br><br>mne_raw = mne.io.RawArray(eeg.iloc[:,:-1].values.T, mne_info)<br><br># Defining the electrodes architecture<br>standard_1020 = mne.channels.make_standard_montage(&#39;standard_1020&#39;)<br>mne_raw.set_montage(standard_1020)</pre><p>In order to extract just important features, we need to filter the time series to exclude high ( &gt; 120 Hz) and low ( &lt; 4 Hz ) frequencies related to artifacts and noise, and also 60Hz contribution from the environment power line.</p><pre># Set filter parameters<br>lowCut = 4 # Hz<br>highCut = 120 # Hz<br>freqNotch = 60 # Hz (eletric interference from the enviroment)<br><br># Apply bandpass and notch filter<br>mne_raw.filter(lowCut, highCut, fir_design=&#39;firwin&#39;)<br>mne_raw.notch_filter(freqNotch, fir_design=&#39;firwin&#39;)</pre><p>Now, the data is ready to go through ICA.</p><pre>ica_obj = mne.preprocessing.ICA(<br>                    n_components=0.95,<br>                    method=&#39;infomax&#39;,<br>                    max_iter=&quot;auto&quot;,<br>                    random_state=1,<br>                    fit_params=dict(extended=True)).fit(mne_raw)<br><br>ica = ica_obj.get_sources(mne_raw).get_data()<br><br>ica_obj.plot_components(picks=None,show=True, inst=mne_raw)</pre><p>The ICA coefficients are used as a proxy to identify spatial contribution to the signal component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-wtT2FjF4LIZ70nWKtHqA.png" /><figcaption>Illustration of the procedure to associate values to spatial regions for each component. Image by the author.</figcaption></figure><p>Therefore, it&#39;s possible to create heat maps for each component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYY-roDzNDO7mpF55XEDHQ.png" /><figcaption>ICA components. Image by the author.</figcaption></figure><p>The first component is the eye blink movement contribution to the signal. As we expected the contribution is greater in electrodes closer to the eyes. It&#39;s also possible to see more deeply the time/frequency information of the component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6kHo8J0H6kv-0t2gNitiCQ.png" /><figcaption>ICA first component time/frequency information. Image by the author.</figcaption></figure><p>Now, to remove the blink movement artefact from the data, we just reconstruct the signal without this specific component. This means recovering the time series without the patterns associated with the artifact.</p><h4>Conclusion</h4><p>In conclusion, Independent Component Analysis (ICA) is a powerful data-driven tool, that assumes non-gaussian data and linear relationships between source and signals to seek statistically independent components. ICA allows us to separate different contributions to the data, making it particularly useful in scenarios where noise or unwanted signals need to be isolated. In the case of EEG data, ICA can identify and remove motion artifacts like eye blink movements, which can contaminate the neural signal.</p><h4>Remarks</h4><p>It&#39;s important to remark that ICA is a powerful tool that should be used with caution. Data-driven methods, do not assume any prior knowledge about the system. Therefore, confusion and spurious conclusions are common, making it essential to check for the requirements and evaluate the results with attention.</p><h4>Acknowledgements</h4><p>This project was inspired by Prof. João Ricardo Sato.</p><p><strong>The notebook for this article is available </strong><a href="https://github.com/Rodrigo-Motta/ICA_EEG"><strong>here</strong></a><strong>.</strong></p><h4>References</h4><p>[1] Hastie T, Tibshirani R, Friedman J, Hastie T, Tibshirani R, et al.. (2009) Basis expansions and regularization. In: <strong><em>The Elements of Statistical Learning</em></strong>, New York, NY: Springer New York, Springer Series in Statistics.</p><p>[2] Mennes M, Wouters H, Vanrumste B, Lagae L, Stiers P. (2010).<strong><em>Validation of ICA as a tool to remove eye movement artifacts from EEG/ERP</em></strong>. <em>Psychophysiology</em>. 2010;47(6):1142–1150. doi:10.1111/j.1469–8986.2010.01015.x</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48df336a1bd8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-power-of-independent-component-analysis-ica-on-real-world-applications-egg-example-48df336a1bd8">The Power of Independent Component Analysis (ICA) on Real-World Applications — EGG Example</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Does the Uncertainty Principle Limit Time Series Analysis?]]></title>
            <link>https://medium.com/data-science/how-does-the-uncertainty-principle-limit-time-series-analysis-c94c442ba953?source=rss-d17b17427c47------2</link>
            <guid isPermaLink="false">https://medium.com/p/c94c442ba953</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[wavelet-transform]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[fourier-transform]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <dc:creator><![CDATA[Rodrigo da Motta Cabral-Carvalho]]></dc:creator>
            <pubDate>Thu, 31 Aug 2023 07:49:55 GMT</pubDate>
            <atom:updated>2023-08-31T19:49:40.344Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why we can’t extract precise time and frequency information from a time series mutually, and how wavelet analysis can tackle this limitation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k_y2gLn9UlwKGJNJ" /><figcaption>Photo by <a href="https://unsplash.com/@jamie452?utm_source=medium&amp;utm_medium=referral">Jamie Street</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Introduction</h3><p>The connection between the Fourier Transform, Uncertainty Principle, and time series analysis unveils a fascinating interplay that shapes the extraction of simultaneous temporal and frequency information. To understand this relationship, it&#39;s important to first briefly understand what a Fourier Transform (FT) and the uncertainty principle are as a consequence. Then, we explore Wavelet Transform (WT) as a promising tool for this limitation, revealing specific frequency temporal occurrences with sufficient clarity.</p><h4>1.1 Fourier Transform</h4><p>The Fourier Transform (FT) serves as a mathematical bridge between the time and frequency domains of a function. An FT can be described as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*cZnGbs4fK7wMXkfWqgbH2g.png" /></figure><p>I’m not going into detail in this integral, but the important part is that an <strong>FT transforms the function <em>f(x)</em> to another function g<em>(ω)</em> in the frequency space. </strong>Hold that information for later, it’s going to be important. (To better understand the FT I highly recommend the video from <a href="https://www.youtube.com/watch?v=spUNpyF58BY">3Blue1Brow</a>.)</p><h4>1.2 Uncertainty Principle as a Consequence of Fourier Transform</h4><p>In 1927 physicist Werner Heisenberg introduced what is probably one of the most famous concepts about quantum mechanics, the uncertainty principle [1]. <strong>The principle is basically a theorem about Fourier Transforms</strong>, when two functions are a Fourier Transform of one another, the uncertainty principle comes into play.</p><p>While we momentarily sidestep its intricate physics, consider just the essence: <strong>the product of uncertainties in <em>position</em> <em>x</em> and <em>momentum p</em> remains bounded. </strong>This limitation underscores the inherent boundary in measuring these quantities with infinite precision (if you’re interested check out this <a href="https://www.youtube.com/watch?v=a8FTr2qMutA">video</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*UKameqGUuDYnGCvR7MLpaQ.png" /><figcaption>Uncertainty Principle in the context of Physics.</figcaption></figure><p><strong>This happens because position and momentum are a Fourier Transform of each other! </strong>In the case of time series analysis, the analogue of <em>position </em><strong><em>x</em></strong><em> </em>and momentum <strong><em>p</em></strong> is the time series in temporal <strong><em>t</em></strong> and frequency <strong><em>ω</em></strong> space, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*fLWajwQaLHSLK4CelcCn4g.png" /><figcaption>Uncertainty Principle in the context of signal processing.</figcaption></figure><h3>2. Conjuring Frequencies with FT in Time Series</h3><p>A very important application of the Fourier Transform is in time series analysis. Consider a scenario where we need to find the inherent frequencies in the time series. For instance, think about discerning the prevalent frequencies that people re-watch a given content. Therefore, we want to <strong>transform <em>f(t) (a time series) </em>into g(<em>ω</em>), a function of the frequencies, using an FT</strong>.</p><h4>2.1 Example</h4><p>To exemplify let&#39;s use the Mauna Loa Weekly Atmospheric CO2 Dataset [2].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w9Kp8Cj2hiON4Oo4ajTNZw.png" /><figcaption>Mauna Loa Weekly Atmospheric CO2 time series. Image by the author.</figcaption></figure><p>Removing the linear trend to remove fake low-frequency contributions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NLAPRnYU383tev1nEFZenQ.png" /><figcaption>Time series detrended. Image by the author.</figcaption></figure><p>Using the Fast Fourier Transform algorithm (FFT) to calculate the FT:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8z1uB8i7RujASpe5VgRog.png" /><figcaption>Fourier Transform of the time series. Image by the author.</figcaption></figure><p>Whence, it’s possible to obtain the frequency that composes the series, and in this case are visible two distinct peaks, one yearly and the other half-yearly. This is a visualization of the clear seasonality of the dataset.</p><p>However, the most interesting aspects happen when there is a perturbation in the time series, which could be the impact of an event or an external variable (e.g. a near volcano eruption). To simulate this we can take the same series plus a stochastic sine addition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cGjKKUCQNmS_fRLTARciHw.png" /><figcaption>Mauna Loa Weekly Atmospheric CO2 detrended time series plus a perturbation. Image by the author.</figcaption></figure><p>Applying the FFT to get the FT of the series:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qhjcvEng4PTRR4hTaqwDyQ.png" /><figcaption>Fourier transform of the perturbed time series. Image by the author.</figcaption></figure><p>Now, there is another set of peaks between 0.5 and 0.75 that is caused by the perturbation.</p><h4>2.2 The limitation</h4><p>At times, we want to know when the perturbation and frequency change happened, or simply the temporal placement of each frequency within the series. In our simulation o the series with and without perturbation, it&#39;s clear that most of the impact is at the beginning of the series. <strong>Yet, a visual inspection of the series combined with FT information is not enough to know where that perturbation happened. Therefore, we need to find another tool to help us.</strong></p><p><strong>However, the Fourier Transform (FT) comes with a trade-off: it strips away temporal information as the uncertainty principle shows, rendering us unaware of when these frequencies manifest in the series.</strong> This is where the uncertainty principle steps in. Instead of pursuing infinite accuracy in either frequency or time, we can harness the uncertainty principle, allowing us to gain insights into both quantities at a reduced resolution, all the while maintaining balance.</p><h3>3. Wavelet Transform as a tool for Time and Frequency trade-off</h3><p><strong>The Wavelet Transform (WT) emerges as a resolution balancing act, which transforms our function <em>f(t)</em> in <em>F(t,ω)</em>,<em> </em>a composition of time and frequency.</strong> I&#39;m not going into detail about how WT works, but, to summarize, the transformation process uses a series of different wavelets (signals with known frequency and shape) to match temporal synchronization with the time series by dot products of two functions. Hence, it&#39;s possible to get a sense of the frequency and temporal occurrence but limited by less resolution in both quantities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*NRuccgEPUcWpaB_ZeGgKpg.png" /><figcaption>Example of a morlet wavelet signal (it&#39;s a complex signal, hence, there is an imaginary and real part). Image of the author.</figcaption></figure><p>To visualize the wavelet transform of a signal, it&#39;s common to represent the x-axis as the time scale and y-axis as the frequency scale, and the colour scale as the Power of the frequency.</p><p>For the detrended time series without perturbation,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s32aCONp8CKqwIaNMMpNEg.png" /><figcaption>Wavelet Transform of the Mauna Loa Weekly Atmospheric CO2 time series. Image by the author.</figcaption></figure><p>it’s possible to see clearly that the seasonality repeats over the years as we expected by visual inspection. But the huge peak of 1-year seasonality from the FT is now wider, so our certainty about the value decreased.</p><p>The most interesting analysis is for the simulated scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K8UleWD_M2MSrldV8pCLQA.png" /><figcaption>Wavelet Transform of the perturbed time series. Image by the author.</figcaption></figure><p>The WT show that the lower frequency perturbation observed in the FT happens in the early years of the series, with significant consequences after 20–25 years. <strong>Even though the WT lose resolution both in time and frequency, the new information about the frequency occurrence is valuable and capable of answering a variety of questions.</strong></p><h3>4. Conclusion</h3><p>In short, the Uncertainty Principle imposes a fundamental limitation on time series analysis, as revealed by the constraints of the Fourier Transform. While the Fourier Transform efficiently extracts frequency information from time series data, it sacrifices any knowledge of when those frequencies occur. Therefore, the Wavelet Transform is a useful tool that enables us to trade off time and frequency resolution to gain insights into the temporal occurrence of frequency components accepting a degree of uncertainty inherent to the principle.</p><h4>Acknowledgements</h4><p>This amazing video from <a href="https://www.youtube.com/watch?v=jnxqHcObNK4"><strong>Artem Kirsanov</strong></a><strong> </strong>inspired me to do this article. If you do want to go further on this topic I also recommend watching the video.</p><h4>Remarks</h4><ul><li>The Fourier Transform (FT) is super important not only for quantum mechanics and time series analysis. It&#39;s also being used at this exact moment to store this article&#39;s data in a cloud service. One of the most famous and used algorithms in history is called Fast Fourier Transform (FFT) and it’s behind basically every data compression nowadays.</li><li>To model the nature of subatomic particles characteristic mathematically a Fourier Transform appears naturally in quantum mechanics. Reflecting in a fundamental shift of perspective that the uncertainty principle brings to our understanding of nature. Measuring the position of a particle makes you lose information about the velocity of that same particle, and vice-versa.</li></ul><p><strong>The notebook for this article is available </strong><a href="https://github.com/Rodrigo-Motta/wavelet_analysis/tree/main"><strong>here</strong></a><strong>.</strong></p><h4>References</h4><p>[1] <a href="https://en.wikipedia.org/wiki/Uncertainty_principle">https://en.wikipedia.org/wiki/Uncertainty_principle</a></p><p>[2] <a href="https://www.statsmodels.org/dev/datasets/generated/co2.html">https://www.statsmodels.org/dev/datasets/generated/co2.html</a> (public domain)</p><p>[3] <a href="https://en.wikipedia.org/wiki/Wavelet_transform">Wavelet transform (Wikipedia)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c94c442ba953" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-does-the-uncertainty-principle-limit-time-series-analysis-c94c442ba953">How Does the Uncertainty Principle Limit Time Series Analysis?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>