index_en.html 40.6 KB
Newer Older
1 2


3 4 5 6 7 8 9 10 11 12
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>Sentiment Analysis Tutorial &mdash; PaddlePaddle  documentation</title>
  
Y
Yu Yang 已提交
13

14 15
  
  
Y
Yu Yang 已提交
16

17 18 19 20
  

  
  
Y
Yu Yang 已提交
21
    
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

  

  
  
    <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
  

  
  
        <link rel="index" title="Index"
              href="../../genindex.html"/>
        <link rel="search" title="Search" href="../../search.html"/>
    <link rel="top" title="PaddlePaddle  documentation" href="../../index.html"/> 

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/perfect-scrollbar/0.6.14/css/perfect-scrollbar.min.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/css/override.css" type="text/css" />
  <script>
  var _hmt = _hmt || [];
  (function() {
    var hm = document.createElement("script");
    hm.src = "//hm.baidu.com/hm.js?b9a314ab40d04d805655aab1deee08ba";
    var s = document.getElementsByTagName("script")[0]; 
    s.parentNode.insertBefore(hm, s);
  })();
  </script>

  

  
  <script src="../../_static/js/modernizr.min.js"></script>

</head>

<body class="wy-body-for-nav" role="document">

  
  <header class="site-header">
    <div class="site-logo">
      <a href="/"><img src="../../_static/images/PP_w.png"></a>
    </div>
    <div class="site-nav-links">
      <div class="site-menu">
        <a class="fork-on-github" href="https://github.com/PaddlePaddle/Paddle" target="_blank"><i class="fa fa-github"></i>Folk me on Github</a>
        <div class="language-switcher dropdown">
          <a type="button" data-toggle="dropdown">
            <span>English</span>
            <i class="fa fa-angle-up"></i>
            <i class="fa fa-angle-down"></i>
          </a>
          <ul class="dropdown-menu">
            <li><a href="/doc_cn">中文</a></li>
            <li><a href="/doc">English</a></li>
          </ul>
        </div>
        <ul class="site-page-links">
          <li><a href="/">Home</a></li>
        </ul>
      </div>
      <div class="doc-module">
        
        <ul>
<li class="toctree-l1"><a class="reference internal" href="../../getstarted/index_en.html">GET STARTED</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../howto/index_en.html">HOW TO</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../api/index_en.html">API</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../about/index_en.html">ABOUT</a></li>
</ul>

        
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>        
      </div>
    </div>
  </header>
  
  <div class="main-content-wrap">

Y
Yu Yang 已提交
104
    
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    <nav class="doc-menu-vertical" role="navigation">
        
          
          <ul>
<li class="toctree-l1"><a class="reference internal" href="../../getstarted/index_en.html">GET STARTED</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../../getstarted/build_and_install/index_en.html">Install and Build</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../../getstarted/build_and_install/docker_install_en.html">PaddlePaddle in Docker Containers</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../getstarted/build_and_install/ubuntu_install_en.html">Debian Package installation guide</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../getstarted/build_and_install/build_from_source_en.html">Installing from Sources</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../howto/index_en.html">HOW TO</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../../howto/usage/cmd_parameter/index_en.html">Set Command-line Parameters</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../../howto/usage/cmd_parameter/use_case_en.html">Use Case</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../howto/usage/cmd_parameter/arguments_en.html">Argument Outline</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../howto/usage/cmd_parameter/detail_introduction_en.html">Detail Description</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../../howto/usage/cluster/cluster_train_en.html">Run Distributed Training</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../howto/usage/k8s/k8s_en.html">Paddle On Kubernetes</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../howto/usage/k8s/k8s_aws_en.html">Distributed PaddlePaddle Training on AWS with Kubernetes</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../howto/dev/new_layer_en.html">Write New Layers</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../howto/dev/contribute_to_paddle_en.html">Contribute Code</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../howto/deep_model/rnn/index_en.html">RNN Models</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../howto/optimization/gpu_profiling_en.html">Tune GPU Performance</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../api/index_en.html">API</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../../api/v2/model_configs.html">Model Configuration</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../../api/v2/config/activation.html">Activation</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../api/v2/config/layer.html">Layers</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../api/v2/config/optimizer.html">Optimizer</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../api/v2/config/pooling.html">Pooling</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../api/v2/config/networks.html">Networks</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../api/v2/config/attr.html">Parameter Attribute</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../../api/v2/data.html">Data Reader Interface and DataSets</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../api/v2/run_logic.html">Training and Inference</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../about/index_en.html">ABOUT</a></li>
</ul>

        
    </nav>
Y
Yu Yang 已提交
153
    
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    <section class="doc-content-wrap">

      

 







<div role="navigation" aria-label="breadcrumbs navigation">
  <ul class="wy-breadcrumbs">
      
    <li>Sentiment Analysis Tutorial</li>
  </ul>
