<?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 Abhishek Kumar on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Kumar on Medium]]></description>
        <link>https://medium.com/@abhieshekumar?source=rss-e1245ce379ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dXAvGSaOnysWxysYRvd80Q.png</url>
            <title>Stories by Abhishek Kumar on Medium</title>
            <link>https://medium.com/@abhieshekumar?source=rss-e1245ce379ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 09:31:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhieshekumar/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[Engineering the Stream: A Frontend Guide to LLM Interfaces]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://blog.stackademic.com/engineering-the-stream-a-frontend-guide-to-llm-interfaces-f2053bcbf514?source=rss-e1245ce379ff------2"><img src="https://cdn-images-1.medium.com/max/2600/0*5hcLzrubMsJNlwHG" width="2600"></a></p><p class="medium-feed-snippet">SSE, Generative UI, Schema validation, Security boundaries, and Error recovery &#x2014; the engineering decisions that matter.</p><p class="medium-feed-link"><a href="https://blog.stackademic.com/engineering-the-stream-a-frontend-guide-to-llm-interfaces-f2053bcbf514?source=rss-e1245ce379ff------2">Continue reading on Stackademic »</a></p></div>]]></description>
            <link>https://blog.stackademic.com/engineering-the-stream-a-frontend-guide-to-llm-interfaces-f2053bcbf514?source=rss-e1245ce379ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2053bcbf514</guid>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[agentic-applications]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Abhishek Kumar]]></dc:creator>
            <pubDate>Tue, 24 Mar 2026 09:07:09 GMT</pubDate>
            <atom:updated>2026-03-24T09:07:09.444Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[The Fault]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/new-literary-society/the-fault-3f636c654898?source=rss-e1245ce379ff------2"><img src="https://cdn-images-1.medium.com/max/2600/0*0mnXklbQUoyi5Hzb" width="2600"></a></p><p class="medium-feed-snippet">The lie was the kindest part.</p><p class="medium-feed-link"><a href="https://medium.com/new-literary-society/the-fault-3f636c654898?source=rss-e1245ce379ff------2">Continue reading on NEW LITERARY SOCIETY »</a></p></div>]]></description>
            <link>https://medium.com/new-literary-society/the-fault-3f636c654898?source=rss-e1245ce379ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f636c654898</guid>
            <category><![CDATA[fiction]]></category>
            <category><![CDATA[short-story]]></category>
            <category><![CDATA[creative-writing]]></category>
            <category><![CDATA[mystery]]></category>
            <category><![CDATA[new-literary-society]]></category>
            <dc:creator><![CDATA[Abhishek Kumar]]></dc:creator>
            <pubDate>Sun, 22 Mar 2026 16:31:00 GMT</pubDate>
            <atom:updated>2026-03-22T16:31:00.446Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Prawaas]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/new-literary-society/prawaas-fe0b4b7079f6?source=rss-e1245ce379ff------2"><img src="https://cdn-images-1.medium.com/max/2000/0*Kdsm8-2l7nWYrsB-" width="2000"></a></p><p class="medium-feed-snippet">A journey of routine and memory.</p><p class="medium-feed-link"><a href="https://medium.com/new-literary-society/prawaas-fe0b4b7079f6?source=rss-e1245ce379ff------2">Continue reading on NEW LITERARY SOCIETY »</a></p></div>]]></description>
            <link>https://medium.com/new-literary-society/prawaas-fe0b4b7079f6?source=rss-e1245ce379ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe0b4b7079f6</guid>
            <category><![CDATA[creative-writing]]></category>
            <category><![CDATA[short-story]]></category>
            <category><![CDATA[storytelling]]></category>
            <category><![CDATA[fiction]]></category>
            <category><![CDATA[new-literary-society]]></category>
            <dc:creator><![CDATA[Abhishek Kumar]]></dc:creator>
            <pubDate>Wed, 18 Mar 2026 17:26:21 GMT</pubDate>
            <atom:updated>2026-03-21T19:30:40.570Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Perspective]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://short.sweet.pub/perspective-83c017af009b?source=rss-e1245ce379ff------2"><img src="https://cdn-images-1.medium.com/max/2600/0*zQqMqITdamO7bClD" width="7295"></a></p><p class="medium-feed-snippet">A teeny tiny possibility that what you see, depends on where you stand.</p><p class="medium-feed-link"><a href="https://short.sweet.pub/perspective-83c017af009b?source=rss-e1245ce379ff------2">Continue reading on Short. Sweet. Valuable. »</a></p></div>]]></description>
            <link>https://short.sweet.pub/perspective-83c017af009b?source=rss-e1245ce379ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/83c017af009b</guid>
            <category><![CDATA[short-read]]></category>
            <category><![CDATA[anecdotes]]></category>
            <category><![CDATA[funny]]></category>
            <category><![CDATA[short-story]]></category>
            <dc:creator><![CDATA[Abhishek Kumar]]></dc:creator>
            <pubDate>Sat, 11 Oct 2025 12:01:43 GMT</pubDate>
            <atom:updated>2025-10-11T12:01:43.266Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Build a React Hook for Fetching Data]]></title>
            <link>https://javascript.plainenglish.io/build-a-react-hook-for-fetching-data-262aabcf9d7e?source=rss-e1245ce379ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/262aabcf9d7e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Abhishek Kumar]]></dc:creator>
            <pubDate>Wed, 19 Jan 2022 08:18:16 GMT</pubDate>
            <atom:updated>2022-01-19T08:18:16.805Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s hook it up!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FY0XFiURQPLjRE6no5b2Fg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@taylor65s?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Taylor Beach</a> on <a href="https://unsplash.com/s/photos/hook?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Hooks have changed the way React is used. One of the things hooks enable is code reusability. Many prominent libraries such as <a href="https://reactrouter.com/">react-router</a>, <a href="https://react-query.tanstack.com/">react-query</a> embrace hooks for the better. Another thing about hooks is that they are composable. You can use basic hooks such as <a href="https://reactjs.org/docs/hooks-reference.html#usestate">useState</a> and <a href="https://reactjs.org/docs/hooks-reference.html#useeffect">useEffect</a> to write your own custom hooks and reuse them in your application.</p><p>Today we are going to write a hook for one such common scenario of fetching data. Without any further delay let’s look at the hook right away —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f100d091d4eb189fc72b827462b8ca20/href">https://medium.com/media/f100d091d4eb189fc72b827462b8ca20/href</a></iframe><p>Let us break it down step by step —</p><h3>Storing status, data, and error.</h3><p>The data in our custom hook is managed by useState hook Line 5. The data and error properties are fairly self-descriptive. The status variable is what makes it interesting. It can take any value amongst idle, loading, resolved, and errored. The inital state is set to idle Line 8, from there it transitions to the loading state Line 14. It can thereafter either take the value of resolved or errored. If resolved the data property is set with the response from the API Line 19. In case of any error, the error property is set with the error object Line 23.</p><p>Fairly simple, right. Let’s continue.</p><h4>Why a status variable instead of variables like isLoading, isError?</h4><p>You might ask why a single status variable of type string instead of boolean variables like isLoading and isError. Wouldn’t a boolean make API a little cleaner?</p><pre><strong>// consuming hook using status varible</strong></pre><pre>if(status === &quot;loading&quot;)<br>  return &lt;div className=&quot;loading&quot;&gt;&lt;/div&gt;<br>else if(status === &quot;errored&quot;)<br>  return &lt;div&gt;An error occured.&lt;/div&gt;<br>else<br>  return &lt;div&gt;{data.id}&lt;/div&gt;</pre><pre><strong>// consuming hook using boolean variables like isLoading, isError</strong></pre><pre>if(isLoading)<br>  return &lt;div className=&quot;loading&quot;&gt;&lt;/div&gt;<br>else if(isError)<br>  return &lt;div&gt;An error occured.&lt;/div&gt;<br>else<br>  return &lt;div&gt;{data.id}&lt;/div&gt;</pre><p>Well, there are two reasons for this —</p><ul><li>Since there is one only variable (the status variable) it minimizes confusion. All we need to do is set the current status without worrying to set the state of other variables. Let’s consider there were two boolean variables. Theoretically, there would have been four different state combinations. Also, extending status is fairly simple with a single variable.</li><li>You can always write a utility to have boolean variables —</li></ul><pre>const mapStatus = (status) =&gt; {<br>  return {<br>    isIdle: status === &quot;idle&quot;,<br>    isLoading: status === &quot;loading&quot;,<br>    isResolved: status === &quot;resolved&quot;,<br>    isError: status === &quot;errored&quot;,<br>  }<br>}</pre><pre>/* Only one amongst the four properties from the above object will be true at any given time.*/</pre><h3>Effectively making an API call.</h3><p>The custom hook uses useEffect to make an external API (<a href="https://jsonplaceholder.typicode.com/">jsonplaceholder</a> in this case) call using <a href="https://axios-http.com/">axios</a>. It’s pretty standard in its way of using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async-await</a> to fetch data from a server. However, there are two things to discuss —</p><h4>Use of shouldSetData variable.</h4><p>Consider you are listing posts and clicking on one of the listed posts fetches details of that respective post. Let&#39;s say you have a list of 10 posts. Ideally, the user clicks on say post 5 and sees its details. Then they click on post 9 and see its details. Works pretty well!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*7GqgJ3TqsF56r1vOWUifIg.png" /><figcaption>List of 10 posts and details of post 9.</figcaption></figure><p>However, let’s say the user clicks on post 1 and before it finishes fetching they click on post 4, and before that finishes loading they click on post 9 and finally wait for it to load.</p><p>What just happened? Let’s dive in.</p><ul><li>We don’t know in what order will server fulfill our requests. However, we know for certain that the user is only interested in the request for the 9th post. So essentially all the time spend on post 1 and post 4 is kind of unnecessary both on the frontend and the server.</li><li>Also in case of components unmounts (maybe because you navigated away) the following error is thrown because of setting the state in an unmounted component.</li></ul><pre><strong>Warning: Can’t call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method</strong></pre><ul><li>Even in cases where the component re-renders it might flash responses from the result of post 1 and post 4 before finally displaying post 9.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*V1h_jbj9k_VGXJPg0e5QSg.gif" /><figcaption>Notice how the screen flashes for 2 before finally showing details of 3rd post.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f569a6eabb04e9b5aed7a1eb78c70dc/href">https://medium.com/media/5f569a6eabb04e9b5aed7a1eb78c70dc/href</a></iframe><p>What actually happens is as the user clicks on the button Line 35 to get details of post 1 (without waiting for it to finish) it triggers an API call Line 2 . But, by the time the API finishes its call, the user has already clicked on another post (or might have navigated away from the component). However, react still will try to set the data, status, and error variable corresponding to post 1.</p><p>The variable shouldSetData helps us control our app&#39;s behaviour in either case (an unmount or a re-render). Observe how shouldSetState is set to false as a part of effect cleanup. It ensures that the data, error and status are only set for correct URL when required.</p><p>This was the frontend part of handling such behaviour. There is one more point to consider though.</p><h4>Using AbortController</h4><p>We have handled the behaviour in our components. But the network requests are still fired. <a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortController">Abort controller</a> allows us to cancel the network request.</p><p>A network request is fired each time the URL is changed Look at the dependency array for useFetch . The controller.abort() in cleanup function ensures that the request for post 1 and post 4 is cancelled and the user only waits on the data for post 9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*Cce4tjuTypgfK1fUxGn4fQ.png" /><figcaption>Observe the request for post 1 and post 4 is aborted without getting resolved.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*_uxptbOsqnq7KHCUC6d5pQ.png" /><figcaption>Network tab cancelling requests.</figcaption></figure><p>Hope you enjoyed the article. The following sandbox provides the demonstration example.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F9rmh8&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F9rmh8&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F9rmh8%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/69ad7b79f4cd09ad108af9f783cfe20e/href">https://medium.com/media/69ad7b79f4cd09ad108af9f783cfe20e/href</a></iframe><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=262aabcf9d7e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/build-a-react-hook-for-fetching-data-262aabcf9d7e">Build a React Hook for Fetching Data</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Overview of React Query]]></title>
            <link>https://javascript.plainenglish.io/an-overview-of-react-query-88935faadcd7?source=rss-e1245ce379ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/88935faadcd7</guid>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Abhishek Kumar]]></dc:creator>
            <pubDate>Wed, 31 Mar 2021 06:42:18 GMT</pubDate>
            <atom:updated>2021-03-31T07:04:42.647Z</atom:updated>
            <content:encoded><![CDATA[<h4>The missing Server State Management library</h4><p>State management has always been a topic of discussion in front end applications. Existing solutions such as Redux, Mobx, et cetera are oriented towards client side state management. However in this article we are going to concentrate on efficiently managing state fetched from the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lHKpcRldk-cUeosTGGr9Sw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@alirexa?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alireza Khatami</a> on <a href="https://unsplash.com/s/photos/server-rack?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>What does server state actually mean?</h3><p>Any piece of data that is fetched from the server can be termed as server state. For example publications you are subscribed to, stories you have clapped for, stories that you have written are all server state. An example of client state can be the user’s theme preference (light or dark).</p><p>It can become tricky to control information stored on a remote server. Besides, server data comes with inherent challenges of caching, fetching, updating, and synchronizing the application’s state with the server’s state.</p><p>Let’s take a look at how react query helps solve these problems.</p><h3>Fetching Data</h3><p>Fetching data concretely refers to making a GET request to an endpoint on a server. The way react query allows us to interact with the server is by providing hooks. It provides the <a href="https://react-query.tanstack.com/reference/useQuery"><strong>useQuery</strong></a><em> </em>hook to fetch data from the server.</p><p>The useQuery hook has two required parameters.</p><p>The first parameter is a function that actually sends out the GET request, (interacts with the API) called as the <a href="https://react-query.tanstack.com/guides/query-functions"><strong>Query Function</strong></a>. The function can choose any method to interact with the server. It can use the native fetch API or any other library such as Axios. The only requirement is that the function should return a promise that will either resolve the data or throw an error.</p><p>Notice how the query function below queries a specific endpoint /users/1 on line 3.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e7f69b71a8df8f365b74a71bf7877ca/href">https://medium.com/media/2e7f69b71a8df8f365b74a71bf7877ca/href</a></iframe><p>The second parameter is called the <a href="https://react-query.tanstack.com/guides/query-keys"><strong>Query Key</strong></a>. It is used by react query to manage caching. Strings, arrays and objects are valid query keys. Query keys should be serializable and unique to the query. Following are some valid examples of query keys.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2da2d3a6cb8a235fa77240272436d3fb/href">https://medium.com/media/2da2d3a6cb8a235fa77240272436d3fb/href</a></iframe><p>Note how the useQuery hooks above have been provided with two parameters, the query key and the query function ( fetchUser ).</p><p>React query internally passes query key to the query function. Let’s modify the above query function to fetch information for any user instead of the hardcoded user ( users/1 endpoint ).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76918a553486392a022647cd757e134f/href">https://medium.com/media/76918a553486392a022647cd757e134f/href</a></iframe><p>Now that we are able to fetch information from the server let us create a component to display information to the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96eab0ecf2f6c0e49069d519172b045d/href">https://medium.com/media/96eab0ecf2f6c0e49069d519172b045d/href</a></iframe><p>Notice how useQuery hook returns<em> isLoading, isError, data, </em>and <em>error </em>( Line 4 ). These are just a couple of values returned by the hook.</p><pre>The list of all the variables returned by the useQuery hook has been <a href="https://react-query.tanstack.com/reference/useQuery">discussed here</a>.</pre><ul><li><em>isLoading </em>is a boolean which is true while data is being fetched. It might result in an error or a successful request.</li><li><em>isError </em>is true if an error occurs while fetching the data. Remember how useQuery expects a query function which returns a promise that will either resolve the data or throw an error. In case the query function throws an error, <em>isError </em>flag is set to true and the corresponding error is available in the <em>error </em>variable.</li><li><em>data </em>contains the actual data that you expect upon a successful request.</li></ul><p>React query has really simplified the boilerplate for our application and provides us with a standard way of fetching data from the server.</p><h3>Caching Data</h3><p>React query maintains a global cache for all the GET requests. The cache is like a dictionary which stores the fetched data against keys called as the query keys. Once data is fetched from the server react query keeps track of aspects such as cache time.</p><p>React query provides a <a href="https://react-query.tanstack.com/devtools">debugging tool</a> to keep track of all the queries in the application.</p><p>The following picture show the data that is stored against the query key [“user”, 1] (remember we fetched and displayed this data in the previous section).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*VMlIYyS-pAn7XMTCa76vmw.png" /><figcaption>Devtools provided by React Query (Notice the Data on the right hand side).</figcaption></figure><p>Take a look at the values of cacheTime, queryKey and queryHash under Query Explorer in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*_ILVCXzv-ZMoAJhirP8n1w.png" /><figcaption>Devtools provided by React Query (Notice the Query on the right hand side).</figcaption></figure><p>React query does the necessary job of maintaing a cache for the developers. It also updates the cache so that the data is in sync with the server’s state.</p><h3>Synchronizing Data</h3><p>Before proceeding let’s understand the concept of <strong>active </strong>and <strong>inactive </strong>query. In the context of react query active queries are the ones that are currently mounted in the application. For example let’s say you have two routes /user and /story. The former route has a component which accesses a query with the key [“user”,1] while the latter route access a query with the key [“story”,1]. In this scenario whenever someone visits /user the [“user”, 1] query becomes active (mounted) while [“story”, 1] query becomes inactive.</p><p>Additionally, each query has a <strong>stale </strong>time associated with it. You can modify the stale time for all the queries globally or on a per query basis. The default stale time is zero. It simply means the data associated with a query is considered stale/old after 0ms relative to the most recent fetch. It implies that react query will re-fetch the data as soon as possible (remember stale time is 0ms). Consider a scenario in which a query say [“likes”,1] has a stale time of 5 minutes. Also let’s assume that the query was last fetched at 1800 hours. It simply means that react query will not refetch the query until 1805 hours because until that time the query is <strong>fresh</strong>. In this scenario react query simply provides the data stored in cache instead of making an external API call.</p><p>Apart from inactive, fresh and stale a query can also be in <strong>fetching </strong>state. A query which is being fetched from the server is in fetching state. Such queries can either return a valid response or result in an error.</p><p>Now let us take a look as to how react query helps in synchronizing state between the server and the application.</p><ul><li>All stale queries are refetched when they become active.</li><li>Stale queries are also refetched when you refocus a window (try switching tabs and inspecting the network tab in a react query project).</li></ul><pre>Read about the <a href="https://react-query.tanstack.com/guides/important-defaults">default behaviour</a> of React Query.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*LCLjPIO_bXtIDtRraJQygw.png" /><figcaption>A timeline showing transition of two react queries with query keys — [“user”,1] and [“story”,1].</figcaption></figure><ul><li>In case of any error while fetching the data, queries are tried three times by default before actually throwing an error.</li><li>Apart from this you can force queries to be refetched by <a href="https://react-query.tanstack.com/guides/query-invalidation">invalidating them</a>. The query key is used to select the queries that you want to invalidate (mark stale). Stale queries are refetched when they become active again.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2c152e439c534d4ad290e3114cfa3bc/href">https://medium.com/media/f2c152e439c534d4ad290e3114cfa3bc/href</a></iframe><p>Invalidating queries can be extremely helpful. Consider a scenario in which settings page modifies the user’s information. In this scenario the profile page has to be in sync with the changes made by the settings page. You can update the user information on settings page and invalidate and queries that you think need to receive the updated state from the server (here [“user”,1] query should be invalidated).</p><h3>Updating Data</h3><p>React query makes it possible to create/update/delete data on the server using <a href="https://react-query.tanstack.com/guides/mutations"><strong>mutations</strong></a>. Just like useQuery, react query provides a <a href="https://react-query.tanstack.com/reference/useMutation"><strong>useMutation</strong></a><strong> </strong>hook for performing mutations on the server. The useMutation hook expects a required parameter called as the <strong>mutation function</strong>. This function is actually responsible for interacting with the server and performing the side effect. Notice how the mutation function below has anything to do with react query specifically. It is just a simple function which performs a mutation on the server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8652754ab943faf0242d70ceda49b01/href">https://medium.com/media/f8652754ab943faf0242d70ceda49b01/href</a></iframe><p>Let’s hook this function with react query.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6052f0542a981d1f2db0a49e0401d56/href">https://medium.com/media/a6052f0542a981d1f2db0a49e0401d56/href</a></iframe><p>The useMutation hook just points to the mutation function (Line 3: in this case the modifyUser function is the mutation function). The mutation function is actually called when you call the mutate function (Line 11) which is returned by the useMutation hook. The object passed to the mutate function (Line 11) is simply passed to the mutation function by react query.</p><p>The useMutation hook returns helper variables such as <em>isLoading</em>, <em>isError</em>, <em>error </em>(Line 3) et cetera which are analogous to variables returned by the useQuery hook. The useMutation hook also provides optional helpers. The most widely used helpers are onSuccess (Line 4) and onError. For example you can invalidate the [“user”,1] query on the settings page when the corresponding mutation reaches onSuccess state. This will ensure that the profile page is actually in sync with the server. Similarly you can also define the onError helper to communicate any error message.</p><h3>Conclusion</h3><p>I hope you were able to have an overall understanding of React Query and how it solves the problem of server state management. There is a lot more to the library than discussed here. For example in addition to useQuery hook it provides solution for common UI use case such as infinite scrolling or creating paginated views.</p><p><a href="https://react-query.tanstack.com/overview">Overview</a></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88935faadcd7" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/an-overview-of-react-query-88935faadcd7">An Overview of React Query</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compound Component Pattern in React]]></title>
            <link>https://javascript.plainenglish.io/compound-component-pattern-in-react-13ee74b819f8?source=rss-e1245ce379ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/13ee74b819f8</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Abhishek Kumar]]></dc:creator>
            <pubDate>Wed, 17 Mar 2021 14:04:24 GMT</pubDate>
            <atom:updated>2021-03-29T14:52:49.797Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide to Component Patterns in React</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1qhU6oHMnqWQIyV11oSvPw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@flowforfrank?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ferenc Almasi</a> on <a href="https://unsplash.com/s/photos/reactjs?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>Note: It is useful to have a good understanding of the </em><a href="https://reactjs.org/docs/context.html"><em>React Context API</em></a><em> in order to be able to follow this piece.</em></p><p>Take a look at the following code snippet from <a href="https://ant.design/">Ant Design</a>, a react UI library. The <a href="https://ant.design/components/menu/"><em>Menu</em></a> component has what it seems to be special properties called as <em>Item</em> and <em>SubMenu</em>.</p><pre>&lt;Menu&gt;<br>  &lt;Menu.Item&gt;Menu&lt;/Menu.Item&gt;<br>  &lt;Menu.SubMenu title=&quot;SubMenu&quot;&gt;<br>    &lt;Menu.Item&gt;SubMenuItem&lt;/Menu.Item&gt;<br>  &lt;/Menu.SubMenu&gt;<br>&lt;/Menu&gt;</pre><p>This way of creating components is referred to as the compound component pattern. The idea is essentially that the component in this case <em>Menu</em> has some logic which is shared internally amongst these properties in this case <em>Item</em> and <em>SubMenu</em>. Think of the select and option tags in HTML. They are intended to work together.</p><p>For the sake of explanation let us take a simple example of how Ant design uses the compound component pattern in the <em>Menu</em> component to provide a theme for the <em>Menu</em>. The default theme used by Ant Design is light as seen in the snippet below.</p><pre><strong>Default Props provided to the <em>Menu</em> component </strong>(<a href="https://github.com/ant-design/ant-design/blob/756a1dffea3b8f00876e61fd13f7ceb9ddc561b1/components/menu/index.tsx#L26">Source</a>)<strong>.</strong></pre><pre>static defaultProps: Partial&lt;MenuProps&gt; = {<br>    className: &#39;&#39;,<br>    <strong><em>theme: &#39;light&#39;, // or dark</em></strong><br>    focusable: false,<br>  };</pre><p>The way in which compound component pattern is implemented is by using the context API. The <em>Menu </em>component uses a context provider and provides the value that has to be shared internally with <em>Item</em> and <em>SubMenu</em> component. Furthermore, the <em>Item</em> and <em>SubMenu</em> component consume the context which results in the state being shared amongst the components.</p><p>Let us see how <em>Menu</em> component uses the above approach to create compound component.</p><pre><strong>Creating the context in <em>Menu</em> component</strong> (<a href="https://github.com/ant-design/ant-design/blob/756a1dffea3b8f00876e61fd13f7ceb9ddc561b1/components/menu/index.tsx#L74">Source</a>)</pre><pre>&lt;MenuContext.Provider<br>  value={{<br>    inlineCollapsed: this.getInlineCollapsed() || false,<br>    <strong><em>antdMenuTheme: theme,</em></strong><br>    direction,<br>  }}<br>&gt;</pre><pre><strong>Consuming the context in <em>SubMenu</em> Component</strong> (<a href="https://github.com/ant-design/ant-design/blob/d5eda4f87e4c1bb605d08a2acea76c8eb7163a4d/components/menu/SubMenu.tsx#L57">Source</a>)</pre><pre>&lt;MenuContext.Consumer&gt;<br>  {({ inlineCollapsed, <strong><em>antdMenuTheme</em></strong> }: MenuContextProps) =&gt; (<br>    &lt;RcSubMenu<br>      {...omit(this.props, [&#39;icon&#39;])}<br>      title={this.renderTitle(inlineCollapsed)}<br>      popupClassName={classNames(<br>        rootPrefixCls,<br>        <strong><em>`${rootPrefixCls}-${antdMenuTheme}`,</em></strong><br>        popupClassName,<br>      )}<br>    /&gt;<br>  )}<br>&lt;/MenuContext.Consumer&gt;</pre><p>Notice the <em>Menu</em> component creates a context and provides the value of <em>theme. </em>The value is then consumed in the <em>SubMenu</em> Component. So, the compound component pattern is created using the context API.</p><p>Here is another example of the compound component pattern used by <a href="https://react-bootstrap.github.io/">React Bootstrap</a>. The example uses the pattern with <a href="https://react-bootstrap.github.io/components/modal/">Modals</a>.</p><pre><strong>Compound component in React Bootstrap</strong> (<a href="https://react-bootstrap.github.io/components/modal/">Source</a>)</pre><pre>&lt;Modal.Dialog&gt;<br>  &lt;Modal.Header closeButton&gt;<br>    &lt;Modal.Title&gt;Modal title&lt;/Modal.Title&gt;<br>  &lt;/Modal.Header&gt;<br>  &lt;Modal.Body&gt;<br>    &lt;p&gt;Modal body text goes here.&lt;/p&gt;<br>  &lt;/Modal.Body&gt;<br>  &lt;Modal.Footer&gt;<br>    &lt;Button variant=&quot;secondary&quot;&gt;Close&lt;/Button&gt;<br>    &lt;Button variant=&quot;primary&quot;&gt;Save changes&lt;/Button&gt;<br>  &lt;/Modal.Footer&gt;<br>&lt;/Modal.Dialog&gt;</pre><p>React bootstrap also makes use of the context API to implement the pattern.</p><h3>Why Compound Component ?</h3><p>I am sure that the pattern must have intrigued you but you might still be wondering about the need of this pattern.</p><ul><li>Let’s assume React Bootstrap provided an API for Modal which looked something like this —</li></ul><pre><strong>Alternative internal implementation of the Modal Component</strong></pre><pre>const Modal = ({title, body}) =&gt; {<br>  return(<br>    &lt;div className=&quot;modal&quot;&gt;<br>      &lt;div className=&quot;modal-title&quot;&gt;{title}&lt;/div&gt;<br>      &lt;div className=&quot;modal-body&quot;&gt;{body}&lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><pre><strong>Consuming the Modal component</strong></pre><pre>&lt;Modal title={...} body={...}/&gt;</pre><p>It definitely will work as the user passes the required props however, the API has a very rigid approach when it comes to displaying the modal. With the compound component approach the user has the flexibility to choose whether or not to display a <em>Modal.Header</em>. The user also has the flexibility of choosing the order of display. For whatever reasons it will still be possible to display <em>Modal.Body</em> before <em>Modal.Header</em>.</p><ul><li>Let us take one more example in which the use case is to toggle content upon clicking a button. The idea is to make use of the state shared implicitly between the components.</li></ul><pre><strong>Creating the Compound Component Pattern</strong></pre><pre>import React, { useContext, useState } from &quot;react&quot;;</pre><pre><em>// creating the context</em><br>const TogglerContext = React.createContext();</pre><pre>const Toggler = ({ children }) =&gt; {<br>  // this state will be shared<br>  const [value, setValue] = useState(false);</pre><pre>  const toggle = () =&gt; {<br>    setValue((prevValue) =&gt; !prevValue);<br>  };</pre><pre>  return (<br>    <em>// using context to share the state between the components<br>    </em>&lt;TogglerContext.Provider value={{ value }}&gt;<br>      &lt;div&gt;<br>        &lt;div role=&quot;button&quot; onClick={toggle}&gt;<br>          Toggle Description<br>        &lt;/div&gt;<br>        {children}<br>      &lt;/div&gt;<br>    &lt;/TogglerContext.Provider&gt;<br>  );<br>};</pre><pre>const Data = ({ children }) =&gt; {<br>  <em>// Consuming the context</em><br>  const TogglerContextConsumer = useContext(TogglerContext);<br>  return TogglerContextConsumer.value &amp;&amp; &lt;&gt;{children}&lt;/&gt;;<br>};</pre><pre><strong>Using the Compound Component Pattern</strong></pre><pre>&lt;Toggler&gt;<br>  &lt;Data&gt;<br>    &lt;p&gt;I will get toggled when you click the button.&lt;/p&gt;<br>  &lt;/Data&gt;<br>&lt;/Toggler&gt;</pre><p>Notice how the <em>Data </em>component makes use of the state variable defined in <em>Toggler </em>component to <a href="https://reactjs.org/docs/conditional-rendering.html">conditionally render</a> its children. Essentially there is an internal sharing of state between the two components which gives the end user a flexible API to work with. The code snippet above is a very basic example to illustrate the idea.</p><p>You must have noticed that the components associated with the compound component pattern are often declared as <em>Modal</em>, <em>Modal.Header</em>, <em>Modal.Title</em>, et-cetera. This kind of notation helps establishing a mental association between the components involved. Let’s quickly modify our example from <em>Toggler</em> to <em>Toogler.Data.</em></p><pre>// Add the following line just after the Data component.<br>Toogler.Data = Data;</pre><pre><strong>Using the Modified Compound Component Pattern</strong></pre><pre>&lt;Toggler&gt;<br>  &lt;Toggler.Data&gt;<br>    &lt;p&gt;I will get toggled when you click the button.&lt;/p&gt;<br>  &lt;/Toggler.Data&gt;<br>&lt;/Toggler&gt;</pre><h3>Conclusion</h3><p>The compound component pattern allows us to express relationship amongst components. The components share state which means that state is used and can be manipulated internally by the components involved. The pattern provides a cleaner API and is implemented using react context.</p><p>Now that you understand the pattern, let’s start using it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13ee74b819f8" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/compound-component-pattern-in-react-13ee74b819f8">Compound Component Pattern in React</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Support Vector Machine]]></title>
            <link>https://medium.com/data-science/support-vector-machine-4b2fb9d3e71c?source=rss-e1245ce379ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b2fb9d3e71c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[support-vector-machine]]></category>
            <dc:creator><![CDATA[Abhishek Kumar]]></dc:creator>
            <pubDate>Tue, 01 Sep 2020 21:21:24 GMT</pubDate>
            <atom:updated>2020-09-02T08:49:00.576Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simpler intuitive explanation</h4><p>Abbreviated as SVM, support vector machine learning algorithm is commonly used for classification problems. It gives us a better way to understand a non-linear decision boundary.</p><p>Let’s begin by considering a scenario where one might want to classify the following data —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXZ-99N3S6rA5sjsFdc0hg.png" /><figcaption>Data set used to illustrate a simple SVM model.</figcaption></figure><p>It is quite evident that the data can be separated into their respective classes using a simple linear decision boundary. However, there are multiple such decision boundaries that can be used to separate the two classes. In fact, there are an infinite number of linear decision boundaries that can be drawn to separate the red and the blue class. Consider the following decision boundaries —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukZaWP9mrK7rspX9IgEv_Q.png" /><figcaption>Possible decision boundaries that can be used to classify the data.</figcaption></figure><ul><li>The one on the left is too close to the blue class implying “whenever in doubt classify the point to be red”.</li><li>The decision boundary in the middle graph is closer to the red class. The decision boundary being close to the red class implies that if a model classifies a point as being red then it is more sure of its decision had it classified the same point as being blue, thereby following “whenever in doubt classify the point as blue”. Also, intuition says we can do better than a perfectly straight decision boundary.</li><li>In the last graph, the decision boundary is close to the instances of both the red and the blue classes.</li></ul><p>From the above discussion, we may conclude that we want a decision boundary that is not too close to either of the two classes. To help us find such a line, SVM is used.</p><p>Support vector machine learning algorithm concentrates on those points of both the classes that are close to each other. The idea being that if a classifier does a good job of classifying challenging points it is likely to perform better on the data. SVM does this by looking up for the closest points from both the classes called the <strong>support vectors. </strong>Once SVM has found its support vectors it will try to find a line that is at maximal distance from these points. In case of two points the perpendicular bisector is the line that is equidistant and therefore at maximal distance from the two points. Any other line will be closer to one point than the other one.</p><p>We can also say that given the support vectors and multiple lines we will choose that line as our decision boundary whose distance is as large as possible from all support vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IfIekTA6EZWqJoNSeNX8zw.png" /><figcaption>Support Vectors and the Hyperplane illustrating the SVM model.</figcaption></figure><p>So the take away is that SVM tries to find a hyper plane that separates the data into two classes, and while doing so it tries to maximise the distance between the hyper plane and the support vectors of the classes.</p><p>A <strong>hyper plane</strong> in an n-dimensional space is a n-1 dimensional subset of that space. It divides the space into two separate parts. In case of 1-D space a <em>point</em> is a hyper plane, in case of 2-D space a <em>line</em> is a hyper plane and in case of 3-D space a <em>plane</em> is a hyper plane and so on.</p><p>In a practical scenario data is not as simple as to fit a linear decision boundary to it. Take a look at the following data set —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fef36c3ac17b46a36b5a671708960d0/href">https://medium.com/media/2fef36c3ac17b46a36b5a671708960d0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oWRg7fx3KeSVzaIkG5hoJg.png" /><figcaption>Data set with a non linear decision boundary.</figcaption></figure><p>Using line as a decision boundary is definitely a bad choice for the data set.</p><p>The solution here is to transform our 2 dimensional data to a higher 3 dimensional data so as to make it separable. Let’s add a third dimension <em>z</em> as <em>z=x*y.</em></p><p>The transformation applied here maps a<em> 2 dimensional dataset</em> to a higher <em>3 dimensional dataset</em> to find an optimal hyper plane. These transformations are called as the SVM’s <strong>Kernel Trick. </strong>In kernel trick a function is used map data to higher dimension so that the data becomes separable and a decision boundary is found.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c331532d69a8458dcaafb5d73fed1495/href">https://medium.com/media/c331532d69a8458dcaafb5d73fed1495/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*q1CaswW1unazglxnx_P4cg.png" /><figcaption>Transforming the data to a higher plane.</figcaption></figure><p>Observe that by applying the kernel all the points of blue class have been confined to the x-y plane and all the points of green class are elevated to the x-y-z space thereby giving us a plane as our optimal hyper plane.</p><p>For the sake of simplicity let’s assume <em>z=1</em> is the optimal decision boundary. However, SVM will output a hyperplane such that it is at maximal distance from the support vectors of either classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*MRvQ2M1Rfbp7R8u6SLIEww.png" /><figcaption>The hyperplane on transformed data.</figcaption></figure><p>We mapped our 2D data to 3D data by using the transformation <em>z=x*y</em>. Now we will map the decision boundary <em>z=1 </em>from the 3D space to the 2D space. This gives us <em>x*y=1. </em>This is how SVM transforms data and outputs a decision boundary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-8zacvQ_m0NSfa3-W2RYg.png" /><figcaption>The mapped decision boundary.</figcaption></figure><p>Linear, Radial Basis Filter, Polynomial, Sigmoid, and Laplace are few common used SVM kernels.</p><p>A detailed discussion of kernels is outside the scope of the article. However, lets briefly address the two basic parameters of a SVM model —</p><h4>Regularisation</h4><p>The regularisation parameter addresses the question, how much do you want to avoid misclassifying the training data. A higher value and the misclassification of the training data will be lesser. However, the model may overfit. It is represented by <em>C </em>in sklearn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*V5vZMdIerR9BJDOvEr3l_w.png" /><figcaption>Left: Smaller value of C gives a simple generalised boundary. Right: Larger value of C gives a boundary edging towards overfitting.</figcaption></figure><h4>Gamma</h4><p>Gamma decides how many examples are to be taken as support vectors. A smaller value means only instances that are closer to the probable hyper plane will be used to further fit it. However, a large value means that the instances which are far from the hyperplane are also used while fitting it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*HteHkhvwtgXBXLFdKmUaHQ.png" /><figcaption>Left: Smaller value of Gamma uses less number of instances around decision boundary. Right: Larger value of gamma means more number of instances to be included while fitting the decision boundary.</figcaption></figure><p>At first glance you might think that SVM is similar to logistic regression however the optimal hyperplane is governed by support vectors in SVM as opposed to all the data points which are taken into consideration in logistic regression. Moreover, logistic regression follows statistical approach and outputs probabilities however SVM is backed up by geometric approach. SVM aims at outputing the optimal hyperplane by maximizing distance between support vectors which reduces the error rate.</p><p>It is advisiable to start with logistic regression and then proceed to SVM with linear kernel. Other kernels such as RBF can be tried out further while keeping the track of selected performance metric.</p><p>Here is an example which classifies cancer as either malignant or benign. The example uses SVM with linear kernel and uses accuracy as performance metric. Feel free to try out different kernels and experiment with the hyper parameters of the model.</p><p><a href="https://colab.research.google.com/drive/1WfnJQ4z3tXVst7ZJxVjGBCtDHNeRdwPE?usp=sharing">Google Colaboratory</a></p><p>SVM has been discussed in detail in the following documentation —</p><p><a href="https://scikit-learn.org/stable/modules/svm.html">1.4. Support Vector Machines</a></p><p>I hope that the article helped you to develop a fair understanding of the intuition behind SVM and related parameters such as Kernel, Regularisation and Gamma.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b2fb9d3e71c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/support-vector-machine-4b2fb9d3e71c">Support Vector Machine</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative Adversarial Network]]></title>
            <link>https://medium.com/data-science/generative-adversarial-network-74eef7a82117?source=rss-e1245ce379ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/74eef7a82117</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Abhishek Kumar]]></dc:creator>
            <pubDate>Sat, 22 Aug 2020 22:37:57 GMT</pubDate>
            <atom:updated>2020-08-23T05:41:40.456Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>A simpler intuitive explanation.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-rBiwly9fS-wiXxO3I-yWg.png" /><figcaption>Super Resolution. An application of GAN (<a href="https://arxiv.org/pdf/1609.04802.pdf">Source</a>).</figcaption></figure><p>Let us assume Sergio is planning his next big heist and he needs his team to travel to a foreign country. Owing to the nature of his job he has decided to <em>generate </em>fake passports. He doesn’t want to take any chances because he believes that the passport officer can <em>discriminate </em>between original and fake passports. He has decided to use his <em>network</em> of designers and experts to carry out his plans effectively.</p><pre>Generative Adversarial Networks have two components a generator and a discriminator. Just take my words as of now :)</pre><pre>Let&#39;s get back to Sergio&#39;s plan and problems.</pre><h3>Sergio’s Passport Generator</h3><p>The diagram below represents Sergio’s plan of action in which a fake passport is generated by using the combined skills of the professionals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*kfnR0nv5YnOgRLyU3TE3xw.png" /><figcaption>Sergio’s generator network (Image by Author using <a href="https://github.com/dair-ai/ml-visuals">ML-Visuals</a>).</figcaption></figure><p>If we were to generalise Sergio’s plan we can say, the diagram is a <em>generator </em>of fake passports. A network of professionals who essentially know the security features of a passports try to recreate a similar one by using their knowledge. In other words given a space the goal is to draw an example which resembles the original space.</p><p>This is precisely what the <em>generator </em>component of a GAN does. It feeds upon the real world examples to observe their features and then create a new example which resembles the original examples.</p><h3>Passport Officer as Discriminator</h3><p>The following diagram represents the workflow of a passport officer. He checks hundreds of passports daily and Sergio wants his generated passports to be identified as the real ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*SeIvL98zZxnv-w74V-kOaA.png" /><figcaption>The workflow of passport officer (Image by Author using <a href="https://github.com/dair-ai/ml-visuals">ML-Visuals</a>).</figcaption></figure><p>The passport officer resembles to the second component of GAN called as the <em>discriminator</em>. The job of the <em>discriminator </em>is classification. It identifies the real instances of data from the fake or generated instances of data.</p><p>Under the given circumstances of counterfeiting, Sergio and the passport officer are competing against each other. Sergio wants his generated passports to be categorised as real ones, while the passport officer wants to do a good job of detecting fake passports. This makes them adversaries, hence the name <em>adversarial network</em>.</p><p>Now that we understand about the two components of a GAN let’s see how to train them to obtain a GAN.</p><h3>Putting it Together</h3><h4>Discriminator Training</h4><p>A discriminator is simply a classifier in case of a GAN which labels a given instance as either real or fake. You can use any neural network which suits your problem statement.</p><p>When a discriminator is trained it is fed with examples from real world as positive instances and examples generated from the generator network as negative instances. While training a discriminator the generator is not trained which is to say that its weights are not changed. Simply, the generator’s output is fed to the discriminator as negative instances. If the discriminator then classifies a negative instance as positive or vice-versa it is penalised by the loss function and its weights are updated through backpropagation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*fAl040xLmTC7T6JRVP37AQ.png" /><figcaption>Discriminator Training (Image by Author using <a href="https://github.com/dair-ai/ml-visuals">ML-Visuals</a>).</figcaption></figure><h4>Generator Training</h4><p>We have already seen that the job of the generator is to output new data instances. Generator is simply nothing but a neural network. However, neural networks have inputs. In case of generators noise is fed to them as input and eventually it learns to generate perceptible data. For any generated image the generator is penalized if the discriminator classifies it as fake. Only the weights of generator are updated while training it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*F1DVSjY8u4ACFp4s2fWwqg.png" /><figcaption>Generator Training (Image by Author using <a href="https://github.com/dair-ai/ml-visuals">ML-Visuals</a>).</figcaption></figure><p>In practice, an iterative approach is used to train a GAN in which you switch between training the generator for one iteration and then training the discriminator for the next iteration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74eef7a82117" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/generative-adversarial-network-74eef7a82117">Generative Adversarial Network</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An overview of using TensorFlow 2.0]]></title>
            <link>https://medium.com/data-science/an-overview-of-using-tensorflow-2-0-8d841748e680?source=rss-e1245ce379ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d841748e680</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Abhishek Kumar]]></dc:creator>
            <pubDate>Sat, 20 Jun 2020 14:21:01 GMT</pubDate>
            <atom:updated>2020-06-20T14:21:01.248Z</atom:updated>
            <content:encoded><![CDATA[<h4>An idea to manifestation.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S6WMoZ2xq5hjOUAehtMZgw.png" /><figcaption><a href="https://www.pngkit.com/bigpic/u2e6e6q8y3q8t4w7/">Transparent Tensorflow Logo Png@pngkit.com</a></figcaption></figure><p>Tensorflow has become one of the most popular deep learning libraries. It can be used by programmers, data scientists and researchers to create models out of the box by either using APIs or by writing things from scratch. It is as abstracted as your requirement.</p><p>The basic sequence of steps required while solving a machine learning problem comprises of having a data set, creating a model, training and evaluating the model and finally deploying it. We will discuss each of these steps in detail. However before that let’s discuss a few useful updates relevant to TensorFlow 2.</p><h4>Eager Execution</h4><p>TensorFlow 2 has enabled eager execution by default. In the earlier versions of TensorFlow a session was to be created even for the simplest of the tasks like printing a tensor. Eager execution makes the code more intuitive.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ada089c41a79d691e2f73c6719dd2f66/href">https://medium.com/media/ada089c41a79d691e2f73c6719dd2f66/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71065a94c99ca41214b2946ff105b5e0/href">https://medium.com/media/71065a94c99ca41214b2946ff105b5e0/href</a></iframe><h4>Like Numpy</h4><p>Numpy is a popular Python library focussing on mathematical operations involving matrices. TensorFlow 2 feels a lot more like numpy owing to eager execution. Also the ‘numpy’ method on tensors allows tensors to be converted into numpy arrays.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa1a3103d6a2ea566ae745505682e298/href">https://medium.com/media/aa1a3103d6a2ea566ae745505682e298/href</a></iframe><h4>tf.function Decorator</h4><p>This decorator speeds up the function’s execution on subsequent calls. It allows to use the performance benefits of the underlying graph model used by TensorFlow. The decorator tells TensorFlow to trace the computations of the function and boost the performance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c6e7022fdf28cbfe2ee3e1713b489d2/href">https://medium.com/media/0c6e7022fdf28cbfe2ee3e1713b489d2/href</a></iframe><h4>Cleaner API</h4><p>The TensorFlow API has been cleaned in which namespaces such as tf.keras.layers and tf.keras.losses have been added. A lot of namespaces have been renamed for better organisation for example tf.mod has been renamed to tf.math.mod. Few endpoints such as tf.rint have been deprecated. For a detailed list of all then changes refer to <a href="https://github.com/tensorflow/community/blob/master/rfcs/20180827-api-names.md">TensorFlow namespaces</a>.</p><h3>Data Design</h3><p>The machine learning community has over the time consolidated a number of useful datasets, some of which are available along with deep learning libraries. You can obviously use your own data and create an input pipeline for training. For example, ‘flow_from_directory’ can be used for effeciently reading images and augmenting them on the fly. Data stored in files such as CSV can also be used. However, in TensorFlow 2 there are two options in terms of datasets —</p><h4>Using Keras Datasets</h4><p>Keras datasets provides regression dataset such as boston housing, image classification datasets such as mnist and sentiment classification datasets such as imdb. These datasets are available in numpy format and fit into the memory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e654379ae6be047cd741ee11bba53bb4/href">https://medium.com/media/e654379ae6be047cd741ee11bba53bb4/href</a></iframe><h4>Using TensorFlow Datasets</h4><p>Tensorflow datasets is the faster, more effecient way of using data. It is a high performance dataset format. The data read using TensorFlow datasets is not in the numpy format, instead it is in tf.data format. It comprises of a large number of research oriented datasets which have been categorized as Audio, Image, Image classification, Object detection, Structured, Summarization, Text, Translate and Video. These data set are more real-world.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58c2be9778582fa7eb27061e84b1b55b/href">https://medium.com/media/58c2be9778582fa7eb27061e84b1b55b/href</a></iframe><h3>Model Design</h3><p>TensorFlow 2 has recommended using Keras as its official API. Designing models in Tensorflow is as simple as plugging in built-in layers to writing everything from scratch for research applications.</p><h4>Sequential API</h4><p>The sequential API is used for making linear models with a stack of layers one on the top of other. Different layers such as Dense, Flatten and Conv2D are added to the model using the add() method. Once you have created your model you can see the model’s summary. Sequential API is the most commonly used API for creating models. The basic idea is to stack a bunch of layers to create a model which is later compiled and further trained to draw inference.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e9779971fe8d297631fad06bdd0e1cc/href">https://medium.com/media/0e9779971fe8d297631fad06bdd0e1cc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*vXeukXOGnz2FSIBvCSAjPA.png" /><figcaption>The model summary. <strong>Documentation</strong> <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Sequential">tf.keras.Sequential.</a></figcaption></figure><h4>Functional API</h4><p>The Sequential API builds linear model however the Functional API is used to build non-linear model. The architecture of these models resembles a directed graph (DAG). These models have the capability of taking multiple inputs, producing multiple outputs and sharing layers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/924c7419cd520bef6dc9f06a4b197e9f/href">https://medium.com/media/924c7419cd520bef6dc9f06a4b197e9f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*gaXojISU1bql0N3FOnWS3w.png" /><figcaption>The representation of model as a graph. <strong>Documentation</strong> : <a href="https://www.tensorflow.org/guide/keras/functional">Keras Functional API</a></figcaption></figure><h4>Subclassing</h4><p>The subclassing allows to write everything from scratch. It gives a finer control over aspects of creating a model. The framework gives a class in which the constructor defines the layers to be used and the call method puts together those layer in an order. This approach is recommended if you want to understand how things work under the hood.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bbb8ba24fb1dc70e2702133ae89ac1e/href">https://medium.com/media/3bbb8ba24fb1dc70e2702133ae89ac1e/href</a></iframe><h3>Training Design</h3><h4>Using the Fit method</h4><p>Fit is the most commonly used method used for training a model. It works for model created using by any of the above discussed strategies. It is used when datasets are small and fit into memory.</p><p>Before training a model using the fit method, the model is compiled during which a loss function, an optimizer and a metric is specified for the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91bd441f399cba32ccf54e59b35ec7c7/href">https://medium.com/media/91bd441f399cba32ccf54e59b35ec7c7/href</a></iframe><h4>Using Callbacks</h4><p>Various graphs are used to monitor the progress of a model during training. Alternatively, callbacks can be used to monitor the state of various evaluatation metrics and make decisions such as to stop the training, save model periodically, schedule learning rate, visualize the training progress, et-cetera. They are called at different points during training such as start of an epoch, end of a batch, et-cetera. Callbacks are passed as a list to the fit method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/075b508ac1936989249e5a0d14d5effe/href">https://medium.com/media/075b508ac1936989249e5a0d14d5effe/href</a></iframe><h4>Using Fit Generator</h4><p>This is another way of training a model. The fit generator method is used when the dataset is so large that it doesn’t fit into the memory. A common use case of fit generator is to read images from a directory while applying data augmentation to them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec43986d2ee1d4ad204d4b0ebcb4d14c/href">https://medium.com/media/ec43986d2ee1d4ad204d4b0ebcb4d14c/href</a></iframe><h4>Using Train on Batch</h4><p>The train on batch works at batch level. It takes a single batch as input and updates the model parameters after performing backpropagation. It allows us to do additional things between each batch. A use case would be to update pre-trained model against a single new batch of samples that you might have collected later. It is also used in LSTMs where the state of an LSTM is needed to be reset usually after each series of data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/752cd8baef9f1dbdf0a2f992a8bd97f6/href">https://medium.com/media/752cd8baef9f1dbdf0a2f992a8bd97f6/href</a></iframe><h4>Writing Custom Training Loops</h4><p>The fit and fit_generator functions abstract a lot of details while training a model. However, if needed TensorFlow 2 allows you look at the gradients of the network using ‘GradientTape’. You can also see how the weights get updated using those gradients. Basically, it gives you finer control on how to update the weight. Discussing a complete example of a custom training loop might get overwhelming. A detailed example has been discussed <a href="https://www.tensorflow.org/tutorials/customization/custom_training">here.</a></p><h4>Distributed Training</h4><p>Scalability is crucial when it comes to training deep learning models. TensorFlow 2 allows to scale up the learning task for faster learning without making significant changes to the code. The training process can be extended to multiple GPUs, TPUs and machines. Multiple strategies have been defined to meet different use cases. For example the MirroredStartegy supports training on multiple GPUs on one machine whereas MultiWorkerMirroredStrategy supports synchronous distributed training across multiple machines, each of those machines can have multiple GPUs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c04a343840a64fc272261b7d5909d5a6/href">https://medium.com/media/c04a343840a64fc272261b7d5909d5a6/href</a></iframe><h3>Serialization</h3><p>Once a model has been trained it needs to saved in order to be used in production. In TensorFlow 2 saving the model has been standerized using SavedModel format which saves the complete model along with its weights. The SavedModel formal makes it easier for deploying model using TensorFlowJS, TensorFlowLite or TensorFlow Serving.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27ed65702c8bbc7ef928d5eeea80d712/href">https://medium.com/media/27ed65702c8bbc7ef928d5eeea80d712/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f843102f7594d55eb687e4f07f3a146c/href">https://medium.com/media/f843102f7594d55eb687e4f07f3a146c/href</a></iframe><h3>Deployment</h3><h4>Using TensorFlow Serving</h4><p>TensorFlow serving allows machine learning models to be served as REST or gRPC (Remote Procedure Call) client APIs. The serving is made easier in TensorFlow by providing a docker file. An implementation has been discussed <a href="https://www.tensorflow.org/tfx/guide/serving">here</a>.</p><h4>Using TensorFlow Lite</h4><p>Mobile and IoT devices can also be used to deploy TensorFlow models. However, these devices have constraints such as power consumption and battery life. TensorFlow provides a method for converting originally trained models to their lighter versions which can be deployed on devices with power and processing constrains. It is a lightweight solution for Android, iOS and embedded systems.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a4d719fa52d9198af9ba8b33853a525/href">https://medium.com/media/4a4d719fa52d9198af9ba8b33853a525/href</a></iframe><h4>Using TensorFlowJS</h4><p>TensorFlowJS has enabled to use machine learning directly in the browser or server side using NodeJS. Once you have saved your model you can easily deploy it using TensorFlowJS. The model is first converted to the TensorFlowJS web format and then loaded for deployment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f04fc25b89cb25d351af86b31163aaf4/href">https://medium.com/media/f04fc25b89cb25d351af86b31163aaf4/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09fc012e5b5a239444c980c4d6b15b6f/href">https://medium.com/media/09fc012e5b5a239444c980c4d6b15b6f/href</a></iframe><h3>Conclusion</h3><p>Following the consolidation of different optimizers, metrics, loss functions and layers under tf.keras namespace, I am able to write more consitent code in TensorFlow 2. Eager execution has simplified debugging. Instead of creating a session to get the value of a tensor, I can now just print it using the standard print<em> </em>function of python. The addition of tf.function decorator has enabled the functions written using standard python to be optimised for performance by TensorFlow. I can easily scale the training of my models using the strategies provided by tf.distribute without making significant changes to the code.</p><p>Additionally, <a href="https://www.tensorflow.org/hub">TensorFlow hub</a> allows me to reuse machine learning models by using Transfer Learning which speeds up the training process. Overall TensorFlow has grown up to be a developer friendly yet powerful artificial intelligence library.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d841748e680" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/an-overview-of-using-tensorflow-2-0-8d841748e680">An overview of using TensorFlow 2.0</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>