CH7- Machine Learning – Clustering & K-NN Quick Notes

Page 1

• Course: UCS551 – Introduction to Data Analytics & Application. This course introduces fundamental concepts and techniques in data analytics, preparing students to process, analyze, and interpret large datasets for informed decision-making.
• Chapter 7 focus: Machine Learning – Clustering (author: Miss Noor Assyikin Binti Alias). This chapter specifically delves into unsupervised machine learning techniques, with a primary focus on clustering algorithms, which play a crucial role in discovering inherent structures within data.

Page 2

• Agenda: This chapter is structured to cover key aspects of clustering and related algorithms:

  1. Clustering Fundamentals: Introduction to the concept of clustering and its importance.

  2. K-Means Applications: Practical uses and real-world scenarios where K-Means clustering is effectively applied.

  3. K-Means Process: A detailed step-by-step breakdown of how the K-Means algorithm operates.

  4. K-Means Pros & Cons: An evaluation of the advantages and limitations of the K-Means algorithm.

  5. K-Nearest Neighbors (K-NN): An introduction to K-NN, a supervised learning algorithm often compared with K-Means.

  6. K-NN vs K-Means Comparison: A comparative analysis highlighting the distinct characteristics and ideal use cases for both algorithms.

Page 3

• Clustering: An unsupervised machine learning technique aimed at grouping a set of data points into subsets (clusters) such that data points in the same cluster are more similar to each other than to those in other clusters. It is "unsupervised" because it works with unlabeled data, finding structures without prior knowledge of output categories.
• K-Means Clustering: A popular algorithm that partitions nn observations into kk clusters. The core idea is to define kk centroids, one for each cluster, and then assign each data point to the nearest centroid.
• Cluster: A collection of data points grouped together because of their high degree of similarity based on specific features or attributes. Points within a cluster are homogeneous, while points in different clusters are heterogeneous.
• K-Means vs. K-NN: It is crucial to distinguish K-Means from K-Nearest Neighbors (K-NN). K-Means is an unsupervised clustering algorithm, whereas K-NN is a supervised classification (or regression) algorithm that uses labeled data to predict the class of new data points based on their neighbors.
• The Value of “kk”: In K-Means, kk represents the pre-defined desired number of clusters that the data will be divided into. For example, if k=5k=5, the algorithm will attempt to form 5 distinct groupings of data points. Choosing an optimal kk is a critical step in K-Means.

Page 4

• Purpose of Clustering: The primary objective of clustering is to group similar objects together, thereby helping to reveal underlying structures, associations, or hidden patterns within complex datasets that might not be immediately apparent. This process transforms raw data into meaningful segments.
• Applications of Clustering: Clustering techniques are widely applied across various domains due to their versatility in handling unlabeled data:

  • Pattern Recognition: Identifying recurring patterns in data for anomaly detection or classification.

  • Data Analysis: Segmenting large datasets to understand natural groupings and derive actionable insights.

  • Image Processing: Tasks like image segmentation, where pixels are grouped into regions based on color or texture similarity.

  • Life Sciences: Analyzing gene expression data, classifying diseases, or identifying similar protein structures.
    • Common Clustering Algorithms: While K-Means is highly popular, other notable algorithms include:

  • K-Means: An iterative algorithm that partitions data into a pre-defined number of clusters.

  • K-Nearest Neighbors (K-NN): Primarily a classification/regression algorithm often mentioned alongside clustering due to its distance-based nature, though it's supervised.

  • Kohonen Self-Organizing Maps (KSOM): A type of artificial neural network that produces a low-dimensional (typically 2D) discretized representation of the input space.

  • Hierarchical Clustering: Builds a hierarchy of clusters, either by starting with individual points and merging them (agglomerative) or starting with one large cluster and splitting it (divisive).
    • Overall Goal: The ultimate aim of clustering is to gain deep insights into the intrinsic structure of a dataset, facilitating better decision-making, targeted strategies, or efficient data management.

Page 5

• Clustering Illustration: Imagine a scatter plot of data points without any labels. Before applying a clustering algorithm, these points appear as a single, undifferentiated mass.

Page 6

