<?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 Serjan Kaur on Medium]]></title>
        <description><![CDATA[Stories by Serjan Kaur on Medium]]></description>
        <link>https://medium.com/@serjankaur?source=rss-ec4ee2f63df8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Lc1kjOH2R7sqTLZNJAGyWg@2x.jpeg</url>
            <title>Stories by Serjan Kaur on Medium</title>
            <link>https://medium.com/@serjankaur?source=rss-ec4ee2f63df8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 03:33:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@serjankaur/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[Uncovering the Surprise Response: Using Machine Learning to Analyze EEG Data]]></title>
            <link>https://medium.com/@serjankaur/uncovering-the-surprise-response-using-machine-learning-to-analyze-eeg-data-a2e1afd6d450?source=rss-ec4ee2f63df8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2e1afd6d450</guid>
            <category><![CDATA[neurotechnology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[eeg]]></category>
            <dc:creator><![CDATA[Serjan Kaur]]></dc:creator>
            <pubDate>Fri, 30 Dec 2022 16:34:39 GMT</pubDate>
            <atom:updated>2022-12-30T16:42:54.068Z</atom:updated>
            <content:encoded><![CDATA[<p>TLDR -&gt;</p><p>∘ <a href="#7247">But like, why?</a><br>· <a href="#434d">Neural interface→</a><br>· <a href="#7d91">The Challenge</a><br>· <a href="#f1f7">Types of Model (some of the many) →</a><br>· <a href="#0caf">Breaking down the code →</a><br>· <a href="#60d3">Now finally, Supervised Learning</a><br>· <a href="#ae2a">Lets now verify the neural network</a><br>· <a href="#3db1">Dataset</a><br>· <a href="#cbb5">LAST, WE CONNECT THE DATA AND THE NETWORK!</a></p><h4>But like, why?</h4><p>Real problems are rarely simple, complex issues aren’t exactly a piece of cake, so scientists often simplify them to get a handle on things. But even with a simplified model, coming up with theories about the real deal is still a daunting task — full of errors, difficulties, and snail-like progress. Ain’t science grand?</p><p>For example, we can look at the global economy. Trying to make sense of the global economy is like trying to solve a Rubik’s Cube blindfolded. There’s just too many variables — from big investment firms’ fancy schmancy strategies to how much risk a single trader is willing to take on. And let’s face it, our brains are about as equipped to handle all that complexity as a hamster is to fly a plane. That’s where machine-run algorithms come in handy — they’re like supercomputers that can solve the economy’s Rubik’s Cube in no time flat, with all the precision of a laser beam.</p><h3>Neural interface→</h3><p>Human brains are extremely complex systems, and studying them can be quite challenging. One issue is that we can’t directly measure brain activity. Instead, we have to rely on sensors that measure voltage levels in the brain. While these sensors can provide us with some useful information, they are indirect measures of brain activity and can’t capture the full complexity of the brain.</p><p>Another issue is that everyone’s brain structure is different. This means that any single solution we find for studying the brain or interfacing with it will not work for everyone. We need to tailor our solutions to the individual, which adds an extra layer of complexity to the problem.</p><p>Additionally, the “problem” we’re trying to solve by interfacing with the brain will change significantly from person to person. There is no one-size-fits-all solution to the problem of studying and interfacing with the human brain, and it is unlikely that there ever will be, even with the use of extremely accurate sensors.</p><h3>The Challenge</h3><p>For this model I focused on a simplified problem and used a simple Neural Network to solve it.</p><p><strong>Dataset</strong> Why? Basically, a program uses data to figure out how to do something. For example, if you want to teach a ML program to recognize cats in pictures, you need to give it lots of pictures of cats and tell it which ones are cats. This is called a “dataset.” The program looks at the pictures and figures out what makes a cat a cat. Maybe it’s the shape of the eyes, the size of the ears, or the color of the fur. The ML program uses this information to make predictions about new pictures. If it sees a picture of a cat it hasn’t seen before, it can say “this is a cat” because it knows what features to look for. <em>In short, a dataset is kind of like a bunch of examples that a ML program uses to learn how to do something. Without a dataset, the ML program wouldn’t know what to do.</em></p><ul><li>I used a dataset from the MNE Python library for this program. This dataset offered a number of EEG samples, each of which has 226 data points. where each sample corresponds to a particular trial from the problem. Where each sample represents a single trial described in the problem.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*E-m4WO8v4ZYHvxD8NnOSYA.png" /><figcaption>this graph has two such plotted samples, with the channel displayed on the top right of the graph.</figcaption></figure><p><strong>The task →</strong></p><p>In this experiment, a subject is seated in front of a screen and is presented with a series of images. The images include checkerboard patterns that are displayed in either the left or right visual field, and are accompanied by tones that are presented to either the left or right ear. The interval between the stimuli (i.e. the checkerboard patterns and tones) is 750 milliseconds (ms).</p><p>Occasionally, a smiley face is presented at the center of the visual field. When this occurs, the subject is asked to press a key with their right index finger as quickly as possible. This task is likely being used to measure the subject’s reaction time to the appearance of the smiley face.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*za2rKced5D3HgpFzNdiUWQ.png" /><figcaption>The idea is to use only the EEG data feed provided, to detect when the subject is shown the Smiley Face image, before they press the key.</figcaption></figure><p>Overall, this experiment is designed to study the subject’s visual and auditory processing, as well as their reaction time. By presenting stimuli to different parts of the visual field and to different ears, the experimenters can study how the subject’s brain processes and integrates this information. The task of pressing a key in response to the smiley face allows the experimenters to measure the subject’s reaction time, which can provide insights into their cognitive processing speed.</p><p>The purpose of this experiment is to find a way to detect surprise or anticipation by looking at the electrical activity of the brain. The experimenters hope that by creating a system to detect the P300 component, they will be able to solve the problem of detecting these emotions.</p><p><strong>But, what is P300?</strong></p><p>The P300 is a specific pattern that appears in the brain’s electrical activity in response to certain stimuli. It is typically observed as a positive deflection, or spike, in the EEG data feed around 300 milliseconds (ms) after a rare or targeted stimulus is presented. For instance, it will show if someone draws a card from a deck that they were anticipating. The P300 speller is a direct application of the P300 on BCI applications. With the help of this application, users can type by focusing on the letter they want to type and selecting it from an alphabet displayed on a screen.</p><p>Note → detecting the P300 can be challenging, because the P300 is a relatively small signal in the EEG data, and it can be difficult to distinguish from other background noise or artifacts. However, by using techniques such as averaging or signal processing, it is possible to enhance the <strong>signal-to-noise ratio</strong> and improve the accuracy of P300 detection.</p><p><strong>Using ML</strong></p><p>First, it’s important to understand that machines can work in many dimensions because they can process and analyze large amounts of data quickly and accurately. This is particularly useful in the context of brain-computer interfaces (BCIs), where machine learning algorithms can be used to analyze patterns in brain activity and make predictions about what the user is trying to do.</p><p>A classifier is a type of machine learning algorithm that is designed to categorize data into different classes or categories. In the context of BCIs, a classifier might be used to analyze brain signals and assign labels to them, such as “Move right” or “Move left.” This can be useful in a variety of applications, such as controlling a prosthetic limb or a computer cursor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*jyRUN2Kjvsj9Q2sbT0ZRyA.png" /></figure><p>One of the benefits of using machine learning algorithms in BCIs is that they can be trained to recognize patterns in brain activity that may be difficult for humans to discern. For example, an algorithm might be able to identify subtle differences in brain activity that are associated with different actions or intentions, even if those differences are not immediately noticeable to a human observer. This can allow the BCI to respond more accurately and efficiently to the user’s intentions.</p><p>So essentially, the use of machine learning algorithms in BCIs can be a powerful tool for helping users to interact with their environment in new and innovative ways. By analyzing patterns in brain activity and making predictions based on those patterns, machine learning algorithms can enable users to control devices and perform tasks that might otherwise be difficult or impossible.</p><h3>Types of Model (some of the many) →</h3><p><strong>Support Vector Machine</strong></p><p>In simple terms, SVM (Support Vector Machine) is a type of machine learning algorithm that is used to classify data into different categories. It does this by finding a line or curve that separates the data into the different categories as accurately as possible. This line or curve is called a “hyperplane.”</p><p>To find the hyperplane that works best for a given set of data, the SVM algorithm goes through an optimization process where it tries to minimize the number of data points that are misclassified, or placed in the wrong category (“training the algorithm”). For example, if you were using SVM to classify basketball players as either guards or forwards, the algorithm would try to find a hyperplane that correctly separates the guards from the forwards as much as possible.</p><p>Specifically in the model I built here, the goal is to use EEG (electroencephalography) signals to determine if a person is experiencing a surprise. To train the SVM (Support Vector Machine) algorithm to perform this task, I needed examples of EEG data with and without the P300 component (two distinct classes of data). The input for the SVM will be the values recorded for each channel of the EEG device.</p><p>The SVM optimization process worked towards 3 different objectives with descending relevance:</p><ul><li>Minimization of misclassified instances → The main goal of the SVM algorithm is to find a line or curve (called a “hyperplane”) that correctly separates different categories of data as much as possible. However, it is not always possible to find a hyperplane that perfectly separates all the data points into their correct categories. In this case, the SVM algorithm will try to minimize the number of misclassified data points, or those that are placed in the wrong category.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*dSLMaIGv96EPndgmyFA0bQ.png" /><figcaption>Line A represents a better SVM than line B.</figcaption></figure><ul><li>“Margin” of the hyperplane → The position of the hyperplane in the SVM algorithm is chosen to maximize the distance between the hyperplane and the nearest data points from either class. Maximizing the margin helps to improve the generalization performance of the SVM model, meaning that it is more likely to correctly classify new, unseen data. In other words, the goal is to find a hyperplane that not only correctly separates the different classes of data, but also has as much distance as possible between the hyperplane and the nearest data points. This helps to ensure that the model is not too complex and is able to generalize well to new data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*8x0_BS94DOI_suNbZrzFhA.png" /><figcaption>line A should be considered over line B.</figcaption></figure><p>Kernel → If it is not possible to separate two classes of data using a straight line or curve (hyperplane), the SVM (Support Vector Machine) algorithm can use a technique called the “kernel trick” to transform the data in a way that allows for separation. The kernel trick involves using mathematical transformations to map the data points to a higher-dimensional space, where it becomes possible to find a hyperplane that separates the two classes. There are various kernels that can be used in this process, but the most common is the Radial Basis Function (RBF) kernel. The RBF kernel helps to place the data from the two classes on different levels, making it easier to find a hyperplane that meets the required condition.</p><p><strong>Neural Network</strong></p><p>Neural networks are designed to mimic the way the human brain works in order to solve problems. In the human brain, neurons communicate with each other through a process called “firing,” in which one neuron sends a signal to other neurons, which in turn sends signals to other neurons, creating a chain reaction. This chain reaction, or “cascade effect,” allows the brain to perform a wide range of tasks and accomplish complex goals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ir--D6D3GRpRtXVa7LmWuw.png" /><figcaption>Neurons v/s Neural Network</figcaption></figure><p>Similarly, neural networks are made up of interconnected “neurons,” or units that process and transmit information. These neurons are organized into layers, and they work together to analyze and understand complex patterns in data. By replicating the way the human brain processes and communicates information, neural networks are able to learn how to solve problems and make accurate predictions or decisions.</p><p><strong>In a brain</strong> or a neural network, neurons are cells that receive and transmit information. They have inputs, called dendrites, that receive signals from other neurons, and outputs, called axons, that transmit signals to other neurons. When a neuron receives enough input, it will “fire” and send a signal down its axon to other neurons. The strength of the connection between two neurons is called the weight of the connection. In a neural network, each neuron also has an “activation algorithm” that determines the output of the neuron based on the input it receives.</p><p>Both neural networks and support vector machines (SVMs) are types of machine learning algorithms that can be used to classify data. A neural network creates a multi-dimensional solution space in order to find the best way to classify the data, while an SVM begins with a pre-determined algorithm. Neural networks require more setup time, but can be more flexible and effective than SVMs. On the other hand, SVMs require less setup time, but may be less flexible and effective than neural networks.</p><p>neural network that can only solve linear problems</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*xx8pEn_ZnECGDCWzSG7WCw.png" /></figure><p><strong>This model</strong> built is not able to accurately identify p300 components in all cases, as these components may vary depending on the person being studied and there may be nonlinear noise present. To address these challenges, I am using a neural network that can adapt to these variations and potentially other issues that may arise. This neural network will be trained to identify p300 components and ultimately be used to determine when a person is surprised by an image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C1OPfq7DzWD40APBKnKqLg.png" /><figcaption>But for problems where the categories might mix, a non-linear approach is necessary. Just add more layers to the network!</figcaption></figure><h3>Breaking down the code →</h3><p>The first step is to set up the environment, load the libraries, and packages</p><p><strong><em>Importing Libraries:</em></strong></p><pre>!pip install mne #EEG Data Package<br>!pip install sklearn # Machine Learning Library<br>!pip install matplotlib # Plotting Library<br>!pip install torch # Machine Learning Library<br>!pip install torchvision<br>!pip install tensorboardX</pre><p>MNE → helps processing, analyzing, and visualizing EEG data</p><p>sklearn → ML package with tools for data analysis and modeling</p><p>matplotlib → It’s a 2D plotting library that allows users to create a wide range of static, animated, and interactive visualizations</p><p>torch → works and operates with multi-dimensional arrays (tensors)</p><p>torchvision → works with image and video processing, object detection, and image classification.</p><p>tensorboardX → works with logging and visualizing the training process of PyTorch models</p><p><strong><em>Importing modules</em></strong></p><pre>from collections import OrderedDict<br>from pylab import rcParams<br>import torch<br>import torch.nn as nn<br>import torchvision.transforms<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import mne<br>from sklearn.preprocessing import RobustScaler</pre><ul><li>The <strong>OrderedDict</strong> module from the <strong>collections</strong> library is imported to use an ordered dictionary data structure. This can be useful for storing data in a specific order, or for creating a mapping between keys and values that maintains the order in which the items were added.</li><li>The <strong>rcParams</strong> function from the <strong>pylab</strong> library is imported to set default values for various plot formatting options in <strong>matplotlib</strong>. This can be useful for setting a consistent appearance for plots in a project.</li><li>The <strong>torch</strong> library is imported to provide access to PyTorch&#39;s tensor library and various machine learning functions.</li><li>The <strong>nn</strong> module from the <strong>torch</strong> library is imported to use PyTorch&#39;s neural network functions.</li><li>The <strong>torchvision.transforms</strong> module is imported to use PyTorch&#39;s image transformation functions. These can be useful for preprocessing images before using them as input to a model.</li><li>The <strong>matplotlib.pyplot</strong> module is imported to use various plotting functions. This can be useful for visualizing data or the results of machine learning models.</li><li>The <strong>numpy</strong> library is imported to use various numerical and scientific computing functions.</li><li>The <strong>mne</strong> library is imported to use various functions for processing and analyzing electrophysiological data, such as EEG and MEG.</li><li>The <strong>RobustScaler</strong> class from the <strong>sklearn.preprocessing</strong> module is imported to use a scaler that is resistant to the effects of outliers in the data. This can be useful for normalizing data when there are potential outliers that could affect the scaling process.</li></ul><p><strong><em>Initialize Parameters</em></strong></p><pre>eeg_sample_count = 240 # How many samples are we training<br>learning_rate = 1e-3 # How hard the network will correct its mistakes while learning<br>eeg_sample_length = 226 # Number of eeg data points per sample<br>number_of_classes = 1 # We want to answer the &quot;is this a P300?&quot; question<br>hidden1 = 500 # Number of neurons in our first hidden layer<br>hidden2 = 1000 # Number of neurons in our second hidden layer<br>hidden3 = 100 # Number of neurons in our third hidden layer<br>output = 10 # Number of neurons in our output layer</pre><ul><li>The variable <strong>eeg_sample_count</strong> represents the number of samples that are being used for training.</li><li>The variable <strong>learning_rate</strong> specifies the strength of the correction made by the network when it learns from its mistakes. A smaller learning rate may result in slower learning, but may also result in a more accurate model.</li><li>The variable <strong>eeg_sample_length</strong> represents the number of EEG data points in each sample.</li><li>The variable <strong>number_of_classes</strong> indicates that the model is being trained to classify a single type of event (in this case, &quot;is this a P300?&quot;).</li><li>The variables <strong>hidden1</strong>, <strong>hidden2</strong>, and <strong>hidden3</strong> represent the number of neurons in each of the three hidden layers of the model. These layers are responsible for extracting features from the input data and passing them on to the output layer.</li><li>The variable <strong>output</strong> represents the number of neurons in the output layer of the model. This layer is responsible for generating the final prediction based on the features extracted by the hidden layers.</li></ul><p><strong><em>Setting up the Neural Network</em></strong></p><p>Overview:</p><p>The network graph is a collection of <strong>linear nodes and activation node</strong>s. This image roughly matches the defined graph.</p><p>Up until it passes through the final output node, the input data will be moving along this graph, picking up biases, being scaled by weights, and being transformed by activation functions. The final value is then scaled into a number between 0 and 1 using a <em>sigmoid function → the final # is the p300 predictor</em></p><p>**</p><pre>## Define the network<br>tutorial_model = nn.Sequential()</pre><pre># Input Layer (Size 226 -&gt; 500)<br>tutorial_model.add_module(&#39;Input Linear&#39;, nn.Linear(eeg_sample_length, hidden1))<br>tutorial_model.add_module(&#39;Input Activation&#39;, nn.CELU()) </pre><pre># Hidden Layer (Size 500 -&gt; 1000)<br>tutorial_model.add_module(&#39;Hidden Linear&#39;, nn.Linear(hidden1, hidden2))<br>tutorial_model.add_module(&#39;Hidden Activation&#39;, nn.ReLU())</pre><pre># Hidden Layer (Size 1000 -&gt; 100)<br>tutorial_model.add_module(&#39;Hidden Linear2&#39;, nn.Linear(hidden2, hidden3))<br>tutorial_model.add_module(&#39;Hidden Activation2&#39;, nn.ReLU())</pre><pre># Hidden Layer (Size 100 -&gt; 10)<br>tutorial_model.add_module(&#39;Hidden Linear3&#39;, nn.Linear(hidden3, 10))<br>tutorial_model.add_module(&#39;Hidden Activation3&#39;, nn.ReLU())</pre><pre># Output Layer (Size 10 -&gt; 1)<br>tutorial_model.add_module(&#39;Output Linear&#39;, nn.Linear(10, number_of_classes))<br>tutorial_model.add_module(&#39;Output Activation&#39;, nn.Sigmoid())</pre><p>Here I defined a neural network using the PyTorch library. It created a Sequential model, which is a feedforward network that consists of a series of layers that process the input data and pass it through to the next layer.</p><ul><li>The network has an input layer with a size of 226 and a hidden layer with a size of 500. The input layer is defined using the <strong>nn.Linear</strong> module, which applies a linear transformation to the input data. The input layer also includes an activation function, which is a nonlinear function that introduces nonlinearity to the network. In this case, the activation function is the CELU (Concurrent Exponential Linear Unit) function.</li><li>The network also has two additional hidden layers, each with a size of 1000 and 100, respectively. These hidden layers are also defined using the <strong>nn.Linear</strong> module and an activation function, which in this case is the ReLU (Rectified Linear Unit) function.</li><li>Finally, the network has an output layer with a size of 1. This layer is also defined using the <strong>nn.Linear</strong> module and an activation function, which in this case is the sigmoid function. The sigmoid function is often used as the activation function for the output layer of a classification model because it maps the output to a value between 0 and 1, which can be interpreted as a probability.</li></ul><p>Overall, this code defines a neural network with a series of fully connected layers that process input data and produce an output. The network has a total of five hidden layers and an output layer, and each layer includes an activation function to introduce nonlinearity to the model.</p><p><strong><em>Training and loss functions</em></strong></p><p>Overview:</p><p>Next, we need loss and training functions. We essentially receive feedback from loss functions on how well the network is training. A loss of zero or almost zero indicates that the network is successfully predicting the training set of data. This value can be used to gauge when the network has finished training.</p><p>Below, I define a basic training procedure that updates the network’s weights and calculates the loss for each iteration, as well as a widely used loss function that can be used in PyTorch.</p><pre># Define a loss function<br>loss_function = torch.nn.MSELoss()</pre><pre># Define a training procedure<br>def train_network(train_data, actual_class, iterations):</pre><pre>  # Keep track of loss at every training iteration<br>  loss_data = []</pre><pre>  # Begin training for a certain amount of iterations<br>  for i in range(iterations):</pre><pre>    # Begin with a classification<br>    classification = tutorial_model(train_data)</pre><pre>    # Find out how wrong the network was<br>    loss = loss_function(classification, actual_class)<br>    loss_data.append(loss)</pre><pre>    # Zero out the optimizer gradients every iteration<br>    optimizer.zero_grad()</pre><pre>    # Teach the network how to do better next time<br>    loss.backward()<br>    optimizer.step()</pre><pre>  # Plot a nice loss graph at the end of training<br>  rcParams[&#39;figure.figsize&#39;] = 10, 5<br>  plt.title(&quot;Loss vs Iterations&quot;)<br>  plt.plot(list(range(0, len(loss_data))), loss_data)<br>  plt.show()</pre><pre># Save the network&#39;s default state so we can retrain from the default weights<br>torch.save(tutorial_model, &quot;/home/tutorial_model_default_state&quot;)</pre><p>This code defines a training procedure for a neural network using the PyTorch library.</p><ul><li>The training procedure takes in three inputs: train_data, actual_class, and iterations. The train_data is a batch of input data that the network will use to learn and update its weights. The actual_class is the correct class label for the input data, which the network will compare its predictions to in order to measure its performance. The iterations parameter specifies the number of times the training procedure should be run.</li><li>The training procedure begins by defining a loss function using the <strong>nn.MSELoss</strong> module. This loss function measures the mean squared error between the network&#39;s predictions and the actual class labels.</li><li>The training procedure then runs a loop for a specified number of iterations. In each iteration, the network makes a prediction using the input data and calculates the loss using the loss function. The gradients of the loss with respect to the network’s weights are then computed using the <strong>loss.backward()</strong> function, and the optimizer updates the weights using the <strong>optimizer.step()</strong> function.</li><li>At the end of the training loop, the training procedure plots a graph of the loss versus the number of iterations to visualize the training process. The network’s default state is also saved using the <strong>torch.save</strong> function, so it can be retrained from the default weights at a later time.</li></ul><h3>Now finally, Supervised Learning</h3><p>Supervised learning algorithms are a type of machine learning algorithm that rely on labeled training data to learn and make predictions. In these algorithms, the input and output for each example in the training data are clearly defined.</p><p>To understand how these algorithms work, consider the example of taking a final exam for an online course. Each question on the exam includes some information that you need to use to solve it (the input), and you provide an answer (the output). Without a defined answer for each question, your teacher would not be able to accurately evaluate your performance because they would not have a way to compare your answers to the correct answers.</p><p>In the same way, supervised learning algorithms use labeled training data to learn the relationship between the input and output. They use this knowledge to make predictions on new, unseen data. Because the input and output for each example in the training data are clearly defined, the algorithm is able to learn and make accurate predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l9F1wf-ge99lhnXizNa2gA.png" /></figure><p>In a nutshell, supervised learning algorithms are like little genies that can predict the future based on past experiences. They have the ability to take in some input features, process them through their magic lamp, and spit out a prediction of what’s to come. But they don’t just pull these predictions out of thin air — they have to be trained first.</p><p>During the training process, these algorithms are fed a series of examples with a correct output, and they use these examples to learn how to make predictions. Different algorithms have different training processes, but they all use a metric to measure how well they are performing on the training examples. This metric can vary depending on the type of model and the goal of the algorithm.</p><p>For classification models, which predict a discrete class label, it is common to use the cross entropy metric. And for regression models, which predict a continuous value, it is common to use the root mean squared error <em>(RMSE).</em> So, if you ever find yourself in a situation where you need to predict the future and you don’t know where to turn, just remember that supervised learning algorithms have got your back (as long as you’ve trained them properly, of course).</p><p>When training a supervised learning model, it is common to divide your data into three different sets: a training set, a validation set, and a test set. The training set is used to feed the model and adjust the weights and biases of the model. The validation set is used to evaluate the performance of the model and tune it based on the results. The test set is used to evaluate the final performance of the model and see how it performs on unseen data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*QI6esrU3nTBoRHPiicpM0Q.png" /></figure><p>To illustrate this concept, consider the example of training a model to recognize P300 brain waves from other brain waves. You might have a dataset with examples of P300 brain waves and examples of other brain waves. You would then divide this dataset into the training set, validation set, and test set. The model would be trained on the training set, and its performance would be evaluated on the validation set. Once the model is finalized, it would be evaluated on the test set to see how well it performs on unseen data.</p><p>Using three separate sets of data allows us to reduce bias in the model and improve its generalization ability. When the model is only evaluated on the training set, it may overfit to the training data and perform poorly on new examples. However, by using a separate validation set and test set, we can ensure that the model is able to generalize to new data and make accurate predictions.</p><h3>Lets now verify the neural network</h3><p>After completing all of that, I tested the data to determine whether the training was effective. Full disclosure → it gets more complex after this but i’ll break it down!</p><pre># Classify our positive test dataset<br>predicted_positives = tutorial_model(test_positives).data.tolist()</pre><p>Here, the <strong>tutorial_model</strong> is applied to each example in the <strong>test_positives</strong> dataset, which is a list of &quot;positive&quot; examples. The output of the model is a list of predictions, which are then converted to a Python list using the <strong>tolist()</strong> method. This list of predictions is stored in the variable <strong>predicted_positives</strong>.</p><pre># Print the results<br>for index, value in enumerate(predicted_positives):<br>  print(&quot;Positive Test {1} Value scored: {0:.2f}%&quot;.format(value[0] * 100, index + 1))</pre><p>This loop iterates over the list of predictions in <strong>predicted_positives</strong> and prints the value of each prediction as a percentage. The <strong>enumerate()</strong> function returns both the index and value of each element in the list, which allows us to include the index in the printed message. The <strong>format()</strong> method is used to insert the values into the message string.</p><pre>#Classify the negative test dataset<br>predicted_negatives = tutorial_model(test_negatives).data.tolist()</pre><p>This line is similar to the first line of code, but it applies the <strong>tutorial_model</strong> to the <strong>test_negatives</strong> dataset, which is a list of &quot;negative&quot; examples. The output is a list of predictions, which is stored in the variable <strong>predicted_negatives</strong>.</p><p>Finally, the rest of the code is a loop similar to the one before it, but it iterates over the list of predictions in **predicted_negatives**and prints the value of each prediction as a percentage. The <strong>enumerate()</strong> function returns both the index and value of each element in the list, which allows us to include the index in the printed message. The <strong>format()</strong> method is used to insert the values into the message string.</p><p>Overall, This code is performing classification on two separate datasets: a “positive” test dataset and a “negative” test dataset. The model used for classification is the tutorial_model, which has already been trained on some data.</p><p>First, the code classifies the positive test dataset by applying the tutorial_model to each example in the dataset and storing the results in a list called predicted_positives. The results are then printed, with the value of each prediction expressed as a percentage.</p><p>Next, the code does the same thing for the negative test dataset, applying the tutorial_model to each example and storing the results in a list called predicted_negatives. The results are again printed as percentages.</p><p>Finally, the code generates a scatter plot with some of the samples from the positive and negative test datasets. The plot shows the distinct areas of red and green dots, with one positive sample plotted in green and two negative samples plotted in red. The y-axis is limited to the range [0, 1], and the x-axis represents the length of the EEG sample. The plot is meant to illustrate the “solution space” of the network, or the areas where the model is able to make accurate predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*QWPRZTPU49hTd5m8MkHrWw.png" /></figure><p>The plot shows distinct areas of red and green dots. If the input to the network were a simple x and y coordinate, the square band in the center would represent the “solution space” of the network. However, an actual EEG signal sample is an array of several points and can cross the boundary at any time. One positive sample is shown in green, and two negative samples are shown in red.</p><p><em>Our network seems to be correctly classifying a straightforward set of fictitious EEG data, and it is now prepared to be tested with real samples. We’re almost prepared to address the P300 issue.</em></p><h3>Dataset</h3><p>I need to set the path to the specific dataset I’m going to use in Python in order to obtain this dataset. In this instance, the brainwaves have been filtered from 0 to 40 Hz in the sample audiovisual database.</p><pre>#getting the from a MNE library, here im using a p300 dataset <br>data_path = mne.datasets.sample.data_path()<br>data_path</pre><p>I only got raw data. This means that rather than signals that have been cut or focused on an interesting event, it is simply a collection of streamed brain signal samples from numerous EEG channels.</p><pre>from pathlib import Path<br>import mne</pre><pre># Set the path to the data directory<br>data_path = Path(&#39;/path/to/data/directory&#39;)</pre><pre># Construct the file paths using the data_path variable<br>raw_fname = data_path / &#39;MEG/sample/sample_audvis_filt-0-40_raw.fif&#39;<br>event_fname = data_path / &#39;MEG/sample/sample_audvis_filt-0-40_raw-eve.fif&#39;</pre><pre># Read the raw data file and preload it into RAM<br>raw_data = mne.io.read_raw_fif(raw_fname, preload=True) </pre><pre># Set the EEG reference to the average of all voltages<br>raw_data.set_eeg_reference()</pre><p>Here, In this code, I loaded the raw data from a file and stored it in a variable called raw_data. Then selected the data from the EEG electrodes and EOG electrodes, which are used to measure brain activity and eye movement, respectively. This dataset also includes data from MEG, a type of brain imaging technique that uses superconductors and requires a large device. <em>However, MEG is not widely available due to its cost and technical requirements.</em></p><p>Next up →</p><pre>raw_data = raw_data.pick(picks=[&quot;eeg&quot;,&quot;eog&quot;])<br>picks_eeg_only = mne.pick_types(raw_data.info, <br>                                eeg=True, <br>                                eog=True, <br>                                meg=False, <br>                                exclude=&#39;bads&#39;)</pre><p>So essentially, The code is picking specific data from the <strong>raw_data</strong> dataset and saving it in a new variable called <strong>raw_data</strong>. The <strong>pick</strong> function allows the user to choose which sources of data they are interested in. In this case, the user is choosing data from the EEG and EOG electrodes.</p><p>The second line of code uses the <strong>pick_types</strong> function to pick data that meets certain criteria. In this case, the user is picking data that is labeled as &quot;eeg&quot; or &quot;eog&quot; (<strong>eeg=True, eog=True</strong>) and excluding data labeled as &quot;meg&quot; or &quot;bads&quot; (<strong>meg=False, exclude=&#39;bads&#39;</strong>). The resulting data is saved in the variable <strong>picks_eeg_only</strong>.</p><p>To simplify, this code is looking at specific events that occurred during the EEG recording, such as when a smiley face was presented to the participant. The data is then sliced or “epoched” to include a certain time period before and after the event occurred. This allows us to analyze the EEG data specifically during these events and potentially identify patterns, like the P300 brain wave. The time period chosen can be adjusted, with shorter periods potentially allowing for more precise analysis of the brain wave patterns.</p><pre>events = mne.read_events(event_fname)<br>event_id = 5<br>tmin = -0.5 <br>tmax = 1<br>epochs = mne.Epochs(raw_data, events, event_id, tmin, tmax, proj=True,<br>                    picks=picks_eeg_only, baseline=(None, 0), preload=True,<br>                    reject=dict(eeg=100e-6, eog=150e-6), verbose = False)<br>print(epochs)</pre><p>This code reads in the event file, which contains information about when certain events occurred during the EEG recording. It then defines the event id of interest (in this case, event id 5 corresponds to when participants were presented with a smiley face) and the time window around the event that we want to extract. The tmin and tmax variables specify the time before and after the event that we want to include in the epoch.</p><p>I use the mne.Epochs() function to create epochs, or small segments of the EEG data, around these events. The epochs are created by selecting only the data from the EEG electrodes and EOG channels (using the picks_eeg_only variable), and applying a baseline correction (subtracting the mean activity in the baseline period from the activity in each epoch). The epochs are then loaded into memory for faster processing. Finally, the epochs object is printed to the console.</p><pre># This is the channel used to monitor the P300 response<br>channel = &quot;EEG 058&quot;</pre><pre># Display a graph of the sensor position we&#39;re using<br>sensor_position_figure = epochs.plot_sensors(show_names=[channel]</pre><p>To find the best EEG channel for detecting the P300 component, consider the following:</p><ul><li>Location of the electrode relative to the brain: The P300 component is typically associated with activity in the prefrontal cortex, so an electrode placed over this region may have a higher indication of the P300 component.</li><li>Signal-to-noise ratio: A high-quality EEG recording system and steps to minimize noise and artifact can help improve the signal-to-noise ratio, making it easier to detect the P300 component.</li><li>Experiment with multiple channels: It may be helpful to try using multiple channels and select the one that provides the clearest and most robust P300 signal.</li></ul><p>In short, the best EEG channel for detecting the P300 component will depend on the specific research question and experimental setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*e9A8RPHpWpyfVSl_bFZgLA.png" /><figcaption>Sensor positions</figcaption></figure><pre>epochs.plot_image(picks=channel)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*0DXLBu-eeMPWtcMYQ-r5lg.png" /><figcaption>The heat graph below shows 12 P300 events within the dataset. If you look closely, you will see a deflection in the signal around 0.3–0.4 seconds, which is the P300 component. Even with the line graph (which is the average of the 12 samples) below the heat graph, it is still challenging to detect the P300 component.</figcaption></figure><p>We need counterexamples to contrast our P300 component data with now that we have it. We’ll also compile all the additional incidental events from that dataset.</p><pre>event_id=[1,2,3,4]<br>epochsNoP300 = mne.Epochs(raw_data, events, event_id, tmin, tmax, proj=True,<br>                    picks=picks_eeg_only, baseline=(None, 0), preload=True,<br>                    reject=dict(eeg=100e-6, eog=150e-6), verbose = False)<br>print(epochsNoP300)</pre><p>Essentially, here the <strong>Epochs</strong> class is used to represent segments of continuous data that are time-locked to some event or trigger. In this case, the <strong>events</strong> variable seems to contain a list of events or triggers, and the <strong>event_id</strong> list specifies which events we want to include in the epochs. The <strong>tmin</strong> and <strong>tmax</strong> variables specify the time range relative to each event that should be included in the epochs.</p><p>The <strong>picks</strong> argument is used to specify which channels or sensors in the raw data should be included in the epochs. The <strong>baseline</strong> argument specifies a time range to use as a reference when computing the epochs. The <strong>preload</strong> argument specifies whether the data should be loaded into memory immediately, and the <strong>reject</strong> argument specifies criteria for rejecting epochs based on the data in them. Finally, the <strong>verbose</strong> argument controls whether the function should print additional information while it is running.</p><p>After the <strong>Epochs</strong> object has been created, it is printed to the console with the <strong>print()</strong> function.</p><p><strong><em>Next,</em></strong></p><p>(this gets pretty complicated but I tried breaking it down with analogy) Imagine that you are trying to identify whether a person is feeling happy or sad based on their facial expression. You have a dataset of pictures of people’s faces, and some of the pictures show happy faces while others show sad faces. There are significantly more pictures of happy faces in the dataset, so you decide to only use a subset of the pictures to keep a balance between the two classes of data (happy and sad faces).</p><p>When you plot the average facial expression for the happy and sad faces, you notice that there is no significant difference between the two around the mouth area. This means that you cannot reliably use the mouth area to determine whether a person is happy or sad based on their facial expression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*-D3tAo8ccpo8rCBRoK08eQ.png" /></figure><p><strong>there are still a bunch of things to do</strong></p><p>In order to make the data more digestible I still need to →</p><ul><li>Scale the data to avoid letting outliers run the show.</li><li>Assign labels to the samples so we know which class they belong to.</li><li>Combine the data into one big happy family.</li><li>Convert the data to the right data type for PyTorch to use.</li></ul><pre>eeg_data_scaler = RobustScaler()</pre><pre># We have 12 p300 samples<br>p300s = np.squeeze(epochs.get_data(picks=channel))</pre><pre># We have 208 non-p300 samples<br>others = np.squeeze(epochsNoP300.get_data(picks=channel))</pre><pre># Scale the p300 data using the RobustScaler<br>p300s = p300s.transpose()<br>p300s = eeg_data_scaler.fit_transform(p300s)<br>p300s = p300s.transpose()</pre><pre># Scale the non-p300 data using the RobustScaler<br>others = others.transpose()<br>others = eeg_data_scaler.fit_transform(others)<br>others = others.transpose()</pre><pre>## Prepare the train and test tensors<br># Specify Positive P300 train and test samples<br>p300s_train = p300s[0:9]<br>p300s_test = p300s[9:12]<br>p300s_test = torch.tensor(p300s_test).float()</pre><pre># Specify Negative P300 train and test samples<br>others_train = others[30:39]<br>others_test = others[39:42]<br>others_test = torch.tensor(others_test).float()</pre><pre># Combine everything into their final structures<br>training_data = torch.tensor(np.concatenate((p300s_train, others_train), axis = 0)).float()<br>positive_testing_data = torch.tensor(p300s_test).float()<br>negative_testing_data = torch.tensor(others_test).float()</pre><pre># Print the size of each of our data structures<br>print(&quot;training data count: &quot; + str(training_data.shape[0]))<br>print(&quot;positive testing data count: &quot; + str(positive_testing_data.shape[0]))<br>print(&quot;negative testing data count: &quot; + str(negative_testing_data.shape[0]))</pre><pre># Generate training labels<br>labels = torch.tensor(np.zeros((training_data.shape[0],1))).float()<br>labels[0:10] = 1.0<br>print(&quot;training labels count: &quot; + str(labels.shape[0]))</pre><p>OKAY, THE CODE BREAKDOWN NOW</p><ul><li>It creates a <strong>RobustScaler</strong> object called <strong>eeg_data_scaler</strong>, which is a type of scaler used to transform data by scaling it to a specific range.</li><li>It extracts the P300 data from an <strong>epochs</strong> object and the non-P300 data from an <strong>epochsNoP300</strong> object using the <strong>get_data()</strong> method, and stores them in the <strong>p300s</strong> and <strong>others</strong> variables, respectively. The <strong>channel</strong> variable is used to specify which channels or sensors in the data should be included.</li><li>It scales the P300 and non-P300 data using the <strong>RobustScaler</strong> object, and stores the scaled data in the <strong>p300s</strong> and <strong>others</strong> variables.</li><li>It splits the scaled P300 and non-P300 data into train and test sets. For P300 data, it uses the first 9 samples for training and the remaining 3 samples for testing. For non-P300 data, it uses the first 9 samples for training and the remaining 3 samples for testing.</li><li>It combines the training data into a single tensor called <strong>training_data</strong> and the test data into separate tensors called <strong>positive_testing_data</strong> and <strong>negative_testing_data</strong>.</li><li>It generates labels for the training data, with a label of 1.0 for P300 data and a label of 0.0 for non-P300 data.</li><li>It prints the size of each of the data structures.</li></ul><h3>LAST, WE CONNECT THE DATA AND THE NETWORK!</h3><p>Firstly, This time, instead of training with the sample data we made, I’ll train on actual EEG data, starting from default weights.</p><pre>tutorial_model = torch.load(&quot;/home/tutorial_model_default_state&quot;)</pre><pre>## Define a learning function, needs to be reinitialized every load<br>optimizer = torch.optim.Adam(tutorial_model.parameters(), lr = learning_rate)</pre><pre>## Use our training procedure with the sample data<br>print(&quot;Below is the loss graph for dataset training session&quot;)<br>train_network(training_data, labels, iterations = 50)</pre><p>This code is loading a pre-trained PyTorch model from a file, defining a learning function (<strong>optimizer</strong>) for the model, and then using the training data and labels to train the model using the defined learning function.</p><p>Here is a more detailed explanation of what each line of code is doing:</p><ol><li><strong>tutorial_model = torch.load(&quot;/home/tutorial_model_default_state&quot;)</strong>: This line loads a pre-trained PyTorch model from a file located at the specified path. The model will be stored in the <strong>tutorial_model</strong> variable.</li><li><strong>optimizer = torch.optim.Adam(tutorial_model.parameters(), lr = learning_rate)</strong>: This line creates a learning function called an <strong>optimizer</strong> using the Adam optimization algorithm. The <strong>optimizer</strong> will be used to update the model&#39;s parameters during training. The <strong>learning_rate</strong> variable specifies the step size to use when making updates to the model&#39;s parameters.</li><li><strong>train_network(training_data, labels, iterations = 50)</strong>: This line calls a function called <strong>train_network()</strong> and passes it the training data, labels, and number of iterations to use for training. The <strong>train_network()</strong> function likely trains the model using the <strong>optimizer</strong> and the provided data. The <strong>print</strong> statement before this line appears to indicate that the loss (a measure of how well the model is fitting the data) will be plotted during the training process.</li></ol><p><strong>LAST step I promise → classifying the dataset</strong></p><pre># Classify our positive test dataset and print the results<br>classification_1 = tutorial_model(positive_testing_data)<br>for index, value in enumerate(classification_1.data.tolist()):<br>  print(&quot;P300 Positive Classification {1}: {0:.2f}%&quot;.format(value[0] * 100, index + 1))</pre><pre>print()</pre><pre># Classify our negative test dataset and print the results<br>classification_2 = tutorial_model(negative_testing_data)<br>for index, value in enumerate(classification_2.data.tolist()):<br>  print(&quot;P300 Negative Classification {1}: {0:.2f}%&quot;.format(value[0] * 100, index + 1))<br>P300 Positive Classification 1: 100.00%<br>P300 Positive Classification 2: 99.94%<br>P300 Positive Classification 3: 100.00%</pre><pre>P300 Negative Classification 1: 99.92%<br>P300 Negative Classification 2: 0.04%<br>P300 Negative Classification 3: 0.00%</pre><ul><li><strong>classification_1 = tutorial_model(positive_testing_data)</strong>: This line uses the <strong>tutorial_model</strong> to classify the samples in the <strong>positive_testing_data</strong> tensor as P300 or non-P300 events. The classification results are stored in the <strong>classification_1</strong> tensor.</li><li><strong>for index, value in enumerate(classification_1.data.tolist()):</strong>: This line starts a loop that iterates over each element in the <strong>classification_1.data</strong> tensor and prints the classification results for each sample. The <strong>enumerate()</strong> function is used to loop over the elements in the tensor and keep track of the current index. The <strong>tolist()</strong> method is used to convert the tensor to a list.</li><li><strong>print(&quot;P300 Positive Classification {1}: {0:.2f}%&quot;.format(value[0] * 100, index + 1))</strong>: This line prints the classification results for the current sample. The <strong>format()</strong> method is used to include the classification value (<strong>value[0]</strong>) and the index of the current sample (<strong>index + 1</strong>) in the string. The classification value is multiplied by 100 to express it as a percentage.</li><li><strong>classification_2 = tutorial_model(negative_testing_data)</strong>: This line is similar to the first classification, but it uses the <strong>negative_testing_data</strong> tensor instead of the <strong>positive_testing_data</strong> tensor.</li><li>The rest of the code is similar to the previous loop, but it iterates over the <strong>classification_2</strong> tensor and prints the classification results for the negative test dataset.</li></ul><p><em>Overall, this code is using the trained model to classify samples in the test datasets and printing the classification results. The results are expressed as percentages, with a higher percentage indicating a higher level of confidence in the classification.</em></p><p>And, that is it!</p><h4>Takeaways -&gt;</h4><ol><li>Through writing and researching this article, I have gained a deeper understanding of machine learning and its applications in analyzing and classifying biological data such as EEG.</li><li>And machine learning in neuroscience research and how it can provide insights into brain activity and behavior.</li><li>Additionally, I also gained practical skills in implementing machine learning algorithms for EEG data analysis and have come to understand the challenges and limitations of such approaches + I have discovered the potential applications and implications of machine learning in detecting and understanding the surprise response in subjects.</li><li>Going through this process, personally, my understanding and knowledge of machine learning and its applications in neuroscience has significanly improved. My critical thinking and analytical skills have been enhanced as I have evaluated the strengths and limitations of different machine learning approaches and considered their potential impacts on research and practice.</li></ol><p>Overall, I’ve been on a wild ride of personal growth and development while writing and researching this article. I’ve been able to come up with my own ideas and learn from others’ work, and it’s been a total blast!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2e1afd6d450" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving the Education Crisis using Brain Computer Interface]]></title>
            <link>https://studentsxstudents.com/solving-the-education-crisis-using-brain-computer-interface-b793e2c8ca01?source=rss-ec4ee2f63df8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b793e2c8ca01</guid>
            <dc:creator><![CDATA[Serjan Kaur]]></dc:creator>
            <pubDate>Sun, 30 Oct 2022 20:54:58 GMT</pubDate>
            <atom:updated>2022-11-07T00:40:41.968Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the summer, I was reading <em>Judith Berger’</em>s 1976 novel “<em>Ordinary People,”</em> a part of the book which is based on a bit of advice given by an psychiatrist to his very neurotic, emotionally disturbed teen patient stood out to me. While discussing falling behind in schoolwork because he is hesitant to abandon some of his courses and risk falling further behind. The doctor asked him ”Behind what?”, What is the Great Schedule in the Sky? The Golden Gradebook?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*-4hKcIoQyPaHl-cy-w7pLA.jpeg" /></figure><p>As I read the recent <a href="https://nces.ed.gov/fastfacts/display.asp?id=16">National Center for Education Statistics </a>report on the global dropout rate, It reminded me of the teenager’s misery. According to the report, there will be 2.0 million status dropouts between the ages of 16 and 24, with a 5.3 percent total dropout rate. Reading this, I can’t help but wonder if a system in which the quantity of schooling is fixed but the quality of education is variable is partly to blame for the 5.3 percent dropout rate.</p><p><strong>TLDR;</strong></p><p><strong>∘ </strong><a href="#39b1"><strong>What is so wrong with the current education system?</strong></a><strong><br> ∘ </strong><a href="#a8f2"><strong>History of Technology in Education and Possible Issues</strong></a><strong><br> ∘ </strong><a href="#cf55"><strong>Model of implementation to Prevent Such Issues:</strong></a><strong><br>· </strong><a href="#3e12"><strong>Applying Brain Computer Interface to Education</strong></a><strong><br> ∘ </strong><a href="#902e"><strong>But first, What are BCI?</strong></a><strong><br> ∘ </strong><a href="#89f0"><strong>Current projects in BCIs and Education</strong></a><strong><br> ∘ </strong><a href="#e1aa"><strong>Finally, The Application of BCI to Solve the Education Crisis-&gt;</strong></a><strong><br>· </strong><a href="#a591"><strong>Creating Personalized Schedules</strong></a></p><h4>What is so wrong with the current education system?</h4><p>The classroom is intended to be a hotbed of heated arguments, fascinating lectures, and enthralling conversations. In truth, I enter the classroom and feel as if I have turned off my brain. Current educational approaches are tedious and rapidly becoming obsolete. Students are increasingly wired to deal with the rapid distribution of information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*heeKvoPKxSyXYHttZ_FbTA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*x2ybFLzUOdPAGkaWqVZpqw.jpeg" /></figure><p>Generation Z is being raised in an environment that provides constant stimulation and quick access to the world’s information. These tendencies will only intensify in the coming years as technology permeates society’s inner workings and everyday lives. The generational divide has manifested itself in the inefficiencies of the classroom. Younger generations are increasingly inclined to use technology to explore the world, deal with complexity, and challenge assumptions.</p><p>The archaic system of categorising children by age stigmatises individuals who require extra time to master one or more of their skills. In fact, fear of this stigma contributed to one of modern education’s biggest blunders: social promotion. Educators were hesitant to hold pupils back a grade, fearful of harming the child’s self-esteem. However, those children who were promoted before they were ready were ultimately harmed: eventually, their self-esteem was greatly affected when they found themselves in high school but lacking the information or skills to succeed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*fqAlq7Byw19zeUnuIdIbRw.jpeg" /></figure><p>The antiquated and dysfunctional system of bells signalling the start of random time blocks, thousands of students seated in rows, and rigid, teacher-centered instruction was created to prepare kids for factory work. Kids were sorted in schools. → Since teachers are required to “teach to the middle,” this practise ensures that the most gifted kids are bored and unchallenged while the the students with fewest academic skills fell further and further behind.</p><h4>History of Technology in Education and Possible Issues</h4><p>In 1913, advancements in audiovisual technology led Thomas Edison to claim “books will soon be obsolete in schools” → One hundred years later, Nicholas Negroponte (founder of <a href="https://www.researchgate.net/publication/262406593_One_Laptop_Per_Child_Vision_vs_Reality">One Laptop Per Child</a>) made a strikingly similar prediction that laptop would replace physical books within five years → History has repeatedly provided examples of educational technologies that failed to live up to expectations. Over the last century, hundreds of millions of dollars have been invested</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*doh6VFtddj7GQIoUnrw9hg.jpeg" /></figure><p>Technologies that do end up becoming widely used often have mixed educational impacts because expectations were not grounded in the complexities of learning</p><ul><li>Technology is incorrectly regarded as a cure for educational problems. As one major educational technology researcher puts it, “much as music does not reside in the piano, teaching, learning, and information do not reside in the computer” (Warschauer, 2011). The fervour surrounding new innovations, combined with the belief that technology has inherent properties that will confer knowledge to all youth regardless of social status, frequently leads to misinformed policies and interventions that produce poor academic outcomes and perpetuate learning inequities.</li><li><a href="https://www.academia.edu/2846432/One_laptop_per_child_Birmingham_Case_study_of_a_radical_experiment"><strong>The botched laptop distribution</strong></a> initiative in Birmingham serves as a painful illustration. The mayor and city council president decided to buy and give 15,000 laptop computers to primary school students without consulting the local education system. Training, curriculum development, and technical support mechanisms were not included in the implementation. Analyses of schools, teachers, and students before and after distribution yielded disappointing results. These ‘one-to-one’ programmes, which equip students with laptop computers, have been found to provide significantly diverse educational outcomes depending on how the interventions are implemented.</li></ul><blockquote>Although educational technology can improve students’ academic performance, projects frequently fail and worsen already-existing disparities along racial, class, and gender lines due to a lack of consideration for the intricacies of educational settings and wider social circumstances.</blockquote><ol><li>Positive academic outcomes are dependent on execution that takes into account the <strong>social context.</strong></li><li>Understanding disparities in <strong>device use across social groups</strong> is crucial for closing achievement inequalities.</li></ol><h4>Model of implementation to Prevent Such Issues:</h4><blockquote><em>Implementation of educational technology typically follows a ‘standard model’ of top-down imposition</em></blockquote><ul><li>Dissemination of instructional technology often follows a predictable pattern, which is compatible with theories of innovation diffusion.</li></ul><ol><li>To begin, cutting-edge technology built for specialized applications is applied to the educational domain.</li><li>Following that, educational technology is made available to kids with exceptional privileges</li><li>As the cost of technology decreases, it will eventually be made available to lower income groups.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0hQzoV6mM9zQLVx5PH-UA.png" /></figure><p><strong>Example:</strong></p><ul><li>The first consumer computer was created in 1975 and was quickly repurposed for educational purposes -&gt; By the end of the next decade, approximately 90% of public schools had at least one computer.</li><li>Wealthier schools were able to purchase more devices than poorer schools, dividing technology use along racial and socioeconomic lines.</li><li>Access gradually increased across all social groups over time, however disparities in types of use maintained.</li></ul><h3>Applying Brain Computer Interface to Education</h3><p>Over the past century, learning environments have made extensive use of various technological breakthroughs. Utilizing educational BCI technology in advance of anticipated developments is the next doable step that can be taken to avoid making the same mistakes twice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*Rbxcr82uxGxmvEq03uZIgA.jpeg" /></figure><p>The divide between neuroscience and educational applications was once thought to be “a bridge too far,” but it has been gradually shrinking thanks to developments in technology, technique, and practise. Understanding that academic development is best aided when educational techniques meet each student’s needs and learning is properly scaffolded is what’s fueling this movement.</p><h4>But first, What are BCI?</h4><p>BCIs are digital systems that enable direct connection between the brain and an external device. This necessitates technology capable of either precisely reading and interpreting brain signals while preserving human meaning or activating relevant neural pathways (and/or promoting connections between neurons) in order to reliably and consistently convey information.</p><p>Almost all existing BCI systems are based on unidirectional information flow between the brain and the device, with other biological systems potentially used as feedback (neurofeedback) mechanisms.</p><p>Types of BCIs and how they read signals:</p><blockquote>Several devices have been used to read brain signals as part of BCI systems; each has its own set of advantages and disadvantages.</blockquote><ol><li>Invasive: Although surgically implanted electrodes provide the most dependable and accurate information transfer, they are limited in the number of neurons they can contact and are prone to deteriorating effectiveness with time →</li><li>Non Invasive: Electroencephalography (EEG), which involves putting a series of electrodes on the scalp to read brain activity, is the most often used non-invasive equipment. Its low cost and versatility come at the expense of noisy signals and limited bandwidth.</li><li>Other non-invasive tools: 723wincluding magnetoencephalography (MEG) and functional magnetic resonance imaging (fMRI), employ magnetic fields to precisely and comprehensively detect brain activity, but they are costly and demand that patients remain still inside a big machine.</li><li>The applications of BCI technology have grown as a result of significant improvements in the precision and speed of reading neural signals as well as the sorts of information that may be measured.</li><li>Many businesses (including NeuroSky, Emotiv, and intendiX) sell devices, apps, and software based on thought-controlled user input.</li><li>These products now include variations of EEG devices. Functional MRI has also been used for a range of tasks, including the recognition and reconstruction of real images from imagined visuals and movies.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*0H6N9ka9VuRRHpOrxfYjzw.png" /></figure><p><strong>Stimulating neurons:</strong></p><ul><li>For invasive: The nervous system (in the brain or elsewhere) can be stimulated by arrays of electrodes in a way that sends the person specific signals.</li><li>Non invasive: There are numerous devices and methods for non-invasive brain stimulation technologies, which are represented by an alphabet soup of acronyms.</li></ul><p><strong>How Brainwaves work:</strong></p><blockquote><em>By analysing the wavelength band, EEG can objectively discern the different states of brain activity.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*Z81xVZngJklBIoUTyfG3ag.png" /></figure><ol><li>When people are engaged in mental activities, beta waves, which are connected to cerebral cortex activity, weaken alpha waves.</li><li>It is believed that alpha wave activity and the level of beta wave activity are inversely related to the state of the brain’s activity (or gamma wave).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LCxAiYfQUGVaANygww-EnQ.png" /><figcaption>The table lists the four frequency bands — delta, theta, alpha, and beta — in which the brain’s electrical activity is classified and related mental states.</figcaption></figure><p><strong>To Summarize:</strong></p><p>BCI technology entails determining a person’s intentions by acquiring and interpreting brain signals and then carrying out the intended tasks with the help of a computer system</p><p>Brain cells communicate by sending out tiny electrical signals. The goal of EEG is to detect and quantify those tiny electrical signals noninvasively. Other BCI system components process and interpret the electrical signals detected by EEG to determine the person’s intentions.</p><p>Some of the tiny electrical signals produced by brain cells are transferred to the person’s scalp. EEG is performed by placing multiple electrodes on the scalp to receive electrical signals from the scalp. A variety of factors, including but not limited to electrode placement locations, electrode-to-scalp contact integrity, electrical interference, and others, can affect EEG accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*_Z3WCYtfIvRheC2WTSRhpg.png" /></figure><h4>Current projects in BCIs and Education</h4><ul><li>Researchers developed a digital learning environment that adapts information based on the cognitive effort of students as assessed by an EEG monitor.</li><li>NeuroSky’s commercially accessible educational software combines digital instructional activities with attention assessments via an affordable EEG headset.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JnuEJyEcpruFEoKlesCmLA.jpeg" /></figure><ul><li>Studies have shown that executive functioning can be tested in methods that are appropriate for complicated learning contexts.</li><li>Systems that respond to pupils’ emotional states are now being developed.</li><li>Brain-computer interfaces and education based on BCI Seven instructional games have been developed to alleviate math anxiety.</li><li>Computer adaptive testing has been integrated with real-time attention assessments via EEG.</li></ul><h4><strong>Finally, The Application of BCI to Solve the Education Crisis-&gt;</strong></h4><h3><strong>Creating Personalized Schedules</strong></h3><p>Today’s colleges and universities face numerous challenges, including disengaged students, high dropout rates, and the ineffectiveness of a traditional “one-size-fits-all” educational approach. But nevertheless, when data from EEGs, big data analytics, and artificial intelligence are used correctly, personalized learning schedules can be created, which may help to resolve some of these challenges.</p><p>Every student would benefit from a completely unique educational approach that is fully tailored to his or her individual abilities and needs with a personalized learning experience. This could boost students’ motivation and reduce their chances of dropping out. It may also provide professors with a better understanding of each student’s learning process, allowing them to teach more effectively.</p><p><strong>It is a twofold solution:</strong></p><ol><li><strong>Getting the data:</strong></li></ol><p>A large amount of student data is the primary component of personalized learning. Student data could be collected and processed in an ethical, secure, and transparent manner using an EEG headset (electroencephalogram).</p><p>→ An EEG headset is a wearable device that records the electrical activity of the brain through electroencephalography. EEG sensors in headsets detect brain activity by placing electrodes along the scalp. EEG data analysis aids in the study of cognitive processes.</p><p>2. <strong>Analyzing the data and making prediction</strong></p><p>The assistance provided by AI algorithms is used to help create optimal learning environments. When it comes to education, combining the strengths of AI and human abilities will produce the best results. AI systems could significantly improve the learning process by providing more precise and accurate feedback, as well as allowing students to repeat study exercises as many times as necessary.</p><blockquote>Personalized learning has the potential to transform the way children learn and is critical to ensuring that students of various ages, cultures, religions, and learning preferences receive the best education possible.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*kLgNk1kPRj8VvAXBj44KaQ.png" /></figure><p><strong>Company already working on the Basic Idea:</strong></p><ul><li><a href="https://www.celayix.com/blog/using-artificial-intelligence-as-a-scheduling-tool/">Complexity</a>, AI used in employee scheduling. Every business has its own set of rules, and each schedule has its own set of complexities and intricacies. When it comes to creating schedules, there are numerous factors to consider. Employee experience, seniority, availability, certification, and total hours are just a few examples.</li></ul><p><strong>Biggest issues with BCI</strong></p><ul><li>Regardless of the progress, there are still significant obstacles to overcome. Due to a mix of technological and pedagogical issues, current BCI educational systems are simply proof-of-concepts and have not proven to be more effective than other error-adaptive tech.</li><li>The use of EEG devices is also a major problem; systems frequently have to make trade-offs between setup time, comfort, signal quality, and cost. The biggest difficulties may lie in the social and cultural spheres, which are frequently ignored in technical literature. The social and cultural circumstances in which educational technology is used ultimately determine its influence and efficacy, as will be covered below.</li></ul><p><strong>Conclusion</strong></p><p>Brain Computer Interface can provide enormous benefits to developing countries by allowing people who previously had no hope of obtaining an education to do so.</p><p>Through the provision of a more accessible and high-quality education system, BCI has the potential to significantly improve the quality of life of children, adults, and families all over the world.</p><blockquote>Hey! Thanks for reading till the end:) I am 16y/o <strong>BCI enthusiast and an Activate at </strong><a href="https://tks.world/"><strong>The Knowledge Society (TKS)</strong></a><strong>.</strong></blockquote><blockquote>Find out more on my <a href="https://serjankaur.webflow.io/"><strong>personal website!</strong></a></blockquote><blockquote>My LinkedIn: <a href="https://www.linkedin.com/in/serjan-kaur-">https://www.linkedin.com/in/serjan-kaur-</a></blockquote><blockquote>My Twitter: <a href="https://twitter.com/serjannnnnn">https://twitter.com/serjannnnnn</a></blockquote><blockquote>Subscribe to my monthly newsletters: <a href="https://serjan.substack.com/">https://serjan.substack.com/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b793e2c8ca01" width="1" height="1" alt=""><hr><p><a href="https://studentsxstudents.com/solving-the-education-crisis-using-brain-computer-interface-b793e2c8ca01">Solving the Education Crisis using Brain Computer Interface</a> was originally published in <a href="https://studentsxstudents.com/">students x students</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using ML in Personality Analysis]]></title>
            <link>https://medium.com/innonation-publication/using-ml-in-personality-analysis-65ce7d1d635b?source=rss-ec4ee2f63df8------2</link>
            <guid isPermaLink="false">https://medium.com/p/65ce7d1d635b</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[personal-growth]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Serjan Kaur]]></dc:creator>
            <pubDate>Mon, 04 Jul 2022 19:34:06 GMT</pubDate>
            <atom:updated>2022-07-04T19:34:06.972Z</atom:updated>
            <content:encoded><![CDATA[<p>You have probably taken a personality test at least once in your life, unless you’ve been living under a rock. These last few months, I had been applying to jobs for the summer. I used to fill out the necessary applications, respond to the generic questions, and attach my resume. Some of them would ask me to complete an online form the very next day with a checkbox where I could mark whether I strongly agreed or disagreed with a predetermined statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jIFWCcwGQgn3T7Vs.jpg" /></figure><p>I was supposed to check the box next to the statement, “I find it difficult to approach individuals,” on the test.</p><ul><li>Strongly Agree</li><li>Agree</li><li>Neither Agree nor Disagree</li><li>Disagree</li><li>Strongly Disagree</li></ul><p>The truth is that I actually have a hard time approaching people. Therefore, in theory, I should have chosen “Agree” with that statement, but when filling out a job applications&#39; assessment, I marked “Strongly Disagree” without batting an eye! It is challenging to accurately estimate a person’s personality, and candidates can sometimes falsify results — as I did.</p><blockquote><em>To this end, we developed a personality trait estimator that uses unstructured written text as input and outputs personality estimations based on the dimensions of the Myers-Briggs personality type indicator. </em>Essentially attempting to infer your personality from the things you have written.</blockquote><p>The growing number of people using social media has resulted in a significant increase in the amount of information available online. The contents that these users post on social media can often provide valuable insights into their personalities (for example, in terms of predicting job satisfaction, specific preferences, and the success of professional and romantic relationships) without the hassle of taking a formal personality test.</p><p>Through personality prediction we break down digital input into components and map them to a personality model. A well-known personality model, known as the big five personality traits, has often been adopted in the literature as the de facto standard for personality evaluation due to its simplicity and proven competence. Natural language processing (NLP) technologies have effectively become an established and appealing go-to method for psychological study over the last decade.</p><h3>But First, Let’s Go Over the Basics</h3><h4><strong>What is NLP?</strong></h4><p><strong>Natural Language Processing</strong> is a part of artificial intelligence which focuses on the overlap between human linguistics and computers. It enables computers to converse with humans in their native tongue and scales other language-related activities. NLP allows computers to read text, hear voice, analyse it, gauge sentiment, and identify which bits are significant, for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*MwG72SPy2hOR9Fnp.jpeg" /></figure><h4><strong>How it works :</strong></h4><ul><li><strong>Tokenization</strong>: It is a process of splitting text objects into smaller units called tokens. Tokens can be numbers, texts, or symbols.</li><li><strong>Part-of-speech-tagging:</strong> POS is categorizing texts into lists of words where they are segregated according to whether the word is a noun, adjective, verb, and so on.</li><li><strong>Stemming and lemmatization</strong>: The process of removing prefixes and suffixes to extract the base form of a word. Lemmatization takes into account the context and converts the word to its meaningful base form, whereas stemming only removes the last few characters, resulting in inaccurate interpretations and spelling mistakes.</li><li><strong>Stop word removal</strong>: As the name suggests it is the eliminating words that appear in a large number of documents in the corpus Articles and pronouns, for example, are commonly characterized as stop words.</li></ul><h4><strong>What is Personality Analysis?</strong></h4><p><strong>Personality analysis</strong> is the process of analyzing and evaluating an individual’s essential attributes, such as dependability, determination, confidence, tenderness, and so on. It accurately assesses a person’s personality by accumulating relevant information. Personality analysis is used to determine not only psychological disorders in individuals, but also to screen possible job candidates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UIXvQpi81v8un6yl" /></figure><p><strong>Use Cases :</strong></p><p>Particular illnesses in mental health are linked to certain personality traits. In forensics, knowing personality features can help narrow the suspect pool. Personality qualities have an impact on one’s fitness for particular occupations in human resources management.It is also used for a variety of other purposes, such as observing personality changes, evaluating hypotheses, determining how beneficial therapy might be, and so on. The analysis is frequently used to determine competence and conduct risk assessments.</p><blockquote><strong><em>Why do we need an alternative?</em></strong></blockquote><p>It is quite easy to deceive them in order to obtain the personality type of our choice, as the questions are straightforward. Individuals who want to take a personality test encounter two major issues: the expense and the length of the test.The majority of personality tests comprise 50–70 questions, which might be tedious for the user.</p><h4><strong>What is Myer Briggs Test Indicator?</strong></h4><p>Have you ever wondered what those cryptic-sounding initials meant when someone said they were an INTJ or an ESTP? Well these individuals are referring to their Myers-Briggs Type Indicator personality type <strong>(MBTI)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*vx17W8srBhOFMTCx" /></figure><p>People are classified into one of 16 personality types based on their responses to the inventory’s questions. The MBTI’s purpose is to help people better understand and explore their own personalities, including their likes, dislikes, strengths, weaknesses, potential job choices, and compatibility with others.</p><h4>Finally, What Are We Doing Here?</h4><p>In around<strong> 50–60 words</strong>, the user must describe their interpretation of an abstract visual. This concept is founded on the notion that everyone thinks and expresses themselves differently. At the conclusion of the test, a detailed analysis is provided, as well as the proportion of each trait. This could be extremely advantageous for both psychological and industrial uses.The project is based on the idea that different personality types utilise different terminology to classify a person’s personality attribute.</p><h4>Step 1 : Importing the Data &amp; Importing Libraries</h4><p><strong>The Dataset :</strong></p><p>Importing datasets is very fundamental when working on a machine learning model. A dataset is a set of data that is usually presented in tabular format. Each column denotes a distinct variable.The dataset we’re using has 4 variables : id, title, author, text and label. The label signifies whether a news is real or fake.</p><p><strong>Our Dataset </strong>: Labeled data was collected from different people’s postings on a personality test forum along with their personality types, for the aim of this project. A total of 8000 data points were used in the dataset for this investigation. This contained all 16 MBTI personality types.</p><p>Here is the <a href="https://github.com/tejaspradhan/Personality-Trait-Analysis-using-NLP-and-Deep-Learning/blob/master/mbti_data.zip"><strong>dataset</strong></a> I used!</p><pre># loading the dataset to a pandas DataFrame<br>df = pd.read_csv(&#39;mbti_1.csv&#39;)</pre><p>The read_csv()function in Pandas imports a CSV file into a DataFrame.</p><h4><strong>The Libraries:</strong></h4><p>Numpy : Numerical Python is a Python library that includes multidimensional array and matrix data structures. I used it to create and manipulate data arrays.It basically did all the Math stuff we don’t really want to do</p><p>Pandas: is another open source library which we use for data analysis</p><p>matplotlib.pyplot: The visualisation toolkit Matplotlib includes a set of functions called Pyplot. A figure’s elements can be changed by using its functions, which include constructing a figure, a plotting area, plot lines, adding plot labels, etc.</p><p>re :The functions in this module allow you to determine whether a given text fits a given regular expression(RE).</p><p>NLTK : The Natural Language Toolkit (NLTK) is a Python programming environment for creating applications for statistical natural language processing (NLP).Text processing libraries for tokenization, parsing, classification, stemming, tagging, and semantic reasoning are included.</p><h4>Step 2: Pre-processing the Data</h4><p><strong>Why do it?</strong></p><p>The dataset contains a lot of slang and terms that could not be used as significant semantic features for defining one’s personality because it was derived from a large social media dataset. Various punctuation marks and a large number of emoticons were also present in the data, which had to be cleaned and eliminated. All redundant punctuation, emoticons, and “stop words” such as “a,” “the,” and others were eliminated from the dataset during data cleaning rounds.</p><blockquote><em>Let me break down the code now :)</em></blockquote><ul><li>Convert to lowercase : By reducing all characters to lowercase, it helps to remove unhelpful sections of the data, or noise. When you want to execute text analysis on pieces of data like comments, removing noise comes in handy.</li></ul><pre>df = pd.read_csv(&#39;mbti_1.csv&#39;)</pre><pre>#convert to lowercase</pre><pre>df[&#39;posts&#39;] = [i.lower() for i in df[&#39;posts&#39;]]</pre><pre>df.head()</pre><ul><li>Splitting the dataset : The split() method splits a string into a list.When it detects a separator that has been defined previously, the function reads the string and separates it.</li></ul><pre>df[&#39;Distinct Posts&#39;] = [i.split(&#39;|||&#39;) for i in df[&#39;posts&#39;]]</pre><ul><li>Removing rows : The drop() method removes a row or column from a table. The drop() method eliminates the given row by specifying the row axis (axis=’1&#39;) and its label.</li></ul><p><strong>Cleaning the dataset</strong></p><p>Without cleaning the dataset, it is frequently a jumble of words that the machine is unable to comprehend. We’ll go over the procedures involved in cleaning data in a typical machine learning text pipeline.</p><pre>import re</pre><pre>df[&#39;Posts&#39;] = df[&#39;posts&#39;].apply(lambda x: re.sub(r&#39;https?:[?:A-Za-z0-9//_?.=/-]+&#39;, &#39;&#39;, x.replace(&#39;|&#39;,&#39;&#39;)))</pre><pre>df[&#39;Posts&#39;]=df[&#39;Posts&#39;].apply(lambda x: re.sub(r&#39;\w*\d\w*&#39;, &#39;&#39;, x))</pre><ul><li>We’re using the.sub command to replace particular values in our dataset, as well as the Regular expression library (re.) to assist us search for words in the data.</li><li>The hyperlinks (https?:[?:A-Za-z0–9//_?.=/-]+) are replaced with empty spaces or “|”</li></ul><pre># removing special symbols</pre><pre>df[&#39;Posts&#39;]=df[&#39;Posts&#39;].apply(lambda x: re.sub(r&#39;[0-9,.&quot;\&#39;*.?/\()@#!$%&amp;^+]&#39;, &#39;&#39;, x))</pre><pre># removing repetitive multiple letter words and too long or too short words</pre><pre>df[&#39;Posts&#39;] = df[&#39;Posts&#39;].apply(lambda x: re.sub(r&#39;([a-z])\1{2,}[\s|\w]*&#39;,&#39;&#39;,x))</pre><pre>df[&#39;Posts&#39;] = df[&#39;Posts&#39;].apply(lambda x: re.sub(r&#39;(\b\w{0,3})?\b&#39;,&#39;&#39;,x))</pre><pre>df[&#39;Posts&#39;] = df[&#39;Posts&#39;].apply(lambda x: re.sub(r&#39;(\b\w{30,1000})?\b&#39;,&#39;&#39;,x))</pre><ul><li>Empty spaces or “|” are used in place of special symbols (0–9,.”’*.?/()@#!$ % &amp;+).</li><li>All repetitive multi-letter terms, as well as those that are too lengthy or short, are removed.</li></ul><pre>#df[&#39;Posts&#39;] = df[&#39;Posts&#39;].apply(lambda x: re.sub(r&#39;\s[\s+]&#39;,&#39;&#39;,x))</pre><pre>df.drop(&#39;posts&#39;,inplace=True,axis=1)</pre><pre>df.to_csv(&#39;mbti_cleaned.csv&#39;)</pre><p>Finally, the drop() method removes first row with the title “posts”</p><p>We now have a clean dataset with only the words that are relevant to studying personality traits. The cleaned dataset’s text is categorized by personality types to provide a final dataset with personality classes and raw text entered by these personalities. The final dataset is labeled “mbti_cleaned”.</p><h4>Step 3 : TF-IDF vectorizer</h4><p>Textual data must still be converted to numerical data before it can be used. This process is known as feature extraction or, more simply, vectorization, and it is a prerequisite for language-aware analysis. Numerically representing documents improves the ability to perform meaningful analytics. In our case, a particular amount of weight must be applied to the words in order to identify personality based on them.</p><p>We use a vectorizer called the TF-IDF vectorizer because it compares how often a term was used by each personality type to the total number of personality types.</p><p><strong>What is a TF-IDF vectorizer, exactly?</strong></p><p>It’s a text vectorizer that converts text into usable vectors using Term Frequency (TF) and Document Frequency (DF) (DF). The TF is the number of times a given phrase appears in a document, and it reflects how important that term is in that document. The number of documents containing a given term is referred to as the number of documents containing that term (Idf). In a document, the frequency of a term reflects how common it is.</p><p><strong>Why TF-IDF vectorizer?</strong></p><p>Because it considers the complete document rather than just a single sentence, TF-IDF works best when dealing with informal text data. As a result, the error created by an excessive use of a certain term by a specific personality type is ignored, and the only way a word is given higher priority is if it is used by a specific personality type and not by others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AqioOvxMcsdMtMdr.jpeg" /></figure><p>Finally, All of the raw text is converted to numerical features, to create an entirely numerical dataset. This data was then used to train our machine learning and deep learning models.</p><p><strong>How?</strong></p><p>Create variables for countvectorizer &amp; tfidfvectorizer respectively and save the function there. After that, the vectorizer functions are fitted(.fit) to the dataset, which implies that all data under the variable is passed through the vectorizer function. Then, using.transform, all of the values will be converted to their corresponding features.</p><pre>#converting the textual data to #<br>vectorizer = TfidfVectorizer()<br>vectorizer.fit(x)x = vectorizer.transform(x)print(x)</pre><h4>Step 4: <strong>Naive Bayesian classifier</strong></h4><p><strong>What is a Naive Bayesian classifier, exactly?</strong></p><p>It’s a classification method based on Bayes’ Theorem and the assumption of predictor independence. A Naive Bayes classifier, in simple terms, posits that the existence of one feature in a class is unrelated to the presence of any other feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YeWlFMQ8O6WPi5XZ.png" /></figure><p><strong>What are we doing here?</strong></p><p>To classify the data in our study, we employed a simple Nave Bayesian classifier. In order to fit the bias of the data, the training parameter ‘alpha’ was set at 0.32. Because of the large bias and multiclass classification, the model only achieved 32% accuracy on the validation set.</p><p><strong>How does it work?</strong></p><ol><li>Create a frequency table from the data set.</li><li>Find the probabilities and create a Likelihood table.</li><li>Calculate the posterior probability for each class using the Naive Bayesian equation. The outcome of prediction is the class with the highest posterior probability.</li></ol><p><strong>Our code :</strong></p><ul><li>Performing a train test split on dataset</li><li>Set the variable model to Naive Bayes model (MultinomialNB)</li><li>Fit the dataset to the model</li><li>Finally, Let’s predict the test results</li></ul><pre>model = MultinomialNB(alpha = 0.0013)</pre><pre>model.fit(x_train_tfidf,y_train)</pre><pre>y_pred = model.predict(cv.transform(x_test))</pre><p>-&gt; The accuracy was 36%</p><h4>Step 5: Support Vector Machine</h4><p><strong>So, What are SVMs?</strong></p><p>The basic principle behind SVM is that it constructs a line or hyperplane that divides data into classes. SVM is an algorithm that takes data as input and, if possible, generates a line that separates the classes.The SVM technique finds the points from both classes that are closest to the line. Support vectors are the names given to these points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/0*fvtBnAinvdSM9G1E.png" /></figure><p>The distance between the line and the support vectors is now computed. The margin is the name given to this distance. Our goal is to find the division between the different personality types. The ideal hyperplane is the one for which the margin is the greatest.</p><p><strong>What are we doing here?</strong></p><p>To increase the fitting towards the data bias, the regularisation value C was increased to 0.16. This strategy was similar to the one used in. On the validation set, the SVM model had a 60% accuracy rate.</p><p><strong>The code :</strong></p><ul><li>In X train tfidf, we have our points, and in y train, we have the classes to which they belong.</li><li>Now we’ll use the above dataset to train our SVM model.</li><li>Finally, we predict the datasets class.</li><li>Tuning Hyper-Parameters</li></ul><pre>from sklearn.svm import LinearSVC</pre><pre>clf = LinearSVC().fit(X_train_tfidf,y_train)</pre><pre>y_pred = clf.predict(c_v.transform(x_test))</pre><p>When you design a classifier, you pass parameters as arguments. The main parameters for SVM are as follows:</p><p>C: It manages the trade-off between having a smooth decision border and correctly classifying training points. A large c number indicates that you will receive more correct training points.</p><h4><strong>Step 6 : Convolutional Neural Network</strong></h4><blockquote><em>Finally, Convolutional Neural Networks were utilized, which is a deep learning approach commonly used on images.</em></blockquote><p><strong>So, What is Deep Learning?</strong></p><p>Deep learning is a type of machine learning that creates more complicated hierarchical models to replicate how humans learn new knowledge. Deep learning algorithms are known as neural networks and are inspired by the structure of the human brain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WTk9IcNK9oWS3U1-.png" /></figure><p>These neural networks are made up of interconnected network switches that are programmed to recognise patterns in the same manner that the human brain and nervous system do.</p><p><strong>And, What are CNNs?</strong></p><p>A convolutional neural network (CNN/ConvNet) is a type of deep neural network used to evaluate visual imagery in deep learning. The system can take an input image, assign relevance (learnable weights and biases) to various aspects/objects in the image, and distinguish between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*sVQkhV8lg1xTvmNN.png" /></figure><p>When compared to other classification methods, the amount of pre-processing required by a ConvNet is significantly less.</p><p><strong>What are we doing here?</strong></p><p>Word vectors are subjected to 1D convolution in this version of CNN. An embedding layer will transform each word into a 1-dimensional vector. These vectors would serve as the CNN layer’s inputs. The input will be one dimensional, unlike images. In order to improve word separation, the 1D vector CNN technique is utilised to take the input vectors and give learnable weights and biases depending on different features of feature extraction and max pooling.</p><blockquote><em>Due to the large number of classes to anticipate, this accuracy did not increase. To fix this, The deep learning model was combined with a strategy known as </em><strong><em>multilabel classification.</em></strong></blockquote><p><strong>Multilabel Classification:</strong></p><p>To achieve higher accuracy, four binary classifiers were employed rather than making predictions for 16 classes based on 16 personality types. As a result, there were 4 neurons with sigmoid activation functions instead of 1 neuron with soft-max activation in the output layer. Word embeddings were constructed in 1D convolution and provided as input to the neural network. The neural network also included a max pooling layer, a dense layer, and a sigmoid layer for getting the results of the four binary classifiers’ multilabel classification.</p><blockquote><em>It is possible to attain greater accuracy in the multilabel classification with thorough analysis, fine-tuning of the number of hidden layers, activation functions at inner levels as well as the output, and max pooling.</em></blockquote><p>Using the TF-IDF vectorization and meticulously adjusting the hyperparameters resulted in a substantially higher accuracy than other models that employed the ngram model with CNN. Convolutional neural network model is utilised in the testing system’s final version as a result of this training.</p><blockquote><strong>That’s it, You see it was pretty simple!</strong></blockquote><h4>Conclusion &amp; Takeaways</h4><p>The project uses visuals rather than questions to categorise the user’s personality in as short as 60 words. The benefit of creating such a process for personality classification is that it can quickly and easily identify personality features. The issue of having to answer at least 50–60 questions in order to get a personality test result that may be readily manipulated was fixed. The project’s output was a precise and time-saving method for using artificial intelligence to quickly and accurately take a personality test.</p><ul><li>If all you are doing is copying and pasting the instructions, comprehending <strong>EVERY line of code</strong> you write won’t help. Because you’ll forget about them afterwards, take notes.</li><li>Genuinely <strong>understand </strong>what you’re performing make the project (like anything else) for the learning opportunity and to hone your talents, not just to complete it.</li><li><strong>Enjoy breaks</strong>! It’s usually time to take a break and work on something else if you’ve been stuck on the same subject for a while. When you return to the debugging process, you’ll view things differently.</li></ul><h4>Aaaand we’re done!!!!!</h4><p>S/O to <a href="https://medium.com/u/4ae9ef694be0">Tejas Pradhan</a> for writing the research paper I followed and helping me when I got stuck!</p><p>I really hope you found this article interesting. If that’s the case, you can find more of my fascinating stuff here:</p><p><a href="https://medium.com/@serjankaur">Serjan Kaur - Medium</a></p><blockquote><em>Hey! Thanks for reading till the end:) I am 16y/o </em><strong>AI enthusiast and an innovator at </strong><a href="https://tks.world/"><strong>The Knowledge Society (TKS)</strong></a><strong>.</strong></blockquote><blockquote>My LinkedIn: <a href="https://www.linkedin.com/in/serjan-kaur-"><em>https://www.linkedin.com/in/serjan-kaur-</em></a></blockquote><blockquote>My Twitter: <a href="https://twitter.com/serjannnnnn"><em>https://twitter.com/serjannnnnn</em></a></blockquote><blockquote>Subscribe to my monthly newsletters: <a href="https://serjan.substack.com/"><em>https://serjan.substack.com/</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65ce7d1d635b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/innonation-publication/using-ml-in-personality-analysis-65ce7d1d635b">Using ML in Personality Analysis</a> was originally published in <a href="https://medium.com/innonation-publication">The Innostation Publication</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking news:ML can help detect fake news and this isn’t fake news ]]></title>
            <link>https://medium.com/@serjankaur/breaking-news-ml-can-help-detect-fake-news-and-this-isnt-fake-news-e1629268bb20?source=rss-ec4ee2f63df8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1629268bb20</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fake-news-detection]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Serjan Kaur]]></dc:creator>
            <pubDate>Fri, 04 Feb 2022 18:39:58 GMT</pubDate>
            <atom:updated>2022-02-04T18:39:58.872Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NiDT-p-fW_NB0WfC.jpg" /></figure><p>Whether it is Web 1.0, 2.0, or web3.0 fabricated news has always existed, even before the Internet. Fake news could be defined as articles that are purposefully made up to deceive the readers. These articles are used as a tactic to increase readership or as part of psychological warfare to profit through clickbait.Enticing-exaggerated-flashy headlines and clickbait are used to spark curiosity to increase advertisements revenues.</p><p>It would be an understatement to say that false news has the power to provide a weapon unlike any other when employed appropriately.Fake news has been omnipresent for a long time now but it has lately gotten a lot of attention because of the massive quantity of disinformation surrounding the novel coronavirus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jizUc7QaLZXOMSc-.jpg" /></figure><p>This article aims to walk you through feasible solutions to detecting and filtering out articles containing misleading information by creating a machine learning model using python and NLP.</p><blockquote>Don&#39;t know what NLP is? Fair enough , I got you!</blockquote><h3><em>Natural Language Processing</em></h3><p>NLP is basically a crossover between computer science and computational linguistics. Computers use binary digits (0,1) to communicate even for the most basic tasks, humans have 6500 different types of languages with their own syntax. NPLs are used for language translators,social media monitoring,chatbots,and survey analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9EEFlZZd8QnNeYTb" /></figure><h4>Let’s go over the Fundamentals</h4><ul><li><strong>Tokenization</strong>: It is a process of splitting text objects into smaller units called tokens. Tokens can be numbers, texts, or symbols.</li><li><strong>Part-of-speech-tagging:</strong> POS is categorizing texts into lists of words where they are segregated according to whether the word is a noun, adjective, verb, and so on.</li><li><strong>Stemming and lemmatization:</strong> The process of removing prefixes and suffixes to extract the base form of a word. Lemmatization takes into account the context and converts the word to its meaningful base form, whereas stemming only removes the last few characters, resulting in inaccurate interpretations and spelling mistakes.</li><li><strong>Stop word removal:</strong> As the name suggests it is the eliminating words that appear in a large number of documents in the corpus Articles and pronouns, for example, are commonly characterized as stop words.</li></ul><h4>Getting the environment set up</h4><p>For starters, to set up the environment I’ll be using<strong> </strong><a href="https://colab.research.google.com/"><strong>google colab</strong></a> because it’s a fantastic tool for tasks requiring deep learning. It’s a hosted Jupyter notebook that doesn’t require installation and has a great free version that gives you free access to Google computing resources like GPUs and TPUs.</p><h3><strong>Let’s go over the code</strong></h3><p>I’ll breakdown the code downbelow but here is the <a href="https://colab.research.google.com/drive/1Ly8BnD3AYEcqPB4GYwglSu1avGFMB017?usp=sharing"><strong>colab link</strong></a> !</p><h4><strong>Start by importing </strong>the<strong> libraries :</strong></h4><pre>#importing libraries <br>import numpy as np<br>import pandas as pd<br>import re<br>from nltk.corpus import stopwords<br>from nltk.stem.porter import PorterStemmer<br>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import accuracy_score</pre><p>Numpy : Numerical Python is a Python library that includes multidimensional array and matrix data structures. I used it to create and manipulate data arrays.It basically did all the Math stuff we don’t really want to do</p><p>Pandas: is another open source library which we use for data analysis</p><p>re: Regular expression is used to search for words in strings</p><h4><strong>Other Essentials</strong></h4><p>Stopwords : Removes words such as articles , prepositions (“the”, “a”, “an”, “in”)that do not add much value</p><p><strong>PorterStemmer</strong> : It implements the Porter Stemming technique. This is the procedure for removing prefixes from a word to reveal the root-word.</p><p><strong>TfidfVectorizer()</strong> : It’s a text vectorizer that uses Term Frequency (TF) and Document Frequency (DF) to convert text into usable vectors (DF). The number of occurrences of a specific term in a document is referred to as the TF, and it indicates how important that term is in that document. The number of documents containing a specific term is referred to as the (Idf). The frequency of a term in a document indicates how common it is.</p><p><strong>LogisticRegression()</strong> : Is a classification algorithm that predicts the probability of a categorical dependent variable using machine learning. In other words, as a function of X, the logistic regression model predicts P(Y=1). [I’ll link it to easy to follow documentation]</p><p>The theory behind <a href="https://realpython.com/logistic-regression-python/"><strong>Logistic Regression</strong></a>, and the<strong> </strong><a href="https://towardsdatascience.com/tf-idf-explained-and-python-sklearn-implementation-b020c5e83275"><strong>TfidfVectorizer</strong></a>, is extensive and complex, and it would take more than one blog to fully explain it. Furthermore, I would still be unable to explain them as precisely as their creators, so I will refrain from doing so.</p><h4><strong>Importing the Datasets</strong></h4><p>Importing datasets is very fundamental when working on a machine learning model. A dataset is a set of data that is usually presented in tabular format. Each column denotes a distinct variable.The dataset we’re using has 4 variables : id, title, author, text and label. The label signifies whether a news is real or fake.</p><p>0 = real</p><p>1 = fake</p><p>Here is the <a href="https://github.com/serjankaur05/serjankaur05/blob/35843d093c4965c1d081da584ce5ebf107efdf76/fakenewsdetection.ipynb">dataset</a> I used! Kaggle provided the dataset for this project as a csv file.</p><pre># loading the dataset to a pandas DataFrame</pre><pre>news_dataset = pd.read_csv(&#39;train.csv&#39;)</pre><pre>news_dataset.shape</pre><p>The read_csv()function in Pandas imports a CSV file into a DataFrame.</p><h3>It’s time to Pre-Process the Data</h3><h4>1. Swapping empty strings with missing values</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XiuYgFoKkHzw7Exa9yMpQA.png" /><figcaption><strong>We count the number of missing values in the dataset and the null values are replaced with empty strings.</strong></figcaption></figure><p><strong>Purpose</strong> : To remove all blank/empty spaces from our datasets because they do not add any value.</p><h4>2. Merging the author name and news title</h4><p>Make a new variable called ‘content’ by combining the author and title columns. Then separate the data (content) from the label and assign x and y variables respectively.</p><pre># merging the author name and news title</pre><pre>news_dataset[&#39;content&#39;] = news_dataset[&#39;author&#39;]+&#39; &#39;+news_dataset [&#39;title&#39;]<br>print(news_dataset[&#39;content&#39;])</pre><pre># separating the data &amp; label<br>X = news_dataset.drop(columns=&#39;label&#39;, axis=1)<br>Y = news_dataset[&#39;label&#39;]</pre><pre>print(X)<br>print(Y)</pre><p>Purpose : instead of focusing on the ‘text’ column from the dataset , I decided to combine ‘author’ and ‘title’ which is the data I’ll use for prediction since it is shorter than ‘text’.</p><h4>3. Stemming time!</h4><p>As I’ve explained before , Stemming is the process of reducing a word to its Root word</p><p>For instance : Playing , Plays, Played → Play</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yAcWmGeGsuyTdpQQ_gX2vw.png" /></figure><p>port_stem = Porterstemmer() The Porter stemming algorithm (also known as the ‘Porter stemmer’) is a method for removing inflexional endings from English. This done because it is important to reduce words down to get the most accurate outcome</p><p>The next step seems complicated but it is really not, let me break it down!</p><p>We create a new function labeled ‘stemming’</p><p>re.sub(&#39;[^a-zA-Z]&#39;,&#39;’,content) : We’re using the .subcommand to substitute certain values and the Regular expression library (re.)to help search for words in data.The command is asking to only use data that is words and sub in empty spaces for puncations, numbers, and other non-alphabetic data.</p><p>stemmed_content.lower(): changes all data into lowercase letters</p><p>stemmed_content.split() : gives you a list of all the words in the string or line.</p><p>port_stem.stem(word) for word in stemmed_content if not word in stopwords.words(‘english’)]: The data frame is passed into a for loop, all stop words are removed, and then stemming is performed on the remaining data.</p><p>Finally , using .join all the data is combined</p><h4>4. Stemming is applied to all data</h4><pre># applying stemming to the data</pre><pre>news_dataset[‘content’] = news_dataset[‘content’].apply(stemming)</pre><p>Purpose : this will leave us with data that is strictly (lowercase) alphabetical and does not include any numbers, punctuations or stopwords which makes it easier when we transform the data to numerical data later on.</p><h4>5. Separating content(data) and label and assign x and y variables</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bjgRSDufrWpkyrfT-mM6uA.png" /></figure><h4>6. Convert texts to numbers</h4><p>Now that we’re done removing stopwords and performing stemming,It’s time to convert textual data into numerical data using TfidfVectorizer!</p><pre>#converting the textual data to #<br>vectorizer = TfidfVectorizer()<br>vectorizer.fit(x)</pre><pre>x = vectorizer.transform(x)</pre><pre>print(x)</pre><p>Create a variable called “vectorizer” and save the function there. The vectorizer functions are then fitted(.fit)with the x value, which means that all data under the x variable passes through the vectorizer function. Then .transform will convert all the values to their respective features.</p><p><strong>Purpose </strong>: Since our computer can not understand textual data it is CRUCIAL to convert it into numerical data for it to get processed.</p><h4>7. Next we split the dataset into training and testing data</h4><pre># split between train and test<br>x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, stratify=y, random_state=2 )</pre><p>The datasets are divided in two parts</p><ul><li><strong>Train Dataset</strong>: This is the data set that is used to fit the machine learning model.</li><li><strong>Test Dataset</strong>: This dataset is used to assess how well a machine learning model fits.</li></ul><p>The goal is to estimate the machine learning model’s performance on new data that was not used to train the model.</p><p>test size = 0.2 means 20% of the total dataset is allocated to testing .</p><p>Staritfy = y will segregate fake and real news similarly to the one in the original dataset</p><p>Purpose : You test a model by making predictions against the test set after it has been processed using the training set. It is simple to determine whether the model’s guesses are correct because the data in the testing set already contains known values for the attribute that you want to predict.</p><h4><strong>8. Finallyyy it’s time to train the model using logistic regression</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2guVt0UxOdKRgo9pg_jRw.png" /><figcaption>This one line of code does all the work we don’t really want to :)</figcaption></figure><p>The variable ‘model’ is assigned to the function logisticRegression()</p><p>.fit will train the model by plotting the sigmoid function curve using logistic regression</p><p>As previously stated, this machine learning classification model aids in the prediction of the probability of a categorical dependent variable, where the dependent variable is a binary variable with data coded as 1 (true) or 0 (false)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*0kfNilomzwElM4uJ.png" /></figure><p>The threshold value is calculated using the sigmoid formula; if the prediction is greater than the threshold value, the value is 1 which in this project means it is fake news; if it is less than the threshold value, the value is 0, which means real news.</p><h4><strong>9. Lets check the accuracy of the training and testing dataset</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JdOmaovW0V8zJLSLvotQ_Q.png" /></figure><p>As you can see the accuracy is pretty great, so good job!</p><h4><strong>9. Predictive System</strong></h4><p>Lastly, we make a predictive system so if new data is introduced to the model, it can still predict it right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*efZXVd9aYAOuAYeqoIcS9g.png" /></figure><p>We’re going to store the first row [0] from the x _test dataset in a new variable called x _new. Next, we use the model we previously trained (model.predict) to predict the label of x _new.</p><p>Then we introduce an if statement which asks to print “the news is real” if the prediction is 0 or else print “fake news” if the prediction output is 1.</p><blockquote><em>That’s it, You see it was pretty simple!</em></blockquote><h4><strong>Conclusion &amp; </strong>Takeaways</h4><p>Building this project sure was a process but I am glad I went through it. I’ve learned quite a bit about building machine learning models and got some experience in working with libraries &amp; algorithms. In the beginning, I was doubting and questioned the process but in retrospect, I would strongly recommend it to anyone who is just getting started and willing to learn.</p><ul><li>It won’t do any good if you are only copy-pasting all the steps, understanding EVERY line of code you’re writing. Make notes because you will forget about them later. <strong>Truly understand</strong> what you’re doing!</li><li>Don’t make the project (much like anything else) for the sake of doing it, do it for the <strong>learning experience </strong>and to expand your skills.</li><li><strong>Take breaks!</strong> If you’re stuck on the same thing for a long time, it’s probably time to step back and work on something else. When you get back to debugging you’ll look at it from a different perspective/light.</li></ul><h4>Aaaand we’re done!!!!!</h4><p>S/O to the <a href="https://youtu.be/nacLBdyG6jE">youtube tutorial</a> I followed!</p><p>I really hope you found this article interesting. If that’s the case, you can find more of my fascinating stuff here:</p><p><a href="https://medium.com/@serjankaur">Serjan Kaur - Medium</a></p><blockquote>Hey! Thanks for reading till the end:) I am 16y/o <strong><em>AI enthusiast and an innovator at </em></strong><a href="https://tks.world/"><strong><em>The Knowledge Society (TKS)</em></strong></a><strong><em>.</em></strong></blockquote><blockquote><em>My LinkedIn: </em><a href="https://www.linkedin.com/in/serjan-kaur-">https://www.linkedin.com/in/serjan-kaur-</a></blockquote><blockquote><em>My Twitter: </em><a href="https://twitter.com/serjannnnnn">https://twitter.com/serjannnnnn</a></blockquote><blockquote><em>Subscribe to my monthly newsletters: </em><a href="https://serjan.substack.com/">https://serjan.substack.com/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1629268bb20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A crossover between AI and advertising?]]></title>
            <link>https://medium.com/@serjankaur/a-crossover-between-ai-and-advertising-7b95568bf863?source=rss-ec4ee2f63df8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b95568bf863</guid>
            <dc:creator><![CDATA[Serjan Kaur]]></dc:creator>
            <pubDate>Fri, 03 Dec 2021 22:50:25 GMT</pubDate>
            <atom:updated>2021-12-04T14:25:05.041Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is <a href="https://www.thedrum.com/opinion/2021/08/18/how-machine-learning-can-help-us-build-effective-contextual-advertising#:~:text=convincing%20contextual">contextual advertising?</a></h4><p>This form of new and revised advertising refers to the technique of placing advertisements on web pages depending on their content. This type of target advertising is seen on online forums including websites and other social media. In context targeting, the media is controlled based on linguistic features in the content of a website. These are selected and served based on automated systems based on the user’s preferred data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-bYnkbzjjPrET6lt.png" /></figure><p><em>Example</em>: Ads for running shoes would be on a fitness article and ads on a new iPhone would be on a tech e-commerce site.</p><h4>What is machine learning</h4><p>The oldest branch of artificial learning, machine learning, revolves around using data and algorithms to copy the actions of humans, gradually increasing its accuracy.ML Without being expressly coded, learn and improve via experience. It focuses on Computer programs that can access data and utilize it to learn for themselves are being developed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*Hu9Lo0JdPjvfD5yE" /></figure><p><em>Example</em>: Image recognition, speech recognition,classification are all examples of machine learning.</p><h4>Crossover? “Contextual Intelligence”</h4><p>In a very literal sense, contextual analysis refers to scanning a web page to get a deeper and better understanding of the history/culture and contextual background of the content. It helps advertisers as it allows for targeting consumers through analyzing the type of content a viewer wants to see. It is extremely fast as it takes mere seconds to come up with a comprehensive report of the audience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RwSqvEGBumjH3iU6.png" /></figure><p>The transition from using keywords found on websites to trigger an ad to “Contextual 2.0” that uses machine learning tech like computer vision and natural language processing, to provide “targeting accuracy”. The technology is now capable of comprehending nuanced meanings behind texts and images that help in outputting far more precise data, further enabling more precise ad placements.</p><h4>Structuring ads:</h4><p>ML also helps in structuring and placement of the content. It uses real-time events and the pattern of how consumers interact with content. A range of data called “signals” incorporates several traditional behavioral concepts. It enables the segmentation of audience targets to be fine-tuned.</p><h4>Working:</h4><ol><li>Recognize sentences that are both in and out of context (in the campaign setup).</li><li>The algorithm will then decide on the optimum ad placements depending on the content of the website.</li><li>Based on the content of a publisher or site, an algorithm will then select the optimum ad placements.</li><li>Targeting can now include relevant terms connected to the context thanks to artificial intelligence (AI).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/0*ajDckkqXigQ3tN5a.png" /></figure><h4>In Conclusion,</h4><p>This type of advertising not only protects companies, but also increases their favorability dramatically even before target consumers have ever clicked the link. Contextual advertising is the way of the future in advertising, and it’s an incredibly effective way to get your message in front of the proper audience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b95568bf863" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Quick Review of Deep Neural Network]]></title>
            <link>https://medium.com/@serjankaur/a-quick-review-of-deep-neural-network-73188709a00a?source=rss-ec4ee2f63df8------2</link>
            <guid isPermaLink="false">https://medium.com/p/73188709a00a</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Serjan Kaur]]></dc:creator>
            <pubDate>Mon, 15 Nov 2021 04:44:04 GMT</pubDate>
            <atom:updated>2021-11-15T05:28:21.841Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine a world without any road accidents, road rage, where every operation is successful, and where people with mental or physical disabilities can enjoy the same quality of life as everyone else. Sounds unattainable? So did self-driving cars and virtual assistants less than a decade ago, but now they are a part of our everyday life. All thanks to Deep Neural Network all of these and much more are possible.</p><h4>What is Artificial Intelligence?</h4><p>AI is the branch of computer science that aims to answer the question, “Can machines think?” In doing so it duplicates and reproduces human intelligence in machine form. It can be efficient in fields such as expert systems, natural language processing, speech recognition, and machine vision.</p><h4>🧠DNN or Deep Neural Network:</h4><p>The article will revolve around a machine learning model of AI called Deep Neural Networks. Inspired by the artificial neurons (interconnected units)in a human brain, DNN or Deep neural networks in a very literal sense are artificial neural networks that have several hidden layers between input and output layers; which are designed to identify patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*2-piUzcrmMqIv_Dw.png" /></figure><p>The term “deep” in Deep Learning refers to the presence of several hidden layers. This machine learning network uses several layers of nodes to transform the data into a more creative and abstract component.</p><h3>🥼Components:</h3><p><strong>Neurons</strong></p><p>Are nodes through which date and calculations flow across. The nodes receive 1+ input signals which come from either raw data or neurons in a previous layer of the neural network. After performing some calculations, output signals are sent to neurons farther down the neural net through a synapse.</p><p><strong>Synapses</strong></p><p>Is the connection between neurons that holds them together while meditating information transfer from one neuron to the next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rLAdeMcRMp6z-UVv.png" /></figure><p>Each synapse has a different level of control as to whether or not a neuron is fired. The synapses are affected by the amplitude of the connection between both nodes, called synaptic weight.</p><h4>Weights</h4><p>Also known as learnable parameters are the variables that control the strength of the connection between two neurons. Its job is to decide how much influence an input has on the output.</p><p><strong>Biases</strong></p><p>The other half of learnable parameters are the constant numbers that always have the value of 1 and are an additional input into the next layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/0*UBzY2ENJoj2Uiugm.png" /></figure><p>They do not have any incoming connections but do affect the outgoing connections with their weights. Their job is to guarantee then when all inputs are zero, there will still be activation in the neuron.</p><h4>Working:</h4><p><strong>Input Layer</strong>:</p><p>At the very beginning of the artificial neural network workflow, The input layer comprises artificial input neurons; its job is to bring the initial data into the system for further processing by subsequent layers of artificial neurons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/0*lOWFy60SjiXF6uyK.png" /><figcaption>(Farhad Malik,2019)</figcaption></figure><p>Because they are the very first layer of the network, they do not take in information from preceding levels. Because this information is just coming into the system, parts of the artificial neurons do not have a set weight yet. The data is sent from the input layer to the succeeding layers, where the neurons have weighted inputs.</p><p><strong>Hidden (computation) Layers</strong></p><p>Located between the input and output layer, the job of the hidden layer is to apply weights to the inputs and direct them to the output layer through the activation function. It is the number of hidden layers that distinguish simple neural networks from deep neural networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*XKAR5T1Osg4hFyS_" /></figure><p>These are layers of mathematical functions whose purpose is to create an outcome that is specific to the goal. The layers allow all data in DNN to be broken down into specific transformations of the data. The job of each layer is specialized to create a predetermined result.</p><h4>Output Layers</h4><p>The last layer of the neurons is responsible for taking inputs passed down by the preceding layers and completing calculations via its neurons, after which the output is generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/0*_VnzYnZBeKs8e6U4.png" /><figcaption>(Farhad Malik,2019)</figcaption></figure><p>There is only one output layer and neurons in it are observed differently because they are the last nodes.</p><p>This Machine Learning tool can be used in Self Driving Cars, Fraud News Detection, Natural Language Processing, Virtual Assistants, Entertainment, Visual Recognition, Fraud Detection, Healthcare, Detecting Developmental Delay in Children, etc.</p><p>Deep Neural Networks are a revolutionizing technology, and now you know a little bit more about them.</p><p>Thanks for reading till the end! Leave a clap and follow me on Medium if you liked the article. 👍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73188709a00a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>