Real time Yelp reviews analysis and response solutions for restaurant owners

Posted on Sep 29, 2017


Before trying a new restaurant, we frequently consult with review platforms, such as Yelp, Zomato, or Google, where we can read comments from previous diners. Reading those reviews helps to make more informed decisions and can lead to a better dining experience with friends and family. It is clear that reviews are influential with diners, but how powerful can a single review be?

If a business receives one more star in overall rating, it can generate a 5 to 9% increase in revenue according to Michael Luca’s research, “Reviews, Reputation, and Revenue: The Case of”. On the flip side, a single negative review may cost a business 30 future customers, which implies that an unfavorable comment can significantly damage reputation, profitability, and trustworthiness of a business.

Given that a single bad review can harm a business, how can the business owner mitigate the negative impact? One simple solution is to improve the business’s customer relationship management system, by raising review complaints to the business’s attention and developing an automated real-time complaint response engine.

Our code is available on GitHub, and we have also created a Shiny App to demonstrate the responses in action.  



After selecting the problem and possible business resolution, we chose the Yelp Open Dataset published on September 1, 2017 as our dataset. After inspecting and cleaning the data, we conducted sentiment analysis to separate the positive reviews from the complaints. We then used the spaCy package to preprocess the complaint review text, and we used the gensim package to train n-gram phrase models and Latent Dirichelet Allocation topic models. Finally, we built an automated response chatbot to demonstrate the response to different types of complaints.


Sentiment Analysis

Determining the sentiment of a review is a deceptively complex problem. As our dataset was unlabeled, it was necessary for us to use an unsupervised method to identify the complaint reviews. We considered several options to achieve this goal.  

First, we considered using the number of review stars as a pseudo-label, assuming all one and two star reviews were complaints. However, upon further inspection it became clear that different reviewers have different standards; a three-star review from one reviewer may describe  a negative experience, while a two-star review from a different reviewer may describe a balanced experience.  

Second, we considered normalizing each review against the reviewer’s own standards to attempt to control for individual preferences and biases. To do this, we calculated the difference between the number of stars given for each review and that reviewer’s average star rating across all reviews. For example, if a reviewer’s average star rating is 3.5, a 2 star rating for an individual review would generate a  “stars_dif” rating of -1.5.  

However, this approach raised problems as well. The mean average star rating across all reviewers is 3.75, which means that the distribution of stars_dif will be skewed negative. We also found a large grouping of data points at stars_dif = 0, due to reviewers with a single review or reviewers giving the same star rating across all reviews.  Thus we believe that stars_dif may not be a reliable indicator of sentiment.

FInally, we decided to look into the actual text of the reviews to determine sentiment. We created a sentiment score rating by tokenizing and processing the text of the reviews using NLTK, and calculating the ratio of positive words vs. negative words in the text using dictionaries of sentiment words. We used the following formula for each review:  

(pos_words - neg_words) / total_words

Each review received a score bounded by -1 and 1; a more negative is closer to -1, while a more positive review is closer to 1.  


Topic Modeling

After we separated the complaints from the positive reviews, we built topic models to categorize the complaint reviews based on the subjects discussed in the text. We trained bigram and trigram models using the Gensim package, creating phrases by linking individual words based on a ratio of the frequency of their appearance together versus the frequency apart.  

After completing n-gram transformations, we trained a Latent Direchlet Allocation model, which is designed to uncover some of the latent topic structure within a corpus of documents. The user selects the desired number of topics as a hyperparameter, and the model will then assign to each topic an assortment of the individual tokens from the ‘vocabulary’ of the corpus. The LDA model assumes that the combination of topics within each document and the combination of tokens within each topic follows a Dirichlet probability distribution, which means that each document will contain just a few topics, and each topic will contain a small number of tokens.

In practice, the LDA model returns a group of the most frequent words for each topic. Each review in the corpus can be rated with a percentage for each topic, and the LDA model can also be used to classify new reviews by the same topic categories.  

After testing a variety of inputs, we determined that three topics generated the most interpretable results with the greatest separation between topics. We also adjusted the models to eliminate some words which appeared high in the output for all topics, in order to improve separation. While the meaning of each topic necessarily involves an element of human interpretation, we believe the three topics most closely correspond to complaints about price, service quality, and food quality.  