• Post-Clustering Visualization: After the application of a clustering algorithm, such as K-Means, the same data points are revealed to form distinct groups. For instance, an illustration might show how seemingly random data points coalesce into 3 clearly visible clusters, each represented by a different color, demonstrating the algorithm's ability to discern hidden patterns.

Page 7

• Real-World Example - Telecom Users: Consider a telecommunications company with a vast dataset of user activity. Clustering can be applied to group these users based on their call duration, number of texts sent, data consumption patterns, and subscription types. This segmentation helps the company understand different customer behaviors (e.g., heavy data users, frequent callers, sporadic users) without prior labels.

Page 8

• Music Analogy: Think about organizing a diverse music collection. Without explicit genre labels, you might naturally group songs by similar characteristics like tempo, instrumentation, or lyrical themes (e.g., rock, jazz, classical, or by decade). Clustering works similarly: it autonomously groups unlabeled examples based on their intrinsic features to uncover the inherent structure of the dataset.

Page 9

• Intuitive Analogy - Vegetable Shop: Picture a fresh produce market. All vegetables are initially mixed together. Applying a "clustering" logic means instinctively separating them into natural categories like carrots, potatoes, onions, and greens. Each pile represents a natural cluster, where items within the pile are similar (e.g., all carrots) and distinct from items in other piles. Before clustering, the dataset (vegetables) is mixed; after, it is clearly categorized into distinct groups, such as 3 identifiable clusters of different vegetable types.

Page 10

• Application – Customer Segmentation: Businesses frequently utilize clustering to segment their customer base. By grouping customers based on shared attributes such as purchasing behavior, income level, browsing history, or demographic data, companies can create highly targeted marketing campaigns, develop personalized product recommendations, and tailor services to specific customer groups, leading to improved customer satisfaction and higher conversion rates.

Page 11

• Application – Document Clustering: In fields like information retrieval and natural language processing, clustering helps organize large collections of unstructured text documents. Documents are grouped based on the similarity of their word usage, themes, or topics. For example, news articles can be clustered into categories like "Politics," "Sports," "Technology," or "Finance," making it easier to navigate and analyze vast news archives.

Page 12

• Application – Anomaly Detection: Clustering is a powerful tool for identifying anomalies or outliers within a dataset. In this context, data points that are significantly far away from any cluster centroid (or are part of very small, isolated clusters) are flagged as potential anomalies. This is crucial for detecting fraudulent transactions in financial systems, identifying network intrusions in cybersecurity, or pinpointing abnormal activity in surveillance systems.

Page 13

• Application – Recommendation Systems: Many modern recommendation engines leverage clustering. By clustering users with similar preferences or behaviors, the system can then suggest items that are popular within that specific cluster. Alternatively, items themselves can be clustered, and users are recommended items from clusters that align with their past interactions, thus enhancing the relevance and accuracy of recommendations for movies, products, or music.

Page 14

• Application – Social Network Analysis: In social media or online communities, clustering can be used to detect natural user communities or groups with strong interconnections. Identifying these coherent groups allows platforms to conduct more effective targeted advertising campaigns, facilitate community engagement, or understand the spread of information within specific user factions.

Page 15

• Application – Healthcare/Medical Diagnosis: Clustering plays a vital role in healthcare by segmenting patient populations based on disease symptoms, genetic markers, treatment responses, or medical history. This allows healthcare providers to identify distinct patient subtypes, personalize treatment plans, predict disease progression, and discover new disease categories, leading to more effective and tailored medical interventions.

Page 16

• Application – Biometric Authentication: In systems requiring biometric verification (e.g., fingerprint or facial recognition), clustering can significantly speed up the authentication process. Instead of searching through an entire database of biometric patterns, the system clusters known patterns. When a new biometric input is provided, it's first assigned to the closest existing cluster, drastically narrowing down the search space for the final match, leading to faster and more efficient identification.

Page 17

