The Wayback Machine - https://web.archive.org/web/20241001201128/https://www.geeksforgeeks.org/named-entity-recognition/
Open In App

Named Entity Recognition

Last Updated : 06 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Named Entity Recognition (NER) is a technique in natural language processing (NLP) that focuses on identifying and classifying entities. The purpose of NER is to automatically extract structured information from unstructured text, enabling machines to understand and categorize entities in a meaningful manner for various applications like text summarization, building knowledge graphs, question answering, and knowledge graph construction. The article explores the fundamentals, methods and implementation of the NER model.

What is Named Entity Recognition (NER)?

Name-entity recognition (NER) is also referred to as entity identification, entity chunking, and entity extraction. NER is the component of information extraction that aims to identify and categorize named entities within unstructured text. NER involves the identification of key information in the text and classification into a set of predefined categories. An entity is the thing that is consistently talked about or refer to in the text, such as person names, organizations, locations, time expressions, quantities, percentages and more predefined categories.

NER system fin applications across various domains, including question answering, information retrieval and machine translation. NER plays an important role in enhancing the precision of other NLP tasks like part-of-speech tagging and parsing. At its core, NLP is just a two-step process, below are the two steps that are involved:

  • Detecting the entities from the text
  • Classifying them into different categories

Ambiguity in NER

  • For a person, the category definition is intuitively quite clear, but for computers, there is some ambiguity in classification. Let’s look at some ambiguous examples:
    • England (Organization) won the 2019 world cup vs The 2019 world cup happened in England (Location).
    • Washington (Location) is the capital of the US vs The first president of the US was Washington (Person).

How Named Entity Recognition (NER) works?

The working of Named Entity Recognition is discussed below:

  • The NER system analyses the entire input text to identify and locate the named entities.
  • The system then identifies the sentence boundaries by considering capitalization rules. It recognizes the end of the sentence when a word starts with a capital letter, assuming it could be the beginning of a new sentence. Knowing sentence boundaries aids in contextualizing entities within the text, allowing the model to understand relationships and meanings.
  • NER can be trained to classify entire documents into different types, such as invoices, receipts, or passports. Document classification enhances the versatility of NER, allowing it to adapt its entity recognition based on the specific characteristics and context of different document types.
  • NER employs machine learning algorithms, including supervised learning, to analyze labeled datasets. These datasets contain examples of annotated entities, guiding the model in recognizing similar entities in new, unseen data.
  • Through multiple training iterations, the model refines its understanding of contextual features, syntactic structures, and entity patterns, continuously improving its accuracy over time.
  • The model’s ability to adapt to new data allows it to handle variations in language, context, and entity types, making it more robust and effective.

Named Entity Recognition (NER) Methods

Lexicon Based Method

The NER uses a dictionary with a list of words or terms. The process involves checking if any of these words are present in a given text. However, this approach isn’t commonly used because it requires constant updating and careful maintenance of the dictionary to stay accurate and effective.

Rule Based Method

The Rule Based NER method uses a set of predefined rules guides the extraction of information. These rules are based on patterns and context. Pattern-based rules focus on the structure and form of words, looking at their morphological patterns. On the other hand, context-based rules consider the surrounding words or the context in which a word appears within the text document. This combination of pattern-based and context-based rules enhances the precision of information extraction in Named Entity Recognition (NER).

Machine Learning-Based Method

Multi-Class Classification with Machine Learning Algorithms

  • One way is to train the model for multi-class classification using different machine learning algorithms, but it requires a lot of labelling. In addition to labelling the model also requires a deep understanding of context to deal with the ambiguity of the sentences. This makes it a challenging task for a simple machine learning algorithm.

Conditional Random Field (CRF)

  • Conditional random field is implemented by both NLP Speech Tagger and NLTK.  It is a probabilistic model that can be used to model sequential data such as words.
  • The CRF can capture a deep understanding of the context of the sentence. In this model, the input [Tex]{\text{X}} =  \left \{ \vec{x}_{1} ,\vec{x}_{2} ,\vec{x}_{3}, \ldots,\vec{x}_{T}   \right \}  [/Tex]
    [Tex] p(y | \mathbf{x}) = \frac{1}{z(\vec{x})} \prod_{t=1}^{T} \exp\left\{ \sum_{k=1}^{K} \omega_k f_k(y_t, y_{t-1}, \vec{x}_t) \right\}[/Tex]