Generating Results on New Text

In order to classify and respond to new Yelp reviews, we wrote code to apply these models to a new input. The code uses the models to assign a primary complaint category and generate an appropriate response to the reviewer based on the complaint category. We then returned these responses to the reviewer via chatbot for demonstration purposes (see below).


Functions of the Shiny App (Check it out)

Interactive Map

In this map, we plot all of the restaurants with negative sentiment score reviews. Users can select the complaint type, and slider inputs can adjust the sentiment score, star rating, and the number of reviews. Notably, the clusters are not spread broadly across the country, because Yelp has only included reviews from 12 states in the dataset. Detailed restaurant information, including restaurant name, category, average star rating, and the number of reviews, is available by clicking on the location tag.


LDA Visualization

We divided negative reviews into three categories. Users can click a circle in the left panel to select a topic, and the bar chart in the right panel will display the 30 most relevant terms for the selected topic, where we define the relevance of a term to a topic, given a weight parameter, 0 ≤ λ ≤ 1, as λ log(p(term | topic)) + (1 - λ) log(p(term | topic)/p(term)). To further explain the influence of changing the value of λ, it adjusts the term rankings -- small values of λ (near 0) highlight potentially rare, but exclusive terms for the selected topic, and large values of λ (near 1) highlight frequent, but not necessarily exclusive, terms for the selected topic.  This can help in assigning an interpretable name or "meaning" to each topic.


Complainteller Chatbot

As the chatbot is built based on LDA results, we classify complaints into three categories -- price, food quality, and service quality. Once the chatbot receives a message, it runs the text through the NLP preprocessing and classification algorithms, ranks the percentage of possible complaint groups and then replies to the review immediately. For the demo video, we selected three-star reviews from NYY Steak (Yankee Stadium), which are new information to the chatbot and are viewed as a neutral comment without applying sentiment analysis. Our chatbot, Complainteller, successfully replies to those negative reviews with appropriate responses.

If you would like to talk to Complainteller, please feel free to register an account on Telegram and then you can start your conversation with @YelpReviews_bot.  Telegram is a free, non-profit cloud-based instant messaging service; bots are represented as Telegram accounts operated by an automated program. They can respond to messages, be invited into groups and be integrated into other programs.


Future Work

For NLP and LDA modeling, we could run more tests on removing different common words to improve the topic groups.  We could test more advanced sentiment score algorithms and models to improve the separation of complaint reviews.

The chatbot currently responds with a single reply to the most prominent topic. However, sometimes, customer complaints are mixed problems. We can further improve the chatbot to reply with an appropriate response incorporating multiple solutions. Additionally, the accuracy of the result depends on the volume of the text. Therefore, creating a common word database and tagging those words into different categories may improve the performance.


About Authors

Yu-Han Chen

Yu-Han is currently pursuing a Master’s degree in Management and Systems at New York University, and being a part-time data scientist and teaching assistant at NYC Data Science Academy. In her prior role as a market research consultant,...
View all posts by Yu-Han Chen >

John Merrick

John is an experienced research analyst with a passion for seeking business insights using quantitative modeling techniques. After eight years as an equities investment analyst covering multiple industries, primarily across technology, media and telecommunications, he developed a deep...
View all posts by John Merrick >

Related Articles

Leave a Comment

Real time Yelp reviews analysis and response solutions for restaurant owners | A bunch of data September 30, 2017
[…] article was first published on R – NYC Data Science Academy Blog, and kindly contributed to […]
Real time Yelp reviews analysis and response solutions for restaurant owners – Mubashir Qasim September 29, 2017
[…] article was first published on R – NYC Data Science Academy Blog, and kindly contributed to […]
Real time Yelp reviews analysis and response solutions for restaurant owners – Cloud Data Architect September 29, 2017
[…] post Real time Yelp reviews analysis and response solutions for restaurant owners appeared first on NYC Data Science Academy […]

View Posts by Categories

Our Recent Popular Posts

View Posts by Tags

#python #trainwithnycdsa 2019 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI