Coursera Capstone: Milestone Report

Based on Reviews predict customer ratings for the Restaurants in Nevada.

Most topic models, such as latent Dirichlet allocation (LDA), are unsupervised: only the words in the documents are modelled. The goal is to infer topics that maximize the likelihood (or the posterior probability) of the collection of terms. In this work, we develop supervised topic models sLDA, where each document is paired with a response.

In this document we used LDA(Latent Dirichlet Allocation) which is simple and widely used to uncover the underlying semantic structure of text.LDAvis is used to visualize the output for LDA model. We fit another model sLDA to predict star ratings based on customer reviews.

The data

First we get the yelp data which is in JSON data format with 5 datasets into R.The data sets are Business, Review, Tip, User and Check-in. Accoding to the question We are focusing on Business & review data. Business data has 61184 observations with 118 variables where as review has 1569264 observations with 8 variables. Out of Restaurant category in Business dataset took a sample of 5000 and did inner join with review dataset. Extracted data related to Nevada city from the resultent dataset. Thus obtained dataset has 216924 observations with 125 variables.

We took a sample of 1000 observations for each ratings.Thus we have 5000 observations of all 1-5 star ratings

# load necessary libraries
library(LDAvis)
## Warning: package 'LDAvis' was built under R version 3.2.2
library(servr)
## Warning: package 'servr' was built under R version 3.2.2
library(lda)
## Warning: package 'lda' was built under R version 3.2.2
library(tm)
## Warning: package 'tm' was built under R version 3.2.2
## Loading required package: NLP
## Warning: package 'NLP' was built under R version 3.2.2
load("Review_Stars.RDA")

Pre-processing

Before fitting a topic model, we need to tokenize the text. This dataset is already fairly clean, so we only remove punctuation and some common stop words. In particular, we use the english stop words from the SMART information retrieval system, available in the R package tm.

Review <- review_Stars$text
stop_words <- stopwords("SMART")
# pre-processing:
Review <- gsub("'", "", Review)  # remove apostrophes
Review <- gsub("[[:punct:]]", " ", Review)  # replace punctuation with space
Review <- gsub("[[:cntrl:]]", " ", Review)  # replace control characters with space
Review <- gsub("^[[:space:]]+", "", Review) # remove whitespace at beginning of documents
Review <- gsub("[[:space:]]+$", "", Review) # remove whitespace at end of documents
Review <- gsub("[[0-9]]", "", Review) # remove numbers 
Review <- tolower(Review)  # force to lowercase

# tokenize on space and output as a list:
doc.list <- strsplit(Review, "[[:space:]]+")

# compute the table of terms:
term.table <- table(unlist(doc.list))
term.table <- sort(term.table, decreasing = TRUE)

# remove terms that are stop words or occur fewer than 5 times:
del <- names(term.table) %in% stop_words | term.table < 5
term.table <- term.table[!del]
vocab <- names(term.table)

# now put the documents into the format required by the lda package:
get.terms <- function(x) {
  index <- match(x, vocab)
  index <- index[!is.na(index)]
  rbind(as.integer(index - 1), as.integer(rep(1, length(index))))
}
documents <- lapply(doc.list, get.terms)

Using the R package ‘lda’ for model fitting

The object ‘documents’ is a list, where each element represents one document. After creating this list, we compute a few statistics about the corpus

# Compute some statistics related to the data set:
D <- length(documents)  # number of documents 
W <- length(vocab)  # number of terms in the vocab 
doc.length <- sapply(documents, function(x) sum(x[2, ]))  # number of tokens per document 
N <- sum(doc.length)  # total number of tokens in the data 
term.frequency <- as.integer(term.table)  # frequencies of terms in the corpus

Next, we set up a topic model with 20 topics, relatively diffuse priors for the topic-term distributions (η = 0.02) and document-topic distributions (α = 0.02), and we set the collapsed Gibbs sampler to run for 5,000 iterations (slightly conservative to ensure convergence). A visual inspection of fit$log.likelihood shows that the MCMC algorithm has converged after 5,000 iterations .

# MCMC and model tuning parameters:
K <- 20
G <- 5000
alpha <- 0.02
eta <- 0.02

set.seed(3571)
t1 <- Sys.time()

