<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Josiah Adesola - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Josiah Adesola - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 22:23:59 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/josiahadesola/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use Your Raspberry Pi Headlessly with VS Code and SSH (No Monitor Needed) ]]>
                </title>
                <description>
                    <![CDATA[ The Raspberry Pi is a portable computer with an onboard processor that fits comfortably in the palm of your hand. Compared with general purpose computers, it’s an affordable option developed by the Raspberry Pi Foundation. The Raspberry Pi Model B wa... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-your-raspberry-pi-headlessly-with-vs-code-and-ssh/</link>
                <guid isPermaLink="false">6835cf3101fd0876c3c66de0</guid>
                
                    <category>
                        <![CDATA[ Raspberry Pi ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ssh ]]>
                    </category>
                
                    <category>
                        <![CDATA[ vscode extensions ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Josiah Adesola ]]>
                </dc:creator>
                <pubDate>Tue, 27 May 2025 14:41:53 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1748452192906/594a76a0-be8f-478b-a9ae-e3ba55850c65.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The Raspberry Pi is a portable computer with an onboard processor that fits comfortably in the palm of your hand. Compared with general purpose computers, it’s an affordable option developed by the <a target="_blank" href="https://www.raspberrypi.org/">Raspberry Pi Foundation</a>.</p>
<p>The Raspberry Pi Model B was introduced in 2012 as the first sellable unit, and the company has since released many more models. There are even low-cost models like the Raspberry Pi Zero Series, which is quite small and tailored to embedded systems applications. All the models operate on an operating system called the Raspberry Pi OS, a Linux flavor niched for Raspberry PI Computers.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747912686077/498ff16a-c6a0-4774-b6e4-a0d573afd4f8.jpeg" alt="A Raspberry Pi Model 4B single-board computer with visible ports, components." class="image--center mx-auto" width="768" height="1020" loading="lazy"></p>
<p>In this tutorial, we’ll be using the Raspberry Pi 4 Model for a headless setup through a SSH connection using Visual Studio Code (VS Code). The Raspberry Pi 4 Model has a Quad-core ARM Cortex-A72 (64-bit) SoC at 1.5GHz, up to 8GB RAM options, video inputs, Ethernet shield, USB ports, MicroSD card slot for storage, USB-C power input and 40 General Purpose Inputs and Outputs Pins (GPIO). Impressive, right?</p>
<p>You’ll be able to use the Raspberry Pi as a personal computer, for home automation and IoT projects, robotics projects, network applications, educational tools, and Artificial Intelligence projects.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-understanding-the-headless-setup">Understanding the Headless Setup</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-preparing-the-microsd-card">Preparing the MicroSD Card</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-boot-the-raspberry-pi">How to Boot the Raspberry Pi</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-the-led-of-the-raspberry-pi-during-setup">Understanding the LED of the Raspberry Pi During Setup</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-establish-an-ssh-connection">How to Establish an SSH Connection</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-set-up-visual-studio-code-for-remote-development">How to Set Up Visual Studio Code for Remote Development</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-write-and-run-the-code-remotely">How to Write and Run the Code Remotely</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-understanding-the-headless-setup">Understanding the Headless Setup</h2>
<p>Many Raspberry Pi computers are sold with additional peripherals, including a keyboard, mouse, and monitor, that are essential for the Raspberry Pi's setup. A headless setup is the process of configuring the Raspberry Pi or preparing it for use without needing these peripherals. This entails operating the Raspberry Pi through a network protocol like SSH (Secure Shell) or VNC (Virtual Network Computing).</p>
<p>This is really helpful when you don’t need peripherals, as it lets you use your personal computer to connect to the Raspberry Pi without needing to purchase specialized peripherals. It’s also excellent for remote access. This headless setup is also essential for remote monitoring systems, such as surveillance systems with remote camera access, and IoT systems.</p>
<p><a target="_blank" href="https://www.raspberrypi.com/products/raspberry-pi-400/"><img src="https://assets.raspberrypi.com/static/neat-lg@2x-38697d13d9952791ca96da4891de9a12.jpg" alt="A Raspberry Pi 400 in use on a desk, with a mouse and monitor connected" width="2600" height="1800" loading="lazy"></a></p>
<p>Remote development lets you write code and modify your Raspberry Pi and other devices connected to the GPIO pins through a headless configuration via SSH.</p>
<p>SSH guarantees a secure connection for transferring and modifying files, as well as transferring and debugging commands from one computer (your personal computer) to another computer (the Raspberry Pi). It restricts unauthorized access from any other system that aims to intercept the communication channel.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Here’s what you’ll need to follow along with this tutorial:</p>
<h3 id="heading-hardware-requirements">Hardware Requirements</h3>
<ol>
<li><p>Raspberry Pi 4 or 5</p>
</li>
<li><p>MicroSD Card (8GB or higher recommended)</p>
</li>
<li><p>Flash Drive with SD Card Slot or a MicroSD Card Adapter</p>
</li>
<li><p>Power Supply (5V 2A/3A)</p>
</li>
<li><p>Network Connection (Wi-Fi, Pi, and laptop must be on the same network)</p>
</li>
<li><p>Personal Computer (Windows, macOS, Linux)</p>
</li>
</ol>
<h3 id="heading-software-requirements">Software Requirements</h3>
<ol>
<li><p>Raspberry Pi Operating System (Raspberry Pi OS)</p>
</li>
<li><p>Visual Studio Code</p>
</li>
<li><p>Remote SSH Extension in VS Code</p>
</li>
</ol>
<h2 id="heading-preparing-the-microsd-card">Preparing the MicroSD Card</h2>
<p>The Raspberry Pi requires a MicroSD Card that serves as the storage of your the Raspberry Pi OS using Raspberry Pi Imager. The operating system of the Raspberry Pi provides a graphical interface to interact with the Raspberry Pi, store files and datasets, and write commands to get your Raspberry Pi working.</p>
<p>But the Raspberry Pi needs an empty MicroSD Card to install the Raspberry Pi OS in the MicroSD Card. Here are some step by step instructions that’ll show you how to get your MicroSD Card setup before inserting it back into the Raspberry Pi for SSH Connection.</p>
<h3 id="heading-downloading-and-flashing-raspberry-pi-os">Downloading and flashing Raspberry Pi OS</h3>
<h4 id="heading-insert-your-microsd-card-into-a-flash-drive-with-a-sd-card-slot">Insert your MicroSD Card into a flash drive with a SD Card slot</h4>
<p>Aside from using a flash drive with an SD Card slot (so as to get the memory card connected to the computer), you can also use a SD Card adapter. Make sure it’s inserted into your computer where you have the Raspberry PI Imager downloaded to flash – that is, transfer the OS into the SD Card.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747921369222/7deebdff-d0bc-4f08-9aab-07c562a712bd.jpeg" alt="My flash drive with an SD card slot" class="image--center mx-auto" width="963" height="1280" loading="lazy"></p>
<h4 id="heading-download-the-raspberry-pi-imagerhttpswwwraspberrypicomsoftware-based-on-your-pcs-operating-system">Download the <a target="_blank" href="https://www.raspberrypi.com/software/">Raspberry Pi Imager</a> based on your PC’s operating system</h4>
<p>This involves clicking the link and selecting your operating system (either MacOS, Windows or Linux operating system). The Raspberry Pi OS comes in these variants for different OSes</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747922079380/d1aa21cb-3166-4924-8f98-e2f16816fec6.png" alt="Screenshot of a webpage from raspberrypi.com showing instructions for installing Raspberry Pi OS using Raspberry Pi Imager. It includes download links for Windows, macOS, and Ubuntu. There is a command for installing on Raspberry Pi OS and an image of the Raspberry Pi Imager interface." class="image--center mx-auto" width="872" height="947" loading="lazy"></p>
<h4 id="heading-next-install-and-open-the-raspberry-pi-imager">Next, install and open the Raspberry Pi imager</h4>
<p>Click the Raspberry Pi Imager download, follow all the instructions during the installation process. Once this screen pops up, you’re good to go!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747922173921/02e58463-0634-41d6-bc85-0a1a3a199996.png" alt="The image shows the Raspberry Pi Imager v1.8.5 interface. It has options to &quot;Choose Device,&quot; &quot;Choose OS,&quot; and &quot;Choose Storage.&quot; There is also a faded &quot;Next&quot; button at the bottom. The background is a shade of raspberry red." class="image--center mx-auto" width="1348" height="930" loading="lazy"></p>
<h4 id="heading-choose-your-raspberry-pi-device-and-operating-system-and-select-storage">Choose your Raspberry Pi Device and operating system and select Storage</h4>
<p>For each of the three configurations, you must select one sequentially. Select a device according to the type of Raspberry Pi you have, and various options will appear. I selected the Raspberry Pi 4, as it is my preferred device. You may choose between the Raspberry Pi 5 and the Raspberry Pi Zero 2 W, depending on your device requirements.</p>
<p>Next, proceed to the operating system – I would recommend choosing the 64-bit version. While many people opt for the legacy version (32-bit), I think the 64-bit version is best. Once you're finished, you can choose a storage option, and your MicroSD should appear. My storage is around 128GB, which is why you can see 125.1GB displayed there in the screenshot below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747922610658/d5f4c750-ab40-47ed-8c0c-fe5951f68660.png" alt="Screenshot of the Raspberry Pi Imager v1.8.5 interface. It shows options for selecting a Raspberry Pi device, operating system, and storage. Available devices include Raspberry Pi 5, 4, and Zero 2 W. Operating systems listed are Raspberry Pi OS in 64-bit and 32-bit versions, and there is a USB device listed for storage." class="image--center mx-auto" width="1080" height="1080" loading="lazy"></p>
<h4 id="heading-click-on-next-and-edit-the-settings">Click on “Next” and edit the settings</h4>
<p>It is a customary practice to keep your username as "pi", but it’s not required. The goal is to have something simple and easy to remember when setting up your SSH connection. It’s also helpful to make your password simple. I used 'roboticsai'.</p>
<p>Try to avoid using numbers simply to make things easier, because you may not be able to see what you are entering in the terminal. Then, make sure that your wireless LAN and SSID (WIFI or Hotspot name if you're using a phone, as well as the password for your WIFI or Hotspot) is the same network as the one linked to your computer.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747922797428/c1a1ae55-e109-4a35-878c-820d1ef3f406.png" alt="Setting up the username and password of the Raspberry Pi" class="image--center mx-auto" width="1077" height="1060" loading="lazy"></p>
<h4 id="heading-click-on-services-and-enable-ssh-then-use-password-authentication-for-security-and-click-on-save">Click on “SERVICES” and enable SSH. Then use password authentication for security and Click on “SAVE”.</h4>
<p>After you've completed the changes in the General Section, go to the Services section and click the checkbox button “<em>Enable SSH</em>”. Once highlighted, make sure you pick “<em>Use password authentication</em>”, avoid the “<em>RUN SSH-KEYGEN</em>” button at the moment, and then click Save.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747923037374/b6c63a5a-e3b6-4c9f-9612-53df7e566e41.png" alt="Screenshot of an OS customization window under the &quot;Services&quot; tab. &quot;Enable SSH&quot; is checked, with &quot;Use password authentication&quot; selected. An option for &quot;Allow public-key authentication only&quot; is available. A disabled &quot;RUN SSH-KEYGEN&quot; button and a &quot;SAVE&quot; button are visible." class="image--center mx-auto" width="1071" height="926" loading="lazy"></p>
<h4 id="heading-click-yes-to-apply-the-customizations-and-the-raspberry-pi-os-should-get-flashed-into-your-sd-card">Click “YES” to apply the customizations, and the Raspberry Pi OS should get flashed into your SD Card.</h4>
<p>Following the previous stage, you will be shown various buttons to apply the adjustments you have made. Pick yes, and the Raspberry Pi OS will be flashed or transferred to your Memory Card. This could take between 10 and 20 minutes to go from transferring to writing or customizing. Hold on and enjoy the process.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747923100214/d86fca18-e540-4844-9f26-5253ef5b04b8.png" alt="Raspberry Pi Imager dialog box offering to apply OS customisation settings with options to edit, clear, accept, or decline." class="image--center mx-auto" width="1345" height="897" loading="lazy"></p>
<h4 id="heading-after-a-successful-installation-into-the-disk-remove-your-sd-card">After a successful installation into the disk, remove your SD Card.</h4>
<p>You will receive a successful popup like the one shown below. This demonstrates that all processes were completed successfully, and the Raspberry Pi OS is now installed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747926095493/ed017dc6-e3a5-4cda-8b3c-6f6a2d74c1ac.png" alt="A notification on Raspberry Pi Imager v1.8.5 shows that Raspberry Pi OS (64-bit) has been successfully written to a mass storage device USB. It instructs to remove the SD card and has a &quot;Continue&quot; button." class="image--center mx-auto" width="1352" height="998" loading="lazy"></p>
<h2 id="heading-how-to-boot-the-raspberry-pi">How to Boot the Raspberry Pi</h2>
<h3 id="heading-eject-the-microsd-safely-from-your-computer"><strong>Eject the MicroSD safely from your computer</strong></h3>
<p>Once the installation is successful, eject the MicroSD safely from the computer.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747926401040/a37dafbb-68ae-4884-9ffe-3c374e6b62b9.jpeg" alt="The Raspberry Pi Board with a micro SD card slot is placed on a wooden surface. A SanDisk 128 GB micro SD card lies next to it." class="image--center mx-auto" width="768" height="1020" loading="lazy"></p>
<h3 id="heading-insert-it-upside-down-into-the-microsd-card-slot-of-your-raspberry-pi">Insert it “upside down” into the MicroSD card slot of your Raspberry Pi</h3>
<p>To properly insert the MicroSD card, place it gently into the slot with the back or gold side facing upward. It will protrude slightly once it is inserted. You are good to go!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747926384277/f7a0c5e9-6a13-4cd2-b94a-65b329a08a5c.jpeg" alt="A Raspberry Pi single-board computer placed on a gray surface, displaying various ports and components including USB ports and an HDMI connector." class="image--center mx-auto" width="768" height="1020" loading="lazy"></p>
<h3 id="heading-connect-the-usb-c-port-of-your-raspberry-pi-to-your-computer-give-the-raspberry-pi-some-time-to-load">Connect the USB-C port of your Raspberry Pi to your computer. Give the Raspberry Pi some time to load</h3>
<p>Get a USB-C cable and connect one end to your Raspberry Pi's USB-C port and the other to a laptop port. It should light up red, indicating that there is an adequate power source. You may also power your Raspberry Pi directly by plugging into a wall socket.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747926452530/b023abe6-5555-4d61-ab99-0d8e36a828a4.jpeg" alt="A Raspberry Pi connected to a laptop via a USB cable on a wooden surface." class="image--center mx-auto" width="768" height="1020" loading="lazy"></p>
<p>After a while, the memory card should begin to boot into the Raspberry Pi, and the green LED will blink for a while. In the next section, we’ll talk about the different states of the two LEDs during and after a successful boot.</p>
<h2 id="heading-understanding-the-led-status-of-the-raspberry-pi-during-setup">Understanding the LED Status of the Raspberry Pi During Setup</h2>
<p>The below table describes the LED statuses you might see when you power on your Raspberry Pi and the SD Card is in the slot.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>LED Color</strong></td><td><strong>State/Pattern</strong></td><td><strong>Meaning/Recommendation</strong></td></tr>
</thead>
<tbody>
<tr>
<td>🔴Red</td><td>Solid (ON)</td><td>Stable and sufficient power supply</td></tr>
<tr>
<td>🔴Red</td><td>Off or Blinking</td><td>Undervoltage detected (Use a direct phone Charger connected to a Socket)</td></tr>
<tr>
<td>🟢Green</td><td>Blinking (Irregular Pattern)</td><td>SD Card is being read/written (normal booting activity)</td></tr>
<tr>
<td>🟢Green</td><td>Solid (ON)</td><td>Raspberry Pi is stuck or trying to boot.</td></tr>
<tr>
<td>🟢Green</td><td>Off</td><td>No SD Card detected or boot completed</td></tr>
<tr>
<td>🟢Green</td><td>Repeated blink patterns (for example 4 long, 4 short)</td><td>Error code indicating firmware issues.</td></tr>
<tr>
<td>🟢Green</td><td>Constant Blinking</td><td>Normal activity (Raspbian OS is loading and running smoothly)</td></tr>
</tbody>
</table>
</div><h2 id="heading-how-to-establish-an-ssh-connection">How to Establish an SSH Connection</h2>
<p>The SSH (Secure Shell) connection is a network protocol that allows two computers to safely communicate without leaking any information. It’s also used for remote command line execution and for file transfers between two computers.</p>
<p>To establish an SSH connection, you’ll have to complete a few steps. Then I’ll explain how to enable SSH using a Visual Studio Code extension</p>
<h3 id="heading-create-a-wpasupplicantconftxt-in-the-same-folder-of-your-raspberry-pi-sd-card"><strong>Create a</strong> <code>wpa_supplicant.conf.txt</code> <strong>in the same folder of your Raspberry Pi SD Card</strong></h3>
<p>Insert your MicroSD card back into the computer. Then the files that comprise the Raspberry Pi OS will appear on your computer. Create a new text (.txt) document on your computer, similar to the image below, under the SD Card storage section.</p>
<p>Add the code below, making sure that "ssid" is the name of your Wi-Fi network and "psk" is your network's password.</p>
<pre><code class="lang-plaintext">country=NG # Your 2-digit country code
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
network={
    ssid="Josiah"
    psk="roboticsai"
    key_mgmt=WPA-PSK
}
</code></pre>
<h3 id="heading-save-the-file-on-the-same-sd-card"><strong>Save the file on the same SD Card</strong></h3>
<p>Once you've finished producing the text file, save it to the SD Card storage, as shown in the image below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747928812199/fb766a84-7750-468d-ae78-1ff3c688a52b.jpeg" alt="Screenshot of a file explorer window showing contents of the &quot;bootfs (D:)&quot; directory. Various system and configuration files are listed, including kernel images and .elf files. The selected file is &quot;wpa_supplicant.conf.txt&quot;." class="image--center mx-auto" width="540" height="960" loading="lazy"></p>
<h3 id="heading-create-a-ssh-folder"><strong>Create a .ssh folder</strong></h3>
<p>In your personal computer, create a <code>.ssh</code> folder if it doesn’t exist on your personal computer.</p>
<p>If it exists, the <code>.ssh</code> folder should contain files like <code>id_rsa</code>, <code>known_hosts</code>, and <code>config</code> files. It shouldn’t be empty.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747928560247/d07f8cb9-ec22-47ff-a2a5-d18b614e9985.png" alt="A computer file explorer window showing a list of folders in the &quot;JOSIAH&quot; directory. The folder names include &quot;.matplotlib,&quot; &quot;.mchp_cm,&quot; &quot;.ssh,&quot; and others, with details like date modified and type. The &quot;.ssh&quot; folder is highlighted." class="image--center mx-auto" width="1919" height="977" loading="lazy"></p>
<p>After a successful boot, open your terminal or command line application on your personal computer.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747928958812/2c198297-08a5-4781-9a6a-45fd6c7e85d3.png" alt="Command Prompt window showing &quot;Microsoft Windows [Version 10.0.26100.3915]&quot; and the prompt at &quot;C:sersOSIAH>&quot;." class="image--center mx-auto" width="1731" height="923" loading="lazy"></p>
<p>Make sure that the Raspberry Pi is connected to the same network before moving ahead. Once your wifi or mobile hotspot is switched on, make sure it’s the same password as the <code>wpa_supplicant.conf.txt</code> and the settings page while installing the Raspberry Pi.</p>
<p>As long as the SD card is in the Raspberry Pi and there is adequate power supply for at least 2-5 minutes, the Raspberry Pi will get connected to the wifi or your mobile hotspot.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747931364223/13947f34-c1a9-4b1c-b020-c236b4d377af.jpeg" alt="Screenshot of connected devices interface showing a limit of 3 devices. Two devices are listed: &quot;raspberrypi&quot; with MAC address d8:3a:dd:43:27:71, and &quot;Josiah&quot; with MAC address dc:71:96:d0:d5:4a. A blocklist option is available for viewing devices not allowed to connect." class="image--center mx-auto" width="720" height="825" loading="lazy"></p>
<h3 id="heading-how-to-resolve-connection-problems">How to Resolve Connection Problems</h3>
<p>If there is no connection, reinstall the Raspberry Pi OS Imager on the SD Card again. Then you can also change the network AP Band from 5GHz to 2.5GHz or vice-versa. This can be very tricky.</p>
<p>It should get connected after trying this. Just make sure that the passwords are consistent and that you don’t accidentally have the caps lock key switched on while typing, for example.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1748028008935/192fb282-93c7-4b65-86a2-c26cdfac9d53.jpeg" alt="Screenshot of a portable hotspot setup screen showing fields for network name, password, security setting (WPA2-Personal), AP band selection (5 GHz), and an option to hide the SSID, which is off." class="image--center mx-auto" width="720" height="914" loading="lazy"></p>
<p>To confirm if the Raspberry Pi is connected using the command line interface, use the <code>ping</code> command – it shows the devices connected to the device.</p>
<pre><code class="lang-bash">ping raspberrypi.local
</code></pre>
<p>After running the above command, you should see an image showing the connection once it’s successful like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747931544791/77217325-4f3e-4abb-a136-d4634b773f2d.png" alt="A command prompt window showing a ping test to &quot;raspberrypi.local&quot; with an IPv6 address. Four packets are sent and received with no loss. Round trip times range from 6ms to 125ms, with an average of 36ms." class="image--center mx-auto" width="925" height="382" loading="lazy"></p>
<p>For establishing an SSH connection using the terminal, run the code below:</p>
<pre><code class="lang-bash">ssh pi@raspberrypi.local
</code></pre>
<p>This will result in a request for a password. If it shows an error like the image below, it means you have to delete the <code>known_hosts.old</code> and <code>known_hosts</code> if either or both exist in the <code>.ssh</code> folder in your PC. This is because the keys are conflicting with each other. Then re-run the above code <code>ssh pi@raspberrypi.local</code> in your terminal.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747931933273/d8f111cc-3455-4de3-af0c-cf0a9814a877.png" alt="SSH warning message indicating a change in the remote host identification for a Raspberry Pi, suggesting possible eavesdropping or a host key update. Offers instructions for resolving the issue by updating the known_hosts file." class="image--center mx-auto" width="912" height="489" loading="lazy"></p>
<p>After successful entry, type “<code>yes</code>” in the terminal.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747932392301/a09ad065-8e1e-464f-baef-5529eee26ce4.png" alt="Command-line interface showing an SSH connection attempt to a Raspberry Pi. It prompts the user to confirm the authenticity of the host with a given key fingerprint, asking if they want to continue connecting." class="image--center mx-auto" width="1392" height="281" loading="lazy"></p>
<p><code>Connection Closed</code> should show when the connection is successful.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747932449402/bcd16bc6-18a1-4a84-82cf-d5c7431345e3.png" alt="Screenshot of a terminal window showing an SSH connection attempt from a user to a Raspberry Pi. The authenticity of the host is questioned, asking for confirmation to continue. The fingerprint is displayed, indicating it's not previously known. The connection is then added to known hosts, before closing." class="image--center mx-auto" width="1501" height="345" loading="lazy"></p>
<h2 id="heading-how-to-set-up-visual-studio-code-for-remote-development">How to Set Up Visual Studio Code for Remote Development</h2>
<p>Download and install <a target="_blank" href="https://code.visualstudio.com/">Visual Studio Code</a> if you don’t have it already.</p>
<p>Then, click on the VS Code extension and search for <code>Remote - SSH</code> by Microsoft and install it to your machine.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747933199343/2c181e3a-80bd-44d1-8b40-5e3cf6191f2b.png" alt="Screenshot of the Visual Studio Code extension marketplace displaying the &quot;Remote - SSH&quot; extension by Microsoft. It shows installation details, ratings, and features like using a remote machine with SSH for development. The left sidebar lists related extensions." class="image--center mx-auto" width="1919" height="888" loading="lazy"></p>
<p>Next, click on the “Remote Explorer” icon that looks like a monitor. Select the SSH config in your <code>C:\Users\{name}\.ssh\config</code> folder.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747933364169/7eaa4a7b-294c-41ef-8ecb-fe80151e6399.png" alt="Screenshot of Visual Studio Code showing the Remote - SSH extension interface. The SSH configuration file selection is open, displaying file paths. On the right, there is a description and installation details for the extension, including version and update information. The left sidebar displays a connection to a remote SSH machine named &quot;raspberrypi&quot;." class="image--center mx-auto" width="1918" height="781" loading="lazy"></p>
<p>Make sure the config has this command:</p>
<pre><code class="lang-bash">Host raspberrypi.local
    HostName raspberrypi.local
    User pi
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747933533204/611b6a3d-cd4c-4756-982b-76efb0aa25c9.png" alt="611b6a3d-cd4c-4756-982b-76efb0aa25c9" class="image--center mx-auto" width="916" height="500" loading="lazy"></p>
<p>Enter your username as <code>raspberrypi.local</code> and input your password – the same as the password during loading Raspbian OS.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747933839359/7f43b231-5177-4b11-9d10-7234961db3f7.png" alt="Visual Studio Code interface showing a prompt to enter a password for &quot;pi@raspberrypi.local&quot; to set up an SSH host. The background features a shortcut guide and a loading bar." class="image--center mx-auto" width="1530" height="1002" loading="lazy"></p>
<p>After inputting the correct password, it should start downloading the server.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747933859344/0c87fd5c-071b-4016-b113-4fc88c166032.png" alt="Visual Studio Code interface showing keyboard shortcuts for various commands. A download progress bar at the bottom indicates &quot;Downloading VS Code Server…&quot;" class="image--center mx-auto" width="1526" height="988" loading="lazy"></p>
<p>Congratulations! The image below has a blue rectangle button showing <code>SSH:raspberrypi.local</code> which shows a successful SSH Connection through Visual Studio Code. This also means you can start remote development as we discussed earlier in this tutorial.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747933925369/a2aaf412-e465-47e9-8e97-129734f87534.png" alt="A screenshot of Visual Studio Code's welcome screen. The interface lists options to open a folder or clone a repository. The &quot;Start&quot; section has options like &quot;New File&quot; and &quot;Open Folder.&quot; The &quot;Recent&quot; section displays a list of recently accessed projects. The &quot;Walkthroughs&quot; area suggests getting started guides. The sidebar on the left shows file explorer and other icons. The bottom status bar indicates an SSH connection." class="image--center mx-auto" width="1919" height="1006" loading="lazy"></p>
<h2 id="heading-how-to-write-and-run-the-code-remotely">How to Write and Run the Code Remotely</h2>
<p>Create a new file on your VS Code. This way, you’re creating files and writing to them directly. Go to the terminal and type the commands to create a folder and a file:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747934210225/a6e7f454-6f65-4a87-8692-cadaa642b007.png" alt="Screenshot of Visual Studio Code showing a terminal session and a text editor. The terminal is open at the bottom, with commands for creating a directory, navigating to it, and opening it in the editor. The main editor area prompts to select a language or open a different editor. The Explorer sidebar is visible on the left." class="image--center mx-auto" width="1916" height="880" loading="lazy"></p>
<h3 id="heading-create-a-new-file-and-write-in-your-code"><strong>Create a new file and write in your code</strong></h3>
<p>Create a new file and name it <code>led.py</code> on your Visual Studio Code. It should be in the same folder as <code>test-raspberry</code> on the Raspberry Pi remote network through the SSH connection on VSCode.</p>
<p>Once you have your file created, you can write in your code such as blinking LED to a Raspberry Pi, as you can see in the code below:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> gpiozero <span class="hljs-keyword">import</span> LED
<span class="hljs-keyword">from</span> time <span class="hljs-keyword">import</span> sleep

<span class="hljs-comment"># Set the GPIO pin where the LED is connected</span>
led = LED(<span class="hljs-number">17</span>)  <span class="hljs-comment"># Replace 17 with your GPIO pin number</span>

<span class="hljs-comment"># Blink the LED in a loop</span>
<span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
    led.on()        <span class="hljs-comment"># Turn LED on</span>
    sleep(<span class="hljs-number">1</span>)        <span class="hljs-comment"># Wait for 1 second</span>
    led.off()       <span class="hljs-comment"># Turn LED off</span>
    sleep(<span class="hljs-number">1</span>)        <span class="hljs-comment"># Wait for 1 second</span>
</code></pre>
<p>After writing this code in the new file you’ve created, run the code by typing the command below in your terminal:</p>
<pre><code class="lang-bash">python led.py
</code></pre>
<p>As soon as this command is sent, the LED positive terminal is connected to the GPIO 17 according to the code and the negative terminal is connected to the GND GPIO pin of the Raspberry Pi. The image from <a target="_blank" href="https://randomnerdtutorials.com/raspberry-pi-pinout-gpios/">Random Nerd Tutorials</a> below shows the GPIO pins and their number to understand the connection. Just note that the connection of the LED is beyond the scope of this tutorial.</p>
<p><img src="https://i0.wp.com/randomnerdtutorials.com/wp-content/uploads/2023/03/Raspberry-Pi-Pinout-Random-Nerd-Tutorials.png?quality=100&amp;strip=all&amp;ssl=1" alt="Raspberry Pi Pinout Guide: How to use the Raspberry Pi GPIOs? | Random Nerd  Tutorials" width="1280" height="720" loading="lazy"></p>
<p>The LED should start blinking each second according to the code. With this, you can now control your Raspberry Pi (a tiny computer) with another computer (your personal computer) through an SSH connection on Visual Studio Code.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you went through the whole process of setting up a headless Raspberry Pi for remote development using VS Code.</p>
<p>This offers a wide range of benefits: there’s no need for external peripherals, it provides remote access from anywhere within your network, and it leverages efficient coding and debugging with VS Code integration.</p>
<p>You can use this to deploy web servers and IoT dashboards, and you can explore with automating processes using Python scripts and GPIO control.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ SVM Kernels Explained: How to Tackle Nonlinear Data in Machine Learning ]]>
                </title>
                <description>
                    <![CDATA[ Have you ever considered how your phone can recognize handwritten text and convert it into regular computer text? Or how your email can separate messages automatically into spam and non-spam categories? Both of these examples work based on classifica... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/svm-kernels-how-to-tackle-nonlinear-data-in-machine-learning/</link>
                <guid isPermaLink="false">677c5a037d6144e9c5ef49f8</guid>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MathJax ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Josiah Adesola ]]>
                </dc:creator>
                <pubDate>Mon, 06 Jan 2025 22:32:35 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1735894336456/dae0caa1-7c01-4b88-a748-79d682bbed78.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Have you ever considered how your phone can recognize handwritten text and convert it into regular computer text? Or how your email can separate messages automatically into spam and non-spam categories?</p>
<p>Both of these examples work based on classification tasks, as does the facial recognition feature on your phone.</p>
<p>When building a classification algorithm, real-world data often has a non-linear relationship. And many machine learning classification algorithms struggle with non-linear algorithms. But in this article, we'll be looking at how Support Vector Machine (SVM) kernel functions can help to solve this problem. We’ll go in-depth into a Python implementation of non-linear classification and SVM kernel functions.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ol>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/learn-machine-learning-in-2024/">Basic Understanding of Machine Learning</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/linear-algebra-full-course/">Linear Algebra Basics</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/ultimate-beginners-python-course/">Basic Python Programming Skills</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/learn-data-visualization-in-this-free-17-hour-course/">Understanding of Data Visualization</a></p>
</li>
<li><p><a target="_blank" href="https://colab.research.google.com/">A Google Colab</a> or <a target="_blank" href="https://www.anaconda.com/">Jupyter Notebook</a> Account</p>
</li>
</ol>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-overview-of-the-support-vector-machine-svm-technique">Overview of the Support Vector Machine (SVM) Technique</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-fundamentals-of-svm">Fundamentals of SVM</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-svm-objective-function">SVM Objective Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-kernel-functions">Understanding Kernel Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-popular-kernel-functions">Popular Kernel Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-choose-the-right-kernel">How to Choose the Right Kernel</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-svm-kernel-implementation">SVM Kernel Implementation</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-overview-of-the-support-vector-machine-svm-technique">Overview of the Support Vector Machine (SVM) Technique</h2>
<p>Support Vector Machine (SVM) is a supervised learning algorithm. It uses a hyperplane that divides features inside a feature space into distinct categories. It’s effective for both classification and regression applications.</p>
<p>By identifying the optimal dividing line or plane that will serve as the decision boundary, SVM seeks to maximize the margin between the various target variables. It’s primarily utilized in classification tasks and is very helpful in ignoring outliers. It categorizes the data points of the features in the dataset into distinct outputs or classes.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734965953633/54d38f2a-8062-4bcb-8cc6-9795064241de.png" alt="Comparison of decision boundaries using SVC with different kernels on a dataset." class="image--center mx-auto" width="640" height="480" loading="lazy"></p>
<p>SVM seeks to achieve the optimal maximum margin and an ideal or near-perfect separation. There are various applications for SVM, such as image classification, face detection, text classification, image classification, and bioinformatics. SVM is also efficient in linear and non-linear classification problems.</p>
<h3 id="heading-importance-of-kernel-methods-in-svm">Importance of Kernel methods in SVM</h3>
<p>Nonlinear classification is a sort of classification that involves categorizing features that have non-linear, curved, or complex decision boundaries. Decision boundaries are regions of space that separate two different classes.</p>
<p>In linear classification tasks, the region of space between the different classes such as if the email is spam or not can be easily separated with a straight line. But in non-linear relationships, it could have a circular, parabola, or a complex-shape decision boundary.</p>
<p>Non-linear classification tasks have patterns that cannot be discovered by linear models. This is because the features have a non-linear relationship with each other.</p>
<p><a target="_blank" href="https://www.researchgate.net/publication/349186066_Machine_Learning_Techniques_for_THz_Imaging_and_Time-Domain_Spectroscopy"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1735885699184/222d7252-7ece-4e31-97f5-577bb8577797.png" alt="Two diagrams illustrating decision boundaries between two classes: (a) shows a complex, wavy decision boundary, while (b) shows a simpler, smoother boundary. Blue dots represent Class A, and red triangles represent Class B.Machine Learning Techniques for THz Imaging and Time-Domain Spectroscopy by Hochong Park and Joo-Huik Son" class="image--center mx-auto" width="1058" height="430" loading="lazy"></a></p>
<p>SVM as a linear classification algorithm isn’t efficient for a non-linear data. To handle this sort of data, it will require a kernel method, which is the core topic of this article.</p>
<p>A kernel method is a technique used in SVM to transform non-linear data into higher dimensions. For example, if the data has a complex decision boundary in a 2-Dimensional space (as I’ll explain further in the later part of this article), it can be transformed into a 3-Dimensional space. This allows efficient classification just with a linear plane.</p>
<p>The goal of the article is to teach you about SVM kernels and their application to non-linear classification tasks.</p>
<h2 id="heading-fundamentals-of-svm">Fundamentals of SVM</h2>
<h3 id="heading-linear-classifiers-and-margin-maximization">Linear Classifiers and Margin Maximization</h3>
<p>Linear classifiers are classification algorithms that make predictions by using a straight line of best fit as a decision boundary between two or more categories.</p>
<p>Marginal planes are used to determine the support vector in the classification task. Support vectors are the data points in the dataset that are used to separate the different target variable categories – they are data points very close to the decision boundary.</p>
<p>In the image below, the marginal planes are the yellow lines, while the hyperplane is the red line. The hyperplane serves as the line of best fit or decision boundary. The data points that are closest to the marginal plane are the support vectors – the data points encircled in green in the image below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1735889303238/33e28db8-a0aa-4aa9-ac63-0ece6b2d8c15.png" alt="Hard Margin: Decision Boundary for classification of two labels Image by the Author" class="image--center mx-auto" width="580" height="436" loading="lazy"></p>
<p>The marginal plane aims to achieve a maximum margin between its plane and the hyperplane – both having equal distance from hyperplane to achieve the best classification. The hyperplane in the image above shows a perfect linear relationship between <code>feature x1</code> and <code>feature x2</code>. The support vectors also help to establish the location of the marginal plane.</p>
<p>We have the hard margin and the soft margin, serving as model optimization methodologies for the SVM. The hard margin shows that you cannot find a data point of <code>feature x1</code> in the same area where there are <code>feature x2</code> data points and vice versa. It used to describe a perfect classification by the algorithm. The image above gives a representation of a hard margin.</p>
<p>A soft margin shows that the classification is imperfect, because you can find some data points of <code>feature x1</code> in the same area where we have data points of feature two, which could be caused by outliers. The image below gives a representation of soft margin.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1735888972196/3e9dfaa1-999e-4e55-b1eb-bc04ef8de24e.png" alt="Soft Margin: Decision Boundary for classification of two labels Image by the Author" class="image--center mx-auto" width="580" height="436" loading="lazy"></p>
<h2 id="heading-svm-objective-function">SVM Objective Function</h2>
<p>For a binary classification, such as a dog or a cat, the dog can be represented as class 1 and cat as -1. This shows that the decision boundary or hyperplane is the determining factor. Any value above the plane is given as 1, and the class below the plane is given as -1.</p>
<p>The mathematical function for the hyperplane is given as:</p>
<p>$$f(x) = \mathbf{w}^T\mathbf{x} + b$$</p><p>$$\begin{array}{l} \text{ The variables used are:} \\ \mathbf{w}: \text{Weight vector (defining the orientation of the hyperplane)} \\ b: \text{Bias term (defining the position of the hyperplane)} \\ \mathbf{x}: \text{Input feature vector} \\ \\ \text{The classification decision is based on the sign of } f(x)\text{:} \\ f(x) &gt; 0: \text{Class 1} \\ f(x) &lt; 0: \text{Class -1} \end{array}$$</p><h3 id="heading-hard-margin-svm">Hard Margin SVM</h3>
<p>The Hard Margin SVM ensures all the data points are all properly classified without error, ensuring that the data points don’t find themselves in the other part of the hyperplane, and also maximizing the margin. It’s an effective method for a “noise-free” dataset. This is achieved by minimizing an objective function given below:</p>
<p>$$\begin{array}{l} \text{Hard Margin SVM Objective Function:} \ \min_{\mathbf{w},b} \frac{1}{2}\|\mathbf{w}\|^2 \\ \\ \text{Subject to:} \\ y_i(\mathbf{w}^T\mathbf{x}_i + b) \geq 1, \,\, \forall i \\ \\ \text{Where:} \\ y_i: \text{ Class label of the }i\text{-th sample } (+1 \text{ or } -1) \\ \mathbf{x}_i: \text{ Feature vector of the }i\text{-th sample} \end{array}$$</p><p>This constraint given above in the objective function ensures that all the data points are not misclassified and the stay outside the margin.</p>
<h3 id="heading-soft-margin-svm">Soft Margin SVM</h3>
<p>The Soft Margin SVM is lenient, as it allows some misclassifications. It’s suitable for real-world datasets, which are noisy, and it handles non-linearly separable data. It introduces a slack variable that penalizes incorrect predictions.</p>
<p>$$\begin{array}{l} \text{Objective Function:} \ \min_{\mathbf{w},b,\xi} \frac{1}{2}\|\mathbf{w}\|^2 + C\sum_{i=1}^n \xi_i \\ \\ \text{Subject to:} \\ y_i(\mathbf{w}^T\mathbf{x}_i + b) \geq 1 - \xi_i, \,\, \forall i \\ \xi_i \geq 0, \,\, \forall i \\ \\ \text{Where:} \\ \xi_i: \text{ Slack variables representing the degree of misclassification or} \\ \text{margin violation.} \\ C: \text{ Regularization parameter controlling the trade-off between} \\ \text{margin maximization and error minimization.} \end{array}$$</p><p>The hyperparameter C helps to control the penalty for a balance between margin maximization and error minimization. A large C value minimizes the classification errors, but causes a smaller margin. A small C value allows some misclassifications but causes a larger margin.</p>
<h3 id="heading-nonlinear-classification-problems">Nonlinear Classification Problems</h3>
<p>Non-linear classification problems include datasets with non-linear patterns that are difficult for linear SVM models to capture. This is a drawback, but SVM kernels can help.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734969794598/58fcb341-735f-4a57-943b-c748b7a3f85c.png" alt="58fcb341-735f-4a57-943b-c748b7a3f85c" class="image--center mx-auto" width="714" height="493" loading="lazy"></p>
<p>Non-linear classification contains datasets with complicated relationships and linear models like linear regression will not be able to accurately generate predictions or identify trends.</p>
<h2 id="heading-understanding-kernel-functions">Understanding Kernel Functions</h2>
<p>In kernel functions, we transform the dataset used in the classification task into a higher dimensional feature space. This line of action enables the hyperplane (a linear decision boundary) to split the data as linearly separable data.</p>
<p>For example, if a dataset contains three features in a 2D plane, the kernel function converts the data to a 3D plane, making it much simpler to partition the dataset using a basic hyperplane. This technique can be used to capture non-linear relationships in data.</p>
<p>To provide a clearer mental image, consider three distinct feature sets in the 2D plane (x and y). This can be taken to a 3D plane by the kernel machine, where <code>features x1</code> and <code>feature x2</code> may be in the x-y plane, which is readily divided by a simple hyperplane, and <code>feature x3</code> may be in the y-z plane, which is already separated.</p>
<h3 id="heading-the-kernel-trick-explained">The Kernel Trick Explained</h3>
<p>Transformation into a higher dimensional space is computationally intensive and is not the best option. But we know the importance of kernel functions in classifying non-linear data. So, what’s the way forward to still achieve the same feat while bypassing the cost of computation? It’s called the kernel trick. The kernel trick explains the “magic power” of the kernel functions.</p>
<p>The kernel trick is the computation of the inner or dot product between the data points in the original dimensional space instead of transforming the data into a higher-dimensional space before doing the computation.</p>
<p>The right side of the equation below shows the dot product of ϕ(x), representing the transformed vector into a higher dimensional space (which is not efficient). It’s the same as a kernel function at the left hand side:</p>
<p>$$K(x_i, x_j) = \phi(x_i) \cdot \phi(x_j)$$</p><p>The purpose of the kernel trick is to perform computation based on the data point in its original dimensional space, instead of performing calculations on complex data that might require an infinite number of dimensions.</p>
<h3 id="heading-mathematical-implementation-of-the-kernel-trick">Mathematical Implementation of the Kernel Trick</h3>
<p>Suppose we have two classes of data that are non-linear in the 2D space representing the original feature space. No straight line can separate these points because they lie diagonally across the origin.</p>
<p>$$\begin{array}{l} \textbf{Mapping Without Kernel Trick: }\\ \\ \begin{align*} \textbf{The 2D data is given as: } \\ &amp; \mathbf{x}_1 = (1,1), &amp; y_1 = +1 \\ &amp; \mathbf{x}_2 = (-1,-1), &amp; y_2 = -1 \end{align*} \\ \\ \textbf{Let's use a mapping function: } \\ \\ \phi(x, y) = (x^2, \sqrt{2}xy, y^2)\ \\ \\ Mapping\ \mathbf{x}_1 \ and \ \ \mathbf{x}_2: \\ \\ \begin{array}{l} - \ \phi(\mathbf{x}_1) = (1^2, \sqrt{2}(1)(1), 1^2) = (1, \sqrt{2}, 1) \\ \\ -\ \phi(\mathbf{x}_2) = ((-1)^2, \sqrt{2}(-1)(-1), (-1)^2) = (1, \sqrt{2}, 1) \end{array} \\ \\ \\ \textbf{Dot Product in Higher-Dimensional Space:} \\ \\ \phi(\mathbf{x}_1) \cdot \phi(\mathbf{x}_2) = (1)(1) + (\sqrt{2})(\sqrt{2}) + (1)(1) = 1 + 2 + 1 = 4 \\ \\ \\ \begin{array}{l} \text{This is the dot product of }\mathbf{x}_1\text{ and }\mathbf{x}_2\text{ after explicitly} \\ \text{mapping them to the higher-dimensional space.} \end{array} \end{array}$$</p><p>$$\begin{array}{l} \textbf{Using the Kernel Trick: }\\ \\ \textbf{Polynomial Kernel Definition:} \\ \\ K(\mathbf{x}_i, \mathbf{x}_j) = (\mathbf{x}_i^\top \mathbf{x}_j + c)^d \\ \\ \textbf{For this example:} \\ \\ d = 2 \ (\text{degree of the polynomial}), \quad c = 0 \ (\text{no bias term}) \\ \\ \textbf{Given: } \\ \\ \mathbf{x}_1 = (1, -1), \quad \mathbf{x}_2 = (-1, -1) \\ \\ \textbf{Compute } K(\mathbf{x}_1, \mathbf{x}_2): \\ \\ \begin{align*} K(\mathbf{x}_1, \mathbf{x}_2) &amp;= ((1)(-1) + (1)(-1))^2 \\ &amp;= (-1 - 1)^2 \\ &amp;= (-2)^2 \\ &amp;= 4 \end{align*} \\ \\ \begin{array}{l} \text{Using the kernel trick, we directly compute the dot product in the higher} \\ \text{dimensional space without explicitly mapping the points.} \end{array} \end{array}$$</p><h2 id="heading-popular-kernel-functions">Popular Kernel Functions</h2>
<h3 id="heading-linear-kernel">Linear kernel</h3>
<p>For a dataset that is linearly separable, the linear kernel is ideal. When used for non-linear data sets, which are the main topic of this article, it may result in underfitting and create a linear decision boundary. It’s provided as the input feature vectors' dot product.</p>
<p>This kernel merely constructs the hyperplane or line of best fit to divide the data points. It does not perform any particular transformation to a higher dimension.</p>
<p>$$Linear Kernel Function: K(x_i, x_j) = x_i \cdot x_j$$</p><h3 id="heading-polynomial-kernel">Polynomial kernel</h3>
<p>The polynomial kernel transforms the data into a polynomial feature space of order d. It does a dot product on the feature vector with a constant c, all within the degree of d. The higher the degree of the polynomial, the better the kernel captures the relationships in the nonlinear dataset.</p>
<p>$$Polynomial Kernel Function: K(x_i, x_j) = (x_i \cdot x_j + c)^d$$</p><h3 id="heading-gaussian-or-radial-basis-function-rbf-kernel">Gaussian or Radial Basis Function (RBF) kernel</h3>
<p>The Gaussian kernel, also known as the RBF kernel, is often used in SVM to map the input feature vector to an infinite-dimensional feature space using a Gaussian function. This kernel can handle more complex relationships.</p>
<p>$$RBF Kernel Function: K(x_i, x_j) = \exp(-\gamma \|x_i - x_j\|^2)$$</p><h3 id="heading-sigmoid-kernel">Sigmoid kernel</h3>
<p>The sigmoid kernel acts similarly to the activation function in neural networks. It functions similarly to a two-layered perception network and can map data into a higher-dimensional feature space.</p>
<p>$$Sigmoid Kernel Function: K(x_i, x_j) = \tanh(\alpha(x_i \cdot x_j) + c)$$</p><p>There are other kernel functions such as Laplacian kernels, hyperbolic kernels, exponential kernels, and custom kernels that you can look into if you’re curious.</p>
<h2 id="heading-how-to-choose-the-right-kernel">How to Choose the Right Kernel</h2>
<p>The various kernel functions are applied based on the linear and nonlinear relationships in the feature space. The linear kernel is simple and fast, and it works well with linearly separable data but not with high-dimensional data.</p>
<p>The polynomial kernel is well-suited for data with non-linear or polynomial relationships, as well as low-dimensional data. The RBF kernel is ideal for dense data that you have no prior knowledge of. Finally, the sigmoid kernel works well for binary and categorical data points.</p>
<h2 id="heading-svm-kernel-implementation">SVM Kernel Implementation</h2>
<p>Let’s now go through an example showing how you can use this technique.</p>
<h3 id="heading-step-1-import-the-necessary-libraries"><strong>Step 1: Import the necessary libraries</strong></h3>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt
<span class="hljs-keyword">from</span> sklearn.datasets <span class="hljs-keyword">import</span> make_circles
<span class="hljs-keyword">from</span> mpl_toolkits.mplot3d <span class="hljs-keyword">import</span> Axes3D
<span class="hljs-keyword">from</span> sklearn.preprocessing <span class="hljs-keyword">import</span> StandardScaler
</code></pre>
<h3 id="heading-step-2-generate-the-non-linear-dataset"><strong>Step 2: Generate the non-linear dataset</strong></h3>
<p>The non-linear dataset used in this article is a circle dataset from <code>sklearn.datasets</code>. We used 1500 samples with a <code>random_state</code> of 46 to keep the dataset consistent for reproducibility. We added a Gaussian noise to the data of 10%. This <code>function generate_circle_data</code> is implemented to generate the dataset used in the article.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">generate_circle_data</span>(<span class="hljs-params">n_samples=<span class="hljs-number">1500</span>, noise=<span class="hljs-number">0.10</span>, random_state=<span class="hljs-number">46</span></span>):</span>
    <span class="hljs-string">"""
    Generate two concentric circles dataset.

    Parameters:
    -----------
    n_samples : int
        The total number of points generated
    noise : float
        Standard deviation of Gaussian noise added to the data
    random_state : int
        Random seed for reproducibility

    Returns:
    --------
    X : array of shape [n_samples, 2]
        The generated samples
    y : array of shape [n_samples]
        The integer labels (0 or 1) for class membership of each sample
    """</span>
    <span class="hljs-keyword">return</span> make_circles(n_samples=n_samples, 
                       noise=noise, 
                       random_state=random_state)
</code></pre>
<h3 id="heading-step-3-plot-the-2d-data"><strong>Step 3: Plot the 2D Data</strong></h3>
<p>The data generated above comes in 2D form. Each color represents the two different data samples. The data points were plotted which allows us to see it as a circular dataset using the <code>Matplotlib</code> library.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">plot_2d_data</span>(<span class="hljs-params">X, y, title=<span class="hljs-string">"2D Circle Dataset"</span></span>):</span>
    <span class="hljs-string">"""
    Plot the 2D dataset with different colors for each class.

    Parameters:
    -----------
    X : array-like of shape (n_samples, 2)
        The input samples
    y : array-like of shape (n_samples,)
        The target values (class labels)
    title : str
        The title of the plot
    """</span>
    plt.figure(figsize=(<span class="hljs-number">8</span>, <span class="hljs-number">6</span>))
    plt.scatter(X[:, <span class="hljs-number">0</span>], X[:, <span class="hljs-number">1</span>], c=y, marker=<span class="hljs-string">'.'</span>, cmap=<span class="hljs-string">'viridis'</span>)
    plt.title(title)
    plt.xlabel(<span class="hljs-string">'X₁'</span>)
    plt.ylabel(<span class="hljs-string">'X₂'</span>)
    plt.colorbar(label=<span class="hljs-string">'Class'</span>)
    plt.grid(<span class="hljs-literal">True</span>, alpha=<span class="hljs-number">0.3</span>)
    plt.show()
</code></pre>
<p>The output image of the dataset is given below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734978596496/a529c7e6-13ce-427e-b462-1241ea6de1bf.png" alt="Output of circular dataset" class="image--center mx-auto" width="913" height="656" loading="lazy"></p>
<h3 id="heading-step-4-transform-into-a-higher-dimensional-space"><strong>Step 4: Transform into a Higher-Dimensional Space</strong></h3>
<p>The data in 2D is transformed into a 3D space using the polynomial kernel. We achieved this by creating a third feature X3 so it can be mapped into a higher dimensional space for easy separation.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">transform_to_3d</span>(<span class="hljs-params">X</span>):</span>
    <span class="hljs-string">"""Transform 2D data to 3D using radius-based transformation"""</span>
    X1 = X[:, <span class="hljs-number">0</span>].reshape(<span class="hljs-number">-1</span>, <span class="hljs-number">1</span>)
    X2 = X[:, <span class="hljs-number">1</span>].reshape(<span class="hljs-number">-1</span>, <span class="hljs-number">1</span>)
    <span class="hljs-comment"># Modified transformation to create better separation</span>
    X3 = X1**<span class="hljs-number">2</span> + X2**<span class="hljs-number">2</span>
    <span class="hljs-keyword">return</span> np.hstack((X1, X2, X3))
</code></pre>
<h3 id="heading-step-5-plot-the-3d-transformation">Step 5: Plot the 3D Transformation</h3>
<p>The next step is to plot the 3D transformed dataset. It now looks like a U-shaped bowl, and is separated with a hyperplane after fitting a <code>LinearSVC</code> model from the <code>sklearn</code> library as the kernel we’re using. This shows a practical example of the concepts you’ve learned so far:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">plot_3d_transformation_with_separator</span>(<span class="hljs-params">X_transformed, y, title=<span class="hljs-string">"3D Transformed Dataset with Linear Separator"</span></span>):</span>
    <span class="hljs-string">"""Plot the 3D transformed dataset with a clear linear separating plane"""</span>

    <span class="hljs-comment"># Scale the transformed features</span>
    scaler = StandardScaler()
    X_scaled = scaler.fit_transform(X_transformed)

    <span class="hljs-comment"># Fit linear SVM with adjusted parameters for better separation</span>
    svm = LinearSVC(C=<span class="hljs-number">1.0</span>, dual=<span class="hljs-string">"auto"</span>, max_iter=<span class="hljs-number">5000</span>)
    svm.fit(X_scaled, y)

    <span class="hljs-comment"># Create the 3D plot</span>
    fig = plt.figure(figsize=(<span class="hljs-number">12</span>, <span class="hljs-number">8</span>))
    ax = fig.add_subplot(<span class="hljs-number">111</span>, projection=<span class="hljs-string">'3d'</span>)

    <span class="hljs-comment"># Plot the two classes with different colors and markers for clarity</span>
    class_0 = y == <span class="hljs-number">0</span>
    class_1 = y == <span class="hljs-number">1</span>

    ax.scatter(X_transformed[class_0, <span class="hljs-number">0</span>], 
              X_transformed[class_0, <span class="hljs-number">1</span>], 
              X_transformed[class_0, <span class="hljs-number">2</span>],
              c=<span class="hljs-string">'blue'</span>, 
              marker=<span class="hljs-string">'o'</span>,
              label=<span class="hljs-string">'Class 0'</span>,
              alpha=<span class="hljs-number">0.6</span>)

    ax.scatter(X_transformed[class_1, <span class="hljs-number">0</span>], 
              X_transformed[class_1, <span class="hljs-number">1</span>], 
              X_transformed[class_1, <span class="hljs-number">2</span>],
              c=<span class="hljs-string">'red'</span>, 
              marker=<span class="hljs-string">'^'</span>,
              label=<span class="hljs-string">'Class 1'</span>,
              alpha=<span class="hljs-number">0.6</span>)

    <span class="hljs-comment"># Create a grid for the separator plane</span>
    x_min, x_max = X_transformed[:, <span class="hljs-number">0</span>].min() - <span class="hljs-number">0.2</span>, X_transformed[:, <span class="hljs-number">0</span>].max() + <span class="hljs-number">0.2</span>
    y_min, y_max = X_transformed[:, <span class="hljs-number">1</span>].min() - <span class="hljs-number">0.2</span>, X_transformed[:, <span class="hljs-number">1</span>].max() + <span class="hljs-number">0.2</span>

    xx, yy = np.meshgrid(np.linspace(x_min, x_max, <span class="hljs-number">50</span>),
                        np.linspace(y_min, y_max, <span class="hljs-number">50</span>))

    <span class="hljs-comment"># Get the separating plane coefficients</span>
    w = svm.coef_[<span class="hljs-number">0</span>]
    b = svm.intercept_[<span class="hljs-number">0</span>]

    <span class="hljs-comment"># Calculate z coordinates of the plane</span>
    grid_points = np.c_[xx.ravel(), yy.ravel(), np.zeros(xx.ravel().shape[<span class="hljs-number">0</span>])]
    scaled_grid = scaler.transform(grid_points)

    <span class="hljs-comment"># Calculate the separator plane</span>
    z = (-w[<span class="hljs-number">0</span>] * scaled_grid[:, <span class="hljs-number">0</span>] - w[<span class="hljs-number">1</span>] * scaled_grid[:, <span class="hljs-number">1</span>] - b) / w[<span class="hljs-number">2</span>]
    z = z.reshape(xx.shape)
    z = scaler.inverse_transform(np.c_[xx.ravel(), yy.ravel(), z.ravel()])[:, <span class="hljs-number">2</span>].reshape(xx.shape)

    <span class="hljs-comment"># Plot the separating plane with adjusted transparency</span>
    surface = ax.plot_surface(xx, yy, z, alpha=<span class="hljs-number">0.3</span>, cmap=<span class="hljs-string">'coolwarm'</span>)

    <span class="hljs-comment"># Customize the plot</span>
    ax.set_xlabel(<span class="hljs-string">'X₁'</span>)
    ax.set_ylabel(<span class="hljs-string">'X₂'</span>)
    ax.set_zlabel(<span class="hljs-string">'X₁² + X₂²'</span>)
    ax.set_title(title)

    <span class="hljs-comment"># Add legend</span>
    ax.legend()

    <span class="hljs-comment"># Adjust the viewing angle for better visualization</span>
    ax.view_init(elev=<span class="hljs-number">20</span>, azim=<span class="hljs-number">45</span>)

    <span class="hljs-comment"># Add text description</span>
    ax.text2D(<span class="hljs-number">0.05</span>, <span class="hljs-number">0.95</span>, 
              <span class="hljs-string">"Polynomial Kernel Transformation:\nΦ(x₁,x₂) → (x₁,x₂,x₁²+x₂²)\n\nClasses are linearly separable\nin transformed space"</span>, 
              transform=ax.transAxes, 
              bbox=dict(facecolor=<span class="hljs-string">'white'</span>, alpha=<span class="hljs-number">0.8</span>))

    plt.show()

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    <span class="hljs-comment"># Generate and plot the dataset</span>
    X, y = generate_circle_data()

    <span class="hljs-comment"># Transform and plot 3D data with clear separator</span>
    X_transformed = transform_to_3d(X)
    plot_3d_transformation_with_separator(X_transformed, y)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    main()
</code></pre>
<p>The <code>main</code> function is a function of functions that put together all the other functions such as <code>generate_circle_data</code>, <code>transform_to_3d</code> and <code>plot_3d_transformation_with_separator</code> together to establish the model. The image below shows a better separation with the aid of the polynomial kernel.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734979669969/2e0af04a-93cc-44e8-8ed5-15a484385fd1.png" alt="2e0af04a-93cc-44e8-8ed5-15a484385fd1" class="image--center mx-auto" width="694" height="754" loading="lazy"></p>
<h3 id="heading-heres-the-full-code">Here’s the full code:</h3>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="f980d950df07000b6779e53641f13a4d">
        <script src="https://gist.github.com/Josiah-Adesola/f980d950df07000b6779e53641f13a4d.js"></script></div><p> </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned about the efficiency of SVM kernels for non-linear classification applications. The various functions demonstrated computational efficiency by changing input data into higher dimensional data, as shown in the example, without requiring vast amounts of storage or processing.</p>
<p>SVM can be used in a variety of classification tasks, including image and text classification, and it has proven to be extremely efficient.</p>
<h3 id="heading-references">References</h3>
<ol>
<li><p>Park, H., &amp; Son, J.-H. (2021). Machine learning techniques for THz imaging and time-domain spectroscopy. <em>Sensors, 21</em>(4), 1186. <a target="_blank" href="https://doi.org/10.3390/s21041186">https://doi.org/10.3390/s21041186</a></p>
</li>
<li><p><a target="_blank" href="https://scikit-learn.org/1.5/modules/svm.html">Scikit-learn developers. (2024). Support vector machines. Scikit-learn.https://scikit-learn.org/1.5/modules/svm.html</a></p>
</li>
</ol>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