</div>
      
      <div class="wy-nav-content" id="doc-content">
        <div class="rst-content">
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
Y
Yu Yang 已提交
177 178 179 180 181 182
            
  <div class="section" id="sentiment-analysis-tutorial">
<span id="sentiment-analysis-tutorial"></span><h1>Sentiment Analysis Tutorial<a class="headerlink" href="#sentiment-analysis-tutorial" title="Permalink to this headline"></a></h1>
<p>Sentiment analysis has many applications. A basic task in sentiment analysis is classifying the polarity of a given text at the document, sentence or feature/aspect level. One simple example is to classify the customer reviews in a shopping website, a tourism website, and group buying websites like Amazon, TaoBao, Tmall etc.</p>
<p>Sentiment analysis is also used to monitor social media based on large amount of reviews or blogs. For example, the researchers analyzed several surveys on consumer confidence and political opinion, found they correlate to sentiment word frequencies in contemporaneous Twitter messages [1]. Another example is to forecast stock movements through analyzing the text content of a daily Twitter blog [2].</p>
<p>On the other hand, grabbing the user comments of products and analyzing their sentiment are useful to understand user preferences for companies, products, even competing products.</p>
183
<p>This tutorial will guide you through the process of training a Long Short Term Memory (LSTM) Network to classify the sentiment of sentences from <a class="reference external" href="http://ai.stanford.edu/~amaas/data/sentiment/">Large Movie Review Dataset</a>, sometimes known as the Internet Movie Database (IMDB). This dataset contains movie reviews along with their associated binary sentiment polarity labels, namely positive and negative. So randomly guessing yields 50% accuracy.</p>
Y
Yu Yang 已提交
184 185 186 187 188
<div class="section" id="data-preparation">
<span id="data-preparation"></span><h2>Data Preparation<a class="headerlink" href="#data-preparation" title="Permalink to this headline"></a></h2>
<div class="section" id="imdb-data-introduction">
<span id="imdb-data-introduction"></span><h3>IMDB Data Introduction<a class="headerlink" href="#imdb-data-introduction" title="Permalink to this headline"></a></h3>
<p>Before training models, we need to preprocess the data and build a dictionary. First, you can use following script to download IMDB dataset and <a class="reference external" href="http://www.statmt.org/moses/">Moses</a> tool, which is a statistical machine translation system. We provide a data preprocessing script, which is capable of handling not only IMDB data, but also other user-defined data. In order to use the pre-written script, it needs to move labeled train and test samples to another path, which has been done in <code class="docutils literal"><span class="pre">get_imdb.sh</span></code>.</p>
189 190
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">cd</span> <span class="n">demo</span><span class="o">/</span><span class="n">sentiment</span><span class="o">/</span><span class="n">data</span>
<span class="o">./</span><span class="n">get_imdb</span><span class="o">.</span><span class="n">sh</span>
Y
Yu Yang 已提交
191 192 193
</pre></div>
</div>
<p>If the data is obtained successfuly, you will see the following files at <code class="docutils literal"><span class="pre">./demo/sentiment/data</span></code>:</p>
194
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">aclImdb</span>  <span class="n">get_imdb</span><span class="o">.</span><span class="n">sh</span>  <span class="n">imdb</span>  <span class="n">mosesdecoder</span><span class="o">-</span><span class="n">master</span>
Y
Yu Yang 已提交
195 196 197 198 199 200 201 202
</pre></div>
</div>
<ul class="simple">
<li>aclImdb: raw dataset downloaded from website.</li>
<li>imdb: only contains train and test data.</li>
<li>mosesdecoder-master: Moses tool.</li>
</ul>
<p>IMDB dataset contains 25,000 highly polar movie reviews for training, and 25,000 for testing. A negative review has a score ≤ 4 out of 10, and a positive review has a score ≥ 7 out of 10. After running <code class="docutils literal"><span class="pre">./get_imdb.sh</span></code>, we can find the dataset has the following structure in <code class="docutils literal"><span class="pre">aclImdb</span></code>.</p>
203
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">imdbEr</span><span class="o">.</span><span class="n">txt</span>  <span class="n">imdb</span><span class="o">.</span><span class="n">vocab</span>  <span class="n">README</span>  <span class="n">test</span>  <span class="n">train</span>
Y
Yu Yang 已提交
204 205 206 207 208 209 210 211 212
</pre></div>
</div>
<ul class="simple">
<li>train: train sets.</li>
<li>test : test sets.</li>
<li>imdb.vocab: dictionary.</li>
<li>imdbEr.txt: expected rating for each token in imdb.vocab.</li>
<li>README: data documentation.</li>
</ul>
213
<p>The file in train set directory is as follows. The test set also contains them except <code class="docutils literal"><span class="pre">unsup</span></code> and <code class="docutils literal"><span class="pre">urls_unsup.txt</span></code>.</p>
214
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">labeledBow</span><span class="o">.</span><span class="n">feat</span>  <span class="n">neg</span>  <span class="n">pos</span>  <span class="n">unsup</span>  <span class="n">unsupBow</span><span class="o">.</span><span class="n">feat</span>  <span class="n">urls_neg</span><span class="o">.</span><span class="n">txt</span>  <span class="n">urls_pos</span><span class="o">.</span><span class="n">txt</span>  <span class="n">urls_unsup</span><span class="o">.</span><span class="n">txt</span>
Y
Yu Yang 已提交
215 216 217 218 219 220 221 222 223 224 225 226 227
</pre></div>
</div>
<ul class="simple">
<li>pos: positive samples, contains 12,500 txt files, each file is one movie review.</li>
<li>neg: negative samples, contains 12,500 txt files, each file is one movie review.</li>
<li>unsup: unlabeled samples, contains 50,000 txt files.</li>
<li>urls_xx.txt: urls of each reviews.</li>
<li>xxBow.feat: already-tokenized bag of words (BoW) features.</li>
</ul>
</div>
<div class="section" id="imdb-data-preparation">
<span id="imdb-data-preparation"></span><h3>IMDB Data Preparation<a class="headerlink" href="#imdb-data-preparation" title="Permalink to this headline"></a></h3>
<p>In this demo, we only use labled train and test set and not use imdb.vocab as dictionary. By default, dictionary is builded on train set. Train set is shuffled and test set is not. <code class="docutils literal"><span class="pre">tokenizer.perl</span></code> in Moses tool is used to tokenize the words and punctuation. Simply execute the following command to preprcess data.</p>
228 229
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">cd</span> <span class="n">demo</span><span class="o">/</span><span class="n">sentiment</span><span class="o">/</span>
<span class="o">./</span><span class="n">preprocess</span><span class="o">.</span><span class="n">sh</span>
Y
Yu Yang 已提交
230 231 232
</pre></div>
</div>
<p>preprocess.sh:</p>
233 234
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">data_dir</span><span class="o">=</span><span class="s2">&quot;./data/imdb&quot;</span>
<span class="n">python</span> <span class="n">preprocess</span><span class="o">.</span><span class="n">py</span> <span class="o">-</span><span class="n">i</span> <span class="n">data_dir</span>
Y
Yu Yang 已提交
235 236 237 238 239 240 241
</pre></div>
</div>
<ul class="simple">
<li>data_dir: input data directory.</li>
<li>preprocess.py: preprocess script.</li>
</ul>
<p>If running successfully, you will see <code class="docutils literal"><span class="pre">demo/sentiment/data/pre-imdb</span></code> directory as follows:</p>
242
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="nb">dict</span><span class="o">.</span><span class="n">txt</span>  <span class="n">labels</span><span class="o">.</span><span class="n">list</span>  <span class="n">test</span><span class="o">.</span><span class="n">list</span>  <span class="n">test_part_000</span>  <span class="n">train</span><span class="o">.</span><span class="n">list</span>  <span class="n">train_part_000</span>
Y
Yu Yang 已提交
243 244 245 246 247 248 249 250 251 252 253 254
</pre></div>
</div>
<ul class="simple">
<li>test_part_000 and train_part_000: all labeled test and train sets. Train sets have be shuffled.</li>
<li>train.list and test.list: train and test file lists.</li>
<li>dict.txt: dictionary generated on train sets by default.</li>
<li>labels.txt: neg  0, pos 1, means label 0 is negative review, label 1 is positive review.</li>
</ul>
</div>
<div class="section" id="user-defined-data-preparation">
<span id="user-defined-data-preparation"></span><h3>User-defined Data Preparation<a class="headerlink" href="#user-defined-data-preparation" title="Permalink to this headline"></a></h3>
<p>If you perform other sentiment classifcation task, you can prepare data as follows. We have provided the scripts to build dictionary and preprocess data. So just organize data as follows.</p>
255 256 257 258 259 260 261 262 263 264 265 266 267
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">dataset</span>
<span class="o">|----</span><span class="n">train</span>
<span class="o">|</span>    <span class="o">|----</span><span class="n">class1</span>
<span class="o">|</span>    <span class="o">|</span>    <span class="o">|----</span><span class="n">text_files</span>
<span class="o">|</span>    <span class="o">|----</span><span class="n">class2</span>
<span class="o">|</span>    <span class="o">|</span>    <span class="o">|----</span><span class="n">text_files</span>
<span class="o">|</span>    <span class="o">|</span>    <span class="o">...</span>
<span class="o">|----</span><span class="n">test</span>
<span class="o">|</span>    <span class="o">|----</span><span class="n">class1</span>
<span class="o">|</span>    <span class="o">|</span>    <span class="o">|----</span><span class="n">text_files</span>
<span class="o">|</span>    <span class="o">|----</span><span class="n">class2</span>
<span class="o">|</span>    <span class="o">|</span>    <span class="o">|----</span><span class="n">text_files</span>
<span class="o">|</span>    <span class="o">|</span>    <span class="o">...</span>
Y
Yu Yang 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
</pre></div>
</div>
<ul class="simple">
<li>dataset: 1st directory.</li>
<li>train, test: 2nd directory.</li>
<li>class1,class2,...: 3rd directory.</li>
<li>text_files: samples with text file format.</li>
</ul>
<p>All samples with text files format under the same folder are same category. Each text file contains one or more samples and each line is one sample. In order to shuffle fully, the preprocessing is a little different for data with multiple lines in one text file, which needs to set <code class="docutils literal"><span class="pre">-m</span> <span class="pre">True</span></code> in <code class="docutils literal"><span class="pre">preprocess.sh</span></code>. And tokenizer.perl is used by default. If you don&#8217;t need it, only set <code class="docutils literal"><span class="pre">-t</span> <span class="pre">False</span></code> in `preprocess.sh&#8217;.</p>
</div>
</div>
<div class="section" id="training">
<span id="training"></span><h2>Training<a class="headerlink" href="#training" title="Permalink to this headline"></a></h2>
<p>In this task, we use Recurrent Neural Network (RNN) of LSTM architecure to train sentiment analysis model. LSTM model was introduced primarily in order to overcome the problem of vanishing gradients. LSTM network resembles a standard recurrent neural network with a hidden layer, but each ordinary node in the hidden layer is replaced by a memory cell. Each memory cell contains four main elements: an input gate, a neuron with a self-recurrent connection, a forget gate and an output gate. More details can be found in the literature [4]. The biggest advantage of the LSTM architecture is that it learns to memorize information over long time intervals without the loss of short time memory. At each time step with a new coming word, historical information stored in the memory block is updated to iteratively learn the sequence representation.</p>
<p><center><img alt="LSTM" src="../../_images/lstm.png" /></center>
<center>Figure 1. LSTM [3]</center></p>
<p>Sentiment analysis is among the most typical problems in natural language understanding. It aims at predicting the attitude expressed in a sequence. Usually, only some key words, like adjectives and adverbs words, play a major role in predicting the sentiment of sequences or paragraphs. However, some review or comment contexts are very long, such as IMDB dataset. We use LSTM to perform this task for its improved design with the gate mechanism. First, it is able to summarize the representation from word level to context level with variable context length which is adapted by the gate values. Second, it can utilize the expanded context at the sentence level, while most methods are good at utilizing n-gram level knowledge. Third, it learns the paragraph representation directly rather than combining the context level information. This results in this end-to-end framework.</p>
<p>In this demo we provide two network, namely bidirectional-LSTM and three layers of stacked-LSTM.</p>
<div class="section" id="bidirectional-lstm">
<span id="bidirectional-lstm"></span><h3>Bidirectional-LSTM<a class="headerlink" href="#bidirectional-lstm" title="Permalink to this headline"></a></h3>
<p>One is a bidirectional LSTM network, connected by fully connected layer and softmax, as shown in Figure 2.</p>
Y
Yu Yang 已提交
289
<p><center><img alt="BiLSTM" src="../../_images/bi_lstm1.jpg" /></center>
Y
Yu Yang 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
<center>Figure 2. Bidirectional-LSTM </center></p>
</div>
<div class="section" id="stacked-lstm">
<span id="stacked-lstm"></span><h3>Stacked-LSTM<a class="headerlink" href="#stacked-lstm" title="Permalink to this headline"></a></h3>
<p>Another is three-layer LSTM structure in Figure 3. The bottom of the figure is word embedding. Next, three LSTM-Hidden layers are connected and the second LSTM is reversed. Then extract the maximum hidden vectors of all time step of hidden and LSTM layer as the representation for the entire sequence. Finally, a fully connected feed forward layer with softmax activation is used to perform the classification task. This network is refered to paper [5].</p>
<p><center><img alt="StackedLSTM" src="../../_images/stacked_lstm.jpg" /></center>
<center>Figure 3. Stacked-LSTM for sentiment analysis </center></p>
<p><strong>Config</strong></p>
<p>Switch into <code class="docutils literal"><span class="pre">demo/sentiment</span></code> directory, <code class="docutils literal"><span class="pre">trainer_config.py</span></code> file is an example of the config, containing algorithm and newtork configure. The first line imports predefined networks from <code class="docutils literal"><span class="pre">sentiment_net.py</span></code>.</p>
<p>trainer_config.py:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">sentiment_net</span> <span class="kn">import</span> <span class="o">*</span>

