The Wayback Machine - https://web.archive.org/web/20240927180202/https://www.geeksforgeeks.org/python-nlp-analysis-of-restaurant-reviews/
Open In App

Python | NLP analysis of Restaurant reviews

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

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 handling predictive analysis.
Scikit-learn is a free software machine learning library for the Python programming language. Scikit-learn is largely written in Python, with some core algorithms written in Cython to achieve performance. Cython is a superset of the Python programming language, designed to give C-like performance with code that is written mostly in Python.
Let’s understand the various steps involved in text processing and the flow of NLP. 
This algorithm can be easily applied to any other kind of text like classify a book into Romance, Friction, but for now, let’s use a restaurant review dataset to review negative or positive feedback.

Steps involved:

Step 1: Import dataset with setting delimiter as ‘\t’ as columns are separated as tab space. Reviews and their category(0 or 1) are not separated by any other symbol but with tab space as most of the other symbols are is the review (like $ for the price, ….!, etc) and the algorithm might use them as a delimiter, which will lead to strange behavior (like errors, weird output) in output. 

Python
# Importing Libraries
import numpy as np  
import pandas as pd 

# Import dataset
dataset = pd.read_csv('Restaurant_Reviews.tsv', delimiter = '\t') 

To download the Restaurant_Reviews.tsv dataset used, click here.
Step 2: Text Cleaning or Preprocessing 

  • Remove Punctuations, Numbers: Punctuations, Numbers don’t help much in processing the given text, if included, they will just increase the size of a bag of words that we will create as the last step and decrease the efficiency of an algorithm.
  • Stemming: Take roots of the word 
     
  • Convert each word into its lower case: For example, it is useless to have some words in different cases (eg ‘good’ and ‘GOOD’).
Python
# library to clean data
import re 

# Natural Language Tool Kit
import nltk 

nltk.download('stopwords')

# to remove stopword
from nltk.corpus import stopwords

# for Stemming propose 
from nltk.stem.porter import PorterStemmer

# Initialize empty array
# to append clean text 
corpus = [] 

# 1000 (reviews) rows to clean
for i in range(0, 1000): 
    
    # column : "Review", row ith
    review = re.sub('[^a-zA-Z]', ' ', dataset['Review'][i]) 
    
    # convert all cases to lower cases
    review = review.lower() 
    
    # split to array(default delimiter is " ")
    review = review.split() 
    
    # creating PorterStemmer object to
    # take main stem of each word
    ps = PorterStemmer() 
    
    # loop for stemming each word
    # in string array at ith row    
    review = [ps.stem(word) for word in review
                if not word in set(stopwords.words('english'))] 
                
    # rejoin all string array elements
    # to create back into a string
    review = ' '.join(review)  
    
    # append each string to create
    # array of clean text 
    corpus.append(review) 

Examples: Before and after applying above code (reviews = > before, corpus => after)

Step 3: Tokenization, involves splitting sentences and words from the body of the text.
Step 4: Making the bag of words via sparse matrix

  • Take all the different words of reviews in the dataset without repeating of words.
  • One column for each word, therefore there is going to be many columns.
  • Rows are reviews
  • If a word is there in the row of a dataset of reviews, then the count of the word will be there in the row of a bag of words under the column of the word.

Examples: Let’s take a dataset of reviews of only two reviews 

Input : "dam good steak", "good food good service"
Output :

For this purpose we need CountVectorizer class from sklearn.feature_extraction.text. 
We can also set a max number of features (max no. features which help the most via attribute “max_features”). Do the training on the corpus and then apply the same transformation to the corpus “.fit_transform(corpus)” and then convert it into an array. If the review is positive or negative that answer is in the second column of the dataset[:, 1]: all rows and 1st column (indexing from zero).

Python
# Creating the Bag of Words model
from sklearn.feature_extraction.text import CountVectorizer

# To extract max 1500 feature.
# "max_features" is attribute to
# experiment with to get better results
cv = CountVectorizer(max_features = 1500) 

# X contains corpus (dependent variable)
X = cv.fit_transform(corpus).toarray() 

# y contains answers if review
# is positive or negative
y = dataset.iloc[:, 1].values 

Description of the dataset to be used:

  • Columns separated by \t (tab space)
  • First column is about reviews of people
  • In second column, 0 is for negative review and 1 is for positive review

Step 5: Splitting Corpus into Training and Test set. For this, we need class train_test_split from sklearn.cross_validation. Split can be made 70/30 or 80/20 or 85/15 or 75/25, here I choose 75/25 via “test_size”. 
X is the bag of words, y is 0 or 1 (positive or negative).

Python
# Splitting the dataset into
# the Training set and Test set
from sklearn.model_selection import train_test_split

