The Wayback Machine - https://web.archive.org/web/20240723161800/https://www.geeksforgeeks.org/bag-of-word-and-frequency-count-in-text-using-sklearn/
Open In App

Bag of word and Frequency count in text using sklearn

Last Updated : 21 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Text data is ubiquitous in today’s digital world, from emails and social media posts to research articles and customer reviews. To analyze and derive insights from this textual information, it’s essential to convert text into a numerical form that machine learning algorithms can process. One of the fundamental methods for this conversion is the “Bag of Words” (BoW) model, which represents text as a collection of word frequencies. In this article, we will explore the BoW model, its implementation, and how to perform frequency counts using Scikit-learn, a powerful machine-learning library in Python.

What is the Bag of Words Model?

The Bag of Words model is a simple and effective way of representing text data. It treats a text document as an unordered collection of words, disregarding grammar and word order while preserving the word frequency. The primary steps involved in creating a BoW model are:

  • Tokenization: Splitting the text into individual words (tokens).
  • Vocabulary Building: Creating a vocabulary of unique words from the entire corpus.
  • Vectorization: Transforming each document into a numerical vector based on the frequency of each word in the vocabulary.

Example: Consider a small corpus with the following two sentences:

"The cat sat on the mat."
"The dog sat on the log."

The vocabulary would consist of the unique words: [“the”, “cat”, “sat”, “on”, “mat”, “dog”, “log”]. Each sentence is then represented as a vector of word counts:

"The cat sat on the mat.": [2, 1, 1, 1, 1, 0, 0]" 
The dog sat on the log.": [2, 0, 1, 1, 0, 1, 1]

Implementing Bag of Words with Scikit-learn

Scikit-learn provides a straightforward implementation of the BoW model through its CountVectorizer class.

Here’s a step-by-step guide to implementing BoW and performing frequency counts using Scikit-learn.

Python
# Step 1: Preparing the Corpus

from sklearn.feature_extraction.text import CountVectorizer
import numpy as np

# Step 2: Preparing the Corpus
corpus = [
    "The cat sat on the mat.",
    "The dog sat on the log."
]

# Step 3: Initializing and Fitting the CountVectorizer
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(corpus)

# Step 4: Displaying the Vocabulary and Frequency Counts
print("Vocabulary:", vectorizer.vocabulary_)
print("Feature Names:", vectorizer.get_feature_names_out())
print("Bag of Words Representation:\n", X.toarray())

# Step 5: Analyzing Word Frequencies
word_counts = np.sum(X.toarray(), axis=0)
word_freq = dict(zip(vectorizer.get_feature_names_out(), word_counts))
print("Word Frequencies:", word_freq)

Output:

Vocabulary: {'the': 6, 'cat': 0, 'sat': 5, 'on': 4, 'mat': 3, 'dog': 1, 'log': 2}
Feature Names: ['cat' 'dog' 'log' 'mat' 'on' 'sat' 'the']
Bag of Words Representation:
[[1 0 0 1 1 1 2]
[0 1 1 0 1 1 2]]
Word Frequencies: {'cat': 1, 'dog': 1, 'log': 1, 'mat': 1, 'on': 2, 'sat': 2, 'the': 4}

Conclusion

In this article, we’ve covered the basic steps to create a BoW model and perform frequency count analysis using Scikit-learn. This knowledge serves as a stepping stone to more advanced text processing techniques, such as TF-IDF, word embeddings, and neural network-based models, which build upon the concepts introduced here.


Similar Reads

Python Sklearn – sklearn.datasets.load_breast_cancer() Function
In this article, we are going to see how to convert sklearn dataset to a pandas dataframe in Python. Sklearn is a python library that is used widely for data science and machine learning operations. Sklearn library provides a vast list of tools and functions to train machine learning models. The library is available via pip install. pip install sci
2 min read
Bag of words (BoW) model in NLP
In this article, we are going to discuss a Natural Language Processing technique of text modeling known as Bag of Words model. Whenever we apply any algorithm in NLP, it works on numbers. We cannot directly feed our text into that algorithm. Hence, Bag of Words model is used to preprocess the text by converting it into a bag of words, which keeps a
4 min read
Continuous bag of words (CBOW) in NLP
In order to make the computer understand a written text, we can represent the words as numerical vectors. One way to do so is by Using Word embeddings, they are a way of representing words as numerical vectors. These vectors capture the meaning of the words and their relationships to other words in the language. Word embeddings can be generated usi
5 min read
Data Pre-Processing with Sklearn using Standard and Minmax scaler
Data Scaling is a data preprocessing step for numerical features. Many machine learning algorithms like Gradient descent methods, KNN algorithm, linear and logistic regression, etc. require data scaling to produce good results. Various scalers are defined for this purpose. This article concentrates on Standard Scaler and Min-Max scaler. The task he
3 min read
Linear and Quadratic Discriminant Analysis using Sklearn
Linear Discriminant Analysis (LDA) and Quadratic Discriminant Analysis (QDA) are two well-known classification methods that are used in machine learning to find patterns and put things into groups. They are especially helpful when you have labeled data and want to classify new observations notes into pre-defined categories. In this we will implemen
5 min read
ML | Implementing L1 and L2 regularization using Sklearn
Prerequisites: L2 and L1 regularizationThis article aims to implement the L2 and L1 regularization for Linear regression using the Ridge and Lasso modules of the Sklearn library of Python. Dataset - House prices dataset.Step 1: Importing the required libraries C/C++ Code import pandas as pd import numpy as np import matplotlib.pyplot as plt from sk
3 min read
Python | Decision Tree Regression using sklearn
Decision Tree is a decision-making tool that uses a flowchart-like tree structure or is a model of decisions and all of their possible results, including outcomes, input costs, and utility.Decision-tree algorithm falls under the category of supervised learning algorithms. It works for both continuous as well as categorical output variables. The bra
4 min read
Python | Create Test DataSets using Sklearn
Python's Sklearn library provides a great sample dataset generator which will help you to create your own custom dataset. It's fast and very easy to use. Following are the types of samples it provides.For all the above methods you need to import sklearn.datasets.samples_generator. C/C++ Code # importing libraries from sklearn.datasets import make_b
3 min read
ML | Implementation of KNN classifier using Sklearn
Prerequisite: K-Nearest Neighbours Algorithm K-Nearest Neighbors is one of the most basic yet essential classification algorithms in Machine Learning. It belongs to the supervised learning domain and finds intense application in pattern recognition, data mining and intrusion detection. It is widely disposable in real-life scenarios since it is non-
2 min read
ML | Dummy classifiers using sklearn
A dummy classifier is a type of classifier which does not generate any insight about the data and classifies the given data using only simple rules. The classifier's behavior is completely independent of the training data as the trends in the training data are completely ignored and instead uses one of the strategies to predict the class label. It
3 min read
three90RightbarBannerImg