Technology

Machine Learning Algorithms from Scratch: Implementing Linear Regression and KNN Without High-Level Libraries

Libraries like scikit-learn let you train a model in three lines of code – obviously very convenient, though the effect is that you completely obscure what’s actually happening inside the algorithm. If you build the model from scratch, you do get a real understanding of the maths, the data flow and the various decisions that will impact your accuracy. This article looks at two of the most fundamental algorithms – linear regression and k-nearest neighbours (KNN) – all in Python with a bit of NumPy to do the array work.

Why build algorithms from scratch?

Understanding Over Memorisation

If you actually go through and write out each step for yourself, then you actually do learn why the model behaves the way it does. You see how the learning rate affects convergence and why feature scaling will change your KNN predictions. That’s how you learn to debug your own projects and how to pick the right model.

Interview and Project Readiness

Technical interviews will always ask you to go through an algorithm from scratch (i.e. explain it or code it) with no libraries to hand. A lot of the learners that come into a data science course in Delhi will tell you that the ‘from scratch’ exercises are one of the fastest ways of building that confidence.

Implementing Linear Regression

The Core Idea

Linear regression models the relationship between the input features and a continuous target. For a single feature, the prediction is y=wx+b (w being the weight and b the bias). The objective is to find the values of w and b that will minimise the mean squared error (MSE) between the predicted and actual values.

Gradient Descent Step by Step

Gradient descent moves the parameters in the direction that reduces error:

  1. Set w and b to zero.
  2. Compute the predictions for all the training points.
  3. Find the gradients: dw = (2/n) Σ(y_pred – y)·x, db = (2/n) Σ(y_pred – y).
  4. Update the parameters: w = w – α·dw and b = b – α·db where α is the learning rate.
  5. Repeat for a fixed number of iterations or until the error stops decreasing.

Structuring the Implementation

Write a small class with two methods. fit() does the gradient descent loop and stores the weights and bias. predict() uses them to make predictions on new inputs. All done via NumPy matrix ops so it’s very short and very fast.

Practical Tips

Scale your features prior to training as large feature values can make gradient descent very unstable. Begin with a small learning rate (say 0.01) and plot the loss to ensure it’s going down steadily.

Implementing K-Nearest Neighbours

How KNN Works

KNN is a non-parametric algorithm. It just stores the training data, and then all the work it does is when a new point comes in. For classification, it finds the k nearest training points and assigns the label that is the most common amongst those k points. There’s no actual training phase, so it’s a classic example of a lazy learner.

Measuring Distance

The most common one is Euclidean distance (the square root of the sum of the squared differences). Manhattan distance is just the sum of the absolute differences and is often a good choice for data that’s on a grid.

Structuring the Implementation

Here the fit method just saves the training data. For each new point, the predict method works out the distance to all of the stored points, picks the k nearest labels and returns the most common of those.

Choosing the Value of k

A small k makes the model extremely sensitive to noise. A large k will tend to smear the class boundaries. Odd values are used in the binary case to avoid ties. The most reliable way to choose k is to try out a number of values on a validation set.

Comparing the Two Algorithms

  • Task type: Linear regression is used for predicting continuous values. KNN is fundamentally a classification algorithm (although it can be used for regression by simply taking the average of the k nearest points).
  • Computational cost: Linear regression takes a bit of time to learn its parameters but once it’s learned, it makes predictions very quickly. KNN has essentially zero training cost (the training time is negligible), but the cost of making a prediction is much higher as it has to work out the distance to every single point in the store.
  • Interpretability: the LR weights tell you how each feature affects the output. KNN is far less interpretable in that regard.
  • Sensitivity to scale: both perform better with normalised features, KNN being far more sensitive as its distances are a direct function of the scale of the features.

Validating Your Implementation

Once your versions are running, compare the outputs against scikit-learn on the same dataset. If they’re identical, then your logic is correct. Minor differences will generally be due to scaling, the learning rate or the number of iterations. That’s precisely why a well-structured programme (a good data science course in Delhi, for example) would include that validation step, so the student can see the theory in action.

Conclusion

Build a linear regression and a KNN from scratch (absolutely no high-level libraries allowed). You get a real understanding of how the models actually learn and make their predictions. You learn about gradients, distance metrics and all the various hyperparameters that the high-level libraries just sort of hide from you. Start with those two and just test them against the established tools. Then use the same approach with logistic regression or decision trees.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button