# experiment with "test_size"
# to get better results
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)

# This code is modified by Susobhan Akhuli

Step 6: Fitting a Predictive Model (here random forest) 

  • Since Random forest is an ensemble model (made of many trees) from sklearn.ensemble, import RandomForestClassifier class
  • With 501 trees or “n_estimators” and criterion as ‘entropy’
  • Fit the model via .fit() method with attributes X_train and y_train
Python
# Fitting Random Forest Classification
# to the Training set
from sklearn.ensemble import RandomForestClassifier

# n_estimators can be said as number of
# trees, experiment with n_estimators
# to get better results 
model = RandomForestClassifier(n_estimators = 501,
                            criterion = 'entropy')
                            
model.fit(X_train, y_train) 

Step 7: Predicting Final Results via using .predict() method with attribute X_test

Python
# Predicting the Test set results
y_pred = model.predict(X_test)

y_pred

Output :

array([0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0,
1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0,
1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0,
1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0,
0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1,
1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1,
0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0,
1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1,
1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1,
0, 0, 0, 1, 0, 0, 1, 1])

Note: Accuracy with the random forest was 72%.(It may be different when performed an experiment with different test sizes, here = 0.25).
Step 8: To know the accuracy, a confusion matrix is needed.
Confusion Matrix is a 2X2 Matrix.

TRUE POSITIVE : measures the proportion of actual positives that are correctly identified. 
TRUE NEGATIVE : measures the proportion of actual positives that are not correctly identified. 
FALSE POSITIVE : measures the proportion of actual negatives that are correctly identified. 
FALSE NEGATIVE : measures the proportion of actual negatives that are not correctly identified.

Note: True or False refers to the assigned classification being Correct or Incorrect, while Positive or Negative refers to assignment to the Positive or the Negative Category

Python
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix

cm = confusion_matrix(y_test, y_pred)

cm

Output :

array([[102,  28],
[ 41, 79]])

Get the complete notebook and dataset link here:

Notebook link : click here.

Dataset link : click here



Previous Article
Next Article

Similar Reads