Deep Learning Based Method

  • Deep learning NER system is much more accurate than previous method, as it is capable to assemble words. This is due to the fact that it used a method called word embedding, that is capable of understanding the semantic and syntactic relationship between various words.
  • It is also able to learn analyzes topic specific as well as high level words automatically.
  • This makes deep learning NER applicable for performing multiple tasks. Deep learning can do most of the repetitive work itself, hence researchers for example can use their time more efficiently.

How to Implement NER in Python?

For implementing NER system, we will leverage Spacy library. The code can be run on colab, however for visualization purpose. I recommend the local environment. We can install the required libraries using:

!pip install spacy !pip install nltk !python -m spacy download en_core_web_sm

Install Important Libraries

Python

import pandas as pd import spacy import requests from bs4 import BeautifulSoup nlp = spacy.load("en_core_web_sm") pd.set_option("display.max_rows", 200)

NER using Spacy

In the following code, we use SpaCy, a natural language processing library to process text and extract named entities. The code iterates through the named entities identified in the processed document and printing each entity’s text, start character, end character and label.

Python

content = "Trinamool Congress leader Mahua Moitra has moved the Supreme Court against her expulsion from the Lok Sabha over the cash-for-query allegations against her. Moitra was ousted from the Parliament last week after the Ethics Committee of the Lok Sabha found her guilty of jeopardising national security by sharing her parliamentary portal's login credentials with businessman Darshan Hiranandani." doc = nlp(content) for ent in doc.ents: print(ent.text, ent.start_char, ent.end_char, ent.label_)

Output:

Congress 10 18 ORG Mahua Moitra 26 38 PERSON the Supreme Court 49 66 ORG the Lok Sabha 94 107 PERSON Moitra 157 163 ORG Parliament 184 194 ORG last week 195 204 DATE the Ethics Committee 211 231 ORG Darshan Hiranandani 373 392 PERSON

The output displayed the names of the entities, their start and end positions in the text, and their predicted labels.

Visualize

The displacy.render function from spaCy is used to visualize the named entities in a text. It generates a visual representation with colored highlights indicating the recognized entities and their respective categories.

Python

from spacy import displacy displacy.render(doc, style="ent")

Output:

How to Implement NER in Python ?

Using the following code, we will create a dataframe from the named entities extracted by spaCy, including the text, type (label), and lemma of each entity.

Python

entities = [(ent.text, ent.label_, ent.lemma_) for ent in doc.ents] df = pd.DataFrame(entities, columns=['text', 'type', 'lemma']) print(df)

Output:

text type lemma 0 Congress ORG Congress 1 Mahua Moitra PERSON Mahua Moitra 2 the Supreme Court ORG the Supreme Court 3 the Lok Sabha PERSON the Lok Sabha 4 Moitra ORG Moitra 5 Parliament ORG Parliament 6 last week DATE last week 7 the Ethics Committee ORG the Ethics Committee 8 Darshan Hiranandani PERSON Darshan Hiranandani

The data frame provides a structured representation of the named entities, their types and lemmatized forms.

Get complete notebook link here :

Notebook: click here.

Frequently Asked Questions (FAQs)

1. What is the purpose of NER system?

The purpose of NER is to automatically extract the structed information from unstructured text, enabling machines to understand and categorize entities in a meaning manner for various applications like text summarization, building knowledge graphs, question answering and knowledge graph construction.

2. What are methods of NER in NLP?

Methods of NER in NLP include:

  • Lexicon based NER.
  • Rules Based
  • ML Based
  • Deep learning Based.

3. What are the uses of NER in NLP?

NER plays an important role in enhancing the precision of other NLP tasks like part-of-speech tagging and parsing.

4. Can BERT do named entity recognition?

Yes, BERT can be used for NER.



Similar Reads

