Reddit/Twitter Posts Classifications using KNN (K Nearest Neighbors)

This video builds a K Nearest Neighbors classifier from scratch to detect depressed versus non-depressed posts across Reddit and Twitter datasets.

6:04 video3 min readWatch on YouTube

Can a simple distance-based algorithm tell the difference between a depressed and a non-depressed social media post? This video continues a series of experiments on classifying Reddit and Twitter posts, this time implementing K Nearest Neighbors, or KNN, entirely from scratch to see how it stacks up against the logistic regression and Naive Bayes approaches covered previously.

What makes KNN different

KNN is a supervised machine learning algorithm that can handle both classification and regression tasks, with target values that can be categorical or numerical. What sets it apart is that it is nonparametric and a lazy learner: it makes no assumptions about the underlying data distribution, and it does not build a model during training. Instead, it simply memorizes the training dataset and makes predictions only when asked.

How a prediction actually gets made

Given a new, unclassified data point, KNN looks at the K nearest existing data points, based on a distance metric, and uses their labels to make a decision. For classification, it takes the majority class among those K neighbors. For regression tasks, it assigns the average of the K nearest values instead. The distance is usually measured with Euclidean distance, though other metrics like Manhattan distance can also be used. The two main parameters that shape the algorithm's behavior are K, the number of neighbors considered, and the choice of distance metric.

Because KNN's decision boundary can be complex and nonlinear, it adapts well to a wide range of data shapes. Its main advantage is simplicity: there is no training phase, and it can adapt readily to changes in the dataset. The tradeoff is that it is computationally expensive for large datasets and sensitive to irrelevant features, since its predictions can be skewed by the scale of the features used.

Building KNN from scratch

Unlike the earlier projects in this series, this implementation builds KNN from scratch rather than relying on a library. The process starts with the same combined dataset used in earlier videos, drawing from the Reddit combined dataset, the Twitter full dataset, and the Twitter non-advertisement dataset. Irrelevant columns are dropped, the three datasets are merged, null values are removed, and the text is cleaned before being split into training and test sets and transformed using a TF-IDF vectorizer.

The custom KNN classifier is initialized with a default number of neighbors set to three. Its fit method stores the training features and labels directly in the class instance, since there is no actual training computation to perform. The predict method then calculates the distance between each input data point and all training data points, converting the training data to a dense array where needed, identifies the K nearest neighbors, retrieves their labels, and predicts the class by majority vote among those neighbors.

The result

For the final run, K was set to five. After fitting the model and generating predictions, the resulting accuracy came out to 85%, somewhat lower than the other two models tested in this series. The video notes that fine-tuning the K hyperparameter, or using a built-in library method, might push that accuracy higher.

Key takeaways

  • KNN is a nonparametric, lazy-learning algorithm that memorizes training data instead of building a model upfront.
  • Predictions are made by majority vote (classification) or averaging (regression) among the K nearest neighbors, typically using Euclidean distance.
  • The from-scratch implementation reused the combined Reddit and Twitter dataset from earlier videos in the series, cleaned and vectorized with TF-IDF.
  • With K set to five, the custom KNN classifier reached 85% accuracy on the depressed-post classification task.
  • KNN is simple and training-free but computationally expensive on large datasets and sensitive to irrelevant or unscaled features.

Who this is for

This video is a good fit for learners who want to see a classic machine learning algorithm implemented line by line rather than imported from a library. It is part of a Humanitarians AI series comparing multiple classification approaches, including logistic regression and Naive Bayes, on the same social media dataset.

Full transcript(auto-generated, with timestamps)

[0:01]Hello everyone previously we have implemented post classification into deess Po and non deess po using logistic regression and multinomial name base and today let's see how we can do it using KNN knnn stands for K nearest neighbor algorithm and it is the supervised machine learning algorithm which can be used for classification task as well as regression task and the DAT the target value can either be a Cate a category data or numerical data and it is a nonparametric and lazy learning algorithm which means it doesn't make assumptions about the underlying data distribution and it doesn't learn a model during the training instead it memorize es the

[1:00]Training data set and then predicts and let us see with an example how KNN Works let's see uh let this be the training data and uh these are already classified into class one and class to and there is another new test data or a new class which we have to predict and this value is predict based on the K value it takes the K nearest classes or nearest neighbors to it and based on that if it is a classification algorithm as it's here it takes the majority and classifies itself into class two and usually in regression task it uh the target value is assigned based on the average of the

[2:05]K nearest values and here the distance measure is usually uh done by using ukian distance method we can also use other distance calculating methods the main parameters here are K which is the number of neighbors to consider to make the predictions and of course the distance metric it is either Ukon or maniton or any else and cann's decision boundary can be complex and nonlinear which makes it suitable for various types of data sets the advantage of using Kess it is simple there's no training phase and it can adapt to changes in the data set the main disadvantage here is it is computationally expensive for Le for

[3:07]Large data sets and it is sensitive to irrelevant features so might be influenced by the scale of its features unlike the previous uh projects that that we have seen uh I have implemented K&N from scratch so let us understand the code and how it works so I've taken the same data set that we have uh previously used the Reddit comi data set the Twitter full and the Twitter non adver data set and I've dropped the all the irrelevant uh columns and combine these three data sets and then uh I've dropped the null values for the data and uh I've cleaned the data I've cleaned the data set and then split the

[4:03]Data into the test and train uh data set and then also I have transformed the data using TF ID factorer here I've implemented the KNN classifier and in the KNN class we have initialized with the number of neighbors key that that is set to three by default and in the fit method that is where we are training we are uh training the data X train features and Y train as the labels and store them in the class instance next is the predict method which takes a set of test data and predicts the class labels for each data point using the predict method the predict method calcul the

[5:00]Distance between the input data point x and all the training data points if the training data is pass it converts it into the dense array it then defines the K nearest neighbors and retrieve their labels and predicts the class label by selecting the majority of the K neighbor classes and here uh for our data I've like uh taken the K value as five and then fit the data and then made the predictions here are the predictions and also so I have calculated the accuracy which turned out to be 85% which is a bit less than the other two models but uh if we use uh we can

[5:52]Fine tune the uh hyper parameter K and also uh if we use the inbu method it might result in the higher accuracy thank you

More videos

Humanitarians AI Lyrical Literacy Project