Sentiment Analysis of Restaurant Reviews - Machine Learning Project
Online reviews are essential in our decision-making process for choosing where to eat, what to buy, and which services to use. But how do businesses interpret the significance of these reviews for their service quality? That's where sentiment analysis comes in. This article provides an overview of sentiment analysis, common terms, and how Natural L
6 min read
Restaurant Review Analysis Using NLP and SQLite
Normally, a lot of businesses are remained as failures due to lack of profit, lack of proper improvement measures. Mostly, restaurant owners face a lot of difficulties to improve their productivity. This project really helps those who want to increase their productivity, which in turn increases their business profits. This is the main objective of
9 min read
Amazon Product Reviews Sentiment Analysis in Python
Amazon gives a platform to small businesses and companies with modest resources to grow larger. And Because of its popularity, people actually spend time and write detailed reviews, about the brand and the product. So, by analyzing that data we can tell companies a lot about their products and also the ways to enhance the quality of the product. Bu
4 min read
Flipkart Reviews Sentiment Analysis using Python
This article is based on the analysis of the reviews and ratings user gives on Flipkart to make others aware of their experience and moreover about the quality of the product and brand. So, by analyzing that data we can tell the users a lot about the products and also the ways to enhance the quality of the product.  Today we will be using Machine L
5 min read
Sentiment Analysis for Customer Reviews in R
In today's digital age, businesses thrive or perish based on their ability to understand and respond to customer sentiment. Customer reviews on platforms such as Amazon, Yelp, or TripAdvisor provide a treasure trove of data, offering insights into consumer opinions, preferences, and satisfaction levels. Sentiment analysis, a branch of natural langu
13 min read
10 Best AI Tools for Restaurant Operations
Restaurant industry is always looking for new and creative ways to improve its processes, make customers happy, and increase its profits. Since AI has come into existence, now restaurants can use it as a list of tools that can surely transform the way they work. These AI tools for Restaurant Operations are created to make the management of restaura
10 min read
Understanding Semantic Analysis - NLP
Introduction to Semantic AnalysisSemantic Analysis is a subfield of Natural Language Processing (NLP) that attempts to understand the meaning of Natural Language. Understanding Natural Language might seem a straightforward process to us as humans. However, due to the vast complexity and subjectivity involved in human language, interpreting it is qu
6 min read
Sentiment Analysis in Ancient Texts Using NLP Techniques.
Natural language processing (NLP) has undergone significant advancements in recent years, with applications ranging from chatbots to language translation. One intriguing application is sentiment analysis, where the goal is to determine the emotional tone behind a body of text. While this is relatively straightforward with contemporary texts, applyi
5 min read
What is Morphological Analysis in Natural Language Processing (NLP)?
Morphological analysis involves studying the structure and formation of words, which is crucial for understanding and processing language effectively. This article delves into the intricacies of morphological analysis in NLP, its significance, methods, and applications. Table of Content Introduction to Morphological AnalysisImportance of Morphologi
8 min read
NLP Sentiment Analysis for US Election
Natural Language Processing is a subfield of Artificial Intelligence that enables computers to understand, analyze, and manipulate human language. This article discusses the prediction of U.S. election results based on Sentiment Analysis using tweets. What is Sentiment Analysis?Sentiment analysis is a technique through which we can examine a text t
15+ min read
Factor Analysis | Data Analysis
Factor analysis is a statistical method used to analyze the relationships among a set of observed variables by explaining the correlations or covariances between them in terms of a smaller number of unobserved variables called factors. Table of Content What is Factor Analysis?What does Factor mean in Factor Analysis?How to do Factor Analysis (Facto
13 min read
Difference Between Factor Analysis and Principal Component Analysis
Factor Analysis (FA) and Principal Component Analysis (PCA) are two pivotal techniques used for data reduction and structure detection. Despite their similarities, they serve distinct purposes and operate under different assumptions. This article explores the key differences between FA and PCA. Understanding Principal Component Analysis (PCA)Princi
4 min read
Data Analysis through Ethnographic Content Analysis
Ethnographic Content Analysis (ECA) is a qualitative research method that combines the systematic approach of content analysis with the depth and contextual richness of ethnography. This hybrid methodology is particularly useful for exploring complex social phenomena, uncovering patterns, and understanding cultural contexts. In this article, we wil
8 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
Lesk Algorithm in NLP - Python
In Natural Language Processing (NLP), word sense disambiguation (WSD) is the challenge of determining which "sense" (meaning) of a word is activated by its use in a specific context, a process that appears to be mostly unconscious in individuals. Lesk Algorithm is a way of Word Sense Disambiguation. The Lesk algorithm is a dictionary-based approach
3 min read
NLP - BLEU Score for Evaluating Neural Machine Translation - Python
Neural Machine Translation (NMT) is a standard task in NLP that involves translating a text from a source language to a target language. BLEU (Bilingual Evaluation Understudy) is a score used to evaluate the translations performed by a machine translator. In this article, we'll see the mathematics behind the BLEU score and its implementation in Pyt
5 min read
NLP Libraries in Python
In today's AI-driven world, text analysis is fundamental for extracting valuable insights from massive volumes of textual data. Whether analyzing customer feedback, understanding social media sentiments, or extracting knowledge from articles, text analysis Python libraries are indispensable for data scientists and analysts in the realm of artificia
15+ min read
LSTM Based Poetry Generation Using NLP in Python
One of the major tasks that one aims to accomplish in Conversational AI is Natural Language Generation (NLG) which refers to employing models for the generation of natural language. In this article, we will get our hands on NLG by building an LSTM-based poetry generator. Note: The readers of this article are expected to be familiar with LSTM. In or
7 min read
Introduction to pyNLPl: Streamlining NLP Workflows with Python
The pyNLPl library, also known as pineapple, is an advanced Python library for Natural Language Processing (NLP). It offers a wide range of functionalities, from handling and analyzing texts to processing them, making it a valuable tool for NLP engineers. This library can perform simple NLP tasks, such as extracting n-grams, as well as advanced tas
7 min read
NLP Primitives Library: A Powerful Python Library for Natural Language Processing
Natural Language Processing (NLP) is a rapidly evolving field, pivotal in applications like sentiment analysis, chatbots, machine translation, and more. However, building robust NLP models often requires intricate text preprocessing and feature engineering. Enter the NLP Primitives Library—a powerful Python library designed to simplify and accelera
7 min read
NLP Augmentation with nlpaug Python Library
Data augmentation is a crucial step in building robust AI models, especially during the data preparation phase. This process involves adding synthetic data to the existing datasets to enhance the quality and diversity of the training data. For textual models, such as generative chatbots and translators, text augmentation becomes essential. Since th
6 min read
Easy-NLP-Augmentation Library: Simplifying Text Augmentation in Python
Text augmentation is a critical step in data preparation for building robust language models. By creating variations of existing text data, we can enhance the diversity and size of the training dataset, ultimately improving the performance of language models. This process involves applying transformations like word substitution, character manipulat
8 min read
Autocorrector Feature Using NLP In Python
Autocorrect is a way of predicting or making the wrong spellings correct, which makes the tasks like writing paragraphs, reports, and articles easier. Today there are a lot of Websites and Social media platforms that use this concept to make web apps user-friendly. Autocorrector Feature Using NLP In PythonSo, here we are using Machine Learning and
5 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
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
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