The Wayback Machine - https://web.archive.org/web/20240906230819/https://www.geeksforgeeks.org/analysis-of-test-data-using-k-means-clustering-in-python/
Open In App

Analysis of test data using K-Means Clustering in Python

Last Updated : 09 Feb, 2018
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
21.56%
904

This article demonstrates an illustration of K-means clustering on a sample random data using open-cv library.

Pre-requisites: Numpy, OpenCV, matplot-lib
Let’s first visualize test data with Multiple Features using matplot-lib tool.




# importing required tools
import numpy as np
from matplotlib import pyplot as plt
  
# creating two test data
X = np.random.randint(10,35,(25,2))
Y = np.random.randint(55,70,(25,2))
Z = np.vstack((X,Y))
Z = Z.reshape((50,2))
  
# convert to np.float32
Z = np.float32(Z)
  
plt.xlabel('Test Data')
plt.ylabel('Z samples')
  
plt.hist(Z,256,[0,256])
  
plt.show()


Here ‘Z’ is an array of size 100, and values ranging from 0 to 255. Now, reshaped ‘z’ to a column vector. It will be more useful when more than one features are present. Then change the data to np.float32 type.

Output:

Now, apply the k-Means clustering algorithm to the same example as in the above test data and see its behavior.
Steps Involved:
1) First we need to set a test data.
2) Define criteria and apply kmeans().
3) Now separate the data.
4) Finally Plot the data.




import numpy as np
import cv2
from matplotlib import pyplot as plt
  
X = np.random.randint(10,45,(25,2))
Y = np.random.randint(55,70,(25,2))
Z = np.vstack((X,Y))
  
# convert to np.float32
Z = np.float32(Z)
  
# define criteria and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
ret,label,center = cv2.kmeans(Z,2,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
  
# Now separate the data
A = Z[label.ravel()==0]
B = Z[label.ravel()==1]
  
# Plot the data
plt.scatter(A[:,0],A[:,1])
plt.scatter(B[:,0],B[:,1],c = 'r')
plt.scatter(center[:,0],center[:,1],s = 80,c = 'y', marker = 's')
plt.xlabel('Test Data'),plt.ylabel('Z samples')
plt.show()


Output:

This example is meant to illustrate where k-means will produce intuitively possible clusters.

Applications:
1) Identifying Cancerous Data.
2) Prediction of Students’ Academic Performance.
3) Drug Activity Prediction.



Similar Reads

