diff --git a/doc/about/index.rst b/doc/about/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..c70940ca852156e61308e60ca9947b6c1a31b347 --- /dev/null +++ b/doc/about/index.rst @@ -0,0 +1,10 @@ +Credits +======== + +PaddlPaddle is an easy-to-use, efficient, flexible and scalable deep learning platform, +which is originally developed by Baidu scientists and engineers for the purpose of applying deep learning to many products at Baidu. + +PaddlePaddle is now open source but far from complete, which is intended to be built upon, improved, scaled, and extended. +We hope to build an active open source community both by providing feedback and by actively contributing to the source code. + +We owe many thanks to `all contributors and developers `_ of PaddlePaddle! diff --git a/doc/algorithm/index.rst b/doc/algorithm/index.rst deleted file mode 100644 index 6073add3c0cbb12529eabb0f8d8a051bcb84e628..0000000000000000000000000000000000000000 --- a/doc/algorithm/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -Algorithm Tutorial -================== - -.. toctree:: - :maxdepth: 1 - - rnn/rnn.rst diff --git a/doc/algorithm/rnn/bi_lstm.jpg b/doc/algorithm/rnn/bi_lstm.jpg deleted file mode 120000 index a53296cf806f97f7f2520e1700c4fb93f6bfc9d8..0000000000000000000000000000000000000000 --- a/doc/algorithm/rnn/bi_lstm.jpg +++ /dev/null @@ -1 +0,0 @@ -../../demo/sentiment_analysis/bi_lstm.jpg \ No newline at end of file diff --git a/doc/algorithm/rnn/encoder-decoder-attention-model.png b/doc/algorithm/rnn/encoder-decoder-attention-model.png deleted file mode 120000 index db71321a43a37b774e7de0af3765a60345033743..0000000000000000000000000000000000000000 --- a/doc/algorithm/rnn/encoder-decoder-attention-model.png +++ /dev/null @@ -1 +0,0 @@ -../../demo/text_generation/encoder-decoder-attention-model.png \ No newline at end of file diff --git a/doc/ui/data_provider/index.rst b/doc/api/data_provider/index.rst similarity index 100% rename from doc/ui/data_provider/index.rst rename to doc/api/data_provider/index.rst diff --git a/doc/ui/data_provider/pydataprovider2.rst b/doc/api/data_provider/pydataprovider2.rst similarity index 100% rename from doc/ui/data_provider/pydataprovider2.rst rename to doc/api/data_provider/pydataprovider2.rst diff --git a/doc/api/index.md b/doc/api/index.md new file mode 100644 index 0000000000000000000000000000000000000000..8c4a65e0d5c7a6663e33e1ab9c982859d6ead1a0 --- /dev/null +++ b/doc/api/index.md @@ -0,0 +1,14 @@ +# API + +## Data Provider + +* [Introduction](data_provider/index.rst) +* [PyDataProvider2](data_provider/pydataprovider2.rst) + +## Trainer Configuration + +* [Model Config Interface](trainer_config_helpers/index.rst) + +## Predict + +* [Python Prediction API](predict/swig_py_paddle_en.rst) diff --git a/doc/ui/predict/predict_sample.py b/doc/api/predict/predict_sample.py similarity index 100% rename from doc/ui/predict/predict_sample.py rename to doc/api/predict/predict_sample.py diff --git a/doc/ui/predict/swig_py_paddle_en.rst b/doc/api/predict/swig_py_paddle_en.rst similarity index 100% rename from doc/ui/predict/swig_py_paddle_en.rst rename to doc/api/predict/swig_py_paddle_en.rst diff --git a/doc/ui/api/trainer_config_helpers/activations.rst b/doc/api/trainer_config_helpers/activations.rst similarity index 100% rename from doc/ui/api/trainer_config_helpers/activations.rst rename to doc/api/trainer_config_helpers/activations.rst diff --git a/doc/ui/api/trainer_config_helpers/attrs.rst b/doc/api/trainer_config_helpers/attrs.rst similarity index 100% rename from doc/ui/api/trainer_config_helpers/attrs.rst rename to doc/api/trainer_config_helpers/attrs.rst diff --git a/doc/ui/api/trainer_config_helpers/data_sources.rst b/doc/api/trainer_config_helpers/data_sources.rst similarity index 100% rename from doc/ui/api/trainer_config_helpers/data_sources.rst rename to doc/api/trainer_config_helpers/data_sources.rst diff --git a/doc/ui/api/trainer_config_helpers/evaluators.rst b/doc/api/trainer_config_helpers/evaluators.rst similarity index 100% rename from doc/ui/api/trainer_config_helpers/evaluators.rst rename to doc/api/trainer_config_helpers/evaluators.rst diff --git a/doc/ui/api/trainer_config_helpers/index.rst b/doc/api/trainer_config_helpers/index.rst similarity index 100% rename from doc/ui/api/trainer_config_helpers/index.rst rename to doc/api/trainer_config_helpers/index.rst diff --git a/doc/ui/api/trainer_config_helpers/layers.rst b/doc/api/trainer_config_helpers/layers.rst similarity index 100% rename from doc/ui/api/trainer_config_helpers/layers.rst rename to doc/api/trainer_config_helpers/layers.rst diff --git a/doc/ui/api/trainer_config_helpers/networks.rst b/doc/api/trainer_config_helpers/networks.rst similarity index 100% rename from doc/ui/api/trainer_config_helpers/networks.rst rename to doc/api/trainer_config_helpers/networks.rst diff --git a/doc/ui/api/trainer_config_helpers/optimizers.rst b/doc/api/trainer_config_helpers/optimizers.rst similarity index 100% rename from doc/ui/api/trainer_config_helpers/optimizers.rst rename to doc/api/trainer_config_helpers/optimizers.rst diff --git a/doc/ui/api/trainer_config_helpers/poolings.rst b/doc/api/trainer_config_helpers/poolings.rst similarity index 100% rename from doc/ui/api/trainer_config_helpers/poolings.rst rename to doc/api/trainer_config_helpers/poolings.rst diff --git a/doc/cluster/index.rst b/doc/cluster/index.rst deleted file mode 100644 index 9062f85f98d2981b5c8dcf8149e32c2ccdac77f4..0000000000000000000000000000000000000000 --- a/doc/cluster/index.rst +++ /dev/null @@ -1,8 +0,0 @@ -Cluster Train -==================== - -.. toctree:: - :glob: - - opensource/cluster_train.md - internal/index.md diff --git a/doc/dev/layer.md b/doc/dev/layer.md deleted file mode 100644 index 930fb0de1ac074b15d06197ed0e732f92288b411..0000000000000000000000000000000000000000 --- a/doc/dev/layer.md +++ /dev/null @@ -1,4 +0,0 @@ -# Layer Documents - -* [Layer Source Code Document](../source/gserver/layers/index.rst) -* [Layer Python API Document](../ui/api/trainer_config_helpers/index.rst) diff --git a/doc/howto/algorithm/index.rst b/doc/howto/algorithm/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..b4ecbc4847057df9fcb335628e0ac587af76e699 --- /dev/null +++ b/doc/howto/algorithm/index.rst @@ -0,0 +1,7 @@ +Algorithm Configuration +======================= + +.. toctree:: + :maxdepth: 1 + + rnn/rnn.rst diff --git a/doc/algorithm/rnn/rnn.rst b/doc/howto/algorithm/rnn/rnn.rst similarity index 100% rename from doc/algorithm/rnn/rnn.rst rename to doc/howto/algorithm/rnn/rnn.rst diff --git a/doc/cluster/opensource/cluster_train.md b/doc/howto/cluster/cluster_train.md similarity index 99% rename from doc/cluster/opensource/cluster_train.md rename to doc/howto/cluster/cluster_train.md index cb493a88f031850cb6a5eeed0ebe9e41bb7e01c3..6b68596dc1234ed90df886136cc9309aafee3d72 100644 --- a/doc/cluster/opensource/cluster_train.md +++ b/doc/howto/cluster/cluster_train.md @@ -9,7 +9,7 @@ In this article, we explain how to run distributed Paddle training jobs on clust 1. Aforementioned scripts use a Python library [fabric](http://www.fabfile.org/) to run SSH commands. We can use `pip` to install fabric: ```bash -pip install fabric + pip install fabric ``` 1. We need to install PaddlePaddle on all nodes in the cluster. To enable GPUs, we need to install CUDA in `/usr/local/cuda`; otherwise Paddle would report errors at runtime. diff --git a/doc/ui/cmd_argument/argument_outline.md b/doc/howto/cmd_argument/argument_outline.md similarity index 100% rename from doc/ui/cmd_argument/argument_outline.md rename to doc/howto/cmd_argument/argument_outline.md diff --git a/doc/ui/cmd_argument/detail_introduction.md b/doc/howto/cmd_argument/detail_introduction.md similarity index 100% rename from doc/ui/cmd_argument/detail_introduction.md rename to doc/howto/cmd_argument/detail_introduction.md diff --git a/doc/howto/cmd_argument/index.md b/doc/howto/cmd_argument/index.md new file mode 100644 index 0000000000000000000000000000000000000000..90472c44cb9ad0adde0844f3195732d8d6091735 --- /dev/null +++ b/doc/howto/cmd_argument/index.md @@ -0,0 +1,5 @@ +# Command Line Argument + +* [Use Case](use_case.md) +* [Argument Outline](argument_outline.md) +* [Detailed Descriptions](detail_introduction.md) diff --git a/doc/ui/cmd_argument/use_case.md b/doc/howto/cmd_argument/use_case.md similarity index 100% rename from doc/ui/cmd_argument/use_case.md rename to doc/howto/cmd_argument/use_case.md diff --git a/doc/build/contribute_to_paddle.md b/doc/howto/contribute_to_paddle.md similarity index 100% rename from doc/build/contribute_to_paddle.md rename to doc/howto/contribute_to_paddle.md diff --git a/doc/dev/index.rst b/doc/howto/dev/index.rst similarity index 71% rename from doc/dev/index.rst rename to doc/howto/dev/index.rst index 0468dd492b6246cfe0771a05c3597ddee95b3ddd..876c42e9dbb11cd21938a181534f7f1b20e5af06 100644 --- a/doc/dev/index.rst +++ b/doc/howto/dev/index.rst @@ -2,8 +2,8 @@ Development Guide ================= .. toctree:: - :maxdepth: 1 + :maxdepth: 2 layer.md new_layer/new_layer.rst - ../source/index.md + source/index.rst diff --git a/doc/howto/dev/layer.md b/doc/howto/dev/layer.md new file mode 100644 index 0000000000000000000000000000000000000000..1ce0cc5829d16c26a0f524a6d160aefda4812338 --- /dev/null +++ b/doc/howto/dev/layer.md @@ -0,0 +1,5 @@ +# Layer Documents + +* [Layer Python API](../../api/trainer_config_helpers/index.rst) +* [Layer Source Code](source/gserver/layers.rst) +* [Writing New Layers](new_layer/new_layer.rst) diff --git a/doc/dev/new_layer/FullyConnected.jpg b/doc/howto/dev/new_layer/FullyConnected.jpg similarity index 100% rename from doc/dev/new_layer/FullyConnected.jpg rename to doc/howto/dev/new_layer/FullyConnected.jpg diff --git a/doc/dev/new_layer/new_layer.rst b/doc/howto/dev/new_layer/new_layer.rst similarity index 100% rename from doc/dev/new_layer/new_layer.rst rename to doc/howto/dev/new_layer/new_layer.rst diff --git a/doc/source/api.rst b/doc/howto/dev/source/api.rst similarity index 100% rename from doc/source/api.rst rename to doc/howto/dev/source/api.rst diff --git a/doc/source/cuda/index.rst b/doc/howto/dev/source/cuda/index.rst similarity index 100% rename from doc/source/cuda/index.rst rename to doc/howto/dev/source/cuda/index.rst diff --git a/doc/source/cuda/matrix.rst b/doc/howto/dev/source/cuda/matrix.rst similarity index 100% rename from doc/source/cuda/matrix.rst rename to doc/howto/dev/source/cuda/matrix.rst diff --git a/doc/source/cuda/nn.rst b/doc/howto/dev/source/cuda/nn.rst similarity index 100% rename from doc/source/cuda/nn.rst rename to doc/howto/dev/source/cuda/nn.rst diff --git a/doc/source/cuda/utils.rst b/doc/howto/dev/source/cuda/utils.rst similarity index 100% rename from doc/source/cuda/utils.rst rename to doc/howto/dev/source/cuda/utils.rst diff --git a/doc/source/gserver/activations.rst b/doc/howto/dev/source/gserver/activations.rst similarity index 100% rename from doc/source/gserver/activations.rst rename to doc/howto/dev/source/gserver/activations.rst diff --git a/doc/source/gserver/dataproviders.rst b/doc/howto/dev/source/gserver/dataproviders.rst similarity index 100% rename from doc/source/gserver/dataproviders.rst rename to doc/howto/dev/source/gserver/dataproviders.rst diff --git a/doc/source/gserver/evaluators.rst b/doc/howto/dev/source/gserver/evaluators.rst similarity index 100% rename from doc/source/gserver/evaluators.rst rename to doc/howto/dev/source/gserver/evaluators.rst diff --git a/doc/source/gserver/gradientmachines.rst b/doc/howto/dev/source/gserver/gradientmachines.rst similarity index 100% rename from doc/source/gserver/gradientmachines.rst rename to doc/howto/dev/source/gserver/gradientmachines.rst diff --git a/doc/source/gserver/index.rst b/doc/howto/dev/source/gserver/index.rst similarity index 100% rename from doc/source/gserver/index.rst rename to doc/howto/dev/source/gserver/index.rst diff --git a/doc/source/gserver/layers.rst b/doc/howto/dev/source/gserver/layers.rst similarity index 100% rename from doc/source/gserver/layers.rst rename to doc/howto/dev/source/gserver/layers.rst diff --git a/doc/source/gserver/neworks.rst b/doc/howto/dev/source/gserver/neworks.rst similarity index 100% rename from doc/source/gserver/neworks.rst rename to doc/howto/dev/source/gserver/neworks.rst diff --git a/doc/source/index.rst b/doc/howto/dev/source/index.rst similarity index 100% rename from doc/source/index.rst rename to doc/howto/dev/source/index.rst diff --git a/doc/source/math/functions.rst b/doc/howto/dev/source/math/functions.rst similarity index 100% rename from doc/source/math/functions.rst rename to doc/howto/dev/source/math/functions.rst diff --git a/doc/source/math/index.rst b/doc/howto/dev/source/math/index.rst similarity index 100% rename from doc/source/math/index.rst rename to doc/howto/dev/source/math/index.rst diff --git a/doc/source/math/matrix.rst b/doc/howto/dev/source/math/matrix.rst similarity index 100% rename from doc/source/math/matrix.rst rename to doc/howto/dev/source/math/matrix.rst diff --git a/doc/source/math/utils.rst b/doc/howto/dev/source/math/utils.rst similarity index 100% rename from doc/source/math/utils.rst rename to doc/howto/dev/source/math/utils.rst diff --git a/doc/source/math/vector.rst b/doc/howto/dev/source/math/vector.rst similarity index 100% rename from doc/source/math/vector.rst rename to doc/howto/dev/source/math/vector.rst diff --git a/doc/source/parameter/index.rst b/doc/howto/dev/source/parameter/index.rst similarity index 100% rename from doc/source/parameter/index.rst rename to doc/howto/dev/source/parameter/index.rst diff --git a/doc/source/parameter/optimizer.rst b/doc/howto/dev/source/parameter/optimizer.rst similarity index 100% rename from doc/source/parameter/optimizer.rst rename to doc/howto/dev/source/parameter/optimizer.rst diff --git a/doc/source/parameter/parameter.rst b/doc/howto/dev/source/parameter/parameter.rst similarity index 100% rename from doc/source/parameter/parameter.rst rename to doc/howto/dev/source/parameter/parameter.rst diff --git a/doc/source/parameter/updater.rst b/doc/howto/dev/source/parameter/updater.rst similarity index 100% rename from doc/source/parameter/updater.rst rename to doc/howto/dev/source/parameter/updater.rst diff --git a/doc/source/pserver/client.rst b/doc/howto/dev/source/pserver/client.rst similarity index 100% rename from doc/source/pserver/client.rst rename to doc/howto/dev/source/pserver/client.rst diff --git a/doc/source/pserver/index.rst b/doc/howto/dev/source/pserver/index.rst similarity index 100% rename from doc/source/pserver/index.rst rename to doc/howto/dev/source/pserver/index.rst diff --git a/doc/source/pserver/network.rst b/doc/howto/dev/source/pserver/network.rst similarity index 100% rename from doc/source/pserver/network.rst rename to doc/howto/dev/source/pserver/network.rst diff --git a/doc/source/pserver/server.rst b/doc/howto/dev/source/pserver/server.rst similarity index 100% rename from doc/source/pserver/server.rst rename to doc/howto/dev/source/pserver/server.rst diff --git a/doc/source/trainer.rst b/doc/howto/dev/source/trainer.rst similarity index 100% rename from doc/source/trainer.rst rename to doc/howto/dev/source/trainer.rst diff --git a/doc/source/utils/customStackTrace.rst b/doc/howto/dev/source/utils/customStackTrace.rst similarity index 100% rename from doc/source/utils/customStackTrace.rst rename to doc/howto/dev/source/utils/customStackTrace.rst diff --git a/doc/source/utils/enum.rst b/doc/howto/dev/source/utils/enum.rst similarity index 100% rename from doc/source/utils/enum.rst rename to doc/howto/dev/source/utils/enum.rst diff --git a/doc/source/utils/index.rst b/doc/howto/dev/source/utils/index.rst similarity index 100% rename from doc/source/utils/index.rst rename to doc/howto/dev/source/utils/index.rst diff --git a/doc/source/utils/lock.rst b/doc/howto/dev/source/utils/lock.rst similarity index 100% rename from doc/source/utils/lock.rst rename to doc/howto/dev/source/utils/lock.rst diff --git a/doc/source/utils/queue.rst b/doc/howto/dev/source/utils/queue.rst similarity index 100% rename from doc/source/utils/queue.rst rename to doc/howto/dev/source/utils/queue.rst diff --git a/doc/source/utils/thread.rst b/doc/howto/dev/source/utils/thread.rst similarity index 100% rename from doc/source/utils/thread.rst rename to doc/howto/dev/source/utils/thread.rst diff --git a/doc/howto/index.rst b/doc/howto/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..e2d688e186c66c56b219f63f5730affa30300592 --- /dev/null +++ b/doc/howto/index.rst @@ -0,0 +1,11 @@ +How to +======= + +.. toctree:: + :maxdepth: 1 + + cmd_argument/index.md + cluster/cluster_train.md + algorithm/index.rst + dev/index.rst + contribute_to_paddle.md \ No newline at end of file diff --git a/doc/index.rst b/doc/index.rst index 668ad75a902bdd14c6198c41380ae93e29cec0d3..a7feed52395ed39c12fd1ddd659a6271729ccaac 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -4,7 +4,9 @@ PaddlePaddle Documentation .. toctree:: :maxdepth: 1 - introduction/index.md - user_guide.rst - dev/index.rst - algorithm/index.rst + introduction/index.rst + tutorials/index.md + howto/index.rst + api/index.rst + about/index.rst + diff --git a/doc/introduction/basic_usage/basic_usage.rst b/doc/introduction/basic_usage/basic_usage.rst new file mode 100644 index 0000000000000000000000000000000000000000..dca7a6b1f4f017b302148c611122806f112564a9 --- /dev/null +++ b/doc/introduction/basic_usage/basic_usage.rst @@ -0,0 +1,109 @@ +Basic Usage +============= + +PaddlePaddle is a deep learning platform open-sourced by Baidu. With PaddlePaddle, you can easily train a classic neural network within a couple lines of configuration, or you can build sophisticated models that provide state-of-the-art performance on difficult learning tasks like sentiment analysis, machine translation, image caption and so on. + +1. A Classic Problem +--------------------- + +Now, to give you a hint of what using PaddlePaddle looks like, let's start with a fundamental learning problem - `simple linear regression `_: you have observed a set of two-dimensional data points of ``X`` and ``Y``, where ``X`` is an explanatory variable and ``Y`` is corresponding dependent variable, and you want to recover the underlying correlation between ``X`` and ``Y``. Linear regression can be used in many practical scenarios. For example, ``X`` can be a variable about house size, and ``Y`` a variable about house price. You can build a model that captures relationship between them by observing real estate markets. + +2. Prepare the Data +-------------------- + +Suppose the true relationship can be characterized as ``Y = 2X + 0.3``, let's see how to recover this pattern only from observed data. Here is a piece of python code that feeds synthetic data to PaddlePaddle. The code is pretty self-explanatory, the only extra thing you need to add for PaddlePaddle is a definition of input data types. + + .. code-block:: python + + # dataprovider.py + from paddle.trainer.PyDataProvider2 import * + import random + + # define data types of input: 2 real numbers + @provider(input_types=[dense_vector(1), dense_vector(1)],use_seq=False) + def process(settings, input_file): + for i in xrange(2000): + x = random.random() + yield [x], [2*x+0.3] + +3. Train a NeuralNetwork +------------------------- + +To recover this relationship between ``X`` and ``Y``, we use a neural network with one layer of linear activation units and a square error cost layer. Don't worry if you are not familiar with these terminologies, it's just saying that we are starting from a random line ``Y' = wX + b`` , then we gradually adapt ``w`` and ``b`` to minimize the difference between ``Y'`` and ``Y``. Here is what it looks like in PaddlePaddle: + + .. code-block:: python + + # trainer_config.py + from paddle.trainer_config_helpers import * + + # 1. read data. Suppose you saved above python code as dataprovider.py + data_file = 'empty.list' + with open(data_file, 'w') as f: f.writelines(' ') + define_py_data_sources2(train_list=data_file, test_list=None, + module='dataprovider', obj='process',args={}) + + # 2. learning algorithm + settings(batch_size=12, learning_rate=1e-3, learning_method=MomentumOptimizer()) + + # 3. Network configuration + x = data_layer(name='x', size=1) + y = data_layer(name='y', size=1) + y_predict = fc_layer(input=x, param_attr=ParamAttr(name='w'), size=1, act=LinearActivation(), bias_attr=ParamAttr(name='b')) + cost = regression_cost(input=y_predict, label=y) + outputs(cost) + +Some of the most fundamental usages of PaddlePaddle are demonstrated: + +- The first part shows how to feed data into PaddlePaddle. In general cases, PaddlePaddle reads raw data from a list of files, and then do some user-defined process to get real input. In this case, we only need to create a placeholder file since we are generating synthetic data on the fly. + +- The second part describes learning algorithm. It defines in what ways adjustments are made to model parameters. PaddlePaddle provides a rich set of optimizers, but a simple momentum based optimizer will suffice here, and it processes 12 data points each time. + +- Finally, the network configuration. It usually is as simple as "stacking" layers. Three kinds of layers are used in this configuration: + - **Data Layer**: a network always starts with one or more data layers. They provide input data to the rest of the network. In this problem, two data layers are used respectively for ``X`` and ``Y``. + - **FC Layer**: FC layer is short for Fully Connected Layer, which connects all the input units to current layer and does the actual computation specified as activation function. Computation layers like this are the fundamental building blocks of a deeper model. + - **Cost Layer**: in training phase, cost layers are usually the last layers of the network. They measure the performance of current model, and provide guidence to adjust parameters. + +Now that everything is ready, you can train the network with a simple command line call: + + .. code-block:: bash + + paddle train --config=trainer_config.py --save_dir=./output --num_passes=30 + + +This means that PaddlePaddle will train this network on the synthectic dataset for 30 passes, and save all the models under path ``./output``. You will see from the messages printed out during training phase that the model cost is decreasing as time goes by, which indicates we are getting a closer guess. + + +4. Evaluate the Model +----------------------- + +Usually, a different dataset that left out during training phase should be used to evalute the models. However, we are lucky enough to know the real answer: ``w=2, b=0.3``, thus a better option is to check out model parameters directly. + +In PaddlePaddle, training is just to get a collection of model parameters, which are ``w`` and ``b`` in this case. Each parameter is saved in an individual file in the popular ``numpy`` array format. Here is the code that reads parameters from last pass. + + .. code-block:: python + + import numpy as np + import os + + def load(file_name): + with open(file_name, 'rb') as f: + f.read(16) # skip header for float type. + return np.fromfile(f, dtype=np.float32) + + print 'w=%.6f, b=%.6f' % (load('output/pass-00029/w'), load('output/pass-00029/b')) + # w=1.999743, b=0.300137 + + .. image:: parameters.png + :align: center + +Although starts from a random guess, you can see that value of ``w`` changes quickly towards 2 and ``b`` changes quickly towards 0.3. In the end, the predicted line is almost identical with real answer. + +There, you have recovered the underlying pattern between ``X`` and ``Y`` only from observed data. + + +5. Where to Go from Here +------------------------- + +- `Install and Build <../build_and_install/index.html>`_ +- `Tutorials <../demo/quick_start/index_en.html>`_ +- `Example and Demo <../demo/index.html>`_ diff --git a/doc/introduction/basic_usage/parameters.png b/doc/introduction/basic_usage/parameters.png new file mode 100644 index 0000000000000000000000000000000000000000..2ec67480951e21f0400bce1c34b3108dcd65c18c Binary files /dev/null and b/doc/introduction/basic_usage/parameters.png differ diff --git a/doc/build/build_from_source.md b/doc/introduction/build_and_install/build_from_source.md similarity index 100% rename from doc/build/build_from_source.md rename to doc/introduction/build_and_install/build_from_source.md diff --git a/doc/build/cmake.png b/doc/introduction/build_and_install/cmake.png similarity index 100% rename from doc/build/cmake.png rename to doc/introduction/build_and_install/cmake.png diff --git a/doc/build/docker_install.rst b/doc/introduction/build_and_install/docker_install.rst similarity index 100% rename from doc/build/docker_install.rst rename to doc/introduction/build_and_install/docker_install.rst diff --git a/doc/build/index.rst b/doc/introduction/build_and_install/index.rst similarity index 80% rename from doc/build/index.rst rename to doc/introduction/build_and_install/index.rst index b4fe4596047c7d201fdf36bc76c26d5134611560..6187be9d7257b1690d223770f0f6a5b466cf2898 100644 --- a/doc/build/index.rst +++ b/doc/introduction/build_and_install/index.rst @@ -8,8 +8,6 @@ Install PaddlePaddle :maxdepth: 1 :glob: - install_* - internal/install_from_jumbo.md docker_install.rst ubuntu_install.rst @@ -24,5 +22,4 @@ Build from Source :maxdepth: 1 :glob: - build_from_source.md - contribute_to_paddle.md + build_from_source.md \ No newline at end of file diff --git a/doc/build/ubuntu_install.rst b/doc/introduction/build_and_install/ubuntu_install.rst similarity index 100% rename from doc/build/ubuntu_install.rst rename to doc/introduction/build_and_install/ubuntu_install.rst diff --git a/doc/introduction/index.md b/doc/introduction/index.md deleted file mode 100644 index 01f52031a1d0247cd0b885218c17001f23685239..0000000000000000000000000000000000000000 --- a/doc/introduction/index.md +++ /dev/null @@ -1,100 +0,0 @@ -# Introduction - -PaddlePaddle is a deep learning platform open-sourced by Baidu. With PaddlePaddle, you can easily train a classic neural network within a couple lines of configuration, or you can build sophisticated models that provide state-of-the-art performance on difficult learning tasks like sentiment analysis, machine translation, image caption and so on. - -## 1. A Classic Problem - -Now, to give you a hint of what using PaddlePaddle looks like, let's start with a fundamental learning problem - **simple linear regression** : you have observed a set of two-dimensional data points of `X` and `Y`, where `X` is an explanatory variable and `Y` is corresponding dependent variable, and you want to recover the underlying correlation between `X` and `Y`. Linear regression can be used in many practical scenarios. For example, `X` can be a variable about house size, and `Y` a variable about house price. You can build a model that captures relationship between them by observing real estate markets. - -## 2. Prepare the Data - -Suppose the true relationship can be characterized as `Y = 2X + 0.3`, let's see how to recover this pattern only from observed data. Here is a piece of python code that feeds synthetic data to PaddlePaddle. The code is pretty self-explanatory, the only extra thing you need to add for PaddlePaddle is a definition of input data types. - -```python -# dataprovider.py -from paddle.trainer.PyDataProvider2 import * -import random - -# define data types of input: 2 real numbers -@provider(input_types=[dense_vector(1), dense_vector(1)],use_seq=False) -def process(settings, input_file): - for i in xrange(2000): - x = random.random() - yield [x], [2*x+0.3] -``` - -## 3. Train a NeuralNetwork in PaddlePaddle - -To recover this relationship between `X` and `Y`, we use a neural network with one layer of linear activation units and a square error cost layer. Don't worry if you are not familiar with these terminologies, it's just saying that we are starting from a random line `Y' = wX + b` , then we gradually adapt `w` and `b` to minimize the difference between `Y'` and `Y`. Here is what it looks like in PaddlePaddle: - -```python -# trainer_config.py -from paddle.trainer_config_helpers import * - -# 1. read data. Suppose you saved above python code as dataprovider.py -data_file = 'empty.list' -with open(data_file, 'w') as f: f.writelines(' ') -define_py_data_sources2(train_list=data_file, test_list=None, - module='dataprovider', obj='process',args={}) - -# 2. learning algorithm -settings(batch_size=12, learning_rate=1e-3, learning_method=MomentumOptimizer()) - -# 3. Network configuration -x = data_layer(name='x', size=1) -y = data_layer(name='y', size=1) -y_predict = fc_layer(input=x, param_attr=ParamAttr(name='w'), size=1, act=LinearActivation(), bias_attr=ParamAttr(name='b')) -cost = regression_cost(input=y_predict, label=y) -outputs(cost) -``` - -Some of the most fundamental usages of PaddlePaddle are demonstrated: - -- The first part shows how to feed data into PaddlePaddle. In general cases, PaddlePaddle reads raw data from a list of files, and then do some user-defined process to get real input. In this case, we only need to create a placeholder file since we are generating synthetic data on the fly. - -- The second part describes learning algorithm. It defines in what ways adjustments are made to model parameters. PaddlePaddle provides a rich set of optimizers, but a simple momentum based optimizer will suffice here, and it processes 12 data points each time. - -- Finally, the network configuration. It usually is as simple as "stacking" layers. Three kinds of layers are used in this configuration: - - **Data Layer**: a network always starts with one or more data layers. They provide input data to the rest of the network. In this problem, two data layers are used respectively for `X` and `Y`. - - **FC Layer**: FC layer is short for Fully Connected Layer, which connects all the input units to current layer and does the actual computation specified as activation function. Computation layers like this are the fundamental building blocks of a deeper model. - - **Cost Layer**: in training phase, cost layers are usually the last layers of the network. They measure the performance of current model, and provide guidence to adjust parameters. - -Now that everything is ready, you can train the network with a simple command line call: - ``` - paddle train --config=trainer_config.py --save_dir=./output --num_passes=30 - ``` - -This means that PaddlePaddle will train this network on the synthectic dataset for 30 passes, and save all the models under path `./output`. You will see from the messages printed out during training phase that the model cost is decreasing as time goes by, which indicates we are getting a closer guess. - - -## 4. Evaluate the Model - -Usually, a different dataset that left out during training phase should be used to evalute the models. However, we are lucky enough to know the real answer: `w=2, b=0.3`, thus a better option is to check out model parameters directly. - -In PaddlePaddle, training is just to get a collection of model parameters, which are `w` and `b` in this case. Each parameter is saved in an individual file in the popular `numpy` array format. Here is the code that reads parameters from last pass. - -```python -import numpy as np -import os - -def load(file_name): - with open(file_name, 'rb') as f: - f.read(16) # skip header for float type. - return np.fromfile(f, dtype=np.float32) - -print 'w=%.6f, b=%.6f' % (load('output/pass-00029/w'), load('output/pass-00029/b')) -# w=1.999743, b=0.300137 -``` - -
![](./parameters.png)
- -Although starts from a random guess, you can see that value of `w` changes quickly towards 2 and `b` changes quickly towards 0.3. In the end, the predicted line is almost identical with real answer. - -There, you have recovered the underlying pattern between `X` and `Y` only from observed data. - - -## 5. Where to Go from Here - -- Build and Installation -- Quick Start -- Example and Demo diff --git a/doc/introduction/index.rst b/doc/introduction/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..ff22f05a1b6187ab9b43ef86134c9e6f602c1b6f --- /dev/null +++ b/doc/introduction/index.rst @@ -0,0 +1,8 @@ +Introduction +============ + +.. toctree:: + :maxdepth: 2 + + build_and_install/index.rst + basic_usage/basic_usage.rst diff --git a/doc/introduction/parameters.png b/doc/introduction/parameters.png deleted file mode 120000 index f47e74c94fffabbd32f055febbadb1b18aa0c429..0000000000000000000000000000000000000000 --- a/doc/introduction/parameters.png +++ /dev/null @@ -1 +0,0 @@ -../../doc_cn/introduction/parameters.png \ No newline at end of file diff --git a/doc/demo/embedding_model/index.md b/doc/tutorials/embedding_model/index.md similarity index 100% rename from doc/demo/embedding_model/index.md rename to doc/tutorials/embedding_model/index.md diff --git a/doc/demo/embedding_model/neural-n-gram-model.png b/doc/tutorials/embedding_model/neural-n-gram-model.png similarity index 100% rename from doc/demo/embedding_model/neural-n-gram-model.png rename to doc/tutorials/embedding_model/neural-n-gram-model.png diff --git a/doc/demo/image_classification/cifar.png b/doc/tutorials/image_classification/cifar.png similarity index 100% rename from doc/demo/image_classification/cifar.png rename to doc/tutorials/image_classification/cifar.png diff --git a/doc/demo/image_classification/image_classification.md b/doc/tutorials/image_classification/image_classification.md similarity index 100% rename from doc/demo/image_classification/image_classification.md rename to doc/tutorials/image_classification/image_classification.md diff --git a/doc/demo/image_classification/image_classification.png b/doc/tutorials/image_classification/image_classification.png similarity index 100% rename from doc/demo/image_classification/image_classification.png rename to doc/tutorials/image_classification/image_classification.png diff --git a/doc/demo/image_classification/index.rst b/doc/tutorials/image_classification/index.rst similarity index 100% rename from doc/demo/image_classification/index.rst rename to doc/tutorials/image_classification/index.rst diff --git a/doc/demo/image_classification/lenet.png b/doc/tutorials/image_classification/lenet.png similarity index 100% rename from doc/demo/image_classification/lenet.png rename to doc/tutorials/image_classification/lenet.png diff --git a/doc/demo/image_classification/plot.png b/doc/tutorials/image_classification/plot.png similarity index 100% rename from doc/demo/image_classification/plot.png rename to doc/tutorials/image_classification/plot.png diff --git a/doc/demo/imagenet_model/resnet_block.jpg b/doc/tutorials/imagenet_model/resnet_block.jpg similarity index 100% rename from doc/demo/imagenet_model/resnet_block.jpg rename to doc/tutorials/imagenet_model/resnet_block.jpg diff --git a/doc/demo/imagenet_model/resnet_model.md b/doc/tutorials/imagenet_model/resnet_model.md similarity index 100% rename from doc/demo/imagenet_model/resnet_model.md rename to doc/tutorials/imagenet_model/resnet_model.md diff --git a/doc/demo/index.md b/doc/tutorials/index.md similarity index 96% rename from doc/demo/index.md rename to doc/tutorials/index.md index 289199d496eb3b527fa8c8261820bc8e4d301786..c845ca229cb99dd17ca7294c3191ce0055365ba2 100644 --- a/doc/demo/index.md +++ b/doc/tutorials/index.md @@ -1,4 +1,4 @@ -# Examples and demos +# Tutorials There are serveral examples and demos here. ## Image diff --git a/doc/demo/quick_start/NetContinuous_en.png b/doc/tutorials/quick_start/NetContinuous_en.png similarity index 100% rename from doc/demo/quick_start/NetContinuous_en.png rename to doc/tutorials/quick_start/NetContinuous_en.png diff --git a/doc/demo/quick_start/NetConv_en.png b/doc/tutorials/quick_start/NetConv_en.png similarity index 100% rename from doc/demo/quick_start/NetConv_en.png rename to doc/tutorials/quick_start/NetConv_en.png diff --git a/doc/demo/quick_start/NetLR_en.png b/doc/tutorials/quick_start/NetLR_en.png similarity index 100% rename from doc/demo/quick_start/NetLR_en.png rename to doc/tutorials/quick_start/NetLR_en.png diff --git a/doc/demo/quick_start/NetRNN_en.png b/doc/tutorials/quick_start/NetRNN_en.png similarity index 100% rename from doc/demo/quick_start/NetRNN_en.png rename to doc/tutorials/quick_start/NetRNN_en.png diff --git a/doc/demo/quick_start/PipelineNetwork_en.jpg b/doc/tutorials/quick_start/PipelineNetwork_en.jpg similarity index 100% rename from doc/demo/quick_start/PipelineNetwork_en.jpg rename to doc/tutorials/quick_start/PipelineNetwork_en.jpg diff --git a/doc/demo/quick_start/PipelineTest_en.png b/doc/tutorials/quick_start/PipelineTest_en.png similarity index 100% rename from doc/demo/quick_start/PipelineTest_en.png rename to doc/tutorials/quick_start/PipelineTest_en.png diff --git a/doc/demo/quick_start/PipelineTrain_en.png b/doc/tutorials/quick_start/PipelineTrain_en.png similarity index 100% rename from doc/demo/quick_start/PipelineTrain_en.png rename to doc/tutorials/quick_start/PipelineTrain_en.png diff --git a/doc/demo/quick_start/Pipeline_en.jpg b/doc/tutorials/quick_start/Pipeline_en.jpg similarity index 100% rename from doc/demo/quick_start/Pipeline_en.jpg rename to doc/tutorials/quick_start/Pipeline_en.jpg diff --git a/doc/demo/quick_start/index_en.md b/doc/tutorials/quick_start/index_en.md similarity index 100% rename from doc/demo/quick_start/index_en.md rename to doc/tutorials/quick_start/index_en.md diff --git a/doc/demo/rec/ml_dataset.md b/doc/tutorials/rec/ml_dataset.md similarity index 100% rename from doc/demo/rec/ml_dataset.md rename to doc/tutorials/rec/ml_dataset.md diff --git a/doc/demo/rec/ml_regression.rst b/doc/tutorials/rec/ml_regression.rst similarity index 100% rename from doc/demo/rec/ml_regression.rst rename to doc/tutorials/rec/ml_regression.rst diff --git a/doc/demo/rec/rec_regression_network.png b/doc/tutorials/rec/rec_regression_network.png similarity index 100% rename from doc/demo/rec/rec_regression_network.png rename to doc/tutorials/rec/rec_regression_network.png diff --git a/doc/demo/semantic_role_labeling/curve.jpg b/doc/tutorials/semantic_role_labeling/curve.jpg similarity index 100% rename from doc/demo/semantic_role_labeling/curve.jpg rename to doc/tutorials/semantic_role_labeling/curve.jpg diff --git a/doc/demo/semantic_role_labeling/feature.jpg b/doc/tutorials/semantic_role_labeling/feature.jpg similarity index 100% rename from doc/demo/semantic_role_labeling/feature.jpg rename to doc/tutorials/semantic_role_labeling/feature.jpg diff --git a/doc/demo/semantic_role_labeling/index.rst b/doc/tutorials/semantic_role_labeling/index.rst similarity index 100% rename from doc/demo/semantic_role_labeling/index.rst rename to doc/tutorials/semantic_role_labeling/index.rst diff --git a/doc/demo/semantic_role_labeling/network_arch.png b/doc/tutorials/semantic_role_labeling/network_arch.png similarity index 100% rename from doc/demo/semantic_role_labeling/network_arch.png rename to doc/tutorials/semantic_role_labeling/network_arch.png diff --git a/doc/demo/semantic_role_labeling/semantic_role_labeling.md b/doc/tutorials/semantic_role_labeling/semantic_role_labeling.md similarity index 97% rename from doc/demo/semantic_role_labeling/semantic_role_labeling.md rename to doc/tutorials/semantic_role_labeling/semantic_role_labeling.md index e2793b2b3494160a7a80f07ec2127bd1f1a4f2e4..f5bdf64487aa189cefcd55d633cc6638912b9e31 100644 --- a/doc/demo/semantic_role_labeling/semantic_role_labeling.md +++ b/doc/tutorials/semantic_role_labeling/semantic_role_labeling.md @@ -1,200 +1,200 @@ -# Semantic Role labeling Tutorial # - -Semantic role labeling (SRL) is a form of shallow semantic parsing whose goal is to discover the predicate-argument structure of each predicate in a given input sentence. SRL is useful as an intermediate step in a wide range of natural language processing tasks, such as information extraction. automatic document categorization and question answering. An instance is as following [1]: - - [ A0 He ] [ AM-MOD would ][ AM-NEG n’t ] [ V accept] [ A1 anything of value ] from [A2 those he was writing about ]. - -- V: verb -- A0: acceptor -- A1: thing accepted -- A2: accepted-from -- A3: Attribute -- AM-MOD: modal -- AM-NEG: negation - -Given the verb "accept", the chunks in sentence would play certain semantic roles. Here, the label scheme is from Penn Proposition Bank. - -To this date, most of the successful SRL systems are built on top of some form of parsing results where pre-defined feature templates over the syntactic structure are used. This tutorial will present an end-to-end system using deep bidirectional long short-term memory (DB-LSTM)[2] for solving the SRL task, which largely outperforms the previous state-of-the-art systems. The system regards SRL task as the sequence labelling problem. - -## Data Description -The relevant paper[2] takes the data set in CoNLL-2005&2012 Shared Task for training and testing. Accordingto data license, the demo adopts the test data set of CoNLL-2005, which can be reached on website. - -To download and process the original data, user just need to execute the following command: - -```bash -cd data -./get_data.sh -``` -Several new files appear in the `data `directory as follows. -```bash -conll05st-release:the test data set of CoNll-2005 shared task -test.wsj.words:the Wall Street Journal data sentences -test.wsj.props: the propositional arguments -feature: the extracted features from data set -``` - -## Training -### DB-LSTM -Please refer to the Sentiment Analysis demo to learn more about the long short-term memory unit. - -Unlike Bidirectional-LSTM that used in Sentiment Analysis demo, the DB-LSTM adopts another way to stack LSTM layer. First a standard LSTM processes the sequence in forward direction. The input and output of this LSTM layer are taken by the next LSTM layer as input, processed in reversed direction. These two standard LSTM layers compose a pair of LSTM. Then we stack LSTM layers pair after pair to obtain the deep LSTM model. - -The following figure shows a temporal expanded 2-layer DB-LSTM network. -
-![pic](./network_arch.png) -
- -### Features -Two input features play an essential role in this pipeline: predicate (pred) and argument (argu). Two other features: predicate context (ctx-p) and region mark (mr) are also adopted. Because a single predicate word can not exactly describe the predicate information, especially when the same words appear more than one times in a sentence. With the predicate context, the ambiguity can be largely eliminated. Similarly, we use region mark mr = 1 to denote the argument position if it locates in the predicate context region, or mr = 0 if does not. These four simple features are all we need for our SRL system. Features of one sample with context size set to 1 is showed as following[2]: -
-![pic](./feature.jpg) -
- -In this sample, the coresponding labelled sentence is: - -[ A1 A record date ] has [ AM-NEG n't ] been [ V set ] . - -In the demo, we adopt the feature template as above, consists of : `argument`, `predicate`, `ctx-p (p=-1,0,1)`, `mark` and use `B/I/O` scheme to label each argument. These features and labels are stored in `feature` file, and separated by `\t`. - -### Data Provider - -`dataprovider.py` is the python file to wrap data. `hook()` function is to define the data slots for network. The Six features and label are all IndexSlots. -``` -def hook(settings, word_dict, label_dict, **kwargs): - settings.word_dict = word_dict - settings.label_dict = label_dict - #all inputs are integral and sequential type - settings.slots = [ - integer_value_sequence(len(word_dict)), - integer_value_sequence(len(predicate_dict)), - integer_value_sequence(len(word_dict)), - integer_value_sequence(len(word_dict)), - integer_value_sequence(len(word_dict)), - integer_value_sequence(len(word_dict)), - integer_value_sequence(len(word_dict)), - integer_value_sequence(2), - integer_value_sequence(len(label_dict))] -``` -The corresponding data iterator is as following: -``` -@provider(init_hook=hook, should_shuffle=True, calc_batch_size=get_batch_size, - can_over_batch_size=False, cache=CacheType.CACHE_PASS_IN_MEM) -def process(settings, file_name): - with open(file_name, 'r') as fdata: - for line in fdata: - sentence, predicate, ctx_n2, ctx_n1, ctx_0, ctx_p1, ctx_p2, mark, label = \ - line.strip().split('\t') - - words = sentence.split() - sen_len = len(words) - word_slot = [settings.word_dict.get(w, UNK_IDX) for w in words] - - predicate_slot = [settings.predicate_dict.get(predicate)] * sen_len - ctx_n2_slot = [settings.word_dict.get(ctx_n2, UNK_IDX)] * sen_len - ctx_n1_slot = [settings.word_dict.get(ctx_n1, UNK_IDX)] * sen_len - ctx_0_slot = [settings.word_dict.get(ctx_0, UNK_IDX)] * sen_len - ctx_p1_slot = [settings.word_dict.get(ctx_p1, UNK_IDX)] * sen_len - ctx_p2_slot = [settings.word_dict.get(ctx_p2, UNK_IDX)] * sen_len - - marks = mark.split() - mark_slot = [int(w) for w in marks] - - label_list = label.split() - label_slot = [settings.label_dict.get(w) for w in label_list] - yield word_slot, predicate_slot, ctx_n2_slot, ctx_n1_slot, \ - ctx_0_slot, ctx_p1_slot, ctx_p2_slot, mark_slot, label_slot -``` -The `process`function yield 9 lists which are 8 features and label. - -### Neural Network Config -`db_lstm.py` is the neural network config file to load the dictionaries and define the data provider module and network architecture during the training procedure. - -Nine `data_layer` load instances from data provider. Eight features are transformed into embedddings respectively, and mixed by `mixed_layer` . Deep bidirectional LSTM layers extract features for the softmax layer. The objective function is cross entropy of labels. - -### Run Training -The script for training is `train.sh`, user just need to execute: -```bash - ./train.sh -``` -The content in `train.sh`: -``` -paddle train \ - --config=./db_lstm.py \ - --use_gpu=0 \ - --log_period=5000 \ - --trainer_count=1 \ - --show_parameter_stats_period=5000 \ - --save_dir=./output \ - --num_passes=10000 \ - --average_test_period=10000000 \ - --init_model_path=./data \ - --load_missing_parameter_strategy=rand \ - --test_all_data_in_one_period=1 \ -2>&1 | tee 'train.log' -``` - -- \--config=./db_lstm.py : network config file. -- \--use_gpu=false: use CPU to train, set true, if you install GPU version of PaddlePaddle and want to use GPU to train, until now crf_layer do not support GPU -- \--log_period=500: print log every 20 batches. -- \--trainer_count=1: set thread number (or GPU count). -- \--show_parameter_stats_period=5000: show parameter statistic every 100 batches. -- \--save_dir=./output: output path to save models. -- \--num_passes=10000: set pass number, one pass in PaddlePaddle means training all samples in dataset one time. -- \--average_test_period=10000000: do test on average parameter every average_test_period batches -- \--init_model_path=./data: parameter initialization path -- \--load_missing_parameter_strategy=rand: random initialization unexisted parameters -- \--test_all_data_in_one_period=1: test all data in one period - - -After training, the models will be saved in directory `output`. Our training curve is as following: -
-![pic](./curve.jpg) -
- -### Run testing -The script for testing is `test.sh`, user just need to execute: -```bash - ./test.sh -``` -The main part in `tesh.sh` -``` -paddle train \ - --config=./db_lstm.py \ - --model_list=$model_list \ - --job=test \ - --config_args=is_test=1 \ -``` - - - \--config=./db_lstm.py: network config file - - \--model_list=$model_list.list: model list file - - \--job=test: indicate the test job - - \--config_args=is_test=1: flag to indicate test - - \--test_all_data_in_one_period=1: test all data in 1 period - - -### Run prediction -The script for prediction is `predict.sh`, user just need to execute: -```bash - ./predict.sh - -``` -In `predict.sh`, user should offer the network config file, model path, label file, word dictionary file, feature file -``` -python predict.py - -c $config_file \ - -w $best_model_path \ - -l $label_file \ - -p $predicate_dict_file \ - -d $dict_file \ - -i $input_file \ - -o $output_file -``` - -`predict.py` is the main executable python script, which includes functions: load model, load data, data prediction. The network model will output the probability distribution of labels. In the demo, we take the label with maximum probability as result. User can also implement the beam search or viterbi decoding upon the probability distribution matrix. - -After prediction, the result is saved in `predict.res`. - -## Reference -[1] Martha Palmer, Dan Gildea, and Paul Kingsbury. The Proposition Bank: An Annotated Corpus of Semantic Roles , Computational Linguistics, 31(1), 2005. - -[2] Zhou, Jie, and Wei Xu. "End-to-end learning of semantic role labeling using recurrent neural networks." Proceedings of the Annual Meeting of the Association for Computational Linguistics. 2015. +# Semantic Role labeling Tutorial # + +Semantic role labeling (SRL) is a form of shallow semantic parsing whose goal is to discover the predicate-argument structure of each predicate in a given input sentence. SRL is useful as an intermediate step in a wide range of natural language processing tasks, such as information extraction. automatic document categorization and question answering. An instance is as following [1]: + + [ A0 He ] [ AM-MOD would ][ AM-NEG n’t ] [ V accept] [ A1 anything of value ] from [A2 those he was writing about ]. + +- V: verb +- A0: acceptor +- A1: thing accepted +- A2: accepted-from +- A3: Attribute +- AM-MOD: modal +- AM-NEG: negation + +Given the verb "accept", the chunks in sentence would play certain semantic roles. Here, the label scheme is from Penn Proposition Bank. + +To this date, most of the successful SRL systems are built on top of some form of parsing results where pre-defined feature templates over the syntactic structure are used. This tutorial will present an end-to-end system using deep bidirectional long short-term memory (DB-LSTM)[2] for solving the SRL task, which largely outperforms the previous state-of-the-art systems. The system regards SRL task as the sequence labelling problem. + +## Data Description +The relevant paper[2] takes the data set in CoNLL-2005&2012 Shared Task for training and testing. Accordingto data license, the demo adopts the test data set of CoNLL-2005, which can be reached on website. + +To download and process the original data, user just need to execute the following command: + +```bash +cd data +./get_data.sh +``` +Several new files appear in the `data `directory as follows. +```bash +conll05st-release:the test data set of CoNll-2005 shared task +test.wsj.words:the Wall Street Journal data sentences +test.wsj.props: the propositional arguments +feature: the extracted features from data set +``` + +## Training +### DB-LSTM +Please refer to the Sentiment Analysis demo to learn more about the long short-term memory unit. + +Unlike Bidirectional-LSTM that used in Sentiment Analysis demo, the DB-LSTM adopts another way to stack LSTM layer. First a standard LSTM processes the sequence in forward direction. The input and output of this LSTM layer are taken by the next LSTM layer as input, processed in reversed direction. These two standard LSTM layers compose a pair of LSTM. Then we stack LSTM layers pair after pair to obtain the deep LSTM model. + +The following figure shows a temporal expanded 2-layer DB-LSTM network. +
+![pic](./network_arch.png) +
+ +### Features +Two input features play an essential role in this pipeline: predicate (pred) and argument (argu). Two other features: predicate context (ctx-p) and region mark (mr) are also adopted. Because a single predicate word can not exactly describe the predicate information, especially when the same words appear more than one times in a sentence. With the predicate context, the ambiguity can be largely eliminated. Similarly, we use region mark mr = 1 to denote the argument position if it locates in the predicate context region, or mr = 0 if does not. These four simple features are all we need for our SRL system. Features of one sample with context size set to 1 is showed as following[2]: +
+![pic](./feature.jpg) +
+ +In this sample, the coresponding labelled sentence is: + +[ A1 A record date ] has [ AM-NEG n't ] been [ V set ] . + +In the demo, we adopt the feature template as above, consists of : `argument`, `predicate`, `ctx-p (p=-1,0,1)`, `mark` and use `B/I/O` scheme to label each argument. These features and labels are stored in `feature` file, and separated by `\t`. + +### Data Provider + +`dataprovider.py` is the python file to wrap data. `hook()` function is to define the data slots for network. The Six features and label are all IndexSlots. +``` +def hook(settings, word_dict, label_dict, **kwargs): + settings.word_dict = word_dict + settings.label_dict = label_dict + #all inputs are integral and sequential type + settings.slots = [ + integer_value_sequence(len(word_dict)), + integer_value_sequence(len(predicate_dict)), + integer_value_sequence(len(word_dict)), + integer_value_sequence(len(word_dict)), + integer_value_sequence(len(word_dict)), + integer_value_sequence(len(word_dict)), + integer_value_sequence(len(word_dict)), + integer_value_sequence(2), + integer_value_sequence(len(label_dict))] +``` +The corresponding data iterator is as following: +``` +@provider(init_hook=hook, should_shuffle=True, calc_batch_size=get_batch_size, + can_over_batch_size=False, cache=CacheType.CACHE_PASS_IN_MEM) +def process(settings, file_name): + with open(file_name, 'r') as fdata: + for line in fdata: + sentence, predicate, ctx_n2, ctx_n1, ctx_0, ctx_p1, ctx_p2, mark, label = \ + line.strip().split('\t') + + words = sentence.split() + sen_len = len(words) + word_slot = [settings.word_dict.get(w, UNK_IDX) for w in words] + + predicate_slot = [settings.predicate_dict.get(predicate)] * sen_len + ctx_n2_slot = [settings.word_dict.get(ctx_n2, UNK_IDX)] * sen_len + ctx_n1_slot = [settings.word_dict.get(ctx_n1, UNK_IDX)] * sen_len + ctx_0_slot = [settings.word_dict.get(ctx_0, UNK_IDX)] * sen_len + ctx_p1_slot = [settings.word_dict.get(ctx_p1, UNK_IDX)] * sen_len + ctx_p2_slot = [settings.word_dict.get(ctx_p2, UNK_IDX)] * sen_len + + marks = mark.split() + mark_slot = [int(w) for w in marks] + + label_list = label.split() + label_slot = [settings.label_dict.get(w) for w in label_list] + yield word_slot, predicate_slot, ctx_n2_slot, ctx_n1_slot, \ + ctx_0_slot, ctx_p1_slot, ctx_p2_slot, mark_slot, label_slot +``` +The `process`function yield 9 lists which are 8 features and label. + +### Neural Network Config +`db_lstm.py` is the neural network config file to load the dictionaries and define the data provider module and network architecture during the training procedure. + +Nine `data_layer` load instances from data provider. Eight features are transformed into embedddings respectively, and mixed by `mixed_layer` . Deep bidirectional LSTM layers extract features for the softmax layer. The objective function is cross entropy of labels. + +### Run Training +The script for training is `train.sh`, user just need to execute: +```bash + ./train.sh +``` +The content in `train.sh`: +``` +paddle train \ + --config=./db_lstm.py \ + --use_gpu=0 \ + --log_period=5000 \ + --trainer_count=1 \ + --show_parameter_stats_period=5000 \ + --save_dir=./output \ + --num_passes=10000 \ + --average_test_period=10000000 \ + --init_model_path=./data \ + --load_missing_parameter_strategy=rand \ + --test_all_data_in_one_period=1 \ +2>&1 | tee 'train.log' +``` + +- \--config=./db_lstm.py : network config file. +- \--use_gpu=false: use CPU to train, set true, if you install GPU version of PaddlePaddle and want to use GPU to train, until now crf_layer do not support GPU +- \--log_period=500: print log every 20 batches. +- \--trainer_count=1: set thread number (or GPU count). +- \--show_parameter_stats_period=5000: show parameter statistic every 100 batches. +- \--save_dir=./output: output path to save models. +- \--num_passes=10000: set pass number, one pass in PaddlePaddle means training all samples in dataset one time. +- \--average_test_period=10000000: do test on average parameter every average_test_period batches +- \--init_model_path=./data: parameter initialization path +- \--load_missing_parameter_strategy=rand: random initialization unexisted parameters +- \--test_all_data_in_one_period=1: test all data in one period + + +After training, the models will be saved in directory `output`. Our training curve is as following: +
+![pic](./curve.jpg) +
+ +### Run testing +The script for testing is `test.sh`, user just need to execute: +```bash + ./test.sh +``` +The main part in `tesh.sh` +``` +paddle train \ + --config=./db_lstm.py \ + --model_list=$model_list \ + --job=test \ + --config_args=is_test=1 \ +``` + + - \--config=./db_lstm.py: network config file + - \--model_list=$model_list.list: model list file + - \--job=test: indicate the test job + - \--config_args=is_test=1: flag to indicate test + - \--test_all_data_in_one_period=1: test all data in 1 period + + +### Run prediction +The script for prediction is `predict.sh`, user just need to execute: +```bash + ./predict.sh + +``` +In `predict.sh`, user should offer the network config file, model path, label file, word dictionary file, feature file +``` +python predict.py + -c $config_file \ + -w $best_model_path \ + -l $label_file \ + -p $predicate_dict_file \ + -d $dict_file \ + -i $input_file \ + -o $output_file +``` + +`predict.py` is the main executable python script, which includes functions: load model, load data, data prediction. The network model will output the probability distribution of labels. In the demo, we take the label with maximum probability as result. User can also implement the beam search or viterbi decoding upon the probability distribution matrix. + +After prediction, the result is saved in `predict.res`. + +## Reference +[1] Martha Palmer, Dan Gildea, and Paul Kingsbury. The Proposition Bank: An Annotated Corpus of Semantic Roles , Computational Linguistics, 31(1), 2005. + +[2] Zhou, Jie, and Wei Xu. "End-to-end learning of semantic role labeling using recurrent neural networks." Proceedings of the Annual Meeting of the Association for Computational Linguistics. 2015. diff --git a/doc/demo/sentiment_analysis/bi_lstm.jpg b/doc/tutorials/sentiment_analysis/bi_lstm.jpg similarity index 100% rename from doc/demo/sentiment_analysis/bi_lstm.jpg rename to doc/tutorials/sentiment_analysis/bi_lstm.jpg diff --git a/doc/demo/sentiment_analysis/index.rst b/doc/tutorials/sentiment_analysis/index.rst similarity index 100% rename from doc/demo/sentiment_analysis/index.rst rename to doc/tutorials/sentiment_analysis/index.rst diff --git a/doc/demo/sentiment_analysis/lstm.png b/doc/tutorials/sentiment_analysis/lstm.png similarity index 100% rename from doc/demo/sentiment_analysis/lstm.png rename to doc/tutorials/sentiment_analysis/lstm.png diff --git a/doc/demo/sentiment_analysis/sentiment_analysis.md b/doc/tutorials/sentiment_analysis/sentiment_analysis.md similarity index 100% rename from doc/demo/sentiment_analysis/sentiment_analysis.md rename to doc/tutorials/sentiment_analysis/sentiment_analysis.md diff --git a/doc/demo/sentiment_analysis/stacked_lstm.jpg b/doc/tutorials/sentiment_analysis/stacked_lstm.jpg similarity index 100% rename from doc/demo/sentiment_analysis/stacked_lstm.jpg rename to doc/tutorials/sentiment_analysis/stacked_lstm.jpg diff --git a/doc/demo/text_generation/encoder-decoder-attention-model.png b/doc/tutorials/text_generation/encoder-decoder-attention-model.png similarity index 100% rename from doc/demo/text_generation/encoder-decoder-attention-model.png rename to doc/tutorials/text_generation/encoder-decoder-attention-model.png diff --git a/doc/demo/text_generation/index.rst b/doc/tutorials/text_generation/index.rst similarity index 100% rename from doc/demo/text_generation/index.rst rename to doc/tutorials/text_generation/index.rst diff --git a/doc/demo/text_generation/text_generation.md b/doc/tutorials/text_generation/text_generation.md similarity index 100% rename from doc/demo/text_generation/text_generation.md rename to doc/tutorials/text_generation/text_generation.md diff --git a/doc/ui/index.md b/doc/ui/index.md deleted file mode 100644 index 9c1ba27bdc14fa9ab762ffb97424a8a5946808f9..0000000000000000000000000000000000000000 --- a/doc/ui/index.md +++ /dev/null @@ -1,20 +0,0 @@ -# User Interface - -## Data Provider - -* [Introduction](data_provider/index.rst) -* [PyDataProvider2](data_provider/pydataprovider2.rst) - -## API Reference - -* [Model Config Interface](api/trainer_config_helpers/index.md) - -## Command Line Argument - -* [Use Case](cmd_argument/use_case.md) -* [Argument Outline](cmd_argument/argument_outline.md) -* [Detailed Descriptions](cmd_argument/detail_introduction.md) - -## Predict - -* [Python Prediction API](predict/swig_py_paddle_en.rst) diff --git a/doc/user_guide.rst b/doc/user_guide.rst deleted file mode 100644 index d4deb3ca5a4523b509ea5082f32be8a315570dea..0000000000000000000000000000000000000000 --- a/doc/user_guide.rst +++ /dev/null @@ -1,13 +0,0 @@ -User Guide -========== - -.. toctree:: - :maxdepth: 1 - - demo/quick_start/index_en.md - build/index.rst - build/contribute_to_paddle.md - ui/index.md - ui/api/trainer_config_helpers/index.rst - demo/index.md - cluster/index.md