fit <- lda.collapsed.gibbs.sampler(documents = documents, K = K, vocab = vocab, 
                                   num.iterations = G, alpha = alpha, 
                                   eta = eta, initial = NULL, burnin = 0,
                                   compute.log.likelihood = TRUE)


t2 <- Sys.time()
t2 - t1  # time taken to run the model
## Time difference of 51.14349 mins
#save(fit,file="Gibbs_fit.RDA")

Visualizing the fitted model with LDAvis

To visualize the result using LDAvis, we’ll need estimates of the document-topic distributions, which we denote by the D×K matrix θ , and the set of topic-term distributions, which we denote by the K×W matrix ϕ . We estimate the “smoothed” versions of these distributions (“smoothed” means that we’ve incorporated the effects of the priors into the estimates) by cross-tabulating the latent topic assignments from the last iteration of the collapsed Gibbs sampler with the documents and the terms, respectively, and then adding pseudocounts according to the priors. A better estimator might average over multiple iterations of the Gibbs sampler (after convergence, assuming that the MCMC is sampling within a local mode and there is no label switching occurring), but we won’t worry about that for now.

# Visualizing the fitted model with LDAvis
theta <- t(apply(fit$document_sums + alpha, 2, function(x) x/sum(x)))
phi <- t(apply(t(fit$topics) + eta, 2, function(x) x/sum(x)))

We’ve already computed the number of tokens per document and the frequency of the terms across the entire corpus. We save these, along with ϕ , θ , and vocab, in a list as the data object RestaurantReviews, which is included in the LDAvis package.

RestaurantReviews <- list(phi = phi,
                          theta = theta,
                          doc.length = doc.length,
                          vocab = vocab,
                          term.frequency = term.frequency)

Now we’re ready to call the createJSON() function in LDAvis. This function will return a character string representing a JSON object used to populate the visualization. The createJSON() function computes topic frequencies, inter-topic distances, and projects topics onto a two-dimensional plane to represent their similarity to each other. It also loops through a grid of values of a tuning parameter, 0≤λ≤1 , that controls how the terms are ranked for each topic, where terms are listed in decreasing of relevance, where the relevance of term w to topic t is defined as λ×p(w∣t)+(1−λ)×p(w∣t)/p(w) . Values of λ near 1 give high relevance rankings to frequent terms within a given topic, whereas values of λ near zero give high relevance rankings to exclusive terms within a topic. The set of all terms which are ranked among the top-R most relevant terms for each topic are pre-computed by the createJSON() function and sent to the browser to be interactively visualized using D3 as part of the JSON object.

# create the JSON object to feed the visualization:
lda.json <- createJSON(phi = RestaurantReviews$phi, 
                   theta = RestaurantReviews$theta, 
                   doc.length = RestaurantReviews$doc.length, 
                   vocab = RestaurantReviews$vocab, 
                   term.frequency = RestaurantReviews$term.frequency)

The serVis() function can take json and serve the result in a variety of ways. Here we’ll write json to a file within the ‘vis’ directory (along with other HTML and JavaScript required to render the page).

# serVis(json)
serVis(lda.json, out.dir='vis',open.browser =TRUE)

sLDA model (supervised LDA - sLDA)

lexicalize reads raw text in doclines format and returns a corpus and vocabulary suitable for the inference procedures defined in the lda package.sLDA take sparsely represented input documents, perform inference, and return point estimates of the latent parameters using the state at the last iteration of Gibbs sampling.

doc_myCorpus <- lexicalize(review_Stars$text, sep = " ", lower = TRUE, count = 1L, vocab = NULL)
# review ratings
ratings <- review_Stars$stars.x
# number of topics
num.topics <- 10
## Initialize the params
set.seed(315711)
params <- sample(c(-1, 1), num.topics, replace=TRUE)
## Initialize the params ,[1] -1 -1  1 -1  1  1 -1  1  1  1
# fit sLDA model
fit_slda <- slda.em(documents=doc_myCorpus$documents,
                  K=num.topics,
                  vocab=doc_myCorpus$vocab,
                  num.e.iterations=10,
                  num.m.iterations=4,
                  alpha=1.0, eta=0.1,
                  ratings ,
                  params,
                  variance=0.25,
                  lambda=1.0,
                  logistic=FALSE,
                  method="sLDA")

