<?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 fuyofulo on Medium]]></title>
        <description><![CDATA[Stories by fuyofulo on Medium]]></description>
        <link>https://medium.com/@fuyofulo?source=rss-8b7146205b3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AzKbhbndnPq0P2-HWJev5Q.png</url>
            <title>Stories by fuyofulo on Medium</title>
            <link>https://medium.com/@fuyofulo?source=rss-8b7146205b3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:23:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fuyofulo/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[Implementing Raft from First Principles in Rust]]></title>
            <link>https://fuyofulo.medium.com/implementing-raft-from-first-principles-in-rust-c2b4e0166c6d?source=rss-8b7146205b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2b4e0166c6d</guid>
            <category><![CDATA[computer-networking]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[fuyofulo]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 03:10:56 GMT</pubDate>
            <atom:updated>2026-02-26T03:10:56.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*3UNb2W1RVTh27Xvb" /></figure><p>This article presents a ground up implementation of the Raft consensus protocol in Rust.</p><p>The implementation encodes Raft’s safety properties directly through explicit state transitions and RPC handling logic. Leader election, log replication, quorum based commit, and state machine application are implemented without any external consensus frameworks.</p><p>Code: <a href="https://github.com/fuyofulo/raft_kv">https://github.com/fuyofulo/raft_kv</a></p><h3>What Raft Consensus Is</h3><p>Raft is a crash fault tolerant consensus protocol for replicated state machines. It ensures that a cluster of nodes agrees on a single, ordered log of commands. Once a command is committed, all correct nodes will apply it in the same order and reach the same state. It guarantees linearizable writes and single leader operation under crash stop failures.</p><p>If you have zero idea about raft, you should watch this video before continuing the rest of the article:</p><p><a href="https://www.youtube.com/watch?v=IujMVjKvWP4">https://www.youtube.com/watch?v=IujMVjKvWP4</a></p><h4>It does three things:</h4><ul><li>elects a leader</li><li>replicates a log of commands</li><li>defines exactly when commands are safe to apply</li></ul><h4>At any point in time:</h4><ul><li>one node is leader (for a term)</li><li>followers accept replicated log entries from that leader</li><li>clients observe a consistent history once entries are committed</li></ul><h3>What Problem Raft Solves</h3><p>Without consensus, replicated systems fail in predictable ways:</p><ul><li>multiple leaders may accept conflicting writes</li><li>stale leaders may overwrite newer state</li><li>nodes may apply commands in different orders</li><li>client retries may cause duplicate effects</li></ul><p>Raft addresses these failures through:</p><ul><li><strong>terms </strong>(logical epochs)</li><li><strong>quorum voting</strong> for leadership</li><li><strong>log-matching checks</strong> (<em>prev_log_index</em>, <em>prev_log_term</em>)</li><li><strong>commit-before-apply discipline</strong></li></ul><h3>Where Raft Is Used</h3><p>Raft is used in systems requiring strongly consistent replicated state with leader based failover, including:</p><ul><li>coordination and control planes</li><li>configuration and service discovery systems</li><li>replicated metadata stores</li><li>distributed key value systems requiring linearizable writes</li></ul><p>Typical production systems add more layers (snapshots, membership changes, compaction), but the core safety rules still come from Raft.</p><h3>Fault Model and Guarantees (First Principles)</h3><p>This implementation assumes:</p><ul><li>crash stop failures</li><li>delayed, dropped, reordered RPC messages</li><li>stable storage for persistent state</li><li>no Byzantine behavior</li></ul><p>Target guarantees:</p><ul><li>election safety (at most one leader per term)</li><li>log matching (shared prefixes for matching index/term pairs)</li><li>leader completeness (committed entries survive leadership changes)</li><li>state machine safety (no two nodes apply different commands at the same index)</li></ul><h3>Cluster Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HfIZmppBwea3wgyR" /><figcaption>The leader appends entries locally, replicates them to followers, and advances the commit index once a quorum has replicated the entry.</figcaption></figure><h4>Election Mechanics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y3OzHWjPXRk528U1" /></figure><p>A vote is granted only if:</p><ul><li>candidate term is current/newer</li><li>node has not voted for a different candidate in same term</li><li>candidate log is at least as upto date</li></ul><h4>Replication Mechanics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rN1U4iBNqxXUdw9S" /></figure><h3>Implementation Entry Point: The Core Raft Module</h3><p>All protocol critical state transitions live in one core module.</p><p>The key design decision is explicit separation of persistent, volatile, and leader only state.</p><h4>State Layout in Code</h4><p>Before election and replication code, we need precise state layout. Most Raft bugs come from incorrect state transitions, not syntax.</p><p>The state is intentionally split into:</p><ul><li>durable protocol state</li><li>runtime protocol state</li><li>leader only replication state</li><li>application state</li></ul><h4>Protocol scalar types</h4><pre>pub type NodeId = u64;<br>pub type Term = u64;<br>pub type LogIndex = u64;</pre><p>These aliases look small, but they make protocol code readable: term math and log index math stay explicit.</p><h4>Replicated command type</h4><pre>pub enum Command {<br>    Put { key: String, value: String },<br>    Update { key: String, value: String },<br>    Delete { key: String },<br>    Noop<br>}</pre><p>These commands are deterministic state machine inputs.</p><p>If two nodes apply the same committed command sequence, they must produce identical KV state.</p><h4>Log entry structure (consensus metadata + idempotency metadata)</h4><pre>pub struct LogEntry {<br>    pub term: Term,<br>    pub command: Command,<br>    pub client_id: Option&lt;u64&gt;,<br>    pub request_id: Option&lt;u64&gt;,<br>}</pre><p>Field meaning:</p><ul><li><em>term</em>: leader term that appended this entry</li><li><em>command</em>: application operation to apply later</li><li><em>client_id</em>, <em>request_id</em>: identity metadata for retry safety</li></ul><p>Why optional request metadata:</p><ul><li>client writes carry these values</li><li>internal entries (like <em>Noop</em>) may not need them</li></ul><h4>Persistent state (must survive restart)</h4><pre>pub struct PersistentState {<br>    pub current_term: Term,<br>    pub voted_for: Option&lt;NodeId&gt;,<br>    pub log: Vec&lt;LogEntry&gt;<br>}</pre><h4>This is the core durable Raft memory:</h4><ul><li><em>current_term</em>: prevents old leaders from resurrecting authority</li><li><em>voted_for</em>: enforces atmost one vote per term</li><li><em>log</em>: canonical replicated history</li></ul><h4>Volatile state (reconstructed / runtime state)</h4><pre>pub struct VolatileState {<br>    pub commit_index: LogIndex,<br>    pub last_applied: LogIndex,<br>    pub role: Role<br>}</pre><p>Why <em>commit_index</em> and <em>last_applied</em> are separate:</p><ul><li><em>commit_index</em> = safe by quorum</li><li><em>last_applied </em>= already executed on state machine</li></ul><p>This prevents “replicated but uncommitted” entries from mutating application state.</p><h4>Leader replication tracking</h4><pre>pub struct LeaderState {<br>    pub next_index: HashMap&lt;NodeId, LogIndex&gt;,<br>    pub match_index: HashMap&lt;NodeId, LogIndex&gt;<br>}</pre><p>Leader only replication cursors:</p><ul><li><em>next_index[peer]</em>: next index to try sending to that peer</li><li><em>match_index[peer]</em>: highest index known replicated on that peer</li></ul><p>This pair drives catch up after lag and partition recovery.</p><h4>Node aggregate state</h4><pre>pub struct RaftNode {<br>    pub id: NodeId,<br>    pub peers: Vec&lt;NodeId&gt;,<br>    pub persistent: PersistentState,<br>    pub volatile: VolatileState,<br>    pub leader_state: Option&lt;LeaderState&gt;,<br>    pub known_leader: Option&lt;NodeId&gt;,<br>    pub state_machine: HashMap&lt;String, String&gt;,<br>    pub dedup_table: HashMap&lt;u64, CachedClientReply&gt;,<br>}</pre><p><em>RaftNode</em> is where protocol and application meet:</p><ul><li>consensus state decides what is safe</li><li>state machine executes only safe entries</li><li>dedup table makes client retries idempotent across leader changes</li></ul><h3>Role Transitions</h3><h4>Follower transition</h4><pre>pub fn become_follower(&amp;mut self, new_term: Term) {<br>    if self.persistent.current_term &gt; new_term {<br>        return;<br>    }<br><br>    if new_term &gt; self.persistent.current_term {<br>        self.persistent.current_term = new_term;<br>        self.persistent.voted_for = None;<br>    }<br><br>    self.volatile.role = Role::Follower;<br>    self.leader_state = None;<br>    self.known_leader = None;<br>}</pre><p>Protocol effect:</p><ul><li>monotonic term</li><li>vote reset on higher term</li><li>leader state cleared</li></ul><h4>Candidate transition</h4><pre>pub fn become_candidate(&amp;mut self) {<br>    self.volatile.role = Role::Candidate;<br>    self.persistent.current_term += 1;<br>    self.persistent.voted_for = Some(self.id);<br>    self.leader_state = None;<br>    self.known_leader = None;<br>}</pre><h4>Leader transition</h4><pre>pub fn become_leader(&amp;mut self) {<br>    self.volatile.role = Role::Leader;<br>    self.known_leader = Some(self.id);</pre><h4>Vote Path (on_request_vote)</h4><pre>pub fn on_request_vote(&amp;mut self, req: RequestVote) -&gt; RequestVoteResponse {<br>    if req.term &lt; self.persistent.current_term {<br>        return RequestVoteResponse { term: self.persistent.current_term, vote_granted: false };<br>    }<br><br>    if req.term &gt; self.persistent.current_term {<br>        self.become_follower(req.term);<br>    }<br><br>    let voted_for_other = matches!(<br>        self.persistent.voted_for,<br>        Some(voted_for) if voted_for != req.candidate_id<br>    );<br>    if voted_for_other {<br>        return RequestVoteResponse { term: self.persistent.current_term, vote_granted: false };<br>    }<br><br>    if !self.is_candidate_log_up_to_date(req.last_log_term, req.last_log_index) {<br>        return RequestVoteResponse { term: self.persistent.current_term, vote_granted: false };<br>    }<br><br>    self.persistent.voted_for = Some(req.candidate_id);<br>    RequestVoteResponse { term: self.persistent.current_term, vote_granted: true }<br>}</pre><h4>Up-to-date rule:</h4><pre>pub fn is_candidate_log_up_to_date(&amp;self, candidate_last_log_term: Term, candidate_last_log_index: LogIndex) -&gt; bool {<br>    let my_term = self.last_log_term();<br>    let my_index = self.last_log_index();<br><br>    if candidate_last_log_term != my_term {<br>        candidate_last_log_term &gt; my_term<br>    } else {<br>        candidate_last_log_index &gt;= my_index<br>    }<br>}</pre><h3>AppendEntries Path (on_append_entries)</h3><h4>Reject stale leader terms</h4><pre>if req.term &lt; self.persistent.current_term {<br>    return AppendEntriesResponse {<br>        term: self.persistent.current_term,<br>        success: false,<br>        match_index: self.last_log_index()<br>    };<br>}</pre><h4>Accept authority of current/newer term leader</h4><pre>self.become_follower(req.term);<br>self.known_leader = Some(req.leader_id);</pre><h4>Enforce log matching</h4><pre>if self.log_term_at(req.prev_log_index) != Some(req.prev_log_term) {<br>    return AppendEntriesResponse {<br>        term: self.persistent.current_term,<br>        success: false,<br>        match_index: self.last_log_index(),<br>    };<br>}</pre><h4>Resolve conflicts and append</h4><pre>match self.persistent.log.get(vec_idx) {<br>    Some(existing) if existing.term == entry.term =&gt; {<br>        insert_index += 1;<br>    }<br>    Some(_) =&gt; {<br>        self.persistent.log.truncate(vec_idx);<br>        self.persistent.log.push(entry);<br>        log_changed = true;<br>        insert_index += 1;<br>    }<br>    None =&gt; {<br>        self.persistent.log.push(entry);<br>        log_changed = true;<br>        insert_index += 1;<br>    }<br>}</pre><h4><strong>Commit propagation (bounded by local log length)</strong></h4><pre>let new_commit = std::cmp::min(req.leader_commit, self.last_log_index());<br>if new_commit &gt; self.volatile.commit_index {<br>    self.volatile.commit_index = new_commit;<br>    self.apply_committed_entries();<br>}</pre><h3><strong>Leader Replication Bookkeeping</strong></h3><h4>Build peer specific AppendEntries from next_index</h4><pre>let next_index = leader_state<br>    .next_index<br>    .get(&amp;peer)<br>    .copied()<br>    .unwrap_or(self.last_log_index() + 1);<br>let prev_log_index = next_index.saturating_sub(1);<br>let prev_log_term = self.log_term_at(prev_log_index)?;<br><br>let start = next_index.saturating_sub(1) as usize;<br>let entries = if start &lt; self.persistent.log.len() {<br>    self.persistent.log[start..].to_vec()<br>} else {<br>    vec![]<br>};</pre><h4>Process AppendEntries responses</h4><pre>if response.success {<br>    leader_state.match_index.insert(from, response.match_index);<br>    leader_state.next_index.insert(from, response.match_index + 1);<br>} else {<br>    let current = leader_state.next_index.get(&amp;from).copied().unwrap_or(default_next);<br>    leader_state.next_index.insert(from, std::cmp::max(1, current.saturating_sub(1)));<br>}</pre><h4>Advance commit index with quorum and current term restriction</h4><pre>for n in (self.volatile.commit_index + 1)..=self.last_log_index() {<br>    if self.log_term_at(n) != Some(self.persistent.current_term) {<br>        continue;<br>    }<br><br>    let mut replicated = 1;<br>    for peer in &amp;self.peers {<br>        let m = leader_state.match_index.get(peer).copied().unwrap_or(0);<br>        if m &gt;= n {<br>            replicated += 1;<br>        }<br>    }<br><br>    if replicated &gt;= quorum {<br>        new_commit = n;<br>    }<br>}</pre><h3>Client Semantics: Leader only + Idempotent</h3><h4>Leader-only writes</h4><pre>if self.volatile.role != Role::Leader {<br>    return ClientWriteResult::NotLeader {<br>        known_leader: self.known_leader,<br>   };<br>}</pre><h4>Dedup lookup before append</h4><pre>if let Some(cached) = self.dedup_table.get(&amp;req.client_id) {<br>    if cached.request_id &gt;= req.request_id {<br>        return ClientWriteResult::Ok {<br>            log_index: cached.log_index,<br>            from_cache: true,<br>            message: cached.message.clone(),<br>        };<br>    }<br>}</pre><h4><strong>Append request as replicated log entry</strong></h4><pre>let entry = LogEntry {<br>    term: self.persistent.current_term,<br>    command: req.command,<br>    client_id: Some(req.client_id),<br>    request_id: Some(req.request_id),<br>};<br>self.persistent.log.push(entry);</pre><h3>Apply Path: Commit Before State Machine Mutation</h3><pre>while self.volatile.last_applied &lt; self.volatile.commit_index {<br>    let index = self.volatile.last_applied + 1;<br>    let vec_idx = (index - 1) as usize;<br>    let Some(entry) = self.persistent.log.get(vec_idx).cloned() else {<br>        break;<br>    };<br><br>    self.apply_entry(index, entry);<br>    self.volatile.last_applied = index;<br>}</pre><p>This is the line between “replicated log data exists” and “state machine changed”.</p><h3>Command application itself:</h3><pre>fn apply_command(&amp;mut self, command: &amp;Command) -&gt; String {<br>    match command {<br>        Command::Put { key, value } =&gt; {<br>            self.state_machine.insert(key.clone(), value.clone());<br>            &quot;ok&quot;.to_string()<br>        }<br>        Command::Update { key, value } =&gt; {<br>            if self.state_machine.contains_key(key) {<br>                self.state_machine.insert(key.clone(), value.clone());<br>                &quot;ok&quot;.to_string()<br>            } else {<br>                &quot;key not found&quot;.to_string()<br>            }<br>        }<br>        Command::Delete { key } =&gt; {<br>            self.state_machine.remove(key);<br>            &quot;ok&quot;.to_string()<br>        }<br>        Command::Noop =&gt; &quot;noop&quot;.to_string(),<br>    }<br>}</pre><h3>End to End Write Trace (put x 10)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CFBt4l6iPKYRaxaJ" /></figure><ol><li>Client hits any node.</li><li>Follower returns <em>NotLeader</em> with leader hint.</li><li>Leader appends <em>(term, command, client_id, request_id)</em> to log.</li><li>Leader replicates using per peer <em>next_index</em>.</li><li>Followers validate prefix via <em>(prev_log_index, prev_log_term)</em>.</li><li>Followers append or truncate+append on conflict.</li><li>Followers ack with <em>match_index</em>.</li><li>Leader computes quorum replication and advances <em>commit_index</em>.</li><li>Leader applies entry (<em>last_applied</em> catches up to <em>commit_index</em>).</li><li>Dedup cache records client reply metadata.</li></ol><p>That path is the core protocol to application bridge.</p><h3>Visualize It Live</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mwi2QvLHnqcRu2wC" /></figure><p>You can run the project and watch Raft behaviour in real time through the dashboard: leader changes, follower catch up, client redirects, and partition/heal effects are all interactive and visible as they happen across all five nodes.</p><p><a href="https://github.com/fuyofulo/raft_kv">https://github.com/fuyofulo/raft_kv</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2b4e0166c6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-time Facial Emotion Recognition using Deep Learning and OpenCV]]></title>
            <link>https://fuyofulo.medium.com/real-time-facial-emotion-recognition-using-deep-learning-and-opencv-30a331d39cf1?source=rss-8b7146205b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/30a331d39cf1</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[project-based-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[image-recognition]]></category>
            <dc:creator><![CDATA[fuyofulo]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 16:23:15 GMT</pubDate>
            <atom:updated>2023-11-15T16:23:15.567Z</atom:updated>
            <content:encoded><![CDATA[<p>As humans, our faces are expressive canvases, revealing a spectrum of emotions from joy and surprise to sadness and anger. In this article, we are going to leverage the power of deep learning and OpenCV to dive into real-time facial emotion recognition from unraveling the complexities of the building a convolutional neural network to training the ML model. <br>while we also discover the significance of this technology and its applications in enhancing human-computer interactions and emotional intelligence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VWXEPqumZU6y6fNN.jpeg" /></figure><p>Facial emotion recognition represents an intersection of artificial intelligence and human psychology. The ability to detect facial expressions not only holds immense value in understanding human emotions but also serves as a interesting direction to look into for enhancing various technological applications. By unraveling the subtle nuances of our facial expressions, machines gain a profound ability to understand human emotions, paving the way for a host of applications across diverse industries.</p><h3>Project Overview</h3><h4>Building a Convolution Neural Network:</h4><p>We’ll start by understanding the complexities of constructing a CNN, the backbone of our facial emotion recognition model. This involves understanding the architecture, layers, and parameters crucial for accurate emotion detection.</p><h4>Training the Machine Learning Model:</h4><p>Once the CNN is in place, we’ll then jump into the process of training the machine learning model. This step involves feeding the model with labeled data to enable it to recognize and classify facial expressions accurately.</p><h4>Real-Time Detection using OpenCV:</h4><p>The final stage of our project involves implementing real-time facial emotion recognition. Leveraging the OpenCV library, we’ll connect your computer’s camera to the model, enabling it to detect and display emotions in real-time.</p><p><em>Ensure that you have Visual Studio Code (VSCode) and Python installed on your system.</em></p><h4>Installing Dataset</h4><p>Click this <a href="https://www.kaggle.com/datasets/jonathanoheix/face-expression-recognition-dataset/">link</a> to go to kaggle and download the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QV64-3JOYTs-ED9PCajx4w.png" /></figure><p>This dataset contains images from which we will train our model and also test it.</p><h4>Required modules</h4><p>Open a folder in vscode where you would like to save this project. Create a file named <strong>requirements.txt </strong>and copy all the modules mentioned below.</p><pre>tensorflow<br>keras<br>pandas<br>numpy<br>jupyter<br>notebook<br>tqdm<br>opencv-contrib-python<br>scikit-learn</pre><p>Now open a new terminal and download all the modules uisng the command</p><pre>pip install -r requirements.txt</pre><p>If this doesn’t work, install every module one by one.</p><pre>pip install tensorflow<br>pip install keras<br>......</pre><p>These are all the modules required to build our convolutional neural network.</p><h3>Building a convolutional neural network</h3><p>Use this command in the terminal to open jupyter notebook. We will be creating and training our neural network in here.</p><pre>jupyter notebook</pre><p>Now click on new and create a new notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypZC88Q0xx-3b45bxBLo9w.png" /></figure><h4>Importing Libraries and Modules</h4><pre>from keras.utils import to_categorical<br>from keras_preprocessing.image import load_img<br>from keras.models import Sequential<br>from keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D<br>import os<br>import pandas as pd<br>import numpy as np</pre><p>This includes the necessary libraries and modules for building and training a neural network. It uses Keras for building the model, pandas for handling data in a tabular form, and other modules for various functionalities.</p><h4>Data Preparation</h4><pre>TRAIN_DIR = &#39;images/train&#39;<br>TEST_DIR = &#39;images/test&#39;</pre><p>These lines define the directories where the training and testing images are located. (I renamed <em>validation </em>as<em> test)</em></p><pre>def createdataframe(dir):<br>    image_paths = []<br>    labels = []<br>    for label in os.listdir(dir):<br>        for imagename in os.listdir(os.path.join(dir, label)):<br>            image_paths.append(os.path.join(dir, label, imagename))<br>            labels.append(label)<br>        print(label, &quot;completed&quot;)<br>    return image_paths, labels</pre><p>This function creates a pandas DataFrame that essentially collects the file paths of images and their corresponding labels, organizing them for further processing.</p><p><strong>Parameters:</strong><br>dir: The input directory containing subdirectories for each label (e.g., &#39;angry&#39;, &#39;happy&#39;).</p><p><strong>Variables: </strong><br>image_paths: An empty list to store the full paths of the image files.<br>labels: An empty list to store the corresponding labels for each image.</p><p><strong>Iteration:</strong> <br>The function iterates over each subdirectory (label) in the given directory (os.listdir(dir)). Within each label’s directory, it iterates over each image file (os.listdir(os.path.join(dir, label))).</p><p><strong>Image Path and Label Collection:<br></strong>For each image, the full path is constructed using os.path.join() and added to the image_paths list.<br>The label of the image is added to the labels list.</p><p><strong>Print Statement:<br></strong>After processing all images in a label, it prints that the label is completed.</p><p><strong>Return: <br></strong>The function returns the lists of image_paths and labels containing information about all the images in the given directory.</p><pre>train = pd.DataFrame()<br>train[&#39;image&#39;], train[&#39;label&#39;] = createdataframe(TRAIN_DIR)<br>print(train)</pre><p>It creates the training DataFrame using the createdataframe function.</p><pre>test = pd.DataFrame()<br>test[&#39;image&#39;], test[&#39;label&#39;] = createdataframe(TEST_DIR)<br>print(test)</pre><p>Similarly, it creates the testing DataFrame.</p><h4>Data Preprocessing</h4><pre>from tqdm.notebook import tqdm</pre><p>This line imports the tqdm module for displaying a progress bar.</p><pre>def extract_features(images):<br>    features = []<br>    for image in tqdm(images):<br>        img = load_img(image, grayscale=True)<br>        img = np.array(img)<br>        features.append(img)<br>    features = np.array(features)<br>    features = features.reshape(len(features), 48, 48, 1)<br>    return features</pre><p>This function reads and processes images using the tqdm progress bar.</p><p><strong>Parameters:<br>images: </strong>A list containing the file paths of images for which features need to be extracted.</p><p><strong>Variables:<br>features:</strong> An empty list to store the extracted features.</p><p><strong>Iteration:<br></strong>The function iterates over each image path in the given list of images.</p><p><strong>Feature Extraction: <br></strong>For each image, it loads the image using load_img from Keras with grayscale=True.<br>Converts the image to a NumPy array.<br>Appends the image to the features list.</p><p><strong>Conversion and Reshaping: <br></strong>Converts the list of features to a NumPy array.<br>Reshapes the array to match the required input shape for the model (48x48x1).</p><p><strong>Return:<br></strong>The function returns the extracted features in the form of a NumPy array.</p><h4>Extraction:</h4><pre>train_features = extract_features(train[&#39;image&#39;])<br>test_features = extract_features(test[&#39;image&#39;])</pre><p><strong>Feature Extraction Function:<br></strong>The extract_features function is called for both the training and testing datasets, passing the lists of image file paths (train[‘image’] and test[‘image’]).</p><p><strong>Extracting Features:<br></strong>The function iterates over each image path.<br>For each image, it loads the image in grayscale using Keras’s load_img.<br>Converts the image to a NumPy array.<br>Appends the image to the features list.</p><p><strong>Conversion and Reshaping:<br></strong>The list of features is converted into a NumPy array.<br>The array is reshaped to match the required input shape for the model (48x48x1).</p><p><strong>Result:<br></strong>train_features and test_features now contain the extracted features from the training and testing datasets, respectively.</p><h4>Normalization:</h4><pre>x_train = train_features / 255.0<br>x_test = test_features / 255.0</pre><p>Each pixel value in the images (ranging from 0 to 255) is divided by 255.0.<br>This operation scales the pixel values to the range of 0 to 1.</p><p><strong>Importance of Normalization:<br></strong>Normalization is a common preprocessing step in neural network training.<br>It ensures that the input features are on a similar scale, preventing certain features from dominating the learning process due to their larger magnitude.</p><p><strong>Result:<br></strong>x_train and x_test now contain the normalized feature values for the training and testing datasets, respectively.</p><pre>from sklearn.preprocessing import LabelEncoder<br>le = LabelEncoder()<br>le.fit(train[&#39;label&#39;])<br>y_train = le.transform(train[&#39;label&#39;])<br>y_test = le.transform(test[&#39;label&#39;])<br>y_train = to_categorical(y_train, num_classes=7)<br>y_test = to_categorical(y_test, num_classes=7)</pre><p>This part encodes the labels using LabelEncoder and converts them into categorical format.</p><h4>Building the Neural Network Model</h4><pre># sequential model<br>model = Sequential()<br><br># convolutional layers<br>model.add(Conv2D(128, kernel_size=(3,3), activation=&#39;relu&#39;, input_shape=(48,48,1)))<br>model.add(MaxPooling2D(pool_size=(2,2)))<br>model.add(Dropout(0.4))<br><br>model.add(Conv2D(256, kernel_size=(3,3), activation=&#39;relu&#39;))<br>model.add(MaxPooling2D(pool_size=(2,2)))<br>model.add(Dropout(0.4))<br><br>model.add(Conv2D(512, kernel_size=(3,3), activation=&#39;relu&#39;))<br>model.add(MaxPooling2D(pool_size=(2,2)))<br>model.add(Dropout(0.4))<br><br>model.add(Conv2D(512, kernel_size=(3,3), activation=&#39;relu&#39;))<br>model.add(MaxPooling2D(pool_size=(2,2)))<br>model.add(Dropout(0.4))<br><br># flattening<br>model.add(Flatten())<br><br># fully connected layers<br>model.add(Dense(512, activation=&#39;relu&#39;))<br>model.add(Dropout(0.4))<br>model.add(Dense(256, activation=&#39;relu&#39;))<br>model.add(Dropout(0.3))<br><br># output layer<br>model.add(Dense(7, activation=&#39;softmax&#39;))<br><br># model compilation<br>model.compile(optimizer = &#39;adam&#39;, loss = &#39;categorical_crossentropy&#39;, metrics = &#39;accuracy&#39; )</pre><p><strong>Sequential Model:</strong><br>The Sequential class is used to create a linear stack of layers for building the model layer by layer.</p><p><strong>Convolutional Layers:</strong></p><ul><li>Four sets of convolutional layers are added.</li><li>Each set consists of a Conv2D layer followed by a MaxPooling2D layer and a Dropout layer.</li><li>The number of filters (feature detectors) increases in each set, capturing hierarchical features.</li></ul><p><strong>Flattening and Fully Connected Layers:</strong></p><ul><li>The Flatten layer is added to transform the 2D array into a vector.</li><li>Two fully connected (Dense) layers follow, each with ReLU activation.</li><li>Dropout layers are added to prevent overfitting.</li></ul><p><strong>Output Layer:</strong></p><ul><li>The final layer is a Dense layer with 7 neurons (equal to the number of classes) and a softmax activation function, suitable for multi-class classification.</li></ul><p><strong>Compilation:</strong></p><ul><li>The model is compiled with the Adam optimizer, categorical crossentropy loss (appropriate for multi-class classification), and accuracy as the evaluation metric.</li></ul><p>This code defines a convolutional neural network (CNN) using the Keras Sequential API. It includes convolutional layers, max-pooling layers, dropout layers, and fully connected layers.</p><h4>Training the Model</h4><pre>model.fit(x=x_train, y=y_train, batch_size=128, epochs=100, validation_data=(x_test, y_test))</pre><p><strong>x_train: </strong>The input data for training, which consists of the features (images) of the training set.</p><p><strong>y_train:</strong> The target (label) data for training, which contains the corresponding labels for the training set.</p><p><strong>batch_size:</strong> The number of samples used in each iteration during training. In this case, it’s set to 128. This parameter controls the number of training samples utilized in one iteration.</p><p><strong>epochs:</strong> The number of times the entire training dataset is passed forward and backward through the neural network. Here, it’s set to 100, meaning the model will see the entire dataset 100 times during training.</p><p><strong>validation_data: </strong>A tuple containing the validation data, which is used to evaluate the model after each epoch. It consists of validation features (x_test) and validation labels (y_test).</p><p>This function will train the model on the provided training data (x_train and y_train) and validate it on the specified validation data after each epoch. The training process aims to optimize the model’s parameters to minimize the defined loss function, making predictions more accurate. The validation data helps assess the model’s generalization performance on unseen data.</p><p><strong><em>This took me around 5 hours to train the model and the accuracy was 62%.</em></strong></p><h4>Saving the Model</h4><pre>model_json = model.to_json()<br>with open(&quot;emotiondetector.json&quot;, &#39;w&#39;) as json_file:<br>    json_file.write(model_json)<br>model.save(&quot;emotiondetector.h5&quot;)</pre><p>It saves the trained model architecture and weights to files.</p><h4>Loading the Model and Making Predictions</h4><pre>from keras.models import model_from_json<br>json_file = open(&quot;emotiondetector.json&quot;, &quot;r&quot;)<br>model_json = json_file.read()<br>json_file.close()<br>model = model_from_json(model_json)<br>model.load_weights(&quot;emotiondetector.h5&quot;)</pre><p><strong>open(“emotiondetector.json”, “r”): </strong>This line opens the JSON file containing the model architecture in read mode (“r”). The file is assumed to be named “emotiondetector.json.”</p><p><strong>model_json = json_file.read(): </strong>Reads the content of the JSON file and stores it in the variable model_json.</p><p><strong>json_file.close():</strong> Closes the opened JSON file.</p><p><strong>model_from_json(model_json):</strong> This function is part of Keras and creates a model from the architecture described in the loaded JSON string (model_json). It constructs the model without any weights.</p><p><strong>model.load_weights(“emotiondetector.h5”): </strong>Loads the pre-trained weights into the model from the H5 file named “emotiondetector.h5.” These weights were likely saved during the training phase.</p><h4>Making Predictions on Test Images</h4><pre>label = [&#39;angry&#39;, &#39;disgust&#39;, &#39;fear&#39;, &#39;happy&#39;, &#39;neutral&#39;, &#39;sad&#39;, &#39;surprise&#39;]<br>def ef(image):<br>    img = load_img(image, grayscale=True)<br>    feature = np.array(img)<br>    feature = feature.reshape(1, 48, 48, 1)<br>    return feature / 255.0</pre><p><strong>label: </strong>A list containing emotion labels corresponding to the model’s output classes.</p><p><strong>def ef(image):</strong> This line defines a function named ef that takes an image file path as an argument.</p><p><strong>img = load_img(image, grayscale=True): </strong>Loads the image using Keras’s load_img function with the grayscale=True argument, indicating that the image should be loaded in grayscale. The resulting image (img) is a Keras image object.</p><p><strong>feature = np.array(img):</strong> Converts the image object to a NumPy array, making it suitable for further processing.</p><p><strong>feature = feature.reshape(1, 48, 48, 1):</strong> Reshapes the array to match the expected input shape of the neural network model. The shape (1, 48, 48, 1) suggests a single image with dimensions 48x48 and one channel (grayscale).</p><p><strong>return feature / 255.0: </strong>Normalizes the pixel values of the image to be in the range [0, 1] by dividing each pixel value by 255.0. Neural networks often perform better when input data is normalized.</p><p>This function takes an image file path, processes it to meet the input requirements of the model, and returns the normalized feature that can be fed into the model for prediction.</p><pre>image = &#39;images/train/sad/42.jpg&#39;<br>print(&quot;original image is of sad&quot;)<br>img = ef(image)<br>pred = model.predict(img)<br>pred_label = label[pred.argmax()]<br>print(&quot;model prediction is &quot;, pred_label)</pre><p>It makes predictions on sample images and prints the predicted labels.</p><h4>Visualizing Predictions</h4><pre>import matplotlib.pyplot as plt<br>%matplotlib inline</pre><p><strong>import matplotlib.pyplot as plt:</strong> Imports the matplotlib library’s pyplot module and aliases it as plt. pyplot is a collection of functions that make matplotlib work like MATLAB.</p><p><strong>%matplotlib inline:</strong> This is a Jupyter magic command that allows the visualizations generated by matplotlib to be displayed directly in the Jupyter Notebook, rather than in a separate window.</p><pre>image = &#39;images/train/sad/42.jpg&#39;<br>print(&quot;original image is of sad&quot;)<br>img = ef(image)<br>pred = model.predict(img)<br>pred_label = label[pred.argmax()]<br>print(&quot;model prediction is &quot;, pred_label)<br>plt.imshow(img.reshape(48, 48), cmap=&#39;gray&#39;)</pre><p>In this segment of the code, we select an image from the training set labeled as “sad” and preprocess it using the ef function. The trained model is then employed to predict the emotion associated with the image, and the result is displayed. The model&#39;s prediction is printed, indicating the emotion it believes the image expresses. Additionally, the original image is visualized in grayscale using matplotlib. This process provides a practical illustration of the model&#39;s effectiveness in recognizing and categorizing emotions in facial expressions.</p><p><strong>Output of the above block of code</strong></p><pre>original image is of sad<br>1/1 [==============================] - 0s 55ms/step<br>model prediction is  sad<br>&lt;matplotlib.image.AxesImage at 0x16abfe14e80&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*WSQLxFnIjVgVztKFPUq0VA.png" /></figure><p>Here the model recognizes the emotion displayed accurately as per the dataset 😁. Lets try with another image.</p><pre>image = &#39;images/train/fear/2.jpg&#39;<br>print(&quot;original image is of fear&quot;)<br>img = ef(image)<br>pred = model.predict(img)<br>pred_label = label[pred.argmax()]<br>print(&quot;model prediction is &quot;,pred_label)<br>plt.imshow(img.reshape(48,48),cmap=&#39;gray&#39;)</pre><p><strong>Output</strong></p><pre>original image is of fear<br>1/1 [==============================] - 0s 31ms/step<br>model prediction is  sad<br>&lt;matplotlib.image.AxesImage at 0x16abfe99060&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*xKhPDD0wAlu6wdBmQqphfw.png" /></figure><p>Here the model recognizes the wrong emotion so it is incorrect 😖.</p><p>This is how you can test how well the model is working.</p><h3>Making the model real time using OpenCV</h3><pre>import cv2<br>from keras.models import model_from_json<br>import numpy as np<br><br># Load the pre-trained model architecture from JSON file<br>json_file = open(&quot;facialemotionmodel.json&quot;, &quot;r&quot;)<br>model_json = json_file.read()<br>json_file.close()<br>model = model_from_json(model_json)<br><br># Load the pre-trained model weights<br>model.load_weights(&quot;facialemotionmodel.h5&quot;)<br><br># Load the Haar cascade classifier for face detection<br>haar_file = cv2.data.haarcascades + &#39;haarcascade_frontalface_default.xml&#39;<br>face_cascade = cv2.CascadeClassifier(haar_file)<br><br># Define a function to extract features from an image<br>def extract_features(image):<br>    feature = np.array(image)<br>    feature = feature.reshape(1, 48, 48, 1)<br>    return feature / 255.0<br><br># Open the webcam (camera)<br>webcam = cv2.VideoCapture(0)<br><br># Define labels for emotion classes<br>labels = {0: &#39;angry&#39;, 1: &#39;disgust&#39;, 2: &#39;fear&#39;, 3: &#39;happy&#39;, 4: &#39;neutral&#39;, 5: &#39;sad&#39;, 6: &#39;surprise&#39;}<br><br>while True:<br>    # Read a frame from the webcam<br>    i, im = webcam.read()<br><br>    # Convert the frame to grayscale<br>    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)<br><br>    # Detect faces in the grayscale frame<br>    faces = face_cascade.detectMultiScale(im, 1.3, 5)<br><br>    try:<br>        # For each detected face, perform facial emotion recognition<br>        for (p, q, r, s) in faces:<br>            # Extract the region of interest (ROI) which contains the face<br>            image = gray[q:q + s, p:p + r]<br><br>            # Draw a rectangle around the detected face<br>            cv2.rectangle(im, (p, q), (p + r, q + s), (255, 0, 0), 2)<br><br>            # Resize the face image to the required input size (48x48)<br>            image = cv2.resize(image, (48, 48))<br><br>            # Extract features from the resized face image<br>            img = extract_features(image)<br><br>            # Make a prediction using the trained model<br>            pred = model.predict(img)<br><br>            # Get the predicted label for emotion<br>            prediction_label = labels[pred.argmax()]<br><br>            # Display the predicted emotion label near the detected face<br>            cv2.putText(im, f&#39;Emotion: {prediction_label}&#39;, (p - 10, q - 10),<br>                        cv2.FONT_HERSHEY_COMPLEX_SMALL, 2, (0, 0, 255))<br><br>        # Display the frame with annotations in real-time<br>        cv2.imshow(&quot;Real-time Facial Emotion Recognition&quot;, im)<br><br>        # Break the loop if the &#39;Esc&#39; key is pressed<br>        if cv2.waitKey(1) == 27:<br>            break<br><br>    except cv2.error:<br>        pass<br><br># Release the webcam and close all OpenCV windows<br>webcam.release()<br>cv2.destroyAllWindows()</pre><ul><li>The code uses OpenCV to capture frames from the webcam and detect faces in real-time.</li><li>For each detected face, the script performs facial emotion recognition using the pre-trained model.</li><li>The recognized emotion label is displayed near each detected face.</li><li>The loop continues until the ‘Esc’ key is pressed, at which point the webcam is released, and OpenCV windows are closed.</li></ul><p>This was a project that I replicated with the intent of learning how to build neural networks.<br>Credits &gt; <a href="https://www.youtube.com/watch?v=aoCIoumbWQY">https://www.youtube.com/watch?v=aoCIoumbWQY</a><br>Entire Code on GitHub: <a href="https://github.com/kumarvivek9088/Face_Emotion_Recognition_Machine_Learning/blob/main/trainmodel.ipynb">https://github.com/kumarvivek9088/Face_Emotion_Recognition_Machine_Learning/blob/main/trainmodel.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30a331d39cf1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Neural Networks from scratch]]></title>
            <link>https://fuyofulo.medium.com/understanding-neural-networks-from-scratch-175b1b7ad952?source=rss-8b7146205b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/175b1b7ad952</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[visual-recognition]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[fuyofulo]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 16:03:31 GMT</pubDate>
            <atom:updated>2026-02-28T12:32:17.095Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Ever wondered how the phone’s facial recognition system works? or how Facebook automatically tags your friends in photos? or how medical systems identify potential health issues just from X-rays and scans?</em></p><p>In this series of articles, we will develop an understanding of the mechanism that works behind all these visual recognition processes from the very scratch.</p><p>In order to comprehend the intricate workings of the visual recognition, its essential to begin by understanding the foundation on which the actual mechanism is built upon.</p><h3>Neural Networks</h3><p>Neural Networks are AI algorithms designed to mimic the way a human brain works. Their primary purpose is to enable computer programs to recognize patterns and draw conclusions from data. But how exactly do these algorithms replicate the working of a human brain?</p><p>Here is an image of how a neural network looks like. We will come back to this image later and you will have an understanding of what’s going on here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8WRaImeOsnjs14w8.jpg" /></figure><p>Lets build a simple neural network of our own to understand how it functions.</p><h3>Building our own Neural Network</h3><p>Suppose we have 3 shapes (circle, square, triangle) and a box with 3 sections. Each section can contain 1 shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ad3GTqQ3T2BY8qO31TrOkA.png" /></figure><p>If we consider the total possibilities, we get 27 possible combinations. Lets number each combination for unique identification. Here they are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hgtzzY6RvwQpCtHZezK1zQ.png" /><figcaption><strong>All possible combinations</strong></figcaption></figure><p>Now we will build a simple algorithm that identifies the number of the box when we just provide it with the box image.</p><p><em>Since we are trying to learn how the neural network works, we are assuming that the computer knows a square is a square, a circle is a circle and a triangle is a triangle.</em></p><p>Suppose this is the input we provide to our neural network. We want our algorithm to provide the number of this box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3X6uvVwBJ7MGXon_N4zsQ.png" /></figure><p><strong>Step 1: Identifying the shape in the first section of the box</strong></p><p>Here there are 3 possibilities, lets label it as <strong><em>layer 1.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTu8j73nxP4yF3w0sfZZvg.png" /><figcaption><strong><em>Step 1</em></strong></figcaption></figure><p>In our case, the first possibility is true so we proceed with that one. Hence, the line pointing it is thicker than others.</p><p><strong>Step 2: Identifying the shape in the second section of the box</strong></p><p>Now that we know the shape in the first section, lets proceed further with the possibilities of shape in second section labelling it as <strong><em>layer 2.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-LM7c0TFA_1Pn9soZc6mQ.png" /><figcaption><strong>Step 2</strong></figcaption></figure><p><strong>Step 3: Identifying the shape in the third section of the box</strong></p><p>Repeating the same process again and building a <strong><em>layer 3.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Al8AKElytBi0JWI6HFU9RA.png" /><figcaption><strong>Step 3</strong></figcaption></figure><p>Now we have identified all the 3 shapes present in the box, we now need to check the number of it by using a 4th layer.</p><p><strong>Step 4: Identify the number of the box</strong></p><p>Layer 4 contains all the numbers of the boxes and is the final step towards identifying the box and sends it as the final output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ts11S4SLTJS7vz8FXjFXBQ.png" /><figcaption><strong>Step 4</strong></figcaption></figure><p>Now lets zoom out a little bit and understand the system more clearly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c0Uii5DwAgOm1kCiL7fNuA.png" /><figcaption><strong>all the steps at a glance</strong></figcaption></figure><p><strong>Possibilities in each layer</strong></p><p>We just looked at the path that our input follows to reach the expected output. Lets calculate the possibilities in each layer. <br><strong>Layer 1:</strong> 3 possibilities<br><strong>Layer 2:</strong> 9 possibilities<br><strong>Layer 3:</strong> 27 possibilities<br><strong>Layer 4:</strong> 27 possibilities</p><p><strong>Learning technical terms from the neural network we built</strong></p><p>We have been using our own terminology, lets now look at the technical terms that are actually used in the field.</p><p>The possibilities we determined are called <strong>nodes</strong>.<br>All the layers we build between the input layer and the output layer would be collectively known as <strong>hidden layers.<br></strong>The thickness given to the arrow indicating the strong possibility to the node in the next layer is known as <strong>weights.</strong></p><p>This is how our neural network can be represented in a technical manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*drvvO2mC1QJzd9YVFTk8Wg.png" /></figure><p>Each node (circle) in layer 3 represents one of the 27 combinations we saw earlier. Now go to the first image of this article and it wouldn’t scare you anymore.<br>So we built our very own neural network from scratch but this one is literally the most simple neural network on earth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=175b1b7ad952" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging the power of brain using Brain Computer Interfaces]]></title>
            <link>https://fuyofulo.medium.com/leveraging-the-power-of-brain-using-brain-computer-interfaces-9fafaaaabca?source=rss-8b7146205b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fafaaaabca</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[brain-computer-interface]]></category>
            <category><![CDATA[brain]]></category>
            <category><![CDATA[neuroscience]]></category>
            <dc:creator><![CDATA[fuyofulo]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 01:14:55 GMT</pubDate>
            <atom:updated>2023-03-31T12:56:04.214Z</atom:updated>
            <content:encoded><![CDATA[<p>Throughout history, humans have demonstrated a persistent desire for power and control, which has manifested in various ways. However, at the core of this desire for power lies the fundamental need for survival and well-being.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XI-EI3NU42qr_Pg7.jpg" /></figure><p>And this desire had led to new inventions and technologies for the betterment of society (or to control it for selfish purposes). Technologies, as we can see, are everywhere from as small as the zip of our pants to as large as the infrastructure of cities and nations. From the buildings we live and work in, the roads and bridges we travel on, the power plants that provide electricity, the satellites that enable global communication, and the machines that manufacture goods at scale, technologies play a crucial role in shaping our world. They have transformed industries, created new opportunities for innovation and growth, and changed the way we live, work, and interact with one another. As technologies continue to advance, they will undoubtedly continue to shape the course of human progress and evolution 🧬.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AinTOi9yguUKwaic.jpg" /></figure><p>While there happens to be a chance that the technologies we read about in fairy tales like teleportation, telepathy, and advanced space exploration might have very well existed in the past, meaning that we are probably living in a post-apocalyptic world 🤯, the possibilities we can imagine with technologies are slowly coming into reality.</p><p><em>But wait a min, how is all this happening? Are we receiving some external sources of knowledge to make all this possible?</em></p><p>That doesn’t seem to be the case and if we take a closer look at things, it’s us processing all the information available to us that leads to one thing or the other. <br>And if we go deeper into what part of our body does all this,</p><h4><em>it’s just a small squishy blob of jelly with some superhero and never takes a break. The boss of the body who’s always barking orders and trying to keep everything running smoothly, but sometimes it gets a little too excited and starts firing off neurons like they’re fireworks </em>🎆<em> on the 4th of July. Like a computer </em>🖥️<em>, but with a personality and a sense of humor — sometimes it remembers everything perfectly, and other times it forgets why it came into a room in the first place </em>🤡<em>.</em></h4><p>And if you still haven’t figured out what we are talking about here, you need some serious training to get yours up and running 💀.</p><h3>THE BRAIN 🧠</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_oAgREHChIr7XfJu.jpg" /><figcaption>looking sharp today</figcaption></figure><p>The brain can be seen as a highly sophisticated organic computer that processes information, makes decisions, and controls the functions of the body. It operates through the transmission of electrical and chemical signals, and it can adapt and learn from experiences, much like a machine that can be programmed to learn and improve over time.</p><p>On the other hand, the brain is vastly different from any man-made machine in that it is capable of subjective experiences, emotions, and consciousness. Unlike a machine that operates according to pre-determined rules and algorithms, the brain has the capacity for creativity, free will, and self-awareness.</p><p><em>And the best part is, we don’t even know how much we don’t know about it.</em></p><h4>Lets take <em>STIMULATION</em></h4><p>Stimulating our very own brain by providing it with a substitute input. <br>The principle behind this is a no-brainer, we learn how the nervous system works and create a chart of input and output. Then we provide the input ourselves through stimulation and get the desired output. <br>This means we can potentially alter our dreams, force ourselves into habits, create memories that we never even lived in the first place, etc.</p><p>The idea behind using brain stimulation to alter dreams, habits, or memories is to first understand the neural circuits and patterns of brain activity associated with these processes. Once we have a good understanding of how the brain processes information during these processes, we can then use brain stimulation to enhance or suppress the relevant neural circuits and thereby influence these processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*u2ZJZ3OvpH4jJVW_.jpg" /></figure><p>For example, let’s say that we want to enhance our memory recall. We would first study the neural circuits and patterns of brain activity that are associated with memory recall. We would then use brain stimulation techniques to enhance the activity of those regions or circuits in order to improve our memory recall.</p><p>Similarly, if we wanted to suppress a bad habit such as smoking, we would first identify the neural circuits associated with that habit. We would then use brain stimulation techniques to suppress the activity of those circuits and thereby reduce the urge to smoke.</p><p>Of course, using brain stimulation in this way is still a relatively new and experimental field, and more research is needed to fully understand its potential and limitations. But the possibilities of using brain stimulation to enhance human cognitive abilities and improve our lives are certainly exciting.</p><p><em>But the other way around is easier to achieve. By that, I mean controlling things directly from our brain with the power of thoughts, and to be more specific, action potentials.</em></p><p><em>Well, what technology could we use to make these desires come true? </em>🤔</p><h3>Introducing Brain-Computer Interfaces (or BCIs)</h3><p>A Brain-Computer Interface (BCI) is a special device that helps you control a computer or other machine using your brain waves. Your brain is always active and produces electrical signals, which can be detected by special sensors called electrodes. BCIs use these electrodes to read your brain signals and translate them into commands that the computer can understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/0*Rr9x5wn5jYSRyfR-.png" /></figure><p>For example, if you want to move a cursor on a computer screen, you can wear a BCI headset that reads your brain signals and uses them to move the cursor. You can also use a BCI to control things like a wheelchair, a robot, or a prosthetic arm.</p><p><em>BCIs can be mainly categorized into 2 types:</em></p><h4>1) Invasive BCIs</h4><p>As the name says, we are invading 👽 the brain by directly placing electrodes on its surface of it to read and interpret its electrical signals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Mw62K4i4dmhpMs3w.jpeg" /></figure><p>These electrodes are typically implanted using surgery, which means that the procedure requires opening the skull. Once the electrodes are in place, they can be used to read the electrical signals produced by the brain and translate them into commands that can be used to control a computer, a robotic device, or even a prosthetic limb. This means that people who have lost the ability to move or communicate due to conditions such as paralysis or ALS can potentially use invasive BCIs to regain some level of control over their lives.</p><p><em>Note that invasive BCIs have high risk as the process is extremely sensitive. However, for people who are severely disabled and have no other options, invasive BCIs can offer a lifeline and a way to regain some level of independence and control over their lives.</em></p><h4>2) Non-Invasive BCIs</h4><p>Non-invasive Brain-Computer Interfaces (BCIs) are a type of BCI that does not require any surgery or implants to access the brain. Instead, non-invasive BCIs rely on external sensors that detect and measure brain activity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*tIx5kezWGX1eSZYW.png" /></figure><p>These sensors are placed on the surface of the scalp or the forehead, and they record brain activity patterns that are associated with specific thoughts or actions. Then, the BCI system analyzes these patterns and translates them into computer commands or control signals that can be used to operate a computer, a wheelchair, a robotic arm, or other devices.<br>Non-invasive BCIs are generally considered safer and easier to use than invasive BCIs, as they do not require any surgery or risk of infection.</p><p><em>Non-invasive BCIs have a broader range of applications and are used in gaming, virtual reality, and even for mental health therapy but it still have some limitations compared to Invasive BCIs such as lower accuracy and sensitivity compared to invasive BCIs, and they may be affected by external factors such as movement, noise, or other distractions.</em></p><h4>Some folks working in the field of BCIs:</h4><p><strong>Neuralink: </strong>A neurotechnology company co-founded by Elon Musk that aims to develop a brain-machine interface (BMI) to help humans keep up with advanced artificial intelligence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yuRS4Yzuf32XpXZ5.png" /></figure><p>Their BMI technology involves implanting electrodes in the brain to enable bidirectional communication between humans and computers.</p><p><strong>Emotiv:</strong> Emotiv is a company that produces electroencephalography (EEG) headsets for consumer use. Their headsets use non-invasive sensors to measure brain activity and allow users to control devices with their thoughts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mxm9QGcTFxW3bF7Z.png" /></figure><p>Emotiv’s technology has been used in various applications, including gaming, virtual reality, and healthcare.</p><p><strong>Neurable:</strong> Neurable is a neurotechnology company that develops brain-computer interfaces (BCIs) for various applications, including gaming, virtual reality, and healthcare.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zsxe0Myp6cMjN44K.jpg" /></figure><p>Its main product, Neurable X, is a platform that allows users to control virtual and augmented reality experiences using their brain activity. The company has received funding from various sources, including the National Science Foundation and venture capital firms.</p><h4>Imagining the future with BCIs</h4><p>The brain, being a highly sophisticated organic computer with subjective experiences, emotions, and consciousness, has tremendous potential for exploration and development through BCIs.</p><p>BCIs may sound like something straight out of a science fiction movie, but they’re actually pretty limited in what they can do as of today and in the near future 😑. You won’t be able to use your mind to control a giant robot or shoot lasers out of your eyes anytime soon. Sorry to burst your bubble. BCIs are more like friendly but forgetful personal assistant, always there to help, but with occasional glitches and miscommunications. Think of them like a loyal but slightly scatterbrained dog — adorable, but not exactly ready to take on the world.</p><p>As promising as Brain-Computer Interfaces (BCIs) may seem, they also carry a dark side. With BCIs, there’s the possibility of accessing people’s private thoughts and emotions, which raises serious ethical concerns about privacy and autonomy. What if someone could hack into your brain and manipulate your decisions without your knowledge or consent?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*LA34A8WZvS_D7WLi.png" /></figure><p>The use of BCIs in the military or law enforcement could potentially lead to abuses of power and human rights violations. Furthermore, the development of BCIs could exacerbate the already existing social and economic inequalities. Imagine a world where the wealthy can afford brain implants that enhance their cognitive abilities, while the poor are left behind, unable to compete in the job market. The implications of BCIs are both exciting and terrifying, and we must proceed with caution as we navigate this uncharted territory.</p><h4>Conclusion</h4><p>The human desire for power and control has led to the invention and development of various technologies, which have transformed industries and shaped the course of human progress and evolution.</p><p>The brain, a highly sophisticated organic computer, is capable of processing information, making decisions, and controlling the functions of the body. Brain stimulation and brain-computer interfaces are exciting new technologies that have the potential to enhance human cognitive abilities and improve our lives. While more research is needed to fully understand their potential and limitations, the possibilities of these technologies are endless. As technology continues to advance, it will undoubtedly continue to shape the course of human progress and evolution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fafaaaabca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>