<?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 Erkan Hatipoğlu on Medium]]></title>
        <description><![CDATA[Stories by Erkan Hatipoğlu on Medium]]></description>
        <link>https://medium.com/@e109261?source=rss-c287c56e4845------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uOooJHw7OQCDgL7fvx5ofA.jpeg</url>
            <title>Stories by Erkan Hatipoğlu on Medium</title>
            <link>https://medium.com/@e109261?source=rss-c287c56e4845------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 09:31:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@e109261/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[Multivariate Linear Regression From Scratch]]></title>
            <link>https://pub.towardsai.net/multivariate-linear-regression-from-scratch-c6702e26cce0?source=rss-c287c56e4845------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6702e26cce0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[cost-function]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Erkan Hatipoğlu]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 12:02:11 GMT</pubDate>
            <atom:updated>2023-03-21T12:02:11.794Z</atom:updated>
            <content:encoded><![CDATA[<h4>With Code in Python</h4><figure><img alt="A man holding a note that writes code shows the paper with his other hand." src="https://cdn-images-1.medium.com/max/1024/0*BZQyOBhaQOYuKHO_" /><figcaption>Photo by <a href="https://unsplash.com/@hiteshchoudhary?utm_source=medium&amp;utm_medium=referral">Hitesh Choudhary</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In this new episode of the Machine Learning Basics series, we will create a model for a multivariate linear regression task and validate our model using <a href="https://matplotlib.org/">Mathplotlib</a>, <a href="https://pandas.pydata.org/">Pandas</a>, and <a href="https://numpy.org/">NumPy</a> libraries in Python. While creating our model, we will use a <a href="https://www.kaggle.com/">Kaggle</a> <a href="https://www.kaggle.com/datasets/mohansacharya/graduate-admissions?datasetId=14872">dataset</a> as a training and validation resource. For this purpose, we will use and explain the essential parts of the following <a href="https://www.kaggle.com/">Kaggle</a> Notebook:</p><p><a href="https://www.kaggle.com/code/erkanhatipoglu/multivariate-linear-regression-from-scratch">Multivariate Linear Regression From Scratch</a></p><p>Our previous episode explained basic machine learning concepts and the notions of hypothesis, cost, and gradient descent. In addition, using Python and some other libraries, we have written functions for those algorithms and created and validated a model for a univariate linear regression task. If you are new to Machine Learning or want to refresh the basic Machine Learning concepts, reading our previous episode will be a good idea since we will not explain those subjects in this episode.</p><p><a href="https://pub.towardsai.net/univariate-linear-regression-from-scratch-68065fe8eb09">Univariate Linear Regression From Scratch</a></p><p>We will use the gradient descent approach for the model creation task and will not discuss the <strong><em>Normal Equation</em></strong> since it will be the subject of another episode in this series. Therefore, we will write code for the hypothesis, cost, and gradient descent functions before training our model.</p><p>We will also introduce two new concepts: <strong><em>Vectorization</em></strong> and <strong><em>Feature Scaling</em></strong>. So, let’s start with vectorization.</p><h3>Vectorization</h3><p>Vectorization is the <strong><em>speed</em></strong> perspective in the implementation [1]. One way to implement Machine Learning algorithms is by using software loops in our code. Since we need to add or substruct values for each data sample for implementing Machine Learning algorithms, it seems obvious to use software loops. On the other hand, various numerical linear algebra libraries we can utilize are either built-in or quickly accessible in most programming languages. Those libraries are more efficient and can use parallel hardware in our computers if available. Therefore, instead of less efficient loops, we can use vectors and matrices in those libraries to speed up. Moreover, we will write less code resulting in a cleaner implementation [2]. This concept is known as vectorization.</p><p>This blog post will use Python’s <a href="https://numpy.org/">NumPy</a> library for vectorization.</p><h3>Feature Scaling</h3><p>We can speed up gradient descent by having each input value in roughly the same range [2]. This approach is called feature scaling. Applying feature scaling may be necessary for objective functions to work precisely in some machine learning algorithms or penalize the coefficients appropriately in regularization [3].</p><p>Still, for our specific case, the gradient descent may converge more quickly if we apply feature scaling since θ will descend more rapidly in small ranges than large ranges, which causes oscillations while finding the optimum θ values [2].</p><p>There are various techniques for scaling; we will present three of them:</p><h4>Standardization</h4><p>For each sample value x of a feature, if we subtract the average value of that feature from x and divide the result by the standard deviation for that feature, we get a standardized solution. In mathematical terms:</p><figure><img alt="x prime equals open paren x minus average of x vector close paren divided by standard deviation of x vector." src="https://cdn-images-1.medium.com/max/385/1*9m5QPzG7_Nm3DRC5UMLmcw.png" /><figcaption>Mathematical Formulation for Standardization — Image by Author</figcaption></figure><h4>Mean Normalization</h4><p>For each sample value x of a feature, if we subtract the average value of that feature from x and divide the result by the difference between the maximum and minimum values of that feature, we get a <br>mean normalized solution. In mathematical terms:</p><figure><img alt="x prime equals open paren x minus average of x vector close paren divided by open paren max of x vector minus min of x vector close paren." src="https://cdn-images-1.medium.com/max/397/1*b-E400MnZMdcnXzk-wQQEg.png" /><figcaption>Mathematical Formulation for Mean Normalization — Image by Author</figcaption></figure><h4>Min-Max Scaling</h4><p>For each sample value x of a feature, if we subtract the minimum value of that feature from x and divide the result by the difference between the maximum and minimum values of that feature, we get a <br>min-max scaled solution. In mathematical terms:</p><figure><img alt="x prime equals open paren x minus min of x vector close paren divided by open paren max of x vector minus min of x vector close paren." src="https://cdn-images-1.medium.com/max/395/1*LXrl_0cz_RMh9gs96BHG0A.png" /><figcaption>Mathematical Formulation for Min-Max Scaling — Image by Author</figcaption></figure><h4>The Normalize Function</h4><p>Below you will find the code we have used for feature scaling. You can find all three approaches we have discussed in the comments. We have chosen min-max scaling for feature scaling, which you can see at the bottom of the code block.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb03342566a36f6a37e3893e9bd1c458/href">https://medium.com/media/eb03342566a36f6a37e3893e9bd1c458/href</a></iframe><p>We use the <a href="https://pandas.pydata.org/docs/index.html">Pandas</a> Library’s <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.min.html">min()</a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.max.html">max()</a> methods inside the code block. You can refer to the <strong>Imports</strong> section for importing Pandas Library. Interested readers may also refer to the Notebook <a href="https://www.kaggle.com/code/erkanhatipoglu/multivariate-linear-regression-from-scratch">Multivariate Linear Regression From Scratch</a> to see which columns are selected for scaling.</p><h3>Imports</h3><p>As stated previously, we need additional libraries to fulfill our requirements while writing the code for a multivariate regression task. These imports can be found below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1a7cbd8ea2e9ecea3c482215c0d3cea/href">https://medium.com/media/c1a7cbd8ea2e9ecea3c482215c0d3cea/href</a></iframe><p>We will use the <a href="https://numpy.org/">NumPy</a> library for Matrix operations and vectorization purposes and the <a href="https://pandas.pydata.org/">Pandas</a> library for data processing tasks. The <a href="https://matplotlib.org/">Matplotlib</a> library will be used for visualization purposes.</p><p><a href="https://scikit-learn.org/stable/">Scikit-learn</a> (or sklearn) is a prevalent library for Machine Learning. <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html#sklearn.model_selection.train_test_split">train_test_split</a> from sklearn is used for splitting the dataset into two portions for training and validation. Although we will not use train_test_split in our code in this blog post, we need to use it for splitting our data. Interested readers may refer to the Notebook <a href="https://www.kaggle.com/code/erkanhatipoglu/multivariate-linear-regression-from-scratch">Multivariate Linear Regression From Scratch</a> for how it is used.</p><h3>The Hypothesis</h3><p>The hypothesis will compute the predicted values for a given set of inputs and weights.</p><p>The hypothesis for a linear regression task with multiple variables is of the form:</p><figure><img alt="y_hat equals h_θ of x equals θ_0 plus θ_1 times x_1 plus θ_2 times x_2 up to θ_n times x_n." src="https://cdn-images-1.medium.com/max/478/1*mlUXXm-TBG0YTrl7wHK9Sw.png" /><figcaption>The Hypothesis Formula — Image by Author</figcaption></figure><p>The equation above is not suitable for a vectorized solution. So let’s define θ and x column vectors such that;</p><figure><img alt="θ is a column vector of elements θ_0 up to θ_n, and x is a column vector of elements x_0 up to x_n, where x_0 equals 1." src="https://cdn-images-1.medium.com/max/306/1*JygFaMAFAU7mOOvim2EJNw.png" /><figcaption>Column vectors of θ and x — Image by Author</figcaption></figure><p>Now we can rewrite the equation above as follows:</p><figure><img alt="h_θ of x equals transpose of θ vector dot x vector." src="https://cdn-images-1.medium.com/max/328/1*tiZtXwXu5v_QD9wvl4TWCA.png" /><figcaption>The Vectorized Hypothesis Formula — Image by Author</figcaption></figure><p>For most of the datasets available, each row represents one training (or test) sample such that:</p><figure><img alt="x is a matrix of m times n with elements x_1 to the one up to x_n to the one in row 1 up to x_1 to the m up to x_n to the m in row m." src="https://cdn-images-1.medium.com/max/241/1*uAs4DWfcIJrzDsjIMqSFmA.png" /><figcaption>A Common Dataset of m Samples and n Features — Image by Author</figcaption></figure><p>However, as described above, we need x₀ = 1 for a vectorized solution. So, we must adjust our data set with a new column of x₀ with all ones.</p><figure><img alt="x is a matrix of m times n plus 1 with elements x_0 to the one up to x_n to the one in row 1 up to x_0 to the m up to x_n to the m in row m." src="https://cdn-images-1.medium.com/max/246/1*VxgmmzjWKLfpBr8dcZzkAg.png" /><figcaption>Modified Dataset of (m X n+1) Dimensions— Image by Author</figcaption></figure><p>Therefore, for a dataset of m samples and n features, we can insert a new column x₀ of ones and then compute a column vector of (m x 1) dimensions such that every element of the column vector is a predicted target for one dataset sample. The formula is as follows:</p><figure><img alt="h_θ of x equals X vector dot θ vector equals column vector with elements h_θ of x_1 up to h_θ of x_m." src="https://cdn-images-1.medium.com/max/740/1*cT9f-wRtdwZtOO9AB9WixA.png" /><figcaption>A Vectorized Hypothesis for an m Sample Dataset — Image by Author</figcaption></figure><blockquote>Note that we have assigned a new column x₀ to the x matrix, which is one. This is necessary for a vectorized solution, and we will see how to do it in the Model Training section.</blockquote><p>As can be seen, we need two parameters to write the hypothesis function. These are an x matrix of (m X n+1) dimensions for training (or test) data and a θ column vector of (n+1) elements for weights. m is the number of samples, and n is the number of features. So, let’s write the Python function for the hypothesis:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fb1dec196702a1aae3f56f31fba1156/href">https://medium.com/media/1fb1dec196702a1aae3f56f31fba1156/href</a></iframe><p>Inside the hypothesis function, we return the dot product of the parameters using the NumPy library dot() method.</p><h3>The Cost Function</h3><p>We will use the squared error cost function as in the <a href="https://medium.com/towards-artificial-intelligence/univariate-linear-regression-from-scratch-68065fe8eb09">univariate linear regression case</a>. Therefore, the cost function is:</p><figure><img alt="j of θ equals one over two times m times sum of open paren h_θ of x minus y close paren squared from one up to m samples." src="https://cdn-images-1.medium.com/max/364/1*jgnPOlWhuIVJsYWAx2lieA.png" /><figcaption>Squared Error Cost Function — Image by Author</figcaption></figure><p>To achieve a vectorized solution, we can use the following vector:</p><figure><img alt="The squared error vector is open paren h of x to the one minus y to the one close paren square up to the h of x to the m minus y to the m close paren square." src="https://cdn-images-1.medium.com/max/156/1*Qa9UMvnAS15QA342SQ9FOQ.png" /><figcaption>The Squared Error Vector — Image by Author</figcaption></figure><p>This (m X 1) vector has some resemblance to the Hypothesis vector explained above, and we will exploit this similarity. The sum of this vector’s elements is the Σ part of the cost function, and that is:</p><figure><img alt="The sum of open paren h of x to the one minus y to the one close paren square up to the h of x to the m minus y to the m close paren square equals the sum of all the elements of the squared error vector." src="https://cdn-images-1.medium.com/max/564/1*gjTUQgCJAG1C74dv-2Totg.png" /><figcaption>The Sum of Squared Errors — Image by Author</figcaption></figure><p>We get the vector below if we factor the squares in each vector item.</p><figure><img alt="The sum of all the items of the squared error vector equals the sum of all the elements of the vector open paren h of x to the one minus y to the one close paren times open paren h of x to the one minus y to the one close paren up to open paren the h of x to the m minus y to the m close paren times open paren the h of x to the m minus y to the m close paren." src="https://cdn-images-1.medium.com/max/540/1*Gfl0aPNLg4VGsK73T1SpOA.png" /><figcaption>Factorization— Image by Author</figcaption></figure><p>This equation can be rewritten as the dot product of the following row and column vectors.</p><figure><img alt="The sum of all the elements of the squared error vector equals the row vector open paren h of x to the one minus y to the one close paren up to open paren h of x to the m minus y to the m close paren dot column vector open paren the h of x to the one minus y to the one close paren up to open paren the h of x to the m minus y to the m close paren." src="https://cdn-images-1.medium.com/max/646/1*kLJXoOh3gQQjeabOpnlBdw.png" /><figcaption>The Dot Product — Image by Author</figcaption></figure><p>We get the following vectors if we change the ordering of the variables in the equation.</p><figure><img alt="The sum of all the elements of the squared error vector equals open paren the row vector h of x to the one up to h of x to the m minus row vector y to the one up to y to the m close paren dot open paren the column vector h of x to the one up to h of x to the m minus column vector y to the one up to y to the m close paren." src="https://cdn-images-1.medium.com/max/718/1*dTlsdGgCcI6nMC2IK1DExA.png" /><figcaption>Reordering — Image by Author</figcaption></figure><p>And by replacing the vectorized hypothesis with Xθ, we get the following equation.</p><figure><img alt="The sum of all the elements of the squared error vector equals open paren x vector dot θ vector minus y vector close paren transpose dot open paren x vector dot θ vector minus y vector close paren." src="https://cdn-images-1.medium.com/max/229/1*Iv3k-8teI4DbdK4Nv_0sAw.png" /><figcaption>Vectorized Form — Image by Author</figcaption></figure><p>Finally, we get the vectorized cost function by multiplying this equation with one over two times m.</p><figure><img alt="J of θ equals one over open paren two times m close paren times open paren x vector dot θ vector minus y vector close paren transpose dot open paren x vector dot θ vector minus y vector close paren." src="https://cdn-images-1.medium.com/max/255/1*kTp1yvmOLD_u4BbD4X-T8g.png" /><figcaption>Vectorized Cost Function — Image by Author</figcaption></figure><p>We need three parameters for the cost function: the X, y, and θ vector. The X parameter is an (m X n+1) dimensions matrix where m is the number of examples and n is the number of features, and it is the training (or test) dataset. The y parameter is an (m X 1) dimensions vector that holds the actual outputs for each sample. The θ parameter is an (n+1 X 1) dimensions vector for weights.</p><blockquote>Note that we are using the hypothesis function inside the cost function, so to use the cost function, we must also write the hypothesis function.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae4cd783d3964b23d58c408e95e29ea6/href">https://medium.com/media/ae4cd783d3964b23d58c408e95e29ea6/href</a></iframe><p>We can factor the cost function formula into three parts. A constant part, a vector of (mX1) dimensions, and the transpose of the same vector with (1Xm) dimensions.</p><p>So, inside the cost function, we first calculate the constant part. Then we calculate the (mX1) vector using the hypothesis function and the y vector. We can then use NumPy’s transpose function to figure the transpose of the same vector. Finally, we can dot product the two vectors employing the Numpy library, multiply by the constant and return the result.</p><h3>Gradient Descent</h3><p>The gradient descent computation is identical to the univariate version, but the equation must be expanded for n + 1 weights [2].</p><figure><img alt="Repeat until convergence: set open paren θ_0 to θ_0 — α over m times sum from i to the m of open paren h_θ to the i minus y to the i close paren times x_0 to the i up to θ_n to θ_n — α over m times sum from i to the m of open paren h_θ to the i minus y to the i close paren times x_n to the i close paren." src="https://cdn-images-1.medium.com/max/322/1*gJWHu7Mrp3j0DgieykC03g.png" /><figcaption>The Gradient Descent — Image by Author</figcaption></figure><p>In the formula above, n is the number of features, θⱼ (for j=0, 1, …, n) is the corresponding weights of the hypothesis function, α is the learning rate, m is the number of examples, h(x⁽ⁱ⁾) is the result of the hypothesis function for the iᵗʰ training example, y⁽ⁱ⁾ is the actual value for the iᵗʰ training example and xₖ⁽ⁱ⁾ (for k=0, 1, …, n; i=1, 2, …, m) is the value of kᵗʰ feature for the iᵗʰ training example.</p><p>Similar to what we have done in the cost function, we can rewrite the Σ part of these equations as the dot product of two vectors for j=0, 1, …, n:</p><figure><img alt="The sum of open paren h_θ of x to the i minus y to the i close paren times x_j to the i from i equals one up to m equals X transpose dot open paren X dot θ minus y close paren." src="https://cdn-images-1.medium.com/max/303/1*5S7BnnXYC-Wjzx3wVrDmXw.png" /><figcaption>Vectorized Form — Image by Author</figcaption></figure><p>So the vectorized solution for gradient descent becomes:</p><figure><img alt="Set θ vector to θ minus α over m times X transpose dot open paren X dot θ minus y close paren." src="https://cdn-images-1.medium.com/max/201/1*sJqntWAFqB_ppAUlSZ8rzw.png" /><figcaption>Vectorized Gradient Descent— Image by Author</figcaption></figure><p>As can be seen, we need four parameters for the gradient descent function: the X, y, θ vector and the learning rate α.</p><blockquote>Note that we are using the hypothesis function inside the gradient function, so to utilize the gradient function, we must also write the hypothesis function.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bd4795666a93375f88441b216319d3e/href">https://medium.com/media/1bd4795666a93375f88441b216319d3e/href</a></iframe><p>Inside the function, we first compute the constant part of the equation and the transpose of X. Then, we figure out the error vector by subtracting the actual output vector from the hypothesis vector. Next, we compute the dot product of two previously calculated vectors and multiply it by the constant. As a final step, we subtract the outcome from the previous θ and return the result.</p><h3>Data</h3><p>To create and validate our model, we will use the following dataset [4] from Kaggle:</p><p><a href="https://www.kaggle.com/datasets/mohansacharya/graduate-admissions">Graduate Admission 2</a></p><p>The dataset includes several parameters critical for the application of Master’s Programs [5]:</p><p><em>GRE Scores ( out of 340 )<br>TOEFL Scores ( out of 120 )<br>University Rating ( out of 5 )<br>Statement of Purpose and Letter of Recommendation Strength ( out of 5 )<br>Undergraduate GPA ( out of 10 )<br>Research Experience ( either 0 or 1 )<br>Chance of Admit ( ranging from 0 to 1 )</em></p><p>The target variable is the ‘Chance of Admit’ parameter. We will use 80 % of the data for training and 20 % for testing. In addition, we will use a percentage estimation instead of finding the probability for the target variable. We will not explain how to load and process data. Interested readers may refer to the Notebook <a href="https://www.kaggle.com/code/erkanhatipoglu/multivariate-linear-regression-from-scratch?scriptVersionId=121745307&amp;cellId=21">Multivariate Linear Regression From Scratch</a> for loading and splitting the data.</p><p>There are two versions of CSV files in the dataset [5]. We will use version 1.1, which has 500 examples.</p><h3>Model Training</h3><p>Since we have written all the necessary functions, it is time to train the model.</p><p>To apply a vectorized solution, we must define an X₀ feature equal to 1 for all training examples. So our first task is to insert the X₀ column into the training and validation data. Next, we need to initialize the θ vector, and we will set weights to all zero. As the last step before gradient descent, we will assign the learning rate and threshold values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab655529a54239e14f577ff2a84519ac/href">https://medium.com/media/ab655529a54239e14f577ff2a84519ac/href</a></iframe><p>Inside the code block, the first thing to do is compute the m and n values for training and test data. Next, we will create a list of ones to insert into the DataFrames as the first column. This is because we need to define the column X₀=1 for a vectorized solution. Next, we set the θ vector as all zeros. After initializing the learning rate and threshold values, we can calculate the initial cost value and initialize some essential variables for display purposes.</p><p>The threshold value will be used to check whether the gradient descent converges. We will subtract consecutive cost values inside the while loop to do that. If the difference is smaller than a certain threshold, we will conclude that the gradient descent converges. Otherwise, we will keep taking the gradient and recalculating the cost value.</p><h4>The Result</h4><p>The result below is for the initial conditions in the model training code block. The training took 24 iterations. The final cost value was computed at approximately 66, and the θ vector is calculated as:</p><p><strong><em>θ</em></strong><em>: [2.03692557 1.13926025 1.14289218 6.02902784 6.60181418 6.82324225 1.20521232 1.25048269]</em></p><figure><img alt="θ equals [2.03692557 1.13926025 1.14289218 6.02902784 6.60181418 6.82324225 1.20521232 1.25048269]" src="https://cdn-images-1.medium.com/max/586/1*eJZ62TRUN6jkk4X1ByAtnw.png" /><figcaption>The Training Result — Image by Author</figcaption></figure><p>We can also utilize the learning curve to ensure that gradient descent works correctly [2]. The learning curve is a plot that shows us the change in the cost value in each iteration during the training, and the cost value should decrease after every iteration [2]. Interested readers may refer to the Notebook <a href="https://www.kaggle.com/code/erkanhatipoglu/multivariate-linear-regression-from-scratch">Multivariate Linear Regression From Scratch</a> for how to plot the learning curve.</p><figure><img alt="Graph: x-axis is iteration count, and the y-axis is J of θ: J of θ decreases each iteration." src="https://cdn-images-1.medium.com/max/1024/1*ewhBUYjjCbcV1rWB4d41jA.png" /><figcaption>The Learning Curve— Image by Author</figcaption></figure><h3>Model Validation</h3><p>As explained above, we can use learning curves to debug our model. Our learning curve seems all right, and its shape is just as desired [2]. But we still require to validate our model. To do that, we can use the validation dataset, which we have split before the training starts since, for validation, we must use data that has never been used in the training process. We will use the θ vector calculated previously for validation.</p><figure><img alt="The cost of test data is 76.48149798139413" src="https://cdn-images-1.medium.com/max/529/1*39aU7ulzn3zxuxWHdxzw-Q.png" /><figcaption>Validation Result — Image by Author</figcaption></figure><p>The cost value of the validation dataset seems slightly bigger (worse) than the training dataset, which is expected.</p><h3>Conclusion</h3><p>In this blog post, we have written the hypothesis, cost, and gradient descent functions in Python with a vectorization method for a multivariate Linear Regression task. We have also scaled a portion of our data, trained a Linear Regression model, and validated it by splitting our data. We have used the <a href="https://www.kaggle.com/">Kaggle</a> dataset <a href="https://www.kaggle.com/datasets/mohansacharya/graduate-admissions"><strong>Graduate Admission 2</strong></a> for this purpose.</p><p>We set the learning rate high and the convergence threshold low for demonstration purposes, resulting in a learning cost of approximately 66 and a validation cost of roughly 76. This high cost is easily seen by checking the predicted and actual <strong><em>Chance of Admit</em></strong> values. By playing with the learning rate and threshold values, we can get a training cost value smaller than 20, resulting in better predictions.</p><p>But we must be aware that the dataset has been chosen only for demonstration purposes for a multivariate linear regression task, and there may be far better algorithms for this dataset.</p><p>Interested readers can find the code used in this blog post in the <a href="https://www.kaggle.com/">Kaggle</a> notebook <a href="https://www.kaggle.com/code/erkanhatipoglu/multivariate-linear-regression-from-scratch"><strong><em>Multivariate Linear Regression from Scratch</em></strong></a>.</p><p>Thank you for reading!</p><h3>References</h3><p>[1] Ng, A. and Ma, T. (2022) <em>CS229 Lecture Notes</em>, <em>CS229: Machine Learning</em>. Stanford University. Available at: <a href="https://cs229.stanford.edu/notes2022fall/main_notes.pdf">https://cs229.stanford.edu/notes2022fall/main_notes.pdf</a> (Accessed: December 24, 2022).</p><p>[2] Ng, A. (2012) <em>Machine Learning Specialization</em>, <em>Coursera.org</em>. Stanford University. Available at: <a href="https://www.coursera.org/specializations/machine-learning-introduction">https://www.coursera.org/specializations/machine-learning-introduction</a> (Accessed: January 9, 2023).</p><p>[3] <em>Feature scaling</em> (2022) <em>Wikipedia</em>. Wikimedia Foundation. Available at: <a href="https://en.wikipedia.org/wiki/Feature_scaling">https://en.wikipedia.org/wiki/Feature_scaling</a> (Accessed: March 6, 2023).</p><p>[4] Mohan S Acharya, Asfia Armaan, Aneeta S Antony: A Comparison of Regression Models for Prediction of Graduate Admissions, IEEE International Conference on Computational Intelligence in Data Science 2019</p><p>[5] Acharya, M.S. (2018) <em>Graduate admission 2</em>, <em>Kaggle</em>. Available at: <a href="https://www.kaggle.com/datasets/mohansacharya/graduate-admissions">https://www.kaggle.com/datasets/mohansacharya/graduate-admissions</a> (Accessed: March 14, 2023).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6702e26cce0" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/multivariate-linear-regression-from-scratch-c6702e26cce0">Multivariate Linear Regression From Scratch</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Univariate Linear Regression From Scratch]]></title>
            <link>https://pub.towardsai.net/univariate-linear-regression-from-scratch-68065fe8eb09?source=rss-c287c56e4845------2</link>
            <guid isPermaLink="false">https://medium.com/p/68065fe8eb09</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cost-function]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Erkan Hatipoğlu]]></dc:creator>
            <pubDate>Mon, 19 Sep 2022 12:02:15 GMT</pubDate>
            <atom:updated>2023-01-28T09:13:17.943Z</atom:updated>
            <content:encoded><![CDATA[<h4>With Code in Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*lEy6nZXfCm9xBZ4WR8wqHw.png" /><figcaption>Univariate Linear Regression — Image by Author</figcaption></figure><h3>Introduction</h3><p>Generally, one of the first subjects of a <em>Machine Learning</em> Course is <strong>Linear Regression</strong>, which is not very complex and easy to understand. Moreover, it includes many <em>Machine Learning</em> notions that can be used later in more complex concepts. So it is reasonable to start with <strong>Linear Regression</strong> to a new <em>Machine Learning</em> basics series.</p><p>In this blog post, we will learn about <strong>Univariate Linear Regression</strong> which means <strong>Linear Regression</strong> with just <em>one variable</em>. At the end of this article, we will understand fundamental <em>Machine Learning</em> concepts such as the <strong>hypothesis</strong>, <strong>cost function</strong>, and <strong>gradient descent</strong>. In addition, we will write the necessary code for those functions and train/test a linear model for a Kaggle dataset using <strong><em>Python </em></strong>[1].</p><p>Before diving into <strong>Univariate Linear Regression</strong>, let&#39;s briefly talk about some basic concepts:</p><h4>Basic Concepts</h4><p><em>Machine Learning</em> is the subfield of Artificial Intelligence that uses data to program computers for some tasks. A typical <em>Machine Learning</em> application uses a dataset and a learning algorithm to make a model that predicts the outputs for new inputs to the application.</p><p><em>Machine Learning</em> applications are generally divided into three categories:</p><ul><li>Supervised Learning</li><li>Unsupervised Learning</li><li>Reinforcement Learning</li></ul><p>In supervised learning [2], the data have identical features that can be mapped to some label. Supervised learning has two types.</p><p>It is called <strong>classification </strong>if the number of labels is limited and can be transformed into some categories. Identifying animals or handwritten digits in images are examples of classification.</p><p>If the set of labels is not restricted to some small number of elements but can be assumed infinitely many, then it is called <strong>regression</strong>. Predicting the price of houses in a region or gas usage per kilometer of cars are regression examples.</p><p>In unsupervised learning [3], the dataset has no labeled data. After the teaching process, the model discovers the patterns in the data. Categorizing the customers of an e-commerce website is an example of unsupervised learning.</p><p>Reinforcement learning [4] uses intelligent agents who act according to reward and punishment mechanisms [5]. It is mainly used in computer gaming.</p><h3>Linear Regression</h3><p>As we have said above, regression maps inputs to infinitely many outputs. In addition, Linear Regression suggests a linear relationship between the inputs and outcomes [6]; it is challenging to visualize this if we have more than one input variable. If we have one input variable, we need to draw a line in the XY plane; if we have two input variables, we need to construct a plane in the three-dimensional coordinate system. More than two input variables are extremely tough to imagine. As a result, we will demonstrate Linear regression using univariate data. Below are the <a href="https://www.kaggle.com/datasets/kennethjohn/housingprice">housing prices from Portland, Oregon dataset</a> [7], which we will use as an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*IlEh02y2KIE0jbHko4w8IA.png" /><figcaption>Housing Prices from Portland, Oregon — Image by Author</figcaption></figure><p>In the graph above, the y-axis is the price (K$) of some houses in Portland, and the x-axis is the house&#39;s size (feet²). We want to draw a straight line on this graph (such as the image below) so that when we know the size of a new home not in this dataset, we can predict its price by using that line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*lEy6nZXfCm9xBZ4WR8wqHw.png" /><figcaption>Housing Prices from Portland, Oregon with Hypothesis— Image by Author</figcaption></figure><p>For example, we can predict that the price of a 3000 feet² house is approximately 500 K$, as seen in the graph below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*FEAseL5rLip4kIB_cMme2Q.png" /><figcaption>Calculating New Inputs for Housing Prices from Portland, Oregon — Image by Author</figcaption></figure><p>So without further ado, let&#39;s dive into more profound concepts to understand how to draw that line.</p><blockquote>Note that this article uses the <a href="https://www.kaggle.com/datasets/andonians/random-linear-regression"><strong>Linear Regression</strong></a> dataset [1] and <a href="https://www.kaggle.com/code/erkanhatipoglu/univariate-linear-regression-from-scratch"><strong>Univariate Linear Regression from Scratch</strong></a> notebook [8] from Kaggle. As described in the content part of the dataset, it has a training dataset of 700 and a test dataset of 300 elements. The data consists of pairs of (x,y) where x’s are numbers between 0 and 100 and y’s have been generated using the Excel function NORMINV(RAND(), x, 3). It is also given that the best estimate for y should be x.</blockquote><p>First, we must write three functions to find a univariate linear regression solution on a dataset. These functions are for the hypothesis, cost, and gradient descent calculations in order. Foremost, we will explain them one by one.</p><h4>The Hypothesis</h4><p>We aim to find a model we can use to predict new inputs. A <a href="https://machinelearningmastery.com/what-is-a-hypothesis-in-machine-learning/#:~:text=A%20statistical%20hypothesis%20is%20an,for%20mapping%20inputs%20to%20outputs.">hypothesis </a>is a potential model for a machine learning system [9].</p><p>As seen in the figure below, we can find the hypothesis for a dataset by using a learning algorithm [10]. Later we will talk about how well this hypothesis fits our data but for now, let&#39;s just define the hypothesis formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*DG8FEpHACfVTz_NFJanTVQ.png" /><figcaption>The Hypothesis — Image by Author</figcaption></figure><p>For a <strong>univariate linear regression</strong> task, the hypothesis is of the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*pus49RG2MNNcYpaZn8iGPw.png" /><figcaption>The Hypothesis Formula — Image by Author</figcaption></figure><p>The intersection of the y-axis with the hypothesis line is called intercept. This is θ₀ in our formula, and the slope of the hypothesis line is θ₁.</p><p>If we know x, θ₀, and θ₁ values, we can predict the target value for a machine learning system. For example, in the housing prices example above, θ₀ = 0.00008, and θ₁ = 0.16538 for the <strong><em>red line</em></strong>. So for a house of 3000 feet² (x=3000), the expected price is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*ZZF7WrKd_yZpRYHaiYsekg.png" /></figure><p>As can be seen, we need three parameters to write the hypothesis function. These are x (input), θ₀, and θ₁. So, let&#39;s write the Python function for the hypothesis:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c752accc7341b367a1a05bcd7148652/href">https://medium.com/media/3c752accc7341b367a1a05bcd7148652/href</a></iframe><p>The process is pretty straightforward. We just need to return <em>(</em>θ₀<em>+ </em>θ₁<em>* x)</em>.</p><h4>The Cost Function</h4><p>When we have a hypothesis (i.e., we know the values of θ₀ and θ₁), we must decide how well this hypothesis fits our data. Turning back to the housing prices example, Let&#39;s take θ₀ as 500 and θ₁ as -0.1 and draw the line on our data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*WmvMQ6AgdKnJjdr1FoZ4FQ.png" /><figcaption>Housing Prices from Portland, Oregon with Unfitting Hypothesis — Image by Author</figcaption></figure><p>As seen from the image above, A hypothesis with θ₀ = 500 and θ₁ = -0.1 is not a good match for our dataset. We do not want such a hypothesis to be our model since it gives faulty results except for a few points. Let&#39;s draw some more lines to have a better understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*z_D_UXObhKZqn8yQg2yK6A.png" /><figcaption>Housing Prices from Portland, Oregon with different Hypothesis Lines — Image by Author</figcaption></figure><p>We have three hypotheses in the above image with different θ values. By intuition, we can easily pick the blue line (θ₀ = 0, θ₁ = 0.165) as the best match for our data. The question is, how can we select a better fit mathematically? In other words, how can we choose the best θ₀ and θ₁ values that give the optimum solution to our goal of finding a model we can use to predict new inputs?</p><p>To do that, we can choose θ₀ and θ₁ such that h(x) is close to the actual value for all training examples [10]. We make errors for each point on the dataset for a specific hypothesis (with known θ₀ and θ₁ values). If we somehow add all of those errors we made for each data point on that dataset, we can choose the best fitting line by selecting the minimum sum (which means we make fewer errors).</p><p>So we define a cost function to measure the total error we make. There are several solutions we can choose. One is called the squared error function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*mpnORyzfBRd_tbWqgUMf3g.png" /><figcaption>The Cost Function— Image by Author</figcaption></figure><p>j(θ₀, θ₁) is called the cost function. It is a function of θ₀ and θ₁, which are the intercept and slope of the hypothesis. h(xᵢ) — y(xᵢ) is the error we made for the ith training example. And by squaring it, we get two significant benefits; first, we punish big mistakes, and second, we get rid of the negative sign if h(x) &lt; y. By dividing the total sum of errors by the number of samples, we find the average error we made. As described above, smaller cost function values suggest a better match, so we are trying to minimize the cost function for a better fit.</p><p>To write the cost function, we must import <a href="https://numpy.org/"><strong><em>NumPy</em></strong></a>, a famous machine-learning library used for linear algebra tasks. NumPy will speed up our calculations. We also need four parameters, and these are θ₀, θ₁, X (input), and y (actual output).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35573f7a65979d23a099699df08bd009/href">https://medium.com/media/35573f7a65979d23a099699df08bd009/href</a></iframe><p>Inside the function, the first thing to do is to calculate the errors for each data point using NumPy&#39;s subtract function. Then we can calculate the square errors for each data point using NumPy&#39;s square function. Finally, we can calculate the total square error using sum() and divide by the number of examples to get the average error. Note that all the training data is passed to the function as a NumPy array. In addition, since we are using the hypothesis function inside the cost function, we must write it prior. Remember also that we are not trying to minimize the cost function yet. We will see how to do it later in the Gradient Descent topic.</p><h4>Gradient Descent</h4><p>Now we can calculate the cost function for a given set of θ₀ and θ₁ on a dataset. We also know that the θ₀ and θ₁ values that make the cost function minimum are the best matches for our data. The next question is how to find those θ₀ and θ₁ values that make the cost function minimum.</p><p>The gradient descent algorithm can be utilized for this purpose, and we can use the climber analogy to explain gradient descent better. Suppose there is a climber at the top of a mountain. He wants to descend to the hillside as soon as possible. So, he observes his surroundings and finds the steepest path to the ground, moving one tiny step in that direction. Then he observes his surroundings again to see the new, most vertical direction to move. He keeps going repeating this procedure till he reaches the hillside.</p><p>The explanation is beyond this blog post, but we know that the squared error cost function has one global minimum with no local minimums. Furthermore, its negative gradient at a point is the steepest direction to this global minimum. So like a climber on the top of a mountain finds his way to the hillside, we can use gradient descent to find the θ values that minimize our cost function.</p><p>To do that, first, we need to select some initial θ₀ and θ₁ to start with. Then, we can calculate the gradient descent at this point and change θ₀ and θ₁ values proportional to the negative gradient calculated. Then repeat the same steps till convergence.</p><p>To better understand the concept of gradient, we will use a random squared error cost function with θ₀ = 0, as shown below. We select θ₀ as zero; otherwise, we would have struggled with a 3D graph instead of dealing with a 2D one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*g90M7KIfC9-yAkBBZRSmwg.png" /><figcaption>J(θ₁) — Image by Author</figcaption></figure><p>In the image above, suppose we are at point = 6 (that is, we have selected our initial θ₁ as 6) and trying to reach the global minimum. The negative gradient at this point is downward, as shown by the arrow. So if we go one step further in that direction, we will end with a point smaller than 6. Then, as shown below, we can repeat the same procedure till convergence at point = 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*IfYFwCL8WZiNnbx1zRM6pg.png" /><figcaption>Convergence of J(θ₁) at the Local Minimum— Image by Author</figcaption></figure><p>Let&#39;s try another point as below. If we have selected another θ₁ value, such as point = -2, the negative gradient at this point would be downward, as shown by the arrow. So if we go one step further in that direction, we will end with a value larger than -2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*j-ws4wzLZTbgxh_5dPnP8g.png" /><figcaption>J(θ₁) — Image by Author</figcaption></figure><p>Then, as shown below, we can repeat the same procedure till convergence at point = 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*Rpmo0GcaIR9Sh88vgmMR9A.png" /><figcaption>Convergence of J(θ₁) at the Local Minimum — Image by Author</figcaption></figure><p>One good question to ask is how to decide when we have converged. That is, what is our stop condition at the code? We have two choices. We can either check the value of the cost function and stop if it is smaller or equal to a predefined value, or we can check the difference between consecutive cost function values and stop if it is smaller or equal to a threshold value. We will choose the latter since, due to the initial θ values selection, we can never reach the predefined cost value we have selected.</p><p>Taking the gradient descent of a function is a freshman-level Calculus concept, and we will not dive into details; instead, we will only give the outcomes. The gradient of the squared error cost function for a univariate dataset is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*hEm-8gA6xDMxfQ_0vdk_Tw.png" /><figcaption>The Gradient Calculation for the Squared Error Cost Function — Image by Author</figcaption></figure><p>Before writing the code for the gradient descent, we must introduce one final concept: the learning rate. As we have discussed above, the gradient descent algorithm requires tiny steps, and as shown below, we may risk overshooting the local minimum if the steps are too big. So, while calculating the new θ values, we multiply the gradient result with the learning rate coefficient. The learning rate is a hyperparameter that needs to be adjusted during training. While a higher learning rate value may result in overshooting, a smaller learning rate value may result in higher training time [10].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*741YG9SNAy67KUBxnF11GA.png" /><figcaption>Overshooting — Image by Author</figcaption></figure><p>As a result, for a univariate dataset with a hypothesis of the form h(x) = θ₀ <em>+ </em>θ₁<em>* x and a squared error cost function J(</em>θ₀, θ₁<em>), the </em>θ <em>values for each step can be calculated as follows:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*CAk2_EQ3bwRFJ8WBwzWmxw.png" /><figcaption>The Algorithm for Calculating θ Values Using Gradient Descent — Image by Author</figcaption></figure><p>As discussed, α is the learning rate, and m is the number of training examples.</p><p>We must import NumPy as in the cost function to write the gradient descent function.<strong><em> </em></strong>We also need five parameters, and these are θ₀, θ₁, α (learning rate), X (input), and y(actual output). We also must be sure <strong><em>not to update</em></strong> θ₀ before calculating θ₁ [10]. Otherwise, we will end up with a faulty result. The code for the gradient function is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/056fef8e039afb98be49d187a0bb6688/href">https://medium.com/media/056fef8e039afb98be49d187a0bb6688/href</a></iframe><p>Inside the function, the first thing to do is to calculate the errors for each data point using NumPy&#39;s subtract function and store it in a variable. Then we can multiply the previous result with x and store it in another variable. Note that all the training data is passed to the function as a NumPy array. So those variables are of type array, and the sum() function can be used to get the total values which then can be multiplied by the learning rate and divided by the number of examples. As a final step, we can calculate and return the new θ values.</p><h4>Model Training</h4><p>Since we have written all the functions we need, it is time to train the model. As discussed before, we need to decide when the gradient descent converges. To do that, we will subtract consecutive cost values. If the difference is smaller than a certain threshold, we will conclude that the gradient descent converges.</p><p>We also draw the hypothesis for each iteration to see how it changes. But this slows down the code. The selection of initial values may significantly change the number of iterations, so it may be suitable to change this part of the code for those who reproduce it. It is also possible to copy the <a href="https://www.kaggle.com/code/erkanhatipoglu/univariate-linear-regression-from-scratch"><strong><em>Univariate Linear Regression from Scratch</em></strong></a> notebook for this purpose, in which a section draws the model trained only because of high iteration counts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd9d0e42e37b49b18522ffb487115f1f/href">https://medium.com/media/dd9d0e42e37b49b18522ffb487115f1f/href</a></iframe><p>Inside the code block, we initialize the α, θ₀, θ₁, and the convergence threshold values. We also calculate the initial cost value by calling the cost function.</p><p>As previously discussed, our stop condition for the while loop is the difference of consecutive cost function values to be smaller than a threshold value. We first draw the training data and the hypothesis for demonstration purposes for each while loop iteration. We then calculate the cost function value by calling the cost function. Next, we calculate the new θ₀ and θ₁ values by calling the gradient function. Next, we use new θ values to recalculate the cost value to find the difference to check the stop condition. At the end of the loop, we print some necessary information for each iteration.</p><h4>The Result</h4><p>The result below is for the initial conditions in the model training code block. The training took 27 iterations. θ₀ is calculated at approximately 0.015, and θ₁ is around 0.999. The final cost value is calculated as about 3.936. The result is very close to the y = x line discussed in the <a href="https://www.kaggle.com/datasets/andonians/random-linear-regression">Linear Regression Dataset</a>. We can also see the change in the hypothesis for each iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*baApGfOHMUKiNUewlx0dpw.png" /><figcaption>The Validation Result Using Test Dataset- Image by Author</figcaption></figure><h4>Validation</h4><p>We can also validate our result with the test dataset, which hasn&#39;t been used in the training process. Below you can find the performance of our model concerning the test dataset. The cost value of the model is approximately 4.702, slightly worse than 3.936 (training cost value), which is expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*MrdV-2zub-XK39GiAwtdjA.png" /><figcaption>The Validation Result Using Test Dataset- Image by Author</figcaption></figure><h3>Conclusion</h3><p>In this blog post, we learned the basics of linear regression, such as the hypothesis, the cost function, and the gradient descent using univariate data. We also wrote those functions in Python. In addition, using them, we have trained a univariate linear model and tested it utilizing the <a href="https://www.kaggle.com/datasets/andonians/random-linear-regression">Linear Regression</a> dataset.</p><p>Interested readers can find the code used in this blog post in the Kaggle notebook <a href="https://www.kaggle.com/code/erkanhatipoglu/univariate-linear-regression-from-scratch"><strong><em>Univariate Linear Regression from Scratch</em></strong></a>.</p><p>Thank you for reading!</p><h3>References</h3><p>[1] V. Andonians, &quot;Linear Regression,&quot; <em>Kaggle.com</em>, 2017. [Online]. Available: <a href="https://www.kaggle.com/datasets/andonians/random-linear-regression.">https://www.kaggle.com/datasets/andonians/random-linear-regression.</a> [Accessed: 12- Sep- 2022].</p><p>[2] &quot;Supervised learning — Wikipedia,&quot; <em>En.wikipedia.org</em>, 2022. [Online]. Available: <a href="https://en.wikipedia.org/wiki/Supervised_learning.">https://en.wikipedia.org/wiki/Supervised_learning.</a> [Accessed: 13- Sep- 2022].</p><p>[3] &quot;Unsupervised learning — Wikipedia,&quot; <em>En.wikipedia.org</em>, 2022. [Online]. Available: <a href="https://en.wikipedia.org/wiki/Unsupervised_learning.">https://en.wikipedia.org/wiki/Unsupervised_learning.</a> [Accessed: 13- Sep- 2022].</p><p>[4]” Reinforcement learning — Wikipedia,&quot; <em>En.wikipedia.org</em>, 2022. [Online]. Available: <a href="https://en.wikipedia.org/wiki/Reinforcement_learning.">https://en.wikipedia.org/wiki/Reinforcement_learning.</a> [Accessed: 13- Sep- 2022].</p><p>[5] J. Carew, &quot;What is Reinforcement Learning? A Comprehensive Overview&quot;, <em>SearchEnterpriseAI</em>, 2021. [Online]. Available: <a href="https://www.techtarget.com/searchenterpriseai/definition/reinforcement-learning.">https://www.techtarget.com/searchenterpriseai/definition/reinforcement-learning.</a> [Accessed: 12- Sep- 2022].</p><p>[6] J. Brownlee, &quot;Linear Regression for Machine Learning,&quot; <a href="https://machinelearningmastery.com/,"><em>https://machinelearningmastery.com/</em>,</a> 2022. [Online]. Available: <a href="https://machinelearningmastery.com/linear-regression-for-machine-learning/">https://machinelearningmastery.com/linear-regression-for-machine-learning/.</a> [Accessed: 11- Sep- 2022].</p><p>[7] JohnX, &quot;Housing Prices, Portland, OR,&quot; <em>Kaggle.com</em>, 2017. [Online]. Available: <a href="https://www.kaggle.com/datasets/kennethjohn/housingprice.">https://www.kaggle.com/datasets/kennethjohn/housingprice.</a> [Accessed: 11- Sep- 2022].</p><p>[8] E. Hatipoglu, &quot;Univariate Linear Regression From Scratch,&quot; <em>Kaggle.com</em>, 2022. [Online]. Available: <a href="https://www.kaggle.com/code/erkanhatipoglu/univariate-linear-regression-from-scratch.">https://www.kaggle.com/code/erkanhatipoglu/univariate-linear-regression-from-scratch.</a> [Accessed: 12- Sep- 2022].</p><p>[9] J. Brownlee, &quot;What is a Hypothesis in Machine Learning?&quot;, <a href="https://machinelearningmastery.com/"><em>machinelearningmastery.com</em></a>, 2019. [Online]. Available: <a href="https://machinelearningmastery.com/what-is-a-hypothesis-in-machine-learning/">https://machinelearningmastery.com/what-is-a-hypothesis-in-machine-learning/.</a> [Accessed: 12- Sep- 2022].</p><p>[10] A. Ng, &quot;Stanford CS229: Machine Learning — Linear Regression and Gradient Descent | Lecture 2 (Autumn 2018)&quot;, <em>Youtube.com</em>, 2018. [Online]. Available: <a href="https://www.youtube.com/watch?v=4b4MUYve_U8&amp;list=PLoROMvodv4rMiGQp3WXShtMGgzqpfVfbU&amp;index=2.">https://www.youtube.com/watch?v=4b4MUYve_U8&amp;list=PLoROMvodv4rMiGQp3WXShtMGgzqpfVfbU&amp;index=2.</a> [Accessed: 12- Sep- 2022].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68065fe8eb09" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/univariate-linear-regression-from-scratch-68065fe8eb09">Univariate Linear Regression From Scratch</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Udacity AI Product Manager Program Review (Part III)]]></title>
            <link>https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-iii-6da01dc2bb8c?source=rss-c287c56e4845------2</link>
            <guid isPermaLink="false">https://medium.com/p/6da01dc2bb8c</guid>
            <category><![CDATA[udacity]]></category>
            <category><![CDATA[ai-product-management]]></category>
            <category><![CDATA[ai-business]]></category>
            <category><![CDATA[business-proposal]]></category>
            <category><![CDATA[udacity-nanodegree]]></category>
            <dc:creator><![CDATA[Erkan Hatipoğlu]]></dc:creator>
            <pubDate>Thu, 23 Dec 2021 09:02:55 GMT</pubDate>
            <atom:updated>2021-12-23T09:02:55.222Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Project Centric Review Approach</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T0tF8xceKQuftuPv" /><figcaption>Photo by <a href="https://unsplash.com/@cdc?utm_source=medium&amp;utm_medium=referral">CDC</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Overview</h4><p>This article is the final episode of a <strong>three parts series</strong> on the review of the <a href="https://www.udacity.com/course/ai-product-manager-nanodegree--nd088">AI Product Manager Program offered by Udacity.</a> Readers interested in part 1 and part 2 can follow the links below.</p><ul><li><a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-1-a85f24ff082b">Udacity AI Product Manager Program Review (Part I)</a></li><li><a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-ii-b9fb55d0314e">Udacity AI Product Manager Program Review (Part II)</a></li></ul><p>As stated in the <a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-1-a85f24ff082b">first part</a> of this series, I have reviewed the project assignments and published each in a <strong>different episode</strong>. Hence, the readers can read about the first project in <a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-1-a85f24ff082b">part I</a>, the second in <a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-ii-b9fb55d0314e">part II</a>, and the final in part III.</p><p>Udacity let students develop a business proposal for an AI product of their choosing as the capstone project.</p><p>I have selected a project about COVID-19 pneumonia detection since I have already done some projects about pneumonia detection in the previous assignments and can use the gained experience in the final project.</p><p>So let&#39;s start the final project.</p><h3>Project 3— Create an AI Product Business Proposal</h3><p>Our business proposal will include some essential elements of product development. These are:</p><ul><li><em>Business Goal,</em></li><li><em>Success Metrics,</em></li><li><em>Data,</em></li><li><em>Model,</em></li><li><em>Minimum Viable Product (MVP),</em></li><li><em>Post-MVP-Deployment.</em></li></ul><p>We will go one by one with each item and complete the proposal together.</p><h4>Business Goal</h4><blockquote>We will start with the business goal. We need to define the industry problem we are trying to solve and justify using ML/AI to solve this task.</blockquote><p>As the final project, we will propose an AI product differentiating healthy, Pneumonia, and COVID-19 pneumonia chest x-ray images.</p><p>It is known that the <a href="https://en.wikipedia.org/wiki/False_positives_and_false_negatives">False Negative (FN)</a> Ratio for COVID-19 rapid and PCR tests is very high. On the other hand, the <a href="https://en.wikipedia.org/wiki/False_positives_and_false_negatives">False Positive (FP)</a> Ratio for them is too small. As a result, doctors rely on other tools such as known symptoms or chest x-ray images to detect COVID-19. Yet, doctors don&#39;t have the means to determine a pneumonia image indicates ordinary Pneumonia or COVID-19 Pneumonia.</p><p>Patients with pneumonia indications in their chest x-ray images with negative test results may be treated assuming they have COVID-19. Or treatment may be delayed until another test is conducted. However, this method is risky. Ordinary pneumonia patients may be treated with stiff medication, or COVID-19 patients may waste valuable time without treatment.</p><p>So the product will use AI to:</p><ul><li>Differentiate COVID-19 Pneumonia from Normal Pneumonia,</li><li>Speed up diagnostics and treatment,</li><li>Conduct the proper treatment at the right time,</li><li>Act as a diagnostic aid for doctors</li><li>Increase patient&#39;s happiness,</li><li>Improve doctor&#39;s credibility.</li></ul><blockquote>The next thing to do is provide a rationale for creating this product by considering drivers of business success, such as its impact on revenue, market share, and customer happiness.</blockquote><p>COVID-19 treatment is highly stiff and has harsh side effects. Differentiating usual Pneumonia from COVID-19 Pneumonia may change medication used and, non-COVID-19 pneumonia patients may get a lighter treatment avoiding unnecessary side effects.</p><p>In addition, wasted time that results from multiple tests caused by negative results will be saved. This wasted time may induce irreversible damages to the patients.</p><p>As a result, the product will speed up the COVID-19 diagnostics and improve patient happiness, and it will also help the credibility of doctors.</p><blockquote>Finally, we need to explain the ML/AI task we will use and the business outcome we will achieve.</blockquote><p>Our ML model will be a multi-class classifier distinguishing No Pneumonia, Normal Pneumonia, and COVID-19 Pneumonia from chest x-ray images.</p><p>User satisfaction and the decision process will be monitored as the outcome.</p><h4>Success Metrics</h4><blockquote>This section will select the metrics to determine our product&#39;s success and specify how we will establish a baseline.</blockquote><p>Since we will monitor user happiness and the decision process as the outcome, we need to apply related success metrics. We will utilize the following metrics:</p><p>• Customer satisfaction</p><p>Customer surveys will be accomplished before and after using the product, and customer surveys made before will be the baseline.</p><p>• Decision Process</p><p>The number of standard pneumonia cases diagnosed by the product will be a success metric. This quantity is essential because it directly indicates the product&#39;s success, and a small amount suggests an inapplicable end product. Average pneumonia cases gathered from the clients before the pandemic will be used as a baseline.</p><p>The difference of diagnosis times calculated with and without using the product will be another success metric. The data will be collected from the customer, and the baseline will be zero.</p><h4>Data</h4><blockquote>We must plan how and where we will acquire the data at what cost. We must also consider possible <a href="https://www.csoonline.com/article/3215864/how-to-protect-personally-identifiable-information-pii-under-gdpr.html">personally identifiable information (PII)</a> or <a href="https://www.upguard.com/blog/sensitive-data">data sensitivity</a> issues.</blockquote><p>For the initial product, data will be gathered from the open-source resources, including the dataset we have used in the <a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-1-a85f24ff082b">first </a>and <a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-1-a85f24ff082b">second </a>projects of this Nanodegree. Below you can find the links to some open-source datasets:</p><ul><li><a href="https://github.com/ieee8023/covid-chestxray-dataset">Cohen, J. P., Morrison, P. &amp; Dao, L. COVID-19 image data collection (2020)</a></li><li><a href="https://www.kaggle.com/c/rsna-pneumonia-detection-challenge">RSNA Pneumonia Detection Challenge — Kaggle</a></li><li><a href="https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia">Chest X-Ray Images (Pneumonia) — Kaggle</a></li><li><a href="https://www.eibir.org/covid-19-imaging-datasets/">COVID-19 imaging datasets</a></li></ul><p>There is no financial cost for gathering this open-source data; however, cleaning, preparing, and combining all the data into one balanced dataset will need labor.</p><p>Since the datasets for the initial product are open source, no PII or data sensitivity issues are expected.</p><p>It is possible that with every mutation of the virus, the images may change form. So, feeding our model with the new data collected from the customers is crucial. This data will be gathered in small batches, and the model will be retrained. While managing those batches, we need to consider the balance of the dataset, and the number of samples for each class must be approximately equal.</p><p>Since we will be using the health data coming from the patients through the clients, we may face PII issues. We need to get the necessary permissions.</p><p>There will be no financial cost for gathering data from the customers since they will be informed that this data will be used for updating the product. As before, we will need labor for cleaning, preparing, and combining all the data into one balanced dataset.</p><blockquote>We must estimate any bias in our data considering its size and source and present possible improvements.</blockquote><p>We have several sources of data. The total size of the data is given below:</p><ul><li><em>Covid-19 Pneumonia:</em> <strong>3595</strong></li><li><em>Normal Pneumonia:</em> <strong>13430</strong></li><li><em>No Pneumonia:</em> <strong>22013</strong></li></ul><p>The combined dataset seems to be unbalanced, introducing bias. So, we need to apply techniques to work with this imbalanced data.</p><p>Another bias may be introduced because of <a href="https://ieeexplore.ieee.org/document/9374968">multisource variability</a>. Depending on the data collected from the customers in later stages may decrease this bias.</p><p>There may also be <a href="https://www.pnas.org/content/117/23/12592">gender bias</a> which may be reduced by diversity.</p><p>There may also be annotation bias from humans annotating and generating those datasets above. We may reannotate some portion of data if needed to solve annotation bias.</p><blockquote>Next, we need to define and explain the labels we will use.</blockquote><p>Since our goal is to differentiate COVID-19 Pneumonia from usual Pneumonia and there may be healthy cases, we will have three labels as described below.</p><p>The labels will be <strong><em>&#39;COVID-19 Pneumonia&#39;</em></strong>, <strong><em>&#39;Normal Pneumonia,&#39;</em></strong> and <strong><em>&#39;No Pneumonia,&#39;</em></strong> indicating the patient has COVID-19, has Pneumonia but not COVID 19, and has neither Pneumonia nor COVID-19, respectively.</p><p>Regular Pneumonia can also be classified as viral and bacterial Pneumonia, as shown in <a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-ii-b9fb55d0314e">project 2</a>. Similarly, bacterial and viral Pneumonia can also be classified into subclasses (In fact, COVID-19 Pneumonia is viral Pneumonia itself). However, we do not need that complexity for our goal, and a standard pneumonia label is enough for us.</p><h4>Model</h4><blockquote>We must explain how the model will be created. By an in-house team or by outsourcing?</blockquote><p>We will build the model using an in-house team since we have already an ML team capable of doing the project. We have also got enough time budget.</p><p>The training and storage of the model will be accomplished using the cloud, probably on <a href="https://azure.microsoft.com/">MS Azure</a>, since our team has experience using Azure ML. Using the cloud will lower compute costs and fulfill storage requirements.</p><p>The deployment will also be on <a href="https://azure.microsoft.com/">MS Azure</a>. We will also use Application Insights. Application Insights is a particular Azure service that provides key facts about an application, and it is a handy tool to detect anomalies and visualize performance.</p><p>The product will consume the deployed service via an HTTP API.</p><blockquote>We must explain the model performance metrics we will use to measure the model&#39;s success and specify a level of performance.</blockquote><p>The output will be monitored using recall since we want to decrease <a href="https://developers.google.com/machine-learning/crash-course/classification/true-false-positive-negative#:~:text=A%20true%20positive%20is%20an,incorrectly%20predicts%20the%20positive%20class.">FP</a> and increase <a href="https://developers.google.com/machine-learning/crash-course/classification/true-false-positive-negative#:~:text=A%20true%20positive%20is%20an,incorrectly%20predicts%20the%20positive%20class.">TP</a>.</p><p>It is known that the <a href="https://www.healthline.com/health/how-accurate-are-rapid-covid-tests#how-accurate-is-it">False Positive ratio for COVID-19 rapid tests</a> is between 45.1% and 55.4 %. If we target at least a recall of 54.9 %, we will beat COVID-19 rapid tests.</p><p>On the other hand, we know that <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7436068/">we can have a sensitivity</a> of 88.62% by using ML. But considering that we may not want the best deployment model, selecting a slightly less value for recall like 85% will be more reasonable and attainable.</p><h4>Minimum Viable Product (MVP)</h4><blockquote>We need to include some product sketches if possible and explain the use-cases.</blockquote><p>Below you can find a draft sketch of the product. Remember, you don&#39;t need to add a professional drawing for submission to Udacity. However, I believe that, in real life, these sketches should be designed more professionally than my sketch below. However, most Udacity students are not graphic designers, and as a result, Udacity doesn&#39;t expect professional drawings for submissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*HqQ_2Hel5sgily4GWSZK5g.png" /></figure><p>This product will primarily be developed for doctors and/or x-ray technicians in hospitals. However, since it will be a WEB-based product, patients can also use it.</p><p>After the chest x-ray image of a patient is taken, the x-ray technician can use the product and post the result to the relevant doctor. Doctors can also use the product directly. The procedure may be determined according to the rules and internal structure of the related clinic.</p><p>On the other hand, patients may also use the application if they have an x-ray image at hand. However, they can predict only once per day, while our regular clients(clinics) can have an infinite number of predictions per day.</p><blockquote>We must also include a <a href="https://blog.hubspot.com/sales/gtm-strategy">go-to-market plan</a> in the proposal.</blockquote><p>Before launch, we need to formulate a go-to-market plan. And after the launch, we need to accomplish this plan.</p><p>We need to fulfill the four components of the <a href="https://medium.com/neemz-growth/go-to-market-g-2-m-plan-9dd9bd08b9ec">go-to-market plan</a>. These are:</p><p><strong>• The Product strategy</strong></p><p><em>We need to distinguish our product from competitors:</em> Our product speeds up the COVID-19 diagnostics process and helps doctors make better treatments. There is no diagnostics process using AI now.</p><p><strong>• The Pricing and Promotion (P&amp;P) strategy</strong></p><p><em>Promotion at launch:</em> Since our business goal for this product is not generating revenue but customer satisfaction, the users will be able to use it free as a WEB application.</p><p><strong>• The Channel strategy</strong></p><p><em>How to sell, educate and support customers:</em> We will distribute the product to our current customers (clinics). Our customers will be able to get a membership using the WEB interface. Education and support will mainly be carried out from WEB.</p><p><strong>• The Marketing Communications (Mar-Comms) strategy</strong></p><p><em>We need to generate awareness with customers and employees:</em><strong><em> </em></strong>We may find a value proposition and positioning statement for this purpose.</p><h4>Post-MVP-Deployment</h4><blockquote>At the final stage of the proposal, we need to plan after deployment. We must think about improvements on the product, diversities between the real-world data and the training data, adaptation to new data, and using A/B testing.</blockquote><p>We anticipate that (because of the mutations) the image data will alter over time, and our model quality will decrease. To overcome this issue, we need to refresh our model from time to time when its performance drops below a certain level. Active learning and A/B testing concepts can help us solve this issue and improve our model.</p><p>We can use active learning to continuously learn and improve our product. To do that, we can use a human-in-the-loop system in which humans annotate (preferably some tiny portion of) the new data gathered from the customers.</p><p>We can also use A/B testing for the new models. We can make a challenger model (with the latest data from our customers) and send that model to 20% of our customers. Since we are making a WEB App, we can select customers on a regional or country basis to reach a 20–80 ratio.</p><blockquote>Finally, we must determine how to monitor or mitigate unwanted bias in our model?</blockquote><p>For the initial model, we will get the data from external datasets. But after the deployment, while gathering new data from clients, we need to agree with them what a chest-Xray image is to prevent additional data from being a source of bias.</p><p>In addition, we need to work with all our customers and learn their procedure of using our product to ensure there is no other source of bias in the new data.</p><p>While training new models with the latest data, we also must be sure that it is diverse enough. We need to use all our customers&#39; (clinics) data appropriately.</p><p>What&#39;s more, our team and annotators should also be diverse enough. We need to work closely with the human resources department to achieve this.</p><h4>Conclusion</h4><p>In the last project of the Nanodegree, we have created a business proposal for an AI product of our choice. To complete the assignment, we have concentrated on some crucial aspects of AI product development: <em>business goal, success metrics, data, model, MVP, and post-MVP-deployment.</em></p><p>Since this is the final episode of project reviews for the <a href="https://www.udacity.com/course/ai-product-manager-nanodegree--nd088">AI Product Manager Program — Udacity</a>, I want to talk about the program itself. This program is not challenging, and any dedicated student with a proper English level can quickly finish the program in less than two months. The program especially suits product managers who don&#39;t have much AI experience and students who want a complete understanding of the AI product lifecycle.</p><p>Refer to <a href="https://github.com/ErkanHatipoglu/AI-Product-Manager-Nanodegree-Program">my GitHub repository</a> or my other episodes below for the Udacity AI Product Manager Program if you liked this subject or are interested in it.</p><ul><li><a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-1-a85f24ff082b">Udacity AI Product Manager Program Review (Part I)</a></li><li><a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-ii-b9fb55d0314e">Udacity AI Product Manager Program Review (Part II)</a></li></ul><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6da01dc2bb8c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-iii-6da01dc2bb8c">Udacity AI Product Manager Program Review (Part III)</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[Udacity AI Product Manager Program Review (Part II)]]></title>
            <link>https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-ii-b9fb55d0314e?source=rss-c287c56e4845------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9fb55d0314e</guid>
            <category><![CDATA[udacity]]></category>
            <category><![CDATA[ai-product-management]]></category>
            <category><![CDATA[confusion-matrix]]></category>
            <category><![CDATA[udacity-nanodegree]]></category>
            <category><![CDATA[metrics]]></category>
            <dc:creator><![CDATA[Erkan Hatipoğlu]]></dc:creator>
            <pubDate>Thu, 25 Nov 2021 14:32:29 GMT</pubDate>
            <atom:updated>2022-09-20T20:18:36.125Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Project Centric Review Approach</h4><figure><img alt="A desk in front of a window with potted plants next to it. There is a laptop, pen, notebook, computer screen, mouse, and keyboard on the desk." src="https://cdn-images-1.medium.com/max/1024/0*IeYagGlw-by02AnW" /><figcaption>Photo by <a href="https://unsplash.com/@grovemade?utm_source=medium&amp;utm_medium=referral">Grovemade</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Overview</h4><p>This article is the second episode of a <strong>three parts series</strong> on the review of the <a href="https://www.udacity.com/course/ai-product-manager-nanodegree--nd088">AI Product Manager Program offered by Udacity.</a> Readers interested in part 1 can follow the link below.</p><p><a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-1-a85f24ff082b">Udacity AI Product Manager Program Review (Part I)</a></p><p>As stated in the <a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-1-a85f24ff082b">first part</a> of this series, I will review through project assignments and publish each project in a <strong>different episode</strong>. Hence, the readers can read about the first project in <a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-1-a85f24ff082b">part I</a>, the second in part II, and the final in <a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-iii-6da01dc2bb8c">part III</a>.</p><p>For each project, I will try to answer the following questions:</p><ul><li><em>What is the project?</em></li><li><em>What is the outcome of the project?</em></li><li><em>What are the sources and tools to complete the project?</em></li><li><em>What is the solution?</em></li><li><em>What are the problems faced during the project implementation?</em></li><li><em>How can those problems be solved?</em></li><li><em>How can the project be improved?</em></li><li><em>What are the references for the project?</em></li></ul><p>So let&#39;s start the second project.</p><h4>Project 2 — Build a Model with Google AutoML</h4><p>This project is a sequel to <a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-1-a85f24ff082b">project 1</a>, in which we have created directives for a labeling job that differentiates the healthy and pneumonia chest x-ray images.</p><p>In a typical <a href="https://cloud.google.com/ai-platform/images/ml-workflow.svg">machine learning (ML) workflow</a>, the subsequent step after data gathering and preparation is the model-building step. Although this Nanodegree proposes a slightly different ml workflow that starts with the <strong><em>Business Goal</em></strong> and ends with <strong><em>Active Learning and Tuning</em></strong>, it is no different at this stage. We need to train and evaluate our model.</p><p><strong>The Target</strong></p><p>So, in this second project of the Nanodegree, we will build four different classification models that differentiate the healthy and pneumonia chest x-ray images. There will be no coding in this assignment. Instead, we will use <a href="https://cloud.google.com/automl/">Google AutoML</a>. AutoML stands for <a href="https://en.wikipedia.org/wiki/Automated_machine_learning">Automated Machine learning</a>. It is a tool to automate the ML workflow and find the best-performing model we can deploy from a given set of model algorithms for a given dataset. By using <a href="https://cloud.google.com/automl/">Google AutoML</a>, we can build and deploy our models in the cloud.</p><p>Our project aims to build four models using <a href="https://console.cloud.google.com/vision">Google&#39;s AutoML Vision platform</a> and understand how data characteristics affect model performance. We will not deploy our model, but we will submit an AutoML Modeling Report for review in the end.</p><p>We will use the <a href="https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia">Kaggle chest x-ray dataset</a> as in the previous project. We will select four <strong>different subsets</strong> of the dataset and build four <strong>ML models</strong> using each of those subsets. We will not label them using <a href="https://client.appen.com/sessions/new">Appen&#39;s platform</a> as in the <a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-1-a85f24ff082b">previous project</a> but use the original labels given in the dataset.</p><p><strong>Google AutoML</strong></p><p>To use <a href="https://console.cloud.google.com/vision">Google&#39;s AutoML Vision platform</a>, we will go to <a href="https://cloud.google.com/automl/">Google AutoML</a>, click the <strong><em>TRY AUTOML </em></strong>button, and select <strong><em>AutoML Vision</em></strong>. After signing in/up to the account, we can create our project with any title. Please note that Google may charge you for this project according to your account status. But if you sign up, you&#39;ll be given a free $300 <a href="https://cloud.google.com/free/docs/gcp-free-tier#how-to-upgrade">credit</a>.</p><p><strong>The Data</strong></p><p>We will use four subsets of the <a href="https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia">Kaggle chest x-ray dataset</a>, and I suggest preparing those subsets <strong>before modeling</strong> to ensure similar dataset usage for our models.</p><p><strong>Create a binary classifier to detect pneumonia using chest x-rays</strong></p><p>The first subset will contain 200 chest x-ray images, 100 from the &#39;<strong><em>normal</em></strong>&#39; class and 100 from the &#39;<strong><em>pneumonia</em></strong>&#39;<strong><em> </em></strong>class.</p><p>I will not go into the details of the training process except for one thing. If required, we can easily find help from Google and the Udacity project page. Instead, I would focus on the results and the modeling report we will submit for review.</p><p>I want to discuss the train/test split concept in the training process, which is very important in ML.</p><p>We can break up the model creation process in ML into three consecutive steps, which are the training, the hyperparameter tuning, and the evaluation steps. We need data in each stage to proceed to the next step. However, the data used in each phase should differ, and we must isolate these datasets from each other at the beginning. Otherwise, we will end up with a poor-performing model, which we do not want. So before creating a model, the first thing to do is split the dataset into three parts. These are the training set used in training, the validation set used in the hyper-parameter tuning, and the test set used in the evaluation.</p><p>So before the training, we will divide the dataset into 80%, 10%, and 10% portions, as in the image below. <strong>More data</strong> for training always means <strong>better model performance</strong>. So we will allocate as much data as possible for training (80%).</p><figure><img alt="Screenshot of Google’s AutoML Vision platform showing class distribution for Normal and Pneumonia classes. 80% of the data is for training, 10% is for testing, and 10% is for validation." src="https://cdn-images-1.medium.com/max/1024/1*mQ6gAme_mBN_y3bUFfDgVg.png" /><figcaption>Train/Test Split for Dataset-1 — Image by Author</figcaption></figure><p>After we finish the training, we can evaluate our model by looking at the <strong><em>confusion matrix</em></strong>.</p><p>A confusion matrix is a grid that shows all the predicted &#39;labels&#39; relative to all actual &#39;labels.&#39; In our case, we have four cells in the confusion matrix below.</p><figure><img alt="Confusion matrix with cell_11 = 10, cell_12 = 0, cell_21 = 2, and cell_22  = 8." src="https://cdn-images-1.medium.com/max/1024/1*kBJrOGjkmULPatk-VwLupg.png" /><figcaption>Confusion Matrix for Dataset-1 — Image by Author</figcaption></figure><p>The explanation of each cell in a confusion matrix is as below.</p><ul><li><strong><em>True Positives</em></strong> (Row 1 Column 1, <strong>TP</strong> in short): TP is the number of positive labels predicted as positives by the best-performing model.</li><li><strong><em>False Negatives</em></strong> (Row 1 Column 2, <strong>FN</strong> in short): FN is the number of positive labels predicted as negatives by the best-performing model.</li><li><strong><em>False Positives</em></strong> (Row 2 Column 1, <strong>FP</strong> in short): FP is the number of negative labels predicted as positives by the best-performing model.</li><li><strong><em>True Negatives</em></strong> (Row 2 Column 2, <strong>TN</strong> in short): TN is the number of negative labels predicted as negatives by the best-performing model.</li></ul><p>As stated earlier, our test set has 10 &#39;<strong><em>normal</em></strong>&#39;<strong><em> </em></strong>and 10 &#39;<strong><em>pneumonia</em></strong>&#39;<strong><em> </em></strong>images. The <strong><em>confusion matrix</em></strong> tells us that our model has predicted the 10 out of 10 &#39;<strong><em>normal</em></strong>&#39;<strong><em> </em></strong>class images as &#39;<strong><em>normal</em></strong>&#39; and 8 out of 10 &#39;<strong><em>pneumonia</em></strong>&#39;<strong><em> </em></strong>class images as &#39;<strong><em>pneumonia.&#39;</em></strong></p><p>In machine learning, we use various metrics to evaluate our model. One of the most popular metrics is model accuracy.</p><p><strong><em>Model accuracy</em></strong> measures the percentage of accurate predictions against the total number of predictions for all classes. In mathematical terms:</p><figure><img alt="The formula of accuracy is (TP+TN) divided by total accuracy, which is (TP+TN) divided by (TP + FP + TN + FN)." src="https://cdn-images-1.medium.com/max/337/1*yrsl4WZhHpnQ6STMRmt9tQ.png" /></figure><p>However, relying on accuracy may be misleading, especially for unbalanced datasets. In this project, we will not use &#39;<strong><em>accuracy</em></strong>.&#39; Still, we will calculate it twice to see how it misleads us. The accuracy for the first model is as follows.</p><figure><img alt="The accuracy is 10 plus 8 divided 10 plus 2 plus 8 plus 0, which is equal to 0.9 ." src="https://cdn-images-1.medium.com/max/393/1*P-Bx2Zn_n-mGdkuQ08dlaQ.png" /></figure><p>To evaluate our model, we will use two metrics calculated from the confusion matrix: precision<strong><em> </em></strong>and <strong><em>recall</em></strong>.</p><p>These metrics measure the model to understand how it performs for an individual class and across categories.</p><p><strong><em>Model precision</em></strong> measures the percentage of correctly identified class instances against that class&#39;s total number of predictions. In mathematical terms:</p><figure><img alt="The formula of precision is TP divided by (TP + FP)." src="https://cdn-images-1.medium.com/max/236/1*beA-CaL5A09QLZoYnbHRUQ.png" /></figure><p><strong><em>Model recall</em></strong> measures the percentage of correctly identified instances of a class against the total possible samples of that class. In mathematical terms:</p><figure><img alt="The formula of recall is TP divided by (TP + FN)." src="https://cdn-images-1.medium.com/max/252/1*OaZSLqZxsZImQvBLy87bKg.png" /></figure><p>So for model-1, which is trained with dataset-1, the <strong><em>precision and recall</em></strong> of the &#39;normal&#39; class are as follows.</p><figure><img alt="Precision is 10 divided by (10 + 2), which is approximately 0.83 and recall is 10 divided (10 + 0) which is 1." src="https://cdn-images-1.medium.com/max/354/1*SO4R_W267qtEFRMhl8nuQg.png" /></figure><p><strong>Create an unbalanced binary classifier</strong></p><p>The second subset will contain 400 chest x-ray images, 100 from the &#39;<strong><em>normal</em></strong>&#39;<strong><em> </em></strong>class and 300 from the &#39;<strong><em>pneumonia</em></strong>&#39;<strong><em> </em></strong>class.</p><p>We will start by splitting our dataset into 80%, 10%, and 10% portions.</p><figure><img alt="Screenshot of Google’s AutoML Vision platform showing class distribution for Normal and Pneumonia classes. 80% of the data is for training, 10% is for testing, and 10% is for validation." src="https://cdn-images-1.medium.com/max/1024/1*Yzq0Z6yMZoyTCE-7xl6Ezg.png" /><figcaption>Train/Test Split for Dataset-2 — Image by Author</figcaption></figure><p>After the training, we will evaluate our model using the confusion matrix.</p><figure><img alt="Confusion matrix with cell_11 = 6, cell_12 = 4, cell_21 = 0, and cell_22 = 30." src="https://cdn-images-1.medium.com/max/1024/1*f9DLNIJAkX_H8wn_FxvGdw.png" /><figcaption>Confusion Matrix for Dataset-2 — Image by Author</figcaption></figure><p>Our test set has 10 &#39;<strong><em>normal</em></strong>&#39;<strong><em> </em></strong>and 30 &#39;<strong><em>pneumonia</em></strong>&#39;<strong><em> </em></strong>images. The <strong><em>confusion matrix</em></strong> tells us that our model has predicted 6 out of 10 &#39;<strong><em>normal</em></strong>&#39;<strong><em> </em></strong>class images as &#39;<strong><em>normal</em></strong>&#39;<em> and </em>30 out of 30 &#39;<strong><em>pneumonia</em></strong>&#39;<strong><em> </em></strong>class images as &#39;<strong><em>pneumonia.</em></strong>&#39;</p><p>Let&#39;s calculate precision and recall for the &#39;normal&#39; class.</p><figure><img alt="Precision is 6 divided by (6 + 0), which is 1 and recall is 6 divided (6 + 4) which is 0.6." src="https://cdn-images-1.medium.com/max/272/1*tgHB1ZjrIRYtC2Jcexvj5g.png" /></figure><p>For the &#39;<strong><em>normal</em></strong>&#39; class, <strong><em>precision </em></strong>increases from 0,83 to 1, and <strong><em>recall</em> </strong>decreases from 1 to 0,6.</p><p>Model-2 predicts mainly the unbalanced class. In other words, model-2 tends to generalize the inputs to the majority class (Pneumonia). As a result, <strong><em>recall</em></strong> decreases for the minority class.</p><p>If we calculate the accuracy for this model, we can see why accuracy is not a good choice for unbalanced datasets. The accuracy calculation is as follows.</p><figure><img alt="The accuracy is 6 plus 30 divided by 6 plus 0 plus 30 plus 4, which equals 0.9." src="https://cdn-images-1.medium.com/max/372/1*9qaE7ySceaEI0xvcb5_X1g.png" /></figure><p>As we can see easily, although the accuracy for this model is the same as the clean/balanced case, this model performs much worse than it. Therefore, as I have said earlier, using accuracy for unbalanced datasets will mislead us.</p><p><strong>Create a binary classifier with dirty data</strong></p><p>For the third dataset, we will begin with the original dataset of 100 &#39;normal&#39; and 100 &#39;pneumonia&#39; images used in the first dataset. Then we will reverse 30 labels in each class and misclassify 30% of the data.</p><p>Again we will start by splitting our dataset into 80%, 10%, and 10% portions.</p><figure><img alt="Screenshot of Google’s AutoML Vision platform showing class distribution for Normal and Pneumonia classes. 80% of the data is for training, 10% is for testing, and 10% is for validation." src="https://cdn-images-1.medium.com/max/1024/1*6p2PWoQ9x8bAs-qsz6julg.png" /><figcaption>Train/Test Split for Dataset-3 — Image by Author</figcaption></figure><p>After the training, we will evaluate our model using the confusion matrix.</p><figure><img alt="Confusion matrix with cell_11 = 8, cell_12 = 2, cell_21 = 1, and cell_22 = 9." src="https://cdn-images-1.medium.com/max/1024/1*rnNOiWQDwhrkmGmkpsJv7w.png" /><figcaption>Confusion Matrix for Dataset-3 — Image by Author</figcaption></figure><p>Our test set has 10 &#39;<strong><em>normal</em></strong>&#39;<strong><em> </em></strong>and 10 &#39;<strong><em>pneumonia</em></strong>&#39;<strong><em> </em></strong>images. The <strong><em>confusion matrix</em></strong> shown above tells us that our model has predicted 8 out of 10 &#39;<strong><em>normal</em></strong>&#39;<strong><em> </em></strong>class images as &#39;<strong><em>normal</em></strong>&#39; and 9 out of 10 &#39;<strong><em>pneumonia</em></strong>&#39;<strong><em> </em></strong>class images as &#39;<strong><em>pneumonia</em></strong>.&#39;</p><p>Let&#39;s calculate precision and recall for the &#39;normal&#39; class.</p><figure><img alt="Precision is (8) divided by (8 + 1), which is approximately 0.88, and recall is (8) divided by (8 + 2), which is 0.8." src="https://cdn-images-1.medium.com/max/296/1*ameVdC7fGQV-9LepIfYg_w.png" /></figure><p>For the &#39;<strong><em>normal</em></strong>&#39; class, <strong><em>precision </em></strong>increases from 0,83 to 0,88, and <strong><em>recall</em> </strong>decreases from 1 to 0,8.</p><p>We can easily see that the overall error (3) is larger than the <em>clean/balanced</em> case errors(2).</p><p>Moreover, there may be some dirty data in the test dataset, which makes the model unreliable, implying the real-life performance may be much worse than the evaluation.</p><p><strong>Create a three-class model with&#39; normal,&#39; &#39;bacterial pneumonia,&#39; and &#39;viral pneumonia.&#39;</strong></p><p>If we study the <a href="https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia">Kaggle chest x-ray dataset</a> in detail, we&#39;ll see that viruses or bacteria can cause pneumonia. We can view this by looking at the image names in the dataset. If the image name contains &#39;virus,&#39; it is viral pneumonia, and if the image name has &#39;bacteria,&#39; it is bacterial pneumonia.</p><p>For the final model, we will create a three-class dataset with 100 images from the &#39;<strong><em>normal</em></strong>&#39;<strong><em> </em></strong>class, 100 images from the &#39;<strong>bacterial pneumonia</strong>&#39; class, and 100 images from the &#39;<strong>viral pneumonia</strong>&#39; class.</p><p>We will start by splitting our dataset into 80%, 10%, and 10% portions.</p><figure><img alt="Screenshot of Google’s AutoML Vision platform showing class distribution for Viral, Normal, and Bacterial Pneumonia classes. 80% of the data is for training, 10% is for testing, and 10% is for validation." src="https://cdn-images-1.medium.com/max/1024/1*rzT5WN74NB24yZ5wJClYPQ.png" /><figcaption>Train/Test Split for Dataset-4 — Image by Author</figcaption></figure><p>After the training, we will evaluate our model using the confusion matrix.</p><figure><img alt="Confusion matrix with cell_11 = 10, cell_12 = 0, cell_13 = 0, cell_21 = 0, cell_22 = 10, cell_23 = 0, cell_31 = 6, cell_32 = 0, and cell_33 = 6." src="https://cdn-images-1.medium.com/max/1024/1*CtqmPVon1ZITDPsFZsSYdA.png" /><figcaption>Confusion Matrix for Dataset-4 — Image by Author</figcaption></figure><p>This time we have ten &#39;<strong><em>normal</em></strong>,&#39;<strong><em> </em></strong>ten &#39;<strong>viral pneumonia</strong>,&#39; and ten &#39;<strong>bacterial pneumonia</strong>&#39; class images in our test set. The <strong><em>confusion matrix</em></strong> tells us that our model has predicted 10 out of 10 &#39;<strong>viral pneumonia</strong>&#39;<strong> </strong>class<strong><em> </em></strong>images as &#39;<strong><em>viral pneumonia</em></strong>,&#39; 10 out of 10 &#39;<strong><em>normal</em></strong>&#39; class images as &#39;<strong><em>normal</em></strong>,&#39; and only 6 out of 10 &#39;<strong>bacterial <em>pneumonia</em></strong>&#39; class<strong><em> </em></strong>images as &#39;<strong>bacterial <em>pneumonia.</em></strong>&#39;</p><p>We can calculate precision and recall for the &#39;normal,&#39; &#39;viral pneumonia,&#39; and the &#39;bacterial pneumonia&#39; classes.</p><p>For the &#39;<strong><em>normal</em></strong>&#39;<strong><em> </em></strong>class:</p><figure><img alt="Precision for Normal Pneumonia class is (10) divided by (10 + 0), which is 1, and recall is (10) divided by (10 + 0), which is 1." src="https://cdn-images-1.medium.com/max/334/1*FbY2CNS_JC6fKkAS3dh1wQ.png" /></figure><p>For the &#39;<strong><em>viral pneumonia</em></strong>&#39;<strong><em> </em></strong>class:</p><figure><img alt="Precision for Viral Pneumonia class is (10) divided by (10 + 4), which is approximately 0.71, and recall is (10) divided by (10 + 0), which is 1." src="https://cdn-images-1.medium.com/max/326/1*i2kN-scdrk8FNqQWp8RHXA.png" /></figure><p>And for the &#39;<strong>bacterial <em>pneumonia</em></strong>&#39; class:</p><figure><img alt="Precision for Bacterial Pneumonia class is (6) divided by (6 + 0), which is 1, and recall is (6) divided by (6 + 4), which is 0.6." src="https://cdn-images-1.medium.com/max/282/1*bmriMYx7JGYMu629AnIleQ.png" /></figure><p>It seems that the model confuses bacterial pneumonia with viral pneumonia. One method to solve this confusion is adding more data to training. So let&#39;s add 20 images for each class to create a new balanced dataset and retrain our model.</p><p>We have 120 images from the &#39;<strong><em>normal</em></strong>&#39;<strong><em> </em></strong>class, 120 from the &#39;<strong>bacterial pneumonia&#39;</strong> class, and 120 from the &#39;<strong>viral pneumonia</strong>&#39; class. The new confusion matrix is as follows.</p><figure><img alt="Confusion matrix with cell_11 = 11, cell_12 = 0, cell_13 = 1, cell_21 = 0, cell_22 = 12, cell_23 = 0, cell_31 =1, cell_32 = 0, and cell_33 = 11." src="https://cdn-images-1.medium.com/max/1024/1*QraqAo8f2sOGUZtpr0wAUA.png" /><figcaption>Confusion Matrix for Dataset-4 b — Image by Author</figcaption></figure><p>We&#39;ve got a better result now. Let&#39;s calculate precision and recall for the last time.</p><p>For the &#39;<strong><em>normal</em></strong>&#39;<strong><em> class</em></strong>:</p><figure><img alt="Precision for Normal Pneumonia class is (12) divided by (12 + 0), which is 1, and recall is (12) divided by (12 + 0), which is 1." src="https://cdn-images-1.medium.com/max/311/1*Ci6h7Suh05gYowA5JDCnqw.png" /></figure><p>For the &#39;<strong><em>viral pneumonia</em></strong>&#39;<strong><em> </em></strong>class:</p><figure><img alt="Precision for Viral Pneumonia class is (11) divided by (11 + 1), which is approximately 0.92, and recall is (11) divided by (11 + 1), which is approximately 0.92." src="https://cdn-images-1.medium.com/max/332/1*IxIpaqNIeGZlWeF2rl4QJw.png" /></figure><p>And for the &#39;<strong>bacterial <em>pneumonia</em></strong>&#39; class:</p><figure><img alt="Precision for Bacterial Pneumonia class is (11) divided by (11 + 1), which is approximately 0.92, and recall is (11) divided by (11 + 1), which is approximately 0.92." src="https://cdn-images-1.medium.com/max/324/1*7WIZtaPhLTYtYCHY8DW1vA.png" /></figure><p>We can see that while the precision score for the &#39;<strong><em>viral pneumonia</em></strong>&#39; class and the recall score for the &#39;<strong>bacterial <em>pneumonia</em></strong>&#39; class increases <strong>considerably</strong>, the recall score for the &#39;<strong><em>viral pneumonia&#39;</em></strong> class and the precision score for the &#39;<strong>bacterial <em>pneumonia</em></strong>&#39; class decreases <strong>slightly</strong>. This phenomenon indicates better performance.</p><p>As a final stage, we will introduce a new metric to see this performance increase, the F1 score. We can calculate the F1 score using precision and recall, and the F1 score is the <a href="https://en.wikipedia.org/wiki/Harmonic_mean">harmonic mean</a> of <a href="https://en.wikipedia.org/wiki/F-score">precision and recall</a>. In mathematical terms:</p><figure><img alt="F1 Score equals two times precision times recall divided by the precision plus recall." src="https://cdn-images-1.medium.com/max/191/1*wVoYgbzpcMSc7ccujos3-g.png" /></figure><p>We will now calculate the F1 score of each class for the two datasets.</p><p>For the &#39;<strong>normal</strong>&#39; class:</p><figure><img alt="For both datasets, the F1 score for the Normal Pneumonia class is equal to (2) times (1) times (1) divided by (1) plus (1), which is equal to 1." src="https://cdn-images-1.medium.com/max/409/1*Qqtb1Pzpuva3E52Q4oA5kQ.png" /></figure><p>For the &#39;<strong><em>viral pneumonia</em></strong>&#39;<strong><em> </em></strong>class:</p><figure><img alt="For dataset_1, the F1 score for the Viral Pneumonia class is equal to (2) times (0.71) times (1) divided by (0.71) plus (1), which is approximately 0.83. For dataset_2, the F1 score for the Viral Pneumonia class is equal to (2) times (0.92) times (0.92) divided by (0.92) plus (0.92), which is 0.92." src="https://cdn-images-1.medium.com/max/456/1*ne5JvJEip-yswvwsKa6QHQ.png" /></figure><p>And for the &#39;<strong>bacterial <em>pneumonia</em></strong>&#39; class:</p><figure><img alt="For dataset_1, the F1 score for the Bacterial Pneumonia class is equal to (2) times (1) times (0.6) divided by (1) plus (0.6), which is 0.75. For dataset_2, the F1 score for the Bacterial Pneumonia class is equal to (2) times (0.92) times (0.92) divided by (0.92) plus (0.92), which is 0.92." src="https://cdn-images-1.medium.com/max/479/1*E-gcc24wQ0s4RmFv6ubaow.png" /></figure><p>The F1 score improves for both <strong><em>viral and bacterial pneumonia classes, suggesting</em></strong> a performance increase.</p><p><strong>Troubleshooting</strong></p><p>This project&#39;s most challenging part was creating an AutoML Vision account since Google doesn&#39;t accept debit cards quickly, and trying different cards generally solves the issue.</p><p>Another problem arises while uploading the datasets. Sometimes Google doesn&#39;t upload all the images while complaining about duplication. Manually adding new images will solve the issue.</p><p>Finally, sometimes the unbalanced model gives unexpectedly good results. Maybe Google AutoML is trying to filter the unbalanced dataset into a balanced dataset. Using a new dataset or retraining the model will solve the issue.</p><p><strong>Conclusion</strong></p><p>In this project, we have learned how data properties affect model performance. We have seen that dirty and unbalanced data significantly decrease model performance.</p><p>In addition, we have seen that using accuracy may mislead us. Instead, precision, recall, or F1 scores may give better results.</p><p>We have also learned how to calculate precision, recall, and F1 score using the confusion matrix.</p><p>As a final note, some of you may notice that although I promised to discuss possible improvements to the project at the beginning of this article, I haven&#39;t mentioned any since I will discuss these improvements in the <a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-iii-6da01dc2bb8c">next episode</a>. Stay tuned for the final episode. Refer to <a href="https://github.com/ErkanHatipoglu/AI-Product-Manager-Nanodegree-Program">my GitHub repository</a> or my first episode below for the Udacity AI Product Manager Program if you liked this subject or are interested in it.</p><p><a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-1-a85f24ff082b">Udacity AI Product Manager Program Review (Part I)</a></p><p>Thank you for reading!</p><p><strong>References</strong></p><ul><li><a href="https://www.udacity.com/">Udacity</a></li><li><a href="https://www.bertelsmann.com/#st-1">Bertelsmann SE &amp; Co. KGaA</a></li><li><a href="https://www.udacity.com/course/ai-product-manager-nanodegree--nd088">AI Product Manager Program</a></li><li><a href="https://www.udacity.com/bertelsmann-tech-scholarships">Bertelsmann Technology Scholarship</a></li><li><a href="https://cloud.google.com/ai-platform/docs/ml-solutions-overview">Machine learning workflow</a></li><li><a href="https://cloud.google.com/automl/">Google AutoML</a></li><li><a href="https://en.wikipedia.org/wiki/Automated_machine_learning">Automated Machine learning</a></li><li><a href="https://console.cloud.google.com/vision">Google&#39;s AutoML Vision platform</a></li><li><a href="https://www.kaggle.com/">Kaggle</a></li><li><a href="https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia">Kaggle chest x-ray dataset</a></li><li><a href="https://client.appen.com/sessions/new">Appen&#39;s platform</a></li><li><a href="https://en.wikipedia.org/wiki/Harmonic_mean">Harmonic Mean</a></li><li><a href="https://en.wikipedia.org/wiki/F-score">F-Score</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9fb55d0314e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-ii-b9fb55d0314e">Udacity AI Product Manager Program Review (Part II)</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[Udacity AI Product Manager Program Review (Part I)]]></title>
            <link>https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-1-a85f24ff082b?source=rss-c287c56e4845------2</link>
            <guid isPermaLink="false">https://medium.com/p/a85f24ff082b</guid>
            <category><![CDATA[dataset-annotation]]></category>
            <category><![CDATA[udacity-nanodegree]]></category>
            <category><![CDATA[ai-product-management]]></category>
            <category><![CDATA[udacity]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Erkan Hatipoğlu]]></dc:creator>
            <pubDate>Fri, 12 Nov 2021 15:03:23 GMT</pubDate>
            <atom:updated>2022-09-24T04:22:04.736Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Project Centric Review Approach</h4><figure><img alt="A man is working on a desk with a computer screen and a keyboard." src="https://cdn-images-1.medium.com/max/1024/0*k7E2F5eZkzoBf_dp" /><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=medium&amp;utm_medium=referral">Austin Distel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Overview</h4><p>This is the first episode of a <strong>three parts series</strong> on the review of the <a href="https://www.udacity.com/course/ai-product-manager-nanodegree--nd088">AI Product Manager Program offered by Udacity.</a></p><p>I&#39;ve been accepted to the <a href="https://www.udacity.com/bertelsmann-tech-scholarships">Bertelsmann Technology Scholarship</a> program phase 1 in <em>December 2020</em> and to phase 2 in <em>March 2021</em>. During the phase 2 period, I completed <a href="https://www.udacity.com/course/ai-product-manager-nanodegree--nd088">AI Product Manager Nanodegree by Udacity</a> and recently <strong>graduated</strong>.</p><p>The Nanodegree consists of <strong>4 chapters and three project assignments</strong>. I believe the most critical part of an online course is the project assignments. Hence I will not go into the details of the lectures. Instead, I will try a different approach and do the review through project assignments.</p><p>I will publish each project in a <strong>different episode</strong>. Hence, the readers can read about the first project in part I, the second in <a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-ii-b9fb55d0314e">part II</a>, and the final in <a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-iii-6da01dc2bb8c">part III</a>.</p><p>For each project, I will try to answer the following questions:</p><ul><li><em>What is the project about?</em></li><li><em>What is the outcome of the project?</em></li><li><em>What are the sources and tools to complete the project?</em></li><li><em>What is the solution?</em></li><li><em>What are the problems faced during the project implementation?</em></li><li><em>How can those problems be solved?</em></li><li><em>How can the project be improved?</em></li><li><em>What are the references for the project?</em></li></ul><p>Without further ado, let&#39;s dive into the first project;</p><h4>Project 1 — Create a Medical Image Annotation Job</h4><p>The first project of the Nanodegree is about designing a <strong>data labeling job</strong> for a given dataset and business goal.</p><p>The business goal is to make an AI product that distinguishes between healthy and Pneumonia chest x-ray images for children.</p><p>As <strong>AI product managers</strong>, our task is to build a labeled dataset for this product. ML engineers can, later on, use this dataset to create a <strong>classification product</strong> that can be used as <strong>diagnostics support</strong> by doctors.</p><p><strong>Outcome</strong></p><p>This project targets learning to create a <strong>high-quality dataset</strong>. Data quality is a <strong>crucial element</strong> of a successful machine learning project. We need to be sure that the data is big enough, complete, correctly labeled, and matches our use case to succeed with our project.</p><p>We will work on a modified subset of this <a href="https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia">Kaggle chest x-ray dataset</a>, with most labels removed. To complete the project, we need to deliver a project proposal as a <strong>pdf file</strong> that includes the design details and strategies for quality assurance, along with an <strong>HTML file</strong> that contains the instructions, examples, and some sample test questions. We will use <a href="https://client.appen.com/sessions/new">Appen&#39;s platform</a> for the data labeling job and create the HTML file as a project requirement. <a href="https://appen.com/about-us/">Appen</a> is a platform that collects and labels data for <strong>Artificial Intelligence systems</strong>.</p><p><strong>Data Annotation Platform</strong></p><p>To annotate an image data source with no labels, we can use data annotation platforms like <a href="https://appen.com/">Appen</a>. Annotation platforms work with <strong>human annotators</strong> that can label the data as required. To do that, we must explain to human annotators what to do and how to do it for all the use cases. In addition, we must design for uncertainty and supply the annotator with a way to handle unclear images. Finally, we need to prepare some<strong> test questions</strong> (unknown to the annotator) to measure the job&#39;s quality and the annotator&#39;s performance.</p><p><strong>The Design</strong></p><p>Our design will be as follows. Since we are trying to differentiate between healthy and Pneumonia images, we need <strong>two labels</strong> (yes or no). In addition, we want to give a method to the annotator to handle unclear images (not sure). As a result, as the <strong>first step</strong>, we need an image with three choices as below.</p><figure><img alt="A chest x-ray image on the left and a question with three answer options on the right." src="https://cdn-images-1.medium.com/max/1023/1*4UOq28keiDaR-2L3sMbvIA.png" /><figcaption>Step-1 — <em>Image by Author</em></figcaption></figure><p>We want to learn what symptoms the annotator has seen in the image. So we ask the symptoms as the <strong>second step</strong> if the annotator selects yes.</p><figure><img alt="A chest x-ray image on the left and two questions with different answer options on the right." src="https://cdn-images-1.medium.com/max/1024/1*cBh8USeyI5gV2RdwEbBtTw.png" /><figcaption>Step-2 — <em>Image by Author</em></figcaption></figure><p>Finally, we want to learn the annotator&#39;s opinion on the likelihood of Pneumonia if they are unsure about the image as the third step.</p><figure><img alt="A chest x-ray image on the left and two questions with different answer options on the right." src="https://cdn-images-1.medium.com/max/1024/1*mZBYVXRMPqkRHFkwVWuUzg.png" /><figcaption>Step-3 — <em>Image by Author</em></figcaption></figure><p><strong>Appen&#39;s Platform</strong></p><p>To use <a href="https://client.appen.com/sessions/new">Appen&#39;s platform</a>, we must first <strong>create an account</strong> as a client. After signing in, we will be directed to the <em>job creation page,</em> where we can find several <strong>job templates</strong> for specific use cases. We will use the <strong><em>Image Categorization</em> template</strong> for our use case since we want to label full images. To do that, we must first click on the <em>Image Categorization</em> template, and after the template is loaded, we need to click the <em>Use this template</em> button at the top right of the screen.</p><p><strong>The Data Tab</strong></p><p>The first thing to do on the job page is to upload the data, and we can use the <strong><em>Data tab</em></strong> for this purpose. As previously mentioned, we will use a subset of the <a href="https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia">Kaggle chest x-ray dataset</a> with 117 images. Sixteen of the images are labeled and will be used as examples or test questions, while 101 of the images are unlabeled and will be used for the annotation job.</p><p><strong>The Design Tab</strong></p><p>The next step is designing the job by clicking the <strong><em>Design tab</em></strong>. The <em>design tab</em> consists of the <strong><em>title</em></strong>, the<strong><em> CML code</em></strong>, and the <strong><em>instructions </em></strong>section. We need to give a relevant title to our job so that the annotators can understand what&#39;s to be done. <strong>Pneumonia Identification</strong> is a good choice for <em>the title</em>.</p><p><strong>Custom Markup Language</strong></p><p><strong><em>CML </em></strong>(Custom Markup Language) is an HTML-based language s<a href="https://success.appen.com/hc/en-us/articles/202817989-CML-Custom-Markup-Language-Overview">pecific to Appen</a>. It is used to define the elements (such as radio buttons) that the annotators use to <strong>interact </strong>with the images in our dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef343b5cd8a97e641e8dd7825143d1f0/href">https://medium.com/media/ef343b5cd8a97e641e8dd7825143d1f0/href</a></iframe><p><strong>Instructions</strong></p><p>As previously stated, we need to give detailed instructions to the annotators so that they can label the images as required. Consequently, the <strong><em>instruction section</em></strong>, which is an HTML code, must consist of an <strong><em>Overview</em></strong> part that narrates the job, a <strong><em>Steps</em></strong> part that describes the steps to be done in order, a <strong><em>Rules and Tips</em></strong> part that explains the details, and an<strong><em> Examples</em></strong> part that clarifies the job for all use-cases.</p><p><strong>The Quality Tab</strong></p><p>After finalizing the design, we need to switch to the <strong><em>Quality tab</em></strong>. In this tab, we will prepare some <strong>test questions</strong> for the annotators. These questions will be used to track the annotators&#39; performance. Udacity suggests preparing at least 5 % of the dataset as test questions, and <a href="https://success.appen.com/hc/en-us/articles/213078963-Test-Question-Best-Practices">Appen</a> suggests 8 for our case. As we have 16 labeled data, we can easily prepare 8 test questions. One thing to note here is that we must prepare a balanced number of test questions for each label. Otherwise, annotators may lean toward the <strong>most-frequent label</strong> while annotating.</p><p>While preparing the test questions, we must provide the <strong>answers </strong>and <strong>explanations </strong>so that if an annotator misses the question and answers incorrectly, she can learn the reason. The annotators must understand why they are wrong to improve their <strong>performance</strong>.</p><p><strong>Saving the HTML File</strong></p><p>After finishing the test questions, we are done with the platform. We can use the eye icon at the top right of the screen and preview our job. We can save the HTML file by right-clicking the page and selecting save as. We need to set save as type as <strong>Webpage, HTML Only</strong>. Note that we <strong>will not launch</strong> the data labeling job! Now it is time to work on the proposal.</p><p><strong>The Proposal</strong></p><p>The proposal consists of 3 sections with seven questions, some of which have been answered above. I will not cover all the details of the proposal; instead, I will focus on some critical aspects.</p><p>In our labeling job, we used three labels. Namely &#39;<strong><em>Has Pneumonia&#39;</em></strong>, &#39;<strong><em>Healthy</em></strong> (no pneumonia),&#39; and &#39;<strong><em>Not Sure.&#39;</em></strong> However, our model needs two labels. &#39;<strong><em>Has Pneumonia&#39;</em></strong> and &#39;<strong><em>Healthy.&#39;</em></strong> We need to find a way to decrease the labels so that our model can use them. If <strong><em>Not Sure</em></strong> answers are rare, then there is no problem. We can make manual checks. But if they are frequent, especially on specific images, we need a method to decide on the labels. We may use the mean of the <strong>scales </strong>for this purpose. We provided a likeliness of the Pneumonia scale to <strong><em>Not Sure</em></strong> answers for this purpose.</p><p>We can use <a href="https://client.appen.com/sessions/new">Appen&#39;s platform</a> tools to monitor annotators during the job period and take necessary actions. For example, sometimes, a respective amount of the annotators may miss a specific test question. This may happen because the test question is <strong>tricky </strong>or the instructions and examples are <strong>not clear</strong>. In this case, we may want to modify the instructions and examples. We may even use the test question as an example question since it is tricky.</p><p>We should also pay attention to the <strong>contributors&#39; feedback</strong> and make necessary changes if needed. We can use <a href="https://vimeo.com/440060571">Appen&#39;s platform monitoring tools</a> for this purpose.</p><p>We must consider <strong>limitations and improvements</strong> for our job as well.</p><p>To do that, we must consider any source of <strong>bias </strong>and how to handle it. Since our dataset is minimal, we may have <strong>sampling bias</strong>. Moreover, we may have <strong>measurement bias</strong> since the images are slightly different in size and taken under faintly different exposure times. So, acquiring more data and using the same imaging procedure for new data may decrease these biases.</p><p>In addition, we must decide how to get new data and what to do with it in the long run. For our use case, it is reasonable to use a <strong>dynamic model</strong> continuously trained with new data since it evolves because of new imaging technologies and new symptoms or diseases (Covid 19, for example).</p><p>After finishing the proposal and creating a pdf file, we can submit our project for <strong>review</strong>.</p><p><strong>Troubleshooting</strong></p><p>I think the curriculum for this Nanodegree is designed in 2018, maybe even 2017. As a result, some information, especially about <a href="https://client.appen.com/sessions/new">Appen&#39;s platform</a>, is <strong>outdated</strong>. Consequently, students may have difficulty understanding the interface. In addition, since the CML is specific to <a href="https://success.appen.com/hc/en-us/articles/202817989-CML-Custom-Markup-Language-Overview">Appen</a>, it may not be easy to find tutorials on it. I suggest Udacity&#39;s mentor help platform and <a href="https://success.appen.com/hc/en-us">Appen&#39;s help pages</a> in case of trouble.</p><p><strong>Conclusion</strong></p><p>Gathering clean data is one of the essential steps of an ML workflow. In this first project of the <a href="https://www.udacity.com/course/ai-product-manager-nanodegree--nd088">AI Product Manager Program</a>, we have learned how to create a labeling job which is key to a successful ML project.</p><p>We have started with a business goal. Then we gathered the dataset. Since the dataset was unlabeled, we decided on the labels and used Appen&#39;s platform to annotate the dataset. We first downloaded the dataset to Appen&#39;s platform to do that. Later we made the design that includes the instructions, examples, test questions, and the unlabeled dataset.</p><p>While making the design, we focused on comprehensibility and quality. We have also considered the possible biases of the data and plan for longevity.</p><p>You can also find a complete project implementation in my <a href="https://github.com/ErkanHatipoglu/AI-Product-Manager-Nanodegree-Program">GitHub repository</a>.</p><p>It is now time to move on to the next project. Stay tuned for part II.</p><p><strong>References</strong></p><ul><li><a href="https://www.udacity.com/">Udacity</a></li><li><a href="https://www.bertelsmann.com/#st-1">Bertelsmann SE &amp; Co. KGaA</a></li><li><a href="https://www.udacity.com/course/ai-product-manager-nanodegree--nd088">AI Product Manager Program</a></li><li><a href="https://www.udacity.com/bertelsmann-tech-scholarships">Bertelsmann Technology Scholarship</a></li><li><a href="https://www.kaggle.com/">Kaggle</a></li><li><a href="https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia">Kaggle chest x-ray dataset</a></li><li><a href="https://appen.com/about-us/">Appen</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a85f24ff082b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/udacity-ai-product-manager-program-review-part-1-a85f24ff082b">Udacity AI Product Manager Program Review (Part I)</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>