# get top words in the cluster
Topics <- apply(top.topic.words(fit_slda$topics, 5, by.score=TRUE),
                2, paste, collapse=" ")
coefs <- data.frame(coef(summary(fit_slda$model)))
theme_set(theme_bw())

coefs <- cbind(coefs, Topics=factor(Topics, Topics[order(coefs$Estimate)]))
coefs <- coefs[order(coefs$Estimate),]

# plot point estimates
qplot(Topics, Estimate, colour=Estimate, size=abs(t.value), data=coefs) +
  geom_errorbar(width=0.5, aes(ymin=Estimate-Std..Error,
                               ymax=Estimate+Std..Error)) + coord_flip()

# predictions
predictions <- slda.predict(doc_myCorpus$documents,
                            result$topics, 
                            result$model,
                            alpha = 1.0,
                            eta=0.1)
library(png)
## Warning: package 'png' was built under R version 3.2.2
library(grid)
img <- readPNG("Topic2.png")
grid.raster(img)

Results

The LDAvis System (Topic Model for restaurant Reviews)

Our interactive, web-based visualization system - LDAvis, has two core functionalities that enable users to understand the topic-term relationships in a fitted LDA model, and a number of extra features that provide additional perspectives on the model.First and foremost, LDAvis allows one to select a topic to reveal the most relevant terms for that topic. From the above Figure 1, Topic 2 is selected, and its 30 most relevant terms λ = 1.0, in this case) populate the barchart to the right (ranked in order of relevance from top to bottom). The widths of the gray bars represent the corpus-wide frequencies of each term, and the widths of the red bars represent the topic-specific frequencies of each term. A slider allows users to change the value of λ , which can alter the rankings of terms to aid topic interpretation.By comparing the widths of the red and gray bars for a given term, users can quickly understand whether a term is highly relevant to the selected topic because of its lift (a high ratio of red to gray), or its probability (absolute width of red).

On the left panel, two visual features provide a global perspective of the topics. First, the areas of the circles are proportional to the relative prevalences of the topics in the corpus.In this view, we plot the topics as circles in the two-dimensional plane whose centers are determined by computing the distance between topics, and then by using multidimensional scaling to project the intertopic distances onto two dimensions. We encode each topic’s overall prevalence using the areas of the circles,where we sort the topics in decreasing order of prevalence.

we fit a model using lda.collapsed.gibbs.sampler.Next we created json object and Visualize the fitted model with LDAvis.Finally,we Predicted new words for the first two documents

supervised latent Dirichlet allocation (sLDA), a statistical model of labelled documents. The model accommodates a variety of response types. We derive a maximum-likelihood procedure for parameter estimation, which relies on variational approximations to handle intractable posterior expectations.Prediction problems motivate this research: we use the fitted model to predict response values for new documents.

we fit another model using slda.em. Get point estimation from the model and dipicted. we predicted the model using slda.predict. Always large samples yields better results.

library(png)
library(grid)
img1 <- readPNG("Estimation.png")
grid.raster(img)
grid.raster(img1)

Discussion

We have described a web-based, interactive visualization system, LDAvis, that enables deep inspection of topic-term relationships in an LDA model, while simultaneously providing a global view of the topics, via their prevalences and similarities to each other, in a compact space.For future work, we anticipate performing a larger user study to further understand how to facilitate topic interpretation in fitted LDA models,including a comparison of multiple methods.

We have developed sLDA, a statistical model of labelled documents. The model accommodates the different types of response variable commonly encountered in practice.

We have developed a shiny app which accepts review as user input and predict the star rating.This is not yielding best results for strong negative/strong positive reviews why because sample plays key role in params initialization(params are initialized before fitting a model).The order of param in the above algorithem is -1 -1 1 -1 1 1 -1 1 1 1 i.e four negative and 6 positive which implies that though the review is either strong negative/strong positive its predicting as either neutral/positive (predicting 3 for both.For strong negative it should be 1 and for strong positive it should be 5) Depending on the sample param the estimations are also varing. Another issues could be small sample(always large sample yields better results)

In Future We should work on every aspect like param and sample to yield better results