<?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 Stephen Echessa on Medium]]></title>
        <description><![CDATA[Stories by Stephen Echessa on Medium]]></description>
        <link>https://medium.com/@stevechesa?source=rss-b4204b4fc55c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KPDAorGFIl7wNuWrSLjRoA.jpeg</url>
            <title>Stories by Stephen Echessa on Medium</title>
            <link>https://medium.com/@stevechesa?source=rss-b4204b4fc55c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:17:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stevechesa/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[ML Basics 105: Building a Neural Network from scratch using Python]]></title>
            <link>https://medium.com/@stevechesa/ml-basics-105-building-a-neural-network-from-scratch-using-python-c860ca088d36?source=rss-b4204b4fc55c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c860ca088d36</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Stephen Echessa]]></dc:creator>
            <pubDate>Sat, 10 Oct 2026 17:22:47 GMT</pubDate>
            <atom:updated>2026-10-10T17:22:47.742Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Bringing gradient descent back to power a multi-layer neural network for classification and regression from scratch.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w47NEZYFvuW-ewse" /><figcaption>Photo by <a href="https://unsplash.com/@choys_?utm_source=medium&amp;utm_medium=referral">Conny Schneider</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome back to ML Basics! In our last post, we took the decision tree’s greedy splitting, ran it across hundreds of bootstrap samples, and used ensemble voting to transform a memorizing tree into a robust forest. Today, we tackle the architecture most people think of when they hear AI: Neural Networks. Built entirely from scratch with NumPy and gradient descent, this implementation uses a single flexible framework to handle both tasks: a sigmoid output for classification and direct numerical values for regression.</p><h3>Definition</h3><p>A neural network is a stack of layers. Each layer holds a number of neurons, and every neuron in one layer connects to every neuron in the next, which is why we call this network fully connected or, in the jargon, <strong>dense</strong>. Ours has four columns: the input layer with the eight features, two hidden layers with eight and four neurons, and one output neuron that speaks the final answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*HRXwtlxr9BkvZQbAOIz3Ew.png" /><figcaption>The eight features of a patient flow in on the left, through two hidden layers of eight and four ReLU neurons, to a single output neuron on the right. Every circle connects to every circle in the next column, and only the weights between them are learned.</figcaption></figure><p><strong>What does each neuron do?</strong> It looks at the signals arriving from the previous layer, combines them, and decides what to pass on. The activation function decides the flavor of that decision. ReLU, which the two hidden layers use, simply zeroes out negative signals and keeps the positive ones. It is a neuron’s way of saying this combination of signals is either worth passing along or it is not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*v1vwsBh835Kn6dN2vBOFEw.png" /></figure><h3>Forward Propagation</h3><p>This is the process of passing input data forward through the network’s layers to generate a prediction. Prediction is a one-way walk, and it is the same walk for both hats. At every arrow in the image above, multiply the incoming values by that arrow’s weight, add a bias, and pass the result through the layer’s activation. Each step is a weighted sum plus a bias, the same line we met in the very first article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*olqCpa38scgXUlXRhRR5Hw.png" /></figure><p>The first hidden layer receives the scaled features, the second receives the first layer’s output, and the output neuron applies the final squeeze: sigmoid for classification, which pins anything onto a 0 to 1 probability, and nothing at all for regression, which lets the raw number speak for itself. You have met sigmoid before, in the logistic regression article. Nothing in the forward walk is new. Only the stacking is.</p><h3>Backward Propagation</h3><p>Backpropagation, short for “backward propagation of errors”, is the mechanism by which a neural network learns. Just as we saw in linear regression, updating a weight requires knowing its contribution to the final prediction error. Backpropagation uses the chain rule to pass that error backward through the network layers, yielding the exact gradients needed to update every weight. Once those gradients are computed, gradient descent uses them to take the downhill step that actually updates the weights.</p><p>The cost functions to minimize should look familiar: binary cross entropy for classification and mean squared error for regression. Working from the output back toward the input, we measure how much of the overall error each layer owns. In short, the entire goal of this backward walk is to compute <em>dL/dw </em>and<em> dL/db</em>, the gradient of the loss with respect to each weight. This is why the forward pass stashes every intermediate value in a cache: the backward pass relies on those exact values to compute those derivatives on its way out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*OK2sKh1T74YTjKuNCARqEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/1*1bjmrRei5MY6VPyjIU2b1w.png" /></figure><p>Once those derivatives are in hand, we take the familiar downhill step: nudge every weight and bias against its gradient across thousands of iterations. The true magic of deep learning isn’t a complex new equation but the exact same optimization rule applied iteratively across a chain of layers.</p><h3>Code Implementation</h3><p>The code follows our familiar pattern: one core base class plus two specialized subclasses, exactly like we did for decision trees. The base class initializes the weights, runs the forward walk, walks the chain rule backward, and handles training. Each subclass only defines its unique output activation and cost function. Here is the base class in two pieces, starting with the setup and the forward walk.</p><pre>import numpy as np<br> <br> <br>class NeuralNetworkBase:<br>    &quot;&quot;&quot;<br>        Shared foundation for a 3-layer feedforward neural network, trained from scratch via Gradient Descent<br>        This base class is shared by NeuralNetworkClassifier and NeuralNetworkRegressor.<br>        It will include parameter initialization, hidden layers&#39; forward pass, backpropagation, and the training loop.<br> <br>        Input -&gt; Hidden layer 1 (ReLU) -&gt; Hidden layer 2 (ReLU) -&gt; Output layer<br>    &quot;&quot;&quot;<br> <br>    def __init__(self, n_input, n_hidden_1, n_hidden_2, learning_rate=0.1, n_iterations=1000):<br>        self.n_input = n_input<br>        self.n_hidden_1 = n_hidden_1<br>        self.n_hidden_2 = n_hidden_2<br> <br>        # Will be used in Gradient Descent<br>        self.lr = learning_rate<br>        self.n_iterations = n_iterations<br>        self.cost_history = []<br> <br>        self._initialize_parameters()<br> <br> <br>    def _initialize_parameters(self):<br>        &quot;&quot;&quot;<br>           Weights are initialized to small random values (not zero) so that the neurons within a layer don&#39;t all learn<br>           the exact same thing.<br> <br>           Biases start at zero.<br>        &quot;&quot;&quot;<br>        rng = np.random.default_rng(seed=42)<br> <br>        self.W1 = rng.standard_normal((self.n_input, self.n_hidden_1)) * 0.01<br>        self.b1 = np.zeros(self.n_hidden_1)<br> <br>        self.W2 = rng.standard_normal((self.n_hidden_1, self.n_hidden_2)) * 0.01<br>        self.b2 = np.zeros(self.n_hidden_2)<br> <br>        self.W3 = rng.standard_normal((self.n_hidden_2, 1)) * 0.01<br>        self.b3 = np.zeros(1)<br> <br> <br>    def _relu(self, Z):<br>        &quot;&quot;&quot;<br>            Used as the activation for the two hidden layers<br>        &quot;&quot;&quot;<br>        return np.maximum(0, Z)<br> <br> <br>    def _relu_derivative(self, Z):<br>        &quot;&quot;&quot;<br>            Computes the derivative of ReLU function: 1 where Z &gt; 0, else 0. This is needed for backpropagation<br>        &quot;&quot;&quot;<br>        return (Z &gt; 0).astype(float)<br> <br> <br>    def _forward_propagation(self, X):<br>        &quot;&quot;&quot;<br>            Pushes X through all the 3 layers to produce a prediction<br>            Naming convention, standard for neural networks:<br>                Z = the linear step of a layer (W . input + b)<br>                A = the activated output of a layer (activation_fn(Z))<br>        &quot;&quot;&quot;<br> <br>        Z1 = X @ self.W1 + self.b1<br>        A1 = self._relu(Z1)<br> <br>        Z2 = A1 @ self.W2 + self.b2<br>        A2 = self._relu(Z2)<br> <br>        Z3 = A2 @ self.W3 + self.b3<br>        A3 = self._output_activation(Z3) # Sigmoid function for classification and identity for regression<br> <br>        # This will be needed for backpropagation<br>        cache = {&quot;X&quot;: X, &quot;Z1&quot;: Z1, &quot;A1&quot;: A1, &quot;Z2&quot;: Z2, &quot;A2&quot;: A2, &quot;Z3&quot;: Z3, &quot;A3&quot;: A3}<br> <br>        return A3, cache</pre><p>Next comes the core training mechanics: the backward pass that computes every gradient, the parameter update, and the loop that repeats both for thousands of iterations. Notice how the training loop remains completely agnostic to whether we are solving classification or regression. It simply steps downhill, leaving the specific loss function, whether cross entropy or mean squared error, safely abstracted behind a single method call.</p><pre>    def _backward_propagation(self, y_true, cache):<br>        &quot;&quot;&quot;<br>            Computes dCost/dw and dCost/db (partial derivatives) for every layer,<br>            working backward from the output layer to the input layer, and applying the chain<br>            rule at each step<br> <br>            This works unchanged for both regression and classification<br>        &quot;&quot;&quot;<br>        n_samples = len(y_true)<br>        y_true = y_true.reshape(-1, 1)<br> <br>        X, A1, A2, A3 = cache[&quot;X&quot;], cache[&quot;A1&quot;], cache[&quot;A2&quot;], cache[&quot;A3&quot;]<br>        Z1, Z2 = cache[&quot;Z1&quot;], cache[&quot;Z2&quot;]<br> <br>        # Output layer<br>        dZ3 = A3 - y_true<br>        dW3 = (1 / n_samples) * (A2.T @ dZ3)<br>        db3 = (1 / n_samples) * np.sum(dZ3, axis=0)<br> <br>        # Hidden layer 2<br>        dA2 = dZ3 @ self.W3.T<br>        dZ2 = dA2 * self._relu_derivative(Z2)<br>        dW2 = (1 / n_samples) * (A1.T @ dZ2)<br>        db2 = (1 / n_samples) * np.sum(dZ2, axis=0)<br> <br>        # Hidden layer 1<br>        dA1 = dZ2 @ self.W2.T<br>        dZ1 = dA1 * self._relu_derivative(Z1)<br>        dW1 = (1 / n_samples) * (X.T @ dZ1)<br>        db1 = (1 / n_samples) * np.sum(dZ1, axis=0)<br> <br>        return {<br>            &quot;dW1&quot;: dW1, &quot;db1&quot;: db1, &quot;dW2&quot;: dW2, &quot;db2&quot;: db2, &quot;dW3&quot;: dW3, &quot;db3&quot;: db3,<br>        }<br> <br> <br>    def _update_parameters(self, gradients):<br>        &quot;&quot;&quot;<br>            Nudges every weight and bias a small step in the direction that reduces cost.<br>        &quot;&quot;&quot;<br>        self.W1 = self.W1 - self.lr * gradients[&quot;dW1&quot;]<br>        self.b1 = self.b1 - self.lr * gradients[&quot;db1&quot;]<br> <br>        self.W2 = self.W2 - self.lr * gradients[&quot;dW2&quot;]<br>        self.b2 = self.b2 - self.lr * gradients[&quot;db2&quot;]<br> <br>        self.W3 = self.W3 - self.lr * gradients[&quot;dW3&quot;]<br>        self.b3 = self.b3 - self.lr * gradients[&quot;db3&quot;]<br> <br> <br>    def fit(self, X, y):<br>        &quot;&quot;&quot;<br>            Gradient Descent Training Loop<br> <br>            In each iteration:<br>                a) Predict(forward propagation) -&gt; measure error cost<br>                b) Compute gradients(backward propagation) -&gt; update weights and biases<br> <br>            Identical for regression and classification, only what cost and the output activation mean underneath differ<br>        &quot;&quot;&quot;<br>        self._initialize_parameters()<br>        self.cost_history = []<br> <br>        for i in range(self.n_iterations):<br>            y_pred, cache = self._forward_propagation(X)<br> <br>            # Change y_pred from 2D array to 1D array<br>            cost = self._compute_cost(y_true=y, y_pred=y_pred.flatten())<br>            self.cost_history.append(cost)<br> <br>            gradients = self._backward_propagation(y_true=y, cache=cache)<br>            self._update_parameters(gradients=gradients)</pre><p>The subclasses remain wonderfully concise. The classifier simply sets the output activation to sigmoid, uses binary cross entropy for its cost function, and converts predicted probabilities into discrete labels using a 0.5 threshold.</p><pre>import numpy as np<br> <br>from models.base_neural_network import NeuralNetworkBase<br> <br> <br>class NeuralNetworkClassifier(NeuralNetworkBase):<br>    &quot;&quot;&quot;<br>        Neural Network for binary classification<br> <br>        Built on top of the Base Neural Network class, but with:<br>                    - a sigmoid activation function (returns 0-1 probabilty)<br>                    - cross-entropy as the cost function<br>    &quot;&quot;&quot;<br>    def _output_activation(self, Z):<br>        &quot;&quot;&quot;<br>            Returns an output by using the sigmoid function<br>        &quot;&quot;&quot;<br>        return 1 / (1 + np.exp(-Z))<br> <br> <br>    def _compute_cost(self, y_true, y_pred):<br>        &quot;&quot;&quot;<br>            Formula for binary cross entropy is: -1/n * sum((y_true * log(y_pred)) + ((1 - y_true) * (log(1 - y_pred))))<br>        &quot;&quot;&quot;<br>        n_samples = len(y_true)<br>        return (-1/n_samples) * np.sum((y_true * np.log(y_pred)) + ((1 - y_true) * np.log(1 - y_pred)))<br> <br> <br>    def _predict_proba(self, X):<br>        &quot;&quot;&quot;<br>            Return model&#39;s predicted probabilities<br>        &quot;&quot;&quot;<br>        y_pred, _ = self._forward_propagation(X)<br>        return y_pred.flatten()<br> <br> <br>    def predict(self, X, threshold = 0.5):<br>        &quot;&quot;&quot;<br>            Converts predicted probabilities into 0/1 class labels using a threshold<br>        &quot;&quot;&quot;<br>        return (self._predict_proba(X) &gt;= threshold).astype(int)</pre><p>The regressor is just as compact. It sets the output activation to a simple identity pass-through, leaving the predictions raw, and uses mean squared error as its cost function. That single configuration is the entire functional difference between classifying and predicting continuous values in a neural network.</p><pre>import numpy as np<br> <br>from models.base_neural_network import NeuralNetworkBase<br> <br> <br>class NeuralNetworkRegressor(NeuralNetworkBase):<br>    &quot;&quot;&quot;<br>        Neural Network for regression<br> <br>        Built on top of the Base Neural Network class, but with:<br>            - an identity output activation (raw linear output)<br>            - mean squared error as the cost function<br>    &quot;&quot;&quot;<br> <br> <br>    def _output_activation(self, Z):<br>        return Z<br> <br> <br>    def _compute_cost(self, y_true, y_pred):<br>        &quot;&quot;&quot;<br>            Formula for MSE is: (1/2n) * sum((y_pred - y_true)²).<br>        &quot;&quot;&quot;<br>        n_samples = len(y_true)<br> <br>        return (1/2 * n_samples) * np.sum((y_pred - y_true) ** 2)<br> <br> <br>    def predict(self, X):<br>        &quot;&quot;&quot;<br>            Returns the model&#39;s predicted value<br>        &quot;&quot;&quot;<br>        y_pred, _ = self._forward_propagation(X)<br>        return y_pred.flatten()</pre><h3>Now it is time to test it: Classification</h3><p>Back to the Pima dataset, same cleaning, same split. The network needs standardized features, so we scale first, then send our network against scikit-learn’s MLP, the library name for exactly this architecture.</p><pre>import numpy as np<br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.neural_network import MLPClassifier as SkNN<br>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score<br> <br>from models.neural_network_classifier import NeuralNetworkClassifier<br> <br>df = pd.read_csv(&#39;../data/pima_diabetes_classification.csv&#39;)<br> <br>train_df, test_df = train_test_split(df, test_size=0.2, random_state=42,<br>                                     stratify=df[&#39;outcome&#39;])<br> <br># Replace hidden zeros (impossible values) with median estimates before training<br>for col in [&#39;glucose&#39;, &#39;blood_pressure&#39;, &#39;bmi&#39;]:<br>    med = train_df.loc[train_df[col] != 0, col].median()<br>    train_df[col] = train_df[col].replace(0, med)<br>    test_df[col] = test_df[col].replace(0, med)<br> <br>for col in [&#39;insulin&#39;, &#39;skin_thickness&#39;]:<br>    meds = train_df.loc[train_df[col] != 0, col].groupby(train_df[&#39;outcome&#39;]).median()<br>    train_df[col] = train_df.apply(lambda r: meds[r[&#39;outcome&#39;]] if r[col] == 0 else r[col], axis=1)<br>    test_df[col] = test_df.apply(lambda r: meds[r[&#39;outcome&#39;]] if r[col] == 0 else r[col], axis=1)<br> <br>feature_cols = [c for c in df.columns if c != &#39;outcome&#39;]<br>X_train_raw = train_df[feature_cols].values<br>X_test_raw = test_df[feature_cols].values<br>y_train = train_df[&#39;outcome&#39;].values<br>y_test = test_df[&#39;outcome&#39;].values<br> <br># Neural networks train on standardised features<br>scaler = StandardScaler()<br>X_train = scaler.fit_transform(X_train_raw)<br>X_test = scaler.transform(X_test_raw)<br> <br># Our implementation from scratch<br>scratch = NeuralNetworkClassifier(n_input=X_train.shape[1], n_hidden_1=8,<br>                                  n_hidden_2=4, learning_rate=0.5,<br>                                  n_iterations=3000)<br>scratch.fit(X_train, y_train)<br>scratch_preds = scratch.predict(X_test)<br> <br># scikit-learn for comparison<br>sk = SkNN(hidden_layer_sizes=(8, 4), activation=&#39;relu&#39;, solver=&#39;sgd&#39;,<br>          learning_rate_init=0.5, max_iter=3000, random_state=42,<br>          batch_size=len(y_train))<br>sk.fit(X_train, y_train)<br>sk_preds = sk.predict(X_test)<br> <br>def report(name, y_true, y_pred):<br>    acc = accuracy_score(y_true, y_pred)<br>    prec = precision_score(y_true, y_pred)<br>    rec = recall_score(y_true, y_pred)<br>    f1 = f1_score(y_true, y_pred)<br>    print(&quot;{name:20s} Acc={acc:.3f}  Prec={prec:.3f}  Rec={rec:.3f}  F1={f1:.3f}&quot;.format(<br>        name=name, acc=acc, prec=prec, rec=rec, f1=f1))<br> <br>report(&#39;From-scratch NN&#39;, y_test, scratch_preds)<br>report(&#39;scikit-learn NN&#39;, y_test, sk_preds)</pre><pre>From-scratch NN        Acc=0.857  Prec=0.796  Rec=0.796  F1=0.796<br>scikit-learn NN        Acc=0.851  Prec=0.816  Rec=0.741  F1=0.777</pre><p>The neural network lands in a dead heat with our Random Forest, matching its 0.857 accuracy, 0.796 recall, and 0.796 F1 score. Two completely different architectures, one splitting nodes, the other updating weights, hit the exact same performance ceiling. In machine learning, that ceiling is usually set by the quality of the data, not the complexity of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*hNNsFW5F8vjwd1AJMd0B5A.png" /></figure><h3>Now let&#39;s do the same for regression</h3><p>Switching over to regression, the network uses the exact same architecture and normalized features to predict disease progression. However, because target values are now continuous, this step introduces target scaling alongside our feature scaling.</p><pre>import numpy as np<br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.neural_network import MLPRegressor as SkNN<br>from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error<br> <br>from models.neural_network_regressor import NeuralNetworkRegressor<br> <br>df = pd.read_csv(&#39;../data/diabetes_progression.csv&#39;)<br>df.drop(columns=&#39;ldl_cholesterol&#39;, inplace=True)<br> <br>train_df, test_df = train_test_split(df, test_size=0.2, random_state=42)<br> <br>feature_cols = [c for c in df.columns if c != &#39;disease_progression&#39;]<br>X_train_raw = train_df[feature_cols].values<br>X_test_raw = test_df[feature_cols].values<br>y_train = train_df[&#39;disease_progression&#39;].values<br>y_test = test_df[&#39;disease_progression&#39;].values<br> <br># Neural networks train on standardised features, the target too for regression<br>scaler_X = StandardScaler()<br>X_train = scaler_X.fit_transform(X_train_raw)<br>X_test = scaler_X.transform(X_test_raw)<br> <br>scaler_y = StandardScaler()<br>y_train_scaled = scaler_y.fit_transform(y_train.reshape(-1, 1)).flatten()<br> <br># Our implementation from scratch<br>scratch = NeuralNetworkRegressor(n_input=X_train.shape[1], n_hidden_1=8,<br>                                 n_hidden_2=4, learning_rate=0.1,<br>                                 n_iterations=2000)<br>scratch.fit(X_train, y_train_scaled)<br>scratch_preds = scaler_y.inverse_transform(<br>    scratch.predict(X_test).reshape(-1, 1)).flatten()<br> <br># scikit-learn for comparison<br>sk = SkNN(hidden_layer_sizes=(8, 4), activation=&#39;relu&#39;, solver=&#39;sgd&#39;,<br>          learning_rate_init=0.1, max_iter=2000, random_state=42,<br>          batch_size=len(y_train_scaled))<br>sk.fit(X_train, y_train_scaled)<br>sk_preds = scaler_y.inverse_transform(<br>    sk.predict(X_test).reshape(-1, 1)).flatten()<br> <br>def report(name, y_true, y_pred):<br>    r2 = r2_score(y_true, y_pred)<br>    rmse = np.sqrt(mean_squared_error(y_true, y_pred))<br>    mae = mean_absolute_error(y_true, y_pred)<br>    print(&quot;{name:20s} R²={r2:.4f}  RMSE={rmse:.2f}  MAE={mae:.2f}&quot;.format(<br>        name=name, r2=r2, rmse=rmse, mae=mae))<br> <br>report(&#39;From-scratch NN&#39;, y_test, scratch_preds)<br>report(&#39;scikit-learn NN&#39;, y_test, sk_preds)</pre><pre>From-scratch NN        R²=0.4942  RMSE=51.77  MAE=41.14<br>scikit-learn NN        R²=0.5233  RMSE=50.26  MAE=38.24</pre><p>The regression results set a new series high with an R² of 0.4942, edging out the Random Forest (0.4784), Linear Regression (0.4526), and Decision Tree (0.3228). Error metrics improve across the board, with an RMSE of 51.77 beating the forest’s 52.57 and an MAE of 41.14 outperforming linear regression’s 42.88.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*1dXbZyUsO_PDD8_T4lOJXQ.png" /></figure><p>One honest asterisk: for the first time this series, the library version pulls ahead of us, 0.5233 to 0.4942 in R². Running the exact same architecture and learning rate, the performance gap comes down to optimization implementation. Scikit-learn’s solver incorporates momentum into its gradient updates, a small acceleration mechanism we missed. This gap doesn’t undermine our scratch implementation; rather, it highlights how much every training detail matters, offering a level of visibility you only get by building from scratch.</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*PPptk-feCn3Fr11sJtKdIQ.gif" /></figure><p>Everything we built throughout this series culminated in today’s model. The weighted sum first appeared in linear regression, the downhill optimization in gradient descent, and the sigmoid activation in logistic regression. A neural network is simply all of those familiar components combined across multiple layers. If understanding this architecture felt surprisingly straightforward, it is because there is nothing entirely new inside it: just weighted sums, an activation function, a cost metric, and iterative gradient updates.</p><p>Across this series, we built five models from scratch across five source files with zero external libraries. When you can read the code behind the algorithms, you can easily cut right through the hype.</p><p>Thank you for following along, and you can explore the complete project implementation on GitHub by clicking <a href="https://github.com/Stephen-Echessa/diabetes_ml_project_backend/blob/master/models/base_neural_network.py">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c860ca088d36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML Basics 104: Building Random Forests from scratch using Python]]></title>
            <link>https://medium.com/@stevechesa/ml-basics-104-building-random-forests-from-scratch-using-python-7b3cc3e3de0f?source=rss-b4204b4fc55c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b3cc3e3de0f</guid>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <dc:creator><![CDATA[Stephen Echessa]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 11:53:23 GMT</pubDate>
            <atom:updated>2026-10-03T11:59:13.807Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Discover how Random Forests solve Decision Tree overfitting by averaging predictions across an ensemble of trees.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7pttRiYWbSfvBatd9VQmMg.jpeg" /></figure><p>Hello, and welcome back to my ML Basics series. In our last article, we built a Decision Tree from scratch, and it matched scikit-learn on both classification and regression. But two numbers from that article do not leave me alone: 93.5% accuracy on the training set versus 81.2% on the test set, and a regression R² of 0.32, which lost to plain linear regression. The tree is smart, but it memorizes. Today we fix both weaknesses by building a Random Forest using the same simple framework: one vote for classification, one average for regression.</p><h3>Why one tree is not enough</h3><p>A tree is a strong learner with a terrible memory. Grown deep enough, it will carve the training set into perfect little boxes, down to single patients, then stumble the moment it meets someone new. That is exactly the 93.5% versus 81.2% gap we saw: great on data it already met, shaky on data it has not.</p><p>There is a second, sneakier weakness. A tree only ever sees one version of its world. Move a few patients around, swap two rows, and the root question can flip entirely. The tree commits to its data as if it were the only data that exists. Fix both weaknesses with one move: do not consult one tree, consult many trees, and let them disagree on purpose.</p><h3>Bootstrap sampling</h3><p>The first way to make trees different is to give each one a slightly different training set. Draw n samples from the n-row training set, with replacement. With replacement, it means each draw can pick the same row again, so by the end some patients appear several times and one or two never show up at all. Every tree grows from a copy of the original size, only with flipped luck.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*DPugVkhZaLYL4dhD08h29w.png" /><figcaption>Bootstrap sampling. Each tree draws its own training set of the same size, with replacement. Tree one’s copy repeats patient A and patient E while patient C never shows up; tree two draws a completely different hand of luck.</figcaption></figure><p>Because every tree reads a different copy, every tree learns different questions. This is the first source of randomness, and scikit-learn turns it on with the setting that became the technique’s name: bootstrap.</p><h3>Feature sampling</h3><p>Different data is a start, but sometimes one feature is so strong that every tree reaches for it first, and the forest quietly becomes a photocopy. So we add a second difference. At every split, each tree may only look at a random subset of the features, not all of them. The standard choice, and the one scikit-learn defaults to, is the square root of the feature count: for our datasets, two or three features per split instead of eight or nine.</p><p>Last article’s tree already carried a hook for exactly this, the max_features argument we set aside and moved on from. Today that hook does the real work. Two random picks, one on the rows and one on the features, and the trees stay strong while stubbornly disagreeing about the details.</p><h3>The vote</h3><p>Prediction is where a forest turns into a tiny parliament. For classification, every tree inspects the patient and shouts its own 0 or 1, and the forest answers with whichever shout won the most votes. For regression, every tree shouts a number, and the forest answers with their average, a single formula and then it is free.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*IazIL3d9Fp_54eAUzyVHaQ.png" /></figure><p>Three trees look at the same patient and call it 1, 0, 1. The forest says 1, and the lone dissenter gets outvoted. That is the entire trick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M42DJGZQ6uthNE0ra-KDig.png" /><figcaption>A forest is a parliament. Every tree inspects the same patient and casts a vote; the forest answers with the majority. For regression each tree shouts their number and the parliament answers with their average.</figcaption></figure><p>Why does the average help? Each tree has its own blind spots and its own small mistakes, and those mistakes are random. Random mistakes do not line up with each other, so in the vote they cancel out. What every tree agrees on is the real signal, and that is what survives. One tree is one strong guess; one hundred trees cancelling each other’s random slips is a reliable answer.</p><h3>The code</h3><p>The forest is a thin wrapper around last article’s trees. It keeps a list of them, feeds each one a bootstrapped copy plus a random feature budget, and combines their answers into a single prediction. The classifier counts votes. The constructor is short, so do not blink.</p><pre>import numpy as np<br>from models.decision_tree_classifier import DecisionTreeClassifier<br> <br> <br>class RandomForestClassifier:<br>    def __init__(self, n_estimators=100, max_depth=5, min_samples_split=5, max_features=&#39;sqrt&#39;):<br>        self.n_estimators = n_estimators # Refers to how many trees to build<br>        self.max_depth = max_depth<br>        self.min_samples_split = min_samples_split<br>        self.max_features = max_features<br>        self.trees = [] # Will hold the trees<br> <br> <br>    def fit(self, X, y):<br>        self.trees = []<br>        n_samples, n_features = X.shape<br> <br>        # Same conversion as sklearn in terms of determining the max number of features<br>        if self.max_features == &quot;sqrt&quot;:<br>            max_feat = int(np.sqrt(n_features))<br>        else:<br>            max_feat = self.max_features<br> <br>        for _ in range(self.n_estimators):<br>            # Bootstrap sampling<br>            bootstrap_idx = np.random.choice(n_samples, size=n_samples, replace=True)<br>            X_sample, y_sample = X[bootstrap_idx], y[bootstrap_idx]<br> <br>            # Feature subsetting which happens inside the tree&#39;s own splits<br>            tree = DecisionTreeClassifier(<br>                max_depth = self.max_depth,<br>                min_samples_split=self.min_samples_split,<br>                max_features=max_feat<br>            )<br>            tree.fit(X_sample, y_sample)<br>            self.trees.append(tree)<br> <br> <br>    def predict(self, X):<br>        # All trees makes their own prediction for every sample<br>        # Should return a 2d array (n_trees, n_patients)<br>        all_predictions = np.array([tree.predict(X) for tree in self.trees])<br> <br>        # For each sample, find the most common prediction across trees<br>        final_predictions = []<br>        for i in range(X.shape[0]):<br>            votes = all_predictions[:, i]<br>            values, counts = np.unique(votes, return_counts=True)<br>            final_predictions.append(values[np.argmax(counts)])<br> <br>        return np.array(final_predictions)</pre><p>The regressor is the same class with one line swapped: instead of counting votes it takes the mean of the trees’ numbers. Majority for classes, average for numbers, exactly the two leaf rules from the last article.</p><pre>import numpy as np<br>from models.decision_tree_regressor import DecisionTreeRegressor<br> <br> <br>class RandomForestRegressor:<br>    def __init__(self, n_estimators=100, max_depth=5, min_samples_split=5, max_features=&#39;sqrt&#39;):<br>        self.n_estimators = n_estimators # Refers to how many trees to build<br>        self.max_depth = max_depth<br>        self.min_samples_split = min_samples_split<br>        self.max_features = max_features<br>        self.trees = [] # Will hold the trees<br> <br> <br>    def fit(self, X, y):<br>        self.trees = []<br>        n_samples, n_features = X.shape<br> <br>        # Same conversion as sklearn in terms of determining the max number of features<br>        if self.max_features == &quot;sqrt&quot;:<br>            max_feat = int(np.sqrt(n_features))<br>        else:<br>            max_feat = self.max_features<br> <br>        for _ in range(self.n_estimators):<br>            # Bootstrap sampling<br>            bootstrap_idx = np.random.choice(n_samples, size=n_samples, replace=True)<br>            X_sample, y_sample = X[bootstrap_idx], y[bootstrap_idx]<br> <br>            # Feature subsetting which happens inside the tree&#39;s own splits<br>            tree = DecisionTreeRegressor(<br>                max_depth = self.max_depth,<br>                min_samples_split=self.min_samples_split,<br>                max_features=max_feat<br>            )<br>            tree.fit(X_sample, y_sample)<br>            self.trees.append(tree)<br> <br> <br>    def predict(self, X):<br>        # All trees makes their own prediction for every sample<br>        # Should return a 2d array (n_trees, n_patients)<br>        all_predictions = np.array([tree.predict(X) for tree in self.trees])<br> <br>        # average across trees per sample (in this case per patient/column)<br>        return np.mean(all_predictions, axis=0)</pre><p>That is the whole model. There is no new learning rule and no new math, the greedy search from the last article did all of the learning. We simply ran it a few hundred times on different copies and combined the answers.</p><h3>Now it is time to test it: classification</h3><p>Back to the Pima dataset, same cleaning, same split, same hyperparameters as the winning tree from last article, with n_estimators=200. Our forest goes head to head with scikit-learn’s.</p><pre>import numpy as np<br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestClassifier as SkRF<br>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score<br> <br>from models.random_forest_classifier import RandomForestClassifier<br> <br>df = pd.read_csv(&#39;../data/pima_diabetes_classification.csv&#39;)<br> <br>train_df, test_df = train_test_split(df, test_size=0.2, random_state=42,<br>                                     stratify=df[&#39;outcome&#39;])<br> <br># Replace hidden zeros (impossible values) with median estimates before training<br>for col in [&#39;glucose&#39;, &#39;blood_pressure&#39;, &#39;bmi&#39;]:<br>    med = train_df.loc[train_df[col] != 0, col].median()<br>    train_df[col] = train_df[col].replace(0, med)<br>    test_df[col] = test_df[col].replace(0, med)<br> <br>for col in [&#39;insulin&#39;, &#39;skin_thickness&#39;]:<br>    meds = train_df.loc[train_df[col] != 0, col].groupby(train_df[&#39;outcome&#39;]).median()<br>    train_df[col] = train_df.apply(lambda r: meds[r[&#39;outcome&#39;]] if r[col] == 0 else r[col], axis=1)<br>    test_df[col] = test_df.apply(lambda r: meds[r[&#39;outcome&#39;]] if r[col] == 0 else r[col], axis=1)<br> <br>feature_cols = [c for c in df.columns if c != &#39;outcome&#39;]<br>X_train = train_df[feature_cols].values<br>X_test = test_df[feature_cols].values<br>y_train = train_df[&#39;outcome&#39;].values<br>y_test = test_df[&#39;outcome&#39;].values<br> <br># Our implementation from scratch<br>custom = RandomForestClassifier(n_estimators=200, max_depth=5,<br>                                min_samples_split=5, max_features=&#39;sqrt&#39;)<br>custom.fit(X_train, y_train)<br>custom_preds = custom.predict(X_test)<br> <br># scikit-learn for comparison<br>sk = SkRF(n_estimators=200, max_depth=5, min_samples_split=5,<br>          max_features=&#39;sqrt&#39;, random_state=42)<br>sk.fit(X_train, y_train)<br>sk_preds = sk.predict(X_test)<br> <br>def report(name, y_true, y_pred):<br>    acc = accuracy_score(y_true, y_pred)<br>    prec = precision_score(y_true, y_pred)<br>    rec = recall_score(y_true, y_pred)<br>    f1 = f1_score(y_true, y_pred)<br>    print(&quot;{name:20s} Acc={acc:.3f}  Prec={prec:.3f}  Rec={rec:.3f}  F1={f1:.3f}&quot;.format(<br>        name=name, acc=acc, prec=prec, rec=rec, f1=f1))<br> <br>report(&#39;From-scratch RF&#39;, y_test, custom_preds)<br>report(&#39;scikit-learn RF&#39;, y_test, sk_preds)</pre><p>The result:</p><pre>From-scratch RF        Acc=0.857  Prec=0.796  Rec=0.796  F1=0.796<br>scikit-learn RF        Acc=0.857  Prec=0.808  Rec=0.778  F1=0.792</pre><p>The forest lands at 0.857 accuracy, up from 0.812 for the lone tree. But more importantly, the recall is 0.796 versus 0.722. For every ten patients who actually have diabetes, the forest catches about eight, whereas the tree caught seven. Fewer sick people slip through, and the forest gives up nothing to get there, precision and F1 move up too. That is overfitting leaving through the back door.</p><h3>And the regression hat</h3><p>Flip the hat and the moral does not change. Same 200 trees, same depth, target now disease_progression.</p><pre>import numpy as np<br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestRegressor as SkRF<br>from sklearn.metrics import r2_score, mean_squared_error<br> <br>from models.random_forest_regressor import RandomForestRegressor<br> <br>df = pd.read_csv(&#39;../data/diabetes_progression.csv&#39;)<br>df.drop(columns=&#39;ldl_cholesterol&#39;, inplace=True)<br> <br>train_df, test_df = train_test_split(df, test_size=0.2, random_state=42)<br> <br>feature_cols = [c for c in df.columns if c != &#39;disease_progression&#39;]<br>X_train = train_df[feature_cols].values<br>X_test = test_df[feature_cols].values<br>y_train = train_df[&#39;disease_progression&#39;].values<br>y_test = test_df[&#39;disease_progression&#39;].values<br> <br># Our implementation from scratch<br>custom = RandomForestRegressor(n_estimators=200, max_depth=5,<br>                               min_samples_split=5, max_features=&#39;sqrt&#39;)<br>custom.fit(X_train, y_train)<br>custom_preds = custom.predict(X_test)<br> <br># scikit-learn for comparison<br>sk = SkRF(n_estimators=200, max_depth=5, min_samples_split=5,<br>          max_features=&#39;sqrt&#39;, random_state=42)<br>sk.fit(X_train, y_train)<br>sk_preds = sk.predict(X_test)<br> <br>def report(name, y_true, y_pred):<br>    r2 = r2_score(y_true, y_pred)<br>    rmse = np.sqrt(mean_squared_error(y_true, y_pred))<br>    print(&quot;{name:20s} R²={r2:.4f}  RMSE={rmse:.2f}&quot;.format(<br>        name=name, r2=r2, rmse=rmse))<br> <br>report(&#39;From-scratch RF&#39;, y_test, custom_preds)<br>report(&#39;scikit-learn RF&#39;, y_test, sk_preds)</pre><p>The result:</p><pre>From-scratch RF        R²=0.4784  RMSE=52.57<br>scikit-learn RF        R²=0.4639  RMSE=53.29</pre><p>Last article admitted the tree embarrassed itself on regression, 0.32, trailing linear regression’s 0.45. The forest answers the call: 0.4784, comfortably ahead of the line. The errors shrink too, RMSE down from 59.90 to 52.57.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*LAre7tUCmtPjYAZQ3pC1-Q.png" /></figure><p>One asterisk before we move on: the from-scratch forest leaves its randomness unseeded; there is no random_state inside it, so re-running it may wiggle the last digits by a hair. That is the point, not a bug. The randomness between trees is exactly what makes the committee work. scikit-learn seeds that randomness with random_state=42, so its digits stay fixed.</p><h3>Conclusion</h3><p>The forest added no algebra and no gradient, just a list of trees and a vote, and every row of the table moved in our favor. That is the whole point of the technique, and the summary is short: a memorizing tree becomes a reliable committee.</p><p>And there you go. The last article’s model was a flowchart; this one is a parliament of flowcharts. The greedy splitting, the recursion, the leaf rules, all untouched. The only new ingredients are bootstrapped copies, random feature subsets, and a final vote, about ten lines of bookkeeping.</p><p>The series keeps compounding. Read the source of one model, and every model after it is a variation on something you already own. The tree and its forest share split logic; the neural network next in line shares the gradient descent we built two articles ago.</p><p>If one thing clicked that did not before, the forest did its job. Thanks for reading, clap if it helped, and I will see you in the next one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*n_VwITGx-v45co1z6DrQzA.gif" /></figure><p>Access the complete code implementation for this project on GitHub <a href="https://github.com/Stephen-Echessa/diabetes_ml_project_backend/blob/master/models/random_forest_regressor.py">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b3cc3e3de0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML Basics 103: Building Decision Trees from scratch using Python]]></title>
            <link>https://medium.com/@stevechesa/ml-basics-103-building-decision-trees-from-scratch-using-python-cbede9490f61?source=rss-b4204b4fc55c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbede9490f61</guid>
            <category><![CDATA[decision-tree-algorithm]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Stephen Echessa]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 04:21:51 GMT</pubDate>
            <atom:updated>2026-09-27T04:21:51.584Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>A practical guide to how trees split data into clean groups, from Gini impurity and sum of squared errors to a working Python implementation.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*4iQ_dmKwxwYS1D4hWtCrcA.jpeg" /></figure><p>Hello, and welcome back to my ML Basics series.</p><p>In the last two articles we built a Linear Regression model and a Logistic Regression model from scratch, and watched each one match scikit-learn. Along the way we leaned on gradient descent, on derivatives, and on a cost function shaped like a smooth bowl. Today we are changing the game completely: no weights, no learning rate, no gradient. Today we build a Decision Tree.</p><p>A Decision Tree is the most human algorithm in machine learning. It asks questions. Is this patient’s glucose above 127? Answer yes, go this way. Is their body mass index below 30? Answer no, go that way. It is a flowchart that learns to split data into ever cleaner groups, and it works for classification and regression alike, with almost no changes between the two. So stay tuned as we unravel the inner workings of the model and enable you, the reader, to understand its true capabilities.</p><h3>Let us define a Decision Tree</h3><p>Despite the intimidating name, a Decision Tree is one of the simplest models you will ever meet. Prediction is just a walk: start at the top, answer a yes or no question, follow the branch, and repeat until you land on an answer box, which we call a leaf. Each leaf forecasts an outcome, a 0 or 1 for classification, a number for regression. There is no probability math, no matrix multiplication, no activation function. A tree is the 20 questions game of machine learning, pure logic, and walls of if statements you could almost write by hand.</p><p>But we do not write those rules ourselves. Hand-coding questions for eight medical features and six hundred patients is hopeless. The tree must discover, on its own, which question to ask at every fork of the path, and that discovery process has a name: splitting. Let us look at a baby version before we build our own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDnBk5XYprQkplpAicLwnw.png" /><figcaption>A decision tree is a flowchart of yes/no questions. Yes answers go left, no answers go right. Follow the highlighted path with one patient: glucose is 140, above the threshold, so the answer is no, and the walk continues down the right side to a prediction.</figcaption></figure><p>Every split picks one feature and one threshold, and answers a single question: is the value of this feature above the threshold? The data flows left or right, and each side becomes its own little problem. Split that side again, and again, and again, and the tree grows until the groups are small or pure enough to trust. Our job, just like every other model in this series, is to find the parameters that make the best groups, and here the parameters are the (feature, threshold) pairs stacked up as the tree grows.</p><p>Everything we have said so far, the flowchart, the walk, the split, is the base decision tree, word for word identical for both variants. The classifier and the regressor are the same tree with only two small things changed: how a split is judged as good, and what a leaf finally says out loud. Both of those are decided by a cost function, so let us look at that cost function twice, once per hat, starting with the classifier.</p><h3>The Split Cost for classification: the Gini impurity</h3><p>In the last two articles the cost was one number attached to the whole model, mean squared error or log loss, and gradient descent pushed parameters downhill to minimize it. A tree has no parameter vector and no slope to descend, so it uses a different kind of cost, applied locally at every candidate split: how impure are the two groups that the split creates? By pure I mean that every sample in the group wears the same label, all diabetic or all non-diabetic, so the impurity is zero. Impure means a mix of both, and the deeper the tangle sinks toward a 50/50 split, the higher the impurity climbs. The best split is simply the one that produces the two most pure groups.</p><p>For classification, the classic measure is the Gini impurity. Imagine labeling a sample at random based only on the class proportions in the group. If the group contains one class only, the label would always be correct, which is perfectly pure, impurity 0. If the group is a coin flip, half the time the label will be wrong, which is as impure as it gets. For a group split across k classes, the Gini impurity is the total probability of mislabeling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*iG7lHLrRaK-d4lxfhqqL6Q.png" /><figcaption>Where p_k is the proportion of class k.</figcaption></figure><p>The curve starts at zero when the group is pure, peaks right in the middle at a 50/50 split, and comes back down to zero. It is the perfect yardstick for how torn a group is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNOitbuq_8MNAKAS8LW52w.png" /><figcaption>Gini impurity is at its worst when a group is split exactly in half, and drops to zero when one class takes over completely.</figcaption></figure><p>Let us compute it by hand, on a small made-up node with six patients from the Pima story: four without diabetes (A, B, C, D) and two with diabetes (E, F). The proportions are p0 = 4/6 and p1 = 2/6, so the node’s Gini is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*R6q6Eq7u2YvUXBzJWMhFsA.png" /></figure><p>Now pretend the tree is pondering three candidate questions for this node. Each question splits the six patients in a different way, and the split’s total cost is the weighted average of the two resulting groups’ impurities, weighted by how many samples land in each group:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*23wqkpdYC2yj8w-7uIVltw.png" /></figure><p>Study the three candidates in the table. The question <em>insulin &lt;= 120</em> crams every diabetic patient into one box and every non-diabetic into the other, so both groups are pure, Gini 0, and the score is a perfect 0. The bmi question leaves a 2/1 mix on each side, Gini 4/9 on both, and a score of 4/9. The age question reaches 0.333. The tree compares the three numbers and picks the lowest, insulin &lt;= 120, which is precisely why the real model, trained on the full data, makes insulin its very first question as we will see in the table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GqVLQYPovAZ1n7p0sIfbuw.png" /></figure><h3>The Split Cost for regression: sum of squared errors</h3><p>The regression twin of the tree shares the shape but swaps the ruler. There are no classes to count here. Instead there is a list of numbers, the progression scores, and the question is how tight a group is around its own center. The ruler is the sum of squared errors (SSE) of each group, how far each value sits from its group’s average, added up over both groups:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*2rrnq9hj_SaUaEE4ndnmIw.png" /></figure><p>Again, lower is better. If a split herds the small scores into one leaf and the large scores into another, both leaves become tight little clusters and the SSE craters. Let us do it by hand on five fictitious progression scores: 90, 120, 140, 155 and 160. Left alone, all five form one leaf whose prediction is the mean, 133, and whose cost is the sum of five squared deviations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oItHVWTz4qqqsMuCY5EVXg.png" /></figure><p>Now split the scores with a candidate question, say bmi &lt;= 30, that sends {90, 120} left and {140, 155, 160} right. The left leaf averages 105 with squared errors 225 + 225, the right leaf averages about 151.7 with squared errors of roughly 136, 11 and 69, so the total cost collapses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*NjztvkOb7yCh_QL7jNDWew.png" /></figure><p>One clean cut took the cost from 3280 down to about 667. A weaker candidate, a feature that leaves low and high scores tangled together, might only manage {90, 140} and {120, 155, 160}, scoring 1250 + 950 = 2200. The tree compares the three totals, 667 versus 2200 versus leaving everyone unsplit at 3280, and keeps the bmi question. Like the classifier, it follows a greedy approach to minimize the cost function.</p><p>And once a regression group is final, its leaf predicts with the average, the one number that sits closest to every sample within that group, keeping the squared error as small as possible. That is the one-sentence reconciliation of everything above: classification minimizes impurity, regression minimizes squared error, and the shared tree just chases whichever number applies.</p><h3>Greedy Search (Finding the best split)</h3><p>How does the tree actually choose its questions? It uses a greedy search. The algorithm evaluates every available feature. For a given feature, it tries every unique value in the dataset as a potential threshold. It splits the data, calculates the Gini Impurity for both sides, and calculates the total impurity reduction. The tree keeps track of the single best (feature, threshold) pair it finds and discards the rest. We call this process “greedy” because the model picks the split that looks best right now without worrying about future steps. This local choice might not yield the absolute best global tree, but every major machine learning framework accepts this trade-off. It keeps training fast while producing a transparent, interpretable model. Under the hood, scikit-learn uses this exact search strategy, which is why our custom implementation will match its outputs.</p><p>One detail makes decision trees refreshingly easy to work with: every decision boils down to a simple comparison. The model only asks one fundamental question at each split: <em>Is feature X greater than threshold Y? </em>Because the exact scale of the numbers does not affect this comparison, preprocessing steps like feature scaling and standardization become completely unnecessary. An age column with values around 25 sits comfortably alongside an insulin column with values in the hundreds. As long as you clean out invalid entries or hidden zeros, the tree handles the raw numbers effortlessly.</p><p>Since the whole model reduces to one economic decision per node, there is really only one result worth deriving: what should a leaf predict once we decide to stop splitting?</p><p>For classification, the answer is that a leaf predicts the most common class among its samples, the majority vote:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*Isph9UxFyK-R2tvJ8vFLPg.png" /></figure><p>For regression, why the average? Because the average is the single number that minimizes the squared error of its group. Because the average is the single number that minimizes the squared error of its group, which is why the code below uses plain np.mean(y):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*sI6M_Qc7OlwgF0Zhkor13g.png" /></figure><p>With the concepts laid out, we are ready to dive into the code. But before writing our first line, here is a quick thought experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*xJu4my0Xagb_7iU3cm1xVw.jpeg" /></figure><h3>The Code Implementation</h3><p>Our implementation strategy follows a clean, object-oriented design: we will construct a core base decision tree class first. Once that foundation is in place, we will build dedicated classifier and regressor classes that inherit directly from it.</p><p>First, the box. One box in the tree is either a question box or an answer box, never both. The left child is the branch taken when the answer is yes, meaning the feature value is at most the threshold, and the right child is the no branch.</p><pre>import numpy as np<br> <br>class Node:<br>    def __init__(self, feature_idx=None, threshold=None,<br>                 left=None, right=None, value=None):<br>        self.feature_idx = feature_idx<br>        self.threshold = threshold<br>        self.left = left<br>        self.right = right<br>        <br>        # If this node is a leaf, only this gets filled in<br>        self.value = value <br>     <br>    def is_leaf(self):<br>        # A node is a leaf only if it has its value set<br>        return self.value is not None </pre><p>Next, the shared skeleton. The constructor keeps the settings: how deep the tree may grow, the smallest group we will allow ourselves to split further, and max_features, a hook that Random Forests will use later to pick a random subset of features at every node.</p><pre>class BaseDecisionTree:<br>    def __init__(self, max_depth=5, min_samples_split=2, max_features=None):<br>        self.max_depth = max_depth<br>        self.min_samples_split = min_samples_split<br>        self.max_features = max_features <br>        self.root = None # Holds the very first Node once fit() has been called<br> <br>    def _best_split(self, X, y):<br>        # Tries every feature, and for each feature, every observed value of that feature is used as a candidate threshold<br>        best_score = float(&quot;inf&quot;)<br>        best_feature_idx = None<br>        best_threshold = None<br>        n_samples, n_features = X.shape<br> <br>        # Consider every feature for use by a base decision tree<br>        if self.max_features is None:<br>            feature_indices = range(n_features)<br><br>        # Select a random subset of features for use by random forest, this can be ignored for now<br>        else:<br>            feature_indices = np.random.choice(<br>                n_features, size=self.max_features, replace=False<br>            )<br> <br>        # Try every feature one at a time<br>        # Find the unique values within the feature, and with each to act as a threshold<br>        for feature_idx in feature_indices:<br>            thresholds = np.unique(X[:, feature_idx])<br> <br>            for threshold in thresholds:<br>                # Split data into low and high groups based on this threshold<br>                left_mask = X[:, feature_idx] &lt;= threshold<br>                right_mask = ~left_mask<br>                 <br>                # If a split does not separate anyone whereby everyone went to one side, skip it<br>                if left_mask.sum() == 0 or right_mask.sum() == 0:<br>                    continue<br>    <br>                left_y, right_y = y[left_mask], y[right_mask]<br>                score = self._split_score(left_y, right_y)<br> <br>                # If this is the best split we&#39;ve seen so far, remember it<br>                if score &lt; best_score:<br>                    best_score = score<br>                    best_feature_idx = feature_idx<br>                    best_threshold = threshold<br> <br>        return best_score, best_feature_idx, best_threshold</pre><p>For every feature, every one of its unique values is a candidate threshold. We split, score, and keep the pair with the lowest score. Notice it calls a method, _split_score, that is not defined here. That is the first blank the subclasses will fill, each with their own idea of what a good split looks like.</p><p>Now the recursion. Building a tree is a matter of finding the best question, splitting the data in half, and repeating the whole ritual on each half. The recursion also needs three stop signs: we have hit max_depth, the group is smaller than min_samples_split, or no split can separate the remaining samples because they are all identical.</p><pre>    def _build_tree(self, X, y, depth):<br>        n_samples = len(y)<br>         <br>        # If any of these are true, stop splitting and make this a leaf<br>        # We should not go any deeper than the max depth, which in our case is <br>        if depth &gt;= self.max_depth:<br>            return Node(value=self._leaf_value(y))<br> <br>        if n_samples &lt; self.min_samples_split:<br>            return Node(value=self._leaf_value(y))<br> <br>        # Otherwise, try to find the best question to ask here<br>        score, feature_idx, threshold = self._best_split(X, y)<br> <br>        # If no split separates the data, we have to stop (every remaining sample is identical), we have to stop<br>        if feature_idx is None:<br>            return Node(value=self._leaf_value(y))<br> <br>        # A good split has been found, now split the data accordingly<br>        left_mask = X[:, feature_idx] &lt;= threshold<br>        right_mask = ~left_mask<br> <br>        # Here is the recursion<br>        left_child = self._build_tree(X[left_mask], y[left_mask], depth + 1)<br>        right_child = self._build_tree(X[right_mask], y[right_mask], depth + 1)<br> <br>        # Returns a question box, pointing to the two children we built.<br>        return Node(feature_idx=feature_idx, threshold=threshold,<br>                    left=left_child, right=right_child)<br> <br>    def fit(self, X, y):<br>        self.root = self._build_tree(X, y, depth=0)<br> <br>    def predict(self, X):<br>        # Predict each row one at a time, by walking down the tree<br>        return np.array([self._traverse(x, self.root) for x in X])<br><br>    def _traverse(self, x, node):<br>        # If we&#39;ve reached an answer box (leaf), we are done<br>        if node.is_leaf():<br>            return node.value<br>   <br>        # Otherwise, we&#39;re at a question box. Check the answer by following the corresponding path (walking down the tree)<br>        if x[node.feature_idx] &lt;= node.threshold:<br>            return self._traverse(x, node.left)<br><br>        return self._traverse(x, node.right)</pre><p>_leaf_value() is the second blank our subclasses will fill. Fit grows the tree from the root. Predict walks each row down, one question at a time, until it lands on an answer box.</p><p>That is the entire base tree. Now we dress it up. The classifier fills the two blanks for classification: it predicts the majority class of a group, and scores a split by the weighted Gini impurity of the two groups it creates, exactly the formula we worked through on the six patients.</p><pre>class DecisionTreeClassifier(BaseDecisionTree):<br>    def _leaf_value(self, y):<br>        # What this leaf will predict by selecting the class that appears the most<br>        values, counts = np.unique(y, return_counts=True)<br>        return values[np.argmax(counts)]<br> <br>    def _split_score(self, left_y, right_y):<br>        # Weighted average of Gini impurity of the two resulting groups. Lower is better<br>        # (|left_y|/n * Gini(left_y)) + (|right_y|/n * Gini(right_y))<br>        n = len(left_y) + len(right_y)<br> <br>        return (<br>            (len(left_y) / n) * self._gini(left_y) +<br>            (len(right_y) / n) * self._gini(right_y)<br>        )<br> <br>    def _gini(self, y):<br>        # Gini impurity = 1 - sum of (proportion of class)²<br>        if len(y) == 0:<br>            return 0<br>        proportions = np.array([np.sum(y == c) for c in np.unique(y)]) / len(y)<br>        return 1 - np.sum(proportions ** 2)</pre><p>And the regressor fills the exact same two blanks with the cost function for regression: a leaf predicts the mean of its samples, and a split is scored by the sum of the squared errors of its two groups, the SSE we computed on the five progression scores. That single inheritance line is the whole difference between the two hats.</p><pre>class DecisionTreeRegressor(BaseDecisionTree):<br>    def _leaf_value(self, y):<br>        # What this leaf will predict by getting average value of y<br>        return np.mean(y)<br> <br>    def _split_score(self, left_y, right_y):<br>        # Gets the sum of the squared error of both groups<br>        left_sse = (np.sum((left_y - np.mean(left_y)) ** 2)<br>                    if len(left_y) &gt; 0 else 0)<br>        right_sse = (np.sum((right_y - np.mean(right_y)) ** 2)<br>                     if len(right_y) &gt; 0 else 0)<br>        return left_sse + right_sse</pre><p>That is the entire model.</p><p>Time to wire it up for classification, on the Pima Indians diabetes dataset from the last article. We clean the hidden zeros, split into train and test, train, and compare head to head with scikit-learn. Notice the features are NOT standardized this time. A tree only cares if a certain value is above a threshold, so scaling is a waste of effort, a hint that trees eat differently from gradient models.</p><pre>import numpy as np<br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.tree import DecisionTreeClassifier as SklearnDecisionTree<br>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score<br> <br>from models.decision_tree_classifier import DecisionTreeClassifier<br> <br>df = pd.read_csv(&#39;../data/pima_diabetes_classification.csv&#39;)<br> <br>train_df, test_df = train_test_split(df, test_size=0.2, random_state=42,<br>                                     stratify=df[&#39;outcome&#39;])<br> <br># Replace hidden zeros (impossible values) with median estimates before training<br>for col in [&#39;glucose&#39;, &#39;blood_pressure&#39;, &#39;bmi&#39;]:<br>    med = train_df.loc[train_df[col] != 0, col].median()<br>    train_df[col] = train_df[col].replace(0, med)<br>    test_df[col] = test_df[col].replace(0, med)<br> <br>for col in [&#39;insulin&#39;, &#39;skin_thickness&#39;]:<br>    meds = train_df.loc[train_df[col] != 0, col].groupby(train_df[&#39;outcome&#39;]).median()<br>    train_df[col] = train_df.apply(lambda r: meds[r[&#39;outcome&#39;]] if r[col] == 0 else r[col], axis=1)<br>    test_df[col] = test_df.apply(lambda r: meds[r[&#39;outcome&#39;]] if r[col] == 0 else r[col], axis=1)<br> <br>feature_cols = [c for c in df.columns if c != &#39;outcome&#39;]<br>X_train = train_df[feature_cols].values<br>X_test = test_df[feature_cols].values<br>y_train = train_df[&#39;outcome&#39;].values<br>y_test = test_df[&#39;outcome&#39;].values<br> <br># Our implementation from scratch<br>custom = DecisionTreeClassifier(max_depth=5, min_samples_split=5)<br>custom.fit(X_train, y_train)<br>custom_preds = custom.predict(X_test)<br> <br># scikit-learn for comparison<br>sk = SklearnDecisionTree(max_depth=5, min_samples_split=5,<br>                         criterion=&#39;gini&#39;, random_state=42)<br>sk.fit(X_train, y_train)<br>sk_preds = sk.predict(X_test)<br> <br>def report(name, y_true, y_pred):<br>    acc = accuracy_score(y_true, y_pred)<br>    prec = precision_score(y_true, y_pred)<br>    rec = recall_score(y_true, y_pred)<br>    f1 = f1_score(y_true, y_pred)<br>    print(&quot;{name:20s} Acc={acc:.3f}  Prec={prec:.3f}  Rec={rec:.3f}  F1={f1:.3f}&quot;.format(<br>        name=name, acc=acc, prec=prec, rec=rec, f1=f1))<br> <br>report(&#39;From-scratch Tree&#39;, y_test, custom_preds)<br>report(&#39;scikit-learn Tree&#39;, y_test, sk_preds)</pre><p>After running it, the output should look like this:</p><pre>From-scratch Tree    Acc=0.812  Prec=0.736  Rec=0.722  F1=0.729<br>scikit-learn Tree    Acc=0.818  Prec=0.750  Rec=0.722  F1=0.736</pre><p>Look at that. With barely any effort the tree beats the Logistic Regression accuracy from the last article on the same test set, 0.812 versus 0.714, and recall matches scikit-learn down to the third decimal. Two models that agree to three decimals on recall are two models doing the same search, which is the reward for building from scratch.</p><p>Now let’s wear the regression hat. The target is disease_progression, a number, from the diabetes progression dataset. Same hyperparameters, same random_state, raw features, no scaling.</p><pre>import numpy as np<br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.tree import DecisionTreeRegressor as SklearnDecisionTree<br>from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error<br> <br>from models.decision_tree_regressor import DecisionTreeRegressor<br> <br>df = pd.read_csv(&#39;../data/diabetes_progression.csv&#39;)<br>df.drop(columns=&#39;ldl_cholesterol&#39;, inplace=True)<br> <br>train_df, test_df = train_test_split(df, test_size=0.2, random_state=42)<br> <br>feature_cols = [c for c in df.columns if c != &#39;disease_progression&#39;]<br>X_train = train_df[feature_cols].values<br>X_test = test_df[feature_cols].values<br>y_train = train_df[&#39;disease_progression&#39;].values<br>y_test = test_df[&#39;disease_progression&#39;].values<br> <br># Our implementation from scratch<br>custom = DecisionTreeRegressor(max_depth=5, min_samples_split=5)<br>custom.fit(X_train, y_train)<br>custom_preds = custom.predict(X_test)<br> <br># scikit-learn for comparison<br>sk = SklearnDecisionTree(max_depth=5, min_samples_split=5, random_state=42)<br>sk.fit(X_train, y_train)<br>sk_preds = sk.predict(X_test)<br> <br>def report(name, y_true, y_pred):<br>    r2 = r2_score(y_true, y_pred)<br>    rmse = np.sqrt(mean_squared_error(y_true, y_pred))<br>    mae = mean_absolute_error(y_true, y_pred)<br>    print(&quot;{name:20s} R²={r2:.4f}  RMSE={rmse:.2f}  MAE={mae:.2f}&quot;.format(<br>        name=name, r2=r2, rmse=rmse, mae=mae))<br> <br>report(&#39;From-scratch Tree&#39;, y_test, custom_preds)<br>report(&#39;scikit-learn Tree&#39;, y_test, sk_preds)</pre><p>And the output:</p><pre>From-scratch Tree    R²=0.3228  RMSE=59.90  MAE=46.67<br>scikit-learn Tree    R²=0.3264  RMSE=59.74  MAE=46.54</pre><p>It performs nearly identically to scikit-learn once again. On this regression task, however, the tree falls behind our Linear Regression model: it explains about 32% of the variance, whereas linear regression explained about 45% on the exact same patient files. This highlights a fundamental truth in machine learning: no single model excels on every dataset. It is always up to the practitioner to experiment with different algorithms and evaluate which one delivers the optimal balance of bias and variance. The good news for us is that in the next article, we will explore how Random Forests build upon decision trees to dramatically improve these results.</p><h3>Conclusion</h3><p>And there it is. Decision Trees from scratch, and results that match scikit-learn on both classification and regression. The tree’s entire engine is a greedy search and a little recursion.</p><p>But the beautiful payoff of the series keeps compounding. Once you can read a model’s source, you see it for what it is. A tree is a flowchart. Nothing more, nothing less. Its power comes from the quiet design decision to ask questions greedily and ask them everywhere, and its weakness is exactly that same naivety, which in various cases leads to it overfitting. That weakness is where we go next. Next up in the series, we turn one tree into a forest. Random Forests.</p><p>Thanks for reading, clap if it helped, and I will see you in the next one.</p><p>Access the complete code implementation for this project on GitHub <a href="https://github.com/Stephen-Echessa/diabetes_ml_project_backend/blob/master/models/base_decision_tree.py">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbede9490f61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML Basics 102: Building a Logistic Regression model from scratch using Python]]></title>
            <link>https://medium.com/@stevechesa/ml-basics-102-building-a-logistic-regression-model-from-scratch-using-python-beca202cca8c?source=rss-b4204b4fc55c------2</link>
            <guid isPermaLink="false">https://medium.com/p/beca202cca8c</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Stephen Echessa]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 15:16:34 GMT</pubDate>
            <atom:updated>2026-09-21T15:16:34.809Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>A practical guide to how classification works under the hood, from basic probability math to a working Python implementation.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*yS-u5GRa7boMYQV4_tczVw.jpeg" /></figure><p>Hello, and welcome back to my ML Basics series.</p><p>In the last article we built a Linear Regression model from scratch, NumPy only, and watched two different roads lead to the exact same answer as scikit-learn. Today we are leveling up: instead of predicting numbers, we will predict categories.</p><p>Logistic Regression is the natural next step. It is the classification cousin of the model we already built, and the journey from one to the other is surprisingly short. Stick with me, because the pieces fit together in a beautiful way.</p><h3>So, let&#39;s define Logistic Regression</h3><p>Despite the intimidating name, Logistic Regression is a classification algorithm, not a regression one. Instead of predicting a number, it answers a yes or no question and gives us a probability along the way. Will I be totally screwed by the end of the week based on my account balance? Will this email be flagged as spam? Will this patient be diagnosed with diabetes? Is this transaction fraudulent? Spam or not, positive or negative, two classes. That is binary classification, and it is everywhere.</p><p>So why can’t we just reuse Linear Regression for this? Because of two problems. First, a straight line can shoot below 0 or above 1, and probabilities outside the range 0 to 1 simply do not make sense. Second, a straight line cannot bend around clustered data the way a decision boundary needs to. We need a function that takes any input, however big or small, and squeezes it into the range between 0 and 1. That function is the sigmoid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*ouy5GIICWaROne5IP3l7pQ.png" /><figcaption>The sigmoid function</figcaption></figure><p>Feed z through the sigmoid and out comes y_hat, a probability between 0 and 1. When z is very negative, y_hat approaches 0. When z is very positive, y_hat approaches 1. Right in the middle, at z = 0, y_hat is exactly 0.5, and that point splits our two classes. So the final decision rule is delightfully simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*4u45ZaCf70BT0ss6Fg_HSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGxEDxH_5luhCP01bzcYuA.png" /><figcaption>Any score z gets squeezed into a probability between 0 and 1, and the 0.5 threshold becomes our decision boundary.</figcaption></figure><p><em>T</em>he decision boundary is the tipping point where a prediction flips from one class to another. Right at this cutoff, the model is completely split 50/50 and totally unsure which side to pick.</p><p>Our job, just like last time, is to find the weights w and the bias b that make y_hat as close as possible to the true labels.</p><h3>The Cost Function</h3><p>In the Linear Regression article, our cost was the Mean Squared Error, and it worked beautifully because the prediction came from a straight line. Here the sigmoid changes the game. If we plugged probabilities into MSE, the cost surface would stop being a smooth single valley and turn into a bumpy rollercoaster with false valleys everywhere. Gradient Descent could fall into one of those valleys and convince itself it was done. We want a cost function that stays convex, one nice bowl, for logistic regression, and that function is Binary Cross-Entropy, also called log loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6duKRGuLhnxA7Nl6ohDc5Q.png" /></figure><p>The intuition is refreshingly simple. For each sample there are two cases. If the true label is 1, we pay a penalty of minus the log of our predicted probability. If the true label is 0, we pay minus the log of the probability we assigned to class 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*un4WFTYOTKH6XKI0aa4DgA.png" /><figcaption><em>We write ln here to explicitly show we are using the natural logarithm with base e, though in standard machine learning literature this is often written simply as log, matching Python’s </em><em>np.log() function.</em></figcaption></figure><p>Why the logarithm? Because it punishes confident mistakes brutally. If the true label is 1 and we predicted a probability of 0.99, the penalty is tiny. If we predicted 0.01 instead, the penalty explodes toward infinity. The model is forced to be both right and confident. Averaging this over every sample gives the full cost function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*HVaTIqIvy3uQgKxzZRbiSg.png" /></figure><p>The negative sign in front is there because a logarithm of a probability is never positive, so the minus flips everything into a positive number that we can then minimize. One practical gotcha: if a prediction lands exactly at 0 or 1, we take the log of zero, which the computer refuses to do. So, we sneak in a tiny epsilon, like 1<em>e-12</em>, to keep the math safe. You will see it in the code.</p><h3>Gradient Descent</h3><p>You might be looking for a closed-form shortcut here, similar to the Normal Equation we used in Linear Regression. However, Logistic Regression doesn’t have one.</p><p>Quadratic cost functions in Linear Regression make it easy to set the gradient to zero and isolate <em>w</em> algebraically. With Logistic Regression, the sigmoid function introduces non-linearity that traps <em>w</em> inside an exponent. Setting the derivative to zero leaves us with an equation that cannot be solved directly.</p><p>Our only practical path forward is iterative optimization via Gradient Descent.</p><h4>Deriving the gradient</h4><p>Same philosophy as last time: the derivative is our compass; it tells us which direction the cost goes down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*9MNjq_Bwf7aEoQNZbQziNw.png" /></figure><p>The derivative of the sigmoid is simply the sigmoid itself multiplied by one minus itself.</p><p>When we apply the chain rule starting from the outer log loss and peeling inward through the sigmoid, the algebraic terms cancel out completely. The resulting gradient for every weight takes a familiar form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*cvPOwbeNSjEO2ZL0fB2jiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*FergvymItp90FBGzwP_AZg.png" /></figure><p>Because the gradient points in the direction of steepest ascent, we step in the opposite direction to minimize cost. We scale this step by our learning rate 𝛼 and update our parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*Yf2bCqPaDRbgwGxIH7lfgw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*Ph0Z18z0TuKw1c9xM-md2w.png" /></figure><p>Remarkably, the update rule mirrors Linear Regression exactly. The core optimization engine remains intact; only the prediction mechanism generating y_hat​ has changed.</p><p>With that finally outta the way…</p><h3>Let&#39;s start coding</h3><p>Similar to last time, I have structured everything below as a class so the model stays organized.</p><p>We keep places for the weights, the bias, and a list that records the cost at every step so we can watch it fall later. We also keep the learning rate and the number of iterations.</p><pre>class LogisticRegression:<br>  def __init__(self, learning_rate=0.01, n_iterations=1000):<br>    self.learning_rate = learning_rate<br>    self.n_iterations = n_iterations<br>    self.bias = None<br>    self.weights = []<br>    self.cost_history = []</pre><p>Compute z, then squeeze it through the sigmoid to get a probability.</p><pre>def _compute_sigmoid(self, X):<br>  z = X @ self.weights + self.bias<br>      return 1 / (1 + np.exp(-z))</pre><p>After that, we implement the Binary Cross-Entropy with the tiny epsilon so we never take the log of zero.</p><pre>def _compute_cost(self, X, y, y_hat):<br>  n_samples = X.shape[0]<br>  <br>  epsilon = 1e-12<br>  return (-1 / n_samples) * np.sum(<br>      y * np.log(y_hat + epsilon) + ((1 - y) * np.log(1 - y_hat + epsilon))<br>  )</pre><p>The execution loop is beautifully straightforward; start with parameters at zero, predict probabilities, compute the gradient using our derived formula, nudge the weights, and record the cost. Repeat until convergence.</p><pre>def fit_gradient_descent(self, X, y):<br>  n_samples, n_features = X.shape<br>  self.weights = np.zeros(n_features)<br>  self.bias = 0<br><br>  for _ in range(self.n_iterations):<br>      y_hat = self._compute_sigmoid(X)<br><br>      dw = (1 / n_samples) * ((y_hat - y) @ X)<br>      db = (1 / n_samples) * np.sum(y_hat - y)<br><br>      self.weights -= self.learning_rate * dw<br>      self.bias -= self.learning_rate * db<br><br>      cost = self._compute_cost(X, y, y_hat)<br>      self.cost_history.append(cost)</pre><p>The next step is to turn probabilities into hard class labels by applying the 0.5 threshold. Everything above the threshold becomes class 1; everything below becomes class 0.</p><pre>def predict(self, X, threshold=0.5):<br>  return (self._compute_sigmoid(X) &gt;= threshold).astype(int)</pre><p>Finally, it’s time to wire everything up. We load the Pima Indians diabetes dataset, split it into train and test, standardize the features using only the training set, train our model, and compare it head to head with scikit-learn. Note the hidden zeros in the medical columns get replaced with sensible median values first, a helpful bit of cleaning for this dataset.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LogisticRegression as SklearnLogistic<br>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score<br> <br>from models.logistic_regression import LogisticRegression<br> <br># Classification dataset (Pima Indians diabetes)<br>df = pd.read_csv(&#39;../data/pima_diabetes_classification.csv&#39;)<br> <br>train_df, test_df = train_test_split(df, test_size=0.2, random_state=42,<br>                                     stratify=df[&#39;outcome&#39;])<br> <br># Replace hidden zeros (impossible values) with median estimates before training<br>for col in [&#39;glucose&#39;, &#39;blood_pressure&#39;, &#39;bmi&#39;]:<br>    med = train_df.loc[train_df[col] != 0, col].median()<br>    train_df[col] = train_df[col].replace(0, med)<br>    test_df[col] = test_df[col].replace(0, med)<br> <br>for col in [&#39;insulin&#39;, &#39;skin_thickness&#39;]:<br>    meds = train_df.loc[train_df[col] != 0, col].groupby(train_df[&#39;outcome&#39;]).median()<br>    train_df[col] = train_df.apply(lambda r: meds[r[&#39;outcome&#39;]] if r[col] == 0 else r[col], axis=1)<br>    test_df[col] = test_df.apply(lambda r: meds[r[&#39;outcome&#39;]] if r[col] == 0 else r[col], axis=1)<br> <br>feature_cols = [&#39;pregnancies&#39;, &#39;glucose&#39;, &#39;blood_pressure&#39;, &#39;skin_thickness&#39;,<br>                &#39;insulin&#39;, &#39;bmi&#39;, &#39;diabetes_pedigree&#39;, &#39;age&#39;]<br>X_train_raw = train_df[feature_cols].values<br>X_test_raw = test_df[feature_cols].values<br>y_train = train_df[&#39;outcome&#39;].values<br>y_test = test_df[&#39;outcome&#39;].values<br> <br># Standardize features using only the training set to prevent data leakage<br>mean = X_train_raw.mean(axis=0)<br>std = X_train_raw.std(axis=0) + 1e-12<br>X_train = (X_train_raw - mean) / std<br>X_test = (X_test_raw - mean) / std<br><br># Our implementation from scratch<br>custom = LogisticRegression(learning_rate=0.1, n_iterations=2000)<br>custom.fit_gradient_descent(X_train, y_train)<br>custom_probs = custom._compute_sigmoid(X_test)<br>custom_preds = custom.predict(X_test)<br> <br># scikit-learn for comparison<br>sk = SklearnLogistic(max_iter=2000, solver=&#39;lbfgs&#39;)<br>sk.fit(X_train, y_train)<br>sk_probs = sk.predict_proba(X_test)[:, 1]<br>sk_preds = sk.predict(X_test)<br> <br>def report(name, y_true, y_pred, y_prob):<br>    acc = accuracy_score(y_true, y_pred)<br>    prec = precision_score(y_true, y_pred, zero_division=0)<br>    rec = recall_score(y_true, y_pred, zero_division=0)<br>    f1 = f1_score(y_true, y_pred, zero_division=0)<br>    auc = roc_auc_score(y_true, y_prob)</pre><p>After running it, the output should look like this:</p><pre>Custom Logistic       Acc=0.714  Prec=0.596  Rec=0.574  F1=0.585  AUC=0.830<br>scikit-learn          Acc=0.714  Prec=0.596  Rec=0.574  F1=0.585  AUC=0.830</pre><p>Look at that. Our hand-built model matches scikit-learn down to the third decimal on every single metric. That is the reward for building from scratch: when your numbers line up with the battle-tested library, you know you did the math right.</p><p>Now, we can plot the cost history and watch gradient descent do its thing. The cost starts at a known resting point and slides downhill, steeply at first, then flattening into a plateau as the model settles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5PnRvaky3aMOcQYzNccBqw.png" /></figure><p>The raw accuracy is 0.714, meaning our model gets roughly 71 out of every 100 patients right. Accuracy alone can be misleading though, especially when one class is rarer than the other. Precision asks: Of the patients we labelled as diabetic, how many actually were? Recall asks: Of the patients who actually have diabetes, how many did we manage to catch? F1 balances the two, and AUC measures how well the model separates the classes across all thresholds, not just 0.5. For a dataset like this, a recall of 0.574 means we catch about 57 percent of true positive cases, a number worth improving, and a great hook for the tree-based models we will build next.</p><h3>Conclusion</h3><p>And there it is. Logistic Regression from scratch, running on the Pima diabetes dataset. The two articles share a secret: swap the prediction function, keep the loop. The real unlock of this series is that the learning algorithm itself, gradient descent, is the thing that generalizes across almost all of machine learning. Almost.</p><p>Next up in the series, we take on the tree-based family, Decision Trees and Random Forests, with a few surprises about how they split the data. Then a Neural Network, the model that plays by these exact same rules. Same rules as always: no libraries.</p><p>If one thing clicked today that did not before, this article did its job. Thanks for reading, clap if it helped, and I will see you in the next one.</p><p>Access the complete code implementation for this project on GitHub <a href="https://github.com/Stephen-Echessa/diabetes_ml_project_backend/blob/master/models/logistic_regression.py">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=beca202cca8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML Basics 101: Building a Linear Regression model from scratch using Python]]></title>
            <link>https://medium.com/@stevechesa/ml-basics-101-building-a-linear-regression-model-from-scratch-using-python-d541638b6861?source=rss-b4204b4fc55c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d541638b6861</guid>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[normal-equation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <dc:creator><![CDATA[Stephen Echessa]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 16:24:29 GMT</pubDate>
            <atom:updated>2026-09-16T17:43:15.271Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Demystifying fundamental optimization algorithms by building an end-to-end regression engine without high-level ML libraries.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gnvTYVsbeu-DyPEwkueH_Q.jpeg" /></figure><h3>Introduction</h3><p>Hello, and welcome to my ML Basics series.</p><p>With all the advancements that have been going on in the AI space, it’s easy to get overwhelmed. Even as we find new ways to put these models to work in our products and businesses, LLMs keep on getting sharper. Sharp enough, in fact, to even break the fourth wall, as we saw in the HuggingFace breach. It’s remarkable how far we’ve come. But in the rush to keep up, it’s easy to lose sight of the fundamentals that got us here in the first place. So I took it upon myself to go back to my roots and see if I can implement some of the classic ML models from scratch. No scikit-learn, PyTorch, just numpy and pure math.</p><p>Is this practical? Honestly, not really. Libraries exist for a reason, and in production you should use them. But there’s a real satisfaction in taking something apart and understanding exactly how it works. The same curiosity that drove Newton to wonder how an apple fell on his head. The best way to understand something is to build it yourself.</p><p>So in this tutorial, I will walk you through how to implement Linear Regression from scratch using two methods:<br>1) Gradient Descent<br>2) Normal Equation</p><h3>So what is Linear Regression really?</h3><p>Linear Regression is the simplest and, honestly, one of the most useful ways to predict a number from a set of inputs. Think of predicting a house price from its size or an exam score from hours of study. In every case we assume the same thing; there is a straight line relationship between the input and the outputs.</p><p>For a single input, that straight line is the classic one from school, <em>y = mx + c</em>. Depending on the field or textbook you consult, you will commonly see this relationship written in one of two standard notations:</p><ul><li><strong>Machine Learning Notation:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/113/1*uO59273PQPpXVarng51Erw.png" /></figure><p>Here, <em>w</em> represents the <strong>weight</strong> (slope) and <em>b</em> represents the <strong>bias</strong> (y-intercept).</p><ul><li><strong>Statistics Notation (</strong><em>β</em><strong>):</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*ilH9Fsz18JRyMfSOTq8EgQ.png" /></figure><p>Here, <em>β0</em> is the <strong>intercept</strong> and <em>β1…βn</em> represent the <strong>coefficients </strong>of each input(slope).</p><p>When scaling up to multiple inputs, the underlying idea remains identical. We simply add more terms. Using vector and matrix notation, we group our features into a matrix <em>X</em> and our parameters into a single vector. This allows us to write the entire model as a single, clean matrix multiplication:</p><ul><li><strong>Using weights and bias:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*rPYesKfFaVc2mqwuCxCYfg.png" /></figure><ul><li><strong>Using beta coefficients (with an added column of 1s in <em>X</em> for </strong><em>β</em><strong><em>0</em>):</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/78/1*qUCzTmmsr2SMhszrJvmrdA.png" /></figure><p>Regardless of which symbols you prefer, our objective stays the same: find the parameter values that make our predictions as close as possible to the ground-truth targets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQP9lzXVEqcnJC9Yf049YQ.png" /></figure><h3>The Cost Function</h3><p>Once we have made our predictions, we need to evaluate their accuracy. That is where the cost function comes in, which quantifies the distance between the actual data points and our predicted values using the Mean Squared Error (MSE). Minimizing this error to find the optimal line of best fit is known as the <strong><em>least squares method</em></strong>. The MSE formula is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*JiZLdDaIV5BMFYIEGmeR9A.png" /></figure><p>Here, <em>n </em>is the number of samples, <em>y</em> is the true value, and <em>y_hat</em> is our prediction. Squaring plays a big role. It punishes large mistakes much harder than small ones, and it makes sure a prediction that is too high does not cancel out a prediction that is too low.</p><p>You might be wondering about that extra 1/2 in front of the fraction. It is not needed to measure the error. We sneak it in on purpose, purely because it makes the derivative cleaner later when we compute the gradient. That is all it does.</p><p>A perfect model has a cost of zero. A bad model has a big cost. So the entire problem of training now boils down to one sentence: find the weights that give the lowest possible cost. The next section shows the two roads to get there.</p><h4>a) The Normal Equation</h4><p>To find the parameter values that minimize our error, we use calculus to locate the lowest point of the cost function surface.</p><p>Calculating the derivative is essential because it gives us the slope of the cost function at any given point. Since the slope tells us the steepness and direction of the function, setting the derivative equal to zero identifies the exact stationary points where the slope is completely flat. Because the Mean Squared Error (MSE) cost function is convex, its global minimum occurs precisely where this derivative equals zero. Solving for the parameters at this zero-slope point yields the optimal solution in a single closed-form step, eliminating the need for iterative guessing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lAs0gnFmBunuuuf4boNBlw.png" /></figure><p>Here’s the step-by-step mathematical breakdown from the cost function to the closed-form solution.</p><ol><li><strong>Define the Matrix Cost Function</strong></li></ol><p>We start with the Mean Squared Error (MSE) cost function <em>J(β)</em> in matrix notation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*H36T6ch2d54ik69W_NMs_Q.png" /></figure><p><strong>2. Expand the Terms</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*gQ_ZmCjReWb3ys26hAIEiQ.png" /></figure><p><strong>3. Compute the Derivative</strong></p><p>Taking the derivative with respect to <em>β</em> using standard matrix calculus rules:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*mYjmENpWd8RAjEd2b--1PA.png" /></figure><p><strong>4. Solve for <em>β</em></strong></p><p>Set the derivative to zero to find the global minimum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*tjrHFmVLMvCsIIUaW6tgSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/147/1*YC3P3wA4lkcd6UbpsXR1yA.png" /></figure><p>Multiplying both sides from the left by <em>(X^T X)^-1</em> isolates <em>β</em> and yields the Normal Equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*n6mjefCImCkdLj76Gx_tmQ.png" /></figure><h4>b) Gradient Descent</h4><p>While the Normal Equation provides an exact analytical solution in a single step, calculating the matrix inverse becomes computationally expensive or even impossible when dealing with massive datasets or millions of features. In these real-world scenarios, we turn to an iterative optimization technique known as Gradient Descent.</p><p>Instead of solving for the optimal parameters directly, Gradient Descent starts with arbitrary initial parameter values and systematically refines them. At each step, it calculates the direction of steepest ascent on the cost function surface and takes a small step in the opposite direction. By repeating this process, the parameters gradually slide down the error curve toward the global minimum, where the cost function reaches its lowest possible value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wBCWyv6E_f-T1pMeGI2d2g.png" /></figure><p>Here is the mathematical breakdown of Gradient Descent using the machine learning notation with weights (<em>w</em>) and bias (<em>b</em>).</p><p><strong>1. Define the Cost Function</strong></p><p>We start with the Mean Squared Error (MSE) cost function defined for <em>n</em> training samples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*rBYTFAAjb1HqM4_nvF-wkw.png" /></figure><p>Substituting our prediction model <em>y_hat = w x^(i) + b</em> into the cost function gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*Y7bZd8MF8e3B--Wjc-A7Xg.png" /></figure><p><strong>2. Derive with Respect to Weight (<em>w</em>)</strong></p><p>To find how the cost changes relative to the weight, we take the partial derivative of <em>J(w, b) </em>with respect to <em>w </em>using the chain rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*CI3q1y_C9OIOXD1YBAi6tA.png" /></figure><p>Since,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*ozBSPLfiPGXyDrR17lHWYQ.png" /></figure><p>The constants cancel out to yield:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*fDkYJ-agBk7Q4H3C0htPfQ.png" /></figure><p><strong>3. Derive with Respect to Bias (<em>b</em>)</strong></p><p>Next, we take the partial derivative of <em>J(w, b)</em> with respect to <em>b</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*lF16b3JDKradBx_Jus-TOw.png" /></figure><p>Since,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*AmGGeRf7f_YeK5_-vHKTaw.png" /></figure><p>Simplifying the equation leads to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*KloraC9AELlblQNYDA-gcA.png" /></figure><p><strong>4. Parameter Update Rules</strong></p><p>Using the calculated gradients, we update both <em>w</em> and <em>b</em> simultaneously at each step by moving in the opposite direction of the derivative, scaled by the learning rate (⍺):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*kaBkVLFAtQjDpRbx4IbA4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*_3hUSza48P4A_kua7oD86g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zztG6qF25zPV1lr0UV1WvQ.jpeg" /></figure><p>Phew! With all that out of the way, we can now get to the fun part.</p><h3>Let’s start coding</h3><p>Everything below is implemented with NumPy, function by function. I have structured it as a class so the model stays organized.</p><p>We start the class and keep a place for the learned weights and bias. We also store the learning rate, the number of iterations, and an empty list that will hold the cost at every step so we can watch it fall later.</p><pre>class LinearRegression:<br>  def __init__(self, learning_rate=0.1, n_iterations=1000):<br>        self.weights = None<br>        self.bias = None<br><br>        # Will be applied in Gradient Descent<br>        self.lr = learning_rate<br>        self.n_iterations = n_iterations<br>        self.cost_history = []</pre><p>Then we write a function, which turns the inputs into predictions. Basically, this computes the formula <em>y = wx + b. </em>On top of that, we add another function that computes the MSE.</p><pre>def _compute_output(self, X):<br>        return (X @ self.weights) + self.bias<br><br>def _compute_cost(self, y_true, y_pred):<br>        n_samples = len(y_true)<br>        return (1 / (2 * n_samples)) * (np.sum(np.square(y_pred - y_true)))</pre><p>The next step is to write a function that implements the Normal Equation by fitting it to our training data and finding the most optimal weights and bias. Don&#39;t forget to add a column of ones at the front of the X matrix, given the weights learned for this end up being the bias.</p><pre>def fit_normal_equation(self, X, y):<br>        &quot;&quot;&quot;<br>            Solves for the exact optimal weights directly, using:<br>                B = (X^T X)⁻¹X^T y<br><br>            This is the algebraic solution to setting the dCost/dB = 0 and solving for B directly.<br>        &quot;&quot;&quot;<br>        n_samples = X.shape[0]<br><br>        # Adds a column of ones at the front of X, the weights learned for this column ends up being the bias<br>        ones_column = np.ones((n_samples, 1))<br>        X_with_bias = np.hstack([ones_column, X])<br><br>        # Solve for coefficients using the normal equation<br>        X_inverse = np.linalg.inv(np.transpose(X_with_bias) @ X_with_bias)<br>        B = (X_inverse @ (np.transpose(X_with_bias) @ y))<br><br>        self.bias = B[0]<br>        self.weights = B[1:]</pre><p>Awesome, now we can head on to Gradient Descent. In this case, we start the weights at zero, loop for n_iterations steps, and inside each step we predict, compute the gradient with the two formulas from earlier, nudge the weights with the learning rate, and record the cost. By the end, <em>cost_history</em> should look like a staircase going downhill.</p><pre>def fit_gradient_descent(self, X, y):<br>        &quot;&quot;&quot;<br>            Gradient Descent Training Loop<br><br>            We iteratively nudge the weights in the direction that reduces cost.<br>        &quot;&quot;&quot;<br><br>        n_samples, n_features = X.shape<br><br>        # We set the weights and the bias to 0 as starting points<br>        self.weights = np.zeros(n_features)<br>        self.bias = 0<br><br>        # Reset the array in case fit_gradient_descent is called more than once<br>        self.cost_history = []<br><br>        for i in range(self.n_iterations):<br>            y_pred = self._compute_output(X)<br><br>            # The formula for dw = 1/n X^T . (y_pred - y_true)<br>            dw = ((1/n_samples) * X.T) @ (y_pred - y)<br><br>            # The formula for db = 1/n . (y_pred - y_true)<br>            db = (1/n_samples) * np.sum(y_pred - y)<br><br>            # Update the coefficients to direct us towards the least cost<br>            self.weights = self.weights - self.lr * dw<br>            self.bias = self.bias - self.lr * db<br><br>            # Record cost for this iteration<br>            cost = self._compute_cost(y_true=y, y_pred=y_pred)<br>            self.cost_history.append(cost)</pre><p>Finally, now that we are done with the class implementation, we can wire everything up. Build the model, standardize the features so both methods behave well, train with both fitters, predict on the test set, and score the result. We will also be comparing our results with scikit-learn&#39;s Linear Regression model to validate our implementation.</p><pre># Import all the rele<br>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LinearRegression as SklearnLinearRegression<br>from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error<br><br>from models.linear_regression import LinearRegression<br><br># Regression dataset (diabetes progression)<br>df_reg = pd.read_csv(&#39;../data/diabetes_progression.csv&#39;)<br>df_reg.drop(columns=&quot;ldl_cholesterol&quot;, inplace=True)<br>train_df_reg, test_df_reg = train_test_split(df_reg, test_size=0.2, random_state=42)<br>reg_feature_cols = [c for c in df_reg.columns if c != &#39;disease_progression&#39;]<br><br># Standardized features<br>reg_mean = X_train_reg_raw.mean(axis=0)<br>reg_std = X_train_reg_raw.std(axis=0)<br>X_train_reg = (X_train_reg_raw - reg_mean) / reg_std<br>X_test_reg = (X_test_reg_raw - reg_mean) / reg_std<br><br># Implementing the linear regression models<br>gd_model = LinearRegression(learning_rate=0.1, n_iterations=1000)<br>gd_model.fit_gradient_descent(X_train_reg, y_train_reg)<br><br>ne_model = LinearRegression()<br>ne_model.fit_normal_equation(X_train_reg, y_train_reg)<br><br>k_model = SklearnLinearRegression()<br>sk_model.fit(X_train_reg, y_train_reg)<br><br># Predict with all three<br>gd_preds = gd_model._compute_output(X_test_reg)<br>ne_preds = ne_model._compute_output(X_test_reg)<br>sk_preds = sk_model.predict(X_test_reg)<br><br># Compare the metrics of the results<br>def report(name, y_true, y_pred):<br>    r2 = r2_score(y_true, y_pred)<br>    rmse = np.sqrt(mean_squared_error(y_true, y_pred))<br>    mae = mean_absolute_error(y_true, y_pred)<br>    print(f&#39;{name:22s} R²={r2:.4f}  RMSE={rmse:.2f}  MAE={mae:.2f}&#39;)<br><br>report(&#39;Gradient Descent&#39;, y_test_reg, gd_preds)<br>report(&#39;Normal Equation&#39;, y_test_reg, ne_preds)<br>report(&#39;scikit-learn&#39;, y_test_reg, sk_preds)</pre><p>Given we have everything set up, we can run the code and see the results for ourselves.</p><pre>Gradient Descent       R²=0.4526  RMSE=53.85  MAE=42.88<br>Normal Equation        R²=0.4526  RMSE=53.85  MAE=42.88<br>scikit-learn           R²=0.4526  RMSE=53.85  MAE=42.88</pre><p>While the prediction scores themselves leave room for improvement :-) , our custom implementations successfully match the results from scikit-learn. Furthermore, watching the cost values decrease step-by-step during Gradient Descent confirms that our iterative optimization is working as intended.</p><pre>plt.figure(figsize=(8, 5))<br>plt.plot(gd_model.cost_history)<br>plt.title(&#39;Gradient Descent Convergence&#39;)<br>plt.xlabel(&#39;Iteration&#39;)<br>plt.ylabel(&#39;Cost (MSE)&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*0B6JLgCAlXIBxdREvzatLA.png" /></figure><h3>Conclusion</h3><p>Both methods lead to the same best line; they just get there in completely different ways. The Normal Equation solves the problem instantly with algebra. Gradient Descent walks its way down the hill, step after step. Use the Normal Equation for small, tidy datasets, and reach for Gradient Descent when the data grows, or when you want to practice a skill that carries over to every neural network you will ever train.</p><p>This is the first chapter of my ML Basics series, and I have a few more models cooking by hand. Logistic Regression, Decision Trees, Random Forests, and Neural Network. Same rules as always: no libraries, just NumPy and math.</p><p>If you made it this far, thank you for reading. If one thing clicked that did not before, the article did its job. Clap if it helped, drop a comment, and I will see you in the next one.</p><p>Access the complete code implementation for this project on GitHub <a href="https://github.com/Stephen-Echessa/diabetes_ml_project_backend/blob/master/models/linear_regression.py">here.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d541638b6861" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stacking Ensembles: Combining XGBoost, LightGBM and CatBoost to Improve Model Performance.]]></title>
            <link>https://medium.com/@stevechesa/stacking-ensembles-combining-xgboost-lightgbm-and-catboost-to-improve-model-performance-d4247d092c2e?source=rss-b4204b4fc55c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4247d092c2e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <dc:creator><![CDATA[Stephen Echessa]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 14:41:53 GMT</pubDate>
            <atom:updated>2024-07-29T14:41:53.341Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q35eCXo_u_HuDcJr" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the ever-evolving world of machine learning, where numerous algorithms vie for supremacy, stacked ensemble stand out as a robust technique that combines the strengths of multiple models to deliver superior predictive performance. In this article, we’ll delve into the concept of stacked ensembles, explore why they’re beneficial, and provide a step-by-step guide to implementing them in Python using three state-of-the-art algorithms: XGBoost, CatBoost, and LightGBM.</p><h3><strong>Why Stacking, and what does it mean?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*6pHtW3UQu_Im-55nejzHew.jpeg" /><figcaption>Image by quickmeme.com</figcaption></figure><p>Picture a relay race where each runner excels in a different segment of the track. This is the essence of stacking. It is an ensemble learning technique that aims to enhance the predictive power of machine learning models by combining multiple individual models, also known as base learners. The core idea is that by leveraging the strengths and compensating for the weaknesses of different models, you can create a final model that performs better than any single model on its own.</p><p>While each individual model has its own merits and demerits, one model may outperform the others on a given machine learning problem. Stacking addresses this by feeding the predictions of the base models to a higher-level model known as the meta-learner or blender, which then combines these inputs to generate the final prediction.</p><p>Stacking is advantageous because of the following reasons:</p><ul><li><strong>Enhanced Accuracy:</strong> Aggregating the predictions of multiple models often leads to better performance than using any single model, thanks to the reduction of individual biases.</li><li><strong>Increased Robustness:</strong> Stacked models generalize better across different datasets, mitigating the risk of overfitting and making the predictions more reliable.</li><li><strong>Greater Flexibility:</strong> Stacking allows for the combination of different types of models (e.g., linear models, decision trees, neural networks), capturing a wider range of patterns in the data.</li></ul><h3><strong>Meet the Titans: XGBoost, CatBoost, and LightGBM</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*hayUOqARsUWM8H9c6D8gsg.jpeg" /><figcaption>Image by Stephen Echessa</figcaption></figure><p>These three algorithms are widely recognized for their superior performance in regression tasks. Each brings unique advantages to the table.</p><h4>XGBoost (eXtreme Gradient Boosting)</h4><p>XGBoost is known for its speed and performance. It efficiently handles large datasets and is highly scalable. Its popularity in data science competitions, like those on Kaggle, is a testament to its robust performance and reliability.</p><h4>CatBoost (Categorical Boosting)</h4><p>CatBoost excels in handling categorical data. It automatically deals with categorical features, eliminating the need for extensive preprocessing. This capability, combined with its resistance to overfitting, makes CatBoost a powerful tool for various applications.</p><h4>LightGBM (Light Gradient Boosting Machine)</h4><p>LightGBM is designed for speed and scalability. It can handle massive datasets with ease and is known for its efficiency in both training and prediction phases. LightGBM’s ability to manage large amounts of data quickly makes it a preferred choice in many scenarios.</p><h3>How Stacking Works</h3><p>This section provides a comprehensive overview of the stacking process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*12lFomTsEZijKXl_J09Ppg.png" /><figcaption>Image by researchgate</figcaption></figure><ol><li><strong><em>Preprocess and split the data: </em></strong>The data should be prepared before modeling. This involves cleaning the data, identifying relevant features and splitting the data to training and validation sets.</li><li><strong><em>Train Base Models:</em> </strong>Each base model is trained on the training set. In our case, these models are XGBoost, CatBoost, and LightGBM.</li><li><strong><em>Generate Predictions: </em></strong>The base models create predictions for the validation set. These predictions serve as input features for the meta-learner.</li><li><strong><em>Train Meta-Learner:</em> </strong>The meta-learner is trained on the predictions of the base models. Simpler machine learning algorithms like Linear regression, Logistic regression, Lasso, Ridge, or Elastic Net are commonly used as meta-learners, acting as the secondary model that is fed the aggregated results of the primary base models.</li><li><strong><em>Make Final Predictions: </em></strong>The trained stacked model (base models + meta-learner) is used to make predictions on new, unseen data.</li></ol><p>The stacking architecture allows you to further customize the model by <strong>restacking</strong>. This involves adding the original input feature X to the final estimator, alongside the predictions from the base learners. In scikit-learn, you can achieve this by setting the passthrough=True parameter on the stacked model.</p><h3>Step-by-Step Implementation in Python</h3><p>Let’s walk through the implementation of stacked ensembles using XGBoost, CatBoost, and LightGBM.</p><h4>1.<strong><em> Load the Data</em></strong></h4><p>We will be using the Boston Housing dataset which contains a total of 14 attributes. Here lies a detailed description:</p><pre>1. CRIM - per capita crime rate by town<br>2. ZN - proportion of residential land zoned for lots over 25,000 sq.ft.<br>3. INDUS - proportion of non-retail business acres per town.<br>4. CHAS - Charles River dummy variable (1 if tract bounds river; 0 otherwise)<br>5. NOX - nitric oxides concentration (parts per 10 million)<br>6. RM - average number of rooms per dwelling<br>7. AGE - proportion of owner-occupied units built prior to 1940<br>8. DIS - weighted distances to five Boston employment centres<br>9. RAD - index of accessibility to radial highways<br>10. TAX - full-value property-tax rate per $10,000<br>11. PTRATIO - pupil-teacher ratio by town<br>12. B - 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town<br>13. LSTAT - % lower status of the population<br>14. MEDV - Median value of owner-occupied homes in $1000&#39;s</pre><p>We will use scikit-learn&#39;s fetch_openml to gain access to the dataset.</p><pre>import pandas as pd<br>import numpy as np<br><br>from sklearn.datasets import fetch_openml<br>from sklearn.model_selection import train_test_split<br><br>boston = fetch_openml(&#39;boston&#39;)<br><br>boston.frame.info()</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 506 entries, 0 to 505<br>Data columns (total 14 columns):<br> #   Column   Non-Null Count  Dtype   <br>---  ------   --------------  -----   <br> 0   CRIM     506 non-null    float64 <br> 1   ZN       506 non-null    float64 <br> 2   INDUS    506 non-null    float64 <br> 3   CHAS     506 non-null    category<br> 4   NOX      506 non-null    float64 <br> 5   RM       506 non-null    float64 <br> 6   AGE      506 non-null    float64 <br> 7   DIS      506 non-null    float64 <br> 8   RAD      506 non-null    category<br> 9   TAX      506 non-null    float64 <br> 10  PTRATIO  506 non-null    float64 <br> 11  B        506 non-null    float64 <br> 12  LSTAT    506 non-null    float64 <br> 13  MEDV     506 non-null    float64 <br>dtypes: category(2), float64(12)<br>memory usage: 49.0 KB</pre><p>The target variable in this case is the column labeled MEDV and the other columns are the input features.</p><h4>2. <strong><em>Preprocess the data</em></strong></h4><p>Prior to model training, we ought to convert the categorical columns RAD and CHAS to integers. This will help to better generalize the inputs across all the models.</p><pre>boston.data[&#39;RAD&#39;] = boston.data[&#39;RAD&#39;].astype(int).apply(lambda x: 0 if x==24 else x)<br>boston.data[&#39;CHAS&#39;] = boston.data[&#39;CHAS&#39;].astype(int)<br><br>boston.data.info()</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 506 entries, 0 to 505<br>Data columns (total 13 columns):<br> #   Column   Non-Null Count  Dtype  <br>---  ------   --------------  -----  <br> 0   CRIM     506 non-null    float64<br> 1   ZN       506 non-null    float64<br> 2   INDUS    506 non-null    float64<br> 3   CHAS     506 non-null    int64  <br> 4   NOX      506 non-null    float64<br> 5   RM       506 non-null    float64<br> 6   AGE      506 non-null    float64<br> 7   DIS      506 non-null    float64<br> 8   RAD      506 non-null    int64  <br> 9   TAX      506 non-null    float64<br> 10  PTRATIO  506 non-null    float64<br> 11  B        506 non-null    float64<br> 12  LSTAT    506 non-null    float64<br>dtypes: float64(11), int64(2)<br>memory usage: 51.5 KB</pre><h4>3. <strong><em>Train the base models</em></strong></h4><p>Make sure to install all the relevant libraries before proceeding.</p><pre>!pip install xgboost lightgbm catboost</pre><pre># Import relevant libraries for Stacking Ensembles<br>from sklearn.linear_model import ElasticNetCV<br>from xgboost import XGBRegressor<br>from lightgbm import LGBMRegressor<br>from catboost import CatBoostRegressor<br>from sklearn.ensemble import StackingRegressor<br><br># Import metrics<br>from sklearn.metrics import r2_score, mean_squared_error<br>from math import sqrt<br><br># Split the data to training and validation sets<br>X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2, random_state=101)<br><br># Function for evaluating the models&#39; performance<br>def evaluate_model(model, X_train, y_train, X_test, y_test):<br>    train_pred = model.predict(X_train)<br>    print(&#39;----------------------------------------------\n&#39;)<br>    print(&#39;Train R2 Score: &#39;, round(r2_score(y_true=y_train, y_pred=train_pred), 6))<br>    print(&#39;Train Root Mean Squared Error: &#39;, sqrt(mean_squared_error(y_true=y_train, y_pred=train_pred)))<br>    print(&#39;----------------------------------------------\n&#39;)<br>    test_pred = model.predict(X_test)<br>    print(&#39;Test R2 Score: &#39;, round(r2_score(y_true=y_test, y_pred=test_pred), 6))<br>    print(&#39;Test Root Mean Squared Error: &#39;, sqrt(mean_squared_error(y_true=y_test, y_pred=test_pred)))</pre><p>Before training the stacked model, let us compare the performance of each of the base learners.</p><p><strong><em>XGBoost</em></strong></p><pre>xgb_model =XGBRegressor(random_state=101)<br>xgb_model.fit(X_train, y_train)<br>evaluate_model(xgb_model, X_train, y_train, X_test, y_test)</pre><pre>----------------------------------------------<br><br>Train R2 Score:  0.999996<br>Train Root Mean Squared Error:  0.017900892709333174<br>----------------------------------------------<br><br>Test R2 Score:  0.860136<br>Test Root Mean Squared Error:  3.961255738804204</pre><p>Decent score!</p><p><strong><em>LightGBM</em></strong></p><pre>light_gbm =LGBMRegressor(random_state=101, verbosity=-1)<br>light_gbm.fit(X_train, y_train)<br>evaluate_model(light_gbm, X_train, y_train, X_test, y_test)</pre><pre>----------------------------------------------<br><br>Train R2 Score:  0.976737<br>Train Root Mean Squared Error:  1.340262997883126<br>----------------------------------------------<br><br>Test R2 Score:  0.840311<br>Test Root Mean Squared Error:  4.232689411294314</pre><p>Lower score than the previous model.</p><p><strong><em>CatBoost</em></strong></p><pre>cat_model =CatBoostRegressor(random_state=101, verbose=0, cat_features=[&#39;CHAS&#39;, &#39;RAD&#39;])<br>cat_model.fit(X_train, y_train)<br>evaluate_model(cat_model, X_train, y_train, X_test, y_test)</pre><pre>----------------------------------------------<br><br>Train R2 Score:  0.993637<br>Train Root Mean Squared Error:  0.7009368522368824<br>----------------------------------------------<br><br>Test R2 Score:  0.886144<br>Test Root Mean Squared Error:  3.5740296984827005</pre><p>Best performing model so far!</p><p><strong><em>Stacked Regression</em></strong></p><p>Scikit-learn provides a stacking model for both regression and classification. In this case we are using StackingRegressor . Let’s see a simple example of how its applied:</p><pre># Store all the base models in a list<br>estimators = [<br>    (&#39;xgb&#39;, xgb_model),<br>    (&#39;lgb&#39;, light_gbm),<br>    (&#39;cat&#39;, cat_model),<br>]<br><br># Create the stacked model with the base models and Elastic Net as the meta-model<br>stack = StackingRegressor(estimators=estimators, final_estimator=ElasticNetCV())<br>stack.fit(X_train, y_train)<br>evaluate_model(stack, X_train, y_train, X_test, y_test)</pre><pre>----------------------------------------------<br><br>Train R2 Score:  0.992734<br>Train Root Mean Squared Error:  0.7490376653420324<br>----------------------------------------------<br><br>Test R2 Score:  0.889421<br>Test Root Mean Squared Error:  3.5222065451926654</pre><p>Slightly better test score from 0.886 to 0.889.</p><p>While we observe a minor improvement in the results with CatBoost, the increased complexity of the model has led to longer processing times. Despite achieving higher scores, it is important to note that stacked regression is not without its drawbacks. The following outlines the disadvantages of using stacking:</p><ul><li><strong>Increased Complexity:</strong> Implementing and tuning multiple models is more complex and time-consuming than using a single model.</li><li><strong>Resource Intensive:</strong> Stacking multiple models can be computationally expensive, requiring more memory and processing power.</li><li><strong>Interpretability:</strong> The final predictions of a stacked model can be harder to interpret compared to a single model, which might be a concern in certain applications.</li></ul><p>To mitigate some of the risks, let us try reducing its complexity by using only two base models.</p><p><strong><em>Stacked Regression(Without XGBoost)</em></strong></p><pre>estimators = [<br>    (&#39;lgb&#39;, light_gbm),<br>    (&#39;cat&#39;, cat_model),<br>]<br><br>stack = StackingRegressor(estimators=estimators, final_estimator=ElasticNetCV())<br>stack.fit(X_train, y_train)<br>evaluate_model(stack, X_train, y_train, X_test, y_test)</pre><pre>----------------------------------------------<br><br>Train R2 Score:  0.992694<br>Train Root Mean Squared Error:  0.7511026908756147<br>----------------------------------------------<br><br>Test R2 Score:  0.890585<br>Test Root Mean Squared Error:  3.5036309701044908</pre><p>We got an even higher test score! This comes as a result of less complexity and fit time.</p><p>Now let’s test another instance by removing the weakest performing model of the bunch.</p><p><strong><em>Stacked Regression(Without LightGBM)</em></strong></p><pre>estimators = [<br>    (&#39;xgb&#39;, xgb_model),<br>    (&#39;cat&#39;, cat_model),<br>]<br><br>stack = StackingRegressor(estimators=estimators, final_estimator=ElasticNetCV())<br>stack.fit(X_train, y_train)<br>evaluate_model(stack, X_train, y_train, X_test, y_test)</pre><pre>----------------------------------------------<br><br>Train R2 Score:  0.993155<br>Train Root Mean Squared Error:  0.7270065887158524<br>----------------------------------------------<br><br>Test R2 Score:  0.891406<br>Test Root Mean Squared Error:  3.4904508443992803</pre><p>Evidently, we got further improvement in the model’s performance.</p><p>You can also fine tune the hyperparameters of the base learners or set passthrough=True to see if the model performance increases. Try out stacking even more diverse models and see if there’s an increase in the results.</p><h3><strong>Conclusion</strong></h3><p>Stacked ensembles are a powerful technique that can significantly boost your model’s performance by combining the strengths of different algorithms. By stacking XGBoost, CatBoost, and LightGBM, you create a model that is accurate, robust, and efficient. Despite some challenges and complexities involved, making stacked ensembles is a go-to strategy for serious data scientists.</p><p>If you find yourself struggling to choose the best model for your regression tasks, remember — you don’t have to choose. Stack them, and let their combined power elevate your predictions to new heights.</p><p><strong><em>Check out my other posts if you liked this one:</em></strong></p><p><a href="https://medium.com/@stevechesa/log-transforming-target-variables-and-enhancing-tree-ensembles-53be435d8041"><em>Log transforming target variables and increase ensemble models’ performance</em></a></p><p><strong><em>You can find me at:</em></strong></p><p><a href="https://github.com/Stephen-Echessa"><em>Github</em></a><em> | </em><a href="https://www.linkedin.com/in/stephen-echessa-621906262/"><em>Linkedin</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4247d092c2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Log Transforming Target Variables and Enhancing Tree Ensembles]]></title>
            <link>https://medium.com/@stevechesa/log-transforming-target-variables-and-enhancing-tree-ensembles-53be435d8041?source=rss-b4204b4fc55c------2</link>
            <guid isPermaLink="false">https://medium.com/p/53be435d8041</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[transformation]]></category>
            <category><![CDATA[random-forest]]></category>
            <dc:creator><![CDATA[Stephen Echessa]]></dc:creator>
            <pubDate>Wed, 03 Jul 2024 19:38:09 GMT</pubDate>
            <atom:updated>2024-07-29T15:04:39.091Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Unleash the Power of Log Transformation and Boost Your Tree Ensemble Models to New Heights.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3IZER8jYAfM0wf5x" /><figcaption>Photo by <a href="https://unsplash.com/@goumbik?utm_source=medium&amp;utm_medium=referral">Lukas Blazek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Greetings fellow data enthusiasts! As a data scientist, I am always looking for ways to squeeze every last drop of performance out of my models. And let me tell you, log transforming your target variables can be like finding a hidden treasure trove of model-boosting goodness. It’s the data science equivalent of turning water into wine — or in this case, turning a skewed distribution into a beautiful, symmetrical bell curve.</p><h3>Understanding Normal Distribution and Log Transformation</h3><p>In the world of data science, a normal distribution is like that one friend who’s always on time, perfectly balanced, and never causes trouble. It’s symmetric, bell-shaped, and oh-so-predictable. Most real-world data, however, does not naturally follow this ideal distribution and can be skewed. Skewed data can complicate the modeling process, leading to suboptimal model performance.</p><p>Log transformation is a method used to reduce skewness and bring the data distribution closer to normal. By applying a logarithmic transformation to the target variable, we can make the data more symmetric, stabilize the variance, and improve the performance of our regression models.</p><figure><img alt="An image of normal distribution curves" src="https://cdn-images-1.medium.com/max/720/1*j4OkrbFdeG1guYC_aJvxTw.jpeg" /><figcaption>Normal Distribution - <a href="https://intuitivetutorial.com/wp-content/uploads/2021/01/Normal_Distribution_PDF-1.jpg">Source</a></figcaption></figure><p>Not so fast! Before diving into the regression bit, we’ve got to understand what ‘log’ means, right? Simply put, the <strong>logarithm</strong> is the inverse function to exponentiation, meaning the logarithm of a number <em>x</em> to the <strong>base</strong> β is the exponent to which β must be raised to produce <em>x</em>. For example, since 100 = 10², the <em>logarithm base</em> 10 of 100 is 2, or log₁₀ (100) = 2. The logarithm of <em>x</em> to <em>base</em> β is denoted as logᵦ (<em>x</em>), or without parentheses, logᵦ <em>x</em>.</p><p>When it comes to log transformations in regression problems, natural logarithms are commonly used. They are denoted as log<em>ₑ (x)</em>, or <em>ln (x) </em>where <em>e</em>≈2.718 being the base raised to produce x. <em>e</em> is also referred to as Euler’s number. Here is an illustration of how natural logarithms look like graphically.</p><pre>plt.figure(figsize=(12, 8))<br>x = np.linspace(start=1, stop=1000)<br>y = np.log(x)<br>plt.plot(x, y)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*MXBuDzzA0GoPb6kMAhI9-w.png" /></figure><p>Looking at the graph, it is clear that the y-values are more spread out for smaller-x values, and as the x-values increase, the y values become closer together. This forms the principle behind log transformation.</p><h3>Why Transforming Data is Important</h3><p>Transforming your features is usually not necessary for tree ensemble methods. These models are robust and can handle various distributions without breaking a sweat. However, transforming the target variable can sometimes work wonders. It can stabilize variance, reduce skewness, and make your life as a data scientist a tad easier.</p><p>Imagine trying to build a treehouse on a steep hill (skewed data). It’s doable, but wouldn’t it be nicer on a flat piece of land (normally distributed data)?</p><h3>Model Implementation</h3><p>For this case study, I will be using the <a href="https://www.kaggle.com/competitions/house-prices-advanced-regression-techniques/data">Ames Housing Dataset</a>. First, import the necessary libraries and read the csv file.</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from scipy import stats<br>from scipy.stats import norm, skew<br><br>data = pd.read_csv(&#39;train.csv&#39;)<br><br>print(&#39;Data shape: &#39;, train.shape)<br>print(&#39;Any missing values: &#39;, data.isna().values.any())</pre><pre>Data shape:  (1460, 81)<br>Any missing values:  True</pre><p>From the above code, we see that there are 1460 rows and 81 columns. The target variable is the ‘SalePrice’ column. Before creating the model, the data needs to be cleaned and missing values imputed.</p><pre>data.drop(&#39;Id&#39;, axis=1, inplace=True)<br><br># Replace all missing values in categorical features with NA<br>data.FireplaceQu.fillna(&#39;NA&#39;, inplace=True)<br>data.PoolQC.fillna(&#39;NA&#39;, inplace=True)<br>data.MiscFeature.fillna(&#39;NA&#39;, inplace=True)<br>data.Alley.fillna(&#39;NA&#39;, inplace=True)<br>data.Fence.fillna(&#39;NA&#39;, inplace=True)<br>data.GarageFinish.fillna(&#39;NA&#39;, inplace=True)<br>data.GarageType.fillna(&#39;NA&#39;, inplace=True)<br>data.GarageQual.fillna(&#39;NA&#39;, inplace=True)<br>data.GarageCond.fillna(&#39;NA&#39;, inplace=True)<br>data.BsmtFinType1.fillna(&#39;NA&#39;, inplace=True)<br>data.BsmtFinType2.fillna(&#39;NA&#39;, inplace=True)<br>data.BsmtExposure.fillna(&#39;NA&#39;, inplace=True)<br>data.BsmtQual.fillna(&#39;NA&#39;, inplace=True)<br>data.BsmtCond.fillna(&#39;NA&#39;, inplace=True)<br>data.MasVnrType.fillna(&#39;NA&#39;, inplace=True)<br><br># Fill other categorical features with most common terms<br>data.MSZoning.fillna(&#39;RL&#39;, inplace=True)<br>data.KitchenQual.fillna(&#39;TA&#39;, inplace=True)<br>data.Electrical.fillna(&#39;SBrkr&#39;, inplace=True)<br>data.Utilities.fillna(&#39;AllPub&#39;, inplace=True)<br>data.Functional.fillna(&#39;Typ&#39;, inplace=True)<br>data.Exterior2nd.fillna(&#39;VinylSd&#39;, inplace=True)<br>data.Exterior1st.fillna(&#39;VinylSd&#39;, inplace=True)<br>data.SaleType.fillna(&#39;WD&#39;, inplace=True)<br><br># Replace all missing values in numerical features with 0<br>data.LotFrontage.fillna(0, inplace=True)<br>data.GarageCars.fillna(0, inplace=True)<br>data.GarageArea.fillna(0, inplace=True)<br>data.BsmtFinSF1.fillna(0, inplace=True)<br>data.TotalBsmtSF.fillna(0, inplace=True)<br>data.GarageYrBlt.fillna(value=0, inplace=True)<br>data.MasVnrArea.fillna(0, inplace=True)<br>data.BsmtUnfSF.fillna(0, inplace=True)<br>data.BsmtFinSF2.fillna(0, inplace=True)<br>data.BsmtFullBath.fillna(0, inplace=True)<br>data.BsmtHalfBath.fillna(0, inplace=True)</pre><p>Now that the data is cleaned, how about converting the categorical features to numeric features. For example, our dataset has a column for the type of road access to property with categories like &quot;Paved” and &quot;Gravel&quot;. While these categories might evoke certain images, our model sees them as gibberish. We need to convert them into a language it understands: numbers.</p><p>To do this, we can assign each unique category to a numerical value using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OrdinalEncoder.html">Ordinal Encoding</a>. In the above example, “Paved” becomes 0 and “Gravel” becomes 1.</p><pre># Select all features with strings<br>string_cols = data.select_dtypes(include=[&#39;object&#39;]).columns<br><br># Convert categorical variables to numeric features<br>from sklearn.preprocessing import OrdinalEncoder<br>ordinal_encoder = OrdinalEncoder()<br><br>data[string_cols] = ordinal_encoder.fit_transform(data[string_cols])</pre><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html">Random Forests Regression</a> is a powerful machine learning algorithm that combines the simplicity of decision trees with the strength of ensemble learning. This is the model that we will be using today. It operates by constructing multiple decision trees during training and outputting the average prediction of the individual trees. This approach enhances model accuracy and robustness while reducing overfitting.</p><p>Let us start off by importing the relevant dependencies and split the dataset into training and test sets.</p><pre>from sklearn.ensemble import RandomForestRegressor<br>from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error<br>from sklearn.model_selection import train_test_split<br><br># Remove warning messages<br>import warnings<br>def ignore_warn(*args, **kwargs):<br>    pass<br>warnings.warn = ignore_warn<br><br># Split data to training set and test set<br>X = data.drop(&#39;SalePrice&#39;, axis=1)<br>y = data[&#39;SalePrice&#39;]<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=101)</pre><h4>Without target transformation</h4><p>We’ll start by building a basic Random Forest model without any transformation and see how it performs.</p><pre>rf = RandomForestRegressor()<br>rf.fit(X_train, y_train)<br>y_pred_train = rf.predict(X_train)<br>y_pred_test = rf.predict(X_test)<br><br>print(&#39;Root Mean Squared Error: &#39;, round(sqrt(mean_squared_error(y_true=y_test, y_pred=y_pred_test)), 3))<br>print(&#39;Mean Absolute Error: &#39;, round(mean_absolute_error(y_true=y_test, y_pred=y_pred_test), 3))<br>print(&#39;R2 Score: &#39;, round(r2_score(y_true=y_test, y_pred=y_pred_test), 3))</pre><pre>Root Mean Squared Error:  32378.672<br>Mean Absolute Error:  18531.23<br>R2 Score:  0.824</pre><p>Not bad! However, it raises the question, “Can it get any better than this?” And the answer is “Yes it can!”</p><h4>With target transformation</h4><p>In order to know for sure whether our independent variable needs to be transformed or not, we need to plot its distribution and measure its skewness.</p><pre># Plot histogram of House selling prices<br>sns.histplot(data[&#39;SalePrice&#39;], bins=20, kde=True)<br><br>(mu, sigma) = norm.fit(data[&#39;SalePrice&#39;])<br>print(f&#39;Distribution Mean: {mu:.5}, Skew: {data.SalePrice.skew():.5} and Std Deviation: {sigma:.5}&#39;)<br><br>plt.title(&#39;House Prices Histogram&#39;)<br><br># Probability plot<br>fig = plt.figure()<br>res = stats.probplot(data[&#39;SalePrice&#39;], plot=plt)<br>plt.show()</pre><pre>Distribution Mean: 1.8092e+05, Skew: 1.8829 and Std Deviation: 7.9415e+04</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*LcJfqemDwlXM4AniuqRDxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*qZkc7WWbbpUpCmZR4PeDRQ.png" /></figure><p>Based on the graphs above, our target variable seems to have a positively skewed distribution(long tail on the right). By plotting the data against its theoretical quantiles, we observe a non-linear relationship which indicates that our distribution isn’t normal. The skew is also far from 0.</p><p>Now let’s apply log transformation and plot the distribution. For our dataset, the mathematical formula we will use is: <em>y′=log(y+1). y </em>is our target variable,<em> and y’ </em>is the transformed target. The<em> +1 </em>ensures we don’t run into issues with zero or negative values.</p><pre>y_transformed = np.log1p(data.SalePrice)<br><br>sns.histplot(y_transformed, bins=20, kde=True)<br><br>(mu, sigma) = norm.fit(y_transformed)<br>print(f&#39;Distribution Mean: {mu:.5}, Skew: {y_transformed.skew():.5}, Std Deviation: {sigma:.5}&#39;)<br><br>plt.title(&#39;Transformed House Prices Histogram&#39;)<br><br># Probability plot<br>fig = plt.figure()<br>res = stats.probplot(y_transformed, plot=plt)<br>plt.show()</pre><pre>Distribution Mean: 12.024, Skew: 0.12135, Std Deviation: 0.39931</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*2uBJGKLUzbtdUJMyJjzJ-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*RDkY2wqMyy9cq6Udwmg0Jw.png" /></figure><p>That’s much better! Our probability plot now has a linear relationship with the exception of a few outliers. Furthermore, our skew is close enough to 0 and the distribution appears more normal. With that out of the way, we can finally start training our model and see the difference transforming our data makes.</p><p>Instead of using<em> </em><a href="https://numpy.org/doc/stable/reference/generated/numpy.log1p.html"><em>numpy.log1p</em></a><em> </em>directly to transform our target variable, we can use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.compose.TransformedTargetRegressor.html">Transformed Target Regressor</a><em> </em>which is a pretty useful tool for applying non-linear transformations to target y in regression problems.</p><pre>from sklearn.compose import TransformedTargetRegressor<br>rf = RandomForestRegressor()<br>log_rf = TransformedTargetRegressor(rf, func=np.log1p, inverse_func=np.expm1)<br>log_rf.fit(X_train, y_train)<br><br>y_pred_train = log_rf.predict(X_train)<br>y_pred_test = log_rf.predict(X_test)<br><br>print(&#39;Root Mean Squared Error: &#39;, round(sqrt(mean_squared_error(y_true=y_test, y_pred=y_pred_test)), 3))<br>print(&#39;Mean Absolute Error: &#39;, round(mean_absolute_error(y_true=y_test, y_pred=y_pred_test), 3))<br>print(&#39;R2 Score: &#39;, round(r2_score(y_true=y_test, y_pred=y_pred_test), 3))</pre><pre>Root Mean Squared Error:  30704.001<br>Mean Absolute Error:  18183.264<br>R2 Score:  0.842</pre><p>We got an improvement in all the scores</p><p>i) R² Score — From 0.824 to 0.842</p><p>ii) MAE — From 18531.23 to 18183.264</p><p>iii) RMSE — From 32378.672 to 30704.001</p><h3>Conclusion</h3><blockquote>Torture the data enough and it will confess to anything — Ronald Coase</blockquote><p>Log transforming your target variable can be a game-changer, especially when dealing with skewed data. By reducing skewness and stabilizing variance, log transformation helps the model better capture the underlying patterns in the data, leading to more accurate predictions. While Tree Ensemble Methods are robust and capable of handling various distributions, applying log transformation to the target variable can provide a meaningful boost to model performance.</p><p>The Python code and data for this article can be found in my <a href="https://github.com/Stephen-Echessa/House-Prices-Prediction/blob/main/Medium%20Article/House%20Prices%20Medium.ipynb">Github repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53be435d8041" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>