<?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 Osama Akhtar on Medium]]></title>
        <description><![CDATA[Stories by Osama Akhtar on Medium]]></description>
        <link>https://medium.com/@oakhtar147?source=rss-c8aa5da467a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4pANXJCmts_m0RY91kXDgA.jpeg</url>
            <title>Stories by Osama Akhtar on Medium</title>
            <link>https://medium.com/@oakhtar147?source=rss-c8aa5da467a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:28:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oakhtar147/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[Analyse Your Business Data With No Code Tool]]></title>
            <link>https://oakhtar147.medium.com/analyse-your-business-data-with-no-code-tool-6c4046f61225?source=rss-c8aa5da467a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c4046f61225</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Osama Akhtar]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 19:29:38 GMT</pubDate>
            <atom:updated>2024-12-03T19:29:38.335Z</atom:updated>
            <content:encoded><![CDATA[<p>For businesses of all sizes, the phrase “data-driven decisions” has become a mantra. But there’s a catch — analysing data is hard, especially if you’re not data analyst. Extracting meaningful insights from spreadsheets and databases often requires skills and effort.</p><p>Cells AI is a tool designed for small and medium businesses (SMBs), non-technical teams, and domain-specific professionals. It empowers anyone to analyze their data by simply asking questions in natural language, and receiving instant insights and visualisations — no technical expertise required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xyFJDiZtQPCQGFeQeFKdCw.png" /><figcaption>Overview of a Project in Cells AI. CSV files uploaded are shown on left, with rich visualisation and answers shown in the chat interface.</figcaption></figure><h4>How Does Cells AI Work?</h4><p>Cells AI transforms the way you interact with your data by combining natural language processing, automated SQL generation, and dynamic visualisations:</p><ol><li><strong>Upload Your Data:</strong> Start by uploading your Excel or CSV file — or connect to your database. Cells AI securely processes your data in seconds.</li><li><strong>Ask a Question:</strong> Type questions like, <em>“What were our top-performing products last quarter?”</em> or <em>“What’s the average customer retention rate?”</em></li><li><strong>Get Instant Insights:</strong> Cells AI processes your query, runs the necessary analysis, and presents <strong>accurate</strong> results — whether as charts, graphs, or tables.</li><li><strong>Export or Refine Results:</strong> Export insights, tweak queries, or dive deeper into your data as needed.</li></ol><p>With this simple workflow, Cells AI eliminates the technical barriers to data analysis, making powerful insights accessible to everyone in your organisation.</p><h4>Why Traditional Data Analysis Falls Short</h4><p><strong>Complexity: </strong>Most data tools expect users to know SQL or advanced analytics platforms like Tableau or Power BI. But not every team has access to those skills, leaving them dependent on overburdened analysts or IT support.</p><p><strong>Time Consuming: </strong>Manually creating charts, filtering data, or crafting SQL queries takes time, especially when exploring large datasets. For fast-paced teams, this delay can mean missed opportunities to act on emerging trends, improve performance, or respond to customer needs. With Cells AI, teams can focus on what’s important — getting insights — and not waste time thinking about how to extract them.</p><p><strong>Unaccessible: </strong>Even for those with technical know-how, juggling between tools like Excel, cloud databases, and visualization platforms can make data analysis frustrating and fragmented.</p><h4>How Cells AI Solves These Pain Points</h4><p><strong>1. Natural Language Queries: </strong>With Cells AI, you can ask questions about your data just like you would a teammate. For example:</p><ul><li><em>“What were the top 5 products sold last month?”</em></li><li><em>“Show me the trend of customer churn over the past 12 months.”</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j8LuzV8vp8MwXzHJu5uhPQ.png" /></figure><p><strong>2. Dynamic Visualizations: </strong>Not only do you get tables,<strong> </strong>Cells AI creates interactive charts, graphs, and dashboards tailored to your needs. With no extra effort, you can spot trends, patterns, and outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GNmK1ar0LYHlX7Kr" /></figure><h3>Real-World Use Cases</h3><p>Here are just a few ways businesses are using Cells AI to transform their workflows:</p><h3><strong>1. E-Commerce</strong></h3><ul><li><strong>Challenge:</strong> Understanding product performance across seasons.</li><li><strong>Solution:</strong> Cells AI provides instant sales breakdowns by category, time frame, and customer segment — no spreadsheets required.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WZKUBdBj7MT59BAd" /><figcaption>E-Commerce data for a store.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1Ofpz-pVG5prdd83" /><figcaption>Instead of focusing on deriving your thoughts into code/excel formulae, simply ask the question in your natural language. The explanation and conclusion section tell you how the answer is derived, so you can be sure it is accurate.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*koVBNzAvA-jGHF3q" /><figcaption>Get both, a tabular and chart visualisation to answer your question.</figcaption></figure><h3>2. Finance</h3><ul><li><strong>Challenge:</strong> Forecasting revenue and tracking KPIs.</li><li><strong>Solution:</strong> Cells AI generates forecasts and visualizations to help finance teams stay proactive.</li></ul><p>Dive into the behavioral insights behind investment choices.</p><p><strong>Case study</strong>: Understanding how gender and age influence investment preferences to create personalised financial products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IoSCfUbbSFBYgdaU" /><figcaption>Financial data to see what we are working with.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6oEafBkit8mdlNE4" /><figcaption>Ask a thought-provoking and generic question. Cells AI will make sensible assumptions with explanations, and lead you to its data driven conclusion.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zb4FIZOX_223w31A" /><figcaption>The resulting query, table, and pie chart show a very insightful answer to the original question — which was generic and not detailed.</figcaption></figure><h3>3. Customer Success</h3><ul><li><strong>Challenge:</strong> Identifying reasons behind churn.</li><li><strong>Solution:</strong> Cells AI highlights customer trends and potential issues, empowering teams to act before it’s too late.</li></ul><p>Discover how customer purchase behavior drives revenue growth.</p><p><strong>Case study:</strong> Using category-level revenue trends and purchase frequency insights to tailor marketing campaigns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oVQoIY9xe3Em9WBS" /><figcaption>The data we are working with.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1RCiwCk19F186oTE" /><figcaption>Asking a relative “number-heavy” and complex question containing two sub-questions.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k8IDRyCHYtqKnoJc" /><figcaption>Cells AI does a very good job at understanding and extracting the required analysis for the question.</figcaption></figure><h3>Why Cells AI Stands Out</h3><p>Cells AI prioritizes simplicity without sacrificing power.</p><ul><li><strong>No learning curve:</strong> Designed for anyone, not just data scientists.</li><li><strong>Customizable insights:</strong> Tailored to your industry and needs.</li><li><strong>Future-proof features:</strong> With upcoming domain-specific automations and integrations, Cells AI is built to evolve with your business.</li></ul><h3>Ready to Unlock Your Data?</h3><p>Cells AI is currently in beta and we’d love to onboard your business for free. This is more than just an early access program — we want to work directly with you to understand your unique challenges and build a solution that truly solves your problems.</p><p>Join us in shaping the future of simple, efficient, and powerful data analysis. From SMBs to e-commerce brands and finance teams, we’re redefining how businesses interact with their data — making insights fast, accessible, and actionable for everyone.</p><p>Start your journey today and see how Cells AI can empower your team to make smarter decisions, faster.</p><p><a href="https://usecells.com/">Cells AI</a> | <a href="https://www.linkedin.com/company/cells-ai">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c4046f61225" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pass and validate attributes passed to a script running in the browser]]></title>
            <link>https://oakhtar147.medium.com/pass-and-validate-attributes-passed-to-a-script-running-in-the-browser-d13d53aa024c?source=rss-c8aa5da467a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d13d53aa024c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[browsers]]></category>
            <dc:creator><![CDATA[Osama Akhtar]]></dc:creator>
            <pubDate>Thu, 20 Jun 2024 15:00:58 GMT</pubDate>
            <atom:updated>2024-06-20T15:04:11.310Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to pass data to a JavaScript script and validate it within the script.</h3><blockquote>You can read this and other related blog on my blog site: <a href="https://oakhtar.vercel.app/blog/validating-script-attributes">https://oakhtar.vercel.app/blog/validating-script-attributes</a></blockquote><p>We use &lt;script /&gt; tags to inject JavaScript code that runs on the browser. In some cases, we need to externally pass data to a script when it is being initialised and executed. Here’s how to pass data and then validate it inside the script.</p><h4>A/B Testing Example</h4><p>Imagine you have a script called ab-testing.js that is responsible for enabling one of two feature correlated flows within your application. We can expect a data- attribute which will determine which feature to show. For example:</p><pre>&lt;script src=&quot;./ab-testing.js&quot; data-variant=&quot;a&quot;&gt;&lt;/script&gt;</pre><p>It is now important that any client consuming your script passes the data-variant exactly either a or b.</p><p>So within the entry-point of your script, you can validate that.</p><pre>function getFeatureVariantOrThrow() {<br>  const script = document.currentScript<br>  const variant = script?.getAttribute(&quot;data-variant&quot;)<br><br>  if (!variant) {<br>    throw new Error(&quot;Please pass a data-variant attribute to the script tag&quot;)<br>  }<br><br>  if ([&quot;a&quot;, &quot;b&quot;].includes(variant)) {<br>    return variant<br>  }<br><br>  throw new Error(<br>    &#39;Invalid value for data-variant. Please pass either &quot;a&quot; or &quot;b&quot;&#39;<br>  )<br>}<br><br>const variant = getFeatureVariantOrThrow()</pre><p>With this, any application that uses your script in their &lt;head /&gt; will need to provide the correct data-variant as well. If not, they’ll see an error in the browser console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*ekj2clLKM_RBGp4Fb3Ctvg.png" /><figcaption>Browser displaying the error that our script throws</figcaption></figure><h4>Summary</h4><p>In this short article, we discussed a very specific use case of passing data- attributes to scripts and then validating them within the script.</p><p>Make sure to follow for more:</p><ol><li><a href="https://www.linkedin.com/in/osamakhtar/">LinkedIn</a></li><li><a href="https://github.com/oakhtar147">GitHub</a></li></ol><p>If you wish to see more content on full-stack engineering, make sure to like and follow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d13d53aa024c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your resume isn’t getting noticed; here’s why.]]></title>
            <link>https://oakhtar147.medium.com/your-resume-isnt-getting-noticed-here-s-why-c3b6e13ad034?source=rss-c8aa5da467a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3b6e13ad034</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[resume]]></category>
            <category><![CDATA[jobs]]></category>
            <category><![CDATA[job-hunting]]></category>
            <category><![CDATA[recruiting]]></category>
            <dc:creator><![CDATA[Osama Akhtar]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 22:07:46 GMT</pubDate>
            <atom:updated>2024-04-08T15:35:54.334Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This article is now added to my own blog site. To read more articles like this, please visit: <a href="https://oakhtar.vercel.app/">https://oakhtar.vercel.app/</a></blockquote><p>The demand for talent is high. There are so many talented experts and relatively very few talent recruiters. Your resume is completely ignored, and you receive an automated email that starts with “<em>unfortunately…”. </em>I’ve been there.</p><p><em>“But I was a decent fit!”.</em> Yes, you were, but no one looked at your resume.</p><p>Companies today use Applicant Tracking Systems (ATS) which automate the initial phase of talent hunting.</p><blockquote><a href="https://getfive.com/blog/eye-opening-facts-must-know-applicant-tracking-systems-ats/">75% of large companies use an ATS</a> because they receive <strong>thousands</strong> of applications every day.</blockquote><p>In simple terms, ATS extracts key information such as contact details, hard skills, work experience, and education. The talent recruiter sets this relevant information for each job posting. For example, for a Full Stack Engineer job post, some keywords are <em>Python</em>, <em>two years of experience</em>, <em>MERN, </em>etc. If your resume is relevant, your contact details will automatically be added to the recruiter’s database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J4XjQl5jlFQoEgZL" /><figcaption>Photo by <a href="https://unsplash.com/@joaoscferrao?utm_source=medium&amp;utm_medium=referral">João Ferrão</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You’re here probably because your resume cannot get past the ATS. So here are proven ways that you can pass it.</p><h4>Format your resume appropriately</h4><p>The structure of your resume matters a lot. If it cannot be parsed by the ATS, the system cannot collect or read data from your resume. Keep your recent experience on top. A readable font and a simple bullet point list layout are great. Nothing fancy. Label each section (e.g. Work Experience, or Skills) accurately. I recommend using an ATS template to make life easier. <a href="https://novoresume.com/resume-templates">Novoresume</a> has good templates.</p><h4>Use relevant keywords</h4><p>Tailor your resume for each application. You can extract keywords from the job description and add them to your resume when applying. Add tools and technologies under Skills, your degree in Education, and your experience in years. These small touches add relevancy to your resume. Your summary section can also be the deciding factor, so make sure it is impactful.</p><h4>Prefer .docx over .pdf</h4><p>The Word document preserves the original format and is the easiest for ATS to parse. Though newer ATS models parse PDF as well, but .docx file formats are the most reliable.</p><p>Finally, to test if your resume is ATS-compliant, test it using some software such as <a href="https://www.jobscan.co/">JobScan</a>.</p><h4>Some additional key points</h4><ol><li>I do not recommend adding your picture to remove unnecessary bias.</li><li>Use plain text instead of rich text.</li><li>Include as-is URLs (LinkedIn, GitHub) as is, as less capable models are not capable of parsing inline links. So prefer www.github.com/user instead of Github where the link is embedded.</li><li>Have a decent line height for legibility.</li></ol><p>Hopefully, these tips and insights help you tailor your resume. If you need further assistance, you can send me your resume on <a href="https://www.linkedin.com/in/osamakhtar/">LinkedIn</a> for review.</p><p>If you found this helpful, follow me on:</p><ol><li><a href="https://www.linkedin.com/in/osamakhtar/">LinkedIn</a></li><li><a href="https://twitter.com/_osamaakhtar">Twitter</a></li><li><a href="https://github.com/oakhtar147">GitHub</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3b6e13ad034" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sync Local Storage state across tabs in React using useSyncExternalStore]]></title>
            <link>https://medium.com/swlh/sync-local-storage-state-across-tabs-in-react-using-usesyncexternalstore-613d2c22819e?source=rss-c8aa5da467a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/613d2c22819e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Osama Akhtar]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 15:57:50 GMT</pubDate>
            <atom:updated>2024-08-02T22:34:51.681Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXUDaHdslT5Q%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXUDaHdslT5Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXUDaHdslT5Q%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/248b39b80e20682667213026f84defdd/href">https://medium.com/media/248b39b80e20682667213026f84defdd/href</a></iframe><blockquote>This article is now added to my own blog site. To read more articles like this, please visit: <a href="https://oakhtar.vercel.app/">https://oakhtar.vercel.app/</a></blockquote><p>Local storage is a good place used commonly to store data (not auth tokens though!) that needs to be persisted between sessions.</p><p>You can conveniently store user preferences like a collapsed or expanded sidebar in local storage. However, updates won’t sync across multiple tabs. To solve this, use the useSyncExternalStore hook in React to ensure consistent data across tabs.</p><p>From the <a href="https://react.dev/reference/react/useSyncExternalStore">official docs</a>:</p><blockquote>useSyncExternalStore is a React Hook that lets you subscribe to an external store.</blockquote><p>In our context, the <em>external store </em>refers to local storage. useSyncExternalStore allows us to bridge the gap between React and local storage by <em>subscribing</em> a component to local storage.</p><h4><strong>Example with </strong><strong>useState + useEffect</strong></h4><p>Let’s first see an example of a bad practice that does not work properly ❌:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*66Qjub7ZJjtKKoEzLrLNgQ.gif" /><figcaption>State is not synced across tabs and is inconsistent with local storage value</figcaption></figure><p>Code that’s used in the example above:</p><pre>import React from &quot;react&quot;;<br><br>type SidebarState = &quot;collapsed&quot; | &quot;expanded&quot;;<br><br>const get = () =&gt; localStorage.getItem(&quot;sidebar&quot;) as SidebarState;<br>const set = (value: SidebarState) =&gt; localStorage.setItem(&quot;sidebar&quot;, value);<br><br>if (!get()) {<br> set(&quot;collapsed&quot;);<br>}<br><br>function App() {<br> const [sidebarState, setSidebarState] = React.useState&lt;SidebarState&gt;(get());<br><br> React.useEffect(() =&gt; {<br>  set(sidebarState);<br> }, [sidebarState]);<br><br> const handleToggle = () =&gt;<br>  setSidebarState(sidebarState === &quot;collapsed&quot; ? &quot;expanded&quot; : &quot;collapsed&quot;);<br><br> return (<br>  &lt;&gt;<br>   &lt;p&gt;<br>    The sidebar is{&quot; &quot;}<br>    &lt;span style={{ color: sidebarState === &quot;collapsed&quot; ? &quot;red&quot; : &quot;green&quot; }}&gt;<br>     {sidebarState}<br>    &lt;/span&gt;<br>   &lt;/p&gt;<br>   &lt;button onClick={handleToggle}&gt;Toggle State&lt;/button&gt;<br>  &lt;/&gt;<br> );<br>}</pre><ol><li>We only use local storage as an initial state for React’s useState. This is needed to achieve reactivity, otherwise React won’t update the UI (re-render) on direct updates to local storage.</li><li>useState means the state is coupled with this component instance—which means it won’t sync across tabs.</li><li>Lastly, useState means we need to sync local storage with changes, so that the next time the app is loaded, we get the latest state that was set.</li></ol><h4>Example with useSyncExternalStore</h4><p>The correct way to do it 💪</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ADlWGBXMQtMaV371F_PElw.gif" /><figcaption>The state is synced and consistent with local storage across tabs and windows</figcaption></figure><p>Code that’s used in the example above:</p><pre>import React from &quot;react&quot;;<br><br>type SidebarState = &quot;collapsed&quot; | &quot;expanded&quot;;<br><br>function setSidebarState(newValue: SidebarState) {<br> window.localStorage.setItem(&quot;sidebar&quot;, newValue);<br> // On localStoage.setItem, the storage event is only triggered on other tabs and windows.<br> // So we manually dispatch a storage event to trigger the subscribe function on the current window as well.<br> window.dispatchEvent(<br>  new StorageEvent(&quot;storage&quot;, { key: &quot;sidebar&quot;, newValue })<br> );<br>}<br><br>const store = {<br> getSnapshot: () =&gt; localStorage.getItem(&quot;sidebar&quot;) as SidebarState,<br> subscribe: (listener: () =&gt; void) =&gt; {<br>  window.addEventListener(&quot;storage&quot;, listener);<br>  return () =&gt; void window.removeEventListener(&quot;storage&quot;, listener);<br> },<br>};<br><br>// Set the initial value.<br>if (!store.getSnapshot()) {<br> localStorage.setItem(&quot;sidebar&quot;, &quot;collapsed&quot; satisfies SidebarState);<br>}<br><br>function App() {<br> const sidebarState = React.useSyncExternalStore(<br>  store.subscribe,<br>  store.getSnapshot<br> );<br><br> const handleToggle = () =&gt; {<br>  setSidebarState(sidebarState === &quot;expanded&quot; ? &quot;collapsed&quot; : &quot;expanded&quot;);<br> };<br><br> return (<br>  &lt;&gt;<br>   &lt;p&gt;<br>    The sidebar is<br>    &lt;span style={{ color: sidebarState === &quot;collapsed&quot; ? &quot;red&quot; : &quot;green&quot; }}&gt;<br>     {sidebarState}<br>    &lt;/span&gt;<br>   &lt;/p&gt;<br>   &lt;button onClick={handleToggle}&gt;Toggle State&lt;/button&gt;<br>  &lt;/&gt;<br> );<br>}</pre><p>useSyncExternalStore accepts two <em>required </em>arguments:</p><ol><li>The subscribe function should subscribe to the store and return a function that unsubscribes. The listener argument in this function automatically listens to storage events and rerenders the component on changes.</li><li>The getSnapshot function should read a snapshot of the data from the store. To keep things simple, you should avoid returning immutable data (e.g. objects) since they are different on every getSnapshot invocation and will cause infinite re-renders. If you <em>need</em> to, you should cache the return value of getSnapshot.</li></ol><p>These two functions connect the data persisted in local storage to React, and allow reactivity across tabs and windows.</p><h4>Bonus: Extract the store to a custom hook</h4><p>Finally, you can extract the logic to a custom hook:</p><pre>import React from &quot;react&quot;;<br><br>type SidebarState = &quot;collapsed&quot; | &quot;expanded&quot;;<br><br>function useSidebarState() {<br> const setSidebarState = (newValue: SidebarState) =&gt; {<br>  window.localStorage.setItem(&quot;sidebar&quot;, newValue);<br>  window.dispatchEvent(<br>   new StorageEvent(&quot;storage&quot;, { key: &quot;sidebar&quot;, newValue })<br>  );<br> };<br><br> const getSnapshot = () =&gt; localStorage.getItem(&quot;sidebar&quot;) as SidebarState;<br><br> const subscribe = (listener: () =&gt; void) =&gt; {<br>  window.addEventListener(&quot;storage&quot;, listener);<br>  return () =&gt; void window.removeEventListener(&quot;storage&quot;, listener);<br> };<br><br> const store = React.useSyncExternalStore(subscribe, getSnapshot);<br><br> return [store, setSidebarState] as const;<br>}</pre><h4>Summary</h4><p>Today, we learned that the combination of useState and useEffect is not the ideal way to manage the state using data that lives in local storage. We can use local storage as an external store that communicates with React using useSyncExternalStore.</p><p><strong>Let’s Connect</strong></p><p>You can connect with me using the following links:</p><ol><li><a href="https://www.linkedin.com/in/osamakhtar/">LinkedIn</a></li><li><a href="https://github.com/oakhtar147">GitHub</a></li></ol><p>If you wish to see more content on full-stack engineering, make sure to like and follow to show your support! Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=613d2c22819e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/sync-local-storage-state-across-tabs-in-react-using-usesyncexternalstore-613d2c22819e">Sync Local Storage state across tabs in React using useSyncExternalStore</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Picking a Hyperparameter Tuning Library for Your Model]]></title>
            <link>https://medium.com/swlh/picking-a-hyperparameter-tuning-library-for-your-model-75220145bb47?source=rss-c8aa5da467a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/75220145bb47</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <dc:creator><![CDATA[Osama Akhtar]]></dc:creator>
            <pubDate>Sun, 13 Dec 2020 05:28:48 GMT</pubDate>
            <atom:updated>2020-12-15T21:05:01.220Z</atom:updated>
            <content:encoded><![CDATA[<p>It is unanimously agreed that model training is more about iterating and tweaking little knobs called hyperparameters to squeeze out the best from your model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*piUicH4fjz-atFEE" /><figcaption>Photo by <a href="https://unsplash.com/@willyin?utm_source=medium&amp;utm_medium=referral">yinka adeoti</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>. This picture has way fewer knobs to tweak than a typical deep learning model!</figcaption></figure><p>During the first three months of my machine learning journey, I quickly realized that I could not train a model that makes the most out of my data; I had to try thousands of different hyperparameter combinations and select the best model for myself.</p><p>At that moment, I knew about techniques like GridSearchCV from scikit-learn but I knew that it was not efficient and needed a lot of computing power and time. I needed a more efficient algorithm for keras; eventually, I stumbled upon two hyperparameter tuning libraries: <strong>aisaratuners</strong> and <strong>keras-tuner.</strong></p><p>In this article, I will compare both these libraries and report my findings so you can have a better idea of which library is for you!</p><p><strong>Aisaratuners </strong>library is a dynamic hyperparameter tuning library that tunes your model’s hyperparameters to give you the most optimized model with the best hyperparameters. Initially, it uses <a href="https://en.wikipedia.org/wiki/Latin_hypercube_sampling">Latin Hypercube Sampling</a>, a sophisticated statistical technique to pick hyperparameters, then uses its API for SOTA pattern recognition. In the end, you get the hyperparameters for the optimized model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*_JGinGj64PM3tyFwS-U8Ug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*uCgfxW1B51mB1Sh-me_a2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YeGp9o5WQYymhLj03bQjdw.png" /><figcaption>Fig. 1: How aisaratuners converges to the best hyperparameters. Source: <a href="https://aisaradeepwadi.medium.com/advance-keras-hyperparameter-tuning-with-aisaratuners-library-78c488ab4d6a">https://aisaradeepwadi.medium.com/advance-keras-hyperparameter-tuning-with-aisaratuners-library-78c488ab4d6a</a></figcaption></figure><p>Enough talking, let’s test the library to see if it actually gets the job done.</p><p>We will use the Fashion MNIST dataset since it is easy to work with and is still slightly difficult to get 90%+ validation accuracy. To keep this article concise, I will only include code relevant to the library and not include the code for loading and preprocessing data. You can refer to the notebooks at the end of this article.</p><p>We will train a rather simple but <em>dynamic</em> model, with the help of aisaratuners library. Here we go.</p><p>To get started, we need to pip install the package:</p><pre>!pip install aisaratuners # pip install using a jupyter notebook</pre><p>We only need two imports from aisaratuners library to get started, yes, it is that simple!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2335165619fea5dd580ec1fdfbf11343/href">https://medium.com/media/2335165619fea5dd580ec1fdfbf11343/href</a></iframe><p>Now comes the fun part, we get to decide which hyperparameters we get to tune <em>dynamically</em> for our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b07261781c54fd32db8e821cb98cd3f0/href">https://medium.com/media/b07261781c54fd32db8e821cb98cd3f0/href</a></iframe><p>We instantiate our Hp object which is a container for all the hyperparameters we wish to tune. You can set min/max ranges, as well.</p><p>Next, in a function containing our model, we will include the Hp object and all the ranges we have defined:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7e6bc40cb882df5445f9f3f2c696d00/href">https://medium.com/media/f7e6bc40cb882df5445f9f3f2c696d00/href</a></iframe><p>One thing I like while working with aisaratuners was the fact that I had to introduce minimal and understandable changes to the model. We just need to use the Hp object we created and access any random number we set in the <em>numrange</em> method in the above cell.</p><p>Let’s now run the optimizer and see how the algorithm performs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9d049ef91f34152113d0f8c17b61b1e/href">https://medium.com/media/b9d049ef91f34152113d0f8c17b61b1e/href</a></iframe><p>We have set 3 rounds, each with 5 trials. This means in any round, the algorithm will sample 5 sets of hyperparameters from the solution space and train models. This is depicted in Fig. 1 above. In each round, the model will try to reduce this solution space. Also, we have set two criteria, one to maximize the validation accuracy and one to minimize validation loss. The mode argument is set to ‘p’ to use the free available API for aisaratuners to function. You could use a commercial API to use as well. Find more information <a href="https://rapidapi.com/aisara-technology-aisara-technology-default/api/aisara-hyperparameter-tuning">here</a>.</p><blockquote>It took me 889.84 seconds to run this optimization.</blockquote><p>Please note that this time will vary for everyone and I was running the optimization using Google Colab, which has a variety of GPUs.</p><p>It took me less than 15 minutes (14.81) minutes to acquire the best model. That is amazing. It usually would take me at least two hours of <strong><em>manual tuning</em></strong><em>. </em>Instead, we<strong> <em>automatically tuned</em></strong><em> </em>for the best model using aisaratuners in much less time.</p><p>Here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_M7C-ZQ7mGiZEXZCcnfkNQ.png" /><figcaption>Fig. 2: Round 1: Orange, Round 2: Green, Round 3: Yellow</figcaption></figure><p>The five trials of each round are labeled. My findings were:</p><blockquote><strong>Orange: </strong>Some variance (e.g. 48% validation accuracy) in the first round, but overall, the accuracies were definitely in the higher region. This is impressive! Aisaratuners algorithm did well in initial sampling.</blockquote><blockquote><strong>Green: </strong>In the second round, the search space was reduced well enough because all the models were now achieving 90%+ validation accuracies.</blockquote><blockquote><strong>Yellow:</strong> Even now, when typically I would stop trying to achieve better results, aisaratuners still managed to squeeze a one per cent increase on the validation set.</blockquote><p>This was exactly what I needed: an automatic hyperparameter tuner. What exceeded my expectations were the visualizations this library provided me with. The above information can be visualized in a <em>picture-worth-a-thousand-words </em>manner. Interactive visualizations are labeled in the captions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*yiZTMkdzrZYtr81yUGKuzw.png" /><figcaption>(Interactive) Infer how in each round the validation accuracy is increasing.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*iH-raTKItsxNMKsH80WGBw.png" /><figcaption>(Interactive) Infer how in the second and third round the variance in the accuracy is becoming negligible. Thus, the tuner has achieve the best model with the range of each hyperparameter you specified</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9c6Ss1QECHxO4YudjD_iqQ.png" /><figcaption>A dynamic overview of the optimization.</figcaption></figure><p>This image gives you a sense of what the optimizer did under the hood. The regions where the lines are dense indicates the best value in the specified range for that hyperparameter. For example, aisaratuners knows that the best number of convolutional filters is 150 and the optimum learning rate for the model is around 0.0001454. How cool is that!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f34J1NDHJ468xifgHrld2w.png" /><figcaption>(Interactive) This visualization also captures the convergence of each hyperparameter to its best value in the range during the rounds.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KEGoKybWORb6SwQBeurMmA.png" /><figcaption>(Interactive) 3D visualization of the solution space and the trails. Notice how at high validation accuracies, the trials get closer to the surface indicating the excellent algorithm behind this tuner.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d904a0534d7e9c99053aac8ecd7496e7/href">https://medium.com/media/d904a0534d7e9c99053aac8ecd7496e7/href</a></iframe><p>That concludes our tutorial for aisaratuners. As with all things, there are some improvements I would suggest:</p><ul><li>Including step size to the range functions will allow for more control of ranges</li><li>Including Boolean customizability to have control over things like optimizer choice (SGD, Adam, RMSProp, etc.)</li><li>Add the ability to conduct one trial multiple times. Usually, a model has a slight (2% or so) variance in the accuracy, multiple executions will make sure you can take an average of the accuracies. Sure, this will slow the optimization process but will make the results much more accurate. I think this tradeoff is sometimes worth it.</li><li>Creating well-formatted, easy-to-use documentation.</li></ul><p>Aisaratuners definitely worked as claimed, the model I got was accurate and the visualizations were great. But let’s compare its algorithm with <strong>keras-tuner.</strong></p><p>Keras-tuner is also a hyperparameter tuning library specifically made for keras. One of the most popular algorithms is RandomSearch.</p><ul><li><strong>RandomSearch</strong> is the basic way of testing out different hyperparameter combinations. It randomly samples hyperparameters and tries to converge on the best model. This is still better than grid search, though.</li></ul><p>You require Python 3.6 and Tensorflow 2.0 for keras-tuner to work.</p><pre>!pip install keras-tuner</pre><p>All code relevant to the library is shared. The rest of the code can be found linked at the end of the article.</p><p>Syntactically, both the libraries are very similar. I will try my best to tune to the same hyperparameters as I did using aisaratuners, and also make sure to keep the number of trials and epochs the same. I want the comparison to be fair.</p><p>Without further ado, let’s dive into the code. Let’s install the dependencies and set the log directory first:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6de8cc8448bcce5572da797076a1f15/href">https://medium.com/media/c6de8cc8448bcce5572da797076a1f15/href</a></iframe><p>Unlike aisaratuners, you do not need to contain all our hyperparameters in a <em>predefined </em>container object. Instead, you simply create a model function and make it dynamic as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/048c5a6a6baf7e9fba3f9998e2831296/href">https://medium.com/media/048c5a6a6baf7e9fba3f9998e2831296/href</a></iframe><p>The syntax is very similar, although keras-tuner does give you a step option. I find that helpful.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8b43ba0527f5bb218d532b1dd7fe4b6/href">https://medium.com/media/b8b43ba0527f5bb218d532b1dd7fe4b6/href</a></iframe><p>Since keras-tuner does not include the ability to set rounds and trials as aisaratuners has, I have set the number of trials to 15 (equal to total trials aisaratuners had in three rounds of five trials each). This also makes sense since the keras-tuner tuning algorithm is random and cannot intelligently reduce the search space in each round. Furthermore, I like the ability to conduct multiple executions per trail to reduce variance in each trial’s result; however, we are going to keep that at 1, so as to produce the fairest conditions.</p><p>Not that we have instantiated the tuner, let’s see it in action.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af084010becd1faf45f48bd48dd04f3b/href">https://medium.com/media/af084010becd1faf45f48bd48dd04f3b/href</a></iframe><blockquote>It took me 1162.78 seconds to complete this optimization.</blockquote><p>Please note that this time will vary for everyone and I was running the optimization using Google Colab, which has a variety of GPUs. For the comparisons, I made sure I was using Google Colab’s Tesla T4 GPU instance. You can always check your GPU instance in Colab using !nvidia-smi . In case you need a different GPU instance, you can factory reset your GPU runtime.</p><p>So, 19.38 minutes. 15 trials. Not bad, not great, either. Compared to aisaratuners which took 14.81 minutes, keras-tuner completed the optimization much slower. But maybe, it has converged to a better validation accuracy? How much better should the validation accuracy be to compensate for increased optimization time?</p><p>It turns out, keras-tuner did get a better validation accuracy — only by 0.27%. One thing I did not like about keras-tuner’s algorithm is that it was unpredictable. For instance, in the seventh trial, one can achieve 92% validation accuracy and in the tenth trial, it could be around 73%. There was not a converging trend as in aisaratuners results (shown in Fig. 2). One would not be exactly sure whether one has got the best hyperparameters mid-way through the optimization process. In other words, had I started this comparison with keras-tuners instead of aisaratuners, no doubt it would have taken me longer. I would then not stop at 15 trials since I did not know if the tuner had reached the highest accuracy due to lack of convergence or ease of visualization.</p><p>Here is how you get the summary of results, get the best model’s hyperparameters or get the best model itself:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4b4e3613671bdb6dd84bee974a9297b/href">https://medium.com/media/f4b4e3613671bdb6dd84bee974a9297b/href</a></iframe><p>I cannot show the output of tuner.results_summary() since it was poorly formatted. You can always view the notebook shared at the end of the article.</p><p>You can also produce some visualizations using keras-tuner of the tuning process; however, they are complicated to produce. They require using TensorBoard and make use of the logs directory.</p><p>I would like to pass on some remarks about keras-tuner before making a final verdict. These are:</p><ul><li>I believe it cannot work with Python &gt; 3.6. With Python 3.9 out, keras-tuner should make sure their library is compatible with the later versions of Python.</li><li>Make the visualizations easier to produce, at least initially. This will allow for much easier iterations.</li><li>Improve the output of tuner.results_summary() . With no convenient visualizations to look at, it was very troublesome to read the summary in poorly formatted output.</li></ul><p>keras-tuner also provides pre-made tunable models, but they are not within the scope of this article.</p><p>That concludes our comprehensive comparison of the two libraries. We looked at their somewhat different syntax. Using each library, we trained a very similar convolutional neural network on the Fashion MNIST dataset to record the optimization results and the time it took for the algorithms to complete the optimization.</p><p>In the end, I chose to stick with the aisaratuners library. I recommend this library because it is much easier to configure, and runs on Python ≥ 3.6. It optimizes faster and the interactive visualizations make the tuning process easy to grasp and more fun. If my suggestions are implemented into their library, it would only make things better.</p><p>Let me know what you think down in the comments! :)</p><p>Follow me on Medium and <a href="https://www.github.com/oakhtar147">GitHub</a> for more content.</p><p>The notebooks for either library can be found on GitHub <a href="https://github.com/oakhtar147/hyperparameter-tuning">here</a>.</p><p>Check out the libraries on GitHub:</p><ul><li><a href="https://github.com/aisara-hub/aisaratuners">Aisaratuners</a></li><li><a href="https://github.com/keras-team/keras-tuner">keras-tuner</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75220145bb47" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/picking-a-hyperparameter-tuning-library-for-your-model-75220145bb47">Picking a Hyperparameter Tuning Library for Your Model</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The GitHub Student Developer Pack]]></title>
            <link>https://medium.com/swlh/the-github-student-developer-pack-aadde59290ff?source=rss-c8aa5da467a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/aadde59290ff</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[github-education]]></category>
            <category><![CDATA[github-student]]></category>
            <dc:creator><![CDATA[Osama Akhtar]]></dc:creator>
            <pubDate>Sat, 26 Sep 2020 07:18:30 GMT</pubDate>
            <atom:updated>2024-04-08T15:36:24.717Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This article is now added to my own blog site. To read more articles like this, please visit: <a href="https://oakhtar.vercel.app/">https://oakhtar.vercel.app/</a></blockquote><p>You might be a programming enthusiast who just got accepted in your dream college or you might even have spent a good year or two in computer science discipline and barely know about <a href="https://github.com/">GitHub</a>.</p><p>GitHub is a <a href="https://en.wikipedia.org/wiki/Version_control"><strong>version control</strong></a> where code lives. It is where people share their hard work for others to see and contribute to. It is used by companies like Google, Microsoft amongst many others to maintain their codebase.</p><p>But to a student it provides much more than that. GitHub has a Student Developer Pack which they provide to students. This pack includes benefits worth a whopping $200k!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3jAYkhce-e508wiApFC0VA.png" /></figure><h4>How do I apply?</h4><p>This program requires you to:</p><ol><li>Be a student having a GitHub account;</li><li>13+ years old.</li><li>Be in any degree-granting program that isn’t restricted by the institution’s accreditation.</li><li>Provide an evidence of your being a student. This could be your school issued email-address, your school ID card or any other form of documentation.</li></ol><p>If you check out these requirements, you are all in for it! You just need to <a href="https://education.github.com/pack">apply for the pack</a>. You will be asked to fill out a short form where you will be asked basic information including an image of your academic status (ID card, for instance). <strong>It is necessary that you fill valid information and upload a clear, decipherable image, or else you could risk getting rejected </strong>(see <a href="https://docs.github.com/en/free-pro-team@latest/github/teaching-and-learning-with-github-education/why-wasnt-my-application-for-a-student-developer-pack-approved">this</a> to avoid getting rejected).</p><h4><strong>Okay, but why should I apply?</strong></h4><p>This is the exciting part. When I found about the Student Pack, I was overwhelmed by the developer tools I was going to get — for free!</p><p>Ranging from developer tools to productivity, GitHub is committed to give facilities to students that will help them learn, be more productive with their time and get acquainted with technologies, technologies that a college student does not usually have the budget to afford.</p><p>The program also includes free subscriptions (either limited or unlimited) to educational sites like AWS Educate and DataCamp. This provides them an opportunity to introduce themselves to new and trending sub-disciplines of software, and potentially master them!</p><p>So if you dream of becoming a game developer, a web developer or a designer, you cannot miss this pack. You can view the details of the tools provided by this program <a href="https://education.github.com/pack#offers">here</a>.</p><h4>Sounds interesting, does the program expire?</h4><p>Yes, this program is only for students and will expire after <strong>two years</strong> since the day of acceptance. But you can always renew your subscription if you are still a student!</p><h4>I am amazed, what else does GitHub offer me?</h4><p>The Student Developer Pack is definitely A large chunk of the benefits they provide students, but other significant incentives are also included:</p><h4><strong>1. GitHub Campus Expert Program:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*g89UciDPBWDy39zR1oWo2A.png" /></figure><p>If you feel the need to lead a team to promote tech in your local campus by carrying out workshops and hackathons, this program would make you capable of doing so. It has a dedicated training that helps you improve your skills like public speaking, leadership etc. Read this <a href="https://mjunaidkhalid.com/2020/09/07/github-campus-expert-program-how-to-become-one/">article by a GitHub Campus Expert</a> to get valuable insights about this program.</p><h4>2. Throw a hackathon or a small event at your college:</h4><p>GitHub can help you ship a 1000$ grant through their links with <a href="https://mlh.io/">Major League Hacking (MLH)</a>. This can either be a massive hackathon or a small workshop.</p><h4>3. GitHub Pro</h4><p>GitHub Pro would allow you additional features when using GitHub. These features are tech-y and not what I would like to share here. You can always read about them in their <a href="https://docs.github.com/en/free-pro-team@latest/github/getting-started-with-github/githubs-products#github-pro">documentation</a>. Oh yes, amongst many other benefits you get with GitHub Pro, you also get to boast about a Pro Badge on your GitHub profile!</p><p>To conclude, the GitHub Student benefits are something you should harness immediately. These incentives will definitely make your work more productive and fun. What do you like the most about this program? Let me know in the comments!</p><p>Be sure to follow me on Medium as well as <a href="https://github.com/oakhtar147">GitHub</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aadde59290ff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/the-github-student-developer-pack-aadde59290ff">The GitHub Student Developer Pack</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intuitive Explanation for Principle Component Analysis (PCA), From Scratch.]]></title>
            <link>https://medium.com/swlh/intuitive-explanation-for-principle-component-analysis-pca-from-scratch-157a1b162f1f?source=rss-c8aa5da467a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/157a1b162f1f</guid>
            <category><![CDATA[principal-component]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Osama Akhtar]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 15:59:01 GMT</pubDate>
            <atom:updated>2024-04-09T15:22:27.336Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intuitive Explanation for Principle Component Analysis (PCA), in Six Minutes.</h3><blockquote>This story is now a part of my blogsite: <a href="https://oakhtar.vercel.app/blog/principle-component-analysis">https://oakhtar.vercel.app/blog/principle-component-analysis</a>. Give it a read.</blockquote><p>Principle Component Analysis (PCA) is arguably a very difficult-to-understand topic for beginners in machine learning. Here, I will try my best to intuitively explain what it is, how the algorithm does what it does. This post assumes you have very basic knowledge of Linear Algebra like matrix multiplication, and vectors.</p><h3>What is PCA?</h3><p>PCA is a dimensionality-reduction technique used to make large datasets with hundreds of thousands of features into smaller datasets with fewer features while retaining as much information about the dataset as possible.</p><p>A perfect example would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-fJbynEC33x1ZOfFdHptQ.png" /></figure><p>Notice that in the original dataset there were five features which could be reduced to two features. These two features <em>generalize </em>the features on the left.</p><h3>Visualizing the idea of PCA.</h3><p>To make a picture of what’s happening, we use our previous example. A 2-dimensional plane showing the correlation of size to number of rooms in a house can be compressed to a single size feature, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sf9_7_N7oB9h54tOhmMMMg.png" /></figure><p>If we <em>project</em> the houses on the black line, we would get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwOO7BYpaDfPREQ5Xs6Btg.png" /></figure><p>So we need to reduce that projection error (the magnitude of blue lines) in order to retain maximum information.</p><h3>Prerequisites to understanding the PCA Algorithm.</h3><p>I will explain some concepts intuitively in order for you to understand the algorithm better.</p><h4>Mean</h4><p>Mean of any dataset refers to the equilibrium of the dataset. Imagine a rod on which balls are placed at some distance <em>x</em> from the wall:</p><figure><img alt="mean" src="https://cdn-images-1.medium.com/max/1024/1*4X8saDi_Zr7C-nv6X6rKzA.png" /></figure><blockquote>Summing the distance of the balls from the wall and dividing by the number of balls results the point of equilibrium, where a pivot would balance the rod.</blockquote><h4>Variance</h4><p>Mean tells us about the equilibrium of the dataset, variance is a metric that tells us about the spread of dataset from its mean. In 1-dimensional dataset, variance can be illustrated as:</p><figure><img alt="variance in one dimension" src="https://cdn-images-1.medium.com/max/1024/1*vGtjLTkJYP-8A0WmKHe4Mw.png" /></figure><blockquote>We take the square of each distance so we do not get any negative values!</blockquote><p>For 2-dimensional dataset, just take the variance after projecting it on each axis (shown later).</p><h4>Covariance</h4><p>In two and higher dimensional two very different datasets could have same variance, leading to misinterpretations of data. For example, both the datasets below have the same variance even though they are entirely different.</p><figure><img alt="variance-intuition" src="https://cdn-images-1.medium.com/max/1024/1*VZ6SGiLJfaFpP6WOv3Lc5A.png" /></figure><blockquote>Notice that the variance is same for both entirely different datasets. Also note how x-variance and y-variance are calculated by projecting the data on each axis.</blockquote><p>Covariance depicts the correlation of dataset. It is a quantity describing the variance as well as the direction of the spread. This will help us distinguish between the above two datasets.</p><figure><img alt="convariance-intuition" src="https://cdn-images-1.medium.com/max/1024/1*qwMVx3u6wluUO61df9lhWQ.png" /></figure><blockquote>To get the covariance simply add the <strong><em>product of coordinates</em></strong> of each point. For example in red dataset. (-2, -1) results in 2 and so does (2, 1).</blockquote><p>The covariance matrix is a linear transformation that transforms given data into another shape. We will see that later. In 2D, this matrix is (2 x 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mo-x2ZZ8F237iEZjjtpjg.png" /></figure><p>For the dataset in the example above, after inserting values, a rough estimate of the covariance matrix would be the one shown. To understand the use of this matrix we first need to understand linear transformations.</p><blockquote>A linear transformation is a mapping that <strong>transforms</strong> any point in the 2D plane to another point in the same plane by using a <strong>transformation matrix.</strong></blockquote><p>Back to our example, the covariance matrix is our transformation matrix. A unit circle would be transformed into an ellipse by the covariance matrix (using matrix multiplication) as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*APps8p5t3GPP3xDg8OCXWQ.png" /></figure><p>This transformation gives us two very special vectors — the <strong>eigenvectors.</strong></p><p>These eigenvectors are special because they are not affected by the transformation (their direction remains the same), they are only increased in magnitude. Below are the two vectors in red and teal color.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q8RqJCKlr0Lcmlw5eGrCBA.png" /></figure><p>Speaking abstractly, these are the vectors on which we shall project our data, that would help us reduce the dimensions.</p><blockquote>The question is: which eigenvector to choose?</blockquote><p>Let me tell you, you are an intelligent person if you chose the red one, because I myself had absolutely no clue!</p><p>Red is the better choice because it would retain maximum variance of the original dataset, which means maximum information is retained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3a77HufPLUqxdXclewd5w.png" /><figcaption>Imagine you had picked the other eigenvector. Projecting the data would cause most of the points to overlap each other, and you will thus lose information. This is because the x-variance is greater than the y-variance.</figcaption></figure><h3>The interesting part: the code!</h3><p>We will apply the algorithm on word embeddings, which is a very high dimensional vector representation of, well, words. The TensorFlow visualization for 10,000 words in 200 dimensions is something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i7_8Ozh56q5yI7ITGSNltA.png" /><figcaption>source: <a href="http://projector.tensorflow.org/">http://projector.tensorflow.org/</a></figcaption></figure><p>We will use a dataset with embeddings in 300 dimensions instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80UkkKchwavTtzKUXMYb9g.png" /><figcaption>How our dataset is arranged.</figcaption></figure><p>The process is as follows:</p><ol><li>Demean the data (center it, so each feature has zero mean);</li></ol><pre>def compute_pca(X, n_components=2):<br>    &quot;&quot;&quot;<br>    Input:<br>        X: of dimension (m,n) where each row corresponds to a word vector<br>        n_components: Number of components you want to keep.<br>    Output:<br>        X_reduced: data transformed in 2 dims/columns + regenerated original data<br>    &quot;&quot;&quot;</pre><pre>    # mean center the data (axis=0 because taking mean along columns)<br>    X_demeaned = X - np.mean(X, axis=0, keepdims=True) # normalize each feature of dataset</pre><p>2. Compute the covariance matrix;</p><pre># calculate the covariance matrix, rowvar=False because our features are in columns, not rows<br>    covariance_matrix = np.cov(X_demeaned, rowvar=False)</pre><p>3. Compute and sort the eigenvectors and eigenvalues from highest to lowest magnitude (eigenvalues), remember we need high eigenvalue eigenvectors so as to retain maximum variance (information) of our word embeddings.</p><pre>    # calculate eigenvectors &amp; eigenvalues of the covariance matrix,           both are returned in ascending order<br>    eigen_vals, eigen_vecs = np.linalg.eigh(covariance_matrix)</pre><pre>    # sort the eigen values (highest - lowest)<br>    eigen_vals_sorted = np.flip(eigen_vals)<br>    <br>    # sort eigenvectors (highest - lowest)<br>    eigen_vecs_sorted = np.flip(eigen_vecs, axis=1)</pre><p>4. Select the <em>n</em> eigenvectors corresponding to the eigenvalues in descending order.</p><pre>    # select the first n eigenvectors (n is desired dimension<br>    # of rescaled data array, or dims_rescaled_data), each      eigenvector is a column in eigen_vecs matrix.</pre><pre>    eigen_vecs_subset = eigen_vecs_sorted[:, :n_components]</pre><p>5. Multiply this subset of eigenvectors by the demeaned data to get the transformed data!</p><pre>   # transform the data by multiplying the demeaned dataset with the    first n eigenvectors</pre><pre>    X_reduced = np.dot(X_demeaned, eigen_vecs_subset)<br>    return X_reduced</pre><h4>Let’s visualize!</h4><p>Let’s try this algorithm on some data.</p><pre>words = [&#39;oil&#39;, &#39;gas&#39;, &#39;happy&#39;, &#39;sad&#39;, &#39;city&#39;, &#39;town&#39;,<br>         &#39;village&#39;, &#39;country&#39;, &#39;continent&#39;, &#39;petroleum&#39;, &#39;joyful&#39;] #11 words</pre><pre># given a list of words and the embeddings, it returns a matrix with all the embeddings<br>X = get_vectors(word_embeddings, words)<br>X.shape # returns (11, 300)</pre><p>Applying our algorithm to reduce from 300 dimensions to 2 dimensions!</p><pre># We have done the plotting for you. Just run this cell.<br>result = compute_pca(X, 2)<br>plt.figure(figsize=(12,8))<br>plt.scatter(result[:, 0], result[:, 1])<br>for i, word in enumerate(words):<br>    plt.annotate(word, xy=(result[i, 0] - 0.05, result[i, 1] + 0.1), )</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*7PBQRUcv77EfC2w9OkyZKA.png" /></figure><blockquote>Takeaway: words that express emotions (sad, joyful, happy) are close to each other, town/village/city are close to each other as well, this is because they are highly related!</blockquote><p>Now we have reduced 300 dimension embeddings to 2 dimension embeddings! That is why we can visualize it!</p><p>I hope I explained everything is a friendly and easy manner :)</p><p>See you soon!</p><p>Note: All the slides shown in this article belong to a YouTube channel Luis Serrano. His video explaining PCA was amazing and here’s a link to his channel: <a href="https://www.youtube.com/channel/UCgBncpylJ1kiVaPyP-PZauQ">https://www.youtube.com/channel/UCgBncpylJ1kiVaPyP-PZauQ</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=157a1b162f1f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/intuitive-explanation-for-principle-component-analysis-pca-from-scratch-157a1b162f1f">Intuitive Explanation for Principle Component Analysis (PCA), From Scratch.</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>