K-Means Algorithm Steps: The K-Means algorithm is an iterative optimization process that aims to minimize the within-cluster sum of squares. Here are its fundamental steps:

  1. Initialization:

    • Choose kk: First, determine the desired number of clusters, kk. The choice of kk can significantly impact the final clustering results (methods like the elbow method or silhouette score can help in selecting an optimal kk).

    • Randomly Set Initial Centroids: Randomly select kk data points from the dataset to serve as the initial centroids (representative centers) for each of the kk clusters. These initial centroids can influence the final cluster configuration, and often the algorithm is run multiple times with different initializations.

  2. Assignment Step (Expectation Step - E-step):

    • For each data point in the dataset, calculate its Euclidean distance (or another chosen distance metric) to every single centroid.

    • Assign each data point to its closest centroid. This creates kk preliminary clusters, where each point belongs to the cluster whose centroid it is nearest to.

  3. Update Step (Maximization Step - M-step):

    • Once all points have been assigned to a cluster, recalculate the position of each of the kk centroids. The new centroid for each cluster is computed as the mean (average) of all the data points currently assigned to that cluster. This new centroid represents the geometric center of its cluster.

  4. Convergence Check:

    • Repeat steps 2 and 3 until a convergence criterion is met. This typically means:

      • Centroids Stabilize: The positions of the centroids no longer change significantly between successive iterations (i.e., the movement of centroids falls below a predefined threshold).

      • Maximum Iterations Reached: A pre-set maximum number of iterations has been completed, preventing the algorithm from running indefinitely.

      • No Point Reassignments: No data points change their cluster assignment between iterations.

    • When one of these conditions is met, the algorithm is said to have converged, and the final clusters are formed.

Page 18

• Example Setup for K-Means: Let's illustrate the K-Means process with a dataset. Suppose we visually observe that the data might naturally separate into three main groups, so we choose k=3k=3. The first step involves randomly selecting three distinct data points to serve as the initial centroids for each of these three potential clusters.

Page 19

• First Assignment Phase: With the initial centroids set, the algorithm proceeds to the assignment step. For every individual data point in the entire dataset, its Euclidean distance (or Manhattan distance, etc.) to each of the three randomly placed centroids is calculated. Each data point is then assigned to the cluster whose centroid it is closest to, forming preliminary clusters.

Page 20

• First Centroid Recalculation: After all data points have been assigned to their nearest centroids, the algorithm moves to the update step. For each of the three provisional clusters, the new centroid position is calculated by taking the mean (average) coordinates of all the data points that were assigned to that particular cluster. This effectively moves the centroids to the center of their newly formed groups.

Page 21

• Iterative Refinement and Convergence: The process of assigning points to the nearest centroid and then recalculating the centroids is repeated iteratively. The algorithm aims to minimize the within-cluster sum of squares (WCSS), which is the sum of squared distances between each point and its assigned cluster centroid. The iteration continues until the cluster assignments no longer change significantly, or the centroids' positions stabilize, meaning their movement between iterations is negligible.

Page 22

• Evaluating “kk” via Total Variation (WCSS): The effectiveness of a chosen kk value can be assessed by measuring the total within-cluster variation (WCSS).
* k=1k=1: If we consider a single cluster (k=1k=1), all data points belong to one large group. The centroid would be the mean of the entire dataset, resulting in the largest possible total variation (WCSS) because points are generally far from this single center. This serves as a baseline, representing the worst-case scenario in terms of internal homogeneity.
* k=2k=2: By splitting the data into two clusters (k=2k=2), the total variation within clusters will significantly decrease compared to k=1k=1 as points are now closer to their respective cluster centers.
* k=3k=3: Further increasing kk to 3 typically leads to an even greater reduction in WCSS, as the data can be partitioned into more granular, tighter groups. This reduction continues to improve the compactness of the clusters.

Page 23

