スキップしてメイン コンテンツに移動

Understanding k-Nearest Neighbors from Scratch

 In the world of data analysis, k-Nearest Neighbors (kNN) has a reputation for being easy to try but surprisingly deep. It has very few difficult parameters and is intuitively easy to understand, but there are unexpected tricks to mastering it in practice.


1. What is k-Nearest Neighbors?


For a given unknown sample, kNN finds the k nearest points (neighbors) within the learning data space. It then uses a simple method – majority voting of the labels (for classification) or the average of the values (for regression) – to predict the answer. You can switch between Euclidean distance, Manhattan distance, cosine similarity, and others depending on the characteristics of the problem.


- Too Small a k


It becomes sensitive to noise and prone to overfitting (e.g., k=1 is the most unstable).


- Too Large a k


It creates overly smooth boundaries, risking ignoring fine differences between categories (underfitting).


- Empirical Tuning


The standard approach is to find the optimal k using cross-validation.


- Weight of Linear Scanning


If you calculate the distance to every sample each time, the response time becomes severe when the number of data points exceeds tens of thousands.


- Fast Search Techniques


You can ensure scalability using KD-Tree, Ball-Tree, Approximate Nearest Neighbor (Annoy, Faiss), etc.


2. What is kNN Used For?


The strengths of kNN lie in its model-free nature, intuitive behaviour, and versatility.


(1). Recommendation

   It can be used for collaborative filtering based on calculating the similarity between users or items.


(2). Anomaly Detection

   It learns the distribution of distances to near neighbours of normal samples and detects outliers as dissimilar points.


(3). Handwritten Digit Recognition

   It calculates distances on a pixel-by-pixel basis and classifies them into "familiar digits."


(4). Medical Diagnosis Support

   It searches for similar patient data and assists in judgement based on the treatment results of past cases.


(5). Image Search Engine

   It extracts "similar images" by calculating the distance between feature-vectorized images.


In fact, it can be used for both classification and regression, and its application range expands dramatically by combining distance definitions and advanced indexing techniques.


3. Benefits of Learning k-Nearest Neighbors


- The idea of quantifying similarity between data points is applicable to clustering, distance-based anomaly detection, and even kernel methods.


- You can confirm its operation with just a few lines of code, allowing you to easily learn the flow of pre-processing and model evaluation.


- You can intuitively grasp the changes in accuracy due to hyperparameter tuning (k and distance metric).


- You can master spatial data structures, which are essential when dealing with large-scale data.


- Speeding up with approximate search libraries is valuable in recommendation and big data analysis.


- If you can understand simple kNN, you can smoothly transition to applying distance learning and local linear models.

If you want to learn k-Nearest Neighbors (Nearest Neighbor Method), we recommend this book (access here).




コメント

このブログの人気の投稿

Understanding the Modified Euler Method (Heun's Method) from Scratch

This article explains the basic concepts, applications, and benefits of learning the Modified Euler Method (Heun's Method). This method, a step forward from the simple Euler method, plays a very important role in the world of numerical analysis. 1. What is the Modified Euler Method (Heun's Method)? The Modified Euler Method, also known as Heun’s Method, is a numerical method for obtaining approximate solutions to initial value problems: dy/dt = f(t, y), y(t_0) = y_0 The traditional Euler method determines the next value, y_{n+1}, using only the slope of the tangent line at time t_n, namely f(t_n, y_n).  However, when the step size is large or the problem exhibits strong non-linearity, this can lead to significant errors. A key feature of Heun’s Method is its ability to achieve higher accuracy (local error of second order) through a two-stage evaluation process, improving upon the Euler method. 2. In What Scenarios is it Applied? Due to its simplicity and improved accuracy, Heun...

Lista de publicaciones del Dr. Mint (en inglés)

   Mint Publishing ha publicado los siguientes libros. Todos ellos son fáciles de entender y están cuidadosamente explicados para que puedas comprenderlos desde cero. Las siguientes series ya están disponibles.   Serie Inteligencia Artificial   Serie Matemáticas   Serie Física   Serie Procesamiento de Imágenes   Serie Cálculo y Análisis Numérico   Serie Python   Serie R Las series están organizadas de tal manera que puedes aprender de la que más te interese, o puedes empezar con el primer volumen de la serie en orden. Al ir y venir entre las series, el contenido es altamente sinérgico entre sí. A continuación se enumeran los libros. (Para más información sobre cada libro, visite la página del libro correspondiente).   Serie Inteligencia Artificial   [1]. Entendiendo los perceptrones : Una base para el aprendizaje profundo  (próximamente) [2]. Understanding the Improved Perceptron (El...

Understanding Reciprocal Functions from Scratch

The reciprocal function is one of the fundamental functions in mathematics, and despite its simplicity, it’s a powerful tool with applications in many fields thanks to its unique characteristics. This article will provide a detailed explanation of the definition and properties of reciprocal functions, explore the contexts in which they are used, and outline the benefits of learning about them. 1. What is a Reciprocal Function? A reciprocal function returns the reciprocal of a given real number.  - Graph Shape The graph of a reciprocal function forms a hyperbola, with values increasing or decreasing rapidly as it approaches the origin. It takes the shape of a hyperbola spanning the first and third quadrants, and has asymptotes at x = 0 and y = 0. Behind this simple equation lies the concept of a multiplicative inverse, which forms the foundation of basic algebra. 2. Where are Reciprocal Functions Used? Due to their fundamental nature and simplicity, reciprocal functions are used in ...