<?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 John michael rono on Medium]]></title>
        <description><![CDATA[Stories by John michael rono on Medium]]></description>
        <link>https://medium.com/@johnmichaelrono?source=rss-a79a8f8d3d3f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nNUdPSusyinpKYgH</url>
            <title>Stories by John michael rono on Medium</title>
            <link>https://medium.com/@johnmichaelrono?source=rss-a79a8f8d3d3f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 22:36:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@johnmichaelrono/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[Gaussian Discriminant Analysis from]]></title>
            <link>https://medium.com/@johnmichaelrono/gaussian-discriminant-analysis-from-655acef23e0a?source=rss-a79a8f8d3d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/655acef23e0a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gaussian-naive-bayes]]></category>
            <category><![CDATA[gaussian-distribution]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[John michael rono]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 15:28:03 GMT</pubDate>
            <atom:updated>2023-02-21T15:28:53.329Z</atom:updated>
            <content:encoded><![CDATA[<p>The math behind gaussian discriminant analysis — with code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eu8XDsti9c99ZgRUmFlM7g.jpeg" /></figure><p>This article gives an overview of the Gaussian Discriminant Analysis algorithm based on concepts drawn from the Stanford CS229 Machine Learning course on Generative learning. For further insights, check out the complete course from the link below.</p><p><a href="https://cs229.stanford.edu/syllabus-summer2019.html">CS229: Machine Learning - The Summer Edition!</a></p><h3><strong>Generative Learning Algorithms</strong></h3><p>Supervised learning algorithms can be classified into two categories:</p><ul><li>Discriminative learning algorithms</li><li>Generative learning algorithms</li></ul><p><strong>a. Discriminative Learning Algorithms</strong></p><p>These algorithms try to learn the mapping between the input space i.e. <strong><em>X</em></strong> to the labels <strong><em>y.</em></strong><br>Examples include:</p><ul><li>Linear regression</li><li>Logistic regression</li></ul><p><strong>b. Generative Learning algorithms</strong></p><p>These algorithms try to model x given y. i.e. They try to model <strong><em>P(x|y)</em></strong> and <strong><em>P(y)</em></strong> Examples include:</p><ul><li>Gaussian Discriminant analysis</li><li>Naïve Bayes</li></ul><p>After modeling 𝑝(𝑥|𝑦) and 𝑝(𝑦), our algorithms then use the Bayes rule in order to derive the posterior distribution on y given x:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*_7qwFDjNs47BiwjvMb-Mgw.png" /></figure><h3>Gaussian Discriminant Analysis</h3><p>Here, the <strong><em>X′s</em></strong> are continuous and the <strong><em>y′s</em></strong> discrete. We make an assumption that <strong><em>P(x|y)</em></strong>, i.e. the <strong><em>X′s</em></strong> follow a <strong>multivariate normal/gaussian distribution.</strong></p><h4>Imports</h4><pre>import numpy as np<br>import pandas as pd<br><br>from scipy.stats import multivariate_normal #for calculating the pdf<br>from sklearn.metrics import accuracy_score #for measuring the accuracy</pre><h4>Data</h4><p>I will be using the famous <a href="https://www.kaggle.com/datasets/arshid/iris-flower-dataset">Iris</a> Dataset. It consists of features of three different species of the Iris flower.</p><p>The <strong>objective </strong>is to predict the type of species given a completely new set of features as input.</p><pre>data = pd.read_csv(&quot;IRIS.csv&quot;)</pre><h4>Preprocessing</h4><p>Here, we need to encode the species column into discrete values. These values will represent each class.</p><pre><br>def encode_num(x):<br>    value = None <br>    if x == &quot;Iris-setosa&quot;:<br>        value = 0<br>    if x == &quot;Iris-versicolor&quot;:<br>        value = 1<br>    if x == &quot;Iris-virginica&quot;:<br>        value = 2<br><br>    return value<br><br><br>data[&#39;species&#39;] = data[&#39;species&#39;].apply(encode_num</pre><h4>Split</h4><p>We will need to split the data into the training set and test set. We will use <em>80%</em> of the data for training and <em>20%</em> of the data for testing</p><pre># shuffling the dataset<br>data = data.sample(frac=1).reset_index(drop=True)<br><br># training set<br>train_size = int(0.8*len(data))<br>train_data = data.head(train_size)<br><br># test set<br>test_size = int(0.2*len(data))<br>test_data = data.tail(test_size)   <br><br>x_train = np.array(train_data.drop(&quot;species&quot;,axis=1))<br>y_train = train_data[&quot;species&quot;]</pre><h4>Model</h4><p>First, a brief overview of the multivariate normal distribution.</p><p><strong>Multivariate Normal/Gaussian Distribution</strong></p><p>It is abbreviated as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*alTDB0eahEJ0eIVN4TC5yQ.png" /></figure><p>where the parameters are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*76iJZwL3b7nfHSwCEPG6MQ.png" /></figure><p>The Density function (PDF) of the distribution is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*BBXCOTNiV4Ln2KSRk-TQAQ.png" /></figure><p>The mean vector and covariance matrix determines the shape of the PDF.</p><p><strong>Modeling</strong></p><p>The model can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*wP9trENzuJdOBkRz4WSStg.png" /></figure><p>Since the <strong><em>X′s</em></strong> are continuous and the <strong><em>y′s</em></strong> discrete, we make an assumption that <strong><em>P(x|y)</em></strong>, i.e. the <strong><em>X′s</em></strong> follow a <strong>multivariate normal/gaussian distribution, and P(y) </strong>i.e. the <strong><em>y’s </em></strong>follow a Bernoulli distribution.</p><p>Therefore, our parameters are 𝜙, Σ, μ0, μ1. To get the value of these parameters we maximize the log-likelihood.</p><p><strong>log-likelihood</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*6Ay2c_-Fo8puu9gtePR8rg.png" /></figure><p>By maximizing the log-likelihood we get the following maximized likelihood estimates of the parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*8YP8htWgdfKUvtoHJDPyQA.png" /></figure><pre># we calculate the probability of occurence for each of the classes<br>priors = y_train.value_counts()/len(y_train)<br><br># we calculate the mean values<br>mean = data.groupby(&#39;species&#39;).mean()<br><br># we calculate the variance values<br>covariance = data.groupby(&#39;species&#39;).cov()</pre><p>In order to make a prediction, we sum the log of P(y) with the log of P(x|y) and choose the class containing the largest result to be the predicted class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*AViR233RYkQ_1XnHuzN-UA.png" /></figure><pre>def predict(x_test, priors, mean , cov):<br>    <br>    labels = mean.shape[0]<br>    results = np.zeros((x_test.shape[0], labels))<br>    for label in range(labels):<br>        pdf = multivariate_normal(mean = mean.loc[label], cov = cov.loc[label])<br>        <br>        for i, data in enumerate(x_test):<br>            results[i, label] = np.log(priors[label]) + pdf.logpdf(data)<br>            <br>    predictions = np.argmax(results, axis=1)<br>    return predictions</pre><h4>Evaluation</h4><p>The model performed quite well with an accuracy of 96.6667% which is in fact pretty good.</p><pre>x_test = test_data[[&#39;sepal_length&#39;, &#39;sepal_width&#39;, &#39;petal_length&#39;, &#39;petal_width&#39;]]<br>y_test = test_data[&#39;species&#39;]<br><br>x_test = np.array(x_test)<br><br>preds = predict(x_test,priors,mean,covariance)<br><br>print(accuracy_score(y_test,preds) * 100)</pre><p>Check out the full code through the link below</p><p><a href="https://github.com/Jayem-11/ML-Algorithms-from-scratch/tree/main/supervised%20learning/Generative_Learning_algorithms/Gaussian%20Discrimanant%20analysis">ML-Algorithms-from-scratch/supervised learning/Generative_Learning_algorithms/Gaussian Discrimanant analysis at main · Jayem-11/ML-Algorithms-from-scratch</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=655acef23e0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression from scratch]]></title>
            <link>https://medium.com/@johnmichaelrono/logistic-regression-from-scratch-f8527293d2ee?source=rss-a79a8f8d3d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8527293d2ee</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <dc:creator><![CDATA[John michael rono]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 18:59:56 GMT</pubDate>
            <atom:updated>2023-01-27T18:59:56.233Z</atom:updated>
            <content:encoded><![CDATA[<p>The math behind Logistic Regression — with code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGVK5EdCKj9z77uSXfBWUw.jpeg" /></figure><p>The following article gives a summarized version of the Stanford CS229 Machine Learning course on logistic regression. In addition, code for the corresponding mathematical equations is included. For an in-depth understanding of the algorithm, you should check out the material.</p><p><a href="http://cs229.stanford.edu/syllabus-summer2019.html">CS229: Machine Learning - The Summer Edition!</a></p><p>Logistic Regression is a supervised machine learning algorithm that is applied to classification problems. Here, the 𝑦′𝑠(Output) are discrete valued i.e. they take the form of 0 or 1.</p><h3>Imports</h3><pre>import pandas as pd #for data manipulation, CSV file I/O (e.g. pd.read_csv)<br>import numpy as np #for numerical calculation<br>import matplotlib.pyplot as plt #for plotting<br>from sklearn.metrics import accuracy_score # for measuring accuracy</pre><h3><strong>Data</strong></h3><p>The <a href="https://www.kaggle.com/code/neisha/heart-disease-prediction-using-logistic-regression/data?q=framingham.csv">data</a> is publicly available on Kaggle. It consists of risk factors as variables that could potentially lead to Heart disease in 10 years&#39; time.</p><p>The <strong>objective</strong> is to predict the overall risk of getting heart disease in 10 years&#39; time based on the features</p><pre>data = pd.read_csv(&#39;Framingham&#39;)<br>data.dropna(inplace = True)<br>data.head()</pre><h3>Split</h3><p>We will need to split the data into the training set and test set so that we can have a means of testing the accuracy of the model we are building. We can use <em>80%</em> of the data for training and <em>20%</em> of the data for testing</p><pre># training set<br>train_size = int(0.8*len(data))<br>train_data = data.head(train_size)<br><br># test set<br>test_size = int(0.2*len(data))<br>test_data = data.tail(test_size)</pre><h3>Features</h3><p>We can separate the training data into X(input features) and y(target)</p><pre>X = train_data[[&#39;male&#39;, &#39;age&#39;, &#39;education&#39;, &#39;currentSmoker&#39;, &#39;cigsPerDay&#39;, &#39;BPMeds&#39;,<br>       &#39;prevalentStroke&#39;, &#39;prevalentHyp&#39;, &#39;diabetes&#39;, &#39;totChol&#39;, &#39;sysBP&#39;,<br>       &#39;diaBP&#39;, &#39;BMI&#39;, &#39;heartRate&#39;, &#39;glucose&#39;]]<br>y = train_data[&#39;target&#39;]</pre><h3>Normalization</h3><p>In order to have a much more uniformly scaled dataset, we can apply the formula below to normalize our data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*66UECL6C0LiZxD5SB9GGcA.png" /></figure><pre>df = pd.DataFrame()<br><br>for i in range(0,15):<br>    col = X.columns[i]<br>    mean = X[col].mean()<br>    std =X[col].std()<br>     <br>    def standard(x):<br>        return (x-mean)/std<br>    <br>    df[col] = X[col].apply(standard)</pre><h3>Hypothesis</h3><p>The goal is to find the hypothesis(<em>h_x</em>) that maps the 𝑋′𝑠 to the corresponding 𝑦 class.</p><p>The input features can be expressed as a linear combination. We have 15 input features</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*YUuTL4IOFS-U0urf0wguvw.png" /></figure><p><strong>where:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/63/1*ZNu8B2kgeTSC95n2b_CFug.png" /></figure><p>The linear combination is then fed into a sigmoid function. The output will then be the hypothesis we need. The sigmoid function outputs values between 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*ZAYseSCKnK1h7H2IL7dTRA.png" /></figure><p>The sigmoid function is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*7o1K9sLH-5qquHfH30iR0A.png" /></figure><p>From the graph, we notice that as 𝑧→∞, 𝑔(𝑧) tends toward 1 and as 𝑧→−∞,𝑔(𝑧)→tends toward 0</p><p>In our case 𝑧=𝜃𝑇𝑥. Therefore, ℎ(𝜃𝑇𝑥)=𝑔(𝜃𝑇𝑥) will consist of values between 0 and 1 with which we can easily classify to either class. For example, if the value of ℎ(𝜃𝑇𝑥) is between 0 and 0.5 it belongs to class 0 and if it falls between 0.5 and 1, it belongs to class 1.</p><pre>x = np.array(df)<br>y = np.array(y)<br><br># x_0 is always 1<br>x = np.hstack((np.ones((x.shape[0],1)), x))<br>y = np.reshape(y, (2924 ,1))<br><br># initial value of theta = 0<br>theta = np.zeros((x.shape[1], 1))<br><br>#hypothesis function<br>def hypo( x, theta):<br>    z = np.matmul(x, theta)<br>    return 1/(1 + np.exp(-z))</pre><h3>Optimization</h3><p>Here, we need to find the value on 𝜃 that will minimize the loss i.e. the value of 𝜃 that will result in a prediction that is as close as possible to the actual value of 𝑦. We can find this 𝜃 value though maximizing the likelihood.</p><p>First, assume:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*IPjhiLh5HJ2gI2Dxir3_Pw.png" /></figure><p>This can be written more compactly as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*1pW4pgz_DZ_CX1VSoImgPg.png" /></figure><p><strong>Likelihood:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*G-KgBq_f0ZHjuuNRpzotYg.png" /></figure><p><strong>Log-likelihood:</strong> It is easier to maximize the log-likelihood</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*W9fEPXx23DdAd6CC7tAVyw.png" /></figure><p><strong>Loss:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*bI3u5U5FViuYVJwb4J0N_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*-qku0V0mMzP-DDLL18J5Og.png" /></figure><p><strong>stochastic gradient ascent rule</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*-B0ti_4j987BPDE1rLuU3w.png" /></figure><p>for a single training example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*aWxqFJugIn1fhong0QouFQ.png" /></figure><pre>def optimize(x,y,theta,alpha=0.1 ,epochs=30):<br>    <br>    for i in range(epochs):<br>        h_x   = hypo(x , theta)<br>        error = np.dot(x.T,(y - h_x))<br>        theta = theta + (alpha)*error<br>    <br>    return theta<br><br>theta = optimize(x, y, theta , alpha= 0.1 , epochs = 3000)</pre><h3>Evaluation</h3><p>We use 20% of the data for testing how accurate we are. Remember, we first need to normalize the data.</p><p>After normalizing the sample, we multiply it with the optimized parameter values to get the predictions</p><p>Finally, we compare the predictions to the actual y values to get an accuracy score.</p><pre>sample =  test_data.drop(&#39;target&#39;,axis=1)<br>y_test = test_data[&#39;target&#39;]<br><br># normalizing the test set<br>for i in range(0,15):<br>    col = X.columns[i]<br>    mean = X[col].mean()<br>    std =X[col].std()<br>    <br>    sample_col = sample.columns[i]<br>     <br>    def standard(x):<br>        return (x-mean)/std<br>    <br>    sample[sample_col] = sample[sample_col].apply(standard)<br><br><br>sample = np.array(sample)<br><br># adding ones to as the initial x_0<br>sample = np.insert(sample, 0, 1, axis=1)<br><br># multiply the sample with the optimized parameters<br>result = hypo(sample, theta)<br><br>predictions = []<br><br># decision boundary<br>for i in range(731):<br>    if result[i] &gt;= 0.5:<br>        predictions.append(1)<br>    elif result[i] &lt; 0.5:<br>        predictions.append(0)<br><br>accuracy_score(y_test,predictions)</pre><p>We get an accuracy of about 70% which is not that bad, but there is room for improvement.</p><h3>Full Code:</h3><p>The full code is available on the GitHub link below:</p><p><a href="https://github.com/Jayem-11/ML-Algorithms-from-scratch/tree/main/supervised%20learning/Logistic_regression">ML-Algorithms-from-scratch/supervised learning/Logistic_regression at main · Jayem-11/ML-Algorithms-from-scratch</a></p><h3>References</h3><p><a href="http://cs229.stanford.edu/syllabus-summer2019.html">CS229: Machine Learning - The Summer Edition!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8527293d2ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression from Scratch]]></title>
            <link>https://medium.com/@johnmichaelrono/linear-regression-from-scratch-122183750df?source=rss-a79a8f8d3d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/122183750df</guid>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[John michael rono]]></dc:creator>
            <pubDate>Fri, 13 Jan 2023 19:51:21 GMT</pubDate>
            <atom:updated>2023-01-13T19:51:21.681Z</atom:updated>
            <content:encoded><![CDATA[<p>The math behind Linear Regression — with code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqfTgqcb9EAwaesuf7i8jA.jpeg" /><figcaption><a href="http://: https://www.pexels.com/photo/bright-flashlights-glow-at-night-national-park-4424068/">Photo by Ricardo Esquivel</a></figcaption></figure><p>The article follows the Stanford CS229 Machine Learning course on linear regression. I strongly emphasize you go through the material for further insights.</p><p><a href="http://cs229.stanford.edu/syllabus-summer2019.html">CS229: Machine Learning - The Summer Edition!</a></p><h3>Data</h3><p>The <a href="https://www.kaggle.com/datasets/kanths028/usa-housing">data</a> consist of 7 columns</p><p><strong>Objective</strong>: To predict the price of a house given only the features<br>- Input features e.g. ‘Avg. Area Income’ — X’s. <br>- Price is the output. — y<br> <br>We can express the hypothesis as a sum of linear combinations of the features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*x1yTfA6WMZepGRrinJoTnA.png" /></figure><pre>def hypo(x, theta):<br>   return np.matmul(x, theta)</pre><p><strong>where θ are the parameters(Weights)</strong></p><p>we can therefore express the hypothesis as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*RSA4m8HyRh6nW1EVut2U2g.png" /></figure><p><strong>Loss Function</strong>:<br>The loss function measures for each θ, how close the predictions are to their corresponding targets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*SPR-8eGDKluWd6lKwHI_FA.png" /></figure><p><strong>Cost function</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*5Gkpd5-brOlw4HMpy_Opqw.png" /></figure><pre>def cost_fn(x,y, theta):<br>    return (hypo(x, theta) - y).T@(hypo(x, theta) - y)/(2*x.shape[0])</pre><p>where n is the number of sampled data</p><p><strong>i.e. cost function is the sum of losses from the loss function</strong></p><h3><strong>1. LMS Algorithm</strong><br> <br><strong>Aim</strong>:</h3><p>We want to choose θ so as to minimize J(θ)</p><p><strong>Gradient Descent</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*SqnSt0ryUyFJIedXSJ8mJg.png" /></figure><p><strong>Solving the differential using chain rule yields:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*Ns34tOPZIYwOqir9Zcu7eg.png" /></figure><p><strong>LMS(Least mean squares) Update rule/Widrow Hoff learning rule :</strong></p><p>For a single training example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*qTSCyD4I1DvqBtcrQjrS1w.png" /></figure><p><strong>Batch Gradient Descent</strong></p><p>For more than one example:</p><p>Repeat until convergence{</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*-CsLG9Ia8nK7xl1w7R_EHw.png" /></figure><p>}</p><p>In a more succinct way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*U2pj1WMtHZYkGps6sqXVqg.png" /></figure><ul><li>Batch Gradient Descent is computationally expensive for a large training set since for each step, gradient descent is computed using the entire training set</li></ul><p><strong>Stochastic Gradient Descent</strong></p><p>Loop{</p><p>for 𝑖=1 to 𝑛, {</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*LzO0kcXgWdfP59Umevuc-g.png" /></figure><p>}</p><p>}</p><p>In a more succinct way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*PmNzAerEfQxCRDL6j9-ORw.png" /></figure><ul><li>This converges much faster</li><li>It is better for a larger training set</li><li>Gradient Descent is computed with a single training sample i.e. k is uniformly sampled at random for the entire training set</li></ul><pre>def grad_d(x,y,theta,alpha=0.1 ,epochs=10):<br>    m = x.shape[0]<br>    cost = []<br>    <br>    for i in range(epochs):<br>        h_x   = hypo(x , theta)<br>        error = (1/m)*(x.T@(h_x - y))<br>        theta = theta - (alpha)*error<br>        cost.append(cost_fn(x,y,theta))<br>    <br>    return theta , cost</pre><h3>2. The Normal Equation</h3><p>Apart from Gradient Descent, we can be able to find the closed-form solution of 𝜃 that minimizes 𝐽(𝜃)</p><ul><li>From the training set we can define a design matrix 𝑋 such that:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/119/1*1amlzsgmnbVeb8I4VEdbZg.png" /></figure><ul><li>From the target values:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*QwDibk_rKnRAPC0hQyQ7zA.png" /></figure><ul><li>The cost function is given by:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*UkgQY3VroLb2nyeOufLHfQ.png" /></figure><ul><li>Therefore the value of 𝜃 that minimizes 𝐽(𝜃) is given in closed form by the equation below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*0HHjyNj1eaFX6jp2DYAMJw.png" /></figure><pre><br>theta_normal = (np.linalg.inv(x.T@x))@(x.T)@(y)</pre><h3>3. Probabilistic Interpretation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*pH9s5A2cRwX3zW1d60x4LQ.png" /></figure><p>where 𝜖 random noise distributed normally with mean 0 and variance 𝜎2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*m1XzSUJrzUJvU12k0_GPzg.png" /></figure><ul><li>This is due to the location-scale property of gaussian</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*fzNZkzRPYj5iKXns7HXBHw.png" /></figure><p><strong>Note</strong></p><ul><li>Maximizing the log-likelihood minimizes the loss.</li></ul><p><strong>𝑎𝑟𝑔𝑚𝑎𝑥ℓ(𝜃)=𝑎𝑟𝑔𝑚𝑖𝑛𝐽(𝜃)</strong></p><h3>The Code</h3><p>The code is available on GitHub:</p><p><a href="https://github.com/Jayem-11/ML-Algorithms-from-scratch">GitHub - Jayem-11/ML-Algorithms-from-scratch: Math behind machine learning algorithms(with code)</a></p><pre>import numpy as np <br>import pandas as pd <br>import matplotlib.pyplot as plt<br><br>#import data<br>data = pd.read_csv(&quot;USA_Housing.csv&quot;)<br>data.drop(&#39;Address&#39;,axis= 1, inplace =True)<br><br>#split data<br>X = data[[&#39;Avg. Area Income&#39;, &#39;Avg. Area House Age&#39;, &#39;Avg. Area Number of Rooms&#39;,<br>       &#39;Avg. Area Number of Bedrooms&#39;, &#39;Area Population&#39;]]<br>y = data[&#39;Price&#39;]<br><br><br>df = pd.DataFrame()<br><br>#preprocessing<br><br>#normalization<br>for i in range(0,5):<br>    col = X.columns[i]<br>    mean = X[col].mean()<br>    std =X[col].std()<br>     <br>    def standard(x):<br>        return (x-mean)/std<br>    <br>    df[col] = X[col].apply(standard)<br>    <br>    <br>x = np.array(df)<br>y = np.array(y)<br><br>x = np.hstack((np.ones((x.shape[0],1)), x))<br>y = np.reshape(y, (5000,1))<br><br>#initial theta values<br>theta = np.zeros((x.shape[1], 1))<br><br>#hypothesis<br>def hypo(x, theta):<br>    return np.matmul(x, theta)<br><br>#cost function<br>def cost_fn(x,y, theta):<br>    return (hypo(x, theta) - y).T@(hypo(x, theta) - y)/(2*x.shape[0])<br><br>#gradient descent<br>def grad_d(x,y,theta,alpha=0.1 ,epochs=10):<br>    m = x.shape[0]<br>    cost = []<br>    <br>    for i in range(epochs):<br>        h_x   = hypo(x , theta)<br>        error = (1/m)*(x.T@(h_x - y))<br>        theta = theta - (alpha)*error<br>        cost.append(cost_fn(x,y,theta))<br>    <br>    return theta , cost<br><br><br>#function to plot cost<br>def pl_cost(J, epochs):<br>    plt.xlabel(&#39;Epochs&#39;)<br>    plt.ylabel(&#39;Cost&#39;)<br>    plt.plot(epochs, J)<br><br>    <br>#optimization<br>theta, cost = grad_d(x, y, theta , alpha= 0.1 , epochs = 30)<br><br><br>epochs = []<br>z = []<br>count = 0<br>for i in cost:<br>    z.append(i[0][0])<br>    epochs.append(count)<br>    count += 1<br>z = np.array(z)<br>epochs = np.array(epochs)<br>pl_cost(z, epochs)<br><br><br>#Testing new sample<br>sample= data.sample()<br>sample.drop(&#39;Price&#39;,axis=1,inplace=True)<br><br><br>for i in range(0,5):<br>    col = X.columns[i]<br>    mean = X[col].mean()<br>    std =X[col].std()<br>    <br>    sample_col = sample.columns[i]<br>     <br>    def standard(x):<br>        return (x-mean)/std<br>    <br>    sample[sample_col] = sample[sample_col].apply(standard)<br>        <br>sample = np.array(sample)<br>sample[0][0] = 1<br><br>result = theta[0] + theta[1]*sample[0][1] + theta[2]*sample[0][2] + theta[3]*sample[0][3]+ theta[4]*sample[0][4]<br>print(&quot;Price of house: &quot;, result[0])<br><br><br># The normal Equation<br>theta_normal = (np.linalg.inv(x.T@x))@(x.T)@(y)<br><br>result_normal = theta_normal[0] + theta_normal[1]*sample[0][1] + theta_normal[2]*sample[0][2] + theta_normal[3]*sample[0][3]+ theta_normal[4]*sample[0][4]<br>print(&quot;Price of house: &quot;, result_normal[0])<br><br></pre><h3>References</h3><p><a href="http://cs229.stanford.edu/syllabus-summer2019.html">CS229: Machine Learning - The Summer Edition!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=122183750df" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>