<?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 Aman Sharma on Medium]]></title>
        <description><![CDATA[Stories by Aman Sharma on Medium]]></description>
        <link>https://medium.com/@amansharma2910?source=rss-84e03a4d7261------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*07DmExkuNdTzswc80qvcpw.jpeg</url>
            <title>Stories by Aman Sharma on Medium</title>
            <link>https://medium.com/@amansharma2910?source=rss-84e03a4d7261------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:01:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amansharma2910/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[Enterprise AI Is Doomed To Fail: Why Your Million-Dollar Investment Won’t Deliver]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://amansharma2910.medium.com/enterprise-ai-is-doomed-to-fail-why-your-million-dollar-investment-wont-deliver-7e4482f52b66?source=rss-84e03a4d7261------2"><img src="https://cdn-images-1.medium.com/max/1536/1*a8O2HByXzYCyw2QXYJkvog.png" width="1536"></a></p><p class="medium-feed-snippet">The enterprise AI gold rush is in full swing, with valuations soaring and capital flowing freely.</p><p class="medium-feed-link"><a href="https://amansharma2910.medium.com/enterprise-ai-is-doomed-to-fail-why-your-million-dollar-investment-wont-deliver-7e4482f52b66?source=rss-84e03a4d7261------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://amansharma2910.medium.com/enterprise-ai-is-doomed-to-fail-why-your-million-dollar-investment-wont-deliver-7e4482f52b66?source=rss-84e03a4d7261------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e4482f52b66</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[ai-in-business]]></category>
            <category><![CDATA[enterprise-technology]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Aman Sharma]]></dc:creator>
            <pubDate>Mon, 12 May 2025 22:05:42 GMT</pubDate>
            <atom:updated>2025-05-12T22:05:42.155Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[API 101: Backdoor to Backend]]></title>
            <link>https://medium.com/data-science/api-101-backdoor-to-backend-8da989e1551c?source=rss-84e03a4d7261------2</link>
            <guid isPermaLink="false">https://medium.com/p/8da989e1551c</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Aman Sharma]]></dc:creator>
            <pubDate>Mon, 23 Jan 2023 18:10:46 GMT</pubDate>
            <atom:updated>2023-01-25T15:31:36.599Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DoXFctykG6FXA2Ok" /><figcaption>Photo by <a href="https://unsplash.com/@lazizli?utm_source=medium&amp;utm_medium=referral">Lala Azizli</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>A Quick Dive Into The World of APIs, And How APIs Drive Applications</h4><blockquote>tl;dr — This is a very detailed introduction to APIs, application development, and a theoretical starter for backend development. This can be used as educational material on these topics.</blockquote><p>In this digital age, we are surrounded by applications that we pretty much rely on to facilitate almost all our day-to-day needs.</p><p>Is reading the news, and getting yourself updated with the happenings around the world the first thing you like to do when you wake up? Well, there are news applications like <em>Google News</em> and <em>Inshorts</em> for that. Running late and wanna grab a cab to work? You can quickly get one right at your doorstep with the <em>Uber</em> app! Hungry but don’t wanna cook? Just grab your phone and order your grocery right from the comfort of your home without having to carry those heavy grocery bags and roam around stores.</p><p>But why are we discussing this? The point is that today we have these very convenient apps that can do almost everything for us. <em>But that’s from the user&#39;s perspective.</em> To a software developer, there’s more to that.</p><p>While overly simplified for the user, an application like this can be pretty complex for the developer to make. So the first question that arises is — <strong>How are these applications made?</strong></p><p>To answer this, we can take a look at the <strong>3-Layer Application Architecture</strong>.</p><h3>The 3 Layer Application Architecture</h3><p>The 3-layer application architecture is a well-established software development architecture, that breaks down software into 3 logical and physical computation layers, viz.</p><ul><li><strong>Presentation Layer-<em> </em></strong><em>R</em>efers to the client-side application, i.e., the app that the users actually see and interact with.</li><li><strong>Application layer- </strong>Refers to the application component that handles all the business logic.</li><li><strong>Data layer-<em> </em></strong>Refers to the component that stores and handles all the data within the application.</li></ul><p>Now, these three individual components work together to make a usable application.</p><ul><li>The user interacts with the client-side (also known as the frontend) application, <em>making some sort of request.</em></li><li>The application layer <em>processes this request.</em></li><li>If any data is <em>generated or altered while processing this request</em>, that is maintained on the data layer.</li><li>After the request is processed by the backend, a response is sent to the frontend application.</li></ul><blockquote><strong><em>NOTE:</em></strong><em> Often, the application and data layer combined together are referred to as the server-side (or backend) application.</em></blockquote><p>But now, another question arises. The one that we’re going to specifically answer in this guide is— <strong>How do the different application layers (frontend and backend, to be more specific) communicate back and forth with each other?</strong></p><p>Well, here comes into play the concept of <strong>API</strong>s.</p><h3>What is an API?</h3><p>API is an acronym for <strong><em>Application Programming Interface</em></strong>. As the name suggests, it is an interface of some sorts.</p><p>To be more precise, APIs allow cross-platform and inter-device communications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*ZAcq7l1JOnbCOzmgejIauw.png" /><figcaption>Image by author</figcaption></figure><ul><li><strong>Software-to-software communication:</strong> Earlier, we discussed how an application can be broken down into client-side and server-side components. These components exchange back and forth a set of requests and data responses. This communication interfacing is facilitated behind the scenes by APIs. The client sends an API request to the server, the server processes the request, and then returns an API response to the client.</li><li><strong>Platform-independent communication:</strong> Since APIs act as an effective communication mechanism between the client and the server, this means that both the client and the server can be based on entirely different tech stacks and yet manage to work together. For example, your frontend application can be written in JavaScript, and your backend can be written in Python. APIs generally have a standardized request and response structure that almost all programming languages support.</li><li><strong>Reusability of code: </strong>APIs promote code reusability. Let us understand it like this. Instagram has both a mobile application, as well as a website. Now, we have two types of clients in the case of Instagram, but only one backend that handles requests from both the web client as well as the mobile client. Both these clients make requests to the same backend server using APIs. Thus, there is no need to implement a separate backend for both mobile and web.</li></ul><p>So now that we have a brief understanding of what APIs are, let us dive deeper and take a look at the different kinds of APIs available.</p><h3>Types of APIs</h3><p>There are primarily three kinds of APIs, based on the services they provide. These are as follows:</p><ul><li><strong>Local API:</strong> These are Operating System (OS) APIs that provide services to the application programs, such as microphone access, camera access, or requesting data from DB service, etc.</li><li><strong>Program API: </strong>It is based on Remote Procedure Call (RPC) technology that allows remote program execution from another server. In simple words, these APIs simply allow the execution of scripts or programs on a remote server or device.</li><li><strong>Web API:</strong> Web APIs, also known as web services, allow applications or devices to communicate with each other via the World Wide Web, using HTTP architecture.</li></ul><blockquote><strong>When it comes to building applications that involve a client-server architecture, we primarily use web APIs.</strong></blockquote><p>Now, since the focus of this article is to familiarize ourselves with how applications are built, we are going to focus specifically on web APIs.</p><blockquote><strong>NOTE:</strong> Web APIs can further be broken down into several classifications like SOAP (Simple Object Access Protocol), REST (REpresentational State Transfer) APIs etc. As of today, a majority of applications around the world predominantly use the REST API architecture for client-server interactions, due to the ease of implementation. Since REST has become the industry standard, in this article, we are going to discuss REST APIs.</blockquote><h3>What are REST APIs?</h3><p>REST stands for REpresentational State Transfer; also known as RESTful web services. It is a standardized API architecture that allows cross-platform and inter-device communications over the HTTP network protocol.</p><blockquote>Again, in simple words, it allows two application components to interact with each other.</blockquote><p>A typical client-server interaction involves primarily four kinds of operations, namely:</p><ol><li>Create: The create operation via an API request pertains to the creation of a resource on the data layer of the backend. <em>Eg.- In a TODO list app, a create API request can be used to create a TODO item in the database.</em></li><li>Read: The read operation can be used to fetch data from the database. This data can be a single resource of a type, a batch of resources of a single type, or a collection of resources of different types based on the client’s request and implementation of resource access on the backend. <em>Taking the example of the same TODO application, a read request can be used to fetch all the TODOs created by a user.</em></li><li>Update: An update operation can be performed to update the data associated with a particular resource in the data layer. <em>In our TODO application, the update request can be used to update the TODO task.</em></li><li>Delete: As the name suggests, the delete operation can be used for the deletion of resources. <em>For our TODO app, delete requests can be used to delete a TODO object from the TODO list.</em></li></ol><p>These operations are collectively referred to as <strong>CRUD</strong> (<strong>C</strong>reate, <strong>R</strong>ead, <strong>U</strong>pdate, <strong>D</strong>elete) <strong>operations</strong>. For any application, these are some of the most basic operations a user can perform.</p><blockquote>To put it in layman’s terms, when a user is interacting with an application, they are either accessing some data, or some data is being created or manipulated. REST APIs act as the intermediary step between the frontend and backend, allowing CRUD operations to be performed within an application.</blockquote><p>Now, we read earlier that because of how APIs are implemented as a communication channel between the client and the server, both the client and the server can be written using entirely different programming tech stacks. However, there has to be a standardized, <em>language agnostic</em> mechanism so that the client and the server can interact via the API. For this, REST APIs use <strong>JSON</strong>-based messaging protocol.</p><p>JSON stands for <strong><em>JavaScript Object Notation</em></strong>. It is an open-standard file format and data interchange format which is human-readable in nature. Data is transmitted using JSON in a key-value pair and array format.</p><p>The following diagram demonstrates a typical client-server interaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*iR-KTYz-4w9MfvdTQVnFvw.png" /><figcaption>Image by author</figcaption></figure><ul><li>The client sends an API request to the server over the HTTP protocol. <em>This request is in the JSON format.</em></li><li>The server parses this API request, processes the request, and then sends an API response back to the client, <em>which is again in the JSON format.</em></li><li>The client can parse the JSON response object to render it.</li></ul><p>As you can observe, since the intermediary communication channel is standardized, hence the client and server can operate independently of each other in terms of platform and implementation. <em>As in, the backend can be written in one programming language (say, Python) and the frontend can be written in another (say, JavaScript), and the application will still work fine.</em></p><p>Another important characteristic of REST APIs is that they are <strong><em>stateless</em></strong>. This means that each request from the client to the server must contain all of the information necessary to understand and complete the request. <em>The subsequent requests aren’t dependent on the previous requests.</em></p><p>With this, we have completed some of the theoretical concepts regarding APIs and what are the characteristics of REST APIs. And all this brings us to the most important part of all.</p><h3>What Does an API Request Look Like?</h3><p>As we discussed earlier, <em>REST API calls are stateless in nature</em>, which simply means that with each API request, we need to send</p><ul><li>all the data that is required in order to process the request. This data involves the type of operation to be performed,</li><li>information regarding user authentication,</li><li>the resource to be accessed via the API,</li><li>and some additional parameters that might be required to process the request.</li></ul><p>Based on these requirements, a REST API request can be broken down into 4 components:</p><h4>Resource Path</h4><p>This is the path to the resource that is to be acted upon via the API request. A resource can be thought of as an object or entity within the database. The resource path is <em>a mapping to</em> an entity within the database. Let’s continue with our example of a TODO app. One of the API endpoints can be used to fetch the list of all the TODOs of a user. The URL of the endpoint looks like this:https://mytodolist.com/todos/</p><p>Here, https://mytodolist.com is the domain of the website. /todos/ is the resource path to the TODO objects.</p><h4>HTTP Verb</h4><p>As we discussed earlier, an API request has to specify what kind of CRUD operation it is intending to perform. For this, we specify an HTTP verb within our API call. The simplest way to understand HTTP verbs is that these are <em>words </em>that tell the server what action to perform on a particular resource.</p><p>There are a bunch of predefined and standardized HTTP verbs, however, the most commonly used ones are as mentioned below.</p><ul><li><strong>POST: </strong>Used to create a resource object</li><li><strong>GET: </strong>Used to perform the read operation on the resource</li><li><strong>PUT: </strong>Used to perform the update operation</li><li><strong>DELETE:</strong> Used to perform the delete operation</li></ul><h4>Request Body</h4><p>The request body can be used to specify some of the additional parameters that can be required to process a request. For example, in our TODO app, in order to create a TODO object, we have to specify the task. Similarly, in order to update a TODO object, we need to specify the new task that will be replacing the original task in the TODO list, along with the ID for the task that has to be modified. In our API request, we will have to send this information via the request body.</p><p><em>Generally, we need to specify a request body for POST and PUT requests. GET requests don’t have a request body.</em></p><blockquote><strong>NOTE:</strong> The request body uses JSON format to send the request data in the form of a key-value pair object.</blockquote><h4>Request Header</h4><p>While the above 3 components are generally enough to make a REST API request, sometimes we need to specify some additional details along with the API request as well. <em>Take an example of user authentication.</em></p><p>In our TODO app, we might have a bunch of users, each of them having their own TODO lists. We have to ensure that first of all, only the authorized users can create, read, update and delete TODOs. Then, we also need to ensure that one user can’t access another user’s TODOs. To guarantee these requirements, we need to implement some sort of authorization on the API endpoints, that determines whether an authorized user is making the API request, and whether the resource actually belongs to the user.</p><p>While we won’t go deep into the authentication strategies, however, just for the sake of information, we send authentication information in the request header, generally in the form of a unique token.</p><p>All these components come together to make an API call.</p><p>Let us look at some example API calls, made using cURL:</p><pre>curl --request GET \<br>     --url https://realstonks.p.rapidapi.com/TSLA \<br>     --header &#39;X-RapidAPI-Host: realstonks.p.rapidapi.com&#39; \<br>     --header &#39;X-RapidAPI-Key: 1ca406921amsh21f2341da9178c3p1a7dd9jsn5d319166bd10&#39;</pre><p>The above given is a GET API request. We specify the HTTP verb using the --request flag. The --url flag is used to specify the request path. Then the headers are specified using --header flag.</p><pre>curl --request POST \<br>     --url https://hotel-price-aggregator.p.rapidapi.com/rates \<br>     --header &#39;X-RapidAPI-Host: hotel-price-aggregator.p.rapidapi.com&#39; \<br>     --header &#39;X-RapidAPI-Key: 1ca406921amsh21f2341da9178c3p1a7dd9jsn5d319166bd10&#39; \<br>     --header &#39;content-type: application/json&#39; \<br>     --data &#39;{<br>    &quot;hotelId&quot;: &quot;102061485&quot;,<br>    &quot;checkIn&quot;: &quot;2022-07-01&quot;,<br>    &quot;checkOut&quot;: &quot;2022-07-02&quot;<br>}&#39;</pre><p>The above given is a POST request where we can see the example of the request body being specified, using the --data flag.</p><p>The implementation of how an API request is made might differ from one programming language or utility tool to another. However, the critical components of the API request are going to remain the same, i.e., the HTTP verb, request URL or request path, a request body, and request headers.</p><p>Now that we know what a API request looks like, there’s just a final component remaining in the API request-response cycle that we need to understand — the API response.</p><h3>What Does an API Response Look Like?</h3><p>The API response is the response that the backend returns to the frontend after the API request has been processed. A response should tell the client whether the request was successful or not, and if successful, it should return the requested data, or an appropriate acknowledgement message to the client. In case the request was unsuccessful, the client should receive a relevant error message.</p><p>Based on these requirements, an API response can be broken down into two parts, as discussed below.</p><h4>Response Body</h4><p>The response body consists of the requested data (in case of a GET API request), or an appropriate acknowledgment message in case of other API request types. In case of a failed API request, the response body consists of the appropriate failure message that specifies why the API call to the server failed.</p><h4>Response Status Code</h4><p>The API response contains a response status code that helps the client determine whether the request was a success or failure. These status codes have been standardized for the HTTP protocol, and can be broadly divided into 5 classes — 1xx→ Informational, 2xx → Success, 3xx → Redirection, 4xx → Client Error, 5xx → Server Error</p><p>Some of the common status codes are as mentioned below.</p><ul><li>200 — <em>OK. The request was successful.</em></li><li>204 — <em>No Content.</em></li><li>301 — <em>Moved Permanently.</em></li><li>400 — <em>Bad Request.</em></li><li>401 — <em>Unauthorized.</em></li><li>403 — <em>Forbidden.</em></li><li>404 — <em>Not Found.</em></li><li>500 — <em>Internal Server Error.</em></li></ul><p>For example, the response to the GET API request we made earlier was as follows:</p><pre>{<br>  &quot;price&quot;: 141.98,<br>  &quot;change_point&quot;: 8.56,<br>  &quot;change_percentage&quot;: 6.42,<br>  &quot;total_vol&quot;: &quot;107.51M&quot;<br>}</pre><p>The response status code was 200.</p><h3>Conclusion</h3><p>With this, we come to the end of this article. Just to summarize, we understood what APIs are, and how they function to allow communication between devices and applications. Finally, we studied REST APIs in depth — how an API request-response cycle works.</p><p>Obviously, APIs are just a foundation, or a backdoor, into the immense world of software development (backend, to be more precise) as the title suggests.</p><p>You can follow me to read more such interesting concepts. In the upcoming blogs in this series, we will dive deeper into backend development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8da989e1551c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/api-101-backdoor-to-backend-8da989e1551c">API 101: Backdoor to Backend</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[The Hitchhiker’s Guide to Optimization in Machine Learning]]></title>
            <link>https://medium.com/data-science/the-hitchhikers-guide-to-optimization-in-machine-learning-edcf5a104210?source=rss-84e03a4d7261------2</link>
            <guid isPermaLink="false">https://medium.com/p/edcf5a104210</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Aman Sharma]]></dc:creator>
            <pubDate>Sat, 05 Jun 2021 11:27:38 GMT</pubDate>
            <atom:updated>2021-06-05T17:07:10.146Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9IHbImpM6Y8iTOLyhICqhw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@max_duz?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Max Duzij</a> on <a href="https://unsplash.com/s/photos/hill?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>A Detailed Guide on Optimization and Stochastic Gradient Descent</h4><blockquote>The aim of this article is to establish a proper understanding of what exactly “<em>optimizing</em>” a Machine Learning algorithm means. Further, we’ll have a look at the gradient-based class (Gradient Descent, Stochastic Gradient Descent, etc.) of optimization algorithms.</blockquote><blockquote><strong>NOTE: </strong>For the sake of simplicity and better understanding, we‘ll restrict the scope of our discussion to <strong>supervised machine learning</strong> algorithms only.</blockquote><p>Machine Learning is the ideal culmination of Applied Mathematics and Computer Science, where we train and use data-driven applications to run inferences on the available data. Generally speaking, for an ML task, the type of inference (i.e., the prediction that the model makes) varies on the basis of the problem statement and the type of data one is dealing with for the task at hand. However, in contrast to these dissimilarities, these algorithms tend to share some similarities as well, especially in the essence of how they operate.</p><p>Let’s try to understand the previous paragraph. Consider supervised ML algorithms as a superset. Now, we can go ahead and further divide this superset into smaller sub-groups based on the characteristics these algorithms share:</p><ul><li>Regression vs classification algorithms</li><li>Parametric vs non-parametric algorithms</li><li>Probabilistic vs non-probabilistic algorithms, etc.</li></ul><p>Although setting these differences apart, if we observe the generalized representation of a supervised machine learning algorithm, it’s evident that these algorithms tend to work more or less in the same manner.</p><ul><li>Firstly, we have some labeled data, which can be broken down into the feature set <strong>X</strong>, and the corresponding label set <strong>Y</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*_JQ8-W2b_hXKMwIkLDY5Gw.png" /><figcaption>The feature set and label set (Image by author)</figcaption></figure><ul><li>Then we have the model function, denoted by <strong>F</strong>, which is a mathematical function that maps the input feature set <strong>X_i</strong> to the output <strong>ŷ_i</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*7JQC4mYrTtLeTbJDcG1AsQ.png" /><figcaption>Model function (Image by author)</figcaption></figure><p><strong>To put it in layman’s terms, every supervised ML algorithm involves passing as input to the model function F a feature set X_i, which the function F processes to generate an output ŷ_i.</strong></p><blockquote>However, this is just the inference (or testing) phase of a model, where theoritically, we are supposed to use the model to generate predictions on the data it has never seen before.</blockquote><blockquote>But what about “training” the model? Let’s have a look at it next.</blockquote><h3>Model Optimization</h3><p>The training phase of a supervised ML algorithm can be broken down into two steps:</p><ol><li><strong>Forward Propagation: </strong>The forward propagation step is similar to the inference phase of a model, where we have a parameterized model function F, that performs transformations on the input set <strong>X_i</strong> to generate the output <strong>ŷ_i</strong>.</li><li><strong>Backward Propagation: </strong>Before we understand how backpropagation works, it is very important to understand why we need it. When we are working with parameterized models, the parameter matrices (model weights and biases) are often initialized randomly. Because of this random initialization and the uncertainty associated with it, there&#39;s a very high probability that the initial model performance will be very underwhelming. <strong><em>Therefore, we need a way to somehow alter the model parameters in a way that its performance improves</em></strong>. This is exactly what backpropagation aims to achieve. In the backpropagation step, we first evaluate the inferred model output <strong>ŷ_i </strong>with reference to the actual label <strong>Y_i</strong> by calculating the total information loss (sometimes also referred to as model cost) via a loss function. Then, on the basis of the loss generated, <strong>we <em>optimize</em> the model</strong> in a way that on the next training cycle, the total cost generated by the model is reduced.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Opu5RKufwwPbXbpMUbGLYw.png" /><figcaption>Model training (Image by author)</figcaption></figure><h4>So how exactly do we define model optimization?</h4><p><strong>Model optimization</strong> can be defined as the process of updating the model parameters (i.e., the model weights and biases), based on a criterion (loss function), such that the information loss, when the model makes inference on the training data, is reduced. <strong>Simply put, during an optimization step, we iteratively update the model parameters such that the cost function is minimized.</strong></p><p>So the model training can be summarised as an iterative cycle where we start with some randomly initialized model parameters, and then slowly optimize these model parameters over several backpropagation steps with the aim of achieving high accuracy and a low model cost.</p><p>So now that we know what model optimization is, let us have a look at some of the most widely used optimization algorithms in Machine Learning.</p><h3>Gradient Descent Algorithm</h3><p>Gradient descent is one of the easiest to implement (and arguably one of the worst) optimization algorithms in machine learning. It is a first-order (i.e., gradient-based) optimization algorithm where we iteratively update the parameters of a differentiable cost function until its minimum is attained.</p><p>Before we understand how gradient descent works, first let us have a look at the generalized formula of GD:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*ZLpiw7lIx0x9EyIYKdjVCg.png" /><figcaption>Gradient descent (Image by author)</figcaption></figure><p>The basic idea here is to update the model parameters in the direction of the negative gradient of the loss function w.r.t. the parameter. To give you a better intuition, you can think of gradient descent as follows:</p><p>Let us imagine that our cost function is a mountainous region, and the aim of our optimization function, gradient descent, is to find the valley in this mountainous region (i.e., the minima of the cost function). Continuing with the analogy of the mountainous region, let’s assume that a blindfolded person is dropped somewhere on the mountain, and is asked to get to the base of the mountain.</p><p>Now, owing to the blindfold, naturally, the person won’t know the direction to the base of the mountain. Therefore, the best information available to the person regarding the direction to the base will be the <strong>direction of the steepest slope at every step they take</strong>. Hence, following the gradient descent approach, our blindfolded person will move in such a way that each step that they take will be in the direction of the steepest descent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*vRM9cQPzkD7VBCaXr9QC1g.png" /><figcaption>The descent down a mountain (Image by author)</figcaption></figure><blockquote>Basically, the gradient descent algorithm follows a <strong>greedy search strategy</strong>, where there might be a better solution in some other direction, however, the parameters get updated only in the direction relative to the gradient (or slope).</blockquote><p><strong>This search strategy however has a major flaw associated with it!</strong> Since it’s a greedy algorithm, there are <strong><em>high chances that the algorithm will run into a local minimum instead of a global minimum</em></strong>, and hence we might never converge to the optimal parameter values for the least model cost.</p><h4>Effect of Learning Rate (γ)</h4><p>When it comes to parameter updation in the gradient descent algorithm, the value of the hyperparameter γ, which denotes the step size (or learning rate) plays a key role.</p><ul><li><strong>If </strong>γ<strong> is too low</strong>, the chance of reaching an optimal solution will increase. However, the convergence rate, i.e., how fast the minimum is reached, will be decreased drastically. This simply means that the number of epochs the model will have to be trained for will increase when the learning rate is too low.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*pG_ntjBdiHtRCM-yrvEy6w.png" /><figcaption>γ is too small (Image by author)</figcaption></figure><ul><li><strong>If </strong>γ<strong> is too large</strong>, the probability of attaining the optima is reduced as the model parameters tend to oscillate around the minima. However, the convergence rate increases as a result of the larger step size. Another noticeable disadvantage of a high learning rate is a phenomenon called divergence, which simply means loss explosion.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*WpDnOOKhBpDjKMwV_IA4Sg.png" /><figcaption>γ is too large (Image by author)</figcaption></figure><p><strong>A practical way to deal with this trade-off between a high learning rate and a low learning rate is to have a variable learning rate</strong>— A larger learning rate for the initial epochs, then a reduced learning rate for the later epochs as we proceed further down the model training process. This will have the advantage of both a high learning rate (faster convergence) and a low learning rate (higher probability of reaching the optima).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*ZZAv70Y2aSUali-xF77KKA.png" /></figure><p>While gradient descent is easy to implement, its drawback of being prone to frequently run into local optimum is something too significant to overlook.</p><blockquote>What good is an optimization algorithm if it can’t actually minimize the model cost?</blockquote><p>Hence, researchers came up with the modified, more optimized version of gradient descent- Stochastic Gradient Descent.</p><h3>Stochastic Gradient Descent</h3><p>While stochastic gradient descent belongs to the same class of first-order iterative optimization algorithm as the gradient descent algorithm, it is a significant improvement over gradient descent— both computationally and performance-wise.</p><p>In SGD, instead of using the gradients of the entire training set for weight updation, we stochastically (randomly) choose a data instance from the training set, then perform weight updation based on the gradients for that single data instance.</p><p>The generalized formula can be given as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*hljMHo9fGyyA9S5Llcs65w.png" /><figcaption>Stochastic Gradient Descent formula (Image by author)</figcaption></figure><p>One look at the SGD formula and it’s clear that it is very much similar to the gradient descent algorithm. The only difference is that instead of taking the gradient of the model loss for the entire batch of data instances, SGD uses the gradient of the model loss of a single instance of data chosen uniformly at random from the dataset.</p><p>Yet, in practice, SGD works significantly better as compared to gradient descent, the reason being the <strong>noisy parameter updates</strong> in SGD. Since we are updating the parameters after forward-prop on every single instance, rather than after accumulating the gradients of the entire training set, the parameters tend to bounce around. This, to some extent, <strong>reduces the probability of getting stuck in a local minimum</strong>. This phenomenon is known as <strong>annealing</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*D_EA2XfG_zwKFaVrpPuw0w.png" /><figcaption>Annealing in SGD (Image by author)</figcaption></figure><p>Also, it is observed that <strong>SGD is computationally less expensive</strong> as compared to GD, thus <strong>significantly reducing the training time</strong>.</p><p>In theory, <strong>we assume that all the data instances in the dataset are independent</strong> w.r.t. each other, i.e., all the instances in the training set are unique. <strong>However, in practice, there’s a lot of redundancy (similar data instances) in the dataset.</strong> This tends to drive the noise in the dataset lower, thus ensuring that the updated parameter values are close to, if not better, than the ones obtained from gradient descent.</p><p><strong>Note: </strong>In practice, instead of updating the model parameters on single data instances, we perform the weight updation on mini-batches of data. This can be thought of as a hybrid of GD and SGD. The advantage of <strong>mini-batch-SGD</strong> is that it is optimized for parallelization on GPUs (i.e., the model function can process multiple data instances at the same time), thus allowing for even faster training times and less noise.</p><h3>Momentum-Based SGD</h3><p>If we talk in terms of Physics terminology, momentum is the property of an object to keep it moving in the direction it is already moving in. In other words, momentum is the physical property of an object that allows it to maintain its direction and state of motion.</p><p>When we talked about Stochastic Gradient Descent in the last section, we observed that the model parameters oscillate a lot due to the noise. This excessive noise, while effective against local minima in practice, prevents the model loss function from attaining the absolute minimum. Hence, the cost function might never attain convergence, as can be seen in the image on the left given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*KWbaJM93BG7qY2vwXiXUGA.png" /><figcaption>SGD vs SGD+Momentum (Source: <a href="https://atcold.github.io/pytorch-Deep-Learning/en/week05/05-1/">https://atcold.github.io/pytorch-Deep-Learning/en/week05/05-1/</a>)</figcaption></figure><p>Therefore, in order to reduce these oscillations, optimization researchers used the motivation behind the Newtonian Physics’ momentum and introduced a momentum-based variation of the Stochastic Gradient Descent algorithm.</p><p>To understand how momentum works, let us have a look at the generalized formula for SGD with momentum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*30jj5iqIq_W5AgGXNmRu5A.png" /><figcaption>SGD+Momentum (Image by author)</figcaption></figure><p><strong>Here’s how SGD+momentum works:</strong></p><ul><li>In non-momentum SGD, the parameters are updated via greedy search in the direction of the gradient.</li><li>However, in SGD+momentum, the momentum additive from the previous steps influences the descent down the slope. As a result, instead of oscillating around in the direction of the negative gradient, the parameter updation is forced along a certain direction. This, as a result, dampens the noise and therefore increases the probability of the model cost attaining the absolute minima.</li></ul><p>If you pay close attention to the formula for the momentum, it is just an accumulation of gradients after each parameter updation step in SGD. However, one important thing to note here is that the hyperparameter β (ranging between 0–1) dampens the accumulated gradients after each step. Thus, the momentum generated due to the gradients in the more recent steps affects the parameter updation more as compared to the momentum in much earlier steps.</p><p>In practice, as we can see in the image above, momentum increases the probability of convergence, while at the same time not being very computationally extensive. This is the reason why most Deep Learning and Machine Learning packages use the momentum-based implementation of SGD rather than the regular one.</p><p>With this, we come to an end of this article. The key takeaways from this article were:</p><ul><li>We saw what model optimization is.</li><li>We had an overview of some of the most widely used optimization algorithms like gradient descent, stochastic gradient descent, and momentum-based SGD.</li></ul><p>If you found the article helpful and would love to keep seeing more articles like this, make sure you hit the follow button.</p><p><strong>Here are some of my other curated articles:</strong></p><ul><li><a href="https://towardsdatascience.com/ml-from-scratch-k-nearest-neighbors-classifier-3fc51438346b">ML from Scratch: K-Nearest Neighbors Classifier</a></li><li><a href="https://towardsdatascience.com/ml-from-scratch-multinomial-logistic-regression-6dda9cbacf9d">ML from Scratch-Multinomial Logistic Regression</a></li><li><a href="https://towardsdatascience.com/linear-regression-model-with-numpy-7d270feaca63">Linear Regression Model with NumPy</a></li></ul><p>You can connect with me on LinkedIn:</p><p><a href="https://www.linkedin.com/in/amansharma2910/">Aman Sharma - Microsoft Learn Student Ambassador - Microsoft | LinkedIn</a></p><p>Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edcf5a104210" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-hitchhikers-guide-to-optimization-in-machine-learning-edcf5a104210">The Hitchhiker’s Guide to Optimization in Machine Learning</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[ML from Scratch: K-Nearest Neighbors Classifier]]></title>
            <link>https://medium.com/data-science/ml-from-scratch-k-nearest-neighbors-classifier-3fc51438346b?source=rss-84e03a4d7261------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fc51438346b</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Aman Sharma]]></dc:creator>
            <pubDate>Sun, 13 Sep 2020 21:11:10 GMT</pubDate>
            <atom:updated>2020-09-14T02:26:31.551Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xE8Us7Jb8WdhrfobGSEidQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@qwitka?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Maksym Kaharlytskyi</a> on <a href="https://unsplash.com/s/photos/wine?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>A Complete Guide to the KNN Classification Algorithm, where We Will See How to Implement a KNN-Based Machine Learning Model from Scratch, while Understanding the Mathematics Behind it.</h4><p>When it comes to solving classification problems via machine learning, there’s a wide variety of algorithm choices available for almost any data type or niche problem that one might be dealing with. These algorithmic choices can be broadly categorized into two groups, which are as follows.</p><ol><li><strong>Parametric Algorithms: </strong>The algorithms belonging to this category rely on algebraic mathematical equations, that use a <strong>set of weights and biases</strong> (collectively known as parameters), in order to predict the final discrete outcome for a given set of data. The model size, i.e., the total number of trainable parameters in the model, can vary from just a few (such as, in the case of <a href="https://datamahadev.com/classification-algorithms-explained-in-30-minutes/">traditional machine learning algorithms</a>) to millions or even billions (as generally seen in the case of <a href="https://datamahadev.com/artificial-neural-networks-detailed-explanation/">artificial neural nets</a>).</li><li><strong>Non-Parametric Algorithms: </strong>The classification algorithms in this category are rather unique in the sense that they <strong><em>don’t use any trainable parameters at all</em></strong>. This means that in order to generate predictions, <em>unlike their parametric counterparts</em>, the models in this category don’t rely on a set of weights and biases, or have any assumptions regarding the data. Rather, in order to predict, say, the target class of a new data point, the models use some sort of comparison techniques that help them determine a final outcome.</li></ol><p>Today, in this article, we are going to study one such non-parametric classification algorithm in detail—<strong> the K-Nearest Neighbors (KNN) algorithm.</strong></p><p>This is going to be a <em>project-based guide</em>, where in the first part, we will be understanding the basics of the KNN algorithm. This will then be followed by a project where we will be implementing a KNN model from scratch using basic PyData libraries like <strong>NumPy </strong>and <strong>Pandas</strong>, while understanding the mathematical foundations of the algorithm.</p><p>So buckle up, and let’s get started!</p><h3>KNN Classifier Basics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqGBK_0wVZNNj_DokuBv_g.jpeg" /><figcaption>KNN Classification (Image by author)</figcaption></figure><p>To begin with, the KNN algorithm is one of the classic <strong>supervised machine learning </strong>algorithms that is capable of both <strong>binary</strong> and <strong>multi-class classification</strong>. <strong>Non-parametric</strong> by nature, KNN can also be used as a <strong>regression algorithm. </strong><em>However, for the scope of this article, we will only focus on the classification aspect of KNN.</em></p><blockquote><strong><em>KNN classification at a glance-</em></strong></blockquote><blockquote>→ Supervised algorithm</blockquote><blockquote>→ Non-parametric</blockquote><blockquote>→ Used for both regression and classification</blockquote><blockquote>→ Support for both binary and multi-class classification</blockquote><p>Before we move any further, let us first break down the definition and understand a few of the terms that we came across.</p><ul><li><strong>KNN is a “supervised” algorithm-</strong> In layman&#39;s terms, this means that the data used for training a KNN model is a labeled one.</li><li><strong>KNN is used for both “binary” and “multi-class classification”-</strong> In the machine learning terminology, a classification problem is one where, given a list of discrete values as possible prediction outcomes (known as <strong>target classes), </strong>the aim of the model is to determine which target class a given data point might belong to. For binary classification problems, the number of possible target classes is 2. On the other hand, a multi-class classification problem, as the name suggests, has more than 2 possible target classes. A KNN classifier can be used to solve either kind of classification problems.</li></ul><p>With that done, we have a rough idea regarding what KNN is. But now, a very important question arises.</p><h4>How does a KNN Classifier work?</h4><p>As we read earlier, KNN is a non-parametric algorithm. Therefore, training a KNN classifier doesn’t require going through the more traditional approach of iterating over the training data for multiple epochs in order to optimize a set of parameters.</p><p>Rather, the actual training process in the case of KNN is quite the opposite. Training a KNN model involves simply fitting <em>(or saving)</em> all the training data instances into the computer memory at the same time, which technically requires a single training cycle.</p><p>After this is done, then during the inference stage, where the model has to predict the target class for a completely new data point, the model simply compares this new data with the existing training data instances. Then finally, on the basis of this comparison, the model assigns this new data point to its target class.</p><p>But now another question arises. What exactly is this comparison that we are talking about, and how does it occur? Well quite honestly, the answer to this question is hidden in the name of the algorithm itself — <em>K-Nearest Neighbors</em>.</p><p>To understand this better, let us dive deeper into <strong>how the inference process works.</strong></p><ul><li>As the first step, our KNN model<strong> </strong>calculates the distance of this new data point from every single data point within the ‘fitted’ training data.</li><li>Then, in the next step, the algorithm selects ‘k’ number of training data points that are closest to this new data point in terms of the calculated distance.</li><li>Finally, the algorithm compares the target label of these ‘k’ points that are the nearest neighbors to our new data point. The target label with the highest frequency among these k-neighbors is assigned as the target class to the new data point.</li></ul><p>And that’s how the KNN classification algorithm works.</p><p>Regarding the calculation of the distances between the data points, we will be using the Euclidean distance formula. We will be understanding this distance calculation in the next section where we will be code our own KNN-based machine learning model from scratch.</p><p>So now onto the fun, practical part! We will begin by having a quick glance at the problem statement that we are addressing via our project.</p><h3>Understanding the Problem Statement</h3><p>For this project, we will be working on the famous <a href="https://archive.ics.uci.edu/ml/datasets/wine+quality#:~:text=UCI%20Machine%20Learning%20Repository%3A%20Wine%20Quality%20Data%20Set&amp;text=Abstract%3A%20Two%20datasets%20are%20included,%2C%20%5BWeb%20Link%5D)."><em>UCI Red Wine Dataset</em></a>. The aim of this project is to create a machine learning solution that can predict the quality of a red wine sample.</p><p>This is a multi-class classification problem. The target variable, i.e., the ‘quality’ of the wine, accepts a discrete integer value ranging from 0–10, where a quality score of 10 denotes a wine of the highest quality standards.</p><p>Now that we have understood the problem, let us begin with the project by importing all the necessary project dependencies, which includes the necessary PyData modules and the dataset.</p><h3>Importing Project Dependencies</h3><p>In the first step, let us import all the necessary Python modules.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de848228fc634de2b302fe9026637c03/href">https://medium.com/media/de848228fc634de2b302fe9026637c03/href</a></iframe><p>Now, let’s import our dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d99fd43bc0e244788bba1cc29c9833ec/href">https://medium.com/media/d99fd43bc0e244788bba1cc29c9833ec/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ABnV9KWbcNk05ZEuGTNlfA.png" /><figcaption>A quick glance at the dataset (image by author)</figcaption></figure><p>Now that we have imported the dataset, let us try to understand what each of the columns in our data denotes.</p><h3>Understanding the Data</h3><p>The following is a brief description of all the individual columns within our dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_wL2CGdO2995nb8rhXUlw.jpeg" /><figcaption>Description of the dataset (image by author)</figcaption></figure><p>As we discussed earlier, the ‘quality’ column is the target variable for this project. The rest of the columns in the dataset represent the feature variables that will be used for training the model.</p><p>Now that we know what the different columns in our dataset represent, let us move on to the next section where we will be doing some pre-processing and exploration of our data.</p><h3>Data Wrangling and EDA</h3><p>Data wrangling <em>(or preprocessing)</em> involves analyzing the data to see if it needs any sort of cleaning or scaling so that it can be prepared for training the model.</p><p>As the first step of data preprocessing, we will check if there are any null values within our data that need to be dealt with.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8a6335b98f3c53c1d1ef8edf803b5d8/href">https://medium.com/media/e8a6335b98f3c53c1d1ef8edf803b5d8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*7DX5dedSYcItaIqzRTxKJg.png" /><figcaption>Column description and null value count (image by author)</figcaption></figure><p>As we can see, there are no null values within our dataset. This is a good thing since we won’t have to deal with any missing data. Now, let us have a look at the statistical analysis of the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cd332d179f86e516a9cc95cad4d9712/href">https://medium.com/media/3cd332d179f86e516a9cc95cad4d9712/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_dVZUYwSJJTkI-2V2aRpiw.png" /></figure><p>One prominent observation from the above given statistical analysis is that there’s a visible inconsistency in the range of values across different columns within our dataset. To be more clear, the values in some columns are of the order <em>1e-1</em> while in a few others, the values can go as high as of the order <em>1e+2</em>. Because of this inconsistency, there are chances that a feature weight bias might arise at the time of training the model. What is basically means is that some features might end up affecting the final prediction more than the others. Therefore, in order to prevent this weight imbalance, we will have to scale our data.</p><p>For this scaling, we will be standardizing our data. <strong><em>Standardization </em></strong>typically means rescaling data in a way such that each feature column has a mean of 0 and a standard deviation of 1 (unit variance).</p><p>The following is the mathematical formula for standard scaling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*U3pChnKEJ2Xij4xBPOqDBQ.jpeg" /></figure><p>Now that we know the mathematical formula, let us go ahead and implement this from scratch in Python.</p><p><strong>Step-1</strong>: Separating the feature matrix and the target array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d5784ce401068b8e5ced1bc0208cff3/href">https://medium.com/media/5d5784ce401068b8e5ced1bc0208cff3/href</a></iframe><p><strong>Step-2</strong>: Declaring the standardization function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/428956696d141ad99491dfafdbdf28b6/href">https://medium.com/media/428956696d141ad99491dfafdbdf28b6/href</a></iframe><p><strong>Step-3</strong>: Performing standardization on the feature set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fad28cf05a6b6d9319410fa57fdbb64/href">https://medium.com/media/4fad28cf05a6b6d9319410fa57fdbb64/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*oHegaPf_-_oNpPBMUbR-pQ.png" /><figcaption>Standardized data (image by author)</figcaption></figure><p>With this, we are done with standardized our data. This will most probably take care of weight bias.</p><p>Now for the last part of our data wrangling and EDA section, we will have a look at the distribution of values across the target column of our dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea488a4001aff2da37f28e9417b3b6f6/href">https://medium.com/media/ea488a4001aff2da37f28e9417b3b6f6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*6c2oDzucL_xjfDhWQxCNUg.png" /><figcaption>Target label counts (Image by author)</figcaption></figure><p>Some of the observations from the above-given graph are-</p><ul><li>Most wine samples in our data are rated 5 and 6, followed by 7.</li><li>No wine sample is rated above 8 or below 3. This implies that a wine sample of extremely high quality (9 or 10) or very low quality (0, 1 or 2) rating can either be thought of as a hypothetically ideal situation, or that probably that <strong>data is suffering from sampling bias</strong>, where the samples of extreme quality didn’t get any representation within the survey.</li><li>Our last assumption of a sampling bias within the data is further strengthened as we notice that a majority of wine samples are rated 5 or 6.</li><li>A model trained on such data will produce biased results, where it is more likely to classify a wine sample as a 5 or 6 on the quality scale as compared to, say, 3 or 8. To know more about sampling bias or how to deal with it, check out <a href="https://datamahadev.com/sampling-bias-in-data-science/">this article</a> of mine.</li></ul><p>Now that we are done exploring our data, let us move on to the final part of our project where we will be code our multi-class classifier KNN model using NumPy.</p><h3>Modeling and Evaluation</h3><p>As the first step of our modeling process, we will first split our dataset into training and test sets. <em>This is done because training and evaluating your model on the same data is considered a bad practice.</em></p><p>Let’s see how to implement the code to split the dataset using Python.</p><p>Step-1: Declaring the split function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2f4d5f55721a62e7087ad88b07ba1e8/href">https://medium.com/media/b2f4d5f55721a62e7087ad88b07ba1e8/href</a></iframe><p>Step-2: Running the splitting function on our standardized dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81023e3b9b1589d044156e87768bbde2/href">https://medium.com/media/81023e3b9b1589d044156e87768bbde2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*-N0rWGtxRkbhbuWl0l9gvg.png" /><figcaption>Shape of the splits (Image by author)</figcaption></figure><p>Now that we have created our training and validation sets, we will finally see how to implement the model.</p><p>On the basis of what we have learned till now, here are the steps involved in creating a KNN model.</p><p><strong>Step-1: Training the model- </strong>As we read earlier, in the case of KNN, this simply means saving the training dataset within the memory. We have already done that when we created our training and validation data splits.</p><p><strong>Step-2: Calculating the distance- </strong>A<strong> </strong>part of the inference process in the KNN algorithm, the process of calculating the distance is an iterative process where we calculate the Euclidean distance of a data point <em>(basically, a data instance/row)</em> in the test data from every single data point within the training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EjbgAueVdmcjPktUFfFRww.jpeg" /><figcaption>Calculation of distance (Image by author)</figcaption></figure><p>Now, let us understand how the Euclidean distance formula works so that we can implement it for our model.</p><ul><li>Let us consider <strong>two data points A and B.</strong></li></ul><p><strong>→ A</strong> = [<strong>a</strong>0, <strong>a</strong>1, <strong>a</strong>2, <strong>a</strong>3,…. <strong>a</strong>n], where <strong>a</strong>i is a feature that represents the data point A.</p><p><strong>→ </strong>Similarly, <strong>B= </strong>[<strong>b</strong>0, <strong>b</strong>1<strong>, b</strong>2<strong>, b</strong>3<strong>,…. b</strong>n].</p><p>Therefore, the Euclidean distance between the data points A and B is calculated using the following formula-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2QtZjSpuKDq1fpSVLnNBw.jpeg" /><figcaption>Euclidean distance formula (image by author)</figcaption></figure><p>Let’s now implement this distance calculation step in Python.</p><ul><li><strong>Step-2.1</strong>: Declaring Python function to calculate Euclidean distance between 2 points.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59b24ac07cd6996a69f6d2dcff2fa197/href">https://medium.com/media/59b24ac07cd6996a69f6d2dcff2fa197/href</a></iframe><ul><li><strong>Step-2.2</strong>: Declaring a Python function to calculate the distance from each point in the training data</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7843c01321d1b6ae50f367ad2ab93702/href">https://medium.com/media/7843c01321d1b6ae50f367ad2ab93702/href</a></iframe><p>Before we move on to the next step, let us test our distance function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76e92c1c3681259dae9130399d1eaa5b/href">https://medium.com/media/76e92c1c3681259dae9130399d1eaa5b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*_6yZZkHs-CnrOaonfyCxsg.png" /></figure><p>As we can see, our distance function successfully calculated the distance of the first point in our test data from all the training data points. Now we can move on to the next step.</p><p><strong>Step-3: Selecting k-nearest neighbors and making the prediction-</strong> This is the final step of the inference stage, where the algorithm selects the k-closest training data points to the test data point based on the distances calculated in step 2. Then, we consider the target labels of these k-nearest neighboring points. The label with the highest occurring frequency is assigned as the target class to the test data point.</p><p>Let us see how to implement this in Python.</p><p><strong>Step-3.1</strong>: Defining the KNN Classification function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/687bb7c07747a7612de53aec578bfaae/href">https://medium.com/media/687bb7c07747a7612de53aec578bfaae/href</a></iframe><p><strong>Step-3.2</strong>: Running inference on our test dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/004dd43546eb77963bd546734d5334cb/href">https://medium.com/media/004dd43546eb77963bd546734d5334cb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*6HOZUGH2aWXXfE0eG3TmiA.png" /><figcaption>Array of predicted values (Image by author)</figcaption></figure><p>With this, we have completed the modeling and inference process. As a final step, we will evaluate our models’ performance. For this, we will be using a simple accuracy function that calculates the number of correct predictions made by our model.</p><p>Let’s have a look at how to implement the accuracy function in Python.</p><p><strong>Step-1</strong>: Defining the accuracy function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb1af9eb8c57bb96eb05e17dee3a9cc8/href">https://medium.com/media/eb1af9eb8c57bb96eb05e17dee3a9cc8/href</a></iframe><p><strong>Step-2</strong>: Checking the accuracy of our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8c3e713a9ddd10b6e38fda9de10a771/href">https://medium.com/media/f8c3e713a9ddd10b6e38fda9de10a771/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*Gi6DK18S891ym1f3NUh9YQ.png" /><figcaption>Initial model accuracy</figcaption></figure><p><strong>Step-3</strong>: Comparing with the accuracy of a KNN classifier <strong>built using the Scikit-Learn library</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/134e42d188a0fd822a39856c6e1abbd0/href">https://medium.com/media/134e42d188a0fd822a39856c6e1abbd0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*IUbL2zxqdDKmZV5A7PQWYQ.png" /><figcaption>Sklearn accuracy with the same k-value as scratch model</figcaption></figure><p>An interesting observation here! Though our model didn’t perform very well (with only 57% correct prediction), it has the exact same accuracy as a Scikit-Learn KNN model. This means the model that we defined from scratch was least able to replicate the performance of a pre-defined model, which is an achievement in itself!</p><p>However, I believe we can further improve the model’s performance to some extent. Therefore, as the last part of our project, we will find the best value of the <strong>hyperparameter </strong>‘k’ for which our model gives the highest accuracy.</p><h3>Model Optimization</h3><p>Before we actually go on to finding the best k-value, first, let us understand the importance of the k-value in the K-Nearest Neighbors algorithm.</p><ul><li>The k-value in the KNN algorithm determines the number of training data points that are to be considered while determining the class of the test data points.</li><li><strong>Impact of a low k-value: </strong>If the k-value is very low, say, 1 or 2, the model will become very sensitive to outliers in the data. <em>Outliers can be defined as the extreme instances within the data that do not follow the general trends within the data. </em>Because of this, the predictions of the model become very unstable.</li><li><strong>Impact of a high k-value: </strong>Now, as the k-value in the KNN algorithm increases, a weird trend is observed. At first, an increase is observed in the stability of the algorithm. One reason for this can be that as we consider more neighbors for predicting the target class of a test data point, because of majority voting, the effect of outliers decreases. However, as we continue to increase the k-value, after a certain point, we start to observe a decline in the stability of the algorithm, and the model accuracy starts to deteriorate.</li></ul><p>The following graph roughly represents the relation between the k-value and stability of a KNN classifier model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cVrUPJOuFwJkF6g_mC0qsw.jpeg" /><figcaption>k-value vs stability (Image by author)</figcaption></figure><p>Now, let us finally evaluate the model for a range of different k-values. The one with the highest accuracy will be chosen as the final k-value for our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f55606379a6f40980a9ecc69c53d2b1/href">https://medium.com/media/6f55606379a6f40980a9ecc69c53d2b1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*9CBfCSv-a6T9KCXqZ4_tZQ.png" /><figcaption>Model accuracy w/ different k-values (Image by author)</figcaption></figure><p>As we can see, k-value 1 has the highest accuracy. But as we discussed earlier, for k=1, the model will be very sensitive to outliers. Hence, we will go with k=8 which has the second-highest accuracy. Let us observe the results with k=8.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d90daed8b1e9affa0dbd0b5fae1c196f/href">https://medium.com/media/d90daed8b1e9affa0dbd0b5fae1c196f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*IPGdRLgCnUGm2mcg-Vzojg.png" /></figure><p>As you can see, we got a performance boost here! Just by tweaking the hyperparameter ‘k’, our model’s accuracy bumped up by almost 3 percent.</p><p>With this, we come to the end of our project.</p><p>To finish things off, let us have a quick rundown of all that we learned today, as well as some of the key takeaways from this lesson.</p><h3>Conclusions</h3><p>In this article, we had an in-depth analysis of the K-Nearest Neighbors classification algorithm. We understood how the algorithm uses Euclidean distance between the data instances as a criterion of comparison, on the basis of which it predicts the target class for a particular data instance.</p><p>In the second part of this guide, we went through a step-by-step process of creating a KNN classification model from scratch, primarily using Python and NumPy.</p><p>Though our model was not able to give a stellar performance, at least we were able to match the performance of a predefined Scikit-Learn mode. Now, while we were able to increase the model’s accuracy up to 60% via hyperparameter optimization, the performance was still not apt.</p><p>This has a lot to do with how the data was structured. As we observed earlier, there was a huge sampling bias in the data. This certainly affected our model’s performance. Another reason for the poor performance can be that probably, the data had a large number of outliers. All this brings us to a very important part that I left for the very end, where we will have a look at the advantages and disadvantages of the KNN classification algorithm.</p><h4>Advantages of KNN-</h4><ul><li>As we discussed earlier, being a non-parametric algorithm, KNN doesn’t require multiple training cycles in order to adapt to the trends within the training data. As a result of this, KNN has an <strong>almost negligible training time,</strong> and in fact, is one of the fastest machine learning algorithms when it comes to training.</li><li>The <strong>implementation of KNN is very easy</strong>, as compared to some other, more complex classification algorithms.</li></ul><h4>Disadvantages of KNN–</h4><ul><li>When it comes to inference, KNN is <strong>very compute-intensive</strong>. For inference on each test data instance, the algorithm has to calculate its distance from every single point in the training data. In terms of <strong>time complexity</strong>, for n-number of training data instances and m-number of test data instances, the complexity of the algorithm evaluates to <strong>O(m x n)</strong>.</li><li>As the dimensionality <em>(i.e., the total number of features)</em> and the scale of the dataset <em>(i.e., the total number of data instances)</em> increases, the model size also increases, which in turn impacts the performance and speed of the model. Therefore, KNN is not a good algorithm choice when it comes to high dimensional, large scale datasets.</li><li>The KNN algorithm is <strong>very sensitive to outliers</strong> in the data. Even a slight increase in the noise within the dataset might drastically affect the model’s performance.</li></ul><p>With this, we finally come to an end of today’s learning session. <a href="https://datamahadev.com/machine-learning-classification-algorithms-step-by-step-comparison/">In another article of mine</a>, I have directly pitted a bunch of machine learning algorithms against each other. There, you can check out how KNN fares against other classification algorithms like logistic regression, decision tree classifiers, random forest ensembles, etc.</p><p>By the way, this was the fourth article in my <strong>ML from Scratch</strong> series, where I cover different machine learning algorithms and their mathematical foundations in detail. If you are interested in learning more, the other articles in this series are-</p><ul><li><a href="https://towardsdatascience.com/ml-from-scratch-multinomial-logistic-regression-6dda9cbacf9d">ML from Scratch-Multinomial Logistic Regression</a></li><li><a href="https://towardsdatascience.com/polynomial-regression-using-pytorch-from-scratch-500b7887b0ed">Polynomial Regression Using PyTorch (From Scratch)</a></li><li><a href="https://towardsdatascience.com/linear-regression-model-with-numpy-7d270feaca63">Linear Regression Model with NumPy</a></li></ul><p><a href="https://github.com/amansharma2910/MachineLearning-Scratch_WineClassificationKNN"><strong>Link to the project GitHub files</strong></a><strong>.</strong></p><p>If you liked the article and would love to keep seeing more articles in the <strong>ML from Scratch</strong> series, make sure you hit that follow button.</p><p>Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fc51438346b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/ml-from-scratch-k-nearest-neighbors-classifier-3fc51438346b">ML from Scratch: K-Nearest Neighbors Classifier</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[ML from Scratch-Multinomial Logistic Regression]]></title>
            <link>https://medium.com/data-science/ml-from-scratch-multinomial-logistic-regression-6dda9cbacf9d?source=rss-84e03a4d7261------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dda9cbacf9d</guid>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Aman Sharma]]></dc:creator>
            <pubDate>Mon, 15 Jun 2020 00:32:52 GMT</pubDate>
            <atom:updated>2020-06-15T00:52:51.034Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfvJRMAf0qNBApc95WML9w.jpeg" /><figcaption>Image source- Unsplash.com</figcaption></figure><h4>Your Complete Guide to Multinomial Logistic Regression, a.k.a. Softmax Regression</h4><p>When it comes to real-world machine learning, around <em>70%</em> of the problems are classification-based, where, on the basis of the available set of features, your model tries to predict that out of a given set of categories(discrete possible outcomes), what category does your target variable might belong to. <strong>Today, in this article, we are going to have a look at Multinomial Logistic Regression− one of the classic supervised machine learning algorithms capable of doing <em>multi-class classification</em>, </strong>i.e., predict an outcome for the target variable when there are more than 2 possible discrete classes of outcomes.</p><p>This is a project-based guide, where we will see how to code an MLR model from scratch while understanding the mathematics involved that allows the model to make predictions.</p><p>For the project, we will be working on the famous <a href="https://archive.ics.uci.edu/ml/datasets/Heart+Disease"><em>UCI Cleveland Heart Disease dataset</em></a>. <strong>We will create an ML model from scratch that uses multinomial logistic regression, capable of predicting the severity of heart disease within a patient.</strong></p><h3>Multinomial Logistic Regression Basics</h3><p>Before we start working on the actual project, let us first familiarize ourselves with the basic idea behind MLR- what it is, what it does, and how it operates?</p><h4>What exactly is Multinomial Logistic Regression?</h4><p>You can think of multinomial logistic regression as logistic regression (more specifically, binary logistic regression) on steroids. While the binary logistic regression can predict binary outcomes (eg.- yes or no, spam or not spam, 0 or 1, etc.), the MLR can predict one out of k-possible outcomes, where k can be any arbitrary positive integer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dVsfG6i-Y93prmLgTcxRwA.jpeg" /><figcaption>The outcome predicted for a feature set is one of the k-possible outcomes</figcaption></figure><h4>How does MLR work?</h4><p>The multinomial regression function<em> </em>is a<em> </em><strong><em>statistical classification algorithm</em></strong>. What this means is that once we feed the function a set of features, the model performs a series of mathematical operations to normalize the input values into a vector of values that follows a probability distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*23H-Vwy_p43ai0Qvz9d6Pg.jpeg" /><figcaption>The MLR function calculates probabilities for possible target classes from the given feature set</figcaption></figure><ul><li>The input that we give to the model is a feature vector, <strong>X</strong>, containing features <strong>x</strong><em>1</em>, <strong>x</strong><em>2</em>, <strong>x</strong><em>3</em>…..<strong>x</strong><em>n</em>.</li><li>The output we get is a probability vector <strong>Y</strong>, containing probabilities <strong>y</strong><em>1</em>, <strong>y</strong><em>2</em>, <strong>y</strong><em>3</em>…<strong>y</strong><em>k</em> for the <strong>k</strong> target classes.</li><li>Here, <strong>y</strong><em>1</em> + <strong>y</strong><em>2</em> + <strong>y</strong><em>3</em>… + <strong>y</strong><em>k</em> = 1, since the total probability of all the possible events in a system is always 1.</li></ul><p>Finally, the outcome with the highest probability will be the predicted outcome for the given feature set.</p><p><strong>Now the question is, how exactly does the MLR function convert feature sets to probability values?</strong> We will try to understand this while working on our project.</p><h3>Importing Project Dependencies</h3><p>Before we begin working on the project, let us first import all the necessary modules and packages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8847a5018cfd3fa5c3722c9cd455a85/href">https://medium.com/media/f8847a5018cfd3fa5c3722c9cd455a85/href</a></iframe><p>Now, we will import the dataset. According to the <a href="https://archive.ics.uci.edu/ml/datasets/Heart+Disease">data source</a>, the dataset does not have column names. So we will set the header attribute as None and then we will manually set the column names as per the information available on the source.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c287869600bb538695fb1b4d41234e3c/href">https://medium.com/media/c287869600bb538695fb1b4d41234e3c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*Ybh-Qf0CQ2SZ543L3dvYuA.png" /><figcaption>Screenshot showing the dataset</figcaption></figure><h4>Understanding the Data</h4><p>Now that we have imported the dataset, let us try to understand what each of these columns denotes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A03KDT7F2GRpSQq4OHVd5Q.jpeg" /></figure><p>Here, the <strong>num </strong>column is our target variable, with the values ranging from 0 (no disease present) to 4 (high chances of heart disease).</p><p>Now that we know exactly what our dataset represents, let us move on to the next step.</p><h3>Data Preprocessing</h3><p>Now, let us analyze the data and see if it needs any cleaning or modifications. As the first step of our data preprocessing, we will check if there are any null values that need to be dealt with.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f4a7ffc3fc5a938ad2d75b55a089b57/href">https://medium.com/media/1f4a7ffc3fc5a938ad2d75b55a089b57/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*KyLHG3_DsmEfGzyNotTx_g.jpeg" /></figure><p>As we can see, the columns <strong>ca</strong> and <strong>thal</strong> have 4 and 2 <strong>‘?’</strong> values respectively. These are null values that we need to deal with. Since both these columns consist of categorical values, we will replace the null values with the median of the respective columns. We will also type-cast the two columns to <em>‘float64’ values.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2a1bbffc120411cee5eddd9eabbd488/href">https://medium.com/media/e2a1bbffc120411cee5eddd9eabbd488/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*aHPWImM0aO75Km29cFpOeQ.png" /></figure><p>Now that we have cleaned our data, let us have a look at the statistical analysis of our dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dca798f1fbf0f210fb7b527270a2bb18/href">https://medium.com/media/dca798f1fbf0f210fb7b527270a2bb18/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_RIv3oT-sKZ79oF_0lPzPg.png" /><figcaption>Statistical analysis of the dataset</figcaption></figure><p>Upon observing the data, we can see that the data needs to be scaled since we have values in the range <em>(1, 1e+2). The main reason we are scaling our data is that since we will be using Stochastic Gradient Descent for optimizing our model parameters, scaling can significantly improve the speed and accuracy of our optimizer.</em></p><p>Here, we will use standard scaling in order to standardize the data. <strong><em>Standardization </em></strong>typically means rescaling data to have a mean of 0 and a standard deviation of 1 (unit variance). The following is the mathematical formula for standard scaling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*sn2lNhtSyj1wLDPoNHfihw.jpeg" /></figure><p>Here,</p><ul><li><strong>μ = Mean of all the values within a column</strong></li><li><strong>σ = Standard deviation of the column</strong></li></ul><p>Now, let us implement this within our code. The first step is to split the dataset into target and feature arrays.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b430bce37ff094192e8cb2fce4784ff/href">https://medium.com/media/2b430bce37ff094192e8cb2fce4784ff/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*Iuy2aS4BxRa7nIQa1vAuwQ.png" /><figcaption>The shape of the feature matrix and target vector respectively</figcaption></figure><p>Now, let us define the function for standard scaling.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c333b15912bbd81164fb82cfa22f9528/href">https://medium.com/media/c333b15912bbd81164fb82cfa22f9528/href</a></iframe><p>We will now perform standardization on our features set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14524d97afc43ae3d42d38ddb02c3992/href">https://medium.com/media/14524d97afc43ae3d42d38ddb02c3992/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*cPt569_V3kLM41JGADw7sw.png" /></figure><p>As we can see, the standard deviation for each feature column is now 1, as expected of the standard scaling. We have successfully standardized our feature set.</p><p>With this, we have completed the data wrangling process. With the data cleaned and standardized, let us now start working on our model.</p><h3>Formulating the Model from Scratch</h3><p>As we saw earlier, the MLR model takes a vector of features as the input and then, on the basis of the features, computes the probabilities for the possible outcomes. So how exactly does the MLR model does that? Let us find out in this section where we will code an MLR model.</p><p>The multinomial regression function consists of two functional layers-</p><ol><li>Linear prediction function (a.k.a. logit layer)</li><li>Softmax function (a.k.a. softmax layer)</li></ol><p>First, let us see what the linear predictor function does. Given below is the formula for the linear prediction function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-sM-0yXmTTbBNZ0cF0rbaA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*qPJHnD0Z9x9Wb2lQ6JqVkA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iw6tUEi05dAtlJNZl4anbQ.jpeg" /></figure><p>If you observe carefully, this is similar to the function that we use for the linear regression model. What it basically does is that it maps the score for each possible outcome of our target variable in the range (-<strong>∞, </strong>+<strong>∞</strong>).</p><p>This is somewhat similar to the log odds(<a href="https://en.wikipedia.org/wiki/Logit">logit function</a>), which maps the odds of an event to the range (-<strong>∞, </strong>+<strong>∞</strong>). Hence, the linear predictor function is also known as the logit function.</p><p>Now, we will see the code for the linear predictor function.</p><p><strong>Step 1</strong>- Creating random weights and biases for our model (Since we have 5 possible target outcomes and 13 features, k = 5 and m = 13).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/758315a8cb825659ce390b2d0520a1b4/href">https://medium.com/media/758315a8cb825659ce390b2d0520a1b4/href</a></iframe><p><strong>Step 2</strong>- Defining the linear predictor function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6c090719eec3286e590d63070ea6e08/href">https://medium.com/media/c6c090719eec3286e590d63070ea6e08/href</a></iframe><p>Now, let us test the function for our features matrix. The final output should be a 303 x 5 matrix since we have 303 feature sets in our dataset and 5 possible outcomes for our target variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e971f24332ae17fc03f5b298c49fef68/href">https://medium.com/media/e971f24332ae17fc03f5b298c49fef68/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/98/1*X2gzWEXuZ7GiBJ-mgcyDuw.png" /></figure><p>As we can see, the function worked just fine. Now to the next step, converting logit scores to probability values. This is where the softmax function comes into the picture. Given below is the formula for the softmax algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*InhXRZP0QQjxNE6NXaxGkw.jpeg" /></figure><p>What the softmax function does is that it normalizes the logit scores for each possible outcome in a way such that the normalized outputs follow a probabilistic distribution.</p><p>In layman’s terms, the softmax function converts logit scores of the possible outcomes of a feature set to probability values.</p><p>Now, let us define the softmax function for our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e83e7e2aa158003d6797584e9153856/href">https://medium.com/media/5e83e7e2aa158003d6797584e9153856/href</a></iframe><p>Now that we have defined our softmax function as well, let us combine these two functions into a single multinomial function for our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02e41da42a49669d12631466ca37a189/href">https://medium.com/media/02e41da42a49669d12631466ca37a189/href</a></iframe><p>Now, let us perform logistic regression on our feature set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36a2af80b0f6dda45bfe505a667b99f7/href">https://medium.com/media/36a2af80b0f6dda45bfe505a667b99f7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*WXDJg7nnc3C4QbQEfvmkvg.png" /></figure><p>Let us now check the accuracy of our model. Since the weights and biases were randomly generated, we can’t expect our model to be very accurate at the moment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6e6e398a05f3d0aab67fc78018b18a6/href">https://medium.com/media/a6e6e398a05f3d0aab67fc78018b18a6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*vOcowJAJU6szCNuP1GwYyw.png" /><figcaption>Initial model accuracy</figcaption></figure><p>As we can see, the initial model accuracy is only about 16%, which is very poor to even consider this model for making any heart disease predictions in real life.</p><p>As a result, we need to optimize our model parameters in order to improve its accuracy.</p><h3>Model Optimization</h3><p>Before we proceed any further towards optimizing our model, we should first split our dataset into test and training sets. <strong>Training and testing on the same dataset is considered a bad practice</strong>, as it can severely affect your model’s real-world performance.</p><p>Let us define train_test_split function for splitting our dataset into training and testing data. We will then run it on our dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c09ebd63162763605e84ffde1f72f1ad/href">https://medium.com/media/c09ebd63162763605e84ffde1f72f1ad/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*dCRL5-ta9YuFiEHhMG-H7g.png" /><figcaption>Size of training features, training targets, testing features, and testing targets respectively</figcaption></figure><p><strong>Now that we have separate training and testing datasets, we will keep the testing dataset aside and only use it for testing purposes. All the training and optimization will be performed on the training dataset.</strong></p><p>Now we are just one step away from optimizing our model. Before we jump to optimization, we have a few questions to answer. <em>What exactly is the criterion on the basis of which we are planning to optimize our model? What exactly is even the purpose of optimization?</em></p><p>The answer is — We want to optimize the model in order to reduce the information loss generated by our model. <strong>Since the criterion for optimization is information loss, we need to define a loss function for our model.</strong></p><p>For the multinomial regression function, generally, we use the <strong>cross-entropy-loss</strong> function. Given below is the formula for the cross-entropy-loss function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wLgdoEMbD6R-ImiRJ10m9Q.jpeg" /></figure><p>Let us now define our cross-entropy loss function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aea31c37c3616637d0af79e9813de1d5/href">https://medium.com/media/aea31c37c3616637d0af79e9813de1d5/href</a></iframe><p>Now that we have defined our loss function, we will finally define our optimizer algorithm. Given below is the formula on which the Stochastic Gradient Descent operates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Gw-TmJoBunjsesykp1pbg.png" /><figcaption><a href="https://madalinabuzau.github.io/2016/11/29/gradient-descent-on-a-softmax-cross-entropy-cost-function.html">Image Source</a></figcaption></figure><p>For more details on this, please refer to <a href="http://machinelearningmechanic.com/deep_learning/2019/09/04/cross-entropy-loss-derivative.html">this source.</a> Given below is the code for the SGD algorithm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac480eb2ebcd2ac3eeaef0db576fc70c/href">https://medium.com/media/ac480eb2ebcd2ac3eeaef0db576fc70c/href</a></iframe><p>Now that we have the optimizer function ready, we will run it for our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f10d8149ea5b6060a3653c46e961ddc/href">https://medium.com/media/3f10d8149ea5b6060a3653c46e961ddc/href</a></iframe><p>We have reached the last step of our project now.</p><p><strong>“We are in the endgame!”</strong></p><p>We will now test our multinomial logistic regression model with the updated weights and biases that we obtained by running the optimizer function.</p><p><strong>NOTE- The test will be conducted on the test dataset and not the training dataset.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e13197264abdf6d61dda4552b5330d1/href">https://medium.com/media/6e13197264abdf6d61dda4552b5330d1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*E_Q-VF-ykuJBFhFRKPw1wg.png" /></figure><p>As we can see, our model showed around 67% accuracy on the test data. While this is a significant improvement over the initial 16% that we got, there’s still enough room for improvement.</p><p>You can further improve the accuracy by playing around with the hyperparameters (learning rate, training epochs, etc.) or by trying the process with a different scaling or optimizer algorithm. Remember, the more you experiment, the more you learn!</p><p>With this, we come to the end of our project.</p><h4>Here were the key takeaways-</h4><ul><li>Coding a multinomial logistic regression model from scratch.</li><li>The mathematics involved in an MLR model.</li></ul><p>For more fun projects like this one, check out <a href="https://medium.com/@amansharma2910">my profile</a>.</p><p>I am just a novice in the field of Machine Learning and Data Science so any suggestions and criticism will really help me improve.</p><p>Hit that follow and stay tuned for more ML stuff!</p><p><strong>Link to GitHub repo for the dataset and Jupyter notebook-</strong></p><p><a href="https://github.com/amansharma2910/MultinomialLogisticRegression-Scratch_HeartDiseasePrediction">amansharma2910/MultinomialLogisticRegression-Scratch_HeartDiseasePrediction</a></p><h3>References</h3><ul><li>Multinomial Logistic Regression — <a href="https://en.wikipedia.org/wiki/Multinomial_logistic_regression">Wikipedia</a></li><li>Logit Function — <a href="https://en.wikipedia.org/wiki/Logit#:~:text=In%20statistics%2C%20the%20logit%20(%2F,.">Wikipedia</a></li><li>Softmax Function — <a href="https://en.wikipedia.org/wiki/Softmax_function">Wikipedia</a></li><li>Cross-Entropy Function- <a href="http://machinelearningmechanic.com/deep_learning/2019/09/04/cross-entropy-loss-derivative.html">MachineLeariningMechanic.com</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dda9cbacf9d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/ml-from-scratch-multinomial-logistic-regression-6dda9cbacf9d">ML from Scratch-Multinomial Logistic Regression</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[Polynomial Regression Using PyTorch (From Scratch)]]></title>
            <link>https://medium.com/data-science/polynomial-regression-using-pytorch-from-scratch-500b7887b0ed?source=rss-84e03a4d7261------2</link>
            <guid isPermaLink="false">https://medium.com/p/500b7887b0ed</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Aman Sharma]]></dc:creator>
            <pubDate>Tue, 02 Jun 2020 09:16:18 GMT</pubDate>
            <atom:updated>2020-09-14T04:53:29.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VGrfNUsYnS55focXfzzZLw.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@lukas-rodriguez-1845331?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Lukas Rodriguez</a> from <a href="https://www.pexels.com/photo/aerial-photography-of-island-3427774/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><h3>ML from Scratch- Polynomial Regression Using PyTorch</h3><h4>A Complete Guide on How to Code a Polynomial Regression Model &amp; the Math Behind It</h4><p>When it comes to predictive analysis, regression models prove to be one of the most cost-efficient methods. While a linear regression model can provide some good predictions, in several cases the polynomial regression models can vastly outperform simple linear models. In the following project, we’ll have a look at how to create a polynomial regression model in PyTorch from scratch.</p><h3>Project Objectives</h3><ul><li>Implementation of a machine learning model in <strong>PyTorch</strong> that uses a polynomial regression algorithm to make predictions.</li></ul><p>We will create the model entirely from scratch, using basic PyTorch tensor operations.</p><ul><li>Using the model to conduct predictive analysis of automobile prices. At the end of the project, we aim at developing a highly efficient ML model that can predict the price of a car on the basis of its features.</li><li>Performing visual &amp; descriptive analysis of the data to predict which features play a key role in determining the price of a car.</li></ul><h3>Importing the Project Dependencies</h3><p>Before we begin working on the project, let us import all the necessary libraries and functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/536f71c05b0841d16b6c05891f5eac00/href">https://medium.com/media/536f71c05b0841d16b6c05891f5eac00/href</a></iframe><p>Now, let us import the dataset.</p><p>Here’s the <a href="https://www.kaggle.com/goyalshalini93/car-data">link to the data set</a> if you plan to work on it yourself.</p><p>I’ll also link the GitHub repo with the project notebook and the data set at the end of this article.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/197bd6cbd75fd55fbe0822de52fda925/href">https://medium.com/media/197bd6cbd75fd55fbe0822de52fda925/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_mGYCJpv3c4Es623HPugA.png" /><figcaption>The data frame as seen in my notebook</figcaption></figure><p>Since a polynomial regression model can already be a bit too overwhelming for beginners, therefore, for the sake of simplicity, we will be working only with continuous variables in our project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3abe3139ed2b812c58b4a24001dd24c2/href">https://medium.com/media/3abe3139ed2b812c58b4a24001dd24c2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hWK8TJJxLZppajMeAZ6jUQ.png" /><figcaption>Updated data frame we will be working on</figcaption></figure><h3>Data Wrangling</h3><p>Now, let us analyze the data and see if it needs any cleaning or modifications. First, let us check the data type of each column of the data frame.</p><p>*One thing to be noted is that the dataset has no null values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfab122ccb42c0d9ab98e80e1c3c1fc9/href">https://medium.com/media/dfab122ccb42c0d9ab98e80e1c3c1fc9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*dtvXshZRpSLj0aR6GrNQpg.png" /><figcaption>The data type of different columns</figcaption></figure><p>As we can see, some of the data is of the type ‘<em>int64’,</em> while some of the type ‘<em>float64’</em>. Since we’ll be working with tensors, we might want a uniform data-type throughout our feature set. As a result, we will cast the entire data frame to ‘<em>float64’</em> at a later step.</p><p>Now, we will have a look at the descriptive analysis of the data frame.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a43e419dfa15765b864b4881d106ce81/href">https://medium.com/media/a43e419dfa15765b864b4881d106ce81/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpitBi1rYZE0Jpq2vrTauA.png" /><figcaption>Table displaying a descriptive analysis of our data frame</figcaption></figure><p>As we can see, the data in different columns vary significantly in scale. We have elements in our data set of the order of <em>1e+0</em> on the lower range and elements of the order of <em>1e+3</em> on the upper range. <strong>We might want to normalize the data</strong>. We will deal with this at a later step in our project.</p><h3>Feature Selection</h3><p>Let us first plot the graph of each independent variable against the target variable (quality).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a92728876635f9504c7cbdbbffa6c44/href">https://medium.com/media/3a92728876635f9504c7cbdbbffa6c44/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bbdc63b217e88629a133265d05877c6/href">https://medium.com/media/6bbdc63b217e88629a133265d05877c6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Zyb4WQTfQSmWPRQX60hbA.png" /><figcaption>A screenshot of all the plots</figcaption></figure><p>Now, let us have a look at the correlation values for our dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b66eb73a33e969da0ee63f9cbeab2ad3/href">https://medium.com/media/b66eb73a33e969da0ee63f9cbeab2ad3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*koKI7bH0MI8XYg_v_yaJhw.png" /></figure><blockquote>From the above visual analysis, we can clearly see that <strong>enginesize</strong> (++0.87), <strong>curbweight</strong> (+0.84) and <strong>horsepower</strong> (+0.81) show a very strong correlation with the dependent variable, <strong>price</strong>.</blockquote><blockquote><strong>carwidth</strong> (0.76), <strong>citympg</strong> (-0.69), <strong>highwaympg</strong> (-0.70) and <strong>carlength</strong> (0.68) show a relatively stronger correlation. So, for this example, we will be selecting these 7 as our training features.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fe0f0c8b775975e73d09366ce3fc60f/href">https://medium.com/media/9fe0f0c8b775975e73d09366ce3fc60f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*Wf7o6d3tTX7UQ6Zl-s7Zjw.png" /><figcaption>Shapes of feature DF and target series</figcaption></figure><blockquote>Now, we will work on our model. But before we do that, first let us observe the plot of the features against the target once again.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/216e59094ad1cb34f4eaaa6c1bd57706/href">https://medium.com/media/216e59094ad1cb34f4eaaa6c1bd57706/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ccn5sKIY8A_iDgOv-sE2xw.png" /><figcaption>Graphs of our independent variables against the dependent variable</figcaption></figure><blockquote>If we observe the graphs carefully, we will notice that the features <strong>enginesize</strong>, <strong>curbweight</strong>, horsepower, <strong>carlength </strong>and <strong>carwidth </strong>have a graph of the type <strong>y = x2</strong>.</blockquote><blockquote>On the other hand, <strong>citympg </strong>and <strong>highwaympg </strong>have a graph of the type <strong>y = 1 / x2</strong>.</blockquote><blockquote>So we will deal with these features accordingly.</blockquote><h3>Formulating the Model from Scratch</h3><p>Given below are the formulae that our polynomial regression model will work on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5v-VrbZgBrPBYFaYbIxHAA.jpeg" /><figcaption>Formulae for polynomial regression as per our feature set</figcaption></figure><blockquote>As we can see, a polynomial regression function can be substituted as a linear regression function</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*qGVPueO7zaFN7vYop4krzg.jpeg" /></figure><p>Here,</p><ul><li><strong>ŷ</strong>- Predicted values of the target variable</li><li><strong>W</strong>- It’s a (1 x m) matrix containing all the weights associated with each polynomially transformed dependant variable</li><li><strong>X</strong>- A transpose of the matrix containing all the polynomially-transformed feature variables</li><li><strong>B</strong>- A (1 x m) matrix, each element of which is the bias value of our function.</li><li><strong>m</strong>- Number of rows in the training/test set</li><li><strong>n</strong>- Number of polynomially-transformed features</li></ul><blockquote>Let us now convert the feature (Pandas Dataframe object) and target (Pandas Series object) into tensor objects so we can use them to train our model with PyTorch.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b803f4a448fb1c155d3891fd2c1b4c4a/href">https://medium.com/media/b803f4a448fb1c155d3891fd2c1b4c4a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*BjuYx2WWmmPld44khgAIsQ.png" /><figcaption>Sizes of tensor features_x2 and features_1byX2</figcaption></figure><blockquote>Now, for features with activation function of the type <strong>y = x2</strong>, we first create the x2 features then concatenate it to our tensor object.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eebef4a7ef6130a448ba7dd30f955276/href">https://medium.com/media/eebef4a7ef6130a448ba7dd30f955276/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*gm2KIEvL8gZqLOccet-5Qg.png" /></figure><blockquote>Now, for features with activation function of the type <strong>y = 1/x2</strong>, we first create the 1/x2 features then concatenate it to our tensor object.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ed0a538851e73dee1a184a81d8549a6/href">https://medium.com/media/8ed0a538851e73dee1a184a81d8549a6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*QTv60uAEL-OzaoJzlyJduA.png" /></figure><blockquote>With this, we have polynomially transformed our features.</blockquote><blockquote>Now finally, we will concatenate all the transformed feature tensors into a single tensor object.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4de3275f03b21fa4dd01311ccdd2ff6f/href">https://medium.com/media/4de3275f03b21fa4dd01311ccdd2ff6f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*QXMygmS5cZne500a07-FBQ.png" /></figure><h3>Feature Scaling</h3><p>Since we will be using Stochastic Gradient Descent (SGD) algorithm as the optimization algorithm for our model, scaling can significantly improve the optimization process and the performance of our model.</p><p>In this project, we will be performing Min-Max Scaling. Min-max normalization converts the data such that all the values are between [0,1].</p><p>The mathematical formula for min-max normalization is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*KkqNiI3DiFPaYJ2pXQS-yw.jpeg" /></figure><p>Here,</p><ul><li><strong>X</strong> = observed value</li><li><strong>X </strong>min = minimum value observed in the column</li><li><strong>X </strong>max = maximum value observed in the column</li><li><strong>X </strong><em>scaled</em> = scaled value</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f678d3c0b963377b950d75020d901ad1/href">https://medium.com/media/f678d3c0b963377b950d75020d901ad1/href</a></iframe><p>Now, let us perform min-max normalization on our feature set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70358ee0a7f3b4acc756389f27d0acb2/href">https://medium.com/media/70358ee0a7f3b4acc756389f27d0acb2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*DT4ycbJNSWBhw61h_5RBFw.png" /><figcaption>The scaled feature set with all values between [0, 1]</figcaption></figure><blockquote>Now, we will create a tensor object that holds the weights associated with the polynomially-transformed, normalized features. These weights are randomly generated and are very small.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfc3cbbcb652e7afd089a1236f2a2889/href">https://medium.com/media/bfc3cbbcb652e7afd089a1236f2a2889/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*2b-tLCUS6BKhsDKVvU723g.png" /></figure><blockquote>Now, let us initialize a random bias for our model.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/987cf33e000357e5c8a426c94ddebacf/href">https://medium.com/media/987cf33e000357e5c8a426c94ddebacf/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*iAIeqE6o2B4wI0mXDQKfxQ.png" /></figure><blockquote>Finally, convert the target array into a tensor.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e526db3127f4e8b8af990696ee780813/href">https://medium.com/media/e526db3127f4e8b8af990696ee780813/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*8upECfuLfQiDIxl5RrjRdg.png" /><figcaption>A screenshot of the target tensor</figcaption></figure><p><strong>Now, let us define the regression function</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a656847cee0c0a502e08f0c6c1a98207/href">https://medium.com/media/a656847cee0c0a502e08f0c6c1a98207/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a5632985e97a87e20441e9ed1489484/href">https://medium.com/media/6a5632985e97a87e20441e9ed1489484/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/1*YjALofNX8p1L7yx-m7cpIQ.png" /></figure><p>Now, we will define our mean-squared error (<strong>MSE</strong>) function. MSE is one of the most commonly used methods to calculate the total model loss. Given below is the formula for the calculation of MSE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*KFsFrFJ5XK55IhdGlh6-_g.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51e856f229a8371fd6049868375c89ee/href">https://medium.com/media/51e856f229a8371fd6049868375c89ee/href</a></iframe><p>Upon running the MSE function for our model-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5b6dac34103172e7cb39572378dd0ac/href">https://medium.com/media/b5b6dac34103172e7cb39572378dd0ac/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*aMHEUjjqOu2d0ivIallOow.png" /></figure><blockquote>As we can see, our model currently gives a very large MSE. Therefore, we need to optimize our model weights and biases to improve its performance.</blockquote><h3>Optimizing the Model</h3><p>For optimizing our model, we will be using the Stochastic Gradient Descent (SGD) algorithm. Given below is the mathematics associated with the SGD optimizer algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9tEbAl8Sbcg9GGjKLS82xA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_04bBSwYP7pqh4-AGDDLag.jpeg" /></figure><p>For more information regarding SGD, kindly visit <a href="https://medium.com/bayshore-intelligence-solutions/why-is-stochastic-gradient-descent-2c17baf016de">this</a> link.</p><p>In our model, we will be using PyTorch’s built-in gradient calculation functions for calculating and upgrading the weights and biases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17b69299c6dc91a59417061c275f184d/href">https://medium.com/media/17b69299c6dc91a59417061c275f184d/href</a></iframe><p>With all this done, we will finally run the optimizer function for our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0e4a6a62412dc1da571a132053ab451/href">https://medium.com/media/a0e4a6a62412dc1da571a132053ab451/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*4nkZHPr7nTciBPfpOf7FrQ.png" /><figcaption>Results obtained by running the optimizer function for our model</figcaption></figure><p>Now, to check the accuracy of our model, we will calculate its r-squared score. The following is the formula for r2 score-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*NXyeK4m9Nstj-aZr390cMg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc3a589a3adaf160d9c6055483f84530/href">https://medium.com/media/cc3a589a3adaf160d9c6055483f84530/href</a></iframe><p>Now, let us check the performance of our model. We will use the updated models and weights obtained by our optimizer function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77816077871370ec3e2abc7350dbd089/href">https://medium.com/media/77816077871370ec3e2abc7350dbd089/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*uyG0sCsdarNZHyIszK447Q.png" /><figcaption>The r-squared score for our model</figcaption></figure><p>As we can see, our polynomial regression model can explain around 83–84% of the variance for the dependent variable. This is a considerably efficient model.</p><p><em>One thing to be noted here is that we performed training and testing on the same dataset, which is a bad practice. Instead, you should split the dataset into test set and training set. However, in this example, while creating the model from scratch, I skipped the step to keep things simple and understandable.</em></p><p>In the end of our project, let us plot the regression plot for all polynomially transformed features of our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa12c2dc8e5512c666b928d54274d12a/href">https://medium.com/media/fa12c2dc8e5512c666b928d54274d12a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*UVSjYxFx_AnVAn6SHlF7dw.png" /></figure><p>From the above graphs, we can see our model is performing pretty well.</p><p>With this, we come to the end of our project. For more fun projects like this one, check out <a href="https://medium.com/@amansharma2910">my profile</a>.</p><p>I am just a novice in the field of Machine Learning and Data Science so any suggestions and criticism will really help me improve.</p><p>Hit that follow and stay tuned for more ML stuff!</p><p><strong>Link to GitHub repo for the dataset and Jupyter notebook-</strong></p><p><a href="https://github.com/amansharma2910/PolynomialRegression_from_scratch_using_PyTorch">amansharma2910/PolynomialRegression_from_scratch_using_PyTorch</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=500b7887b0ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/polynomial-regression-using-pytorch-from-scratch-500b7887b0ed">Polynomial Regression Using PyTorch (From Scratch)</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[Linear Regression Model with NumPy]]></title>
            <link>https://medium.com/data-science/linear-regression-model-with-numpy-7d270feaca63?source=rss-84e03a4d7261------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d270feaca63</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Aman Sharma]]></dc:creator>
            <pubDate>Wed, 27 May 2020 17:27:07 GMT</pubDate>
            <atom:updated>2020-09-14T05:08:27.525Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZLFL7YJJtHj7LGxohHYRWQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ridham?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ridham Nagralawala</a> on <a href="https://unsplash.com/s/photos/line?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>ML from Scratch: Linear Regression Model with NumPy</h3><h4>Your Complete Guide to Linear Regression</h4><p>In this project, we will see how to create a machine learning model that uses the Multiple Linear Regression algorithm.</p><p><em>The main focus of this project is to explain how linear regression works, and how you can code a linear regression model from scratch using the awesome NumPy module.</em></p><p>Of course, you can create a linear regression model using the scikit-learn with just 3–4 lines of code, but really, coding your own model from scratch is far more awesome than relying on a library that does everything for you while you sit and watch.</p><p>Not only that, coding a custom model means you have full control over what the model does and how that model deals with the data that you will be feeding it. This allows for more flexibility during the training process, and you can actually tweak the model to make it more robust and responsive to the real world data as required in the future during re-training or in the production.</p><p>In this project, our model will be used to predict the CO₂ emissions of a vehicle based on its features such as its engine size, fuel consumption etc.</p><p>Let’s start working on the project.</p><h3>Making the Necessary Imports</h3><p>First, we will import the necessary PyData modules.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>%matplotlib inline</pre><p>Now, let us import our data set. The data set contains model-specific fuel consumption ratings and estimated carbon dioxide emissions for new light-duty vehicles for retail sale in Canada.</p><pre>df = pd.read_csv(&quot;FuelConsumptionCo2.csv&quot;)<br>print(df.head())</pre><p>Here’s the link for the data set. I will also share the link to the Github repo containing the Jupyter notebook and the dataset at the end of this project.</p><p><a href="https://drive.google.com/file/d/13UHA0B1velyQh9fk3eBOK4i337J441Ce/view?usp=sharing">FuelConsumptionCo2.csv</a></p><p>Here’s how it looks in my Jupyter notebook:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9E-QFyLsHnF9dUcr1fO4A.jpeg" /><figcaption>A view of the dataframe in Jupyter notebook</figcaption></figure><p>The following are the columns present in our data set.</p><ul><li><strong>MODELYEAR</strong> e.g. 2014</li><li><strong>MAKE</strong> e.g. Acura</li><li><strong>MODEL</strong> e.g. ILX</li><li><strong>VEHICLE CLASS</strong> e.g. SUV</li><li><strong>ENGINE SIZE</strong> e.g. 4.7</li><li><strong>CYLINDERS</strong> e.g 6</li><li><strong>TRANSMISSION</strong> e.g. A6</li><li><strong>FUEL CONSUMPTION in CITY(L/100 km)</strong> e.g. 9.9</li><li><strong>FUEL CONSUMPTION in HWY (L/100 km)</strong> e.g. 8.9</li><li><strong>FUEL CONSUMPTION COMB (L/100 km)</strong> e.g. 9.2</li><li><strong>CO2 EMISSIONS (g/km)</strong> e.g. 182 → low → 0</li></ul><h3>Data Wrangling &amp; Feature Selection</h3><p>One of the most important steps in any data science project is pre-processing the data. This involves cleaning the data, typecasting some columns as required, conversion of categorical variables and standardizing/normalizing the data as per the project requirements.</p><p>For our project, the first step of the pre-processing is going to be checking whether we need to typecast the data type of any feature/target variable.</p><pre>print(df.dtypes)</pre><p>We get the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*h9yjAUcGdqMZ0zFvckvraA.jpeg" /><figcaption>Data types of different columns</figcaption></figure><p>As we can see, there’s no need to typecast any column.</p><p>The second step in our data wrangling process is analyzing whether the features need to be standardized or not. For that, let us have a look at the descriptive analysis of the dataframe.</p><pre>print(df.describe())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CId5KdCr_cTxgEizgqgttQ.jpeg" /><figcaption>Descriptive analysis of the dataframe</figcaption></figure><p>As we can see, all the potential features are of the same order in terms of scales, so we needn’t standardize any feature.</p><p>For this project, the features we will be choosing are <strong>ENGINESIZE, CYLINDERS </strong>&amp;<strong> FUELCONSUMPTION_COMB</strong> and the target variable is <strong>CO2EMISSIONS</strong>.</p><pre>df = df[[&#39;ENGINESIZE&#39;,&#39;CYLINDERS&#39;,&#39;FUELCONSUMPTION_COMB&#39;,&#39;CO2EMISSIONS&#39;]]</pre><pre>print(df.head())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*PERHjDOQlhZQijst97iR3Q.jpeg" /></figure><p>Our next step- Checking the number of NaN(null) values in the dataframe.</p><pre>for i in df.columns:<br>    print(df[i].isnull().value_counts()) </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*aNiG6JJDY6DUr45q2kiJIw.jpeg" /><figcaption>Null value counts in the dataframe</figcaption></figure><p>As we can see, there are are no null values in our dataframe. So the data is perfect for training the model.</p><h3>Data Visualization &amp; Analysis</h3><p>First, we will have a look at the correlation of the features and the target variables.</p><pre>print(df.corr())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*B8refuSCmc-hUZFHAxQwCA.jpeg" /></figure><p>This table shows a strong positive correlation between the features and the target variable. Remember, a strong correlation is a good thing for a linear regression model.</p><p>Now, let us visualize the plots of different features against the target variable. This will allow us to get an idea whether the features show a linear relation with the target variable or not.</p><pre>fig, a <strong>=</strong>  plt.subplots(1,3, figsize <strong>=</strong> (18, 5))</pre><pre>a[0].scatter(df[&#39;ENGINESIZE&#39;], df[&#39;CO2EMISSIONS&#39;], color <strong>=</strong> &#39;c&#39;)<br>a[0].set_title(&#39;Engine Size vs CO2 Emissions&#39;)<br>a[0].set_xlabel(&#39;Engine Size (L)&#39;)</pre><pre>a[1].scatter(df[&#39;CYLINDERS&#39;], df[&#39;CO2EMISSIONS&#39;], color <strong>=</strong> &#39;m&#39;)<br>a[1].set_title(&#39;No. of Cylinders vs CO2 Emissions&#39;)<br>a[1].set_xlabel(&#39;No. of Cylinders&#39;)</pre><pre>a[2].scatter(df[&#39;FUELCONSUMPTION_COMB&#39;], df[&#39;CO2EMISSIONS&#39;], color <strong>=</strong> &#39;b&#39;)<br>a[2].set_title(&#39;Fuel Consumption vs CO2 Emissions&#39;)<br>a[2].set_xlabel(&#39;Fuel Consumption (L/100km)&#39;)</pre><pre>fig.text(0.08, 0.5, &#39;CO2 Emissions&#39;, va<strong>=</strong>&#39;center&#39;, rotation<strong>=</strong>&#39;vertical&#39;)</pre><pre><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rt3OLKfgsLpLHVb2K6598g.jpeg" /><figcaption>Plots of different features (x-axes) against target variable (y-axes)</figcaption></figure><p>As we can see, the features show a considerable linear relationship with the target. Hence, we can use them for training the model.</p><h3>Linear Regression Model from Scratch</h3><p>Linear regression uses the following mathematical formula for prediction of a dependent variable using an independent variable.</p><p><strong>y = wx + b</strong></p><p>Here,</p><ul><li><strong>y</strong>- Dependent variable(s)</li><li><strong>x</strong>- Dependent variable(s)</li><li><strong>w</strong>- Weight(s) associated with the independent variable(s)</li><li><strong>b</strong>- Biases for the given lin-reg equation</li></ul><p>The following is the process for developing a linear regression model.</p><ol><li>Splitting the data set into training and testing sets. <em>For the sake of simplicity however, we will be skipping this step in our custom model.</em></li><li>Assigning random weights and biases to the model and then calculating dependent variable, <strong>ŷ</strong> on the basis of the random weights and biases.</li><li>Using a loss function to calculate the total information loss, i.e., the total inaccuracy within out model. <em>In our examples, we will be using the Mean Squared Error </em>(<strong>MSE</strong>)<em> loss function.</em></li><li>Our next step is to reduce the total MSE of our model. <em>For this, we will be using the Stochastic Gradient Descent (</em><strong><em>SGD</em></strong><em>) function, which is one of the most popular optimizer algorithms used in regression models.</em> We will discuss the SGD function in detail while coding the optimizer function.</li><li>We will update the model weights and biases based on our optimizer algorithm, then retrain the model. This is a recurrent process that will keep on repeating until we achieve an optimum model with low information loss.</li></ol><p>First, let’s cast the features to a NumPy array, <strong>features</strong>.</p><pre>features <strong>= </strong>df[[&#39;ENGINESIZE&#39;,&#39;CYLINDERS&#39;,&#39;FUELCONSUMPTION_COMB&#39;]].to_numpy() <em>#Converts the dataframe to numpy array</em></pre><pre>print(features)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*J_GKo6MrEB8_qnvqypk75Q.jpeg" /><figcaption>Array of features for training the model</figcaption></figure><p>Now, let us get cast the target column to a NumPy array, <strong>target</strong>.</p><pre>target = df[‘CO2EMISSIONS’].to_numpy() #Converts the dataframe to numpy array</pre><pre>print(target)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*3_80bfD5DmTQqVwA_Jg11A.jpeg" /><figcaption>Array of target variable (actual CO₂ emission values for a vehicle)</figcaption></figure><p>Since we have 3 dependent variables, we will have 3 weights. Let’s generate array weights of 3 small random weights.</p><pre>weights <strong>=</strong> np.random.rand(3) <em>#Generates a numpy array with two small random floats</em></pre><pre>print(weights)</pre><p>Since we have a single target variable, we will have just one bias, <strong>b</strong>. We will also create an array <strong>bias </strong>equal to the length of <strong>features</strong> array having bias <strong>b</strong> for each element.</p><pre>b <strong>=</strong> np.random.rand(1) <em>#Generates a numpy array with a small random float</em></pre><pre>bias <strong>=</strong> np.array([b[0] <strong>for</strong> i <strong>in</strong> range(len(features))])</pre><pre>print(bias)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*2a78N-F43zqwavU5GiFIzw.jpeg" /><figcaption>Bias array</figcaption></figure><p>Now, we will define our model function that uses weights, biases and dependent variables to calculate ŷ.</p><pre><strong>def</strong> linearRegr(features, weights, bias):</pre><pre>    &quot;&quot;&quot;Calculates the y_hat predicted values using the given parameters of weights, dependent variables, and biases.</pre><pre>    Args:<br>        -dependant_var: Matrix of dependant variable values<br>        -weights: Matrix/array of weights associated with each dependant variable<br>        -biases: Biases for the model<br>    Returns:<br>        -Array/matrix of predicted values</pre><pre>    &quot;&quot;&quot;</pre><pre>    y_hat <strong>=</strong> weights.dot(features.transpose()) <strong>+</strong> np.array([bias[0] <strong>for</strong> i <strong>in</strong> range(len(features))]) <em># Takes the value stored in the bias array and makes an array of length of feature matrix for addition</em></pre><pre><strong>    return</strong> y_hat</pre><p>Now, let us run the function once to see the results we’ll get.</p><pre>y_hat = linearRegr(features, weights, b)<br>print(y_hat)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*ywP6cXdrfRG43_EqKwFDgA.jpeg" /><figcaption>ŷ (pronounced “y_hat”) array obtained on running linearRegr function for the randomly generated weights and biases</figcaption></figure><p>Now, we will define the MSE function to calculate the total loss of our model.</p><pre>def meanSqrError(y, y_hat):<br>    &quot;&quot;&quot;Calculates the total mean squared error.<br>    <br>    Args- <br>        y: Array of actual target values<br>        y_hat: Array of predicted target values<br>        <br>    Returns-<br>        total mean squared error<br>    &quot;&quot;&quot;<br>    MSE = np.sum((y - y_hat) ** 2) / len(y)<br>    return MSE</pre><p>Let us now calculate the information loss based on the <strong>y_hat</strong> values we got earlier.</p><pre>print(&#39;Total error- {}&#39;.format(meanSqrError(target, y_hat)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*h2ZVdtsgifPLeBWbPZPqtg.png" /></figure><p>As we can see, our model is currently massively inaccurate and we need to optimize it.</p><h3>Optimizing the Model</h3><p>Now comes the most important step in the linear regression. Formulating the SGD function. This is a slightly advance topic as compared to all the basic functions we have covered up until this point. It requires some knowledge of differential calculus; partial differentiation to be specific. I have tried to explain this in the image below, however, if you don’t get it, I’d strongly suggest you get familiar with the mathematics portion of Machine Learning (Calculus, Statistics and Probability, Linear Algebra) before proceeding any further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-hLh_JujozKKXB1eQzksTA.jpeg" /></figure><p>Image source- <a href="https://towardsdatascience.com/linear-regression-using-gradient-descent-97a6c8700931">Adarsh Menon-Medium.com</a></p><p><strong>Once we have calculated the gradients, we will update the parameters as follows.</strong></p><ul><li><strong>m = m - α D</strong>m</li><li><strong>c = c - α D</strong>c</li></ul><p>Here,</p><ul><li><strong>E</strong>- Total mean squared error</li><li><strong>m</strong>- Weights associated with features</li><li><strong>c</strong>- Model bias</li><li><strong>y</strong>- Array of actual target values</li><li><strong>ŷ</strong>- Predicted target values</li><li><strong>D</strong>m- Partial derivative of E w.r.t. weights <strong>m</strong></li><li><strong>D</strong>c- Partial derivative of E w.r.t. bias <strong>c</strong></li><li><strong>α</strong>- Learning rate, i.e., size of the step that the optimizer function takes.</li></ul><p>Once we have the new updated values of the weights and biases, we will calculate the loss again. We will repeat the process for <strong>n</strong> epochs, i.e., number of cycles and plot the loss values after each epoch. To keep the code clean, I will create a separate function for calculation of gradients.</p><pre>def gradient(target, features, weights, bias):<br>    &quot;&quot;&quot;Returns the gradient(slopes) for weights and biases<br>    &quot;&quot;&quot;  <br>    m = len(features)<br>    target_pred = linearRegr(features, weights, bias)<br>    loss = target - target_pred # y-y_hat<br>    # Gradient calculation for model bias<br>    grad_bias = np.array([-2/m * np.sum(loss)])<br>    <br>    grad_weights = np.ones(3)<br>    # Gradient calculation for first feature<br>    feature_0 = np.array([feature[0] for feature in features])<br>    grad_weights[0] = -2/m * np.sum(loss * feature_0)<br>    # Gradient calculation for second feature<br>    feature_1 = np.array([feature[1] for feature in features])<br>    grad_weights[1] = -2/m * np.sum(loss * feature_1)<br>    # Gradient calculation for third feature<br>    feature_2 = np.array([feature[1] for feature in features])<br>    grad_weights[2] = -2/m * np.sum(loss * feature_2)<br>    <br>    return grad_bias, grad_weights</pre><p>Now, let us write the SDG function that will return the updated weights and biases so we can formulate our final model.</p><pre>def stochGradDesMODIFIED(learning_rate, epochs, target, features, weights, bias):<br>    &quot;&quot;&quot;Performs stochastic gradient descent optimization on the model.<br>    <br>    Args-<br>        learning_rate- Size of the step the function will take during optimization<br>        epochs- No. of iterations the function will run for on the model<br>        target- Actual emission values<br>        features- Matrix of dependent variables<br>        weights- Weights associated with each feature<br>        bias- Model bias<br>    <br>    Returns-<br>        return_dict = {&#39;weights&#39;: weights, &#39;bias&#39;: bias[0], &#39;MSE&#39;: total_MSE_new, &#39;MSE_list&#39;: MSE_list}<br>        <br>    &quot;&quot;&quot;</pre><pre>MSE_list = []<br>    for i in range(epochs):<br>        grad_bias, grad_weights = gradient(target, features, weights, bias)<br>        weights -= grad_weights * learning_rate<br>        bias -= grad_bias * learning_rate<br>        new_pred = linearRegr(features, weights, bias)<br>        total_MSE_new = meanSqrError(target, new_pred)<br>        MSE_list.append(total_MSE_new)<br>    return_dict = {&#39;weights&#39;: weights, &#39;bias&#39;: bias[0], &#39;MSE&#39;: total_MSE_new, &#39;MSE_list&#39;: MSE_list}<br>    return return_dict</pre><p>Finally, we have the optimizer function for our linear regression model. Let us run the function now and store the values for further use.</p><pre>model_val = stochGradDesMODIFIED(0.001, 2000, target, features, weights, bias)</pre><pre>print(&quot;Weights- {}\nBias- {}\nMSE- {}&quot;.format(model_val[&#39;weights&#39;], model_val[&#39;bias&#39;], model_val[&#39;MSE&#39;]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*uXqPwWp7gkOTIuYsQ98d3A.png" /><figcaption>Updated weights, bias and MSE error</figcaption></figure><p>The initial MSE was around 65,000 while the current MSE is around 680. We can see from the results that our model has significantly improved.</p><p>Finally, we will write the model function that uses the updated model weights and biases to predict the target values.</p><pre>def LinearRegressionModel(model_val, feature_list):<br>    &quot;&quot;&quot;Predicts the CO2 emission values of the vehicle<br>    <br>    Args-<br>        model_val- This is the dictionary returned by the stockGradDesMODIFIED function. Contains model weights and biases<br>        feature_list- An array of the dependent variables<br>    Returns-<br>        co2_emission- Emission predictions for the given set of features<br>    &quot;&quot;&quot;<br>    co2_emission = np.sum(model_val[&#39;weights&#39;] * feature_list) + model_val[&#39;bias&#39;]<br>    return co2_emission</pre><h3>Testing and Evaluation</h3><p>As a test run, we will now test our model on the following data.</p><p>feature_list = [2.0, 4, 8.5]</p><p>The actual target value for the data is 196. Let’s see how our model fares.</p><pre>target_price = 196<br>feature_list = [2.0, 4, 8.5]<br>predicted_price = LinearRegressionModel(model_val, feature_list)<br>print(predicted_price)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*_BCUA0LDNxMYHo44qSxWoA.png" /><figcaption>Predicted CO2 emission</figcaption></figure><p>The original target value was 196 for the given model. As we can see, our model did a fairly good job at making the prediction, considering this is a model implementation from scratch. You can further improve the model though, by tweaking a few things or maybe running more optimization epochs. However, too much optimization can lead to model overfitting, which is equally bad for the model as overfitting makes the model practically unusable for real world data.</p><p>Now, to check the accuracy of our model, we will calculate its r-squared score. The following is the formula for r2 score-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*ikgOLveg7aK_quszXlkDJA.jpeg" /><figcaption>Formula for R-squared score</figcaption></figure><pre>def r2_score(target, prediction):<br>    &quot;&quot;&quot;Calculates the r2 score of the model<br>    <br>    Args-<br>        target- Actual values of the target variable<br>        prediction- Predicted values, calculated using the model<br>        <br>    Returns- <br>        r2- r-squared score of the model<br>    &quot;&quot;&quot;<br>    r2 = 1- np.sum((target-prediction)**2)/np.sum((target-target.mean())**2)<br>    return r2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*jA_3aKmcLP78oCeSc3wUfw.png" /><figcaption>r-squared score of our model</figcaption></figure><p>As we can see, our model explains around 83% of the variability of the response data around its mean, which is fairly good. However, there is always room for improvement in a Machine Learning model!</p><p>With this, we come to an end for our project.</p><p>I am going to make a series of blogs, where we will be working on similar projects, coding new ML models from scratch, working hands-on with real world datasets and problem statements.</p><p>I am just a novice in the field of Machine Learning and Data Science so any suggestions and criticism will really help me improve.</p><p>Hit that follow and stay tuned for more ML stuff!</p><p><strong>Link to GitHub repo for dataset and Jupyter notebook-</strong></p><p><a href="https://github.com/amansharma2910/CO2_emission_predictionML">amansharma2910/CO2_emission_predictionML</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d270feaca63" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/linear-regression-model-with-numpy-7d270feaca63">Linear Regression Model with NumPy</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>