<?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 Anson Tan on Medium]]></title>
        <description><![CDATA[Stories by Anson Tan on Medium]]></description>
        <link>https://medium.com/@ansonnn?source=rss-f7d4df14c0fd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TMMvwudMQuj2dJANC-j75A.png</url>
            <title>Stories by Anson Tan on Medium</title>
            <link>https://medium.com/@ansonnn?source=rss-f7d4df14c0fd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 12:21:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ansonnn/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[Logistic Regression: Implementation from Scratch in Python]]></title>
            <link>https://medium.com/geekculture/logistic-regression-implementation-from-scratch-in-python-f9d6cd4a0747?source=rss-f7d4df14c0fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9d6cd4a0747</guid>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[implementation]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Anson Tan]]></dc:creator>
            <pubDate>Sat, 26 Jun 2021 18:03:31 GMT</pubDate>
            <atom:updated>2021-06-26T18:03:31.568Z</atom:updated>
            <content:encoded><![CDATA[<h4>Including both binary classification and multi-class classification.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBBmKt07SrO4q8MGYLgBYg.png" /><figcaption>Drawn by author in excalidraw.com</figcaption></figure><p>Do you want to know how do machine learning models make classifications such as “is this person suffering from heart disease or not?”? Logistic regression is one of the most common algorithms used to do just this. Logistic regression is similar to the plain old linear regression in some way. They are usually the first two models being introduced to beginners learning machine learning models. Nevertheless, logistic regression is a very powerful classification model capable of handling large datasets and a high number of features.</p><p>One of the notable applications of logistic regression that I could think of is, in the field of Natural Language Processing, specifically in sentiment analysis. It is ubiquitous that people often try to apply a logistic regression model for sentiment analysis to test the performance before deciding whether it is really necessary to proceed to use more complex language models, or at least used a comparison to complex models. In fact, I have already built a <a href="https://imdb-review-sentiment-1.herokuapp.com/">Streamlit app</a> for IMDB movie review sentiment analysis using a logistic regression model, which out of the box, has already achieved 90% accuracy out of 50k reviews.</p><p>Today, I am going to share how I solidify my understanding of logistic regression by implementing the logistic regression algorithm from scratch in Python. Both the implementation for binary classification and multi-class classification will also be covered.</p><p>Some of the key concepts to training most machine learning models have already been covered in <a href="https://medium.com/geekculture/understanding-linear-regression-by-implementing-from-scratch-761e2a48fce4">my previous article</a> about implementing linear regression from scratch, and most of them can be applied to logistic regression, therefore, they will not be explained in detail again in this article.</p><p><a href="https://medium.com/geekculture/understanding-linear-regression-by-implementing-from-scratch-761e2a48fce4">Understanding Linear Regression by Implementing from Scratch</a></p><h3>A brief introduction to logistic regression</h3><p>Logistic regression is similar to linear regression in which they are both <strong>supervised machine learning models</strong>, but logistic regression is designed for <strong>classification </strong>tasks instead of regression tasks. In other words, logistic regression is used to predict discrete variables (aka categorical variables) instead of continuous variables (numerical variables).</p><p>Generally, logistic regression is used for <strong>binary classification</strong>, where there are only two classes to be classified, e.g. healthy or unhealthy. But, it can easily be extended to multi-class classification due to the nature of logistic regression being modeled with binomial probability distributions. In this article, <strong>both </strong>binary classification and multi-class classification implementations will be covered, but to further understand how everything works for multi-class classification, you may refer to <a href="https://machinelearningmastery.com/multinomial-logistic-regression-with-python/">this amazing post</a> published in Machine Learning Mastery by Jason Brownlee.</p><p>Just like linear regression, logistic regression also fits a line to the data to make predictions. However, logistic regression fits an “S” shaped <strong>sigmoid function</strong> (or “<strong>logistic function</strong>”, thus the name) instead of a straight line as shown in the <strong>figure below</strong>. This function is modeled with a probability distribution known as a <strong>binomial</strong> <strong>distribution</strong>.</p><p>Therefore, on the <strong>y-axis</strong>, instead of using continuous values directly from the features themselves (like in linear regression), the y-axis for logistic regression uses the probability of obtaining “Yes” or “No”, e.g. in the<strong> figure below</strong>, “Is Healthy” or “Unhealthy”. These probabilities are then used to predict whether the person is “healthy” or “unhealthy” by comparing against a specified threshold, generally, <strong>0.5</strong> to decide the output category. In this example, any data point above 0.5 will be classified as “healthy”, and anything below 0.5 will be classified as “unhealthy”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZVxEulyZhXGSA1KNOnC7w.png" /><figcaption>Drawn by author in excalidraw.com. Inspired by Josh Starmer’s <a href="https://youtu.be/yIYKR4sgzI8">video</a>.</figcaption></figure><p><strong>NOTE</strong>: In this article, I will use some of the beautiful graphs inspired by those made by <a href="https://www.youtube.com/channel/UCtYLUTtgS3k1Fg4y5tAhLbw">Josh Starmer</a> in his <strong>YouTube StatQuest video series </strong>about Logistic Regression (below shows the first video from the series), because his graphs are really amazing and I really enjoyed watching him teaching with those visuals. I recommend you to watch his videos to truly understand how logistic regression works, with his clear explanations and wonderful visuals (not to mention the attractive songs and “BAMS”), it is really enjoyable and informative to learn through his videos.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FyIYKR4sgzI8%3Flist%3DPLblh5JKOoLUICTaGLRoHQDuF_7q2GfuJF&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DyIYKR4sgzI8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FyIYKR4sgzI8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/225f5e8f719f40a42bfeb7958a1304af/href">https://medium.com/media/225f5e8f719f40a42bfeb7958a1304af/href</a></iframe><blockquote>In this article, I will bridge the gap between the intuition and the math of logistic regression by implementing it from scratch in Python. The intuition is mostly inspired from the StatQuest videos of Logistic Regression, while the math is mostly from the <a href="https://www.coursera.org/learn/machine-learning">Machine Learning course</a> (Week 3) by Andrew Ng in Coursera.</blockquote><h4>So how do we obtain the probability for each data point?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5F5ALv2fAAfNsGlZBn_ZA.png" /><figcaption>Image drawn by author in excalidraw.com. Inspired by Josh Starmer’s <a href="https://youtu.be/BfKanl1aSG0?list=PLblh5JKOoLUICTaGLRoHQDuF_7q2GfuJF">video</a> about Logistic Regression.</figcaption></figure><p>The right side of the figure shows how a line is fitted to the data points (just like in linear regression) to obtain the <em>log(odds)</em>,<em> </em>aka <strong>logits </strong>of each data point. The <em>log(odds) </em>are obtained by projecting them onto the fitted line and taking the values on the <strong>y-axis</strong>. Therefore, the equation for <em>log(odds)</em> for logistic regression can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*WB4xvPCLpX49NkY5vzzwRw.png" /><figcaption>Equation to obtain the best-fit line for log(odds).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*agQjr8hF96MHRlEfknTTpg.png" /><figcaption>Vectorized version.</figcaption></figure><p>The right-hand side of the equation is just like the one shown in <a href="https://medium.com/geekculture/understanding-linear-regression-by-implementing-from-scratch-761e2a48fce4">my previous article</a> to fit a line for linear regression, where W is the matrix consisting of the slope coefficients for every feature, with the <strong>shape </strong>of (number_of_features, 1); and X is the matrix consisting of the features for every sample, with the <strong>shape </strong>of (number_of_samples, number_of_features). The <em>log(odds) </em>are then transformed to the probability equation p at the left of the figure, where the <strong>y-axis</strong> of the graph represents the probability.</p><p><em>Odds</em> are similar to probabilities, they are obtained by computing the ratio of the number of occurrences of the “Yes” category against the “No” category. For example, given that there are 5 <strong>obese </strong>people and 10 <strong>not obese</strong> people, the <em>odds </em>of <strong>obese </strong>would be 5:10 or 5/10, whereas the probability of <strong>obese </strong>would be 5/(5+10) instead. The <em>log(odds) </em>are just simply the natural logarithm of the odds. To further understand the concepts about odds and <em>log(odds)</em>, you may refer to this <a href="https://youtu.be/ARfXDSkQf1Y?list=PLblh5JKOoLUICTaGLRoHQDuF_7q2GfuJF">amazing video</a> by Josh Starmer.</p><p>In the figure above, we can see that the formula of probability p = np.exp(np.log(odds)) / (1 + np.exp(np.log(odds)). This formula is derived from the equation of <em>log(odds)</em> = <em>log(p / (1 - p))</em>. To see the derivation process, you may refer to the video (at the time of <strong>4:00</strong>) linked in the image above. This formula can also be further simplified into p = np.exp(1 / (1 + np.exp( - np.log(odds)) by dividing both the numerator and denominator by the exponential term, np.exp(np.log(odds).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*sN2SuZbs-X5Hwj79KSyN3A.png" /><figcaption>Sigmoid function of logits in logistic regression.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/116/1*ekcvGx1C4nPvW71dYRBtrw.png" /><figcaption>Sigmoid function.</figcaption></figure><p>This is the most common form of the formula, known as the <strong>sigmoid function</strong> or <strong>logistic function</strong>. In the case of logistic regression, we specifically use the<strong> sigmoid function of the <em>log(odds)</em></strong> to obtain the probabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cbU9i63iMD9jpZHO.png" /><figcaption>Sigmoid function. Image from <a href="https://en.wikipedia.org/wiki/Sigmoid_function">Wikipedia</a>.</figcaption></figure><p>Meanwhile, the <em>log(odds)</em> are obtained by fitting a line to the data points, as explained above in this section. Later, these concepts will be applied to building the implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*zblJQURTM-acnTUakxXo8Q.png" /><figcaption>The final equation to compute the probability.</figcaption></figure><h3>Summary of key concepts to training a logistic regression model for binary classification</h3><h4>Hypothesis equation to make predictions</h4><p>The probability is obtained from the equation below. Then, the prediction of a category is made by comparing against a threshold as explained above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*vWZIPKlJ9qRDL7EosII2xg.png" /><figcaption>The sigmoid function of logits (equivalent to the equation from the fitted line) in logistic regression</figcaption></figure><h4>Parameters</h4><p>The parameters to be trained are same with linear regression.</p><p>W: the slope coefficients, with the shape of (number_of_features, 1).</p><p>b: the y-intercept.</p><h4>Cost function (or loss function)</h4><p>Binary cross-entropy loss (aka log loss):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*6Dsu0EjojE-HKoM6g3W8eg.png" /></figure><p>where:<br><strong>m</strong> = number of samples.<br><strong>y</strong> = true values, usually only consist of 0 and 1 in the case of binary classification.<br><strong>h</strong> = the hypothesis equation, in this case, the equation to obtain the probability (as shown above).</p><p>This method of minimizing the cross-entropy loss is also known as <strong>Maximum Likelihood Estimation (MLE)</strong>.</p><h4>Derivatives</h4><p>Derivative for the cost function with respect to <strong>b </strong>(<strong><em>β₀ </em></strong>in the figure):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*7EGKAxhCKt9EeSNbBvkjGw.png" /><figcaption>Derivation for the y-intercept in cross-entropy, from Wikipedia. (<a href="https://en.wikipedia.org/wiki/Cross_entropy">source</a>)</figcaption></figure><p>Derivative for the cost function with respect to <strong>W </strong>(<strong><em>β₁ </em></strong>in the figure):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*C0uJblrhwmrmlqEF0i8PdA.png" /><figcaption>Derivation for the slope coefficient in cross-entropy, from Wikipedia. (<a href="https://en.wikipedia.org/wiki/Cross_entropy">source</a>)</figcaption></figure><p>There is a multiplication of (1 / m) in the cost function, but they were not included in the derivations from Wikipedia. Therefore, the “translation” to code would be:</p><pre># Let y_proba = the probability computed from the hypothesis equation<br>db = (1 / m) * np.sum(y_proba - y)<br>dW = (1 / m) * (X.T @ (y_proba - y))</pre><h3>Implementation for binary classification</h3><p>Let’s get ready the dataset first. We are using the <a href="https://www.kaggle.com/ronitf/heart-disease-uci">Heart Disease UCI dataset</a> for this implementation for binary classification of whether a person is suffering from heart disease or not.</p><pre>df = pd.read_csv(&#39;heart.csv&#39;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*D9aDhpH7E6Pm1_aNUeXXrA.png" /></figure><p>Split the dataset into training and test set:</p><pre>X = df.drop(columns=&#39;target&#39;)<br>y = df[&#39;target&#39;]<br>X.shape, y.shape<br># ((303, 13), (303,))</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br>y_train.shape, y_test.shape<br># ((242,), (61,))</pre><pre># IMPORTANT STEP (as explained in my previous article)<br>y_train = y_train.values.reshape(-1, 1)<br>y_test = y_test.values.reshape(-1, 1)<br>y_train.shape, y_test.shape<br>((242, 1), (61, 1))</pre><p>Scaling the dataset in order to ensure more accurate and consistent results when comparing to Scikit-learn implementation later.</p><pre>scaler = StandardScaler()<br>X_train = scaler.fit_transform(X_train)<br>X_test = scaler.transform(X_test)</pre><p>Then the training process can be broken down into:</p><ol><li>Randomly initialize the parameters</li><li>Make predictions to obtain probabilities with the model in the current state</li><li>Compute the derivatives with respect to the cost function</li><li>Use gradient descent to update the parameters</li><li>Repeat steps 2–4 in a loop based on a given number of iterations</li></ol><p>The fit method in the class below contains the code for the entire training process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90a41920e9903340bb66299055d57379/href">https://medium.com/media/90a41920e9903340bb66299055d57379/href</a></iframe><p><strong>Line 10</strong>: The init_params method implements the random initialization of the parameters.</p><p><strong>Line 23</strong>: The get_logits method is used to obtain the equation of the fitted line, which is equivalent to the <em>log(odds)</em> or logits in the case of logistic regression.</p><p><strong>Line 30</strong>:<strong> </strong>The predict_proba method is the sigmoid function used to obtain the probability for binary classification.</p><p><strong>Line 38</strong>: The fit method implements the entire training process.</p><p><strong>Line 76–84</strong>: The predict method is used to obtain the predicted class by comparing the probability against a specified threshold, while the predict_score method is used to compute the accuracy of the predictions.</p><p>I decided to inherit the BaseEstimator and ClassifierMixin classes to be able to use this class to further compute cross-validation using the sklearn&#39;s cross_val_score. But you may omit them if deemed unnecessary.</p><p>Now, let’s look at the training results.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab6d7d5127b83428dfdb6da63ebd24f6/href">https://medium.com/media/ab6d7d5127b83428dfdb6da63ebd24f6/href</a></iframe><pre># OUTPUT:<br>My implementation:<br>0.8524590163934426<br>[[25  4]<br> [ 5 27]]</pre><pre>Scikit-learn implementation:<br>0.8524590163934426<br>[[25  4]<br> [ 5 27]]</pre><pre>Cross-validation score:<br>0.8179421768707483<br>0.8179421768707483</pre><p>Great! The test accuracy, the confusion matrix, and even the cross-validation score are the same as the sklearn implementation. But, there is a problem with getting the same results every time I fit the model, I am not sure why the results are different every time although I have already set the random seed for NumPy to be 42. So you may have to repeat the model creation and training a few times to obtain the same result with the sklearn implementation. Now let’s show some nice visualizations.</p><h3>Visualizations</h3><pre># plot confusion matrix for binary classification<br>from sklearn.metrics import plot_confusion_matrix<br>plot_confusion_matrix(my_log_reg, X_test, y_test, cmap=&#39;Blues&#39;, display_labels=[&#39;Healthy&#39;, &#39;Heart Disease&#39;])<br>plt.grid(None);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*Rt-rB4H-uqFZXki0i9yocw.png" /><figcaption>Image by author.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18d97898bcf398f312c9da59f9f64fa9/href">https://medium.com/media/18d97898bcf398f312c9da59f9f64fa9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*xXyTChQGw1YQ7nkRn3fx3w.png" /><figcaption>Image by author.</figcaption></figure><p>This visualization shows the predicted probabilities computed by the trained model, then the different colors of the data points show the actual labels of either “Unhealthy” (have heart disease) or “Healthy”. Notice that the curve looks similar to a sigmoid curve.</p><p>Ok, we are happy with the results of the implementation for binary classification. Next, I would like to talk about the implementation of multi-class classification too, as it is actually a simple extension of the current class.</p><h3>Key concepts for Multinomial Logistic Regression</h3><blockquote>The probability distribution that defines multi-class probabilities is called a multinomial probability distribution. A logistic regression model that is adapted to learn and predict a multinomial probability distribution is referred to as <strong>Multinomial Logistic Regression</strong>.<br> — Jason Brownlee, <a href="https://machinelearningmastery.com/multinomial-logistic-regression-with-python/">Machine Learning Mastery</a></blockquote><h4>Hypothesis equation</h4><p>The <strong>softmax function </strong>is used to compute the probabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*xBLSfr75eoe2T7ATB8a7_A.png" /><figcaption>Softmax function. (<a href="https://www.kdnuggets.com/2016/07/softmax-regression-related-logistic-regression.html">source</a>)</figcaption></figure><p>In the case of logistic regression, the <strong><em>z </em></strong>in the equation above is replaced by the matrix of logits computed from the equation of the fitted line, which is similar to the logits in the binary classification version, but with the <strong>shape</strong> of (number_of_samples, number_of_classes) instead of (number_of_samples, 1). Essentially, the softmax function here will <strong>output probabilities for every class</strong>, unlike the sigmoid function in binary classification, where only the probability of obtaining the “Yes” category is computed. Here’s a basic introduction to softmax using code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8382a2cfb90c37f67dfed377439bff05/href">https://medium.com/media/8382a2cfb90c37f67dfed377439bff05/href</a></iframe><pre># OUTPUT:<br>[[1002 1080 1100]<br> [   5    7    8]<br> [   2    4    6]<br> [   3    4    5]]<br>mx = array([[1100],<br>       [   8],<br>       [   6],<br>       [   5]])<br>x - mx = array([[-98, -20,   0],<br>       [ -3,  -1,   0],<br>       [ -4,  -2,   0],<br>       [ -2,  -1,   0]])<br>denominator = array([[1.        ],<br>       [1.41766651],<br>       [1.15365092],<br>       [1.50321472]])<br>result = array([[2.74878500e-43, 2.06115362e-09, 9.99999998e-01],<br>       [3.51190270e-02, 2.59496460e-01, 7.05384513e-01],<br>       [1.58762400e-02, 1.17310428e-01, 8.66813332e-01],<br>       [9.00305732e-02, 2.44728471e-01, 6.65240956e-01]])<br>Sum of probabilities = [[1.]<br> [1.]<br> [1.]<br> [1.]]</pre><p>As shown in the outputs, every row (every data record) has been transformed into probabilities and each of them sums up to 1, which proves that the softmax function transforms them into probabilities for each class, which, in this example, there are 3 classes (3 columns). As a side note, there is already an existing implementation by scipy from scipy.special.softmax.</p><h4>Parameters</h4><p>The parameters to be trained are still the same as in the case of binary classification, but with <strong>different shapes</strong> to accommodate the <strong>higher number of classes</strong>.</p><p>W: the slope coefficients for every feature and every class, with the <strong>shape</strong> of (number_of_features, number_of_classes).</p><p>b: the y-intercepts for every class, with the <strong>shape </strong>of (1, number_of_classes)</p><h4>Cost function</h4><p>The cost function is the <strong>categorical cross-entropy loss</strong>, which is a generalization of the binary cross-entropy loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*NAD3PzZR-RZi6bQRFXaOGg.png" /><figcaption>Cross-entropy for multi-class classification. (<a href="https://ml-cheatsheet.readthedocs.io/en/latest/loss_functions.html">source</a>)</figcaption></figure><p>Here the y stands for the “target” (the true class labels) and the h stands for output (the computed probabilities via softmax; <strong><em>not </em></strong>the predicted class label).</p><h4>Derivatives</h4><p>Here are the partial derivatives for both parameters, the tedious details for the derivations will not be shown here as they are quite complicated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*v0E3GqqMcSvbdzN7V9Avog.png" /><figcaption>Derivatives obtained from the first article reference below.</figcaption></figure><p>The “translation” to code will be:</p><pre>dW = (1 / m) * (X.T @ (y_proba - y))<br>db = (1 / m) * np.sum((y_proba - y), axis=0, keepdims=True)</pre><p>To further understand how softmax works, how the cost function is defined, and how they are related to multinomial logistic regression, you may refer to the article below.</p><p><a href="https://www.kdnuggets.com/2016/07/softmax-regression-related-logistic-regression.html">What is Softmax Regression and How is it Related to Logistic Regression? - KDnuggets</a></p><p>You may also refer to the article below for detailed explanations of softmax.</p><p><a href="https://towardsdatascience.com/softmax-activation-function-how-it-actually-works-d292d335bd78">Softmax Activation Function — How It Actually Works</a></p><h3>Implementation for multi-class classification</h3><p>There are only a few changes to the binary classification version. First, we are using the iris dataset from sklearn as there are 3 target classes. However, first of all, the target labels must be one-hot encoded to ensure proper calculations and of softmax and derivatives:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01cbf3995fdeff5ba2b2db31d7b5a010/href">https://medium.com/media/01cbf3995fdeff5ba2b2db31d7b5a010/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/767ec154c0a88bfa85fd1a02d222ec34/href">https://medium.com/media/767ec154c0a88bfa85fd1a02d222ec34/href</a></iframe><p>Then first change to our MyLogisticReg class is to the parameter initialization — init_params method for the coefficients and intercepts, where the shapes are different as explained above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84cc8b34a268cd271eb675204c229528/href">https://medium.com/media/84cc8b34a268cd271eb675204c229528/href</a></iframe><p>Then, softmax function instead of sigmoid function is used for multi-class classification. The predict_proba method shown above can accommodate both binary and multi-class classifications.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72e9236c83d51e3269cc9aa0310118ba/href">https://medium.com/media/72e9236c83d51e3269cc9aa0310118ba/href</a></iframe><p>In the fit method, the calculation for the gradient is also changed slightly for the derivative of b, db, to compute the sum at the right axis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff413e5fa1ca76f1bec9f2ecfc3a4032/href">https://medium.com/media/ff413e5fa1ca76f1bec9f2ecfc3a4032/href</a></iframe><p>Next, both the predict method would obtain the predicted class label by computing the index of the highest probability across all the probabilities of the classes. The predict_score method will compute the true class from the one-hot encoded y values, and the accuracy score of the predictions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9376ac4bcb8457a23530960bcfc8aefe/href">https://medium.com/media/9376ac4bcb8457a23530960bcfc8aefe/href</a></iframe><pre># OUTPUT:<br>Result in accuracy:<br>My implementation	: 0.98<br>Sklearn implementation	: 0.98</pre><p>The training results are the same as Scikit-learn implementation again. Therefore, our implementation should be very close to the multinomial implementation of the Scikit-learn’s LogisticRegression class.</p><p>The entire class can be seen here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eeb4caf8f686216b1ef7f8facbb3c41e/href">https://medium.com/media/eeb4caf8f686216b1ef7f8facbb3c41e/href</a></iframe><p>For the full code used in this article, you may refer to the <a href="https://github.com/ansonnn07/ML-implmentations/blob/main/logistic_regression/log_reg_from_scratch.ipynb">notebook here in GitHub</a>.</p><h3>Final Thoughts</h3><p>In this article, we learned about the basic concepts of logistic regression, as well as the key concepts to both binary and multi-class classifications and their respective implementations. I believe this should help solidify our understanding of logistic regression.</p><p>These concepts, especially the softmax and categorical cross-entropy loss, are very common in the field of neural networks as there are many multi-class classification problems. Hence, by further understanding the underlying concepts of these, I am sure you would feel more confident about applying them in neural networks, as well as some other applications not mentioned here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9d6cd4a0747" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/logistic-regression-implementation-from-scratch-in-python-f9d6cd4a0747">Logistic Regression: Implementation from Scratch in Python</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Linear Regression by Implementing from Scratch]]></title>
            <link>https://medium.com/geekculture/understanding-linear-regression-by-implementing-from-scratch-761e2a48fce4?source=rss-f7d4df14c0fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/761e2a48fce4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[implementation]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <dc:creator><![CDATA[Anson Tan]]></dc:creator>
            <pubDate>Fri, 18 Jun 2021 10:05:01 GMT</pubDate>
            <atom:updated>2021-06-18T19:32:28.974Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Machine Learning Fundamentals by Implementing Linear Regression from Scratch</h3><h4>Learn the key concepts to training most machine learning models</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*mTtQAgn-lZJP_5ZBUWyLhQ.png" /><figcaption>Drawn in excalidraw.com.</figcaption></figure><p>Linear regression may be the simplest machine learning model, but it is vital to fully understand the fundamentals of it before moving on to more complex models. By learning about the key concepts of linear regression, you would be able to build the fundamental knowledge required to understand about machine learning in general. In my opinion, having a strong foundation will make your life much easier in most of the things you learn, I believe this should hold true to everyone else too.</p><p>In this article, the following information regarding linear regression models will be covered:</p><ul><li>What is a linear regression model?</li><li>Why use linear regression models?</li><li>Key concepts of training a linear regression model, or most machine learning model in general</li><li>Implementation from scratch, with derivatives explained</li><li>Implementation with tf.GradientTape (performs the computation of derivatives for us)</li></ul><h3>So what exactly is a linear regression model?</h3><p>Linear regression is a <strong>supervised machine learning model</strong> built for <strong>regression tasks</strong>, which are tasks involving predicting continuous (or real-valued) variables instead of discrete (categorical) variables. Supervised learning means that it requires both the input data and the correct outputs in order to be trained to make the correct predictions.</p><p>There are basically <strong>two types of linear regression models</strong>: univariate linear regression and multiple (or multivariate) linear regression. Univariate is just a “fancy” word of saying that the model only used one feature (or variable) to make predictions, whereas multiple linear regression uses more than one feature. Multivariate linear regression may sound complicated, but in fact, it’s just a very simple “upgrade” of the simple linear regression model, and the implementation of it is also very simple and basically identical due to the powerful capabilities of matrix multiplication. This will be shown in the implementation later.</p><p>A linear regression model adopts the most basic aspects of what defines a machine learning model. Most machine learning models including linear regression, make use of the following <strong>key principles</strong>:</p><ol><li>Define the <strong>equation</strong> used for making predictions</li><li>Define the <strong>parameters </strong>to learn to make predictions</li><li>Define the <strong>cost function</strong> (or loss function) required to train the model</li><li><strong>Train </strong>the model using <strong>gradient descent</strong> in order to minimize the cost function</li><li>Make <strong>predictions </strong>using the trained parameters</li></ol><h3>Defining the key concepts for training a linear regression model</h3><p>These concepts are very important for building up the knowledge required to implement the model from scratch, it’s a little bit long but it’s well worth the time to understand it, so please bear with me.</p><p>In the case of a linear regression model, the things to be defined are:</p><h4><strong>Equation</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*Btk0tNiMuJi8Kp8NifE0GQ.png" /><figcaption>Image from Investopedia. (<a href="https://www.investopedia.com/terms/m/mlr.asp">Source</a>)</figcaption></figure><p>Due to the power of matrix multiplication, the long equation above can actually be simplified into this equation below for a more efficient training process, for arbitrary number of samples and arbitrary number of features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*cyRUhzBq0d1usRuy7aMSUA.png" /></figure><p>where:<br><strong>Y </strong>= dependent variable (target variable) in <strong>matrix form</strong>, with the <strong>shape </strong>of (number_of_samples, 1)— represented with (number_of_rows, number_of_columns)<br><strong>b </strong>= y-intercept (similar to bias in neural networks, thus the b notation)<br><strong>W </strong>= the slope coefficients in <strong>matrix form</strong> (similar to weights in neural networks, thus the W notation), with the <strong>shape </strong>of (number_of_features, 1).<br><strong>X</strong> = the independent variables (features) in matrix form, with the <strong>shape </strong>of (number_of_samples, number_of_features).</p><p>The dot in between the <strong>W </strong>and <strong>X </strong>represents the dot product of them. This dot product will output exactly the same result as the terms <em>after </em>the y-intercept ( <strong><em>β₀</em></strong>) in the long equation shown above. This will be proven in the next section, where matrix multiplication (same as dot product) will be explained.</p><p><strong>NOTE</strong>: The <strong>capital letters</strong> are used to represent <strong>matrix forms</strong>. And the notations used here are subjective, the notations used here are based on my personal preference.</p><h4>Matrix multiplication (dot product)</h4><p>The visual below shows an example of matrix multiplication in the case of only <strong>1 sample</strong> and<strong> 3 features</strong>, which will output a matrix of shape (n_samples, 1), the output is exactly the same as the equation in the image shown earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U-j4wPRBiNCxd5sOPKrWPg.png" /></figure><p>One great tip that I always like to use is by <strong>remembering how the shape changes</strong> during matrix multiplication. For example, in the image above, the first matrix has a shape of (1, 3), the second matrix (3, 1), and third matrix (1, 1). The change in the shape would be like this image below, where the middle part must have the same shape (3 in this case), and they would be cut off and left only the sides in the end:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*jPYZQGRQMn4DJh7H94bLGw.png" /></figure><p>To further experiment with matrix multiplication to understand how it works, I would recommend this <a href="http://matrixmultiplication.xyz/">fun website</a>, which lets you try matrix multiplications of any kind of shape.</p><h4><strong>Parameters</strong></h4><p>These parameters are going to be initialized randomly, and they will keep updating during the training process (by using gradient descent), in order to become better at making accurate predictions. The parameters are as following:</p><ol><li>W: the slope coefficients for each explanatory variable (same meaning as “feature”), where each feature has its own slope coefficient.</li><li>b: the y-intercept.</li></ol><h4><strong>Cost function</strong></h4><p>Generally, mean squared error (MSE) is used for regression tasks. In simple words, MSE is just the average of the squared of the <strong>residuals </strong>(predicted values - true values), as shown in the equation below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*pc9B24G1Ag1BULbWDpP1ig.png" /></figure><p>The visual below shows how the <strong>residuals (the dashed lines)</strong> are calculated for each point. The purple line is generated by the linear regression model. So, y_pred(predicted values) are the points on the purple line, while y (true values) are the blue dots. <strong>Note</strong>: this figure is drawn based on a single feature only, therefore it’s 2-dimensional, if there is more than one feature, it would require much higher dimensions to draw.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*4tbrAFzyAfXz9Ot4u-4xuA.png" /></figure><h4>Gradient Descent</h4><p>Only the basics of gradient descent will be covered here, for a more in-depth explanation, you may refer to this amazing <a href="https://youtu.be/IHZwWFHWa-w">YouTube video</a>. For now, let’s just know that gradient descent has this formula shown in the image below.</p><p>Let <strong><em>p </em></strong>= any trainable parameter, <strong><em>lr </em></strong>= learning rate and <strong><em>dp</em>/<em>dx</em></strong><em> </em>= the partial derivative of <strong><em>p</em> </strong>with respect to <strong>cost function’s parameter</strong> <strong><em>x</em></strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*iNWn2zmlCiGWAmRUf3NAwA.png" /><figcaption>General gradient descent formula.</figcaption></figure><p>Gradient descent works hand in hand with the cost function for a machine learning model. So it’s important to understand the cost function used when explaining gradient descent. For the cost function of MSE in this case, the graph for <strong>training a single parameter</strong> would be like the <strong>purple curve </strong>in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*NbsNn4kf1-8J12F-Odzchw.png" /><figcaption>Example of MSE loss function = (x - 100)² / 5000, where true value = 100, n_samples = 5000.</figcaption></figure><p>The <strong>x-axis</strong> represents the predicted values, while the <strong>y-axis</strong> represents the MSE values. The orange and green lines represent the tangents to the curve at the respective points to allow slopes to be calculated. Initially, the predicted value would start at somewhere high around point A because of high loss (bad predictions), having a slope (or gradient) of -1.674 as shown in the figure, denoted by m. Then, after each <em>iteration</em> of gradient descent, ideally, the predicted value and the slope will be gradually going down the curve until it finally converges to the <em>global minimum</em> — point C in the figure, having a slope of zero, which is basically the same as zero loss, i.e. the best linear regression line has been fitted to make the most accurate predictions possible.</p><p>To explain gradient descent in simple words: At each iteration, the gradients computed are used to minimize the cost function in order to reduce the residuals. When the gradient reaches zero, i.e. the mean of sum squared residuals has reached zero, then the model would have already found the best fit line for the current dataset.</p><p>If the <strong>learning rate</strong> was set to too low, it would require many iterations to converge to the global minimum. On the contrary, if the <strong>learning rate</strong> was set to too high, it would cause the gradients to explode and would never be able to converge to the global minimum.</p><p>The <strong>derivatives </strong>(basically the math notation for slope) for the MSE loss function, in this case, will be as follows:</p><p><strong>The cost function:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*mI1aIUZeGxXakKyfKhlRpg.png" /></figure><p><strong>The derivatives:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*ligoacE8y1TVnpJLqKsN2Q.png" /><figcaption>from StackOverflow (<a href="https://math.stackexchange.com/questions/3152235/partial-derivative-of-mse-cost-function-in-linear-regression?newreg=d8f2602266cc42de80d9c1a37974a781">source</a>)</figcaption></figure><p>For me, by directly “translating” the math notations into code, it would always be much more readable and more understandable, so here is the “translated” code for deriving the derivatives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*mAtOYEF6P24C3ZQe2WvpyA.png" /></figure><h3>Implementation</h3><p>The steps can be broken down as follows:</p><ol><li>Randomly initialize the parameters</li><li>Make predictions with the model in the current state</li><li>Compute the derivatives with respect to the cost function</li><li>Use gradient descent to update the parameters</li><li>Repeat steps 2–4 in a loop based on a given number of iterations</li></ol><p>There is <strong>one major tip</strong> that I would like to talk about first before beginning the implementation. In the case of machine learning, one of the common errors that causes debugging disasters is when the variables have the <strong>incorrect shapes</strong> for computations. The one that had caused me to waste a lot of time was the variables with shapes of (nrows,), therefore, I would always compute a reshape(-1, 1) on such variables to change them into the shape of (nrows, 1) as shown in the implementation later.</p><p>Ok enough with the jibber-jabber, let’s start by creating a dummy dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ba56b33d360bf227669e66878289d17/href">https://medium.com/media/5ba56b33d360bf227669e66878289d17/href</a></iframe><p>As you can see, at <strong>line 4</strong>, the shape of y is (500,). As I mentioned before, I immediately reshape into (500, 1) to avoid disasters later.</p><p><strong>Line 9</strong>: Split into train set and test set of size 20%.</p><p>The scatterplot plt.scatter(X, y) for the data is like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*55vB9gLaitaXE_94yVtQKw.png" /></figure><p>Then, initialize the parameters with random numbers generated from the normal distribution (because machine learning models generally love normally distributed things).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b52d78a86efa93dbc22b406d49235d51/href">https://medium.com/media/b52d78a86efa93dbc22b406d49235d51/href</a></iframe><p>Then make predictions, compute derivatives, and perform gradient descent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f69c75e6ece1675fb3e90a13c099023/href">https://medium.com/media/2f69c75e6ece1675fb3e90a13c099023/href</a></iframe><p>Then compare it with the gold standard from Scikit-learn sklearn implementation, notice that I always keep track of the shape as they are very important for debugging:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/111012d994c5969554555d2daba06199/href">https://medium.com/media/111012d994c5969554555d2daba06199/href</a></iframe><p>Hooray! The implementation has exactly the same R2 score as the sklearn implementation.</p><p>But let’s refactor them into a class object as Python should always make use of its powerful and pythonic object-oriented programming (OOP) capabilities.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a38b6e473a0b88cfd4b1dca4ab1de6ce/href">https://medium.com/media/a38b6e473a0b88cfd4b1dca4ab1de6ce/href</a></iframe><p>And let’s run a training loop to confirm it’s working.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a109b3abf7e016152b01619c5e4979dd/href">https://medium.com/media/a109b3abf7e016152b01619c5e4979dd/href</a></iframe><p>Ok great, it’s working for a dataset of <strong>only a single feature variable</strong>. Now let’s try running for a dataset of <strong>multiple features</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c99925bd32a0ec9ff7e7a88a0a99804f/href">https://medium.com/media/c99925bd32a0ec9ff7e7a88a0a99804f/href</a></iframe><p>Alright, everything is working great. But deriving the derivatives manually every time may not be the most practical method, that’s why usually the gradients for more complex models such as neural networks would use the functions provided by TensorFlow or PyTorch to compute the derivatives and the loss. An example of using Tensorflow’s tf.GradientTapeto compute the derivatives for us will be shown next.</p><h4>Using tf.GradientTape</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9255cebc5dd7f862e3b1964ca1f13785/href">https://medium.com/media/9255cebc5dd7f862e3b1964ca1f13785/href</a></iframe><p>As you can see in <strong>Lines 29–38</strong>, the loss is computed within the tf.GradientTape context manager, then <strong>line 41</strong>, tape.gradient would compute the derivatives for us to use to perform gradient descent.</p><p>But there is actually an even shorter method shown in the fit2 method in the script above, which makes use of an optimizer to minimize() the parameters using the optimizer directly for us, skipping the entire steps of manually coding the GradientTape and updating parameters at the cost of a small increase in training time. The end result is exactly the same in this case considering that <strong><em>Stochastic Gradient Descent optimizer </em></strong>is almost the same as normal gradient descent, and the dataset is relatively simple.</p><h3>Visualizing the best fit line, and Animate it!</h3><p>Let’s try to visualize the result for the univariate linear regression model:</p><pre>if X.shape == y.shape:<br>    plt.scatter(X, y, color=&#39;orange&#39;)<br>    plt.plot(X, my_linear_reg.predict(X.reshape(-1, 1)), linewidth=3);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*Z2Zyk8eiL3603tPnz8964Q.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac518988ff1145e456073c72a41629aa/href">https://medium.com/media/ac518988ff1145e456073c72a41629aa/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fdampunnaturalleafcutterant&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fdampunnaturalleafcutterant&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FDampUnnaturalLeafcutterant-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="870" height="656" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5ff7bda0835bf5eeb072983e3ee6b69/href">https://medium.com/media/c5ff7bda0835bf5eeb072983e3ee6b69/href</a></iframe><h3>Conclusions</h3><p>To sum up, we have discussed the key concepts for training a machine learning model in general, and specifically focusing on implementing a linear regression model in Python. These are very important concepts and can be applied to more complex models.</p><p>The implementation is also applicable to multiple linear regression, and the steps for hard-coding the derivatives can also be converted into TensorFlow’s tf.GradientTape to simplify the process for us.</p><p><strong>Endnotes</strong>: Hopefully you learnt something useful in this article. This is my first article published in Medium, please forgive me if my writing or visuals have some flaws. And I really welcome any kind of feedback. Thank you very much for reading until here!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=761e2a48fce4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/understanding-linear-regression-by-implementing-from-scratch-761e2a48fce4">Understanding Linear Regression by Implementing from Scratch</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>