The Wayback Machine - https://web.archive.org/web/20240831172902/https://www.geeksforgeeks.org/continuous-bag-of-words-cbow-in-nlp/
Open In App

Continuous bag of words (CBOW) in NLP

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

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 using unsupervised learning algorithms such as Word2vec, GloVe, or FastText. 

Word2vec is a neural network-based method for generating word embeddings, which are dense vector representations of words that capture their semantic meaning and relationships. There are two main approaches to implementing Word2vec:

What is a Continuous Bag of Words (CBOW)?

Continuous Bag of Words (CBOW) is a popular natural language processing technique used to generate word embeddings. Word embeddings are important for many NLP tasks because they capture semantic and syntactic relationships between words in a language. CBOW is a neural network-based algorithm that predicts a target word given its surrounding context words. It is a type of “unsupervised” learning, meaning that it can learn from unlabeled data, and it is often used to pre-train word embeddings that can be used for various NLP tasks such as sentiment analysis, text classification, and machine translation. 

Example of a CBOW Model

Example of a CBOW Model

Is there any difference between  Bag-of-Words (BoW) model and the Continuous Bag-of-Words (CBOW)?

  • The Bag-of-Words model and the Continuous Bag-of-Words model are both techniques used in natural language processing to represent text in a computer-readable format, but they differ in how they capture context.
  • The BoW model represents text as a collection of words and their frequency in a given document or corpus. It does not consider the order or context in which the words appear, and therefore, it may not capture the full meaning of the text. The BoW model is simple and easy to implement, but it has limitations in capturing the meaning of language.
  • In contrast, the CBOW model is a neural network-based approach that captures the context of words. It learns to predict the target word based on the words that appear before and after it in a given context window. By considering the surrounding words, the CBOW model can better capture the meaning of a word in a given context.

Architecture of the CBOW model

The CBOW model uses the target word around the context word in order to predict it. Consider the above example “She is a great dancer.” The CBOW model converts this phrase into pairs of context words and target words. The word pairings would appear like this ([she, a], is), ([is, great], a) ([a, dancer], great) having window size=2. 

 

CBOW Architecture

CBOW Architecture

The model considers the context words and tries to predict the target term. The four 1∗W input vectors will be passed to the input layer if have four words as context words are used to predict one target word. The hidden layer will receive the input vectors and then multiply them by a W∗N matrix. The 1∗N output from the hidden layer finally enters the sum layer, where the vectors are element-wise summed before a final activation is carried out and the output is obtained from the output layer.

Code Implementation of CBOW

Let’s implement a word embedding to show the similarity of words using the CBOW model. In this article I have defined my own corpus of words, you use any dataset. First, we will import all the necessary libraries and load the dataset. Next, we will tokenize each word and convert it into a vector of integers.

Python3




import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,\
    Embedding, Lambda
from tensorflow.keras.preprocessing.text import Tokenizer
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
 
# Define the corpus
corpus = ['The cat sat on the mat',
          'The dog ran in the park',
          'The bird sang in the tree']
 
# Convert the corpus to a sequence of integers
tokenizer = Tokenizer()
tokenizer.fit_on_texts(corpus)
sequences = tokenizer.texts_to_sequences(corpus)
print("After converting our words in the corpus \
into vector of integers:")
print(sequences)


Output:

After converting our words in the corpus into vector of integers:
[[1, 3, 4, 5, 1, 6], [1, 7, 8, 2, 1, 9], [1, 10, 11, 2, 1, 12]]

Now, we will build the CBOW model having window size = 2.

Python3




# Define the parameters
vocab_size = len(tokenizer.word_index) + 1
embedding_size = 10
window_size = 2
 
# Generate the context-target pairs
contexts = []
targets = []
for sequence in sequences:
    for i in range(window_size, len(sequence) - window_size):
        context = sequence[i - window_size:i] +\
            sequence[i + 1:i + window_size + 1]
        target = sequence[i]
        contexts.append(context)
        targets.append(target)
 
# Convert the contexts and targets to numpy arrays
X = np.array(contexts)
 
# Define the CBOW model
model = Sequential()
model.add(Embedding(input_dim=vocab_size,
                    output_dim=embedding_size,
                    input_length=2*window_size))
model.add(Lambda(lambda x: tf.reduce_mean(x, axis=1)))
model.add(Dense(units=vocab_size, activation='softmax'))
model.save_weights('cbow_weights.h5')
 
 
# Load the pre-trained weights
model.load_weights('cbow_weights.h5')


Next, we will use the model to visualize the embeddings.

Python3




# Get the word embeddings
embeddings = model.get_weights()[0]
 
# Perform PCA to reduce the dimensionality
# of the embeddings
pca = PCA(n_components=2)
reduced_embeddings = pca.fit_transform(embeddings)
 
# Visualize the embeddings
plt.figure(figsize=(5, 5))
for i, word in enumerate(tokenizer.word_index.keys()):
    x, y = reduced_embeddings[i]
    plt.scatter(x, y)
    plt.annotate(word, xy=(x, y), xytext=(5, 2),
                 textcoords='offset points',
                 ha='right', va='bottom')
