Sentiment Analysis

Background

In natural language processing, sentiment analysis refers to determining the emotion expressed in a piece of text. The text can be a sentence, a paragraph, or a document. Emotion categorization can be binary -- positive/negative or happy/sad -- or in three classes -- positive/neutral/negative. Sentiment analysis is applicable in a wide range of services, such as e-commerce sites like Amazon and Taobao, hospitality services like Airbnb and hotels.com, and movie rating sites like Rotten Tomatoes and IMDB. It can be used to gauge from the reviews how the customers feel about the product. Table 1 illustrates an example of sentiment analysis in movie reviews:

Movie Review

Category

Best movie of Xiaogang Feng in recent years!

Positive

Pretty bad. Feels like a tv-series from a local TV-channel

Negative

Politically correct version of Taken ... and boring as Heck

Negative

delightful, mesmerizing, and completely unexpected. The plot is nicely designed.

Positive

Table 1 Sentiment Analysis in Movie Reviews

In natural language processing, sentiment analysis can be categorized as a Text Classification problem, i.e., to categorize a piece of text to a specific class. It involves two related tasks: text representation and classification. Before the emergence of deep learning techniques, the mainstream methods for text representation include BOW (bag of words) and topic modeling, while the latter contains SVM (support vector machine) and LR (logistic regression).

The BOW model does not capture all the information in a piece of text, as it ignores syntax and grammar and just treats the text as a set of words. For example, “this movie is extremely bad“ and “boring, dull, and empty work” describe very similar semantic meaning, yet their BOW representations have very little similarity. Furthermore, “the movie is bad“ and “the movie is not bad“ have high similarity with BOW features, but they express completely opposite semantics.

This chapter introduces a deep learning model that handles these issues in BOW. Our model embeds texts into a low-dimensional space and takes word order into consideration. It is an end-to-end framework and it has large performance improvement over traditional methods [1].

Model Overview

The model we used in this chapter uses Convolutional Neural Networks (CNNs) and Recurrent Neural Networks (RNNs) with some specific extensions.

Revisit to the Convolutional Neural Networks for Texts (CNN)

The convolutional neural network for texts is introduced in chapter recommender_system, here is a brief overview.

CNN mainly contains convolution and pooling operation, with versatile combinations in various applications. We firstly apply the convolution operation: we apply the kernel in each window, extracting features. Convolving by the kernel at every window produces a feature map. Next, we apply max pooling over time to represent the whole sentence, which is the maximum element across the feature map. In real applications, we will apply multiple CNN kernels on the sentences. It can be implemented efficiently by concatenating the kernels together as a matrix. Also, we can use CNN kernels with different kernel size. Finally, concatenating the resulting features produces a fixed-length representation, which can be combined with a softmax to form the model for the sentiment analysis problem.

For short texts, the aforementioned CNN model can achieve very high accuracy [1]. If we want to extract more abstract representations, we may apply a deeper CNN model [2,3].

Recurrent Neural Network (RNN)

RNN is an effective model for sequential data. In terms of computability, the RNN is Turing-complete [4]. Since NLP is a classical problem of sequential data, the RNN, especially its variant LSTM[5]), achieves state-of-the-art performance on various NLP tasks, such as language modeling, syntax parsing, POS-tagging, image captioning, dialog, machine translation, and so forth.

Figure 1. An illustration of an unfolded RNN in time.

As shown in Figure 1, we unfold an RNN: at the $t$-th time step, the network takes two inputs: the $t$-th input vector $\vec{x_t}$ and the latent state from the last time-step $\vec{h_{t-1}}$. From those, it computes the latent state of the current step $\vec{h_t}$. This process is repeated until all inputs are consumed. Denoting the RNN as function $f$, it can be formulated as follows:

where $W_{xh}$ is the weight matrix to feed into the latent layer; $W_{hh}$ is the latent-to-latent matrix; $b_h$ is the latent bias and $\sigma$ refers to the $sigmoid$ function.

In NLP, words are often represented as one-hot vectors and then mapped to an embedding. The embedded feature goes through an RNN as input $x_t$ at every time step. Moreover, we can add other layers on top of RNN, such as a deep or stacked RNN. Finally, the last latent state may be used as a feature for sentence classification.

Long-Short Term Memory (LSTM)

Training an RNN on long sequential data sometimes leads to the gradient vanishing or exploding[6]. To solve this problem Hochreiter S, Schmidhuber J. (1997) proposed Long Short Term Memory (LSTM)[5]).

Compared to the structure of a simple RNN, an LSTM includes memory cell $c$, input gate $i$, forget gate $f$ and output gate $o$. These gates and memory cells dramatically improve the ability for the network to handle long sequences. We can formulate the LSTM-RNN, denoted as a function $F$, as follows：

In the equation，$i_t, f_t, c_t, o_t$ stand for input gate, forget gate, memory cell and output gate, respectively. $W$ and $b$ are model parameters, $\tanh$ is a hyperbolic tangent, and $\odot$ denotes an element-wise product operation. The input gate controls the magnitude of the new input into the memory cell $c$; the forget gate controls the memory propagated from the last time step; the output gate controls the magnitutde of the output. The three gates are computed similarly with different parameters, and they influence memory cell $c$ separately, as shown in Figure 2:

Figure 2. LSTM at time step $t$ [7].

LSTM enhances the ability of considering long-term reliance, with the help of memory cell and gate. Similar structures are also proposed in Gated Recurrent Unit (GRU)[8] with a simpler design. The structures are still similar to RNN, though with some modifications (As shown in Figure 2), i.e., latent status depends on input as well as the latent status of the last time step, and the process goes on recurrently until all inputs are consumed:

$$ h_t=Recrurent(x_t,h_{t-1})$$
where $Recrurent$ is a simple RNN, GRU or LSTM.

Stacked Bidirectional LSTM

For vanilla LSTM, $h_t$ contains input information from previous time-step $1..t-1$ context. We can also apply an RNN with reverse-direction to take successive context $t+1…n$ into consideration. Combining constructing deep RNN (deeper RNN can contain more abstract and higher level semantic), we can design structures with deep stacked bidirectional LSTM to model sequential data[9].

As shown in Figure 3 (3-layer RNN), odd/even layers are forward/reverse LSTM. Higher layers of LSTM take lower-layers LSTM as input, and the top-layer LSTM produces a fixed length vector by max-pooling (this representation considers contexts from previous and successive words for higher-level abstractions). Finally, we concatenate the output to a softmax layer for classification.

Figure 3. Stacked Bidirectional LSTM for NLP modeling.

Dataset

We use IMDB dataset for sentiment analysis in this tutorial, which consists of 50,000 movie reviews split evenly into a 25k train set and a 25k test set. In the labeled train/test sets, a negative review has a score <= 4 out of 10, and a positive review has a score >= 7 out of 10.

paddle.datasets package encapsulates multiple public datasets, including cifar, imdb, mnist, moivelens, and wmt14, etc. There's no need for us to manually download and preprocess IMDB.

After issuing a command python train.py, training will start immediately. The details will be unpacked by the following sessions to see how it works.

Model Configuration

Our program starts with importing necessary packages and initializing some global variables:

Parameter input_dim denotes the dictionary size, and class_dim is the number of categories.

The above Text CNN network extracts high-level features and maps them to a vector of the same size as the categories. paddle.activation.Softmax function or classifier is then used for calculating the probability of the sentence belonging to each category.

The above stacked bidirectional LSTM network extracts high-level features and maps them to a vector of the same size as the categories. paddle.activation.Softmax function or classifier is then used for calculating the probability of the sentence belonging to each category.

To reiterate, we can either invoke convolution_net or stacked_lstm_net. In below steps, we will go with convolution_net.

Next we define an inference_program that simply uses convolution_net to predict output with the input from fluid.layer.data.

Then we define a training_program that uses the result from inference_program to compute the cost with label data.
Also define optimizer_func to specify the optimizer.

In the context of supervised learning, labels of the training set are defined in paddle.layer.data too. During training, cross-entropy is used as loss function in paddle.layer.classification_cost and as the output of the network; During testing, the outputs are the probabilities calculated in the classifier.
First result that returns from the list must be cost.

Model Training

Specify training environment

Specify your training environment, you should specify if the training is on CPU or GPU.

use_cuda=Falseplace=fluid.CUDAPlace(0)ifuse_cudaelsefluid.CPUPlace()

Datafeeder Configuration

Next we define data feeders for test and train. The feeder reads a buf_size of data each time and feed them to the training/testing process.
paddle.dataset.imdb.train will yield records during each pass, after shuffling, a batch input of BATCH_SIZE is generated for training.

Notice for loading and reading IMDB data, it could take up to 1 minute. Please be patient.

Create Lod Tensor with test data

To do inference, we pick 3 potential reviews out of our mind as testing data. Feel free to modify any of them.
We map each word in the reviews to id from word_dict, replaced by 'unknown' if the word is not in word_dict.
Then we create lod data with the id list and use create_lod_tensor to create lod tensor.

reviews_str=['read the book forget the movie','this is a great movie','this is very bad']reviews=[c.split()forcinreviews_str]UNK=word_dict['<unk>']lod=[]forcinreviews:lod.append([word_dict.get(words,UNK)forwordsinc])base_shape=[[len(c)forcinlod]]tensor_words=fluid.create_lod_tensor(lod,base_shape,place)

Infer

Now we can infer and predict probability of positive or negative from each review above.

results=inferencer.infer({'words':tensor_words})fori,rinenumerate(results[0]):print("Predict probability of ",r[0]," to be positive and ",r[1]," to be negative for review \'",reviews_str[i],"\'")

Conclusion

In this chapter, we use sentiment analysis as an example to introduce applying deep learning models on end-to-end short text classification, as well as how to use PaddlePaddle to implement the model. Meanwhile, we briefly introduce two models for text processing: CNN and RNN. In following chapters, we will see how these models can be applied in other tasks.