<span class="n">data_dir</span>  <span class="o">=</span> <span class="s2">&quot;./data/pre-imdb&quot;</span>
<span class="c1"># whether this config is used for test</span>
<span class="n">is_test</span> <span class="o">=</span> <span class="n">get_config_arg</span><span class="p">(</span><span class="s1">&#39;is_test&#39;</span><span class="p">,</span> <span class="nb">bool</span><span class="p">,</span> <span class="bp">False</span><span class="p">)</span>
<span class="c1"># whether this config is used for prediction</span>
<span class="n">is_predict</span> <span class="o">=</span> <span class="n">get_config_arg</span><span class="p">(</span><span class="s1">&#39;is_predict&#39;</span><span class="p">,</span> <span class="nb">bool</span><span class="p">,</span> <span class="bp">False</span><span class="p">)</span>
<span class="n">dict_dim</span><span class="p">,</span> <span class="n">class_dim</span> <span class="o">=</span> <span class="n">sentiment_data</span><span class="p">(</span><span class="n">data_dir</span><span class="p">,</span> <span class="n">is_test</span><span class="p">,</span> <span class="n">is_predict</span><span class="p">)</span>

<span class="c1">################## Algorithm Config #####################</span>

<span class="n">settings</span><span class="p">(</span>
  <span class="n">batch_size</span><span class="o">=</span><span class="mi">128</span><span class="p">,</span>
  <span class="n">learning_rate</span><span class="o">=</span><span class="mf">2e-3</span><span class="p">,</span>
  <span class="n">learning_method</span><span class="o">=</span><span class="n">AdamOptimizer</span><span class="p">(),</span>
315
  <span class="n">average_window</span><span class="o">=</span><span class="mf">0.5</span><span class="p">,</span>
Y
Yu Yang 已提交
316 317 318 319 320 321 322 323 324 325 326 327 328
  <span class="n">regularization</span><span class="o">=</span><span class="n">L2Regularization</span><span class="p">(</span><span class="mf">8e-4</span><span class="p">),</span>
  <span class="n">gradient_clipping_threshold</span><span class="o">=</span><span class="mi">25</span>
<span class="p">)</span>

<span class="c1">#################### Network Config ######################</span>
<span class="n">stacked_lstm_net</span><span class="p">(</span><span class="n">dict_dim</span><span class="p">,</span> <span class="n">class_dim</span><span class="o">=</span><span class="n">class_dim</span><span class="p">,</span>
                 <span class="n">stacked_num</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">is_predict</span><span class="o">=</span><span class="n">is_predict</span><span class="p">)</span>
<span class="c1">#bidirectional_lstm_net(dict_dim, class_dim=class_dim, is_predict=is_predict)</span>
</pre></div>
</div>
<ul class="simple">
<li><strong>Data Definition</strong>:<ul>
<li>get_config_arg(): get arguments setted by <code class="docutils literal"><span class="pre">--config_args=xx</span></code> in commandline argument.</li>
329
<li>Define data provider, here using Python interface to load data. For details, you can refer to the document of PyDataProvider2.</li>
Y
Yu Yang 已提交
330 331 332 333 334
</ul>
</li>
<li><strong>Algorithm Configuration</strong>:<ul>
<li>set batch size of 128.</li>
<li>set global learning rate.</li>
335 336 337 338
<li>use adam optimization.</li>
<li>set average sgd window.</li>
<li>set L2 regularization.</li>
<li>set gradient clipping threshold.</li>
Y
Yu Yang 已提交
339 340 341
</ul>
</li>
<li><strong>Network Configuration</strong>:<ul>
342 343
<li>dict_dim: dictionary dimension.</li>
<li>class_dim: category number, IMDB has two label, namely positive and negative label.</li>
Y
Yu Yang 已提交
344 345 346 347 348 349 350
<li><code class="docutils literal"><span class="pre">stacked_lstm_net</span></code>: predefined network as shown in Figure 3, use this network by default.</li>
<li><code class="docutils literal"><span class="pre">bidirectional_lstm_net</span></code>: predefined network as shown in Figure 2.</li>
</ul>
</li>
</ul>
<p><strong>Training</strong></p>
<p>Install PaddlePaddle first if necessary. Then you can use script <code class="docutils literal"><span class="pre">train.sh</span></code> as follows to launch local training.</p>
351 352
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">cd</span> <span class="n">demo</span><span class="o">/</span><span class="n">sentiment</span><span class="o">/</span>
<span class="o">./</span><span class="n">train</span><span class="o">.</span><span class="n">sh</span>
Y
Yu Yang 已提交
353 354 355
</pre></div>
</div>
<p>train.sh:</p>
356
<div class="highlight-default"><div class="highlight"><pre><span></span>config=trainer_config.py
Y
Yu Yang 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
output=./model_output
paddle train --config=$config \
             --save_dir=$output \
             --job=train \
             --use_gpu=false \
             --trainer_count=4 \
             --num_passes=10 \
             --log_period=20 \
             --dot_period=20 \
             --show_parameter_stats_period=100 \
             --test_all_data_in_one_period=1 \
             2&gt;&amp;1 | tee &#39;train.log&#39;
</pre></div>
</div>
<ul class="simple">
Y
Yu Yang 已提交
372 373 374 375 376 377 378 379 380
<li>--config=$config: set network config.</li>
<li>--save_dir=$output: set output path to save models.</li>
<li>--job=train: set job mode to train.</li>
<li>--use_gpu=false: use CPU to train, set true, if you install GPU version of PaddlePaddle and want to use GPU to train.</li>
<li>--trainer_count=4: set thread number (or GPU count).</li>
<li>--num_passes=15: set pass number, one pass in PaddlePaddle means training all samples in dataset one time.</li>
<li>--log_period=20: print log every 20 batches.</li>
<li>--show_parameter_stats_period=100: show parameter statistic every 100 batches.</li>
<li>--test_all_data_in_one_period=1: test all data every testing.</li>
Y
Yu Yang 已提交
381 382
</ul>
<p>If the run succeeds, the output log is saved in path of <code class="docutils literal"><span class="pre">demo/sentiment/train.log</span></code> and model is saved in path of <code class="docutils literal"><span class="pre">demo/sentiment/model_output/</span></code>. The output log is explained as follows.</p>
383 384 385 386
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">Batch</span><span class="o">=</span><span class="mi">20</span> <span class="n">samples</span><span class="o">=</span><span class="mi">2560</span> <span class="n">AvgCost</span><span class="o">=</span><span class="mf">0.681644</span> <span class="n">CurrentCost</span><span class="o">=</span><span class="mf">0.681644</span> <span class="n">Eval</span><span class="p">:</span> <span class="n">classification_error_evaluator</span><span class="o">=</span><span class="mf">0.36875</span>  <span class="n">CurrentEval</span><span class="p">:</span> <span class="n">classification_error_evaluator</span><span class="o">=</span><span class="mf">0.36875</span>
<span class="o">...</span>
<span class="n">Pass</span><span class="o">=</span><span class="mi">0</span> <span class="n">Batch</span><span class="o">=</span><span class="mi">196</span> <span class="n">samples</span><span class="o">=</span><span class="mi">25000</span> <span class="n">AvgCost</span><span class="o">=</span><span class="mf">0.418964</span> <span class="n">Eval</span><span class="p">:</span> <span class="n">classification_error_evaluator</span><span class="o">=</span><span class="mf">0.1922</span>
<span class="n">Test</span> <span class="n">samples</span><span class="o">=</span><span class="mi">24999</span> <span class="n">cost</span><span class="o">=</span><span class="mf">0.39297</span> <span class="n">Eval</span><span class="p">:</span> <span class="n">classification_error_evaluator</span><span class="o">=</span><span class="mf">0.149406</span>
Y
Yu Yang 已提交
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
</pre></div>
</div>
<ul class="simple">
<li>Batch=xx: means passing xx batches.</li>
<li>samples=xx: means passing xx samples.</li>
<li>AvgCost=xx: averaged cost from 0-th batch to current batch.</li>
<li>CurrentCost=xx: current cost of latest log_period batches.</li>
<li>Eval: classification_error_evaluator=xx: means classfication error from 0-th batch ro current batch.</li>
<li>CurrentEval: classification_error_evaluator: current classfication error of the lates log_period batches.</li>
<li>Pass=0: Going through all training set one time is called one pass. 0 means going through training set first time.</li>
</ul>
<p>By default, we use the <code class="docutils literal"><span class="pre">stacked_lstm_net</span></code> network, which converges at a faster rate than <code class="docutils literal"><span class="pre">bidirectional_lstm_net</span></code> when passing same sample number. If you want to use bidirectional LSTM, just remove comment in the last line and comment <code class="docutils literal"><span class="pre">stacked_lstm_net</span></code>.</p>
</div>
</div>
<div class="section" id="testing">
<span id="testing"></span><h2>Testing<a class="headerlink" href="#testing" title="Permalink to this headline"></a></h2>
<p>Testing means evaluating the labeled validation set using trained model.</p>
404 405
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">cd</span> <span class="n">demo</span><span class="o">/</span><span class="n">sentiment</span>
<span class="o">./</span><span class="n">test</span><span class="o">.</span><span class="n">sh</span>
Y
Yu Yang 已提交
406 407 408 409 410 411
</pre></div>
</div>
<p>test.sh:</p>
<div class="highlight-bash"><div class="highlight"><pre><span></span><span class="k">function</span> get_best_pass<span class="o">()</span> <span class="o">{</span>
  cat <span class="nv">$1</span>  <span class="p">|</span> grep -Pzo <span class="s1">&#39;Test .*\n.*pass-.*&#39;</span> <span class="p">|</span> <span class="se">\</span>
  sed  -r <span class="s1">&#39;N;s/Test.* error=([0-9]+\.[0-9]+).*\n.*pass-([0-9]+)/\1 \2/g&#39;</span> <span class="p">|</span> <span class="se">\</span>
412
  sort <span class="p">|</span> head -n <span class="m">1</span>
Y
Yu Yang 已提交
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
<span class="o">}</span>

<span class="nv">log</span><span class="o">=</span>train.log
<span class="nv">LOG</span><span class="o">=</span><span class="sb">`</span>get_best_pass <span class="nv">$log</span><span class="sb">`</span>
<span class="nv">LOG</span><span class="o">=(</span><span class="si">${</span><span class="nv">LOG</span><span class="si">}</span><span class="o">)</span>
<span class="nv">evaluate_pass</span><span class="o">=</span><span class="s2">&quot;model_output/pass-</span><span class="si">${</span><span class="nv">LOG</span><span class="p">[1]</span><span class="si">}</span><span class="s2">&quot;</span>

<span class="nb">echo</span> <span class="s1">&#39;evaluating from pass &#39;</span><span class="nv">$evaluate_pass</span>

<span class="nv">model_list</span><span class="o">=</span>./model.list
touch <span class="nv">$model_list</span> <span class="p">|</span> <span class="nb">echo</span> <span class="nv">$evaluate_pass</span> &gt; <span class="nv">$model_list</span>
<span class="nv">net_conf</span><span class="o">=</span>trainer_config.py
paddle train --config<span class="o">=</span><span class="nv">$net_conf</span> <span class="se">\</span>
             --model_list<span class="o">=</span><span class="nv">$model_list</span> <span class="se">\</span>
             --job<span class="o">=</span><span class="nb">test</span> <span class="se">\</span>
             --use_gpu<span class="o">=</span><span class="nb">false</span> <span class="se">\</span>
             --trainer_count<span class="o">=</span><span class="m">4</span> <span class="se">\</span>
             --config_args<span class="o">=</span><span class="nv">is_test</span><span class="o">=</span><span class="m">1</span> <span class="se">\</span>
431
             <span class="m">2</span>&gt;<span class="p">&amp;</span><span class="m">1</span> <span class="p">|</span> tee <span class="s1">&#39;test.log&#39;</span>
Y
Yu Yang 已提交
432 433 434
</pre></div>
</div>
<p>The function <code class="docutils literal"><span class="pre">get_best_pass</span></code> gets the best model by classification error rate for testing. In this example, We use test dataset of IMDB as validation by default. Unlike training, it needs to specify <code class="docutils literal"><span class="pre">--job=test</span></code> and model path, namely <code class="docutils literal"><span class="pre">--model_list=$model_list</span></code> here. If running successfully, the log is saved in path of <code class="docutils literal"><span class="pre">demo/sentiment/test.log</span></code>. For example, in our test, the best model is <code class="docutils literal"><span class="pre">model_output/pass-00002</span></code>, the classification error is 0.115645 as follows.</p>
435
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">Pass</span><span class="o">=</span><span class="mi">0</span> <span class="n">samples</span><span class="o">=</span><span class="mi">24999</span> <span class="n">AvgCost</span><span class="o">=</span><span class="mf">0.280471</span> <span class="n">Eval</span><span class="p">:</span> <span class="n">classification_error_evaluator</span><span class="o">=</span><span class="mf">0.115645</span>
Y
Yu Yang 已提交
436 437 438 439 440 441
</pre></div>
</div>
</div>
<div class="section" id="prediction">
<span id="prediction"></span><h2>Prediction<a class="headerlink" href="#prediction" title="Permalink to this headline"></a></h2>
<p><code class="docutils literal"><span class="pre">predict.py</span></code> provides a predicting interface. You should install python api of PaddlePaddle before using it. One example to predict unlabeled review of IMDB is as follows. Simply running:</p>
442 443
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">cd</span> <span class="n">demo</span><span class="o">/</span><span class="n">sentiment</span>
<span class="o">./</span><span class="n">predict</span><span class="o">.</span><span class="n">sh</span>
Y
Yu Yang 已提交
444 445 446
</pre></div>
</div>
<p>predict.sh:</p>
447
<div class="highlight-default"><div class="highlight"><pre><span></span>#Note the default model is pass-00002, you shold make sure the model path
Y
Yu Yang 已提交
448
#exists or change the mode path.
Y
Yu Yang 已提交
449
model=model_output/pass-00002/
Y
Yu Yang 已提交
450
config=trainer_config.py
Y
Yu Yang 已提交
451
label=data/pre-imdb/labels.list
452 453 454 455 456 457
cat ./data/aclImdb/test/pos/10007_10.txt | python predict.py \
     --tconf=$config\
     --model=$model \
     --label=$label \
     --dict=./data/pre-imdb/dict.txt \
     --batch_size=1
Y
Yu Yang 已提交
458 459 460
</pre></div>
</div>
<ul class="simple">
461 462 463 464 465 466 467
<li><code class="docutils literal"><span class="pre">cat</span> <span class="pre">./data/aclImdb/test/pos/10007_10.txt</span></code> : the input sample.</li>
<li><code class="docutils literal"><span class="pre">predict.py</span></code> : predicting interface.</li>
<li><code class="docutils literal"><span class="pre">--tconf=$config</span></code> : set network configure.</li>
<li><code class="docutils literal"><span class="pre">--model=$model</span></code> : set model path.</li>
<li><code class="docutils literal"><span class="pre">--label=$label</span></code> : set dictionary about corresponding relation between integer label and string label.</li>
<li><code class="docutils literal"><span class="pre">--dict=data/pre-imdb/dict.txt</span></code> : set dictionary.</li>
<li><code class="docutils literal"><span class="pre">--batch_size=1</span></code> : set batch size.</li>
Y
Yu Yang 已提交
468
</ul>
Y
Yu Yang 已提交
469 470
<p>Note you should make sure the default model path <code class="docutils literal"><span class="pre">model_output/pass-00002</span></code>
exists or change the model path.</p>
Y
Yu Yang 已提交
471
<p>Predicting result of this example:</p>
472 473
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">Loading</span> <span class="n">parameters</span> <span class="kn">from</span> <span class="nn">model_output</span><span class="o">/</span><span class="k">pass</span><span class="o">-</span><span class="mi">00002</span><span class="o">/</span>
<span class="o">./</span><span class="n">data</span><span class="o">/</span><span class="n">aclImdb</span><span class="o">/</span><span class="n">test</span><span class="o">/</span><span class="n">pos</span><span class="o">/</span><span class="mi">10014</span><span class="n">_7</span><span class="o">.</span><span class="n">txt</span><span class="p">:</span> <span class="n">predicting</span> <span class="n">label</span> <span class="ow">is</span> <span class="n">pos</span>
Y
Yu Yang 已提交
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
</pre></div>
</div>
<p>We sincerely appreciate your interest and welcome your contributions.</p>
</div>
<div class="section" id="reference">
<span id="reference"></span><h2>Reference<a class="headerlink" href="#reference" title="Permalink to this headline"></a></h2>
<p>[1] Brendan O&#8217;Connor, Ramnath Balasubramanyan, Bryan R. Routledge, and Noah A. Smith. 2010. <a class="reference external" href="http://homes.cs.washington.edu/~nasmith/papers/oconnor+balasubramanyan+routledge+smith.icwsm10.pdf">From Tweets to Polls: Linking Text Sentiment to Public Opinion Time Series</a>. In ICWSM-2010. <br>
[2] Johan Bollen, Huina Mao, Xiaojun Zeng. 2011. <a class="reference external" href="http://arxiv.org/abs/1010.3003">Twitter mood predicts the stock market</a>, Journal of Computational Science.<br>
[3] Alex Graves, Marcus Liwicki, Santiago Fernan- dez, Roman Bertolami, Horst Bunke, and Ju ̈rgen Schmidhuber. 2009. <a class="reference external" href="http://www.cs.toronto.edu/~graves/tpami_2009.pdf">A novel connectionist system for unconstrained handwriting recognition. IEEE Transactions on Pattern Analysis and Machine In- telligence</a>, 31(5):855–868.<br>
[4] Zachary C. Lipton, <a class="reference external" href="http://arxiv.org/abs/1506.00019v1">A Critical Review of Recurrent Neural Networks for Sequence Learning</a>, arXiv:1506.00019. <br>
[5] Jie Zhou and Wei Xu; <a class="reference external" href="http://www.aclweb.org/anthology/P/P15/P15-1109.pdf">End-to-end Learning of Semantic Role Labeling Using Recurrent Neural Networks</a>; ACL-IJCNLP 2015. <br></p>
</div>
</div>


489
           </div>
Y
Yu Yang 已提交
490
          </div>
491 492 493 494 495 496 497 498 499 500 501 502 503 504
          <footer>
  

  <hr/>

  <div role="contentinfo">
    <p>
        &copy; Copyright 2016, PaddlePaddle developers.

    </p>
  </div>
  Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>
Y
Yu Yang 已提交
505 506 507

        </div>
      </div>
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543

    </section>

  </div>
  


  

    <script type="text/javascript">
        var DOCUMENTATION_OPTIONS = {
            URL_ROOT:'../../',
            VERSION:'',
            COLLAPSE_INDEX:false,
            FILE_SUFFIX:'.html',
            HAS_SOURCE:  true,
            SOURCELINK_SUFFIX: ".txt",
        };
    </script>
      <script type="text/javascript" src="../../_static/jquery.js"></script>
      <script type="text/javascript" src="../../_static/underscore.js"></script>
      <script type="text/javascript" src="../../_static/doctools.js"></script>
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
       
  

  
  
    <script type="text/javascript" src="../../_static/js/theme.js"></script>
  
  
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/perfect-scrollbar/0.6.14/js/perfect-scrollbar.jquery.min.js"></script>
  <script src="../../_static/js/paddle_doc_init.js"></script> 

</body>
Y
Yu Yang 已提交
544
</html>