<p>The source code for this tutorial is live at <ahref="https://github.com/PaddlePaddle/book/tree/develop/02.recognize_digits">book/recognize_digits</a>. For instructions on getting started with Paddle, please refer to <ahref="https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_en.rst">installation instructions</a>.</p>
<p>When one learns to program, the first task is usually to write a program that prints “Hello World!”. In Machine Learning or Deep Learning, the equivalent task is to train a model to recognize hand-written digits on the dataset <ahref="http://yann.lecun.com/exdb/mnist/">MNIST</a>. Handwriting recognition is a classic image classification problem. The problem is relatively easy and MNIST is a complete dataset. As a simple Computer Vision dataset, MNIST contains images of handwritten digits and their corresponding labels (Fig. 1). The input image is a $28\times28$ matrix, and the label is one of the digits from $0$ to $9$. All images are normalized, meaning that they are both rescaled and centered.</p>
<p>The MNIST dataset is created from the <ahref="https://www.nist.gov/srd/nist-special-database-19">NIST</a> Special Database 3 (SD-3) and the Special Database 1 (SD-1). The SD-3 is labeled by the staff of the U.S. Census Bureau, while SD-1 is labeled by high school students the in U.S. Therefore the SD-3 is cleaner and easier to recognize than the SD-1 dataset. Yann LeCun et al. used half of the samples from each of SD-1 and SD-3 to create the MNIST training set (60,000 samples) and test set (10,000 samples), where training set was labeled by 250 different annotators, and it was guaranteed that there wasn’t a complete overlap of annotators of training set and test set.</p>
<p>Yann LeCun, one of the founders of Deep Learning, have previously made tremendous contributions to handwritten character recognition and proposed the <strong>Convolutional Neural Network</strong> (CNN), which drastically improved recognition capability for handwritten characters. CNNs are now a critical concept in Deep Learning. From the LeNet proposal by Yann LeCun, to those winning models in ImageNet competitions, such as VGGNet, GoogLeNet, and ResNet (See <ahref="https://github.com/PaddlePaddle/book/tree/develop/03.image_classification">Image Classification</a> tutorial), CNNs have achieved a series of impressive results in Image Classification tasks.</p>
<p>Many algorithms are tested on MNIST. In 1998, LeCun experimented with single layer linear classifier, Multilayer Perceptron (MLP) and Multilayer CNN LeNet. These algorithms quickly reduced test error from 12% to 0.7% [<ahref="#References">1</a>]. Since then, researchers have worked on many algorithms such as <strong>K-Nearest Neighbors</strong> (k-NN) [<ahref="#References">2</a>], <strong>Support Vector Machine</strong> (SVM) [<ahref="#References">3</a>], <strong>Neural Networks</strong> [<ahref="#References">4-7</a>] and <strong>Boosting</strong> [<ahref="#References">8</a>]. Various preprocessing methods like distortion removal, noise removal, and blurring, have also been applied to increase recognition accuracy.</p>
<p>In this tutorial, we tackle the task of handwritten character recognition. We start with a simple <strong>softmax</strong> regression model and guide our readers step-by-step to improve this model’s performance on the task of recognition.</p>
<p>Before introducing classification algorithms and training procedure, we provide some definitions:<br/>
- $X$ is the input: Input is a $28\times 28$ MNIST image. It is flattened to a $784$ dimensional vector. $X=\left (x_0, x_1, \dots, x_{783} \right )$.<br/>
- $Y$ is the output: Output of the classifier is 1 of the 10 classes (digits from 0 to 9). $Y=\left (y_0, y_1, \dots, y_9 \right )$. Each dimension $y_i$ represents the probability that the input image belongs to class $i$.<br/>
- $L$ is the ground truth label: $L=\left ( l_0, l_1, \dots, l_9 \right )$. It is also 10 dimensional, but only one dimension is 1 and all others are all 0.</p>
<p>In a simple softmax regression model, the input is fed to fully connected layers and a softmax function is applied to get probabilities of multiple output classes[<ahref="#References">9</a>].</p>
<p>The input $X$ is multiplied by weights $W$, and bias $b$ is added to generate activations.</p>
<p>For an $N$-class classification problem with $N$ output nodes, an $N$ dimensional vector is normalized to $N$ real values in the range $[0,1]$, each representing the probability that the sample belongs to a certain class. Here $y_i$ is the prediction probability that an image is digit $i$.</p>
<p>In such a classification problem, we usually use the cross entropy loss function:</p>
<p>The softmax regression model described above uses the simplest two-layer neural network. That is, it only contains an input layer and an output layer. So its regression ability is limited. To achieve better recognition results, consider adding several hidden layers [<ahref="#References">10</a>] between the input layer and the output layer.</p>
<ol>
<li>After the first hidden layer, we get $ H_1 = \phi(W_1X + b_1) $, where $\phi$ is the activation function. Some common ones are sigmoid, tanh and ReLU.</li>
<li>After the second hidden layer, we get $ H_2 = \phi(W_2H_1 + b_2) $.</li>
<li>Finally, the output layer outputs $Y=\text{softmax}(W_3H_2 + b_3)$, the final classification result vector.</li>
</ol>
<p>Fig. 3. shows a Multilayer Perceptron network, with the weights in blue, and the bias in red. +1 indicates that the bias is $1$.</p>
<p>The Convolutional layer is the core of a Convolutional Neural Network. The parameters in this layer are composed of a set of filters or kernels. In the forward step, each kernel moves horizontally and vertically, we compute a dot product of the kernel and the input at the corresponding positions. Then, we add the bias and apply an activation function. The result is a two-dimensional activation map. For example, some kernel may recognize corners, and some may recognize circles. These convolution kernels may respond strongly to the corresponding features.</p>
<p>Fig. 4 is a dynamic graph of a convolutional layer, where depths are not shown for simplicity. Input is $W_1=5, H_1=5, D_1=3$. In fact, this is a common representation for colored images. $W_1$ and $H_1$ of a colored image correspond to the width and height respectively. $D_1$ corresponds to the 3 color channels for RGB. The parameters of the convolutional layer are $K=2, F=3, S=2, P=1$. $K$ is the number of kernels. Here, $Filter W_0$ and $Filter W_1$ are two kernels. $F$ is kernel size. $W0$ and $W1$ are both $3\times3$ matrix in all depths. $S$ is the stride. Kernels move leftwards or downwards by 2 units each time. $P$ is padding, an extension of the input. The gray area in the figure shows zero padding with size 1.</p>
<p>A Pooling layer performs downsampling. The main functionality of this layer is to reduce computation by reducing the network parameters. It also prevents overfitting to some extent. Usually, a pooling layer is added after a convolutional layer. Pooling layer can be of various types like max pooling, average pooling, etc. Max pooling uses rectangles to segment the input layer into several parts and computes the maximum value in each part as the output (Fig. 5.)</p>
<p><ahref="http://yann.lecun.com/exdb/lenet/">LeNet-5</a> is one of the simplest Convolutional Neural Networks. Fig. 6. shows its architecture: A 2-dimensional input image is fed into two sets of convolutional layers and pooling layers, this output is then fed to a fully connected layer and a softmax classifier. The following three properties of convolution enable LeNet-5 to better recognize images than Multilayer fully connected perceptrons:</p>
<ul>
<li>3D properties of neurons: a convolutional layer is organized by width, height and depth. Neurons in each layer are connected to only a small region in the previous layer. This region is called the receptive field.</li>
<li>Local connection: A CNN utilizes the local space correlation by connecting local neurons. This design guarantees that the learned filter has a strong response to local input features. Stacking many such layers generates a non-linear filter that is more global. This enables the network to first obtain good representation for small parts of input and then combine them to represent a larger region.</li>
<li>Sharing weights: In a CNN, computation is iterated on shared parameters (weights and bias) to form a feature map. This means all neurons in the same depth of the output respond to the same feature. This allows detecting a feature regardless of its position in the input and enables translation equivariance.</li>
</ul>
<p>For more details on Convolutional Neural Networks, please refer to <ahref="http://cs231n.github.io/convolutional-networks/">this Stanford open course</a> and <ahref="https://github.com/PaddlePaddle/book/blob/develop/image_classification/README.md">this Image Classification</a> tutorial.</p>
<h3id="list-of-common-activation-functions"><aname="user-content-list-of-common-activation-functions"href="#list-of-common-activation-functions"class="headeranchor-link"aria-hidden="true"><spanclass="headeranchor"></span></a>List of Common Activation Functions</h3>
<p>In fact, tanh function is just a rescaled version of the sigmoid function. It is obtained by magnifying the value of the sigmoid function and moving it downwards by 1.</p>
<p>PaddlePaddle provides a Python module, <code>paddle.dataset.mnist</code>, which downloads and caches the <ahref="http://yann.lecun.com/exdb/mnist/">MNIST dataset</a>. The cache is under <code>/home/username/.cache/paddle/dataset/mnist</code>:</p>
<li>Convolution network LeNet-5: the input image is fed through two convolution-pooling layers, a fully-connected layer, and the softmax output layer:</li>
<p>PaddlePaddle provides a special layer <code>layer.data</code> for reading data. Let us create a data layer for reading images and connect it to a classification network created using one of above three functions. We also need a cost layer for training the model.</p>
<p>Now, it is time to specify training parameters. In the following <code>Momentum</code> optimizer, <code>momentum=0.9</code> means that 90% of the current momentum comes from that of the previous iteration. The learning rate relates to the speed at which the network training converges. Regularization is meant to prevent over-fitting; here we use the L2 regularization.</p>
<p>Then we specify the training data <code>paddle.dataset.movielens.train()</code> and testing data <code>paddle.dataset.movielens.test()</code>. These two methods are <em>reader creators</em>. Once called, a reader creator returns a <em>reader</em>. A reader is a Python method, which, once called, returns a Python generator, which yields instances of data.</p>
<p><code>shuffle</code> is a reader decorator. It takes in a reader A as input and returns a new reader B. Under the hood, B calls A to read data in the following fashion: it copies in <code>buffer_size</code> instances at a time into a buffer, shuffles the data, and yields the shuffled instances one at a time. A large buffer size would yield very shuffled data.</p>
<p><code>batch</code> is a special decorator, which takes in reader and outputs a <em>batch reader</em>, which doesn’t yield an instance, but a minibatch at a time.</p>
<p>During training, <code>trainer.train</code> invokes <code>event_handler</code> for certain events. This gives us a chance to print the training progress.</p>
# Test with Pass 0, Cost 0.326659, {'classification_error_evaluator': 0.09470000118017197}
</code></pre>
<p>After the training, we can check the model’s prediction accuracy.</p>
<pre><code># find the best pass
best = sorted(lists, key=lambda list: float(list[1]))[0]
print 'Best pass is %s, testing Avgcost is %s' % (best[0], best[1])
print 'The classification accuracy is %.2f%%' % (100 - float(best[2]) * 100)
</code></pre>
<p>Usually, with MNIST data, the softmax regression model achieves an accuracy around 92.34%, the MLP 97.66%, and the convolution network around 99.20%. Convolution layers have been widely considered a great invention for image processing.</p>
<p>This tutorial describes a few basic Deep Learning models using Softmax regression, Multilayer Perceptron Network, and Convolutional Neural Network. The subsequent tutorials will derive more sophisticated models from these. It is crucial to understand these models for future learning. When our model evolves from a simple softmax regression to slightly complex Convolutional Neural Network, the recognition accuracy on the MNIST data set achieves large improvement in accuracy. This is due to the Convolutional layers’ local connections and parameter sharing. While learning new models in the future, we encourage the readers to understand the key ideas that lead a new model to improve the results of an old one. Moreover, this tutorial introduces the basic flow of PaddlePaddle model design, which starts with a <em>dataprovider</em>, a model layer construction, and finally training and prediction. Readers can leverage the flow used in this MNIST handwritten digit classification example and experiment with different data and network architectures to train models for classification tasks of their choice.</p>
<li>LeCun, Yann, Léon Bottou, Yoshua Bengio, and Patrick Haffner. <ahref="http://ieeexplore.ieee.org/abstract/document/726791/">“Gradient-based learning applied to document recognition.”</a> Proceedings of the IEEE 86, no. 11 (1998): 2278-2324.</li>
<li>Wejéus, Samuel. <ahref="http://www.diva-portal.org/smash/record.jsf?pid=diva2%3A753279&dswid=-434">“A Neural Network Approach to Arbitrary SymbolRecognition on Modern Smartphones.”</a> (2014).</li>
<li>Decoste, Dennis, and Bernhard Schölkopf. <ahref="http://link.springer.com/article/10.1023/A:1012454411458">“Training invariant support vector machines.”</a> Machine learning 46, no. 1-3 (2002): 161-190.</li>
<li>Simard, Patrice Y., David Steinkraus, and John C. Platt. <ahref="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.160.8494&rep=rep1&type=pdf">“Best Practices for Convolutional Neural Networks Applied to Visual Document Analysis.”</a> In ICDAR, vol. 3, pp. 958-962. 2003.</li>
<li>Salakhutdinov, Ruslan, and Geoffrey E. Hinton. <ahref="http://www.jmlr.org/proceedings/papers/v2/salakhutdinov07a/salakhutdinov07a.pdf">“Learning a Nonlinear Embedding by Preserving Class Neighbourhood Structure.”</a> In AISTATS, vol. 11. 2007.</li>
<li>Cireşan, Dan Claudiu, Ueli Meier, Luca Maria Gambardella, and Jürgen Schmidhuber. <ahref="http://www.mitpressjournals.org/doi/abs/10.1162/NECO_a_00052">“Deep, big, simple neural nets for handwritten digit recognition.”</a> Neural computation 22, no. 12 (2010): 3207-3220.</li>
<li>Deng, Li, Michael L. Seltzer, Dong Yu, Alex Acero, Abdel-rahman Mohamed, and Geoffrey E. Hinton. <ahref="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.185.1908&rep=rep1&type=pdf">“Binary coding of speech spectrograms using a deep auto-encoder.”</a> In Interspeech, pp. 1692-1695. 2010.</li>
<li>Kégl, Balázs, and Róbert Busa-Fekete. <ahref="http://dl.acm.org/citation.cfm?id=1553439">“Boosting products of base classifiers.”</a> In Proceedings of the 26th Annual International Conference on Machine Learning, pp. 497-504. ACM, 2009.</li>
<li>Rosenblatt, Frank. <ahref="http://psycnet.apa.org/journals/rev/65/6/386/">“The perceptron: A probabilistic model for information storage and organization in the brain.”</a> Psychological review 65, no. 6 (1958): 386.</li>
<li>Bishop, Christopher M. <ahref="http://users.isr.ist.utl.pt/~wurmd/Livros/school/Bishop%20-%20Pattern%20Recognition%20And%20Machine%20Learning%20-%20Springer%20%202006.pdf">“Pattern recognition.”</a> Machine Learning 128 (2006): 1-58.</li>
</ol>
<p><br/><br/>
This tutorial is contributed by <axmlns:cc="http://creativecommons.org/ns#"href="http://book.paddlepaddle.org"property="cc:attributionName"rel="cc:attributionURL">PaddlePaddle</a>, and licensed under a <arel="license"href="http://creativecommons.org/licenses/by-nc-sa/4.0/">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.</p></article></body></html>
<p>The source codes of this section can be located at <ahref="https://github.com/PaddlePaddle/book/tree/develop/understand_sentiment">book/understand_sentiment</a>. First-time users may refer to PaddlePaddle for <ahref="https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_en.rst">Installation guide</a>.</p>
<p>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:</p>
<table>
<thead>
<tr>
<th>Movie Review</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<tr>
<td>Best movie of Xiaogang Feng in recent years!</td>
<td>Positive</td>
</tr>
<tr>
<td>Pretty bad. Feels like a tv-series from a local TV-channel</td>
<td>Negative</td>
</tr>
<tr>
<td>Politically correct version of Taken … and boring as Heck</td>
<td>Negative</td>
</tr>
<tr>
<td>delightful, mesmerizing, and completely unexpected. The plot is nicely designed.</td>
<td>Positive</td>
</tr>
</tbody>
</table>
<palign="center">Table 1 Sentiment Analysis in Movie Reviews</p>
<p>In natural language processing, sentiment analysis can be categorized as a <strong>Text Classification problem</strong>, 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 (<em>bag of words</em>) and topic modeling, while the latter contain SVM (<em>support vector machine</em>) and LR (<em>logistic regression</em>).</p>
<p>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 with 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.</p>
<p>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 [<ahref="#Reference">1</a>].</p>
<p>The model we used in this chapter uses <strong>Convolutional Neural Networks</strong> (<strong>CNNs</strong>) and <strong>Recurrent Neural Networks</strong> (<strong>RNNs</strong>) with some specific extensions.</p>
<h3id="convolutional-neural-networks-for-texts-cnn"><aname="user-content-convolutional-neural-networks-for-texts-cnn"href="#convolutional-neural-networks-for-texts-cnn"class="headeranchor-link"aria-hidden="true"><spanclass="headeranchor"></span></a>Convolutional Neural Networks for Texts (CNN)</h3>
<p><strong>Convolutional Neural Networks</strong> are frequently applied to data with grid-like topology such as two-dimensional images and one-dimensional texts. A CNN can extract multiple local features, combine them, and produce high-level abstractions, which correspond to semantic understanding. Empirically, CNN is shown to be efficient for image and text modeling.</p>
<p>CNN mainly contains convolution and pooling operation, with versatile combinations in various applications. Here, we briefly describe a CNN used to classify texts[<ahref="#Refernce">1</a>], as shown in Figure 1.</p>
<p>Let $n$ be the length of the sentence to process, and the $i$-th word has embedding as $x_i\in\mathbb{R}^k$,where $k$ is the embedding dimensionality.</p>
<p>First, we concatenate the words by piecing together every $h$ words, each as a window of length $h$. This window is denoted as $x_{i:i+h-1}$, consisting of $x_{i},x_{i+1},\ldots,x_{i+h-1}$, where $x_i$ is the first word in the window and $i$ takes value ranging from $1$ to $n-h+1$: $x_{i:i+h-1}\in\mathbb{R}^{hk}$.</p>
<p>Next, we apply the convolution operation: we apply the kernel $w\in\mathbb{R}^{hk}$ in each window, extracting features $c_i=f(w\cdot x_{i:i+h-1}+b)$, where $b\in\mathbb{R}$ is the bias and $f$ is a non-linear activation function such as $sigmoid$. Convolving by the kernel at every window ${x_{1:h},x_{2:h+1},\ldots,x_{n-h+1:n}}$ produces a feature map in the following form:</p>
<p>$$c=[c_1,c_2,\ldots,c_{n-h+1}], c \in \mathbb{R}^{n-h+1}$$</p>
<p>Next, we apply <em>max pooling</em> over time to represent the whole sentence $\hat c$, which is the maximum element across the feature map:</p>
<p>$$\hat c=max(c)$$</p>
<p>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 (as shown in Figure 1 in different colors).</p>
<p>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.</p>
<p>For short texts, the aforementioned CNN model can achieve very high accuracy [<ahref="#Reference">1</a>]. If we want to extract more abstract representations, we may apply a deeper CNN model [<ahref="#Reference">2</a>,<ahref="#Reference">3</a>].</p>
<p>RNN is an effective model for sequential data. In terms of computability, the RNN is Turing-complete [<ahref="#Reference">4</a>]. Since NLP is a classical problem on sequential data, the RNN, especially its variant LSTM[<ahref="#Reference">5</a>]), 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.</p>
Figure 2. An illustration of an unfolded RNN in time.
</p>
<p>As shown in Figure 2, 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:</p>
<p>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.</p>
<p>In NLP, words are often represented as a 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.</p>
<h3id="long-short-term-memory-lstm"><aname="user-content-long-short-term-memory-lstm"href="#long-short-term-memory-lstm"class="headeranchor-link"aria-hidden="true"><spanclass="headeranchor"></span></a>Long-Short Term Memory (LSTM)</h3>
<p>Training an RNN on long sequential data sometimes leads to the gradient vanishing or exploding[<ahref="#">6</a>]. To solve this problem Hochreiter S, Schmidhuber J. (1997) proposed <strong>Long Short Term Memory</strong> (LSTM)[<ahref="#Reference">5</a>]). </p>
<p>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 <strong>LSTM-RNN</strong>, denoted as a function $F$, as follows:</p>
<p>$$ h_t=F(x_t,h_{t-1})$$</p>
<p>$F$ contains following formulations[<ahref="#Reference">7</a>]:<br/>
\begin{align}<br/>
i_t & = \sigma(W_{xi}x_t+W_{hi}h_{h-1}+W_{ci}c_{t-1}+b_i)\\<br/>
f_t & = \sigma(W_{xf}x_t+W_{hf}h_{h-1}+W_{cf}c_{t-1}+b_f)\\<br/>
c_t & = f_t\odot c_{t-1}+i_t\odot \tanh(W_{xc}x_t+W_{hc}h_{h-1}+b_c)\\<br/>
o_t & = \sigma(W_{xo}x_t+W_{ho}h_{h-1}+W_{co}c_{t}+b_o)\\<br/>
h_t & = o_t\odot \tanh(c_t)\\<br/>
\end{align}</p>
<p>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. The $tanh$ is a hyperbolic tangent, and $\odot$ denotes an element-wise product operation. Input gate controls the magnitude of new input into the memory cell $c$; forget gate controls memory propagated from the last time step; output gate controls output magnitude. The three gates are computed similarly with different parameters, and they influence memory cell $c$ separately, as shown in Figure 3:</p>
<p>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)[<ahref="Reference">8</a>] with simpler design. <strong>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 last time-step, and the process goes on recurrently until all input are consumed:</strong></p>
<p>$$ h_t=Recrurent(x_t,h_{t-1})$$<br/>
where $Recrurent$ is a simple RNN, GRU or LSTM.</p>
<p>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[<ahref="#Reference">9</a>].</p>
<p>As shown in Figure 4 (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.</p>
<p>We use <ahref="http://ai.stanford.edu/%7Eamaas/data/sentiment/">IMDB</a> dataset for sentiment analysis in this tutorial, which consists of 50,000 movie reviews split evenly into 25k train and 25k test sets. 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.</p>
<p><code>paddle.datasets</code> package encapsulates multiple public datasets, including <code>cifar</code>, <code>imdb</code>, <code>mnist</code>, <code>moivelens</code>, and <code>wmt14</code>, etc. There’s no need for us to manually download and preprocess IMDB.</p>
<p>After issuing a command <code>python train.py</code>, training will start immediately. The details will be unpacked by the following sessions to see how it works.</p>
<p>We must import and initialize PaddlePaddle (enable/disable GPU, set the number of trainers, etc).</p>
<pre><codeclass="python">import sys
import paddle.v2 as paddle
# PaddlePaddle init
paddle.init(use_gpu=False, trainer_count=1)
</code></pre>
<p>As alluded to in section <ahref="#model-overview">Model Overview</a>, here we provide the implementations of both Text CNN and Stacked-bidirectional LSTM models.</p>
<p>Parameter <code>input_dim</code> denotes the dictionary size, and <code>class_dim</code> is the number of categories. In <code>convolution_net</code>, the input to the network is defined in <code>paddle.layer.data</code>.</p>
</li>
<li>
<p>Define Classifier</p>
<p>The above Text CNN network extracts high-level features and maps them to a vector of the same size as the categories. <code>paddle.activation.Softmax</code> function or classifier is then used for calculating the probability of the sentence belonging to each category.</p>
</li>
<li>
<p>Define Loss Function</p>
<p>In the context of supervised learning, labels of the training set are defined in <code>paddle.layer.data</code>, too. During training, cross-entropy is used as loss function in <code>paddle.layer.classification_cost</code> and as the output of the network; During testing, the outputs are the probabilities calculated in the classifier.</p>
<p>Parameter <code>input_dim</code> denotes the dictionary size, and <code>class_dim</code> is the number of categories. In <code>stacked_lstm_net</code>, the input to the network is defined in <code>paddle.layer.data</code>.</p>
</li>
<li>
<p>Define Classifier</p>
<p>The above stacked bidirectional LSTM network extracts high-level features and maps them to a vector of the same size as the categories. <code>paddle.activation.Softmax</code> function or classifier is then used for calculating the probability of the sentence belonging to each category.</p>
</li>
<li>
<p>Define Loss Function</p>
<p>In the context of supervised learning, labels of the training set are defined in <code>paddle.layer.data</code>, too. During training, cross-entropy is used as loss function in <code>paddle.layer.classification_cost</code> and as the output of the network; During testing, the outputs are the probabilities calculated in the classifier.</p>
</li>
</ol>
<p>To reiterate, we can either invoke <code>convolution_net</code> or <code>stacked_lstm_net</code>.</p>
<p><code>feeding</code> is devoted to specifying the correspondence between each yield record and <code>paddle.layer.data</code>. For instance, the first column of data generated by <code>paddle.dataset.imdb.train()</code> corresponds to <code>word</code> feature.</p>
<p>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.</p>
<li>Kim Y. <ahref="http://arxiv.org/pdf/1408.5882">Convolutional neural networks for sentence classification</a>[J]. arXiv preprint arXiv:1408.5882, 2014.</li>
<li>Kalchbrenner N, Grefenstette E, Blunsom P. <ahref="http://arxiv.org/pdf/1404.2188.pdf?utm_medium=App.net&utm_source=PourOver">A convolutional neural network for modelling sentences</a>[J]. arXiv preprint arXiv:1404.2188, 2014.</li>
<li>Yann N. Dauphin, et al. <ahref="https://arxiv.org/pdf/1612.08083v1.pdf">Language Modeling with Gated Convolutional Networks</a>[J] arXiv preprint arXiv:1612.08083, 2016.</li>
<li>Siegelmann H T, Sontag E D. <ahref="http://research.cs.queensu.ca/home/akl/cisc879/papers/SELECTED_PAPERS_FROM_VARIOUS_SOURCES/05070215382317071.pdf">On the computational power of neural nets</a>[C]//Proceedings of the fifth annual workshop on Computational learning theory. ACM, 1992: 440-449.</li>
<li>Bengio Y, Simard P, Frasconi P. <ahref="http://www-dsi.ing.unifi.it/~paolo/ps/tnn-94-gradient.pdf">Learning long-term dependencies with gradient descent is difficult</a>[J]. IEEE transactions on neural networks, 1994, 5(2): 157-166.</li>
<li>Graves A. <ahref="http://arxiv.org/pdf/1308.0850">Generating sequences with recurrent neural networks</a>[J]. arXiv preprint arXiv:1308.0850, 2013.</li>
<li>Cho K, Van Merriënboer B, Gulcehre C, et al. <ahref="http://arxiv.org/pdf/1406.1078">Learning phrase representations using RNN encoder-decoder for statistical machine translation</a>[J]. arXiv preprint arXiv:1406.1078, 2014.</li>
<li>Zhou J, Xu W. <ahref="http://www.aclweb.org/anthology/P/P15/P15-1109.pdf">End-to-end learning of semantic role labeling using recurrent neural networks</a>[C]//Proceedings of the Annual Meeting of the Association for Computational Linguistics. 2015.</li>
</ol>
<p><br/><br/>
This tutorial is contributed by <axmlns:cc="http://creativecommons.org/ns#"href="http://book.paddlepaddle.org"property="cc:attributionName"rel="cc:attributionURL">PaddlePaddle</a>, and licensed under a <arel="license"href="http://creativecommons.org/licenses/by-nc-sa/4.0/">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.</p></article></body></html>