plt.show()


Output:

Vectorized representation of the words using the CBOW Model

Vectorized representation of the words using the CBOW Model

This visualization allows us to observe the similarity of the words based on their embeddings. Words that are similar in meaning or context are expected to be close to each other in the plot.



Similar Reads

Word Embeddings in NLP: Comparison Between CBOW and Skip-Gram Models
Word embeddings have revolutionized the field of natural language processing (NLP) by enabling machines to understand the meaning and context of words. Two of the most popular word embedding algorithms are Continuous Bag of Words (CBOW) and Skip-Gram. While they share the same goal of learning word representations, they differ significantly in thei
8 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
Bag of word and Frequency count in text using sklearn
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 "Ba
3 min read
NLP | Filtering Insignificant Words
Many of the words used in the phrase are insignificant and hold no meaning. For example - English is a subject. Here, 'English' and 'subject' are the most significant words and 'is', 'a' are almost useless. English subject and subject English holds the same meaning even if we remove the insignificant words - ('is', 'a'). Using the nltk, we can remo
2 min read
NLP | How to score words with Execnet and Redis
Distributed word scoring can be performed using Redis and Execnet together. For each word in movie_reviews corpus, FreqDist and ConditionalFreqDist are used to calculate information gain. Using >RedisHashFreqDist and a RedisConditionalHashFreqDist, same thing can be performed with Redis. The scores are then stored in a RedisOrderedDict. In order
4 min read
Top K Nearest Words using Edit Distances in NLP
We can find the Top K nearest matching words to the given query input word by using the concept of Edit/Levenstein distance. If any word is the same word as the query input(word) then their Edit distance would be zero and is a perfect match and so on. So we can find the Edit distances between the query word and the words present in our vocabulary p
3 min read
NLP | How tokenizing text, sentence, words works
Tokenization in natural language processing (NLP) is a technique that involves dividing a sentence or phrase into smaller units known as tokens. These tokens can encompass words, dates, punctuation marks, or even fragments of words. The article aims to cover the fundamentals of tokenization, it's types and use case. What is Tokenization in NLP?Natu
8 min read
Continuous Kernel Convolution
Continuous Kernel convolution was proposed by the researcher of Verije University Amsterdam in collaboration with the University of Amsterdam in a paper titled 'CKConv: Continuous Kernel Convolution For Sequential Data'. The motivation behind that is to propose a model that uses the properties of convolution neural networks and Recurrent Neural net
6 min read
Deep parametric Continuous Convolutional Neural Network
Deep Parametric Continuous Kernel convolution was proposed by researchers at Uber Advanced Technologies Group. The motivation behind this paper is that the simple CNN architecture assumes a grid-like architecture and uses discrete convolution as its fundamental block. This inhibits their ability to perform accurate convolution to many real-world ap
6 min read
How to Make a CNN Predict a Continuous Value?
Answer : To make a CNN predict a continuous value, use it in a regression setup by having the final layer output a single neuron with a linear activation function.Convolutional Neural Networks (CNNs) are widely recognized for their prowess in handling image data, typically in classification tasks. However, their versatility extends to regression pr
2 min read
Lifelong Learning in AI: Revolutionizing Continuous Adaptation in Technology
Lifelong learning in AI eliminates fixed behaviors making AI a more dynamic solution in that it would always learn in the real world. In this article, we have discussed the definition of lifelong learning in AI and its significance in today’s technological world, the main ideas, facilitating tools, and applications. Table of Content What is Lifelon
9 min read
Fixing Accuracy Score ValueError: Can't Handle Mix of Binary and Continuous Target
When working with machine learning models in Python, especially with libraries like Scikit-learn, you might encounter various errors that can be confusing. One such error is the "ValueError: Can't Handle Mix of Binary and Continuous Target" when calculating the accuracy score of your model. This error typically arises when there's a mismatch in the
5 min read
Decision tree using continuous variable in R
Decision trees are widely used due to their simplicity and effectiveness. They split data into branches to form a tree structure based on decision rules, making them intuitive and easy to interpret. In R, several packages such as rpart and party are available to facilitate decision tree modeling. This guide will specifically delve into how to utili
5 min read
Continuous Probability Distributions for Machine Learning
Machine learning relies heavily on probability distributions because they offer a framework for comprehending the uncertainty and variability present in data. Specifically, for a given dataset, continuous probability distributions express the chance of witnessing continuous outcomes, like real numbers. Table of Content What are Continuous probabili
6 min read
NLP | Classifier-based Chunking | Set 2
Using the data from the treebank_chunk corpus let us evaluate the chunkers (prepared in the previous article). Code #1 : C/C++ Code # loading libraries from chunkers import ClassifierChunker from nltk.corpus import treebank_chunk train_data = treebank_chunk.chunked_sents()[:3000] test_data = treebank_chunk.chunked_sents()[3000:] # initializing chun
2 min read
BART Model for Text Auto Completion in NLP
BART stands for Bidirectional and Auto-Regressive Transformer. It is a denoising autoencoder that is a pre-trained sequence-to-sequence method, that uses masked language modeling for Natural Language Generation and Translation. It is developed by Lewis et al. in 2019. BART architecture is similar to an encoder-decoder network except that it uses a
7 min read
Processing text using NLP | Basics
In this article, we will be learning the steps followed to process the text data before using it to train the actual Machine Learning Model. Importing Libraries The following must be installed in the current working environment: NLTK Library: The NLTK library is a collection of libraries and programs written for processing of English language writt
2 min read
Readability Index in Python(NLP)
Readability is the ease with which a reader can understand a written text. In natural language, the readability of text depends on its content (the complexity of its vocabulary and syntax). It focuses on the words we choose, and how we put them into sentences and paragraphs for the readers to comprehend. Our main objective in writing is to pass alo
6 min read
Feature Extraction Techniques - NLP
Introduction : This article focuses on basic feature extraction techniques in NLP to analyse the similarities between pieces of text. Natural Language Processing (NLP) is a branch of computer science and machine learning that deals with training computers to process a large amount of human (natural) language data. Briefly, NLP is the ability of com
11 min read
Bidirectional LSTM in NLP
In this article, we will first discuss bidirectional LSTMs and their architecture. We will then look into the implementation of a review system using Bidirectional LSTM. Finally, we will conclude this article while discussing the applications of bidirectional LSTM. Bidirectional LSTM (BiLSTM)Bidirectional LSTM or BiLSTM is a term used for a sequenc
8 min read
Python | NLP analysis of Restaurant reviews
Natural language processing (NLP) is an area of computer science and artificial intelligence concerned with the interactions between computers and human (natural) languages, in particular how to program computers to process and analyze large amounts of natural language data. It is the branch of machine learning which is about analyzing any text and
6 min read
NLP | Chunking and chinking with RegEx
Chunk extraction or partial parsing is a process of meaningful extracting short phrases from the sentence (tagged with Part-of-Speech). Chunks are made up of words and the kinds of words are defined using the part-of-speech tags. One can even define a pattern or words that can't be a part of chuck and such words are known as chinks. A ChunkRule cla
2 min read
NLP | Training Unigram Tagger
A single token is referred to as a Unigram, for example - hello; movie; coding. This article is focused on unigram tagger. Unigram Tagger: For determining the Part of Speech tag, it only uses a single word. UnigramTagger inherits from NgramTagger, which is a subclass of ContextTagger, which inherits from SequentialBackoffTagger. So, UnigramTagger i
2 min read
NLP | Synsets for a word in WordNet
WordNet is the lexical database i.e. dictionary for the English language, specifically designed for natural language processing. Synset is a special kind of a simple interface that is present in NLTK to look up words in WordNet. Synset instances are the groupings of synonymous words that express the same concept. Some of the words have only one Syn
2 min read
NLP | Word Collocations
Collocations are two or more words that tend to appear frequently together, for example - United States. There are many other words that can come after United, such as the United Kingdom and United Airlines. As with many aspects of natural language processing, context is very important. And for collocations, context is everything. In the case of co
3 min read
NLP | WuPalmer - WordNet Similarity
How does Wu & Palmer Similarity work? It calculates relatedness by considering the depths of the two synsets in the WordNet taxonomies, along with the depth of the LCS (Least Common Subsumer). The score can be 0 < score <= 1. The score can never be zero because the depth of the LCS is never zero (the depth of the root of taxonomy is one).
2 min read
NLP | Splitting and Merging Chunks
SplitRule class : It splits a chunk based on the specified split pattern for the purpose. It is specified like <NN.*>}{<.*> i.e. two opposing curly braces surrounded by a pattern on either side. MergeRule class : It merges two chunks together based on the ending of the first chunk and the beginning of the second chunk. It is specified l
2 min read
NLP | Chunking Rules
Below are the steps involved for Chunking - Conversion of sentence to a flat tree. Creation of Chunk string using this tree.Creation of RegexpChunkParser by parsing the grammar using RegexpParser.Applying the created chunk rule to the ChunkString that matches the sentence into a chunk. Splitting the bigger chunk to a smaller chunk using the defined
2 min read
NLP | Expanding and Removing Chunks with RegEx
RegexpParser or RegexpChunkRule.fromstring() doesn't support all the RegexpChunkRule classes. So, we need to create them manually. This article focusses on 3 of such classes : ExpandRightRule: It adds chink (unchunked) words to the right of a chunk. ExpandLeftRule: It adds chink (unchunked) words to the left of a chunk. For ExpandLeftRule and Expan
2 min read
NLP | Leacock Chordorow (LCH) and Path similarity for Synset
Path-based Similarity: It is a similarity measure that finds the distance that is the length of the shortest path between two synsets. Leacock Chordorow (LCH) : It is a similarity measure which is an extended version of Path-based similarity as it incorporates the depth of the taxonomy. Therefore, it is the negative log of the shortest path (spath)
1 min read