The Wayback Machine - https://web.archive.org/web/20240819203813/https://www.geeksforgeeks.org/clustering-text-documents-using-k-means-in-scikit-learn/
Open In App

Clustering Text Documents using K-Means in Scikit Learn

Last Updated : 09 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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-means algorithm is a well-liked unsupervised learning algorithm that organizes data points into groups based on similarities. The algorithm operates by iteratively assigning each data point to its nearest cluster centroid and then recalculating the centroids based on the newly formed clusters.

Preprocessing

Preprocessing describes the procedures used to get data ready for machine learning or analysis. It frequently involves transforming, reformatting, and cleaning raw data and vectorization into a format appropriate for additional analysis or modeling.

Steps

  1. Loading or preparing the dataset [dataset link: https://github.com/PawanKrGunjan/Natural-Language-Processing/blob/main/Sarcasm%20Detection/sarcasm.json]
  2. Preprocessing of text in case the text is loaded instead of manually adding it to the code
  3. Vectorizing the text using TfidfVectorizer
  4. Reduce the dimension using PCA
  5. Clustering the documents
  6. Plot the cluster using matplotlib

Python3




# import the necessary libraries
import json
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
  
# Dataset link: 
df=pd.read_json('sarcasm.json')
  
# Extract the sentence only
sentence = df.headline
  
# create vectorizer
vectorizer = TfidfVectorizer(stop_words='english')
  
# vectorizer the text documents
vectorized_documents = vectorizer.fit_transform(sentence)
  
# reduce the dimensionality of the data using PCA
pca = PCA(n_components=2)
reduced_data = pca.fit_transform(vectorized_documents.toarray())
  
  
# cluster the documents using k-means
num_clusters = 2
kmeans = KMeans(n_clusters=num_clusters, n_init=5,
                max_iter=500, random_state=42)
kmeans.fit(vectorized_documents)
  
  
# create a dataframe to store the results
results = pd.DataFrame()
results['document'] = sentence
results['cluster'] = kmeans.labels_
  
# print the results
print(results.sample(5))
  
# plot the results
colors = ['red', 'green']
cluster = ['Not Sarcastic','Sarcastic']
for i in range(num_clusters):
    plt.scatter(reduced_data[kmeans.labels_ == i, 0],
                reduced_data[kmeans.labels_ == i, 1], 
                s=10, color=colors[i], 
                label=f' {cluster[i]}')
plt.legend()
plt.show()


Output:

                                                document  cluster
16263  study finds majority of u.s. currency has touc...        0
5318   an open and personal email to hillary clinton ...        0
12994        it's not just a muslim ban, it's much worse        0
5395   princeton students confront university preside...        0
24591     why getting married may help people drink less        0
Text clustering using KMeans - Geeksforgeeks

Text clustering using KMeans



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
Classification of text documents using sparse features in Python Scikit Learn
Classification is a type of machine learning algorithm in which the model is trained, so as to categorize or label the given input based on the provided features for example classifying the input image as an image of a dog or a cat (binary classification) or to classify the provided picture of a living organism into one of the species from within t
5 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
Structured vs Unstructured Ward in Hierarchical Clustering Using Scikit Learn
Hierarchical clustering is a popular and widely used method for grouping and organizing data into clusters. In hierarchical clustering, data points are grouped based on their similarity, with similar data points being placed in the same cluster and dissimilar data points being placed in different clusters. One of the key decisions in hierarchical c
3 min read
Clustering Performance Evaluation in Scikit Learn
In this article, we shall look at different approaches to evaluate Clustering Algorithms using Scikit Learn Python Machine Learning Library. Clustering is an Unsupervised Machine Learning algorithm that deals with grouping the dataset to its similar kind data point. Clustering is widely used for Segmentation, Pattern Finding, Search engine, and so
3 min read
Agglomerative clustering with different metrics in Scikit Learn
Agglomerative clustering is a type of Hierarchical clustering that works in a bottom-up fashion. Metrics play a key role in determining the performance of clustering algorithms. Choosing the right metric helps the clustering algorithm to perform better. This article discusses agglomerative clustering with different metrics in Scikit Learn. Scikit l
4 min read
Agglomerative clustering with and without structure in Scikit Learn
Agglomerative clustering is a hierarchical clustering algorithm that is used to group similar data points into clusters. It is a bottom-up approach that starts by treating each data point as a single cluster and then merges the closest pair of clusters until all the data points are grouped into a single cluster or a pre-defined number of clusters.
10 min read
Comparing Different Clustering Algorithms on Toy Datasets in Scikit Learn
In the domain of machine learning, we generally come across two kinds of problems that is regression and classification both of them are supervised learning problems. In unsupervised learning, we have to try to form different clusters out of the data to find patterns in the dataset provided. For that, we have different types of clustering algorithm
9 min read
Spectral Co-Clustering Algorithm in Scikit Learn
Spectral co-clustering is a type of clustering algorithm that is used to find clusters in both rows and columns of a data matrix simultaneously. This is different from traditional clustering algorithms, which only cluster the rows or columns of a data matrix. Spectral co-clustering is a powerful tool for data analysis, as it can help to uncover hid
4 min read
Project | Scikit-learn - Whisky Clustering
Introduction | Scikit-learn Scikit-learn is a machine learning library for Python.It features various classification, regression and clustering algorithms including support vector machines, random forests, gradient boosting, k-means and DBSCAN, and is designed to interoperate with the Python numerical and scientific libraries NumPy and SciPy.Learn
4 min read
Hierarchical Clustering with Scikit-Learn
Hierarchical clustering is a popular method in data science for grouping similar data points into clusters. Unlike other clustering techniques like K-means, hierarchical clustering does not require the number of clusters to be specified in advance. Instead, it builds a hierarchy of clusters that can be visualized as a dendrogram. In this article, w
4 min read
Analysis of test data using K-Means Clustering in Python
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.ra
2 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
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
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 Segmentation Using Fuzzy C-Means Clustering
This article delves into the process of image segmentation using Fuzzy C-Means (FCM) clustering, a powerful technique for partitioning images into meaningful regions. We'll explore the fundamentals of FCM, its advantages over traditional methods, and provide a step-by-step guide to implementing FCM for image segmentation using Python. By the end of
7 min read
Text Classification using scikit-learn in NLP
The purpose of text classification, a key task in natural language processing (NLP), is to categorise text content into preset groups. Topic categorization, sentiment analysis, and spam detection can all benefit from this. In this article, we will use scikit-learn, a Python machine learning toolkit, to create a simple text categorization pipeline.
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 - 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
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
Is K Means Clustering Considered Supervised or Unsupervised Machine Learning?
Answer: K-means clustering is considered an unsupervised machine learning algorithm. This categorization is because it does not rely on labeled input data for training; instead, it organizes data into clusters based on inherent similarities without any predefined labels.In this article we will explore K-Means Clustering in Machine Learning Unsuperv
2 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
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
three90RightbarBannerImg