Named Entity Recognition in NLP
In this article, we'll dive into the various concepts related to NER, explain the steps involved in the process, and understand it with some good examples. Named Entity Recognition (NER) is a critical component of Natural Language Processing (NLP) that has gained significant attention and research interest in recent years. It involves identifying a
6 min read
NLP | Named Entity Chunker Training
Self Named entity chunker can be trained using the ieer corpus, which stands for Information Extraction: Entity Recognition. The ieer corpus has chunk trees but no part-of-speech tags for the words, so it is a bit tedious job to perform. Named entity chunk trees can be created from ieer corpus using the ieertree2conlltags() and ieer_chunked_sents()
2 min read
NLP | Extracting Named Entities
Recognizing named entity is a specific kind of chunk extraction that uses entity tags along with chunk tags. Common entity tags include PERSON, LOCATION and ORGANIZATION. POS tagged sentences are parsed into chunk trees with normal chunking but the trees labels can be entity tags in place of chunk phrase tags. NLTK has already a pre-trained named e
2 min read
How to fix " ModuleNotFoundError: No module named 'sklearn' "
Encountering the error "ModuleNotFoundError: No module named 'sklearn'" can be frustrating, especially when you're eager to dive into your machine learning project. This error typically occurs when Python cannot locate the Scikit-Learn library in your environment. In this comprehensive guide, we'll explore the reasons behind this error and provide
4 min read
Can Named Arguments Be Used with Python Enums?
Enums (Enumerations) are a symbolic representation of a set of named values, commonly used in programming to define a collection of constants. In Python, Enums are used to organize sets of related constants in a more readable and maintainable way. Using named arguments with enums can enhance clarity and functionality by allowing us to associate add
3 min read
How to Fix Unprocessable Entity Error in ChatGPT
In the world of Artificial Intelligence, a game-changing innovation has emerged – ChatGPT by OpenAI. This remarkable creation revolutionizes daily life, aiding with coding, content creation, and more. Yet, the "Unprocessable Entity" error occasionally puzzles users, interrupting their experience. This article explores the causes and solutions for t
5 min read
ML | Implement Face recognition using k-NN with scikit-learn
k-Nearest Neighbors: k-NN is one of the most basic classification algorithms in machine learning. It belongs to the supervised learning category of machine learning. k-NN is often used in search applications where you are looking for “similar” items. The way we measure similarity is by creating a vector representation of the items, and then compare
5 min read
Pattern Recognition | Basics and Design Principles
Prerequisite – Pattern Recognition | Introduction Pattern Recognition System Pattern is everything around in this digital world. A pattern can either be seen physically or it can be observed mathematically by applying algorithms. In Pattern Recognition, pattern is comprises of the following two fundamental things: Collection of observationsThe conc
4 min read
Applications of Pattern Recognition
Pattern Recognition is the science of making inferences from the perceptual data using the tools from statistics, probability, computational geometry, machine learning, signal processing and algorithm design. The applications of pattern recognition are: Machine Vision: A machine vision system captures images via a camera and analyzes them to produc
2 min read
Python | Multiple Face Recognition using dlib
This article aims to quickly build a Python face recognition program to easily train multiple images per person and get started with recognizing known faces in an image. In this article, the code uses ageitgey's face_recognition API for Python. This API is built using dlib's face recognition algorithms and it allows the user to easily implement fac
4 min read
Object Detection vs Object Recognition vs Image Segmentation
Object Recognition: Object recognition is the technique of identifying the object present in images and videos. It is one of the most important applications of machine learning and deep learning. The goal of this field is to teach machines to understand (recognize) the content of an image just like humans do. Object Recognition Using Machine Learni
5 min read
Deep Face Recognition
DeepFace is the facial recognition system used by Facebook for tagging images. It was proposed by researchers at Facebook AI Research (FAIR) at the 2014 IEEE Computer Vision and Pattern Recognition Conference (CVPR). In modern face recognition there are 4 steps: DetectAlignRepresentClassify This approach focuses on alignment and representation of f
8 min read
ML | Face Recognition Using PCA Implementation
Face Recognition is one of the most popular and controversial tasks of computer vision. One of the most important milestones is achieved using This approach was first developed by Sirovich and Kirby in 1987 and first used by Turk and Alex Pentland in face classification in 1991. It is easy to implement and thus used in many early face recognition a
6 min read
ML | Face Recognition Using Eigenfaces (PCA Algorithm)
In 1991, Turk and Pentland suggested an approach to face recognition that uses dimensionality reduction and linear algebra concepts to recognize faces. This approach is computationally less expensive and easy to implement and thus used in various applications at that time such as handwritten recognition, lip-reading, medical image analysis, etc. PC
4 min read
FaceNet - Using Facial Recognition System
FaceNet is the name of the facial recognition system that was proposed by Google Researchers in 2015 in the paper titled FaceNet: A Unified Embedding for Face Recognition and Clustering. It achieved state-of-the-art results in the many benchmark face recognition dataset such as Labeled Faces in the Wild (LFW) and Youtube Face Database. They propose
5 min read
Human Activity Recognition - Using Deep Learning Model
Human activity recognition using smartphone sensors like accelerometer is one of the hectic topics of research. HAR is one of the time series classification problem. In this project various machine learning and deep learning models have been worked out to get the best final result. In the same sequence, we can use LSTM (long short term memory) mode
6 min read
License Plate Recognition with OpenCV and Tesseract OCR
You will learn about Automatic number-plate recognition. We will use the Tesseract OCR An Optical Character Recognition Engine (OCR Engine) to automatically recognize text in vehicle registration plates. Python-tesseract: Py-tesseract is an optical character recognition (OCR) tool for python. That is, it'll recognize and "read" the text embedded in
5 min read
Face recognition using Artificial Intelligence
The current technology amazes people with amazing innovations that not only make life simple but also bearable. Face recognition has over time proven to be the least intrusive and fastest form of biometric verification. The software uses deep learning algorithms to compare a live captured image to the stored face print to verify one's identity. Ima
15+ min read
Image Recognition with Mobilenet
Introduction: Image Recognition plays an important role in many fields like medical disease analysis, and many more. In this article, we will mainly focus on how to Recognize the given image, what is being displayed. We are assuming to have a pre-knowledge of Tensorflow, Keras, Python, MachineLearning Also, we will be using Colaboratory as our note
5 min read
Convolutional Block for Image Recognition
INTRODUCTION: The basic neural network design i.e. an input layer, few dense layers, and an output layer does not work well for the image recognition system because objects can appear in lots of different places in an image. So the solution is to add one or more convolutional layers. A convolutional block is a building block used in a convolutional
5 min read
Python - Facial and hand recognition using MediaPipe Holistic
What is MediaPipe: Object Detection is one of the leading and most popular use cases in the domain of computer vision. Several object detection models are used worldwide for their particular use case applications. Many of these models have been used as an independent solution to a single computer vision task with its own fixed application. Combinin
4 min read
Traffic Signs Recognition using CNN and Keras in Python
We always come across incidents of accidents where drivers' Overspeed or lack of vision leads to major accidents. In winter, the risk of road accidents has a 40-50% increase because of the traffic signs' lack of visibility. So here in this article, we will be implementing Traffic Sign recognition using a Convolutional Neural Network. It will be ver
6 min read
Human Activity Recognition with OpenCV
Have you ever wondered while watching a Sci-Fi film how does computer Recognize what a person's next move will be or how it predicts our actions according to activities performed? Well, the simple answer is it uses Human Activity Recognition (HAR) Technology for this. To accurately engineer features from the raw data to build a machine learning mod
8 min read
Flower Recognition Using Convolutional Neural Network
In this article, we will use Convolutional Neural Network to solve a Supervised Image Classification problem of recognizing the flower types - rose, chamomile, dandelion, sunflower, & tulip. Understanding the concept of a Convolutional Neural Network refers to this. Once, understand the concept of CNN we can start with the project. Steps to be
4 min read
Image Recognition using TensorFlow
In this article, we'll create an image recognition model using TensorFlow and Keras. TensorFlow is a robust deep learning framework, and Keras is a high-level API(Application Programming Interface) that provides a modular, easy-to-use, and organized interface to solve real-life deep learning problems. Image Recognition: In Image recognition, we inp
6 min read
Sign Language Recognition System using TensorFlow in Python
The first step of any machine learning problem is finding the appropriate dataset. For Sign language recognition let's use the Sign Language MNIST dataset. It has images of signs corresponding to each alphabet in the English language. Since the sign language of J and Z requires motion, those two classes are not available in the dataset. Importing L
4 min read
Emojify using Face Recognition with Machine Learning
In this article, we will learn how to implement a modification app that will show an emoji of expression which resembles the expression on your face. This is a fun project based on computer vision in which we use an image classification model in reality to classify different expressions of a person. This project will be implemented in two parts: Bu
7 min read
Audio Recognition in Tensorflow
This article discusses audio recognition and also covers an implementation of a simple audio recognizer in Python using the TensorFlow library which recognizes eight different words. Audio RecognitionAudio recognition comes under the automatic speech recognition (ASR) task which works on understanding and converting raw audio to human-understandabl
8 min read
Face Recognition with Local Binary Patterns (LBPs) and OpenCV
In this article, Face Recognition with Local Binary Patterns (LBPs) and OpenCV is discussed. Let's start with understanding the logic behind performing face recognition using LBPs. A beginner-friendly explanation of LBPs is described below. Local Binary Patterns (LBP)LBP stands for Local Binary Patterns. It's a technique used to describe the textur
13 min read
Optical Character Recognition using TensorFlow
Optical Character Recognition (OCR) stands as a transformative force, bridging the gap between the physical and digital worlds. OCR enables machines to interpret and convert printed or handwritten text into machine-readable data, revolutionizing how we interact with information. This article explores the powerful capabilities of OCR and presents a
8 min read