K-Means clustering on the handwritten digits data using Scikit Learn in Python
K - means clustering is an unsupervised algorithm that is used in customer segmentation applications. In this algorithm, we try to form clusters within our datasets that are closely related to each other in a high-dimensional space. In this article, we will see how to use the k means algorithm to identify the clusters of the digits. Load the Datase
5 min read
K-Means Clustering using PySpark Python
In this tutorial series, we are going to cover K-Means Clustering using Pyspark. K-means is a clustering algorithm that groups data points into K distinct clusters based on their similarity. It is an unsupervised learning technique that is widely used in data mining, machine learning, and pattern recognition. The algorithm works by iteratively assi
4 min read
Image compression using K-means clustering
Prerequisite: K-means clustering The internet is filled with huge amounts of data in the form of images. People upload millions of pictures every day on social media sites such as Instagram, and Facebook and cloud storage platforms such as google drive, etc. With such large amounts of data, image compression techniques become important to compress
6 min read
Image Segmentation using K Means Clustering
Image Segmentation: In computer vision, image segmentation is the process of partitioning an image into multiple segments. The goal of segmenting an image is to change the representation of an image into something that is more meaningful and easier to analyze. It is usually used for locating objects and creating boundaries. It is not a great idea t
4 min read
K means clustering using Weka
In this article, we are going to see how to use Weka explorer to do simple k-mean clustering. Here we will use sample data set which is based on iris data that is available in ARFF format. There are 150 iris instances in this dataset. Before starting let's have a small intro about clustering and simple-k. Note: This article assumes that the data ha
3 min read
Clustering Text Documents using K-Means in Scikit Learn
Clustering text documents is a typical issue in natural language processing (NLP). Based on their content, related documents are to be grouped. The k-means clustering technique is a well-liked solution to this issue. In this article, we'll demonstrate how to cluster text documents using k-means using Scikit Learn. K-means clustering algorithm The k
2 min read
Analyzing Decision Tree and K-means Clustering using Iris dataset
Iris Dataset is one of best know datasets in pattern recognition literature. This dataset contains 3 classes of 50 instances each, where each class refers to a type of iris plant. One class is linearly separable from the other 2 the latter are NOT linearly separable from each other. Attribute Information:Sepal Length in cmSepal Width in cmPetal Len
5 min read
ML | Determine the optimal value of K in K-Means Clustering
Prerequisite: K-Means Clustering | IntroductionThere is a popular method known as elbow method which is used to determine the optimal value of K to perform the K-Means Clustering Algorithm. The basic idea behind this method is that it plots the various values of cost with changing k. As the value of K increases, there will be fewer elements in the
2 min read
Difference between K means and Hierarchical Clustering
k-means is method of cluster analysis using a pre-specified no. of clusters. It requires advance knowledge of 'K'. Hierarchical clustering also known as hierarchical cluster analysis (HCA) is also a method of cluster analysis which seeks to build a hierarchy of clusters without having fixed number of cluster. Main differences between K means and Hi
2 min read
K-Means Clustering in R Programming
K Means Clustering in R Programming is an Unsupervised Non-linear algorithm that cluster data based on similarity or similar groups. It seeks to partition the observations into a pre-specified number of clusters. Segmentation of data takes place to assign each training example to a segment called a cluster. In the unsupervised algorithm, high relia
3 min read
ML | Mini Batch K-means clustering algorithm
Prerequisite: Optimal value of K in K-Means Clustering K-means is one of the most popular clustering algorithms, mainly because of its good time performance. With the increasing size of the datasets being analyzed, the computation time of K-means increases because of its constraint of needing the whole dataset in main memory. For this reason, sever
6 min read
Difference between K means and K medoids Clustering
Clustering is the most basic form of data grouping in data analysis as well as in machine learning; the process involves putting the given set of objects into various groups. In which the objects in any single group will be much closer to one another than the objects belonging to other groups. Facilitating the process of clustering, there are sever
5 min read
What is the Most Efficient K-Means Clustering Package in R?
K-means clustering is one of the most popular unsupervised machine learning algorithms used for grouping data points into a specified number of clusters. Each data point is assigned to the cluster with the nearest mean, serving as a prototype of the cluster. In R, several packages provide implementations of the K-means algorithm, each with differen
6 min read
K means Clustering - Introduction
K-Means Clustering is an Unsupervised Machine Learning algorithm, which groups the unlabeled dataset into different clusters. The article aims to explore the fundamentals and working of k mean clustering along with the implementation. Table of Content What is K-means Clustering?What is the objective of k-means clustering?How k-means clustering work
9 min read
DBSCAN Clustering in ML | Density based clustering
Clustering analysis or simply Clustering is basically an Unsupervised learning method that divides the data points into a number of specific batches or groups, such that the data points in the same groups have similar properties and data points in different groups have different properties in some sense. It comprises many different methods based on
7 min read
Difference between CURE Clustering and DBSCAN Clustering
Clustering is a technique used in Unsupervised learning in which data samples are grouped into clusters on the basis of similarity in the inherent properties of the data sample. Clustering can also be defined as a technique of clubbing data items that are similar in some way. The data items belonging to the same clusters are similar to each other i
2 min read
Difference Between Agglomerative clustering and Divisive clustering
Hierarchical clustering is a popular unsupervised machine learning technique used to group similar data points into clusters based on their similarity or dissimilarity. It is called "hierarchical" because it creates a tree-like hierarchy of clusters, where each node represents a cluster that can be further divided into smaller sub-clusters. There a
5 min read
Social Network Analysis Based on BSP Clustering Algorithm
Social Network Analysis (SNA) is a powerful tool used to study the relationships and interactions within a network of individuals, organizations, or other entities. It helps in uncovering patterns, identifying influential nodes, and understanding the overall structure of the network. One of the critical aspects of SNA is the ability to cluster simi
6 min read
Logistic regression vs clustering analysis
Data analysis plays a crucial role in various fields, helping organizations make informed decisions, identify trends, and solve complex problems. Two widely used methods in data analysis are logistic regression and clustering analysis. Logistic regression is a statistical technique used for binary classification problems while clustering analysis i
7 min read
How do I predict new data's cluster after clustering training data in R?
To predict the cluster of new data after training a clustering model in R, you generally need to use the centroids (for k-means) or the hierarchical structure (for hierarchical clustering) obtained from the trained model. Here are steps and examples for predicting new data clusters using k-means and hierarchical clustering. What is Clustering?Clust
4 min read
Factor Analysis | Data Analysis
Factor analysis is a statistical method used to analyze the relationships among a set of observed variables by explaining the correlations or covariances between them in terms of a smaller number of unobserved variables called factors. Table of Content What is Factor Analysis?What does Factor mean in Factor Analysis?How to do Factor Analysis (Facto
13 min read
RFM Analysis Analysis Using Python
In this article, we are going to see Recency, Frequency, Monetary value analysis using Python. But first, let us understand the RFM analysis briefly. What is RFM analysis? RFM stands for recency, frequency, monetary value. In business analytics, we often use this concept to divide customers into different segments, like high-value customers, medium
3 min read
Color Quantization using K-Means in Scikit Learn
In this article, we shall play around with pixel intensity value using Machine Learning Algorithms. The goal is to perform a Color Quantization example using KMeans in the Scikit Learn library. Color Quantization Color Quantization is a technique in which the color spaces in an image are reduced to the number of distinct colors. Even after the colo
2 min read
Clustering in Data Mining
Clustering: The process of making a group of abstract objects into classes of similar objects is known as clustering. Points to Remember: One group is treated as a cluster of data objects In the process of cluster analysis, the first step is to partition the set of data into groups with the help of data similarity, and then groups are assigned to t
2 min read
Different Phases of Projected Clustering in Data Analytics
We know Projected clustering is a typical dimension reduction subspace clustering method which instead of initiating from single dimensional spaces, proceeds by identifying an initial approximation of the clusters in high dimensional attribute space. But to do this projected clustering algorithm goes through different phases. In this article, we ar
3 min read
Top 7 Clustering Algorithms Data Scientists Should Know
Clustering is primarily concerned with the process of grouping data points based on various similarities or dissimilarities between them. It is widely used in Machine Learning and Data Science and is often considered as a type of unsupervised learning method. Subsequently, there are various standard Clustering algorithms out there that are being ut
12 min read
Find mean of subarray means in a given array
You are given an array of n-elements you have to find the mean of the array as mean of all consecutive m-elements of array for all possible m-length array with consecutive elements. Examples: Input :arr[] = {3, 5, 1, 8, 9, 4}, m = 4 Output : Mean = 5.16667 Explanation : {3, 5, 1, 8}, {5, 1, 8, 9}, {1, 8, 9, 4} are three set of m-consecu- tive eleme
6 min read
Find N Geometric Means between A and B
Given three integers A, B and N the task is to find N Geometric means between A and B. WE basically need to insert N terms in a Geometric progression. where A and B are first and last terms. Examples: Input : A = 2 B = 32 N = 3 Output : 4 8 16 the geometric progression series as 2, 4, 8, 16 , 32 Input : A = 3 B = 81 N = 2 Output : 9 27 Approach : L
5 min read
Find N Arithmetic Means between A and B
Given three integers A, B and N the task is to find N Arithmetic means between A and B. We basically need to insert N terms in an Arithmetic progression. where A and B are first and last terms. Examples: Input : A = 20 B = 32 N = 5 Output : 22 24 26 28 30 The Arithmetic progression series as 20 22 24 26 28 30 32 Input : A = 5 B = 35 N = 5 Output :
5 min read
ML | Random Initialization Trap in K-Means
Random initialization trap is a problem that occurs in the K-means algorithm. In random initialization trap when the centroids of the clusters to be generated are explicitly defined by the User then inconsistency may be created and this may sometimes lead to generating wrong clusters in the dataset. So random initialization trap may sometimes preve
2 min read