<?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 Derek Yang on Medium]]></title>
        <description><![CDATA[Stories by Derek Yang on Medium]]></description>
        <link>https://medium.com/@derek246810?source=rss-ee99eea7fb21------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PATfnKv4HZCHvjUO.</url>
            <title>Stories by Derek Yang on Medium</title>
            <link>https://medium.com/@derek246810?source=rss-ee99eea7fb21------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 04:48:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@derek246810/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[Popular Machine Learning Algorithms breakdown — Supervised Learning]]></title>
            <link>https://medium.com/@derek246810/popular-machine-learning-algorithms-breakdown-supervised-learning-f1460a8a7ddf?source=rss-ee99eea7fb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1460a8a7ddf</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[scikit]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <dc:creator><![CDATA[Derek Yang]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 05:12:51 GMT</pubDate>
            <atom:updated>2024-09-24T05:12:51.090Z</atom:updated>
            <content:encoded><![CDATA[<h3>Popular Machine Learning Algorithms breakdown — Supervised Learning</h3><h3>Introduction</h3><p>In this post we break down some of the popular supervised learning machine learning algorithms accompanied with their scikit-learn implementation. Stay tune for unsupervised learning algorithms and more!</p><p>In simple terms, <strong>supervised learning</strong> means that we have a labeled dataset where each input is paired with a corresponding “correct answer ” . The goal is to train a model to learn the relationship between the inputs and outputs so that it can make accurate predictions on new, unseen data. Essentially, the model is ‘supervised’ by the correct answers provided in the training data.</p><p>Below we explain some of the popular algorithms:</p><h3>Linear Regression</h3><blockquote>Linear regression is a statistical method that aims to find a linear relationship between your data(s) and the outcome</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Mdu-GlntAmUzrRWVZXtXIQ.png" /><figcaption>Image from author</figcaption></figure><p>Imagine you’re on a taxi ride, and you want to find out how much you’ll need to pay before you reach your destination. The fare is typically calculated based on a few factors, like the base fare when you get in the cab, the distance traveled, and the time spent in traffic. Each of these factors contributes to the final price.</p><p><strong>Linear regression</strong> is doing the same thing. We assume there is a linear relationship between the input variables (features), like distance and time in the taxi analogy, and the output, which is the final fare. You will want to use linear regression when you are predicting a <strong>continuous value</strong>.</p><p>If we use only one feature to determine the outcome, it’s called <strong>simple linear regression</strong>. In contrast, <strong>multiple linear regression</strong> uses more than one feature to predict the outcome, allowing for more accurate predictions by considering multiple factors.</p><pre>from sklearn.datasets import load_diabetes<br><br>dataset = load_diabetes()<br>X_train, X_test, y_train, y_test = train_test_split(dataset.data[:,np.newaxis,2], dataset.target, test_size = 0.2)</pre><pre>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import mean_squared_error, r2_score<br><br>model = LinearRegression()<br>model.fit(X_train,y_train)<br><br>y_pred = model.predict(X_test)<br><br>print(&quot;Mean squared error: %.2f&quot; % mean_squared_error(y_test, y_pred))<br>print(&quot;Coefficient of determination: %.2f&quot; % r2_score(y_test, y_pred))<br><br>plt.scatter(X_test, y_test, color=&quot;black&quot;,s=10)<br>plt.plot(X_test, y_pred, color=&quot;red&quot;, linewidth=2)<br>plt.xticks(())<br>plt.yticks(())<br><br>plt.show()</pre><h3>Support Vector machine</h3><blockquote>Support Vector machine utilizes data points to create “support vectors” to maximize margins for classification task and provide error margins for regression tasks.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*t2dgYbOXJbk5RSWx.png" /><figcaption>Image from <a href="https://scikit-learn.org/stable/modules/svm.html">scikit-learn support vector machine documentation</a></figcaption></figure><p>In classification tasks, SVMs are tasked to find the best hyperplane that splits the classes apart. <strong>Support vectors</strong> are the data points closest to the hyperplane. They are critical in defining the position and orientation of the hyperplane. We focus on these points because they are the most informative for creating the decision boundary. Which is why this algorithm is called a “support vector” machine.</p><p>In regression tasks, Support Vector Machines (SVM) are adapted as Support Vector Regression (SVR) to predict continuous outcomes. SVR introduces an error margin, allowing predictions to fall within a certain distance from actual values without penalty.</p><p>The goal of SVR is to find a hyperplane that minimizes the error between predicted and actual values while respecting the margin. Support vectors in SVR are the points outside this margin, which determine the hyperplane’s position.</p><p>Typically, SVMs are used to differentiate between two classes. If we want to expand the use of SVMs for multi-class classification, we can employ strategies like One-vs-One (find a plane for all the class-vs-class) or One-vs-All (for every class, find a plane to determine if its this class or not).</p><pre>from sklearn.datasets import load_iris<br><br>data, target = load_iris(return_X_y = True)<br>X_train, X_test, y_train, y_test = train_test_split(data, target, test_size = 0.2)</pre><pre>from sklearn.svm import SVC<br>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix<br><br>model = SVC(decision_function_shape=&#39;ovo&#39;)<br>model.fit(X_train,y_train)<br><br>y_pred = model.predict(X_test)<br><br>print(f&quot;Accuracy:{accuracy_score(y_test,y_pred)}&quot;)<br>print(f&quot;Precision:{precision_score(y_test,y_pred,average = &#39;macro&#39;)}&quot;)<br>print(f&quot;Recall:{recall_score(y_test,y_pred,average = &#39;macro&#39;)}&quot;)<br>print(f&quot;f1 score:{f1_score(y_test,y_pred,average = &#39;macro&#39;)}&quot;)<br>print(f&quot;Confusion Matrix:\n{confusion_matrix(y_test,y_pred)}&quot;)</pre><h3>K-Nearest Neighbors</h3><blockquote>K-Nearest Neighbors works by finding the K closest data points (neighbors) to a given input based on a distance metric (like Euclidean distance). Works both on regression tasks and classification tasks.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kqADIz_az50Ss1El.png" /><figcaption>Image from scikit-learn <a href="https://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html">nearest neighbor classification documentation</a></figcaption></figure><p>The intuition of KNN is fairly simple; we should be able to assume that datapoints with the same class will be located close to each other in the feature space. When we want to classify a new data point, we can look at its ‘neighbors’ — the K nearest points in the training data — and assign the most common class among these neighbors.</p><p>In regression task we can do a simple average of all the k neighbors or we can do a weighted average base on their distance with our predicted datapoint.</p><p>The choice of K is crucial; a smaller K can be sensitive to noise, while a larger K may smooth out class boundaries too much.</p><pre>from sklearn.datasets import load_wine<br>from sklearn.preprocessing import StandardScaler<br><br>data,target = load_wine(return_X_y = True)<br>data = StandardScaler().fit_transform(data)<br>X_train,X_test,y_train,y_test = train_test_split(data,target,test_size = 0.2)</pre><pre>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix<br><br>model = KNeighborsClassifier()<br>model.fit(X_train,y_train)<br><br>y_pred = model.predict(X_test)<br><br>print(f&quot;Accuracy:{accuracy_score(y_test,y_pred)}&quot;)<br>print(f&quot;Precision:{precision_score(y_test,y_pred,average = &#39;macro&#39;)}&quot;)<br>print(f&quot;Recall:{recall_score(y_test,y_pred,average = &#39;macro&#39;)}&quot;)<br>print(f&quot;f1 score:{f1_score(y_test,y_pred,average = &#39;macro&#39;)}&quot;)<br>print(f&quot;Confusion Matrix:\n{confusion_matrix(y_test,y_pred)}&quot;)</pre><h3>Decision Tree</h3><blockquote>Decision tree is a model that makes predictions by splitting data into branches based on feature values. It starts at a root, asks a series of yes/no questions (splits), and moves down branches until it reaches a leaf, where a prediction is made.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*oGh7xjHxrqwgWSx8.png" /><figcaption>Image from <a href="https://scikit-learn.org/stable/modules/tree.html">scikit-learn decision tree documentation</a></figcaption></figure><p>Decision tree works by finding the best feature to differentiate the current dataset at each node, evaluating how well each feature separates the data into distinct classes or have the lowest variance. It recursively splits the data based on the selected features, creating branches that lead to further splits until it reaches a point where the data is either perfectly classified or cannot be split any further.</p><p>When doing predictions, the input data will follow the structure of the decision tree. At each node, the decision tree evaluates the relevant feature and directs the input to the appropriate branch until it reaches a leaf node.</p><p>In classification tasks, the prediction is made based on the majority class label assigned to that leaf node. In regression tasks, the prediction is determined by averaging the target values of the training data that reached that leaf node.</p><pre>from sklearn.datasets import load_iris<br>data, target = load_iris(return_X_y = True)<br>X_train, X_test, y_train, y_test = train_test_split(data, target, test_size = 0.2)</pre><pre>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix<br><br>model = DecisionTreeClassifier()<br>model.fit(X_train,y_train)<br>y_pred = model.predict(X_test)<br>print(f&quot;Accuracy:{accuracy_score(y_test,y_pred)}&quot;)<br>print(f&quot;Precision:{precision_score(y_test,y_pred,average = &#39;macro&#39;)}&quot;)<br>print(f&quot;Recall:{recall_score(y_test,y_pred,average = &#39;macro&#39;)}&quot;)<br>print(f&quot;f1 score:{f1_score(y_test,y_pred,average = &#39;macro&#39;)}&quot;)<br>print(f&quot;Confusion Matrix:\n{confusion_matrix(y_test,y_pred)}&quot;)</pre><h3>Random Forest</h3><blockquote>Random Forest is an <strong>ensemble learning method</strong> that combines multiple decision trees. Each tree is trained on small subset of the data, and the final prediction is made by averaging the predictions of all the trees (for regression) or by majority voting (for classification).</blockquote><p>Instead of using one big decision tree, <strong>Random Forest</strong> builds multiple smaller <strong>decision trees</strong> during training, each based on a random subset of the data and a random subset of the features.</p><p>For classification tasks, Random Forest will predict the class by taking a <strong>majority vote</strong> across all the decision trees in the forest.</p><p>For regression tasks, Random Forest predicts the output by <strong>averaging the predictions</strong> from all the decision trees in the forest.</p><p>Random Forest improves upon Decision Trees by reducing overfitting and increasing accuracy through its ensemble of multiple trees. It is more robust and generalizes better to unseen data. However, Random Forests are less interpretable than a single Decision Tree, require more computational resources, and can be slower to train and predict due to the larger number of trees involved.</p><pre>from sklearn.datasets import load_wine<br>data, target = load_wine(return_X_y = True)<br>X_train,X_test,y_train,y_test = train_test_split(data,target,test_size = 0.2)</pre><pre>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix<br><br>model = RandomForestClassifier()<br>model.fit(X_train,y_train)<br>y_pred = model.predict(X_test)<br>print(f&quot;Accuracy:{accuracy_score(y_test,y_pred)}&quot;)<br>print(f&quot;Precision:{precision_score(y_test,y_pred,average = &#39;macro&#39;)}&quot;)<br>print(f&quot;Recall:{recall_score(y_test,y_pred,average = &#39;macro&#39;)}&quot;)<br>print(f&quot;f1 score:{f1_score(y_test,y_pred,average = &#39;macro&#39;)}&quot;)<br>print(f&quot;Confusion Matrix:\n{confusion_matrix(y_test,y_pred)}&quot;)</pre><h3>Logistic Regression</h3><blockquote>Logistic regression is a statistical method used for binary classification, which means it helps predict one of two possible outcomes(like yes/no, true/false).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EAOrxbl2oJKGDTBk.png" /><figcaption>Image from <a href="https://en.wikipedia.org/wiki/Logistic_regression">Wikipedia</a></figcaption></figure><p>Similar to linear regression mentioned above, logistic regression finds how important each feature is to our final prediction value. However, instead of predicting a continuous value, it predicts the probability of the target belonging to a particular class through “<strong>sigmoid</strong>” which maps our output between 0 and 1.</p><p>You can think of it like it is predicting the certainty of the model thinking the input belongs to this certain class. For example, imagine you are using logistic regression to predict whether a student will pass a class based on their attendance and study hours. The model might predict a 0.85, meaning that the model thinks this student might have an 85% chance of passing the class.</p><p>In simple binary classification, you can set a threshold (for example, 0.5). Anything above the threshold would be considered class A, while anything below would be considered class B. The further the predicted output is from our threshold, the more certain we can be about the classification.</p><p>logistic regression not only helps in making predictions but also provides insights into the relationships between the features and the outcome, allowing us to understand which factors are most significant in driving the predicted probabilities.</p><pre>from sklearn.datasets import load_breast_cancer<br>from sklearn.preprocessing import StandardScaler<br><br>data,target = load_breast_cancer(return_X_y = True)<br>data = StandardScaler().fit_transform(data)<br>X_train,X_test,y_train,y_test = train_test_split(data,target,test_size=0.2)</pre><pre>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix<br><br>model = LogisticRegression(max_iter=10000)<br>model.fit(X_train,y_train)<br><br>y_pred = model.predict(X_test)<br><br>print(f&quot;Accuracy:{accuracy_score(y_test,y_pred)}&quot;)<br>print(f&quot;Precision:{precision_score(y_test,y_pred)}&quot;)<br>print(f&quot;Recall:{recall_score(y_test,y_pred)}&quot;)<br>print(f&quot;f1 score:{f1_score(y_test,y_pred)}&quot;)<br>print(f&quot;Confusion Matrix:\n{confusion_matrix(y_test,y_pred)}&quot;)</pre><h3>Naive Bayes</h3><blockquote>Naive Bayes is a simple classification algorithm based on conditional probability. It assumes that all features are independent of each other (the “naive” assumption) given the class label.</blockquote><p>Imagine you’re classifying emails as “spam” or “not spam” based on the presence of certain words and you realize the word “free” appear on 80% of the spam emails and 20% on non-spam emails. So with a new incoming email, you can safely assume an email with the word “free” has a higher probability of being a spam than a non-spam.</p><p>Naive Bayes does the exact same thing but with all the features you provide. Even if the features (words in this case) are correlated in reality, the naive assumption simplifies the calculations. It allows the algorithm to quickly evaluate the overall likelihood of the email being spam by combining the probabilities for all the relevant features.</p><pre>from sklearn.datasets import load_digits<br><br>data, target = load_digits(return_X_y = True)<br>X_train,X_test,y_train,y_test = train_test_split(data,target,test_size = 0.2)</pre><pre>from sklearn.naive_bayes import GaussianNB<br>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix<br><br>model = GaussianNB()<br>model.fit(X_train,y_train)<br><br>y_pred = model.predict(X_test)<br><br>print(f&quot;Accuracy:{accuracy_score(y_test,y_pred)}&quot;)<br>print(f&quot;Precision:{precision_score(y_test,y_pred,average = &#39;macro&#39;)}&quot;)<br>print(f&quot;Recall:{recall_score(y_test,y_pred,average = &#39;macro&#39;)}&quot;)<br>print(f&quot;f1 score:{f1_score(y_test,y_pred,average = &#39;macro&#39;)}&quot;)<br>print(f&quot;Confusion Matrix:\n{confusion_matrix(y_test,y_pred)}&quot;)</pre><h3>Evaluation</h3><p>For evaluating a regression model, typical methods are:</p><ul><li><strong>R-squared:</strong> Shows how well the predicted values from the model differ from simply predicting the average value. If the model is predicting good results then we would be getting a score closer to 1.</li><li><strong>MSE (Mean Squared Error):</strong> The average of the squared differences between predicted and actual values.</li><li><strong>MAE (Mean Absolute Error):</strong> The average of the absolute differences between predicted and actual values.</li><li><strong>RMSE (Root Mean Squared Error):</strong> The square root of MSE.</li></ul><p>For evaluating a classification model, typical methods are:</p><ul><li><strong>Accuracy</strong>: The ratio of correctly predicted instances to the total instances in the dataset.</li><li><strong>Precision</strong>: For all the positive predictions, what percent of it is correct.</li><li><strong>Recall (Sensitivity)</strong>: For all the actual positive instances, what percent of them were correctly predicted as positive.</li><li><strong>F1 Score</strong>: The harmonic mean of precision and recall, providing a balance between the two.</li><li><strong>Confusion Matrix</strong>: A table that summarizes the performance of a classification model by showing the true positive, true negative, false positive, and false negative counts.</li><li><strong>ROC-AUC (Receiver Operating Characteristic — Area Under the Curve)</strong>: Measures the model’s ability to distinguish between classes across various threshold settings. An AUC value closer to 1 indicates better performance.</li></ul><p>For some of the algorithms I have implementations from scratch in the full notebook!</p><p>If you want to see the full <a href="https://github.com/dkyg1087/ML-Study-Notes/tree/main/contents/Popular_Machine_Learning_Algorithms_breakdown_Supervised_Learning">notebook</a> ← click here!</p><p>Thank you for taking the time to read through this post! I believe that teaching concepts helps reinforce understanding and I hope my explanations were clear. Please let me know if you have any feedback, questions, or topics you’d like to see covered in future posts. Your input is greatly appreciated!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1460a8a7ddf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an XOR Neural Network from Scratch: Learn from the Basics]]></title>
            <link>https://medium.com/@derek246810/building-an-xor-neural-network-from-scratch-learn-from-the-basics-63a2a22495ae?source=rss-ee99eea7fb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/63a2a22495ae</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Derek Yang]]></dc:creator>
            <pubDate>Sat, 03 Aug 2024 22:41:07 GMT</pubDate>
            <atom:updated>2024-08-03T22:41:07.517Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The XOR (exclusive OR) problem is a well-known challenge in machine learning because it cannot be solved by a single-layer neural network due to its non-linear separability. To address this, we use a neural network with a hidden layer, allowing it to learn the complex patterns required.</p><p>In this post, we’ll cover the basic concepts of neural network, gradient descent and backpropagation. Through code examples, hoping that you can also understand how these methods enable the network to learn and accurately replicate the XOR functions!</p><p>Before we dive in, I want to recommend an excellent YouTube video from <a href="https://www.youtube.com/@3blue1brown">3Blue1Brown</a> that covers similar topics in greater depth. This video provided many of the concepts discussed in this post and offers a thorough explanation of neural networks and beyond. If you’re interested in a more detailed exploration, I strongly suggest watching it!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIlg3gGewQ5U%3Flist%3DPLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIlg3gGewQ5U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FIlg3gGewQ5U%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d90bc49c0af9ad8b60f6e33e0299d6ae/href">https://medium.com/media/d90bc49c0af9ad8b60f6e33e0299d6ae/href</a></iframe><h3>Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*8Ng3snd449yj3gFDROOnlw.png" /></figure><p>Above is the overall structure for our neural network. The network consists of three layers:</p><ol><li><strong>Input Layer</strong>: This layer has two neurons, each representing one input of the XOR gate. In this case, Input 1 and Input 2 receive the binary inputs that we want to evaluate.</li><li><strong>Hidden Layer</strong>: This layer contains two neurons. These neurons help the network learn complex patterns by combining and transforming the inputs from the previous layer through weighted connections and activation functions.</li><li><strong>Output Layer</strong>: This layer has one neuron that produces the final output of the network. For the XOR gate, this output neuron will provide a value close to either 0 or 1, representing the XOR result of the two inputs.</li></ol><p>Each connection between the neurons represents a weighted link that adjusts during the training process to minimize the error in the network’s predictions.</p><p>It’s okay you are not familiar with some of the concepts, we will be talking a little bit more in detail in the later sections.</p><h3>Implementation</h3><p>First we import <a href="https://numpy.org/">N<em>umPy</em></a><em> for </em>easy and faster calculations and <a href="https://matplotlib.org/">M<em>atplotlib</em></a><em> </em>for visualization.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt</pre><p>We can now finally talk about how a neural network gets its name: the base of every neural network — the neuron.</p><p><strong>Neuron</strong></p><blockquote>A neuron in a neural network is inspired by the biological neuron in the human brain. Each neuron receives the inputs from previous neurons after some calculation, it runs the the result through an activation function to determine what exactly is sent out of this neuron and pass it to the next one.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*reI0qS7qoAAErtRZa-wFFw.png" /></figure><p>The process of a neuron is:</p><ol><li><strong>Input Reception</strong>: Receives input signals from the previous layer or input data.</li><li><strong>Weight Application</strong>: Each input is multiplied by a weight that is stored in the neuron, usually in a form of a matrix.</li><li><strong>Bias Addition: </strong>A bias term stored in the neuron would also be added to the<strong> </strong>output of the weighted result, to mimic a linear function:</li></ol><p><strong><em>z(input)</em> <em>= weight * input + bias</em></strong></p><p><strong>4. Activation Function</strong>: We apply an activation function <em>a(x)</em> to introduce non-linearity to the neuron, in the case of this implementation we choose to use the common function called <strong><em>sigmoid</em></strong>, which maps the linear output z to a value between 0 and 1.</p><p><strong>5. Output</strong>: The result a(x) is the output of the neuron, which is then passed to the next layer or used as the final output.</p><p>Below is the code implementation of the neuron, the weights and bias are initialized randomly to adjust during training to minimize the error and improve the network’s performance.</p><pre>class Neuron:<br>    def __init__(self, num_inputs):<br>        self.weights = np.random.uniform(size=num_inputs)<br>        self.bias = np.random.uniform()<br><br>    def activate(self, inputs):<br>        self.inputs = inputs<br>        self.output = self.sigmoid(np.dot(inputs, self.weights) + self.bias)<br>        return self.output<br><br>    def sigmoid(self, x):<br>        return 1 / (1 + np.exp(-x))</pre><p>However, without a mechanism to update the weights, the network cannot learn from the data. Therefore, we implement the method to adjust the weights and another method calculating the derivative of the sigmoid function for “back propagation”, which we will cover later in the layers section.</p><p>You might see there is a parameter called <strong><em>learning_rate</em></strong><em>. </em>This parameter controls how much the network learns from the mistake. We will also talk about it later.</p><pre>    def sigmoid_derivative(self):<br>        return self.output * (1 - self.output)<br><br>    def update_weights(self, delta, learning_rate):<br>        self.weights += learning_rate * delta * self.inputs<br>        self.bias += learning_rate * delta</pre><p>So the full neuron structure would look something like this:</p><pre>class Neuron:<br>    def __init__(self, num_inputs):<br>        self.weights = np.random.uniform(size=num_inputs)<br>        self.bias = np.random.uniform()<br><br>    def activate(self, inputs):<br>        self.inputs = inputs<br>        self.output = self.sigmoid(np.dot(inputs, self.weights) + self.bias)<br>        return self.output<br><br>    def sigmoid(self, x):<br>        return 1 / (1 + np.exp(-x))<br><br>    def sigmoid_derivative(self):<br>        return self.output * (1 - self.output)<br><br>    def update_weights(self, delta, learning_rate):<br>        self.weights += learning_rate * delta * self.inputs<br>        self.bias += learning_rate * delta</pre><p>Once we have our bricks (the neurons), we need to stack them into walls (the layers) to build our structure (the neural network). So lets talk about layers!</p><p><strong>Layer</strong></p><p>Layers are groups of neurons that work together to perform complex calculations. That’s where you will hear terms like ‘shallow networks’ and ‘deep networks.’ Shallow networks have only a few layers, typically just one hidden layer, while deep networks have many hidden layers. These additional layers in deep networks allow them to learn and model more intricate patterns in the data.</p><p>In our case we just need a shallow network with all the neurons connected to all the previous neurons.</p><pre>class Layer:<br>    def __init__(self, num_neurons, num_inputs_per_neuron):<br>        self.neurons = [Neuron(num_inputs_per_neuron) for _ in range(num_neurons)]</pre><p>Now its time to talk about the first part the two crucial processes in a neural network — forward pass.</p><p>Forward pass is the process of passing the input data through the layers to produce an output, it shows how the current neural network reacts to a given input.</p><p>In essence, the forward pass is like a pipeline where data flows through multiple layers, getting transformed at each step until we get an output.</p><pre>def forward(self, inputs):<br>        return np.array([neuron.activate(inputs) for neuron in self.neurons])</pre><p>While the forward pass generates the output, the backward pass is where the learning happens. The backward pass takes the error from our forward pass prediction and adjust the weights and bias to better predict the inputs. To properly understand the backwards pass, we need to talk about two things : Gradient Descent and Back propagation.</p><p><strong>Gradient Descent</strong></p><blockquote><strong>Gradient Descent</strong> is the optimization algorithm that utilizes the gradients calculated through backpropagation to update the network’s weights and biases.</blockquote><p>Imagine you’re on a hill with a ball, and your goal is to get the ball to the lowest point in a valley:</p><p>As the ball rolls down the hill, it naturally follows the path of steepest descent. At any point on the hill, you can observe the slope to determine which direction is downhill.</p><p>In a neural network, we calculate the gradient of the loss with respect to the weights to find the steepest direction. The steepest slope (gradient) guides the ball (and our parameter updates) toward the lowest point (minimum error).</p><p>This is where <strong>learning rate</strong> comes in as well, learning rate determines how fast the ball rolls down the hill. If the ball rolls too quickly (high learning rate), it might overshoot the lowest point and bounce around, possibly end up in a puddle that is not the lowest. If the ball rolls too slowly (low learning rate), it may take a long time to reach the bottom, making the descent inefficient.</p><p><strong>Back Propagation</strong></p><blockquote><strong>Backpropagation</strong> is the process used to compute the gradients of the loss function with respect to each weight and bias in the network within each neurons. It works by propagating the error backward through the network from the output layer to the input layer.</blockquote><p>During this process, the chain rule of calculus is applied to calculate how each weight and bias contributes to the overall error. Without getting into too much about math and calculus, I will try to explain it in simple terms.</p><p><em>Again, if you want a more through explanation, I strongly suggest watching the video from 3Blue1Brown I mentioned at the top.</em></p><p>From our ball rolling down a hill analogy, we understand that to reach the bottom, we need to follow the path of steepest descent. We can find the steepest descent by identifying the direction in which a small forward movement will cause the greatest decrease in altitude.</p><p>Finding the gradient is somewhat similar to this concept. The gradient of the error with respect to a weight tells us how the error will change if we ‘nudge’ that specific weight in a particular direction. This is done by finding an equation that describes the interaction between the error and that specific weight and then taking the partial derivative of the error with respect to that weight.</p><p>However, we cannot always find a direct equation for each weight and bias in the network because they are all interconnected but do not directly affect the final error. This is where the chain rule of calculus comes in. The chain rule tells us that if we know the interaction between A and B, and the interaction between B and C, we can determine the interaction between A and C. For example, if increasing B by 1 causes A to decrease by 2, and increasing C by 1 causes B to increase by 2, we can deduce that increasing C by 1 will cause A to decrease by 4!</p><p>With the chain rule and gradient calculation in mind, this is why the process is called “backpropagation.” We start at the output layer and move backward through the network, layer by layer. By applying the chain rule, we calculate how changes in each layer’s weights and biases affect the error, propagating this information backward to update all parameters. Making sure that each weight and bias is adjusted appropriately based on its contribution to the overall error.</p><pre>    def backward(self, errors, learning_rate):<br>        deltas = []<br>        for i, neuron in enumerate(self.neurons):<br>            delta = errors[i] * neuron.sigmoid_derivative()<br>            neuron.update_weights(delta, learning_rate)<br>            deltas.append(delta)<br>        return np.dot(np.array([neuron.weights for neuron in self.neurons]).T, deltas)</pre><p>So the full Layer structure would look something like this:</p><pre>class Layer:<br>    def __init__(self, num_neurons, num_inputs_per_neuron):<br>        self.neurons = [Neuron(num_inputs_per_neuron) for _ in range(num_neurons)]<br><br>    def forward(self, inputs):<br>        return np.array([neuron.activate(inputs) for neuron in self.neurons])<br><br>    def backward(self, errors, learning_rate):<br>        deltas = []<br>        for i, neuron in enumerate(self.neurons):<br>            delta = errors[i] * neuron.sigmoid_derivative()<br>            neuron.update_weights(delta, learning_rate)<br>            deltas.append(delta)<br>        return np.dot(np.array([neuron.weights for neuron in self.neurons]).T, deltas)</pre><p>After learning about neurons and layers, we can finally create the actual neural network.</p><p><strong>Neural network</strong></p><p>If you can recall the overall structure we mentioned above, the network is constructed with multiple layers, just like layers are constructed with multiple neurons.</p><p>When building a neural network, one of the essential components to define is the number of “<strong>epochs</strong>”. It determines how many times the network will go through this process of learning from the data. The more epochs you specify, the more opportunities the network has to adjust its parameters and improve its predictions.</p><p>However, too high of an epoch would also potentially “overfit” the data, meaning that the model has seen the training data too many times and may become too specialized in the training data. In simple terms, the network “memorized” 1+1 = 2 but can’t generalize it when it is asked to perform 2+2 .</p><p>In our situation, overfitting is somewhat acceptable because there are only four possible input combinations for the XOR gate, and we train the model with all four. This means the network will see every possible input and outcome during training, making overfitting less of a concern. However, in most real-world scenarios, overfitting is something that needs consideration.</p><p>The input layer just takes in the inputs, so we don’t need to initialize anything there. It’s the hidden layers and the output layer where we need to set up the neurons with initial weights and biases to ge<strong>t things started.</strong></p><pre>class NeuralNetwork:<br>    def __init__(self, layers, learning_rate=0.1, epochs=10000):<br>        self.learning_rate = learning_rate<br>        self.epochs = epochs<br>        self.layers = []<br><br>        # Initialize layers<br>        for i in range(len(layers) - 1):<br>            self.layers.append(Layer(layers[i+1], layers[i]))</pre><p>We now define the process of training in the neural network:</p><p>The training process of this neural network can be simplified to:</p><ol><li>Run the inputs through the neural network and retrieve the output from the output layer — forward pass</li><li>Base on our output we compare the difference between it and the “ground truth (correct output)” — error calculation</li><li>Base on the difference we determine how much do we want to tweak the weights and bias of our network — backwards pass</li><li>Repeat the process from 1. to 3. for the specified number of epochs</li></ol><p>The loss function(error calculation) algorithm chosen for this is the Mean square error (MSE) which is just finding the difference between the ground truth and our prediction and square it.</p><pre>def train(self, inputs, outputs):<br>        for epoch in range(self.epochs):<br>            total_error = 0<br>            for x, y in zip(inputs, outputs):<br>                # Forward pass<br>                activations = [x]<br>                for layer in self.layers:<br>                    activations.append(layer.forward(activations[-1]))<br><br>                # Calculate error<br>                output_errors = y - activations[-1]<br>                total_error += np.sum(output_errors ** 2)<br><br>                # Backward pass<br>                errors = output_errors<br>                for i in reversed(range(len(self.layers))):<br>                    errors = self.layers[i].backward(errors, self.learning_rate)<br><br>            # Print MSE every 1000 epochs<br>            if epoch % 1000 == 0:<br>                mse = total_error / len(inputs)<br>                print(f&#39;Epoch {epoch}, MSE: {mse}&#39;)</pre><p>After a neural network has been trained on a dataset, we need a way to apply the learned patterns to new, unseen data to get meaningful results.</p><p>The method is simply a forward pass that runs through the network.</p><pre>    def predict(self, inputs):<br>        activations = inputs<br>        for layer in self.layers:<br>            activations = layer.forward(activations)<br>        return activations</pre><p>The full Neural Network structure would look something like this:</p><pre>class NeuralNetwork:<br>    def __init__(self, layers, learning_rate=0.1, epochs=10000):<br>        self.learning_rate = learning_rate<br>        self.epochs = epochs<br>        self.layers = []<br><br>        # Initialize layers<br>        for i in range(len(layers) - 1):<br>            self.layers.append(Layer(layers[i+1], layers[i]))<br><br>    def train(self, inputs, outputs):<br>        for epoch in range(self.epochs):<br>            total_error = 0<br>            for x, y in zip(inputs, outputs):<br>                # Forward pass<br>                activations = [x]<br>                for layer in self.layers:<br>                    activations.append(layer.forward(activations[-1]))<br><br>                # Calculate error<br>                output_errors = y - activations[-1]<br>                total_error += np.sum(output_errors ** 2)<br><br>                # Backward pass<br>                errors = output_errors<br>                for i in reversed(range(len(self.layers))):<br>                    errors = self.layers[i].backward(errors, self.learning_rate)<br><br>            # Print MSE every 1000 epochs<br>            if epoch % 1000 == 0:<br>                mse = total_error / len(inputs)<br>                print(f&#39;Epoch {epoch}, MSE: {mse}&#39;)<br><br>    def predict(self, inputs):<br>        activations = inputs<br>        for layer in self.layers:<br>            activations = layer.forward(activations)<br>        return activations</pre><h3>Training</h3><p>Now we need to create our training data for our neural network.</p><p>Below is the truth table for an XOR gate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*6fXoG2scXLIXyLRyZhFb3A.png" /></figure><p>We create it according to the truth table:</p><pre>inputs = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])<br>outputs = np.array([[0], [1], [1], [0]])</pre><p>The initialization step is fairly simple since we already defined everything. We initialize the layers with:</p><p><strong><em>[ num_inputs, num_neurons_in_hidden_layer, num_outputs ]</em></strong></p><p>If we want to increase the amount of hidden layers we can easily do so by adding more layers between<strong><em> num_inputs</em></strong> and <strong><em>num_outputs</em></strong> like this:</p><p><strong><em>[ num_inputs, hidden_layer 1, hidden_layer 2, num_outputs ]</em></strong></p><p>We initialize the neural network with 10,000 epochs and 0.1 learning rate and train with our inputs and outputs.</p><pre># Initialize the neural network with an input layer, one hidden layer, and an output layer<br>layers = [2,2,1]  # 2 input neurons, 2 neurons in hidden layer, 1 output neuron<br>nn = NeuralNetwork(layers,0.1,10000)<br><br># Train the neural network<br>nn.train(inputs, outputs)</pre><p>The actual execution would look something like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*GMOhKWoOesHq0y8-Mg5Oyg.png" /></figure><h3>Evaluation</h3><p>We can perform a simple test on our network using the input data.</p><pre># Test the neural network<br>predicted_output = np.array([nn.predict(x) for x in inputs])<br>print(&quot;Predicted Output:\n&quot;, predicted_output)</pre><p>Since our model aims to replicate an XOR gate, we can round our outputs: any value greater than 0.5 will be considered as 1, and anything less will be considered as 0.</p><p>Given the nature of sigmoid functions, we can interpret the output as an indication of how confident the model is that the input belongs to 1. The closer the output is to 1, the more confident the model is; similarly, an output closer to 0 indicates greater confidence in the input belonging to 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*SSL1KqVDzfPPYYfkeNNgSg.png" /></figure><p>After we successfully trained our network it is best to visualize the result. I will not bore you with how this code works, it basically shows the boundary of where the model will determine it as 1 or 0.</p><pre># Round the predicted output to get binary predictions<br>predicted_output_binary = np.round(predicted_output)<br><br># Plot the decision boundary<br>x_min, x_max = inputs[:, 0].min() - 0.5, inputs[:, 0].max() + 0.5<br>y_min, y_max = inputs[:, 1].min() - 0.5, inputs[:, 1].max() + 0.5<br>xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1),<br>                     np.arange(y_min, y_max, 0.1))<br>Z = np.array([nn.predict(np.array([x, y])) for x, y in zip(xx.ravel(), yy.ravel())])<br>Z = np.round(Z.reshape(xx.shape))<br><br>plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)<br>plt.scatter(inputs[:, 0], inputs[:, 1], c=outputs.ravel(), cmap=plt.cm.Spectral)<br>plt.title(&quot;XOR Neural Network Decision Boundary&quot;)<br>plt.xlabel(&quot;Input 1&quot;)<br>plt.ylabel(&quot;Input 2&quot;)<br>plt.show()<br><br># Print the accuracy<br>accuracy = np.mean(predicted_output_binary.ravel() == outputs.ravel())<br>print(&quot;Accuracy:&quot;, accuracy)</pre><p>As shown in the plot, the purple points represent our input data. The blue and red regions indicate that points within these areas will be classified as 1 and 0, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*om7VGdfACemNjTyJ8mSG3Q.png" /></figure><p>If you want to see the full <a href="https://github.com/dkyg1087/ML-Study-Notes/blob/main/contents/Building_XOR_From_Scratch/XOR_from_scratch.ipynb"><strong><em>notebook</em></strong></a> ← click here!</p><p>Thank you for taking the time to read through this post! This is my first attempt at writing an introductory article. I believe that teaching concepts helps reinforce understanding and I hope my explanations were clear. Please let me know if you have any feedback, questions, or topics you’d like to see covered in future posts. Your input is greatly appreciated!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63a2a22495ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>