• Optimal “kk” and the Elbow Method: While increasing kk generally reduces WCSS (because points are closer to their own cluster's centroid when there are more clusters), the rate of reduction starts to diminish beyond a certain point. For example, moving from k=3k=3 to k=4k=4 might still reduce within-cluster variation, but the gain in reduction might not be as substantial as going from k=1k=1 to k=2k=2, or k=2k=2 to k=3k=3. This phenomenon is often visualized using an "elbow plot," where the optimal kk is typically found at the "elbow" of the curve, representing a trade-off between minimizing WCSS and having a manageable number of clusters.

Page 24

K-Means Algorithm Advantages and Disadvantages:
• Advantages:
* Simplicity and Ease of Implementation: K-Means is conceptually straightforward and relatively easy to implement, making it a good choice for beginners and for quickly gaining initial insights into data structure.
* Computational Efficiency: For datasets with a moderate number of features and observations, K-Means is computationally fast, especially when compared to hierarchical clustering algorithms. Its linear complexity with respect to the number of data points (O(n<em>k</em>d∗i)O(n<em>k</em>d*i), where nn is data points, kk is clusters, dd is dimensions, ii is iterations) makes it scalable for certain datasets.
* No Heavy Parameter Tuning: While choosing kk is crucial, other parameters typically don't require extensive fine-tuning compared to more complex machine learning models.
* Versatility: It can be applied across a wide range of domains and data types, from customer segmentation to image compression, due to its effectiveness in finding spherical clusters.
• Disadvantages:
* Sensitivity to Initial Centroids: The final clustering results can vary significantly depending on the initial random placement of centroids. Multiple runs with different initializations are often necessary.
* Requires Pre-defined kk: The user must specify the number of clusters (kk) beforehand, which can be challenging if the natural number of groups in the data is unknown. Incorrect kk can lead to poor clustering results.
* Challenges with Non-Spherical Clusters: K-Means performs best when clusters are spherical and well-separated. It struggles with clusters that have complex shapes (e.g., elongated, intertwined) or varying densities, as it attempts to partition data into convex shapes.
* Sensitivity to Outliers: Being centroid-based (mean), K-Means is heavily influenced by outliers, which can pull centroids away from their true cluster centers and distort the clustering.
* Scalability Issues: While efficient for many datasets, K-Means can become computationally intensive and slow down significantly when dealing with extremely large samples (many data points, nn) or datasets with very high dimensionality (many features, dd), as distance calculations become more expensive.
* Requires Numeric Data: K-Means is inherently designed for numerical data and does not directly handle categorical features without prior encoding.

Page 25

K-Nearest Neighbors (K-NN) Overview:
• Learning Type: K-NN is a non-parametric, instance-based, supervised machine learning algorithm. This means it learns from labeled training data to make predictions on new, unlabeled data. It does not construct a generalized model during training, but rather memorizes the entire training dataset.
• Primary Use Cases: K-NN is predominantly used for:
* Classification: Predicting the categorical class label of a new data point (e.g., "spam" or "not spam").
* Regression: Predicting a continuous numerical value for a new data point (e.g., predicting house prices).
• Distinction from Clustering: Unlike K-Means, K-NN is not a clustering algorithm designed to discover inherent groupings in unlabeled data. It requires pre-labeled data for training and then uses these labels to classify or predict for new, unlabeled points.
• The Meaning of “kk”: In K-NN, the parameter “kk” refers to the number of nearest data points (neighbors) in the training dataset that will be considered when making a prediction for a new, unknown data point. The optimal choice of this kk influences the model's bias-variance tradeoff.

Page 26

Relationship Between K-NN and Clustering Techniques:
While fundamentally different in their learning paradigms (supervised vs. unsupervised), K-NN and clustering algorithms share some conceptual similarities and can sometimes complement each other:
• Shared Principle: Distance Metrics: Both K-NN and many clustering algorithms heavily rely on distance metrics (e.g., Euclidean distance, Manhattan distance) to quantify the similarity or dissimilarity between data points. In K-NN, distance determines which points are considered "neighbors," while in clustering, distance helps group similar points together and assign them to centroids.
• K-NN to Aid Centroid Initialization (for K-Means): In some advanced implementations, K-NN or similar nearest-neighbor methods can be used to select the initial centroids for the K-Means algorithm. For example, one could use K-NN to identify highly dense regions or representative points, which might serve as more robust initial centroids than purely random selection, potentially leading to faster convergence and better quality clusters.
• Distance Matrix for Hierarchical Clustering: The distance matrix computed as part of identifying neighbors in K-NN (which stores the pairwise distances between all data points) can be directly utilized in hierarchical clustering. Hierarchical clustering algorithms, particularly agglomerative ones, build a tree of clusters by iteratively merging the closest pairs of points or clusters based on such a distance matrix.

Page 27

K-NN Algorithm Step 1: Choosing the Value of “kk”:
The first crucial step in applying the K-NN algorithm is to determine the appropriate integer value for kk (the number of nearest neighbors). This decision involves a significant trade-off:
• Small kk (e.g., k=1k=1):
* Pros: The model is highly flexible and captures local patterns effectively. It makes predictions based on very localized information.
* Cons: It is highly sensitive to noise and outliers in the training data. A single noisy neighbor can drastically alter the prediction for a new point, leading to high variance and potentially overfitting the training data. The decision boundary will be highly irregular.
• Large kk:
* Pros: The model becomes less sensitive to individual noisy data points as the prediction is based on a larger consensus. It results in smoother decision boundaries.
* Cons: The model might over-smooth the decision boundaries, potentially missing important local details and increasing bias. It might incorporate points that are too far away, leading to underfitting. If kk is too large (approaching the dataset size), it might even consider distant points from other classes, diluting the influence of truly close neighbors. The choice of kk is often determined through cross-validation.

Page 28

K-NN Algorithm Step 2: Computing Distances:
Once kk is chosen, for a new, unlabeled data point (query point) that needs to be classified or regressed, the algorithm calculates its distance to every single point in the entire training dataset. The most common and widely used distance metric is the Euclidean Distance.
• Euclidean Distance: This metric measures the straight-line distance between two points in Euclidean space. For two points p=(p<em>1,p</em>2,…,p<em>n)p = (p<em>1, p</em>2, …, p<em>n) and q=(q</em>1,q<em>2,…,q</em>n)q = (q</em>1, q<em>2, …, q</em>n) in nn-dimensional space, the Euclidean distance d(p,q)d(p,q) is calculated as:
d(p,q)=∑<em>i=1n(p</em>i−q<em>i)2d(p,q) = \sqrt{\sum<em>{i=1}^n (p</em>i - q<em>i)^2} where: * p</em>ip</em>i and qiq_i are the coordinates (feature values) of points pp and qq in the ii-th dimension.
* The sum is taken over all nn dimensions (features).
• Other Distance Metrics: While Euclidean distance is common, other metrics can also be used depending on the nature of the data and problem, such as:
* Manhattan Distance (L1 norm): Sum of absolute differences of their Cartesian coordinates.
* Minkowski Distance: A generalization of Euclidean and Manhattan distances.
* Hamming Distance: For categorical or binary data.
* Cosine Similarity: Often used for text data, measuring the cosine of the angle between two vectors.

Page 29

K-NN Algorithm Step 3: Identifying the kk Closest Neighbors:
After computing the distance of the new query point to all points in the training dataset, the next step is to identify the kk data points from the training set that have the smallest calculated distances to the query point. These kk points are considered the "nearest neighbors" of the query point. It's crucial that these neighbors are selected from the labeled training data, as their labels will be used for making the prediction.

Page 30

K-NN Algorithm Step 4: Making a Prediction:
Once the kk nearest neighbors are identified, the K-NN algorithm proceeds to make a prediction for the unlabeled query point based on the labels (or values) of these neighbors. The method of prediction depends on whether the task is classification or regression:
• For Classification Tasks:
* The algorithm counts the number of neighbors belonging to each class among the kk selected neighbors.
* The query point is then assigned the class label that is most frequent among its kk nearest neighbors. This is known as a "majority vote." For example, if k=5k=5 and 3 neighbors are 'Class A' and 2 are 'Class B', the query point is classified as 'Class A'.
* In cases of ties (e.g., k=4k=4, 2 'Class A' and 2 'Class B'), strategies like reducing kk by one, choosing based on the closest neighbor, or random selection might be employed.
• For Regression Tasks:
* Instead of categorical labels, the neighbors have continuous numerical values.
* The algorithm computes the average (mean) of the numerical values of the kk nearest neighbors. This average value is then assigned as the predicted output for the query point.
* Weighted Average (Optional): A more sophisticated approach is to use a weighted average, where closer neighbors contribute more to the average than farther ones. This is typically done by weighting each neighbor's value by the inverse of its distance to the query point, giving more influence to literally "closer" information.

Page 31

• Simple K-NN Classification Example: Consider a 2-dimensional space where data points are either red circles or green squares (representing two classes). We have a new, unlabeled data point, depicted as a blue star, whose class we want to predict. If we choose k=3k=3 neighbors, the algorithm first calculates the distances from the blue star to all existing labeled points. It then identifies the three data points (red circles or green squares) that are numerically closest to the blue star.

Page 32

• Prediction based on Majority Vote: In this specific example, suppose out of the three closest neighbors identified, all three turn out to be red circles. Based on the "majority vote" rule for classification, the unlabeled blue star would then be classified as "red." This simple illustration powerfully demonstrates how the choice of kk significantly influences the outcome. A different kk (e.g., k=5k=5) might include a green square, potentially altering the majority vote and leading to a different classification, underscoring the critical importance of selecting an appropriate kk for optimal model performance.

Page 33

When to Use K-NN:
K-NN is a robust and often effective algorithm, particularly suitable for certain scenarios:
• Small to Medium-Sized Datasets (or where computational resources are available): K-NN is an instance-based learning algorithm, meaning it stores the entire training dataset. For very large datasets, the computational cost of calculating distances to all training points for each new prediction can become prohibitive and slow. However, for smaller datasets, its simplicity can be an advantage.
• Complex and Irregular Decision Boundaries: K-NN is non-parametric, meaning it makes no assumptions about the underlying data distribution. This flexibility allows it to model highly complex and non-linear relationships in the data, producing irregular decision boundaries that linear models might miss.
• Prioritizing Accuracy Over Model Interpretability: K-NN often achieves high accuracy, especially on well-behaved datasets. However, it's considered a "black box" model: it provides a prediction but doesn't offer insights into why a particular prediction was made (e.g., feature importance or coefficients), unlike linear models. Therefore, it's preferred when predictive performance is more critical than understanding the internal workings of the model.
• Data with Noisy or Sparse Features: K-NN can be resilient to some noise if kk is chosen appropriately (not too small). In cases with many features, feature scaling is crucial, and dimensionality reduction might be beneficial to avoid the "curse of dimensionality."

Page 34

K-Means vs. K-Nearest Neighbors (K-NN) Summary Comparison:
While both algorithms use "k" and rely on distance metrics, their fundamental principles, purposes, and operational mechanisms are distinct:
• Learning Type:
* K-Means: Unsupervised Learning. It works with unlabeled data to find inherent structures or groupings without prior knowledge of output categories.
* K-NN: Supervised Learning. It learns from a pre-labeled training dataset to make predictions (classifications or regressions) on new, unseen data points.
• Primary Purpose/Goal:
* K-Means: Primarily for Clustering. Its goal is to partition data into K distinct, non-overlapping clusters based on similarity.
* K-NN: Primarily for Classification or Regression. Its goal is to predict the class label (for classification) or a numerical value (for regression) of a test data point based on its neighbors' known labels/values.
• Meaning of “kk” Parameter:
* K-Means: Refers to the desired number of clusters into which the dataset will be partitioned.
* K-NN: Refers to the number of nearest data points (neighbors) to consider when making a prediction for a new query point.
• Training Process/Model Building:
* K-Means: Involves an iterative "training" process where centroids are repeatedly recalculated and points are reassigned until stability is reached. It essentially builds a model represented by the final centroids.
* K-NN: Often referred to as "Lazy Learning" or "instance-based learning." It does not involve an explicit training phase to build a model; instead, it simply stores the entire training dataset. All computation occurs at the time of prediction when a query point is presented.
• Output/Prediction Mechanism:
* K-Means: For any given data point, its output is its assignment to a specific cluster, typically identified by its nearest cluster centroid.
* K-NN: For a new query point, the output is determined by the majority vote of its kk nearest neighbors' class labels (for classification) or the average (or weighted average) of their numerical values (for regression).

Page 35

• References: This chapter's content is synthesized from various educational resources, including insightful videos, informative blogs, and authoritative articles on machine learning, specifically focusing on clustering and classification algorithms.

Page 36

• End of Material: This concludes the in-depth discussion on K-Means clustering and K-Nearest Neighbors. Thank you for your attention.