<?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 Evelyn Teng on Medium]]></title>
        <description><![CDATA[Stories by Evelyn Teng on Medium]]></description>
        <link>https://medium.com/@evelynqyteng?source=rss-86a9edfd1309------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xHsZqGzUX9XHeCzMMyHqlQ.png</url>
            <title>Stories by Evelyn Teng on Medium</title>
            <link>https://medium.com/@evelynqyteng?source=rss-86a9edfd1309------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 19:32:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@evelynqyteng/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[Decoding Focus: Categorizing EEG Signals with Python and AI]]></title>
            <link>https://medium.com/@evelynqyteng/decoding-focus-categorizing-eeg-signals-with-python-and-ai-046cb7035653?source=rss-86a9edfd1309------2</link>
            <guid isPermaLink="false">https://medium.com/p/046cb7035653</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[brain-computer-interface]]></category>
            <dc:creator><![CDATA[Evelyn Teng]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 09:55:04 GMT</pubDate>
            <atom:updated>2025-06-06T09:55:04.850Z</atom:updated>
            <content:encoded><![CDATA[<p>For more background on this project, check out my <a href="https://medium.com/@evelynqyteng/lines-and-scribbles-using-python-to-decode-the-brain-3462734f83fd">earlier article on using Python to decode EEG signals</a> and another on <a href="https://medium.com/@evelynqyteng/lines-scribbles-and-an-algorithm-ai-in-brain-mapping-75f7dc30a23e">how AI can be used to determine stages of sleep from brain activity</a>!</p><p>I’ve also made a <a href="https://youtu.be/Wlq7MpQq2Io">video</a>, so if you prefer a quick summary, check it out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41Pt1g5lb5LtiZLHETcMlA.jpeg" /></figure><p>In my previous article, I discussed how AI can be used to identify if someone’s asleep by getting it to analyse no other information other than the person’s brainwaves. But to do that, you have to have labelled data. What if there is no labelled data to assess the accuracy of your AI model? This is the question I asked myself when I decided to use brain activity and Python MNE to determine an individual’s level of focus.</p><p>The inherent challenge in analysing neurophysiological data in this case lies in the scarcity of precisely labelled datasets available online, which can make supervised learning approaches a lot more difficult to validate. Furthermore, the clinical and practical utility of any brain-computer interface relies heavily on the interpretability of its classifications. Reproducibility is equally so, as we must ensure that the developed pipeline can be consistently applied to new data and replicated by other researchers!</p><p>This is why in this article, I walk through a complete EEG signal processing and focus classification pipeline built using Python. The goal is to create an interpretable, reproducible system that:</p><ul><li>Reads EEG data from CSV format</li><li>Preprocesses and cleans the signal</li><li>Extracts relevant frequency features</li><li>Uses the Theta/Beta Ratio (TBR) to quantify attention</li><li>Applies both rule-based and unsupervised learning for classification</li><li>Evaluates the overlap between algorithmic predictions</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4sXLPw652eFLLyb8" /><figcaption>The final result, where the EEG is labelled by focus level</figcaption></figure><p><strong>Background</strong></p><p>Why shift from categorising sleep to categorising focus, you might ask? This is because I’m excited to announce that I’m working on a new project in collaboration with OpenBCI. I’m going to be creating a lightweight, portable brain-monitoring system that helps people understand how focused or stressed they are in real time. It uses non-invasive EEG technology to read brain signals, figure out what mental state you’re in (like focused, tired, or anxious), and then automatically adjusts things like music or screen brightness to help you stay productive. Think of it like a smart environment that listens to your brain and helps you work better.</p><p>The above is still a work in progress, so be sure to stay tuned for updates!</p><p>Now, to dive into the project. For those who might be unfamiliar with how focus is categorised and determined, we break down the brainwave into what is referred to as frequency bins. The ratio between two frequency bins is then taken and used to determine the level of focus!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*9ThFX2lyS-epD4G5" /><figcaption>The different frequencies found in a brainwave. <a href="https://raphaelvallat.com/bandpower.html">Image credit</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*YLmdkS7--kgbSFG7" /><figcaption>The functions of each frequency. <a href="https://www.researchgate.net/publication/249645538_Human_Brain_Mapping_based_on_COLD_Signal_Hemodynamic_Response_and_Electrical_Neuroimaging?_tp=eyJjb250ZXh0Ijp7ImZpcnN0UGFnZSI6Il9kaXJlY3QiLCJwYWdlIjoiX2RpcmVjdCJ9fQ">Image credit</a>.</figcaption></figure><p>EEG measures voltage fluctuations from the scalp, capturing the collective electrical activity of the brain. It offers high temporal resolution (millisecond scale), making it ideal for tracking cognitive changes in real time.</p><p>As stated above, Beta and Theta play a crucial role in focus measurement. <a href="https://pubmed.ncbi.nlm.nih.gov/30604100/">Studies</a> have consistently shown that high Beta is linked to sustained attention, while high Theta is associated with mind-wandering or inattention. Thus, the Beta/Theta Ratio (BTR) becomes a reliable marker of focus: higher ratios indicate higher attention and vice versa</p><p>The data utilized in this project comes from a <a href="https://www.kaggle.com/datasets/amananandrai/complete-eeg-dataset/data">Kaggle database</a>, which contains multi-channel EEG recordings from participants engaged in various mental arithmetic tasks designed to elicit varying levels of cognitive effort and attention.</p><p>We use a CSV-formatted dataset from Kaggle, where each row is a time point and each column is a channel (e.g., Ch1 to Ch14). The first column is time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/0*l6TQA46dCHnCFGgG" /></figure><p>This sets up our data for MNE, a Python library designed for EEG/MEG analysis. We then convert the DataFrame into an MNE RawArray and by structuring data this way, we can use MNE to process the information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xs6nUonz5ZdU3Xf8" /></figure><p><strong>Signal Cleaning with ICA</strong></p><p>It’s important to keep in mind when analysing data that EEG recordings contain noise from eye blinks, muscle tension, and other sources of electrical interference. To isolate the true neural signals, we apply Independent Component Analysis (ICA), which is where EEG signals are broken down into independent parts. It works by finding a way to change the data so that these parts are as unrelated to each other as possible. It’s effective at isolating artifacts (e.g., ocular artifacts are usually low-frequency with a stereotypical shape) without damaging the underlying brain signal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*GNMQCDqyoiSfviNf" /></figure><p><strong>Epoching the Data</strong></p><p>We segment the continuous EEG into 1-second epochs for granular analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/0*l9T2lq_MFpxINmsI" /></figure><p>We do this because neural states fluctuate rapidly. By epoching and breaking the signal into 1-second windows, we can detect local changes in attention levels.</p><p><strong>Feature Extraction with PSD and Band Power</strong></p><p>For each epoch, we compute the Power Spectral Density (PSD) using Welch’s method.</p><p>Welch’s method essentially provides a smooth, low-variance estimate of the PSD while reducing noise via window averaging, and it’s particularly useful when dealing with noisy or non-stationary signals. It involves dividing the signal into overlapping segments, calculating the periodogram (an estimate of the spectral density of a signal) for each segment, and then averaging these periodograms. This averaging process helps reduce the variance of the PSD estimate compared to using a single periodogram.</p><p>We then compute average power in key bands, and we create a variable called “BTR”. This stands for beta/theta ratio. As mentioned above, high beta is a well-established neurophysiological correlate of attention and arousal. Higher BTR is consistently associated with higher focus.</p><p><strong>Smoothing and Outlier Handling</strong></p><p>Since EEG features are inherently noisy due to interference, we want to stabilize BTR trends through smoothing. We then identify and remove any statistical outliers so that our data is as accurate as possible. This improves the signal-to-noise ratio and helps ensure that transient spikes do not mislead the classifier we will be working on later in this project.</p><p>To address this, we apply a rolling median filter, which helps smooth out short-term fluctuations while preserving longer-term structure in the signal. The rolling median over a 5-epoch window acts as a low-pass filter that dampens sudden spikes without being as susceptible to outliers as a rolling mean. This smoothing process helps to accentuate general trends in attention while filtering out noise caused by movement, muscular tension, or transient electrical interference.</p><p>However, even after smoothing, extreme values may still be present. These are often statistical outliers — values far from the norm that may result from rare noise events or momentary lapses in measurement quality. To handle these, we compute Z-scores</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/0*7aMZPenhwodNAQN6" /></figure><p><strong>Adaptive Threshold Classification</strong></p><p>EEG data produced by every brain and every individual is different. What is considered low for someone’s BTR is not necessarily also considered low for someone else. That person might be very focused, or have slightly higher baseline measures of beta or theta. Because we’re unable to retrieve a baseline for these individuals, we have to generate a personalized threshold for BTR in order to prevent misclassification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/0*topeatVpnZqIPOhl" /></figure><p><strong>K-Means Clustering</strong></p><p>We use unsupervised learning to detect patterns in band power. Using K-Means reveals natural groupings in the data. With no labels, clustering helps validate whether our feature space reflects distinct mental states. I’ve also decided to do this in order to compare and validate our rule-based classification, in addition to possibly revealing latent focus states not captured by simple thresholds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/0*0V-Muf9Ee8S8cn21" /></figure><p><strong>Annotation and Visualization</strong></p><p>We can map all of the classifications we’ve made above back to the EEG timeline for visualization. Through this, we can see when the periods of low, medium and high focus are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/0*nMeQ_fhKnVVDuHbD" /></figure><p><strong>PCA for Cluster Visualization</strong></p><p>PCA (Principal Component Analysis) simplifies complex, high-dimensional data for easier visualization and clustering by reducing the number of variables while retaining as much of the original information as possible. By transforming the data into a lower-dimensional space while retaining the most important variance, PCA helps to make cluster structures more apparent. The resulting scatter plot of the first two principal components visually represents the separation (or overlap) of the identified clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*yIeSSEw3H2KQ-L13" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/0*jVy4OnfZkKJAxRSw" /></figure><p><strong>Comparing Approaches (With K-Means Clustering vs. Without)</strong></p><p>We quantify the agreement between our adaptive classification and clustering by calculating the agreement between the two. This agreement metric reveals whether different approaches converge on similar classifications, which can help increase confidence in the pipeline.</p><p>Between all 20 or so datasets that I had, the agreement was anywhere from 30 to 60%. Is that necessarily a bad thing? Not really! It could mean that there are patterns within the data that using normal algorithms was unable to pick up on. This largely stems from the principles behind the two methods. While adaptive thresholding relies solely on the Theta/Beta Ratio, K-Means considers the broader spectral power distribution. The lower-than-perfect agreement could indicate that certain focus-related states are better captured by patterns in the overall frequency spectrum than by the BTR alone, or that the unsupervised learning approach is identifying nuances not explicitly defined by our rule-based system!</p><p><strong>Key Takeaways and Discussion</strong></p><p>Being able to do all of this from scratch without a tutorial or any kind of reference code through easily downloadable software and data online shows just how accessible technology like this is in today. Not only that, but there are also several commercial applications of this technology. The one that is most interesting to me is Neurosity, which is a really cool company aiming to help people improve their focus with neurofeedback.</p><p>I’m hoping to extend this project further with the help of some hardware. Currently, I’m ideating on the following possible extensions:</p><ul><li>Implementing real-time feedback loops for neurofeedback applications</li><li>Using transfer learning to adapt the model to new users with minimal data</li></ul><p>We’re getting ever closer to a future where a wearable device that can track focus levels throughout the day is completely commonplace. This could be revolutionary for people with conditions like ADHD or autism that make focus difficult. From Neurosity alone, we’re already seeing some early-stage consumer applications.</p><p><strong>Author’s Note</strong></p><p>This was my first time ever writing code completely from scratch, so it’s no surprise that this was a challenging project with loads of bugs and hurdles that kept cropping up, but I’m satisfied with the work I’ve done . As with all of my other projects, I’ve definitely learned even more and built on my knowledge and skills. There’s still a lot to explore, especially with the integration of AI into all of this, but I’m excited to refine this even further in the near future, while also hopefully integrating some hardware!</p><p>If this project or my work interests you, feel free to connect with me via email (evelynqyteng@gmail.com), <a href="http://linkedin.com/in/evelyn-teng">LinkedIn</a> or follow my Medium page for future articles!</p><p>Thank you for reading, and I hope you found this as fascinating as I did!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=046cb7035653" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lines, Scribbles, and an Algorithm: AI in Sleep Analysis and Brain Mapping]]></title>
            <link>https://medium.com/@evelynqyteng/lines-scribbles-and-an-algorithm-ai-in-brain-mapping-75f7dc30a23e?source=rss-86a9edfd1309------2</link>
            <guid isPermaLink="false">https://medium.com/p/75f7dc30a23e</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[brain-computer-interface]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[eeg]]></category>
            <dc:creator><![CDATA[Evelyn Teng]]></dc:creator>
            <pubDate>Sun, 09 Feb 2025 14:23:09 GMT</pubDate>
            <atom:updated>2025-02-24T12:42:21.610Z</atom:updated>
            <content:encoded><![CDATA[<p>For more background on this project, check out my <a href="https://medium.com/@evelynqyteng/lines-and-scribbles-using-python-to-decode-the-brain-3462734f83fd">earlier article on using Python to decode EEG signals</a>!</p><p>I’ve also made a <a href="https://youtu.be/ygWfQ3Gr7cU">video</a>, so if you prefer a quick summary, check it out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xdXL4RDaNpU81uDMz9_Tg.png" /><figcaption>Cover Image</figcaption></figure><p>How can we get a computer to identify if someone’s asleep by getting it to analyse <strong>no other information</strong> other than the person’s <strong>brainwaves</strong>? Well, that’s not too difficult, all things considered. If the waves have <strong>big spikes</strong> and are <strong>higher in frequency</strong>, you can essentially get a computer to determine a <strong>threshold</strong> for “asleep” and “awake” states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*isCp13wtz871kfFQ" /><figcaption>Graph showing the time points at which a person is considered to be asleep by analysis of their EEG data</figcaption></figure><p>But what about trying to determine what <a href="https://www.ncbi.nlm.nih.gov/books/NBK526132/#:~:text=Sleep%20occurs%20in%20five%20stages,%2Dfrequency%20(LAMF)%20activity."><strong>stage</strong> of sleep</a> a person is in? Could we employ AI to section a brainwave reading so that we’re able to see exactly when an individual is experiencing a specific stage of sleep? How do we go from a mess of lines to something clearly labelled and annotated?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ts0Ht-DJfVTMaycQ" /><figcaption>The original set of data before analysis</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KTK1JlX9tRjjqDnD" /><figcaption>The data after analysis</figcaption></figure><p><strong>Background</strong></p><p>For those who might be unfamiliar with the different stages of sleep, here’s a visual to hopefully help make it clearer what brainwaves during each stage looks like. Here, we can see that as humans, we might be able to easily classify it manually, but for a computer, this job might be a little more challenging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uKECEj1GtGkzv_pl" /><figcaption><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fcourses.lumenlearning.com%2Fwaymaker-psychology%2Fchapter%2Fstages-of-sleep%2F&amp;psig=AOvVaw25gdcaMwZWgmTYR5kpk_zB&amp;ust=1738213531201000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBQQjRxqFwoTCKjDvZWUmosDFQAAAAAdAAAAABAE">Image Credit</a></figcaption></figure><p>This is where time-series data comes in. Electroencephalography (EEG) time-series data is a mighty tool when it comes to the areas of neuroscience and clinical research, especially in sleep studeis. This is because it’s able to capture the more dynamic changes in our biological systems, making it essential for understanding states like sleep and wakefulness. However, the non-stationary and noise-prone nature of EEG signals requires specialized techniques to extract meaningful patterns, especially when it comes to training machine learning models.</p><p>Hence, I’m going to explore the end-to-end process of classifying EEG segments from a sleep study dataset using machine learning and Python MNE. I’ve split this into four mains sections:</p><ul><li>Data Loading and Preprocessing</li><li>Feature Calculation</li><li>Classification</li><li>Result Analysis</li></ul><p>Before we dive into it, <a href="https://www.youtube.com/watch?v=B8kILqgbxoc">here</a> is where I got the majority of the code used for this project. Massive thank you to Mr Yacine Mahdid for his tutorial and making this publicly available knowledge. The data utilized in this project comes from a 1995 study on age and gender effects in sleep EEG, available on the <a href="https://www.physionet.org/content/sleep-edf/">PhysioNet database</a>.</p><p><strong>The Environment</strong></p><p>I used Jupyter Lab to execute all the code throughout this entire project. A possible alternative is to use Google Colab. In addition to this, I’m using the Python MNE package installations like I’ve done previously. A simple <strong>pip install</strong> and a bunch of <strong>imports</strong> as shown below does the trick in terms of setting up for the bulk of the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ogGhtaca5I7mRLV9" /></figure><p><strong>Data loading and preprocessing</strong></p><p>The first step is to load the EEG data and preprocess it. With the MNE Python library, we’re able to <strong>load</strong> the EEG data, and then preprocess it to <strong>remove the noise and artifacts</strong>. After this, we can then create 30 second long <strong>epochs</strong> of all the EEG data, which basically allows us to split our data into smaller chunks so we’re able to classify them into awake and sleep states later on. Fortunately, for some pieces of data in the dataset, certain events (sleep stages) have already been labelled for us. This will be really useful for us later on, as we can train our model on this data!</p><p>We also establish something called <strong>frequency bands</strong>. This allows us to categorise different types of brainwaves, namely <strong>alpha, beta, theta, sigma and delta</strong>. The general significance of each is as follows:</p><ul><li><strong>Beta</strong> — alert wakefulness, REM sleep</li><li><strong>Alpha</strong> — relaxed wakefulness</li><li><strong>Theta</strong> — light sleep, REM sleep</li><li><strong>Delta</strong> — deep sleep</li><li><strong>Gamma</strong> — increased attention during wakefulness</li></ul><p>We also have different phases of sleep:</p><ul><li><strong>NREM (Non-Rapid Eye Movement) 1 </strong>— The lightest stage of sleep producing predominantly alpha and delta waves</li><li><strong>NREM 2</strong> — The transition from shallow to deep sleep which produces very small spikes in EEG readings</li><li><strong>NREM 3 and 4</strong> — Deep sleep producing predominantly delta and theta waves</li><li><strong>REM Sleep</strong> — Brain activity similar to wakefulness producing mixed frequency brain wave activity closer to that seen in wakefulness</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*_h6iKSivAqjE1MYa" /><figcaption>Frequency bands being used in this model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p-lKAFt6hsnLP2e6" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U4ingOP46nG235fa" /></figure><p>The above data that the computer has displayed shows us how many epochs belong to a specific stage of sleep of a single individual.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sj99zEmynQLBotNW" /></figure><p>This displays the data more graphically, and we can see when the individual was in each sleep stage.</p><p><strong>Feature calculation</strong></p><p>The second step is to <strong>calculate features</strong> (or meaningful summaries) from the EEG data. The feature calculation part is about turning raw EEG data into something that a machine learning model can understand and use to make predictions. It <strong>decomposes</strong> a single brainwave into its respective frequencies (or what we refer to as <strong>“frequency bins”</strong>) of delta, theta, alpha, sigma, and beta. We use something called the <strong>power spectral density (PSD)</strong> to do so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/0*BNiEl1YFjWj59czN" /><figcaption>This is what the different brainwaves look like at different frequencies. Beta has the highest frequency, and delta has the lowest.</figcaption></figure><p>The tutorial I followed employs a method called the <strong>multi-taper method </strong>in order to go about calculating the PSD and decomposing the brainwave. The multi-taper method is a smart way to analyze signals (like EEG data) and figure out how much “<strong>power</strong>” is in different frequency ranges.</p><p>Imagine that an EEG signal is like music playing in a noisy room. You want to hear the real melody (the actual EEG frequencies), but there’s background noise (random fluctuations in the signal). One way to analyze the music would be to listen once and guess the main tune. But if there’s a lot of noise, that guess might not be super accurate. The multi-taper method is like using multiple microphones placed around the room to listen to the music from slightly different angles. With this, each microphone gives you a slightly different version of the song, and by averaging all of them together, you get a much clearer and more reliable idea of what the true melody sounds like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2wVUcCPXK_AJ3OdU" /></figure><p><strong>Classification</strong></p><p>Now that we have useful features in the form of frequency bins, we can use them to train a <strong>Random Forest Classifier</strong> to tell whether a person is awake or asleep.</p><p>Random Forest Classifiers are machine learning algorithms that use an ensemble of multiple decision trees to classify data by aggregating the predictions from each tree. This basically creates a “forest” of decision trees (hence the name) to make a more robust and accurate classification decision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VeXMOvivNv4gk34A" /></figure><p>When testing the model, we can get the computer to predict awake/sleeping states on new EEG data (i.e. the data we <em>didn’t</em> use to train it). After that, we can then compare predictions with real labels in order to compute the accuracy of this model. The accuracy rates were as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/0*3t56_1ScA69NgPcm" /></figure><p>This is a table that shows how many of the predicted labels corresponded with the true labels. This produced an accuracy rate of around 86%, which is relatively accurate!</p><p><strong>Result analysis</strong></p><p>The fourth step is to analyze the results of the classification. We can calculate the <strong>precision, recall, and F1-score </strong>of the classifier. The precision is the percentage of epochs that are predicted to be positive that are actually positive. The recall is the percentage of epochs that are actually positive that are predicted to be positive, and the F1-score is the mean of the precision and recall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*gIoFWAqnc8b3KYQM" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/0*g9ZQnpS8zuZEtUn4" /><figcaption>A confusion matrix generated after the AI is tasked with classifying the data</figcaption></figure><p><strong>True Positive (✅, top left)</strong> → The model correctly predicted “Awake” when the person was actually awake.</p><p><strong>False Negative (❌, top right)</strong> → The model said “Asleep” but the person was actually awake.</p><p><strong>False Positive (❌, bottom left)</strong> → The model said “Awake” but the person was actually asleep.</p><p><strong>True Negative (✅, bottom right)</strong> → The model correctly predicted “Asleep” when the person was actually asleep.</p><p>Instead of just saying “the model has an86% accuracy,” the confusion matrix helps us see where the model is making mistakes.</p><p><strong>Key Takeaways and Discussion</strong></p><p>The ability to decode brain activity like this has a lot of implications — not just in research, but in real-world applications like <strong>healthcare, sleep studies, and brain-computer interfaces</strong>. A future where a wearable device could even track your everyday thought patterns with EEG data is not so far off. We might even be able to design wearable that can <strong>alert you to potential health risks</strong> before they become a problem. This could be revolutionary for early detection of preventable and potentially fatal things like seizures, epilepsy, infection, and inflammation.</p><p>We’re already seeing early-stage consumer applications, from <strong>sleep trackers to neurofeedback tools</strong> for focus and relaxation. But as we move toward more powerful and accessible EEG-based AI systems, we also have to be able to address some issues. For example, how can we ensure <strong>ethical use of data</strong>? How can we make these tools more widely available, with so many EEG-based technologies still expensive and inaccessible to most people?</p><p>As with many other technologies, I believe our next steps must be <strong>scalable, accurate, and responsible</strong>. Both the areas of BCIs and AI are not just futuristic ideas — they’re developing <strong>right now</strong>, and we’re only scratching the surface of what’s possible by merging these two novel technologies</p><p><strong>Author’s Note</strong></p><p>This was my first real deep dive into integrating machine learning with EEG data, and I’ve learned even more through this project and built on my knowledge. There’s still a lot to explore — especially in refining how we classify and interpret brain activity — but I’m excited to build on this in the near future.</p><p>Ultimately, I want to work with a real BCI — one that can collect and interpret my own EEG data in real-time. The idea that we can bridge the gap between brain signals and AI-driven insights is incredibly exciting, and I can’t wait to keep pushing forward!</p><p>If this project or my work interests you, feel free to connect with me via email (evelynqyteng@gmail.com) or follow my Medium page for future articles!</p><p>Thank you for reading, and I hope you found this as fascinating as I did! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75f7dc30a23e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Look at the Future of (Im)Mortality: An Essay]]></title>
            <link>https://medium.com/@evelynqyteng/a-look-at-the-future-of-im-mortality-an-essay-90020fb36dc0?source=rss-86a9edfd1309------2</link>
            <guid isPermaLink="false">https://medium.com/p/90020fb36dc0</guid>
            <category><![CDATA[life]]></category>
            <category><![CDATA[longevity]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[health]]></category>
            <dc:creator><![CDATA[Evelyn Teng]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 14:14:14 GMT</pubDate>
            <atom:updated>2025-02-06T14:14:14.610Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*knt5DAWNoLck0s4C.jpg" /><figcaption><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Ftechcentral.co.za%2Fcould-our-technology-make-us-immortal%2F179854%2F&amp;psig=AOvVaw03_7mpNlMRVLLAypoBPtJj&amp;ust=1738933701727000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBQQjRxqFwoTCKi4xv6Or4sDFQAAAAAdAAAAABAE">Image Credit</a></figcaption></figure><p><strong>A Table of Contents</strong></p><p>Viewing life, longevity and immortality through the lens of:</p><ul><li><strong>Literature</strong></li><li><strong>Technology and Innovations</strong></li><li><strong>Biology</strong></li><li><strong>Cognition and Psychology</strong></li><li><strong>Ethics and Morality</strong></li><li><strong>Practicality and Logistics</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*BCL-hM305nfzfTb8.png" /><figcaption><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fourworldindata.org%2Flife-expectancy&amp;psig=AOvVaw33TWyCZ18dLbYJbE0XNLya&amp;ust=1738935582039000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBQQjRxqFwoTCPCP2oCWr4sDFQAAAAAdAAAAABAE">Image Credit</a></figcaption></figure><p>In the last 200 years, life expectancy has doubled from an average of <a href="https://www.ons.gov.uk/peoplepopulationandcommunity/birthsdeathsandmarriages/lifeexpectancies/articles/howhaslifeexpectancychangedovertime/2015-09-09">40 years to 80</a>. How much longer can we expect this trend to last? Will we get to a point where this graph plateaus, or will death be treated as a disease to be eradicated in its entirety?</p><p><strong>On Transcending Mortality and Antiquating Death</strong></p><p>In <em>The Postmortal</em>, a sci-fi novel by Drew Magary, humanity finds a <strong>cure for ageing</strong> and the human race becomes immortal. In Greg Egan’s <em>Permutation City</em> and Ray Kurzweil’s <em>The Singularity is Near: When Humans Transcend Biology</em>, humanity has found a way to <strong>upload our human consciousness</strong> into computers and live our lives through a simulation (not so dissimilar to <em>Black Mirror</em>’s<em> “San Junipero”</em>). In Richard K. Morgan’s <em>Altered Carbon</em>, human consciousness can be <strong>transferred into different bodies</strong>, and our species could theoretically live on forever.</p><p>These are only a few examples of the many works of literature that have been published, all of which offer us glimpses into futures in which we make ourselves superhuman or even immortal. Although these stories seem largely fictitious, it appears that they are not entirely fantastical.</p><p>So will humanity achieve superhuman abilities and immortality? Is this something we would, or should, aspire to do in the first place?</p><p>But before delving into the complexities of this question, it is important to first <strong>define</strong> the terms “superhuman” and “immortal”. For the sake of a more scientifically-backed and logically sound argument, this essay will take the terms:</p><ul><li>“Superhuman” to mean becoming so technologically advanced that we transcend our current biological capabilities</li><li>“Immortal” to describe humans as organisms that never decay, never age and, hence, never die.</li></ul><p>After all, if it is assumed that “superhuman” and “immortal” means we become god-like and divine, the parameters around that would grow increasingly vague, and this essay would be far too long.</p><p><strong>Technological Evolution</strong></p><p>This then begs a simple, but somewhat unanswerable, question: is it even possible for us to do such a thing? Could we one day become superhuman, immortal and finally evade our most constant companion and enemy: death? Lewis Mumford’s seminal work <em>Technics and Civilization</em> presents a framework that delineates three distinct phases of technological development that humanity has progressed through thus far — the <strong>eotechnic, paleotechnic, and neotechnic</strong> phases — each characterised by different forms of <strong>technological organisation</strong>. It seems that humanity is slowly moving into a new phase which should perhaps be aptly named the <strong>biotechnic</strong> phase, as we seek to integrate technology into our very bodies. In this hypothetical phase, humans may transcend traditional biological limitations through the convergence of <strong>nanotechnology, neuroengineering, and artificial intelligence</strong>. By merging biology with technology, humans may one day achieve levels of cognitive performance previously thought unattainable, and perhaps even physical resilience to the point of immortality.</p><p><strong>The Biological Challenges: Transplants and Nanobots</strong></p><p>To do so, <strong>replacing failing organs, tissues or cells</strong> has emerged as a promising avenue, and some have even begun to speculate on the possibility of <strong>head transplants</strong>. This kind of surgery could be a life-saving procedure for individuals who suffer from a terminal disease, but whose head and brain are healthy.</p><p>Recently, the first <a href="http://www.ncbi.nlm.nih.gov/pmc/articles/PMC6511668/,%20%20https://doi.org/10.26574/maedica.2019.14.1.5">cephalosomatic anastomosis</a> in a human model was successfully performed, confirming the surgical feasibility of the procedure. Still, even with these organ transplants and the constant replacing of what is inside our bodies, we are not immortal. Our brains, what can be considered to be the centre of our consciousness still ages, brain cells and neurons continue to die, and our bodies eventually <strong>grow unable to sustain themselves</strong>. So, can we become any more technologically advanced than we are today in order to prolong or even infinitely sustain our bodies?</p><p>In Don DeLillo’s <em>Zero K</em>, humans achieve immortality by having their bodies <strong>regularly restored</strong>. Cells are constantly refashioned by specialised <strong>nanobots</strong> that also work to augment the brain. From a scientific point of view, this may not actually be so far-fetched. In fact, nanobots can already be engineered to repair cells and tissue, and scientists have been trying to create nanobots that can mimic and reinforce in vivo tissue repair strategies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*pkz95sWzi3uT9q7w.jpg" /><figcaption><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.azonano.com%2Farticle.aspx%3FArticleID%3D5761&amp;psig=AOvVaw2keCSZ1SEoES1nMM2p7KsV&amp;ust=1738936861842000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBQQjRxqFwoTCKiRuOOar4sDFQAAAAAdAAAAABAE">Image Credit</a></figcaption></figure><p>In the last decade, much research has been done on the application of nano-engineered scaffolds designed to replace or restore skin, bone, cardiac and nerve tissues, and the outcomes are certainly promising, with the nanobots tested in clinical trials producing <a href="http://www.mdpi.com/1996-1944/6/4/1333/pdf,%20https://doi.org/10.3390/ma6041333">highly encouraging results</a>. However, there is not yet a <strong>scientifically-backed framework</strong>, and such technology presents many concerns surrounding possible unknown risks and health hazards. It has been found that materials used in more contemporary nanorobot designs might have <a href="http://pubs.rsc.org/en/content/articlelanding/2020/en/d0en00570c#,%20%20https://doi.org/10.1039/D0EN00570C">hazardous properties</a>. For example, some forms of the nickel used to magnetically control nanobot propulsion is known to be <strong>allergenic, carcinogenic, toxic and teratogenic </strong>(i.e. being able to cause birth defects or other abnormalities in a developing fetus) at high doses.</p><p><strong>The Cognitive Challenges: Our Consciousness</strong></p><p>So, although the whole concept of restoring the body through artificial means is <strong>not at all impossible</strong>, it may prove to be dangerous because of several <strong>biological and technological limitations</strong>. In order to achieve immortality, we must also explore other ways to allow what we refer to as our “consciousness” (i.e. our mind and our memories) to persevere. This is where the line between organic and man-made truly begins to break down, and our sense of human and machine blurs.</p><p>From a literary perspective, many seem keen to explore the idea of transferring our consciousness into computers, as suggested by Kurzweil and Egan. After all, what we ultimately seek to preserve is not our body but our <strong>intellectual and cognitive capabilities</strong>. Unfortunately, this process, known as mind uploading, is likely impossible. Neuroscientist Moheb Costandi elaborates that <a href="http://nextbigideaclub.com/magazine/body-new-science-self-consciousness-bookbite/40179/">bodily awareness is critical for self-consciousness</a>, and self-consciousness cannot exist without the body. Hence, it is established that we are not so much limited by the capabilities of technology, as much as we are limited by our own biology. If the body is crucial for self-consciousness, then it follows that a mind uploaded to a supercomputer <strong>could never gain consciousness</strong> because it will be nothing more than a <strong>disembodied virtual brain</strong>. So would this prospect still be appealing to those who wish to immortalise their minds? Our sense of identity would be very much challenged: a stance that Egan presents in his novel <em>Permutation City</em>. There would no doubt be a difference between a computer simulation of a person and a “real” person, given how inseparable we are from our bodies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nuV-RvWDwA99ZvgT" /><figcaption><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.reddit.com%2Fr%2Fsingularity%2Fcomments%2F18b9wch%2Fuploading_your_mind_to_a_computer_will_require_3%2F&amp;psig=AOvVaw3LV2Cs_pEYIfGkUIe5LSwP&amp;ust=1738936925969000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBQQjRxqFwoTCNjSw4Cbr4sDFQAAAAAdAAAAABAS">Image Credit</a></figcaption></figure><p><strong>Ethical Implications: The Value of Life</strong></p><p>But even if we do find a way to make ourselves so resilient to the point of possessing superhuman qualities and resilience to the point of immortality, would we really want to have death antiquated entirely? Will individuals actually want to live on forever?</p><p>In <em>The Denial of Death, </em>Ernest Becker illustrates our two conflicting sides: <strong>Agape and Eros</strong> — the two ways we try to create meaning in our seemingly ephemeral lives and in the face of the immenseness of death. Agape refers to our tendency to achieve transcendence and permanence by creating meaning in our lives through <strong>merging with an ultimate beyond</strong>. On the other hand, we wish to stand out in our current existence through Eros in order to achieve a <strong>sense of individuality and importance in our lives</strong> . We can see Agape in many age-old concepts rooted in <strong>religion, afterlife, and enlightenment</strong>. Eros is evident through our <strong>achievements and never-ending desire for more</strong> in this life. However, should we become immortal, this seems to satisfy both Agape and Eros. The reason they exist in the first place is that humanity needed to find ways to make the <strong>idea of dying more bearable</strong>. If there is no threat of death at all, perhaps we will no longer feel the urge to connect with a higher order through religion; perhaps we won’t feel the need to be so driven all the time to try and create our legacy because now, our time on Earth could be as <strong>infinite as we wish it to be</strong>. It seems it is then possible to assume that immortality is for the betterment of all humanity. There might be less greed in the world as there is no longer the pressing and omnipresent issue of making the most of everything before we die. In the best case scenario, there might be fewer wars and conflicts as a result of religious differences as there is <strong>no longer the fear of dying</strong> and facing the judgement of a higher power or the fear of passing into a dark, empty, abyssal afterlife.</p><p>However, once death has simply become another enemy we’ve conquered, would there be any point in living at all? After all, the meaning of human life desires is <strong>irrevocably bound with our human instincts</strong> (i.e. biologically speaking, “to spread one’s genes”), so what meaning do lives have, and what serves as the basis of values when the limits of our biology no longer forms a part of life? Once the initial relief, happiness and novelty of removing death from the equation has worn off, it seems likely the desire to continue living and the value of life itself will begin to wane. In a study done by van Wijngaarden et al., there appears to be a large percentage of elderly over the age of 70 “<a href="http://www.sciencedirect.com/science/article/pii/S0277953615002889?via%3Dihub,%20%20https://doi.org/10.1016/j.socscimed.2015.05.015">who are tired of life and who consider their life to be completed</a>”. Could this be a likely scenario for individuals who do choose to pursue immortality? And if so, would immortality still be something we desire?</p><p><strong>Practical Implications: Our Current World</strong></p><p>The eradication of death raises <strong>societal and logistical concerns</strong>, too. If death is no longer a natural endpoint, <strong>resource allocation, population control, and societal stability</strong> will likely become issues that grow increasingly more difficult to manage. Even now, with our population at around 8 billion, we struggle with issues such as <strong>unequal food distribution and economic disparities</strong> with <a href="https://medium.com/www.census.gov/library/stories/2023/11/world-population-estimated-eight-billion.html">millions of people</a> worldwide lacking access to their basic needs. If we do choose to make ourselves immortal, our population would continue to rise at an even more exponential rate. Hence, it is imperative that our basic humanitarian issues be ameliorated first, if not completely solved as there are simply <strong>not enough resources</strong> to sustain so many people at the moment.</p><p>Although solving an issue that has plagued humanity for centuries sounds like an idealistic notion, our species has had an excellent track record of finding ways to make everyday life better. Will MacAskill, a philosopher who advocates the idea of effective altruism, argues that if we continue to follow the trend of <a href="https://medium.com/www.ted.com/talks/will_macaskill_what_are_the_most_important_moral_problems_of_our_time">rapid advancement of humankind</a>, we can expect that there will be a point in time not so far in the future where <strong>no one lives in extreme poverty</strong>. There will be a point in time in the next few hundred years where we can expect everyone to be <strong>better off than the richest person alive today</strong>.</p><p>Counter-arguments to this aside, if we can say with a great deal of certainty that coming close to achieving total equality is possible, to allow our population to grow at an even more exponential rate without addressing the problems that those at the bottom of our social hierarchies experience in their everyday lives first would simply be immoral. If we choose to plough ahead, we will only <strong>add to the number of people</strong> who must live at the bottom, struggling to satisfy their basic everyday needs. This is especially the case as we can most certainly anticipate problems such as <strong>disparities</strong> in access to any <strong>biology-enhancing technologies</strong> will arise, further <strong>exacerbating the existing inequalities</strong> we see today, or even creating new forms of <strong>social stratification</strong> if we do not take action to solve our current issues.</p><p><strong>A Conclusion</strong></p><p>Like many other technological advancements, the prospect of gaining immortality and superhuman abilities comes with its own set of complex questions and challenges. While scientific and technological trends seem to paint a future where humanity is likely to transcend its biological limitations, the ethical, existential, and societal implications of such advancements cannot be overlooked. As with many other scientific advancements that are constantly being made, we must wield it as a double-edged sword — one that can carve the salvation of humanity or the destruction of it.</p><p><strong>Author’s Note</strong></p><p>This is the first time I’ve ever written something like this, and it’s very different from the rest of the content on my page at the moment. Even though I’m far more of a tech-focused person, I do still enjoy discussing the more philosophical implications of our scientific innovations. To be honest, this was definitely more of a brain dump of thoughts and an internal monologue than a proper essay!</p><p>If my work, ideas or goals interests you, feel free to connect with me via my email @<a href="/service/mailto:evelynqyteng@gmail.com">evelynqyteng@gmail.com</a>, or keep following my Medium page. You can also find my website and more about me at evelynteng.github.io! I really enjoyed writing this, so I will definitely be considering writing more such essays, especially if this is of interest to lots of people.</p><p>Thank you for reading my article, and I hope you’ve enjoyed it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90020fb36dc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lines and Scribbles: Using Python to Decode the Brain]]></title>
            <link>https://medium.com/@evelynqyteng/lines-and-scribbles-using-python-to-decode-the-brain-3462734f83fd?source=rss-86a9edfd1309------2</link>
            <guid isPermaLink="false">https://medium.com/p/3462734f83fd</guid>
            <category><![CDATA[eeg]]></category>
            <category><![CDATA[brain-computer-interface]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[science]]></category>
            <dc:creator><![CDATA[Evelyn Teng]]></dc:creator>
            <pubDate>Sat, 11 Jan 2025 14:52:50 GMT</pubDate>
            <atom:updated>2025-01-13T02:26:49.935Z</atom:updated>
            <content:encoded><![CDATA[<p>For a slightly shorter video version, <a href="https://youtu.be/Q5t_PhLLvVo">click here</a>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*8Ut-F39m09-r12ckHfeBMg.png" /><figcaption>Cover image</figcaption></figure><p>Wires and electrodes all hooked up to some clunky machine with seemingly random lines on it. How on earth can a person even make sense of what’s coming out?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fjRWKCTkCGJv6j7n" /><figcaption>An EEG graph displaying readings from 9 different electrodes, taken from <a href="https://resources.healthgrades.com/right-care/electroencephalogram-eeg/understanding-your-eeg-results">Understanding Your EEG Results</a></figcaption></figure><p>Bizarre and confusing as it might seem, healthcare practitioners read these graphs on a daily basis to diagnose patients. For the untrained eye, however, there are tools out there to help make sense of these lines. This is where Pybrain comes in: an EEG analysis tool that uses MNE Python, which helps with data processing, source estimation, filtering, artifact removal, visualisation, and machine learning for classification tasks.</p><p>In the real world, being able to analyse an EEG is massively important because an EEG can find changes in brain activity that might aid in diagnosing brain conditions, especially epilepsy or another seizure condition. In addition to this, EEGs make it possible to interpret certain aspects of a person’s mental or cognitive state. For example, brain-computer interface (BCI) systems are examples of EEG systems that allow users nearly real-time control of an external actuator. If we are able to decode the information from an EEG, we get a step closer to being able to put together a BCI.</p><p>In this article, I will be discussing how we’re able to make use of Pybrain and MNE Python to obtain useful information from all this data. I have split this article into 6 main parts, and will be discussing:</p><ul><li>Reading, cropping and filtering data</li><li>BIDS data</li><li>Epoching</li><li>Cleaning epoched data</li><li>Temporal decoding</li><li>Classifiers</li><li>Frequency analysis</li></ul><p>Before we get into it, <a href="https://github.com/hoechenberger/pybrain_mne/tree/main">here</a> is where I got the majority of the code used for this project. Massive thank you to Dr Richard Höchenberger for also creating a video to go along with it, which can be found <a href="https://www.youtube.com/watch?v=t-twhNqgfSY">here</a>.</p><p><strong>The Environment</strong></p><p>Throughout this project, I used Jupyter Lab to execute all the code. In addition to this, Python package installations, specifically the MNE environment, were really important for handling neurophysiological data. I activated and downloaded Anaconda in addition to JupyterLab and the Python MNE environment before running a simple Python command to check if the MNE package is available.</p><p><strong>Part 1: Reading, Cropping and Filtering Raw Data</strong></p><p>The first part of the project was focused on reading, cropping and filtering raw data. Although I would have loved to work with data from a patient, this is only a practice so that I can get used to the process involved. I hope that in future projects, I’m able to recreate this without the help of a tutorial, so I can use a dataset that interests me!</p><p>All the data that I used in here came from samples which can be found on the official <a href="https://mne.tools/stable/documentation/datasets.html">MNE website</a>. EEG data from a 60-channel electrode cap was acquired simultaneously with the MEG. In the experiment that provided this data, checkerboard patterns were presented to the subject into the left and right visual field, interspersed by tones to the left or right ear every 750 ms. Occasionally, a smiley face was presented at the centre of the visual field. The subject was then asked to press a key with the right index finger as soon as possible after the appearance of the face.</p><p>Alright, let’s get started!</p><p>First, we load the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r1H2UK5j3K49cFVY" /></figure><p>Then, we visualise it with raw.plot. Essentially, this process is to manage the many MEG and EEG channels that you can see in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3KfAW2r0km6ac2Zm" /></figure><p>You might notice that some lines are gray in colour. This is because we’ve marked the channel as “bad” because it is producing no signal, so we exclude it from our data.</p><p>We can also visualise where the sensors are, which could help us with seeing which part of the brain is active while processing specific stimuli!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/0*TfFeSsLMD3vbYzxa" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yr7-pIxwdQtl6FuP" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6XcIGy8o0U9KMlwP" /></figure><p>Lastly, we crop the data so that we can focus on a specific time interval. We also make sure to save it so we can use it in the future!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hsnYyPVx8IwFYU5Z" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IxnAGzOeT24aI8T1" /></figure><p><strong>Part 2: BIDS Data</strong></p><p>BIDS stands for Brain Imaging Data Structure. Essentially, BIDS is designed to make data sharing and analysis easier. It was developed to address the lack of standards for capturing, processing, and storing data, which makes it difficult to reproduce findings and share data between labs.</p><p>Before we go ahead and visualise our data, we have to sort something out first. That is, we have to make sure that the tine calibration and crosstalk files are there.</p><ul><li><strong>Fine calibration file</strong>: adjusts for sensor-specific characteristics</li><li><strong>Crosstalk file</strong>: addresses interference from neighboring electrodes, allowing for more precise measurement of brain activity</li><li>Both files are critical for improving data quality by reducing noise and compensating for artifacts (which are unwanted bits of data that is accidentally collected during the recording process).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/0*j_jVjUgcT4mltqbZ" /></figure><p>After reading the input data we want to convert to BIDS so that it turns into a universally understood chunk of data. We can then generate a data summary that looks a little something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FSddtxKZAS3Y_wcW" /><figcaption>A block of text that appears in the codespace. This gives us all the information we need, including the number of participants, the details of that participant, the number of recording sessions and the amount of time recorded.</figcaption></figure><p><strong>Part 3: Creating epochs (epoching) and generating evoked responses</strong></p><p>EEG epoching is a procedure researchers use, where data in specific time-windows are extracted from the continuous EEG signal. These time windows are called “epochs”, and usually are time-locked with respect to an event.</p><p>To create an epoch, we write something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/0*LuIVH0sBpjhCpCTT" /></figure><p>Evoked data is similar, but is basically just an average of epochs. To do that, we put this in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P9RWCD7odIAMUgkQ" /></figure><p>To see things more visually, we can also use Python to topographic maps of EEG data for specific time periods. The tutorial I followed demonstrates a method to visualize differences in global field potentials (GFP) between auditory and visual stimuli.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HD4C-qwNLHRZ7tBp" /></figure><p>With this information, the computer is now able to track each event and plot when it happens, which is really helpful as it allows us to qualitatively see what kind of brain activity is caused by a certain stimulus!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2gmlMVxD10FCsDJ6" /><figcaption>A graph showing the Event ID of each stimulus in addition to the time at which they occur. To the right is a legend that shows what event each coloured line represents and how many of them there are in total.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HtbPdbHb_K-zAaaO" /><figcaption>An EEG plot showing each event/stimulus, as marked by the different coloured lines. What event each coloured line represents will be elaborated more later on in this article.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y41OL6CVIPG4jBXy" /><figcaption>An EEG, gradiometer and magnetometer plot across a given stimulus. Each colour corresponds to the location of the electrode, as mapped in the top left corner of each plot. We can then see which area of the brain is more active during particular stimuli and which are less active. This also gives us more quantitative data by giving us frequency in addition to visual spikes.</figcaption></figure><p><strong>Part 4: Cleaning Epoched Data</strong></p><p>Now that we have sorted our data, it is really important to also clean it. We apply something called baseline correction to improve data accuracy, as it helps to normalize the data for better comparison. This adjustment helps minimise artefacts and enhances signal clarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*vtlrgOOPeamL_kOK" /></figure><p>Artifact rejection is another method of adjustment which helps in eliminating noise from blinks or other physical movements. The common challenge with this, however, is trying to preserve as much data as possible while minimizing the impact of artifacts on the results.</p><p>This tutorial actually talked a lot about the significant data loss during EEG analysis due to artifact rejection (a method of adjustment which helps in eliminating noise from blinks or other physical movements).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/0*v80TCfFUbI6rlJKS" /></figure><p>To deal with this, there are a bunch of different artifact correction methods we can use.</p><p>Signal space projection (SSP) helps to remove artifacts without losing entire epochs by projecting the signal onto a lower-dimensional subspace and calculating the direction of the noise by averaging the pattern across sensors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mr1AaO6qnz8N3g2j" /></figure><p>Independent component analysis (ICA) analyzes EEG signals by breaking them down into independent parts. It works by finding a way to change the data so that these parts are as unrelated to each other as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*wn6pwS9kph6FgENQ" /></figure><p>Since raw data is crucial for accurate epoch analysis in data processing, I also learned that different electrode placements can yield varying levels of artifact impact, and preprocessing can help significantly enhance the effects of artifact detection and correction.</p><p>As we can see from the images below, 15.3% of the epochs were removed (cleaned). The graph shows the randomly generated epochs, and the lines on the graph each represent one channel, with the red representing the data before ICA and the black representing the data after ICA was done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Eip8WfXzmCrKdv1R" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CwB_lOKF3KijQxPp" /></figure><p><strong>Part 5: Temporal Decoding</strong></p><p>Temporal decoding is an approach used to decode specific cognitive processes or stimuli based on the temporal patterns of EEG data. Did you know that researchers have actually used this method to successfully decode which words were heard by participants by analyzing their EEG signals?</p><p>This part of the tutorial addressed the reshaping of measurement data so that it can be turned into a suitable format for training classifiers, a process that is crucial in machine learning. We needed to do something called data scaling which is the process of transforming the values of the features of a dataset till they are within a specific range, e.g. 0 to 1 or -1 to 1. This ensures that no single feature dominates the distance calculations in an algorithm and also resolves issues of floating-point inaccuracies.</p><p>We then train a classifier on this scaled data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MiwYojMrs8eWSEpH" /></figure><p>Here, the classifier is trained to discriminate between experimental conditions by using the spatio-temporal patterns of entire trials. This is why we were able to predict which activation patterns belonged to which condition.</p><p>However, how do we find out when exactly the brain signals for two conditions differ?</p><p>To answer this, we can try to fit a classifier at every single time point. If the classifier can successfully discriminate between the two conditions, we can conclude that the spatial activation patterns measured by the MEG or EEG sensors differed at a very specific time point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HtG-ZeeczK8WQ1UN" /></figure><p>And we cross-validate its accuracy by plotting a box plot to see how well the classifier does when working with non-learned data from the dataset. Ours looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TxBrhMhFaZ4VUkUz" /><figcaption>A box plot showing the cross-validation scores for this specific classifier. A higher score means a more accurate classifier. The range extends from 0.825 to 0.995, with the mean (represented by the green triangle) being at around the 0.91 mark, which is an indicator of strong performance.</figcaption></figure><p>After this, we can generate a line graph that shows what the GFP looks like for each stimulus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JuoX0eX0mGgk_lzw" /><figcaption>A graph showing what the GFP (which quantifies the amount of activity at each time point in the field considering the data from all recording electrodes) looks like for each stimulus. Each line represents a specific stimulus, and from this, we can then see the average of brain activity against time.</figcaption></figure><p><strong>Part 6: Frequency Analysis</strong></p><p>Frequency analysis is a method that examines the frequency domain of EEG waveforms to gain insight into the information they contain. This is also known as spectral analysis and is one of the most common and standard methods for EEG analysis.</p><p>Using this, we can create custom topographic maps for a variety of different frequency ranges. We can use these maps to then compare activation patterns across different electrodes. If you want a more comprehensive overview of the data, these maps can also be linked through joint plots. Using time-frequency analysis, we can also look at inter-trial coherence, and find out brain activity dynamics during different tasks!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Py_d3aQDBmgMU6Uc" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SOkWjlib6WLfF_Iv" /><figcaption>Two topographical maps that shows the location of the signals in addition to the power spectral density (a measure that describes how the power of a signal is distributed across different frequencies). As expected, delta and theta waves (which are associated with deep sleep and relaxation) are less prominent, whereas waves like alpha, beta and gamma are more dominant. This would make sense, since higher frequency waves are associated with states of passive attention and increased cognitive activity.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sqXy0exyhMl1NXVs" /><figcaption>A topographical map showing the mean of electrical activity across all 59 EEG electrodes at a given time interval (0.05s and 0.10s). This shows us the brain regions that are most active at that point in time.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mdijefdzAwJt7nNd" /><figcaption>A map of inter-trial coherence. Each rectangle can be clicked into and analysed at specific time points.</figcaption></figure><p><strong>Key Takeaways and Discussion</strong></p><p>The ability to decode brain activity in this way has very exciting implications for healthcare — think early diagnosis of neurological conditions — or even personalized neurofeedback for mental health. Patients might no longer need to go to a clinic or hospital for a quick diagnosis. Already, this technology is being implemented in wearables to monitor patients who are prone to seizures or strokes. In the future, <em>this</em> could be the technology that saves millions of lives worldwide via early detection.</p><p>Of course, as we move forward, ethical concerns like data privacy and equitable access to these tools will need careful consideration. However, I do believe that with the right regulation, EEG technology will advance into more portable and affordable systems, enabling BCIs for everyday use — whether that’s for gaming, productivity, or rehabilitation. This isn’t even a very far-off dream. As I’ve mentioned before in a previous <a href="https://medium.com/@evelynqyteng/neuroprosthetics-the-future-of-brain-computer-interfaces-and-regenerative-medicine-acc011cc8859">article</a>, this is happening right now before our very eyes.</p><p>I believe the next big step is integrating EEG analysis with AI to make interpretations more precise and accessible. As with all technology, the question is: how do we balance this innovation with responsible use?</p><p><strong>Author’s Note</strong></p><p>This is the first time I’ve ever done something related to data analysis and machine learning. I’ve still got a lot to learn about the topic, but can’t wait to come back with another project and with even more insights!</p><p>My goal in the future is to work on an actual BCI and be able to collect my own data to interpret. I believe BCIs are our future, and we are barely scratching the surface of what it could do.</p><p>If my work or goals interests you, feel free to connect with me via my email @<a href="/service/mailto:evelynqyteng@gmail.com">evelynqyteng@gmail.com</a>, or keep following my Medium page if you would like to learn more. I have a YouTube video about this too, which can be accessed <a href="https://youtu.be/Q5t_PhLLvVo">here</a>!</p><p>Thank you for reading my article, and I hope you’ve enjoyed it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3462734f83fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neuroprosthetics: The Future of Brain-Computer Interfaces and Regenerative Medicine]]></title>
            <link>https://medium.com/@evelynqyteng/neuroprosthetics-the-future-of-brain-computer-interfaces-and-regenerative-medicine-acc011cc8859?source=rss-86a9edfd1309------2</link>
            <guid isPermaLink="false">https://medium.com/p/acc011cc8859</guid>
            <category><![CDATA[biomedical-engineering]]></category>
            <category><![CDATA[brain-computer-interface]]></category>
            <category><![CDATA[neuroprosthetics]]></category>
            <dc:creator><![CDATA[Evelyn Teng]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 08:12:31 GMT</pubDate>
            <atom:updated>2024-10-25T08:12:31.980Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZ2NK4rM1V0BZScWzykoIA.jpeg" /><figcaption>Image taken from <a href="https://neurosciencenews.com/neuroscience-terms/neuroprosthetics/">https://neurosciencenews.com/neuroscience-terms/neuroprosthetics/</a></figcaption></figure><p><strong>An Introduction</strong></p><p>Our perception of the limits of human potential is constantly being reshaped and expanded, and what used to be science fiction is slowly becoming our reality. The theme that ties the most impactful of these technologies together seems to be the fusion of the organic and the inorganic — of biology and technology, of human and machine. No technology better epitomises this than neuroprosthetics and Brain-Computer Interfaces (BCIs). Think about it: what if you could control a robotic arm or regain lost hearing by using thought alone? BCIs make this possible by bypassing the need for <a href="https://www.hopkinsmedicine.org/health/treatment-tests-and-therapies/electromyography-emg#:~:text=Electromyography%20(EMG)%20measures%20muscle%20response,to%20help%20detect%20neuromuscular%20abnormalities.">traditional electromyographical (EMG) microprocessors</a>, which rely on muscle signals, and instead connect artificial devices directly to the brain’s neural pathways. This direct connection enables a level of precision and functionality that was previously unattainable with EMGs.</p><p>At their core, <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3497935/">BCIs</a> are a mix of hardware and software. They acquire brain signals through a series of sensors in the form of sensitive electrodes that detect the minute electrical activity of neurons firing. What makes BCIs so unique is that there are minimally invasive options that don’t involve the embedding of these sensors into the brain itself. Instead, these sensors can be placed virtually anywhere, whether that be on the scalp or positioned around peripheral nerves. Specialised software is then utilised to analyse the data collected, and the data is translated into commands that are relayed to output devices, like a prosthetic limb or an interactive screen.</p><p>This technology offers far more than just restored functionality — it is offering hope to the millions out there who have experienced loss of movement, speech, or sensation due to injury or illness. Patients no longer need to rely solely on muscle signals; they can bypass damaged neural pathways entirely. Beyond this, BCIs also have the potential to enhance natural human abilities, allowing for faster communication, and more efficient interactions with devices. As this technology is being constantly refined, this technology is defining the next wave of innovation.</p><p><strong>Use Cases</strong></p><p>Mobility is a major use case for neuroprosthetics, particularly for individuals who have lost the ability to move due to injury or disease. A real-world, current example of a motor neuroprosthetic is <a href="https://blackrockneurotech.com/insights/blackrock-neurotech-moveagain-brain-computer-interface-system/">Blackrock’s MoveAgain BCI</a> that received FDA approval back in 2021. They</p><p>have claimed that it could “offer improved mobility and independence that leads to returning to work, participating in leisure activities and communicating more effectively and quickly”. It involves an array that is surgically implanted into the brain, which then decodes movement from neuronal activity. The signals are then transmitted wirelessly to an external device, like a cursor or wheelchair, providing people with control over their external environment.</p><p>Mobility is also closely linked with speech. Those who are paralysed often face many issues when it comes to communicating with the people around them. A clinical research publication led by <a href="https://www.youtube.com/watch?v=9oka8hqsOzg">Stanford University investigators</a> in 2017 has demonstrated that a BCI can enable people with paralysis to type via direct brain control at the high speeds and accuracy levels. This technology has only grown and developed in the 7 years since then. As of 2022, Blackrock’s tech enables thought-to-text typing at up to <a href="https://blackrockneurotech.com/insights/thought-to-text-typing-hits-90-charactersminute-with-94-accuracy/">90 characters per minute with a 94% accuracy rate</a>, which has allowed tetraplegic patients to regain agency over their communicative abilities. For those with impairments, spinal cord injuries or degenerative diseases, this has the potential to become a life-changing piece of technology.</p><p>Other than this, BCIs can also restore the senses. Somatosensory neuroprosthetics can be used to restore hearing and sight by directly interfacing with neural pathways. Although cochlear and retinal implants are not yet commercially available, proof-of-concepts already exist, so this might not be such a far-off dream. What currently exists is sensory feedback, as can be seen in <a href="https://cybathlon.ethz.ch/en/teams/neuro-legs">NeuroLegs</a>: a technology developed by ETH Zurich that provides sensory feedback to amputees. What’s unique about this technology is that instead of reading a signal from the brain and sending it to the limb, this device flips things around. It uses a microprocessor to detect an interaction between the prosthetic and the external environment, before converting it into electrical stimulation to stimulate sensation in the stump.</p><p><strong>Challenges and Limitations</strong></p><p>One of the biggest challenges in the development and adoption of BCIs so far is the <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC10403483/#:~:text=Invasive%20BCI%20provides%20a%20more,and%20sophisticated%20signal%20processing%20techniques.">level of invasiveness required</a>. Many of the most precise and reliable BCIs must be surgically implanted into the brain to ensure a direct, accurate connection with neural pathways, while minimising noise and interference. However, these invasive methods come with significant risks, including infection, scarring, and long-term maintenance issues, with users potentially needing to undergo regular surgeries to replace hardware. The prospect of undergoing brain surgery can be daunting for many, and when this technology becomes more commercially available, would likely limit the number of people willing to adopt such technology. In addition</p><p>to this, because BCIs are being placed inside the body, they require <a href="https://www.sciencedirect.com/science/article/pii/S2452199X24003724#:~:text=Biocompatibility%20in%20this%20context%20refers,contact%20with%20the%20listed%20materials.">biocompatible materials</a> to avoid rejection by the body, which complicates design and increases costs.</p><p>On the bright side, researchers are exploring less invasive alternatives, such as non-invasive or minimally invasive BCIs that can detect brain signals without requiring surgery. These include devices that use electroencephalography (EEG) to read signals through electrodes placed on the scalp, or near-infrared spectroscopy (NIRS), which measures brain activity by monitoring blood flow. Although these non-invasive BCIs offer a safer and more comfortable option, they currently lack the precision and reliability of their invasive counterparts. Finding a balance in this trade-off between safety and precision is something that scientists are rapidly finding investigating.</p><p><strong>Future Projections</strong></p><p>Despite the challenges, the future of neuroprosthetics and BCIs is undoubtedly bright. With several exciting and promising research trends that could unlock many new possibilities, it is undeniable that BCIs will only continue to develop and improve in the next few years.</p><p>One promising direction for the future of BCIs involves the integration of external sensors and AI to enhance precision and control. Since invasiveness is such a large issue, it would only be following precedent for there to be research done into how the accuracy and precision external sensors, such as wearable devices or smart implants, can be improved. There is the possibility that BCIs will soon <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7327323/">used in combination with AI</a> to process the vast amounts of data generated by BCIs. Since machine learning algorithms can analyse brain signals in real time, there is the possibility that it will help BCIs recognise patterns and predict the user’s intentions with greater accuracy. For example, AI can help a BCI distinguish between different types of motor commands, such as moving a hand up versus down, or can filter out noise from other neural activity or from external interference. As AI continues to evolve, we can expect even more sophisticated BCIs that are capable of understanding complex commands and adapting to the user’s unique brain patterns.</p><p>Another possibly revolutionary trend in BCI research is the development of <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC10076878/">“closed-loop” systems</a>. Unlike current BCIs, which can only read brain signals, closed-loop systems are designed to both read and stimulate neural pathways. This bidirectional communication would not only allow the BCI to interpret the user’s intentions, but would also enable the BCI to provide feedback to the brain, creating continuous, two-way interactions.</p><p>For instance, a closed-loop BCI could detect when a user intends to move their arm and send a command to a neuroprosthetic to execute the motion. If the BCI detects that the motion was not performed correctly, it could send a signal back to the brain to prompt the user to adjust their movement. This kind of feedback loop has the potential to make neuroprosthetics far more responsive and precise, as it can compensate for any discrepancies in real time. Closed-loop systems are also being explored for their potential to treat neurological disorders. For example, they could be used to monitor and regulate abnormal brain activity in conditions like epilepsy, depression, or Parkinson’s disease. It could combine therapeutic options (such as <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC9954740/">Deep Brain Stimulation and Transcranial Magnetic Stimulation</a>) to provide targeted stimulation that would function to correct disruptions in neural circuits. This approach could lead to more effective and personalized treatments, with fewer side effects as compared to traditional medications.</p><p>While the primary focus of BCIs has been on restoring lost functions and for therapeutic effects, there is growing interest in expanding their use beyond medical applications. Future BCIs could be used to enhance human abilities, which could serve to offer users the option to augment their cognitive and motor skills, and change the way they interact with the world around them. For example, BCIs could be <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7139579/">used in everyday life</a> to control devices such as computers, smartphones, and smart home systems. If you thought activating a virtual assistant like Amazon’s Alexa with your voice is cool, imagine being able to navigate online interfaces, type messages, or operate appliances with thought alone. Not only would this make technology more accessible for people with disabilities, but it could also appeal to the general population as a more efficient and intuitive way to interact with devices.</p><p>Another potential application of BCIs is in cognitive enhancement. Researchers are currently exploring ways to use BCIs to <a href="https://www.researchgate.net/publication/354795317_Cognitive_and_Affective_Brain-Computer_Interfaces_for_Improving_Learning_Strategies_and_Enhancing_Student_Capabilities_A_Systematic_Literature_Review">improve memory, concentration, and learning by stimulating specific brain regions</a>. This might even lead to a new perspective when it comes to education and productivity, as helping students learn more efficiently could become a biological problem and not just a cognitive or mental one.</p><p>I strongly believe that the future of brain-computer interfaces holds immense promise. While it also presents its own set of unique challenges, these problems pale in comparison to the benefits BCIs can bring. As we move forward, the integration of BCIs into our daily lives seems likely and it will not only improve the quality of life for people with disabilities but could also redefine how we perform our everyday tasks. With the rate that our technology is developing, we are getting closer and closer to the fusion of the human mind and machine technology.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acc011cc8859" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>