GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing thepythoncode.com — Tokenization, Stemming, and Lemmatization in Python - The Python Code Want to code faster? Our Python Code Generator lets you create Python scripts with just a few clicks. Try it now! IntroductionWith the advancement in computing power, machine learning and artificial intelligence have reached new heights. Natural Language Processing, a form of artificial intelligence that deals with human language and computer interactions, have become immensely popular both in research as well as in practical applications. Natural Language Processing works on the text data collected from various sources such as the internet, interviews, writings, etc. The collected data is in a raw format containing undesirable characters, different forms of root words, extra spaces, etc. We can not feed the raw data to the NLP algorithms as it would reduce their efficiency to unacceptable levels. Therefore, as much as we want to dive right into the algorithmic part of the NLP model, it is absolutely critical that we process the collected data in the correct format. This formatting of the data is commonly known as preprocessing. For the text data, the preprocessing often involves the procedures given below:
This article discusses each of these procedures in detail. We would also discuss different ways of achieving each preprocessing procedure along with examples of code in Python. Table of contents: TokenizationWhen we collect the data, it is almost always in the form of long, meaningful sentences containing words, special characters, and whitespaces. For a human being, it is easier to read the sentences, but for an algorithm, the sentence is often of no use, as most of the NLP algorithms work on the words rather than sentences. Therefore, it is necessary to convert the sentences or documents to words before feeding them to the algorithm. Tokenization, as the name suggests, is the process of converting sentences or documents into a set of tokens or words. In a sentence, the words are often separated by whitespaces but can also be separated by special characters such as a comma, a hyphen, etc. In the tokenization process, we would break the sentences into words and store them as a list of words rather than a continuous sentence.
There are different ways to achieve the task of tokenization in Python. Let us discuss each of these ways one by one. Tokenization by Splitting the Sentence by WhitespacesAs the words are often separated by whitespaces in a sentence, the easiest way to create tokens from a sentence is to split the sentence by whitespaces. You can traverse the sentence and separate each word by detecting the whitespaces between them. Python provides a built-in function For example:
By default, the Example 1: Splitting by whitespace:
Output:
Example 2: Splitting by comma.
Output:
Example 3: In this example, code reads a text file containing sentences and tokenizes each sentence. Note that we would use the
Output:
DisadvantagesHowever, there is a shortcoming of this method. The Tokenization using TextBlob Library
We can tokenize a sentence from our data using the TextBlob’s words object that returns a list of words. Note that the returned list is not a simple Python list; rather, it is a The tokenization using
Once the libraries are installed, they are ready to use. Let us see the example code to tokenize the sentences from our file:
Output:
Note that the commas and periods are removed from the tokenized words. Tokenization using NLTK LibraryNLTK library is yet another popular library for NLP applications. It provides many tools to perform NLP operations, including preprocessing and tokenization. There are two different types of tokenizations that NTLK provides:
Let us understand each of them using examples. But before writing the code, make sure that the Example 1: Sentence tokenization using
Output:
Example 2: Word tokenization using
Output:
DisadvantagesThe shortcoming of this method is that it includes special characters such as a comma and a period as separate tokens. Byte-Pair Encoding TokenizersByte-Pair encoding tokenizer is a new state-of-the-art tokenizing method. This is a supervised tokenizing mechanism as opposed to the other rule-based tokenizing mechanisms that we have seen till now. Byte-pair encoding algorithm works as follows:
BPE is a data compression algorithm that replaces the most frequent pairs of bytes in a given input with a single, unused byte. It is commonly used to encode text data in natural language processing tasks. To implement BPE, the algorithm first creates a vocabulary of all the unique bytes in the input. It then iteratively identifies the most frequent pair of bytes in the input that is not already in the vocabulary and replaces it with a new, unused byte. This process is repeated until the desired vocabulary size is reached. The resulting vocabulary can be used to encode the input text as a sequence of bytes, with each byte representing a symbol in the vocabulary. We will use the HuggingFace libraries to implement a Byte-Pair encoding tokenizer. If you do not have installed libraries, install them by using the below pip commands.
Once you have installed the needed libraries, you would need a text dataset to train the BPE tokenizer model. For this, we can use the
Once the file is downloaded, unzip it. It would be easier if you unzip it into the same folder as your program file folder. Let us see the code, and let’s understand it. Example: BPE tokenizer
We have instantiated a Although we can train the tokenizer after we have created a After the model is trained, it is better to save the model because training it each time would cost us a lot of time, and it is not a likable phenomenon. Now let us fetch the saved model and tokenize our text data.:
Output:
HuggingFace's tokenizers library has several pre-trained tokenizers as well. These tokenizers save time to train our own tokenizers. You can get a pre-trained tokenizer, as given in the below example, without the need for training:
Subword TokenizationIn the previous example, you might have noticed that some of the words in the BPE tokenizer’s output are meaningless. This happens because the word pair tokenization works on the principle of merging the frequently appearing words together without considering the fact that some words are split, producing meaningless results. The subword tokenization takes care of this issue. It works on the principle that frequently occurring words should not be broken into smaller words. Rather, rarely occurring words should be broken into smaller and more meaningful words. An advantage of subword tokenization is that the model can efficiently process words it has never seen. Also, the vocabulary size is limited. The
Example: Subword tokenization
Output:
WordPiece TokenizerThe WordPiece tokenizer is a subword tokenization algorithm and is quite similar to the Byte Pair encoding tokenizer. However, it differs in the way it forms the tokens such that it does not choose the most frequent pair of characters that occur together. Rather, it chooses those character pairs that increase the likelihood of training data that is added to the vocabulary. The HuggingFace’s
Example: Bert Word Piece Tokenizer
Output:
Sentence Piece TokenizerAt this point, you are familiar with many different tokenization approaches. However, the problem with all these approaches is that they assume that the words are separated using spaces. However, this might not be true for all languages. The sentence piece tokenization approach treats the text as a raw stream rather than assuming whitespace to be a separating character. In this way, the whitespace is itself included in the character set. In the transformers library, you can find a predefined and pre-trained tokenizer named Example: Sentence piece tokenizer
Output:
And with that, we have wrapped up tokenization. StemmingWhen humans express themselves, we use different forms of words as per language grammar. For example, the grammatically correct sentence is “I am playing”, where “playing” is different from its root form. Stemming is a process of converting such words to their root form. Stemming does so by deleting the suffix and (or) prefix based on predefined rules. For example, ‘playing’ might be converted to ‘play’ after stemming. Stemming can be an important preprocessing step before feeding the text to the NLP algorithm, as all the words originating from the same root words are converted to the same form. It increases the efficiency of the algorithm. NLTK library provides us with two different algorithms for stemming. These are given below:
Let us see examples of Porter Stemmer and Snowball Stemmer. Example 1: Porter Stemmer
Output:
Example 2: Snowball Stemmer
Output:
Disadvantages of Stemming
LemmatizationThe purpose of lemmatization is the same as that of stemming. However, as you might have noticed, stemming sometimes results in meaningless words. Moreover, it does not take care if the word is a noun, verb, or adjective. In turn, it might affect the efficiency of your NLP algorithm. Lemmatization overcomes these drawbacks as it converts the words into a meaningful base word called the lemma. It takes vocabulary and morphological analysis into consideration rather than just trimming the words. Lemmatization is more efficient and produces more accurate results but takes more time than stemming owing to the increased complexity of the algorithm. NLTK library provides the Example: WordNet lemmatizer
Output:
Part of Speech TaggingAs we discussed, words can mean differently in different forms. For example, a word can mean differently when it is used as a noun and when it is used as a verb. Part of Speech tagging enables us to identify the form of a word in a sentence.
The part of the speech tag is helpful in correctly lemmatizing the word. Some of the most common POS tags are given below.
Let us see an example where we generate the POS tags for words and then pass them to Example: POS Tags
Output:
You can clearly see the difference between the previous two outputs. We have tagged each word with the verb, and hence the Comparison between Stemming and Lemmatization
ConclusionYou have seen three basic pre-processing procedures that are necessary before feeding the text data to the NLP algorithm. Each of these procedures can be performed using many different methods. This article discussed the most popular methods of doing each of these tasks. While you can use the codes given in the articles directly, remember to make changes according to your environment and your needs. You can get the complete codes for this tutorial here. Learn also: Named Entity Recognition using Transformers and Spacy in Python. Happy learning ♥ Want to code smarter? Our Python Code Assistant is waiting to help you. Try it now!
Sharing is caring!
Read also
Named Entity Recognition using Transformers and Spacy in PythonLearn how you can perform named entity recognition using HuggingFace Transformers and spaCy libraries in Python.
Text Generation with Transformers in PythonLearn how you can generate any type of text with GPT-2 and GPT-J transformer models with the help of Huggingface transformers library in Python.
How to Paraphrase Text using Transformers in PythonExplore different pre-trained transformer models in transformers library to paraphrase sentences in Python. CommentsGot a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips! |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |