提交 94538798 编写于 作者: Y Yu Yang

Merge branch 'develop' of github.com:baidu/Paddle into feature/travis_pre_commit_checks

...@@ -9,3 +9,6 @@ build/ ...@@ -9,3 +9,6 @@ build/
.pydevproject .pydevproject
Makefile Makefile
.test_env/ .test_env/
*~
bazel-*
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
sha: v0.13.2 sha: v0.13.2
hooks: hooks:
- id: yapf - id: yapf
files: (.*\.(py|bzl)|BUILD|.*\.BUILD|WORKSPACE)$ # Bazel BUILD files follow Python syntax.
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
sha: 7539d8bd1a00a3c1bfd34cdb606d3a6372e83469 sha: 7539d8bd1a00a3c1bfd34cdb606d3a6372e83469
hooks: hooks:
......
...@@ -46,16 +46,19 @@ addons: ...@@ -46,16 +46,19 @@ addons:
before_install: before_install:
- | - |
if [ ${JOB} == "BUILD_AND_TEST" ]; then if [ ${JOB} == "BUILD_AND_TEST" ]; then
if ! git diff --name-only $TRAVIS_COMMIT_RANGE | grep -qvE '(\.md$)|(\.rst$)|(\.jpg$)|(\.png$)' local change_list=`git diff --name-only $TRAVIS_COMMIT_RANGE`
if [ $? -eq 0 ]; then # if git diff return no zero, then rerun unit test.
if ! echo ${change_list} | grep -qvE '(\.md$)|(\.rst$)|(\.jpg$)|(\.png$)'
then then
echo "Only markdown docs were updated, stopping build process." echo "Only markdown docs were updated, stopping build process."
exit exit
fi fi
fi fi
fi
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo paddle/scripts/travis/before_install.linux.sh; fi - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo paddle/scripts/travis/before_install.linux.sh; fi
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then paddle/scripts/travis/before_install.osx.sh; fi - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then paddle/scripts/travis/before_install.osx.sh; fi
- if [[ "$JOB" == "PRE_COMMIT" ]]; then sudo ln -s /usr/bin/clang-format-3.8 /usr/bin/clang-format; fi - if [[ "$JOB" == "PRE_COMMIT" ]]; then sudo ln -s /usr/bin/clang-format-3.8 /usr/bin/clang-format; fi
- pip install wheel protobuf sphinx breathe recommonmark virtualenv numpy sphinx_rtd_theme pre-commit - pip install wheel protobuf sphinx recommonmark virtualenv numpy sphinx_rtd_theme pre-commit
script: script:
- paddle/scripts/travis/main.sh - paddle/scripts/travis/main.sh
notifications: notifications:
......
# External dependency to Google protobuf.
http_archive(
name = "protobuf",
url = "http://github.com/google/protobuf/archive/v3.1.0.tar.gz",
sha256 = "0a0ae63cbffc274efb573bdde9a253e3f32e458c41261df51c5dbc5ad541e8f7",
strip_prefix = "protobuf-3.1.0",
)
# External dependency to gtest 1.7.0. This method comes from
# https://www.bazel.io/versions/master/docs/tutorial/cpp.html.
new_http_archive(
name = "gtest",
url = "https://github.com/google/googletest/archive/release-1.7.0.zip",
sha256 = "b58cb7547a28b2c718d1e38aee18a3659c9e3ff52440297e965f5edffe34b6d0",
build_file = "third_party/gtest.BUILD",
strip_prefix = "googletest-release-1.7.0",
)
...@@ -30,7 +30,6 @@ if(WITH_DOC) ...@@ -30,7 +30,6 @@ if(WITH_DOC)
find_package(Sphinx REQUIRED) find_package(Sphinx REQUIRED)
find_package(Doxygen REQUIRED) find_package(Doxygen REQUIRED)
find_python_module(recommonmark REQUIRED) find_python_module(recommonmark REQUIRED)
find_python_module(breathe REQUIRED)
endif() endif()
if(WITH_SWIG_PY) if(WITH_SWIG_PY)
......
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import os import os, sys
import numpy as np import numpy as np
from optparse import OptionParser from optparse import OptionParser
from py_paddle import swig_paddle, DataProviderConverter from py_paddle import swig_paddle, DataProviderConverter
...@@ -66,35 +66,27 @@ class SentimentPrediction(): ...@@ -66,35 +66,27 @@ class SentimentPrediction():
for v in open(label_file, 'r'): for v in open(label_file, 'r'):
self.label[int(v.split('\t')[1])] = v.split('\t')[0] self.label[int(v.split('\t')[1])] = v.split('\t')[0]
def get_data(self, data_file): def get_index(self, data):
""" """
Get input data of paddle format. transform word into integer index according to the dictionary.
""" """
with open(data_file, 'r') as fdata: words = data.strip().split()
for line in fdata:
words = line.strip().split()
word_slot = [ word_slot = [
self.word_dict[w] for w in words if w in self.word_dict self.word_dict[w] for w in words if w in self.word_dict
] ]
if not word_slot: return word_slot
print "all words are not in dictionary: %s", line
continue
yield [word_slot]
def predict(self, data_file): def batch_predict(self, data_batch):
""" input = self.converter(data_batch)
data_file: file name of input data.
"""
input = self.converter(self.get_data(data_file))
output = self.network.forwardTest(input) output = self.network.forwardTest(input)
prob = output[0]["value"] prob = output[0]["value"]
lab = np.argsort(-prob) labs = np.argsort(-prob)
for idx, lab in enumerate(labs):
if self.label is None: if self.label is None:
print("%s: predicting label is %d" % (data_file, lab[0][0])) print("predicting label is %d" % (lab[0]))
else: else:
print("%s: predicting label is %s" % print("predicting label is %s" %
(data_file, self.label[lab[0][0]])) (self.label[lab[0]]))
def option_parser(): def option_parser():
usage = "python predict.py -n config -w model_dir -d dictionary -i input_file " usage = "python predict.py -n config -w model_dir -d dictionary -i input_file "
...@@ -119,11 +111,13 @@ def option_parser(): ...@@ -119,11 +111,13 @@ def option_parser():
default=None, default=None,
help="dictionary file") help="dictionary file")
parser.add_option( parser.add_option(
"-i", "-c",
"--data", "--batch_size",
type="int",
action="store", action="store",
dest="data", dest="batch_size",
help="data file to predict") default=1,
help="the batch size for prediction")
parser.add_option( parser.add_option(
"-w", "-w",
"--model", "--model",
...@@ -137,14 +131,21 @@ def option_parser(): ...@@ -137,14 +131,21 @@ def option_parser():
def main(): def main():
options, args = option_parser() options, args = option_parser()
train_conf = options.train_conf train_conf = options.train_conf
data = options.data batch_size = options.batch_size
dict_file = options.dict_file dict_file = options.dict_file
model_path = options.model_path model_path = options.model_path
label = options.label label = options.label
swig_paddle.initPaddle("--use_gpu=0") swig_paddle.initPaddle("--use_gpu=0")
predict = SentimentPrediction(train_conf, dict_file, model_path, label) predict = SentimentPrediction(train_conf, dict_file, model_path, label)
predict.predict(data)
batch = []
for line in sys.stdin:
batch.append([predict.get_index(line)])
if len(batch) == batch_size:
predict.batch_predict(batch)
batch=[]
if len(batch) > 0:
predict.batch_predict(batch)
if __name__ == '__main__': if __name__ == '__main__':
main() main()
...@@ -19,9 +19,9 @@ set -e ...@@ -19,9 +19,9 @@ set -e
model=model_output/pass-00002/ model=model_output/pass-00002/
config=trainer_config.py config=trainer_config.py
label=data/pre-imdb/labels.list label=data/pre-imdb/labels.list
python predict.py \ cat ./data/aclImdb/test/pos/10007_10.txt | python predict.py \
-n $config\ --tconf=$config\
-w $model \ --model=$model \
-b $label \ --label=$label \
-d ./data/pre-imdb/dict.txt \ --dict=./data/pre-imdb/dict.txt \
-i ./data/aclImdb/test/pos/10007_10.txt --batch_size=1
.. _api_pydataprovider:
PyDataProvider2 PyDataProvider2
================= ===============
We highly recommand users to use PyDataProvider2 to provide training or testing We highly recommand users to use PyDataProvider2 to provide training or testing
data to PaddlePaddle. The user only needs to focus on how to read a single data to PaddlePaddle. The user only needs to focus on how to read a single
......
API API
==== ===
DataProvider API DataProvider API
---------------- ----------------
...@@ -10,6 +10,8 @@ DataProvider API ...@@ -10,6 +10,8 @@ DataProvider API
data_provider/index_en.rst data_provider/index_en.rst
data_provider/pydataprovider2_en.rst data_provider/pydataprovider2_en.rst
.. _api_trainer_config:
Model Config API Model Config API
---------------- ----------------
......
.. _api_trainer_config_helpers_data_sources:
DataSources DataSources
=========== ===========
......
...@@ -20,6 +20,8 @@ LayerOutput ...@@ -20,6 +20,8 @@ LayerOutput
Data layer Data layer
=========== ===========
.. _api_trainer_config_helpers_layers_data_layer:
data_layer data_layer
---------- ----------
.. automodule:: paddle.trainer_config_helpers.layers .. automodule:: paddle.trainer_config_helpers.layers
...@@ -29,6 +31,8 @@ data_layer ...@@ -29,6 +31,8 @@ data_layer
Fully Connected Layers Fully Connected Layers
====================== ======================
.. _api_trainer_config_helpers_layers_fc_layer:
fc_layer fc_layer
-------- --------
.. automodule:: paddle.trainer_config_helpers.layers .. automodule:: paddle.trainer_config_helpers.layers
...@@ -68,6 +72,8 @@ img_conv_layer ...@@ -68,6 +72,8 @@ img_conv_layer
:members: img_conv_layer :members: img_conv_layer
:noindex: :noindex:
.. _api_trainer_config_helpers_layers_context_projection:
context_projection context_projection
------------------ ------------------
.. automodule:: paddle.trainer_config_helpers.layers .. automodule:: paddle.trainer_config_helpers.layers
...@@ -185,6 +191,8 @@ mixed_layer ...@@ -185,6 +191,8 @@ mixed_layer
:members: mixed_layer :members: mixed_layer
:noindex: :noindex:
.. _api_trainer_config_helpers_layers_embedding_layer:
embedding_layer embedding_layer
--------------- ---------------
.. automodule:: paddle.trainer_config_helpers.layers .. automodule:: paddle.trainer_config_helpers.layers
...@@ -237,6 +245,8 @@ trans_full_matrix_projection ...@@ -237,6 +245,8 @@ trans_full_matrix_projection
Aggregate Layers Aggregate Layers
================ ================
.. _api_trainer_config_helpers_layers_pooling_layer:
pooling_layer pooling_layer
------------- -------------
.. automodule:: paddle.trainer_config_helpers.layers .. automodule:: paddle.trainer_config_helpers.layers
...@@ -333,6 +343,8 @@ tensor_layer ...@@ -333,6 +343,8 @@ tensor_layer
:members: tensor_layer :members: tensor_layer
:noindex: :noindex:
.. _api_trainer_config_helpers_layers_cos_sim:
cos_sim cos_sim
------- -------
.. automodule:: paddle.trainer_config_helpers.layers .. automodule:: paddle.trainer_config_helpers.layers
......
...@@ -13,6 +13,8 @@ sequence_conv_pool ...@@ -13,6 +13,8 @@ sequence_conv_pool
:members: sequence_conv_pool :members: sequence_conv_pool
:noindex: :noindex:
.. _api_trainer_config_helpers_network_text_conv_pool:
text_conv_pool text_conv_pool
-------------- --------------
.. automodule:: paddle.trainer_config_helpers.networks .. automodule:: paddle.trainer_config_helpers.networks
......
...@@ -144,5 +144,6 @@ def setup(app): ...@@ -144,5 +144,6 @@ def setup(app):
# no c++ API for now # no c++ API for now
app.add_config_value('recommonmark_config', { app.add_config_value('recommonmark_config', {
'url_resolver': lambda url: github_doc_root + url, 'url_resolver': lambda url: github_doc_root + url,
'enable_eval_rst': True,
}, True) }, True)
app.add_transform(AutoStructify) app.add_transform(AutoStructify)
...@@ -79,7 +79,7 @@ As a simple example, consider the following: ...@@ -79,7 +79,7 @@ As a simple example, consider the following:
```bash ```bash
pip install 'sphinx>=1.4.0' pip install 'sphinx>=1.4.0'
pip install sphinx_rtd_theme breathe recommonmark pip install sphinx_rtd_theme recommonmark
# install doxygen on Ubuntu # install doxygen on Ubuntu
sudo apt-get install doxygen sudo apt-get install doxygen
......
...@@ -104,3 +104,70 @@ container: ...@@ -104,3 +104,70 @@ container:
Then we can direct our Web browser to the HTML version of source code Then we can direct our Web browser to the HTML version of source code
at http://localhost:8088/paddle/ at http://localhost:8088/paddle/
Development Using Docker
------------------------
Develpers can work on PaddlePaddle using Docker. This allows
developers to work on different platforms -- Linux, Mac OS X, and
Windows -- in a consistent way.
The general development workflow with Docker and Bazel is as follows:
1. Get the source code of Paddle:
.. code-block:: bash
git clone --recursive https://github.com/paddlepaddle/paddle
2. Build a development Docker image `paddle:dev` from the source code.
This image contains all the development tools and dependencies of
PaddlePaddle.
.. code-block:: bash
cd paddle
docker build -t paddle:dev -f paddle/scripts/docker/Dockerfile .
3. Run the image as a container and mounting local source code
directory into the container. This allows us to change the code on
the host and build it within the container.
.. code-block:: bash
docker run \
-d # run the container in background mode \
--name paddle # we can run a nginx container to serve documents \
-p 2022:22 # so we can SSH into this container \
-v $PWD:/paddle # mount the source code \
-v $HOME/.cache/bazel:/root/.cache/bazel # mount Bazel cache \
paddle:dev
4. SSH into the container:
.. code-block:: bash
ssh root@localhost -p 2022
5. We can edit the source code in the container or on this host. Then
we can build using cmake
.. code-block:: bash
cd /paddle # where paddle source code has been mounted into the container
mkdir -p build
cd build
cmake -DWITH_TESTING=ON ..
make -j `nproc`
CTEST_OUTPUT_ON_FAILURE=1 ctest
or Bazel in the container:
.. code-block:: bash
cd /paddle
bazel test ...
```eval_rst
.. _cmd_line_index_en:
```
# How to Set Command-line Parameters # How to Set Command-line Parameters
* [Use Case](use_case_en.md) * [Use Case](use_case_en.md)
......
API
===
.. doxygenfile:: paddle/api/PaddleAPI.h
.. doxygenfile:: paddle/api/Internal.h
CUDA
====
.. toctree::
:maxdepth: 2
matrix.rst
nn.rst
utils.rst
Matrix
======
Base
----
hl_matrix.h
```````````
.. doxygenfile:: paddle/cuda/include/hl_matrix.h
hl_matrix_base.h
````````````````
.. doxygenfile:: paddle/cuda/include/hl_matrix_base.cuh
hl_matrix_apply.cuh
```````````````````
.. doxygenfile:: paddle/cuda/include/hl_matrix_apply.cuh
hl_matrix_ops.cuh
`````````````````
.. doxygenfile:: paddle/cuda/include/hl_matrix_ops.cuh
hl_matrix_type.cuh
``````````````````
.. doxygenfile:: paddle/cuda/include/hl_matrix_type.cuh
hl_sse_matrix_kernel.cuh
````````````````````````
.. doxygenfile:: paddle/cuda/include/hl_sse_matrix_kernel.cuh
Matrix Function
---------------
hl_batch_transpose.h
````````````````````
.. doxygenfile:: paddle/cuda/include/hl_batch_transpose.h
hl_aggregate.h
``````````````
.. doxygenfile:: paddle/cuda/include/hl_aggregate.h
hl_top_k.h
``````````
.. doxygenfile:: paddle/cuda/include/hl_top_k.h
hl_table_apply.h
````````````````
.. doxygenfile:: paddle/cuda/include/hl_table_apply.h
Sparse Matrix
-------------
hl_sparse.h
```````````
.. doxygenfile:: paddle/cuda/include/hl_sparse.h
hl_sparse.ph
````````````
.. doxygenfile:: paddle/cuda/include/hl_sparse.ph
Neural Network
==============
Base
----
.. doxygenfile:: paddle/cuda/include/hl_gpu.h
.. doxygenfile:: paddle/cuda/include/hl_functions.h
.. doxygenfile:: paddle/cuda/include/hl_avx_functions.h
.. doxygenfile:: paddle/cuda/include/hl_gpu_functions.cuh
.. doxygenfile:: paddle/cuda/include/hl_activation_functions.h
CNN Related APIs
----------------
.. doxygenfile:: paddle/cuda/include/hl_cnn.h
.. doxygenfile:: paddle/cuda/include/hl_cuda_cudnn.h
.. doxygenfile:: paddle/cuda/include/hl_cuda_cudnn.ph
RNN Related APIs
----------------
.. doxygenfile:: paddle/cuda/include/hl_recurrent_apply.cuh
.. doxygenfile:: paddle/cuda/include/hl_sequence.h
LSTM Model
``````````
.. doxygenfile:: paddle/cuda/include/hl_lstm.h
.. dpxygenfile:: paddle/cuda/include/hl_cpu_lstm.cuh
.. doxygenfile:: paddle/cuda/include/hl_gpu_lstm.cuh
.. doxygenfile:: paddle/cuda/include/hl_lstm_ops.cuh
GRU Model
`````````
.. doxygenfile:: paddle/cuda/include/hl_gru_ops.cuh
.. doxygenfile:: paddle/cuda/include/hl_cpu_gru.cuh
.. doxygenfile:: paddle/cuda/include/hl_gpu_gru.cuh
Utils
=====
Dynamic Link Libs
-----------------
.. doxygenfile:: paddle/cuda/include/hl_dso_loader.h
GPU Resources
-------------
hl_cuda.ph
``````````
.. doxygenfile:: paddle/cuda/include/hl_cuda.ph
hl_cuda.h
`````````
.. doxygenfile:: paddle/cuda/include/hl_cuda.h
HPPL Base
---------
.. doxygenfile:: paddle/cuda/include/hl_base.h
CUBLAS Wrapper
--------------
.. doxygenfile:: paddle/cuda/include/hl_cuda_cublas.h
Timer
-----
.. doxygenfile:: paddle/cuda/include/hl_time.h
Thread Resource
---------------
.. doxygenfile:: paddle/cuda/include/hl_thread.ph
Device Function
---------------
.. doxygenfile:: paddle/cuda/include/hl_device_functions.cuh
Activations
===========
.. doxygenclass:: paddle::ActivationFunction
:members:
==============
Data Providers
==============
DataProviders
=============
Base
----
.. doxygenclass:: paddle::DataProvider
:members:
DataProviderGroup
-----------------
.. doxygenclass:: paddle::DataProviderGroup
:members:
MultiDataProvider
-----------------
.. doxygenclass:: paddle::MultiDataProvider
:members:
PyDataProvider
==============
IFieldScanner
-------------
.. doxygenclass:: paddle::IFieldScanner
:members:
DenseScanner
-------------
.. doxygenclass:: paddle::DenseScanner
:members:
IndexScanner
-------------
.. doxygenclass:: paddle::IndexScanner
:members:
SparseNonValueScanner
---------------------
.. doxygenclass:: paddle::SparseNonValueScanner
:members:
SparseValueScanner
------------------
.. doxygenclass:: paddle::SparseValueScanner
:members:
SequenceScanner
---------------
.. doxygenclass:: paddle::SparseValueScanner
:members:
IPyDataProviderCache
--------------------
.. doxygenclass:: paddle::IPyDataProviderCache
:members:
NoCacheStrategy
---------------
.. doxygenclass:: paddle::NoCacheStrategy
:members:
CacheOnePassInMemory
--------------------
.. doxygenclass:: paddle::CacheOnePassInMemory
:members:
IPyDataProvider
---------------
.. doxygenclass:: paddle::PyDataProvider2
:members:
ProtoDataProvider
=================
ProtoDataProvider
----------------
.. doxygenclass:: paddle::ProtoDataProvider
:members:
ProtoSequenceDataProvider
-------------------------
.. doxygenclass:: paddle::ProtoSequenceDataProvider
:members:
==========
Evaluators
==========
Base
====
.. doxygenclass:: paddle::Evaluator
:members:
Sum
===
SumEvaluator
------------
.. doxygenclass:: paddle::SumEvaluator
:members:
ColumnSumEvaluator
------------------
.. doxygenclass:: paddle::ColumnSumEvaluator
:members:
Classification
==============
ClassificationErrorEvaluator
---------------------------
.. doxygenclass:: paddle::ClassificationErrorEvaluator
:members:
SequenceClassificationErrorEvaluator
------------------------------------
.. doxygenclass:: paddle::SequenceClassificationErrorEvaluator
:members:
AucEvaluator
-------------
.. doxygenclass:: paddle::AucEvaluator
:members:
PrecisionRecallEvaluator
------------------------
.. doxygenclass:: paddle::PrecisionRecallEvaluator
:members:
ChunkEvaluator
--------------
.. doxygenclass:: paddle::ChunkEvaluator
:members:
CTCEvaluator
------------
.. doxygenclass:: paddle::CTCErrorEvaluator
:members:
Rank
====
PnpairEvaluator
-------------
.. doxygenclass:: paddle::PnpairEvaluator
:members:
AucEvaluator
-------------
.. doxygenclass:: paddle::RankAucEvaluator
:members:
Printer
=======
ValuePrinter
-------------
.. doxygenclass:: paddle::ValuePrinter
:members:
GradientPrinter
---------------
.. doxygenclass:: paddle::GradientPrinter
:members:
MaxIdPrinter
------------
.. doxygenclass:: paddle::MaxIdPrinter
:members:
MaxFramePrinter
---------------
.. doxygenclass:: paddle::MaxFramePrinter
:members:
SequenceTextPrinter
------------------
.. doxygenclass:: paddle::SequenceTextPrinter
:members:
ClassificationErrorPrinter
--------------------------
.. doxygenclass:: paddle::ClassificationErrorPrinter
:members:
Gradient Machines
=================
GradientMachine
---------------
.. doxygenclass:: paddle::GradientMachine
:members:
GradientMachineMode
-------------------
.. doxygenclass:: paddle::IGradientMachineMode
:members:
MultiGradientMachine
--------------------
.. doxygenclass:: paddle::MultiGradientMachine
:members:
TrainerThread
`````````````
.. doxygenclass:: paddle::TrainerThread
:members:
RecurrentGradientMachine
------------------------
.. doxygenclass:: paddle::RecurrentGradientMachine
:members:
GServer
=======
.. toctree::
:maxdepth: 2
activations.rst
dataproviders.rst
evaluators.rst
gradientmachines.rst
layers.rst
neworks.rst
======
Layers
======
Base
====
Layer
-----
.. doxygenclass:: paddle::Layer
:members:
Projection
----------
.. doxygenclass:: paddle::Projection
:members:
Operator
--------
.. doxygenclass:: paddle::Operator
:members:
Data Layer
==========
.. doxygenclass:: paddle::DataLayer
:members:
Fully Connected Layers
======================
FullyConnectedLayer
-------------------
.. doxygenclass:: paddle::FullyConnectedLayer
:members:
SelectiveFullyConnectedLayer
----------------------------
.. doxygenclass:: paddle::SelectiveFullyConnectedLayer
:members:
Conv Layers
===========
ConvBaseLayer
-------------
.. doxygenclass:: paddle::ConvBaseLayer
:members:
ConvOperator
------------
.. doxygenclass:: paddle::ConvOperator
:members:
ConvShiftLayer
--------------
.. doxygenclass:: paddle::ConvShiftLayer
:members:
CudnnConvLayer
--------------
.. doxygenclass:: paddle::CudnnConvLayer
:members:
ExpandConvBaseLayer
-------------------
.. doxygenclass:: paddle::ExpandConvBaseLayer
:members:
ExpandConvLayer
---------------
.. doxygenclass:: paddle::ExpandConvLayer
:members:
ContextProjection
-----------------
.. doxygenclass:: paddle::ContextProjection
:members:
Pooling Layers
==============
PoolLayer
---------
.. doxygenclass:: paddle::PoolLayer
:members:
PoolProjectionLayer
-------------------
.. doxygenclass:: paddle::PoolProjectionLayer
:members:
CudnnPoolLayer
--------------
.. doxygenclass:: paddle::CudnnPoolLayer
:members:
SpatialPyramidPoolLayer
-----------------------
.. doxygenclass:: paddle::SpatialPyramidPoolLayer
:members:
MaxOutLayer
-----------
.. doxygenclass:: paddle::MaxOutLayer
:members:
Norm Layers
===========
NormLayer
---------
.. doxygenclass:: paddle::NormLayer
:members:
CMRProjectionNormLayer
----------------------
.. doxygenclass:: paddle::CMRProjectionNormLayer
:members:
DataNormLayer
-------------
.. doxygenclass:: paddle::DataNormLayer
:members:
ResponseNormLayer
-----------------
.. doxygenclass:: paddle::ResponseNormLayer
:members:
BatchNormBaseLayer
------------------
.. doxygenclass:: paddle::BatchNormBaseLayer
:members:
BatchNormalizationLayer
-----------------------
.. doxygenclass:: paddle::BatchNormalizationLayer
:members:
CudnnBatchNormLayer
-----------------------
.. doxygenclass:: paddle::CudnnBatchNormLayer
:members:
SumToOneNormLayer
-----------------
.. doxygenclass:: paddle::SumToOneNormLayer
:members:
Activation Layer
================
ParameterReluLayer
------------------
.. doxygenclass:: paddle::ParameterReluLayer
:members:
Recurrent Layers
================
RecurrentLayer
--------------
.. doxygenclass:: paddle::RecurrentLayer
:members:
SequenceToBatch
---------------
.. doxygenclass:: paddle::SequenceToBatch
:members:
LSTM
----
LstmLayer
`````````
.. doxygenclass:: paddle::LstmLayer
:members:
LstmStepLayer
`````````````
.. doxygenclass:: paddle::LstmStepLayer
:members:
LstmCompute
```````````
.. doxygenclass:: paddle::LstmCompute
:members:
MDLSTM
------
MDLstmLayer
```````````
.. doxygenclass:: paddle::MDLstmLayer
:members:
CoordIterator
`````````````
.. doxygenclass:: paddle::CoordIterator
:members:
GRU
---
GatedRecurrentLayer
```````````````````
.. doxygenclass:: paddle::GatedRecurrentLayer
:members:
GruStepLayer
````````````
.. doxygenclass:: paddle::GruStepLayer
:members:
GruCompute
``````````
.. doxygenclass:: paddle::GruCompute
:members:
Recurrent Layer Group
=====================
AgentLayer
----------
.. doxygenclass:: paddle::AgentLayer
:members:
SequenceAgentLayer
------------------
.. doxygenclass:: paddle::SequenceAgentLayer
:members:
GatherAgentLayer
----------------
.. doxygenclass:: paddle::GatherAgentLayer
:members:
SequenceGatherAgentLayer
------------------------
.. doxygenclass:: paddle::SequenceGatherAgentLayer
:members:
ScatterAgentLayer
-----------------
.. doxygenclass:: paddle::ScatterAgentLayer
:members:
SequenceScatterAgentLayer
-------------------------
.. doxygenclass:: paddle::SequenceScatterAgentLayer
:members:
GetOutputLayer
--------------
.. doxygenclass:: paddle::GetOutputLayer
:members:
Mixed Layer
===========
.. doxygenclass:: paddle::MixedLayer
:members:
DotMulProjection
----------------
.. doxygenclass:: paddle::DotMulProjection
:members:
DotMulOperator
--------------
.. doxygenclass:: paddle::DotMulOperator
:members:
FullMatrixProjection
--------------------
.. doxygenclass:: paddle::FullMatrixProjection
:members:
IdentityProjection
------------------
.. doxygenclass:: paddle::IdentityProjection
:members:
IdentityOffsetProjection
------------------------
.. doxygenclass:: paddle::IdentityOffsetProjection
:members:
TableProjection
---------------
.. doxygenclass:: paddle::TableProjection
:members:
TransposedFullMatrixProjection
------------------------------
.. doxygenclass:: paddle::TransposedFullMatrixProjection
:members:
Aggregate Layers
================
Aggregate
---------
AverageLayer
````````````
.. doxygenclass:: paddle::AverageLayer
:members:
MaxLayer
````````
.. doxygenclass:: paddle::MaxLayer
:members:
SequenceLastInstanceLayer
`````````````````````````
.. doxygenclass:: paddle::SequenceLastInstanceLayer
:members:
Concat
------
ConcatenateLayer
````````````````
.. doxygenclass:: paddle::ConcatenateLayer
:members:
ConcatenateLayer2
`````````````````
.. doxygenclass:: paddle::ConcatenateLayer2
:members:
SequenceConcatLayer
```````````````````
.. doxygenclass:: paddle::SequenceConcatLayer
:members:
Subset
------
SubSequenceLayer
````````````````
.. doxygenclass:: paddle::SubSequenceLayer
:members:
Reshaping Layers
================
BlockExpandLayer
----------------
.. doxygenclass:: paddle::BlockExpandLayer
:members:
ExpandLayer
-----------
.. doxygenclass:: paddle::ExpandLayer
:members:
FeatureMapExpandLayer
---------------------
.. doxygenclass:: paddle::FeatureMapExpandLayer
:members:
ResizeLayer
-----------
.. doxygenclass:: paddle::ResizeLayer
:members:
SequenceReshapeLayer
--------------------
.. doxygenclass:: paddle::SequenceReshapeLayer
:members:
Math Layers
===========
AddtoLayer
----------
.. doxygenclass:: paddle::AddtoLayer
:members:
ConvexCombinationLayer
----------------------
.. doxygenclass:: paddle::ConvexCombinationLayer
:members:
InterpolationLayer
------------------
.. doxygenclass:: paddle::InterpolationLayer
:members:
MultiplexLayer
--------------
.. doxygenclass:: paddle::MultiplexLayer
:members:
OuterProdLayer
--------------
.. doxygenclass:: paddle::OuterProdLayer
:members:
PowerLayer
----------
.. doxygenclass:: paddle::PowerLayer
:members:
ScalingLayer
------------
.. doxygenclass:: paddle::ScalingLayer
:members:
SlopeInterceptLayer
-------------------
.. doxygenclass:: paddle::SlopeInterceptLayer
:members:
TensorLayer
------------
.. doxygenclass:: paddle::TensorLayer
:members:
TransLayer
----------
.. doxygenclass:: paddle::TransLayer
:members:
Sampling Layers
===============
BilinearInterpLayer
-------------------
.. doxygenclass:: paddle::BilinearInterpLayer
:members:
MultinomialSampler
------------------
.. doxygenclass:: paddle::MultinomialSampler
:members:
MaxIdLayer
----------
.. doxygenclass:: paddle::MaxIdLayer
:members:
SamplingIdLayer
---------------
.. doxygenclass:: paddle::SamplingIdLayer
:members:
Cost Layers
===========
CostLayer
-----------
.. doxygenclass:: paddle::CostLayer
:members:
HuberTwoClass
`````````````
.. doxygenclass:: paddle::HuberTwoClass
:members:
LambdaCost
```````````
.. doxygenclass:: paddle::LambdaCost
:members:
MultiBinaryLabelCrossEntropy
````````````````````````````
.. doxygenclass:: paddle::MultiBinaryLabelCrossEntropy
:members:
MultiClassCrossEntropy
```````````````````````
.. doxygenclass:: paddle::MultiClassCrossEntropy
:members:
MultiClassCrossEntropyWithSelfNorm
``````````````````````````````````
.. doxygenclass:: paddle::MultiClassCrossEntropyWithSelfNorm
:members:
RankingCost
```````````
.. doxygenclass:: paddle::RankingCost
:members:
SoftBinaryClassCrossEntropy
```````````````````````````
.. doxygenclass:: paddle::SoftBinaryClassCrossEntropy
:members:
SumOfSquaresCostLayer
`````````````````````
.. doxygenclass:: paddle::SumOfSquaresCostLayer
:members:
SumCostLayer
`````````````````````
.. doxygenclass:: paddle::SumCostLayer
:members:
CosSimLayer
-----------
.. doxygenclass:: paddle::CosSimLayer
:members:
CosSimVecMatLayer
-----------------
.. doxygenclass:: paddle::CosSimVecMatLayer
:members:
CRFDecodingLayer
----------------
.. doxygenclass:: paddle::CRFDecodingLayer
:members:
CRFLayer
--------
.. doxygenclass:: paddle::CRFLayer
:members:
CTCLayer
--------
.. doxygenclass:: paddle::CTCLayer
:members:
HierarchicalSigmoidLayer
------------------------
.. doxygenclass:: paddle::HierarchicalSigmoidLayer
:members:
LinearChainCRF
--------------
.. doxygenclass:: paddle::LinearChainCRF
:members:
LinearChainCTC
--------------
.. doxygenclass:: paddle::LinearChainCTC
:members:
NCELayer
--------
.. doxygenclass:: paddle::NCELayer
:members:
Validation Layers
-----------------
ValidationLayer
```````````````
.. doxygenclass:: paddle::ValidationLayer
:members:
AucValidation
`````````````
.. doxygenclass:: paddle::AucValidation
:members:
PnpairValidation
````````````````
.. doxygenclass:: paddle::PnpairValidation
:members:
Check Layers
============
EosIdCheckLayer
---------------
.. doxygenclass:: paddle::EosIdCheckLayer
:members:
Networks
========
NeuralNetwork
-------------
.. doxygenclass:: paddle::NeuralNetwork
:members:
ParallelNeuralNetwork
---------------------
.. doxygenclass:: paddle::ParallelNeuralNetwork
:members:
Source Code Documents
=====================
.. toctree::
:maxdepth: 1
gserver/index.rst
trainer.rst
parameter/index.rst
pserver/index.rst
api.rst
cuda/index.rst
math/index.rst
utils/index.rst
Functions
=========
MathFunctions
-------------
.. doxygenfile:: paddle/math/MathFunctions.h
SIMDFunctions
-------------
.. doxygenfile:: paddle/math/SIMDFunctions.h
Math
====
.. toctree::
:maxdepth: 2
vector.rst
matrix.rst
functions.rst
utils.rst
Matrix
======
Base
----
BaseMatrix Template
```````````````````
.. doxygenclass:: paddle::BaseMatrixT
:members:
Matrix
``````
.. doxygenclass:: paddle::Matrix
:members:
MatrixOffset
````````````
.. doxygenclass:: paddle::MatrixOffset
:members:
CpuMatrix
---------
CpuMatrix
`````````
.. doxygenclass:: paddle::CpuMatrix
:members:
SharedCpuMatrix
```````````````
.. doxygenclass:: paddle::SharedCpuMatrix
:members:
GpuMatrix
---------
.. doxygenclass:: paddle::GpuMatrix
:members:
CpuSparseMatrix
---------------
CpuSparseMatrix
```````````````
.. doxygenclass:: paddle::CpuSparseMatrix
:members:
SparseRowCpuMatrix
``````````````````
.. doxygenclass:: paddle::SparseRowCpuMatrix
:members:
SparseAutoGrowRowCpuMatrix
``````````````````````````
.. doxygenclass:: paddle::SparseAutoGrowRowCpuMatrix
:members:
SparsePrefetchRowCpuMatrix
``````````````````````````
.. doxygenclass:: paddle::SparsePrefetchRowCpuMatrix
:members:
SparseRowIdsCpuMatrix
`````````````````````
.. doxygenclass:: paddle::SparseRowIdsCpuMatrix
:members:
CacheRowCpuMatrix
`````````````````
.. doxygenclass:: paddle::CacheRowCpuMatrix
:members:
GpuSparseMatrix
---------------
.. doxygenclass:: paddle::GpuSparseMatrix
:members:
Memory Manager
==============
Memory Handle
-------------
.. doxygenfile:: paddle/math/MemoryHandle.h
Allocator
---------
.. doxygenfile:: paddle/math/Allocator.h
PoolAllocator
`````````````
.. doxygenfile:: paddle/math/PoolAllocator.h
Storage
-------
.. doxygenfile:: paddle/math/Storage.h
Vector
======
BaseVector
``````````
.. doxygenclass:: paddle::BaseVector
:members:
Vector Template
```````````````
.. doxygenclass:: paddle::VectorT
:members:
CpuVector Template
``````````````````
.. doxygenclass:: paddle::CpuVectorT
:members:
GpuVector Template
``````````````````
.. doxygenclass:: paddle::GpuVectorT
:members:
ParallelCpuVector Template
``````````````````````````
.. doxygenclass:: paddle::ParallelCpuVectorT
:members:
ParallelGpuVector Template
``````````````````````````
.. doxygenclass:: paddle::ParallelGpuVectorT
:members:
CpuGpuVector Template
`````````````````````
.. doxygenclass:: paddle::CpuGpuVectorT
:members:
Parameter
=========
.. toctree::
:maxdepth: 2
parameter.rst
optimizer.rst
updater.rst
Optimizer
=========
ParameterOptimizer
------------------
.. doxygenfile:: paddle/parameter/ParameterOptimizer.h
Regularizer
-----------
.. doxygenfile:: paddle/parameter/Regularizer.h
FirstOrderOptimizer
-------------------
.. doxygenfile:: paddle/parameter/FirstOrderOptimizer.h
AverageOptimizer
----------------
.. doxygenfile:: paddle/parameter/AverageOptimizer.h
OptimizerWithRegularizer
------------------------
.. doxygenfile:: paddle/parameter/OptimizerWithRegularizer.h
Parameter
=========
Parameter
---------
.. doxygenfile:: paddle/parameter/Argument.h
.. doxygenfile:: paddle/parameter/Parameter.h
.. doxygenfile:: paddle/parameter/ParallelParameter.h
Weight
------
.. doxygenfile:: paddle/parameter/Weight.h
Updater
=======
Base
----
.. doxygenfile:: paddle/parameter/ParameterUpdaterBase.h
Hook
----
.. doxygenfile:: paddle/parameter/ParameterUpdaterHook.h
Functions
---------
.. doxygenfile:: paddle/parameter/ParameterUpdateFunctions.h
Client
======
BaseClient
----------
.. doxygenclass:: paddle::BaseClient
:members:
ParameterClient2
----------------
.. doxygenclass:: paddle::ParameterClient2
:members:
PServer
=======
.. toctree::
:maxdepth: 2
client.rst
network.rst
server.rst
utils.rst
Network
=======
SocketServer
------------
.. doxygenclass:: paddle::SocketServer
:members:
SocketWorker
------------
.. doxygenclass:: paddle::SocketWorker
:members:
SocketClient
------------
.. doxygenclass:: paddle::SocketClient
:members:
SocketChannel
-------------
.. doxygenclass:: paddle::SocketChannel
:members:
MessageReader
-------------
.. doxygenclass:: paddle::MsgReader
:members:
Server
======
ProtoServer
-----------
.. doxygenclass:: paddle::ProtoServer
:members:
ParameterServer2
----------------
.. doxygenclass:: paddle::ParameterServer2
:members:
Trainer
=======
TrainerStats
------------
.. doxygenclass:: paddle::TrainerStats
:members:
RemoteParameterUpdater
-----------------------
.. doxygenclass:: paddle::RemoteParameterUpdater
:members:
ConcurrentRemoteParameterUpdater
--------------------------------
.. doxygenclass:: paddle::ConcurrentRemoteParameterUpdater
:members:
SparseRemoteParameterUpdater
----------------------------
.. doxygenclass:: paddle::SparseRemoteParameterUpdater
:members:
SparseRemoteParameterUpdaterComposite
-------------------------------------
.. doxygenclass:: paddle::SparseRemoteParameterUpdaterComposite
:members:
CustomStackTrace
================
.. doxygenclass:: paddle::CustomStackTrace
:members:
Enumeration wrapper
===================
.. doxygennamespace:: paddle::enumeration_wrapper
Utils
=====
.. toctree::
:maxdepth: 2
lock.rst
queue.rst
thread.rst
customStackTrace.rst
enum.rst
Lock
====
RWLock
------
.. doxygenclass:: paddle::RWLock
:members:
ReadLockGuard
-------------
.. doxygenclass:: paddle::ReadLockGuard
:members:
SpinLock
--------
.. doxygenclass:: paddle::SpinLock
:members:
Semaphore
---------
.. doxygenclass:: paddle::Semaphore
:members:
ThreadBarrier
-------------
.. doxygenclass:: paddle::ThreadBarrier
:members:
LockedCondition
---------------
.. doxygenclass:: paddle::LockedCondition
:members:
Queue
=====
Queue
-----
.. doxygenclass:: paddle::Queue
:members:
BlockingQueue
-------------
.. doxygenclass:: paddle::BlockingQueue
:members:
Thread
======
Thread
------
.. doxygenclass:: paddle::Thread
:members:
ThreadWorker
------------
.. doxygenclass:: paddle::ThreadWorker
:members:
SyncThreadPool
--------------
.. doxygenclass:: paddle::SyncThreadPool
:members:
MultiThreadWorker
-----------------
.. doxygenclass:: paddle::MultiThreadWorker
:members:
AsyncThreadPool
---------------
.. doxygenclass:: paddle::AsyncThreadPool
:members:
...@@ -12,7 +12,7 @@ This tutorial will teach the basics of deep learning (DL), including how to impl ...@@ -12,7 +12,7 @@ This tutorial will teach the basics of deep learning (DL), including how to impl
To get started, please install PaddlePaddle on your computer. Throughout this tutorial, you will learn by implementing different DL models for text classification. To get started, please install PaddlePaddle on your computer. Throughout this tutorial, you will learn by implementing different DL models for text classification.
To install PaddlePaddle, please follow the instructions here: <a href = "../../build/index.html" >Build and Install</a>. To install PaddlePaddle, please follow the instructions here: <a href = "../../getstarted/build_and_install/index_en.html" >Build and Install</a>.
## Overview ## Overview
For the first step, you will use PaddlePaddle to build a **text classification** system. For example, suppose you run an e-commence website, and you want to analyze the sentiment of user reviews to evaluate product quality. For the first step, you will use PaddlePaddle to build a **text classification** system. For example, suppose you run an e-commence website, and you want to analyze the sentiment of user reviews to evaluate product quality.
...@@ -156,14 +156,14 @@ define_py_data_sources2(train_list='data/train.list', ...@@ -156,14 +156,14 @@ define_py_data_sources2(train_list='data/train.list',
obj="process", obj="process",
args={"dictionary": word_dict}) args={"dictionary": word_dict})
``` ```
You can refer to the following link for more detailed examples and data formats: <a href = "../../ui/data_provider/pydataprovider2.html">PyDataProvider2</a>. You can refer to the following link for more detailed examples and data formats: <a href = "../../api/data_provider/pydataprovider2_en.html">PyDataProvider2</a>.
## Network Architecture ## Network Architecture
You will describe four kinds of network architectures in this section. You will describe four kinds of network architectures in this section.
<center> ![](./PipelineNetwork_en.jpg) </center> <center> ![](./PipelineNetwork_en.jpg) </center>
First, you will build a logistic regression model. Later, you will also get chance to build other more powerful network architectures. First, you will build a logistic regression model. Later, you will also get chance to build other more powerful network architectures.
For more detailed documentation, you could refer to: <a href = "../../ui/api/trainer_config_helpers/layers_index.html">Layer documentation</a>All configuration files are in `demo/quick_start` directory. For more detailed documentation, you could refer to: <a href = "../../api/trainer_config_helpers/layers.html">layer documentation</a>. All configuration files are in `demo/quick_start` directory.
### Logistic Regression ### Logistic Regression
The architecture is illustrated in the following picture: The architecture is illustrated in the following picture:
...@@ -366,7 +366,7 @@ You can use single layer LSTM model with Dropout for our text classification pro ...@@ -366,7 +366,7 @@ You can use single layer LSTM model with Dropout for our text classification pro
<br> <br>
## Optimization Algorithm ## Optimization Algorithm
<a href = "../../ui/api/trainer_config_helpers/optimizers.html">Optimization algorithms</a> include Momentum, RMSProp, AdaDelta, AdaGrad, Adam, and Adamax. You can use Adam optimization method here, with L2 regularization and gradient clipping, because Adam has been proved to work very well for training recurrent neural network. <a href = "../../api/trainer_config_helpers/optimizers.html">Optimization algorithms</a> include Momentum, RMSProp, AdaDelta, AdaGrad, Adam, and Adamax. You can use Adam optimization method here, with L2 regularization and gradient clipping, because Adam has been proved to work very well for training recurrent neural network.
```python ```python
settings(batch_size=128, settings(batch_size=128,
...@@ -391,7 +391,8 @@ paddle train \ ...@@ -391,7 +391,8 @@ paddle train \
--use_gpu=false --use_gpu=false
``` ```
If you want to install the remote training platform, which enables distributed training on clusters, follow the instructions here: <a href = "../../cluster/index.html">Platform</a> documentation. We do not provide examples on how to train on clusters. Please refer to other demos or platform training documentation for mode details on training on clusters. We do not provide examples on how to train on clusters here. If you want to train on clusters, please follow the <a href = "../../howto/cluster/cluster_train_en.html">distributed training</a> documentation or other demos for more details.
## Inference ## Inference
You can use the trained model to perform prediction on the dataset with no labels. You can also evaluate the model on dataset with labels to obtain its test accuracy. You can use the trained model to perform prediction on the dataset with no labels. You can also evaluate the model on dataset with labels to obtain its test accuracy.
<center> ![](./PipelineTest_en.png) </center> <center> ![](./PipelineTest_en.png) </center>
...@@ -406,7 +407,7 @@ paddle train \ ...@@ -406,7 +407,7 @@ paddle train \
--init_model_path=./output/pass-0000x --init_model_path=./output/pass-0000x
``` ```
We will give an example of performing prediction using Recurrent model on a dataset with no labels. You can refer to: <a href = "../../ui/predict/swig_py_paddle_en.html">Python Prediction API</a> tutorial,or other <a href = "../../demo/index.html">demo</a> for the prediction process using Python. You can also use the following script for inference or evaluation. We will give an example of performing prediction using Recurrent model on a dataset with no labels. You can refer to <a href = "../../api/predict/swig_py_paddle_en.html">Python Prediction API</a> tutorial,or other <a href = "../../tutorials/index_en.html">demo</a> for the prediction process using Python. You can also use the following script for inference or evaluation.
inference script (predict.sh): inference script (predict.sh):
...@@ -508,7 +509,7 @@ The scripts of data downloading, network configurations, and training scrips are ...@@ -508,7 +509,7 @@ The scripts of data downloading, network configurations, and training scrips are
* \--config_args:Other configuration arguments. * \--config_args:Other configuration arguments.
* \--init_model_path:The path of the initial model parameter. * \--init_model_path:The path of the initial model parameter.
By default, the trainer will save model every pass. You can also specify `saving_period_by_batches` to set the frequency of batch saving. You can use `show_parameter_stats_period` to print the statistics of the parameters, which are very useful for tuning parameters. Other command line arguments can be found in <a href = "../../ui/index.html#command-line-argument">command line argument documentation</a> By default, the trainer will save model every pass. You can also specify `saving_period_by_batches` to set the frequency of batch saving. You can use `show_parameter_stats_period` to print the statistics of the parameters, which are very useful for tuning parameters. Other command line arguments can be found in <a href = "../../howto/cmd_parameter/index_en.html">command line argument documentation</a>
### Log ### Log
......
```eval_rst
.. _demo_ml_dataset_en:
```
# MovieLens Dataset # MovieLens Dataset
The [MovieLens Dataset](http://grouplens.org/datasets/movielens/) was collected by GroupLens Research. The [MovieLens Dataset](http://grouplens.org/datasets/movielens/) was collected by GroupLens Research.
......
...@@ -16,7 +16,7 @@ Data Preparation ...@@ -16,7 +16,7 @@ Data Preparation
```````````````` ````````````````
Download and extract dataset Download and extract dataset
'''''''''''''''''''''''''''' ''''''''''''''''''''''''''''
We use `movielens 1m dataset <ml_dataset.html>`_ here. We use :ref:`demo_ml_dataset_en` here.
To download and unzip the dataset, simply run the following commands. To download and unzip the dataset, simply run the following commands.
.. code-block:: bash .. code-block:: bash
...@@ -239,26 +239,16 @@ Then we combine each features of movie into one movie feature by a ...@@ -239,26 +239,16 @@ Then we combine each features of movie into one movie feature by a
get one user feature. Then we calculate the cosine similarity of these two get one user feature. Then we calculate the cosine similarity of these two
features. features.
In these network, we use several api in `trainer_config_helpers In these network, we use several api in :ref:`api_trainer_config` . There are
<../../ui/api/trainer_config_helpers/index.html>`_. There are
* Data Layer, :ref:`api_trainer_config_helpers_layers_data_layer`
* Data Layer, `data_layer * Fully Connected Layer, :ref:`api_trainer_config_helpers_layers_fc_layer`
<../../ui/api/trainer_config_helpers/layers.html#id1>`_ * Embedding Layer, :ref:`api_trainer_config_helpers_layers_embedding_layer`
* Fully Connected Layer, `fc_layer * Context Projection Layer, :ref:`api_trainer_config_helpers_layers_context_projection`
<../../ui/api/trainer_config_helpers/layers.html#fc-layer>`_ * Pooling Layer, :ref:`api_trainer_config_helpers_layers_pooling_layer`
* Embedding Layer, `embedding_layer * Cosine Similarity Layer, :ref:`api_trainer_config_helpers_layers_cos_sim`
<../../ui/api/trainer_config_helpers/layers.html#embedding-layer>`_ * Text Convolution Pooling Layer, :ref:`api_trainer_config_helpers_network_text_conv_pool`
* Context Projection Layer, `context_projection * Declare Python Data Sources :ref:`api_trainer_config_helpers_data_sources`.
<../../ui/api/trainer_config_helpers/layers.html#context-projection>`_
* Pooling Layer, `pooling_layer
<../../ui/api/trainer_config_helpers/layers.html#pooling-layer>`_
* Cosine Similarity Layer, `cos_sim
<../../ui/api/trainer_config_helpers/layers.html#cos-sim>`_
* Text Convolution Pooling Layer, `text_conv_pool
<../../ui/api/trainer_config_helpers/networks.html
#trainer_config_helpers.networks.text_conv_pool>`_
* Declare Python Data Sources, `define_py_data_sources2
<../../ui/api/trainer_config_helpers/data_sources.html>`_
Data Provider Data Provider
''''''''''''' '''''''''''''
...@@ -274,7 +264,7 @@ In this :code:`dataprovider.py`, we should set\: ...@@ -274,7 +264,7 @@ In this :code:`dataprovider.py`, we should set\:
* use_seq\: Whether this :code:`dataprovider.py` in sequence mode or not. * use_seq\: Whether this :code:`dataprovider.py` in sequence mode or not.
* process\: Return each sample of data to :code:`paddle`. * process\: Return each sample of data to :code:`paddle`.
The data provider details document see `there <../../ui/data_provider/pydataprovider2.html>`_. The data provider details document see :ref:`api_pydataprovider`.
Train Train
````` `````
...@@ -290,8 +280,7 @@ The run.sh is shown as follow: ...@@ -290,8 +280,7 @@ The run.sh is shown as follow:
It just start a paddle training process, write the log to `log.txt`, It just start a paddle training process, write the log to `log.txt`,
then print it on screen. then print it on screen.
Each command line argument in :code:`run.sh`, please refer to the `command line Each command line argument in :code:`run.sh`, please refer to the :ref:`cmd_line_index_en` page. The short description of these arguments is shown as follow.
arguments <../../ui/index.html#command-line-argument>`_ page. The short description of these arguments is shown as follow.
* config\: Tell paddle which file is neural network configuration. * config\: Tell paddle which file is neural network configuration.
* save_dir\: Tell paddle save model into './output' * save_dir\: Tell paddle save model into './output'
......
# 语义角色标注教程 #
语义角色标注(Semantic role labeling, SRL)是浅层语义解析的一种形式,其目的是在给定的输入句子中发现每个谓词的谓词论元结构。 SRL作为很多自然语言处理任务中的中间步骤是很有用的,如信息提取、文档自动分类和问答。 实例如下 [1]:
[ <sub>A0</sub> He ] [ <sub>AM-MOD</sub> would ][ <sub>AM-NEG</sub> n’t ] [ <sub>V</sub> accept] [ <sub>A1</sub> anything of value ] from [<sub>A2</sub> those he was writing about ].
- V: 动词
- A0: 接受者
- A1: 接受的东西
- A2: 从……接受
- A3: 属性
- AM-MOD: 情态动词
- AM-NEG: 否定
给定动词“accept”,句子中的组块将会扮演某些语义角色。这里,标签方案来自 Penn Proposition Bank。
到目前为止,大多数成功的SRL系统是建立在某种形式的句法分析结果之上的,使用了基于句法结构的预定义特征模板。 本教程将介绍使用深度双向长短期记忆(DB-LSTM)模型[2]的端到端系统来解决SRL任务,这在很大程度上优于先前的最先进的系统。 这个系统将SRL任务视为序列标注问题。
## 数据描述
相关论文[2]采用 CoNLL-2005&2012 共享任务中设置的数据进行训练和测试。由于数据许可的原因,演示采用 CoNLL-2005 的测试数据集,可以在网站上找到。
用户只需执行以下命令就可以下载并处理原始数据:
```bash
cd data
./get_data.sh
```
`data `目录会出现如下几个新的文件:
```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
```
## 训练
### DB-LSTM
请参阅情感分析的演示以了解有关长期短期记忆单元的更多信息。
与在 Sentiment Analysis 演示中使用的 Bidirectional-LSTM 不同,DB-LSTM 采用另一种方法来堆叠LSTM层。首先,标准LSTM以正向处理该序列。该 LSTM 层的输入和输出作为下一个 LSTM 层的输入,并被反向处理。这两个标准 LSTM 层组成一对 LSTM。然后我们堆叠一对对的 LSTM 层后得到深度 LSTM 模型。
下图展示了时间扩展的2层 DB-LSTM 网络。
<center>
![pic](./network_arch.png)
</center>
### 特征
两个输入特征在这个流程中起着至关重要的作用:predicate(pred)和argument(arguments)。 还采用了两个其他特征:谓词上下文(ctx-p)和区域标记(mr)。 因为单个谓词不能精确地描述谓词信息,特别是当相同的词在句子中出现多于一次时。 使用谓词上下文,可以在很大程度上消除歧义。类似地,如果它位于谓词上下文区域中,则使用区域标记 m<sub>r</sub> = 1 来表示参数位置,反之则 m<sub>r</sub> = 0。这四个简单的特征是我们的SRL系统所需要的。上下文大小设置为1的一个样本的特征如下[2]所示:
<center>
![pic](./feature.jpg)
</center>
在这个示例中,相应的标记句子是:
[ <sub>A1</sub> A record date ] has [ <sub>AM-NEG</sub> n't ] been [ <sub>V</sub> set ] .
在演示中, 我们采用上面的特征模板, 包括: `argument`, `predicate`, `ctx-p (p=-1,0,1)`, `mark` 并使用 `B/I/O` 方案来标记每个参数。这些特征和标签存储在 `feature` 文件中, 用`\t`分割。
### 数据提供
`dataprovider.py` 是一个包装数据的 Python 文件。 函数 `hook()` 定义了网络的数据槽。六个特征和标签都是索引槽。
```
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))]
```
相应的数据迭代器如下:
```
@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
```
函数 `process` 返回8个特征list和1个标签list。
### 神经网络配置
`db_lstm.py` 是在训练过程中加载字典并定义数据提供程序模块和网络架构的神经网络配置文件。
九个 `data_layer` 从数据提供程序加载实例。八个特征分别转换为向量,并由`mixed_layer`混合。 深度双向LSTM层提取softmax层的特征。目标函数是标签的交叉熵。
### 训练
训练的脚本是 `train.sh`,用户只需执行:
```bash
./train.sh
```
`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 : 网络配置文件
- \--use_gpu=false: 使用 CPU 训练(如果已安装 PaddlePaddle GPU版本并想使用 GPU 训练可以设置为true,目前 crf_layer 不支持 GPU)
- \--log_period=500: 每20个batch输出日志
- \--trainer_count=1: 设置线程数(或 GPU 数)
- \--show_parameter_stats_period=5000: 每100个batch显示参数统计
- \--save_dir=./output: 模型输出路径
- \--num_passes=10000: 设置数据遍历次数,一个pass意味着PaddlePaddle训练数据集中的所有样本被遍历一次
- \--average_test_period=10000000: 每个 average_test_period 批次对平均参数进行测试
- \--init_model_path=./data: 参数初始化路径
- \--load_missing_parameter_strategy=rand: 随机初始不存在的参数
- \--test_all_data_in_one_period=1: 在一个周期内测试所有数据
训练后,模型将保存在目录`output`中。 我们的训练曲线如下:
<center>
![pic](./curve.jpg)
</center>
### 测试
测试脚本是 `test.sh`, 执行:
```bash
./test.sh
```
`tesh.sh` 的主要部分:
```
paddle train \
--config=./db_lstm.py \
--model_list=$model_list \
--job=test \
--config_args=is_test=1 \
```
- \--config=./db_lstm.py: 网络配置文件
- \--model_list=$model_list.list: 模型列表文件
- \--job=test: 指示测试任务
- \--config_args=is_test=1: 指示测试任务的标记
- \--test_all_data_in_one_period=1: 在一个周期内测试所有数据
### 预测
预测脚本是 `predict.sh`,用户只需执行:
```bash
./predict.sh
```
`predict.sh`中,用户应该提供网络配置文件,模型路径,标签文件,字典文件,特征文件。
```
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` 是主要的可执行python脚本,其中包括函数:加载模型,加载数据,数据预测。网络模型将输出标签的概率分布。 在演示中,我们使用最大概率的标签作为结果。用户还可以根据概率分布矩阵实现柱搜索或维特比解码。
预测后,结果保存在 `predict.res` 中。
## 引用
[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, SRL)是浅语义解析的一种形式,其目的是在给定的输入句子中发现每个谓词的谓词参数结构。 SRL作为很多自然语言处理任务中的中间步骤是很有用的,如信息提取、文档自动分类和问答。 实例如下 [1]:
[ <sub>A0</sub> 他 ] [ <sub>AM-MOD</sub> 将 ][ <sub>AM-NEG</sub> 不会 ] [ <sub>V</sub> 接受] [ <sub>A1</sub> 任何东西 ] 从 [<sub>A2</sub> 那些他写的东西中 ]。
- V: 动词
- A0: 接受者
- A1: 接受的东西
- A2: 从……接受
- A3: 属性
- AM-MOD: 情态动词
- AM-NEG: 否定
给定动词“接受”,句子中的大部分将会扮演某些语义角色。这里,标签方案来自 Penn Proposition Bank。
到目前为止,大多数成功的SRL系统是建立在某种形式的解析结果之上的,其中在语法结构上使用了预先定义的特征模板。 本教程将介绍使用深度双向长短期记忆(DB-LSTM)模型[2]的端到端系统来解决SRL任务,这在很大程度上优于先前的最先进的系统。 这个系统将SRL任务视为序列标记问题。
## 数据描述
相关论文[2]采用 CoNLL-2005&2012 共享任务中设置的数据进行训练和测试。根据数据许可证,演示采用 CoNLL-2005 的测试数据集,可以在网站上找到。
用户只需执行以下命令就可以下载并处理原始数据:
```bash
cd data
./get_data.sh
```
`data `目录会出现如下几个新的文件:
```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
```
## 训练
### DB-LSTM
请参阅情绪分析的演示以了解有关长期短期记忆单元的更多信息。
与在 Sentiment Analysis 演示中使用的 Bidirectional-LSTM 不同,DB-LSTM 采用另一种方法来堆叠LSTM层。首先,标准LSTM以正向处理该序列。该 LSTM 层的输入和输出作为下一个 LSTM 层的输入,并被反向处理。这两个标准 LSTM 层组成一对 LSTM。然后我们堆叠一对对的 LSTM 层后得到深度 LSTM 模型。
下图展示了时间扩展的2层 DB-LSTM 网络。
<center>
![pic](./network_arch.png)
</center>
### 特征
两个输入特性在这个管道中起着至关重要的作用:predicate(pred)和argument(arguments)。 还采用了两个其他特征:谓词上下文(ctx-p)和区域标记(mr)。 因为单个谓词不能精确地描述谓词信息,特别是当相同的词在句子中出现多于一次时。 使用谓词上下文,可以在很大程度上消除歧义。类似地,如果它位于谓词上下文区域中,则使用区域标记 m<sub>r</sub> = 1 来表示参数位置,反之则 m<sub>r</sub> = 0。这四个简单的特征是我们的SRL系统所需要的。上下文大小设置为1的一个样本的特征如下[2]所示:
<center>
![pic](./feature.jpg)
</center>
在这个示例中,相应的标记句子是:
[ <sub>A1</sub> A record date ] has [ <sub>AM-NEG</sub> n't ] been [ <sub>V</sub> set ] .
在演示中, 我们采用上面的特征模板, 包括: `argument`, `predicate`, `ctx-p (p=-1,0,1)`, `mark` 并使用 `B/I/O` 方案来标记每个参数。这些特征和标签存储在 `feature` 文件中, 用`\t`分割。
### 数据提供
`dataprovider.py` 是一个包装数据的 Python 文件。 函数 `hook()` 定义了网络的数据槽。六个特征和标签都是索引槽。
```
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))]
```
相应的数据迭代器如下:
```
@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
```
函数 `process` 产出有8个特征和标签的9个表。
### 神经网络配置
`db_lstm.py` 是在训练过程中加载字典并定义数据提供程序模块和网络架构的神经网络配置文件。
九个 `data_layer` 从数据提供程序加载实例。八个特征分别转换为嵌入,并由`mixed_layer`混合。 深度双向LSTM层提取softmax层的特征。目标函数是标签的交叉熵。
### 训练
训练的脚本是 `train.sh`,用户只需执行:
```bash
./train.sh
```
`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 : 网络配置文件
- \--use_gpu=false: 使用 CPU 训练(如果已安装 PaddlePaddle GPU版本并想使用 GPU 训练可以设置为true,目前 crf_layer 不支持 GPU)
- \--log_period=500: 每20批(batch)输出日志
- \--trainer_count=1: 设置线程数(或 GPU 数)
- \--show_parameter_stats_period=5000: 每100批显示参数统计
- \--save_dir=./output: 模型输出路径
- \--num_passes=10000: 设置通过数,一次通过意味着PaddlePaddle训练数据集中的所有样本一次
- \--average_test_period=10000000: 每个 average_test_period 批次对平均参数进行测试
- \--init_model_path=./data: 参数初始化路径
- \--load_missing_parameter_strategy=rand: 随机初始不存在的参数
- \--test_all_data_in_one_period=1: 在一个周期内测试所有数据
训练后,模型将保存在目录`output`中。 我们的训练曲线如下:
<center>
![pic](./curve.jpg)
</center>
### 测试
测试脚本是 `test.sh`, 执行:
```bash
./test.sh
```
`tesh.sh` 的主要部分:
```
paddle train \
--config=./db_lstm.py \
--model_list=$model_list \
--job=test \
--config_args=is_test=1 \
```
- \--config=./db_lstm.py: 网络配置文件
- \--model_list=$model_list.list: 模型列表文件
- \--job=test: 指示测试任务
- \--config_args=is_test=1: 指示测试任务的标记
- \--test_all_data_in_one_period=1: 在一个周期内测试所有数据
### 预测
预测脚本是 `predict.sh`,用户只需执行:
```bash
./predict.sh
```
`predict.sh`中,用户应该提供网络配置文件,模型路径,标签文件,字典文件,特征文件。
```
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` 是主要的可执行python脚本,其中包括函数:加载模型,加载数据,数据预测。网络模型将输出标签的概率分布。 在演示中,我们使用最大概率的标签作为结果。用户还可以根据概率分布矩阵实现集束搜索或维特比解码。
预测后,结果保存在 `predict.res` 中。
## 引用
[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.
...@@ -293,20 +293,21 @@ predict.sh: ...@@ -293,20 +293,21 @@ predict.sh:
model=model_output/pass-00002/ model=model_output/pass-00002/
config=trainer_config.py config=trainer_config.py
label=data/pre-imdb/labels.list label=data/pre-imdb/labels.list
python predict.py \ cat ./data/aclImdb/test/pos/10007_10.txt | python predict.py \
-n $config\ --tconf=$config\
-w $model \ --model=$model \
-b $label \ --label=$label \
-d data/pre-imdb/dict.txt \ --dict=./data/pre-imdb/dict.txt \
-i data/aclImdb/test/pos/10007_10.txt --batch_size=1
``` ```
* `predict.py`: predicting interface. * `cat ./data/aclImdb/test/pos/10007_10.txt` : the input sample.
* -n $config : set network configure. * `predict.py` : predicting interface.
* -w $model: set model path. * `--tconf=$config` : set network configure.
* -b $label: set dictionary about corresponding relation between integer label and string label. * ` --model=$model` : set model path.
* -d data/pre-imdb/dict.txt: set dictionary. * `--label=$label` : set dictionary about corresponding relation between integer label and string label.
* -i data/aclImdb/test/pos/10014_7.txt: set one example file to predict. * `--dict=data/pre-imdb/dict.txt` : set dictionary.
* `--batch_size=1` : set batch size.
Note you should make sure the default model path `model_output/pass-00002` Note you should make sure the default model path `model_output/pass-00002`
exists or change the model path. exists or change the model path.
......
...@@ -291,20 +291,21 @@ predict.sh: ...@@ -291,20 +291,21 @@ predict.sh:
model=model_output/pass-00002/ model=model_output/pass-00002/
config=trainer_config.py config=trainer_config.py
label=data/pre-imdb/labels.list label=data/pre-imdb/labels.list
python predict.py \ cat ./data/aclImdb/test/pos/10007_10.txt | python predict.py \
-n $config\ --tconf=$config\
-w $model \ --model=$model \
-b $label \ --label=$label \
-d data/pre-imdb/dict.txt \ --dict=./data/pre-imdb/dict.txt \
-i data/aclImdb/test/pos/10007_10.txt --batch_size=1
``` ```
* `predict.py`: 预测接口脚本。 * `cat ./data/aclImdb/test/pos/10007_10.txt` : 输入预测样本。
* -n $config : 设置网络配置。 * `predict.py` : 预测接口脚本。
* -w $model: 设置模型路径。 * `--tconf=$config` : 设置网络配置。
* -b $label: 设置标签类别字典,这个字典是整数标签和字符串标签的一个对应。 * `--model=$model` : 设置模型路径。
* -d data/pre-imdb/dict.txt: 设置字典文件。 * `--label=$label` : 设置标签类别字典,这个字典是整数标签和字符串标签的一个对应。
* -i data/aclImdb/test/pos/10014_7.txt: 设置一个要预测的示例文件。 * `--dict=data/pre-imdb/dict.txt` : 设置字典文件。
* `--batch_size=1` : 设置batch size。
注意应该确保默认模型路径`model_output / pass-00002`存在或更改为其它模型路径。 注意应该确保默认模型路径`model_output / pass-00002`存在或更改为其它模型路径。
......
FROM ubuntu:14.04 FROM ubuntu:14.04
MAINTAINER PaddlePaddle Authors <paddle-dev@baidu.com> MAINTAINER PaddlePaddle Authors <paddle-dev@baidu.com>
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update \ RUN apt-get update \
&& apt-get install -y cmake libprotobuf-dev protobuf-compiler git \ && apt-get install -y cmake libprotobuf-dev protobuf-compiler git \
libgoogle-glog-dev libgflags-dev libatlas-dev libatlas3-base g++ m4 python-pip \ libgoogle-glog-dev libgflags-dev libgtest-dev \
libatlas-dev libatlas3-base g++ m4 python-pip \
python-protobuf python-numpy python-dev swig openssh-server \ python-protobuf python-numpy python-dev swig openssh-server \
wget unzip python-matplotlib tar xz-utils bzip2 gzip coreutils \ wget unzip python-matplotlib tar xz-utils bzip2 gzip coreutils \
sed grep graphviz libjpeg-dev zlib1g-dev doxygen \ sed grep graphviz libjpeg-dev zlib1g-dev doxygen \
clang-3.8 llvm-3.8 libclang-3.8-dev \ clang-3.8 llvm-3.8 libclang-3.8-dev \
&& apt-get clean -y && apt-get clean -y
RUN cd /usr/src/gtest && cmake . && make && cp *.a /usr/lib
RUN pip install -U BeautifulSoup docopt PyYAML pillow \ RUN pip install -U BeautifulSoup docopt PyYAML pillow \
sphinx sphinx_rtd_theme breathe recommonmark sphinx sphinx_rtd_theme recommonmark
# cmake tends to hide and blur the dependencies between code modules, as
# noted here https://github.com/PaddlePaddle/Paddle/issues/763. We are
# thinking about using Bazel to fix this problem, e.g.,
# https://github.com/PaddlePaddle/Paddle/issues/681#issuecomment-263996102. To
# start the trail of fixing, we add Bazel to our Dockerfiles.
RUN apt-get update && apt-get install -y curl software-properties-common \
&& add-apt-repository ppa:webupd8team/java \
&& echo "oracle-java8-installer shared/accepted-oracle-license-v1-1 select true" | debconf-set-selections \
&& echo "deb [arch=amd64] http://storage.googleapis.com/bazel-apt stable jdk1.8" | tee /etc/apt/sources.list.d/bazel.list \
&& curl https://bazel.build/bazel-release.pub.gpg | apt-key add - \
&& apt-get update && apt-get install -y oracle-java8-installer bazel
ARG WITH_AVX ARG WITH_AVX
ARG WITH_DOC ARG WITH_DOC
......
FROM nvidia/cuda:7.5-cudnn5-devel-ubuntu14.04 FROM nvidia/cuda:7.5-cudnn5-devel-ubuntu14.04
MAINTAINER PaddlePaddle Authors <paddle-dev@baidu.com> MAINTAINER PaddlePaddle Authors <paddle-dev@baidu.com>
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update \ RUN apt-get update \
&& apt-get install -y cmake libprotobuf-dev protobuf-compiler git \ && apt-get install -y cmake libprotobuf-dev protobuf-compiler git \
libgoogle-glog-dev libgflags-dev libatlas-dev libatlas3-base g++ m4 python-pip \ libgoogle-glog-dev libgflags-dev libgtest-dev \
libatlas-dev libatlas3-base g++ m4 python-pip \
python-protobuf python-numpy python-dev swig openssh-server \ python-protobuf python-numpy python-dev swig openssh-server \
wget unzip python-matplotlib tar xz-utils bzip2 gzip coreutils \ wget unzip python-matplotlib tar xz-utils bzip2 gzip coreutils \
sed grep graphviz libjpeg-dev zlib1g-dev doxygen \ sed grep graphviz libjpeg-dev zlib1g-dev doxygen \
clang-3.8 llvm-3.8 libclang-3.8-dev \ clang-3.8 llvm-3.8 libclang-3.8-dev \
&& apt-get clean -y && apt-get clean -y
RUN cd /usr/src/gtest && cmake . && make && cp *.a /usr/lib
RUN pip install -U BeautifulSoup docopt PyYAML pillow \ RUN pip install -U BeautifulSoup docopt PyYAML pillow \
sphinx sphinx_rtd_theme breathe recommonmark sphinx sphinx_rtd_theme recommonmark
# cmake tends to hide and blur the dependencies between code modules, as
# noted here https://github.com/PaddlePaddle/Paddle/issues/763. We are
# thinking about using Bazel to fix this problem, e.g.,
# https://github.com/PaddlePaddle/Paddle/issues/681#issuecomment-263996102. To
# start the trail of fixing, we add Bazel to our Dockerfiles.
RUN apt-get update && apt-get install -y curl software-properties-common \
&& add-apt-repository ppa:webupd8team/java \
&& echo "oracle-java8-installer shared/accepted-oracle-license-v1-1 select true" | debconf-set-selections \
&& echo "deb [arch=amd64] http://storage.googleapis.com/bazel-apt stable jdk1.8" | tee /etc/apt/sources.list.d/bazel.list \
&& curl https://bazel.build/bazel-release.pub.gpg | apt-key add - \
&& apt-get update && apt-get install -y oracle-java8-installer bazel
ARG WITH_AVX ARG WITH_AVX
ARG WITH_DOC ARG WITH_DOC
......
...@@ -3,5 +3,5 @@ COPY build.sh / ...@@ -3,5 +3,5 @@ COPY build.sh /
RUN pip install sphinx &&\ RUN pip install sphinx &&\
pip install sphinx_rtd_theme &&\ pip install sphinx_rtd_theme &&\
apt install -y doxygen graphviz &&\ apt install -y doxygen graphviz &&\
pip install breathe recommonmark numpy protobuf==2.6.1 pip install recommonmark numpy protobuf==2.6.1
CMD /build.sh CMD /build.sh
...@@ -47,17 +47,20 @@ if [ $? -eq 0 ]; then ...@@ -47,17 +47,20 @@ if [ $? -eq 0 ]; then
fi fi
set -e set -e
# Commit if [ -n $SSL_KEY ]; then # Only push updated docs for github.com/PaddlePaddle/Paddle.
git add . # Commit
git config user.name "Travis CI" git add .
git config user.email "paddle-dev@baidu.com" git config user.name "Travis CI"
git commit -m "Deploy to GitHub Pages: ${SHA}" git config user.email "paddle-dev@baidu.com"
git commit -m "Deploy to GitHub Pages: ${SHA}"
# Set ssh private key
openssl aes-256-cbc -K $SSL_KEY -iv $SSL_IV -in ../../paddle/scripts/travis/deploy_key.enc -out deploy_key -d # Set ssh private key
chmod 600 deploy_key openssl aes-256-cbc -K $SSL_KEY -iv $SSL_IV -in ../../paddle/scripts/travis/deploy_key.enc -out deploy_key -d
eval `ssh-agent -s` chmod 600 deploy_key
ssh-add deploy_key eval `ssh-agent -s`
ssh-add deploy_key
# Push
git push $SSH_REPO $TARGET_BRANCH # Push
git push $SSH_REPO $TARGET_BRANCH
fi
...@@ -3364,6 +3364,14 @@ def my_fatal(s): ...@@ -3364,6 +3364,14 @@ def my_fatal(s):
logger.critical(s) logger.critical(s)
raise Exception() raise Exception()
_parse_config_hooks = set()
def register_parse_config_hook(f):
"""
Register a hook function for parse_config. parse_config will invoke the hook
at the beginning of parse. This make it possible to reset global state for
for constructing the model.
"""
_parse_config_hooks.add(f)
def parse_config(config_file, config_arg_str): def parse_config(config_file, config_arg_str):
''' '''
...@@ -3371,6 +3379,8 @@ def parse_config(config_file, config_arg_str): ...@@ -3371,6 +3379,8 @@ def parse_config(config_file, config_arg_str):
passed to config script as a dictionary CONFIG_ARGS passed to config script as a dictionary CONFIG_ARGS
''' '''
init_config_environment() init_config_environment()
for hook in _parse_config_hooks:
hook()
config_args = {} config_args = {}
......
...@@ -78,6 +78,17 @@ class DefaultNameFactory(object): ...@@ -78,6 +78,17 @@ class DefaultNameFactory(object):
""" """
pass pass
def reset(self):
self.__counter__ = 0
_name_factories = []
def reset_hook():
for factory in _name_factories:
factory.reset()
register_parse_config_hook(reset_hook)
def wrap_name_default(name_prefix=None): def wrap_name_default(name_prefix=None):
""" """
...@@ -95,7 +106,9 @@ def wrap_name_default(name_prefix=None): ...@@ -95,7 +106,9 @@ def wrap_name_default(name_prefix=None):
:return: a decorator to set default name :return: a decorator to set default name
:rtype: callable :rtype: callable
""" """
return wrap_param_default(["name"], DefaultNameFactory(name_prefix)) factory = DefaultNameFactory(name_prefix)
_name_factories.append(factory)
return wrap_param_default(["name"], factory)
def wrap_param_attr_default(param_names=None, default_factory=None): def wrap_param_attr_default(param_names=None, default_factory=None):
......
...@@ -4,6 +4,11 @@ add_test(NAME layers_test ...@@ -4,6 +4,11 @@ add_test(NAME layers_test
python ${PROJ_ROOT}/python/paddle/trainer_config_helpers/tests/layers_test.py python ${PROJ_ROOT}/python/paddle/trainer_config_helpers/tests/layers_test.py
WORKING_DIRECTORY ${PROJ_ROOT}/python/paddle) WORKING_DIRECTORY ${PROJ_ROOT}/python/paddle)
add_test(NAME test_reset_hook
COMMAND ${PROJ_ROOT}/paddle/.set_python_path.sh -d ${PROJ_ROOT}/python/
python ${PROJ_ROOT}/python/paddle/trainer_config_helpers/tests/test_reset_hook.py
WORKING_DIRECTORY ${PROJ_ROOT}/python/paddle)
if (PROTOBUF_3) if (PROTOBUF_3)
add_paddle_exe(protobuf_equal add_paddle_exe(protobuf_equal
ProtobufEqualMain.cpp) ProtobufEqualMain.cpp)
......
...@@ -11,10 +11,12 @@ for conf in ${configs[*]} ...@@ -11,10 +11,12 @@ for conf in ${configs[*]}
do do
echo "Generating " $conf echo "Generating " $conf
python -m paddle.utils.dump_config $conf.py > $protostr/$conf.protostr.unittest python -m paddle.utils.dump_config $conf.py > $protostr/$conf.protostr.unittest
cat ${conf}.py |python test_config_parser_for_non_file_config.py > $protostr/$conf.protostr.non_file_config.unittest
done done
for conf in ${whole_configs[*]} for conf in ${whole_configs[*]}
do do
echo "Generating " $conf echo "Generating " $conf
python -m paddle.utils.dump_config $conf.py "" --whole > $protostr/$conf.protostr.unittest python -m paddle.utils.dump_config $conf.py "" --whole > $protostr/$conf.protostr.unittest
cat ${conf}.py |python test_config_parser_for_non_file_config.py --whole > $protostr/$conf.protostr.non_file_config.unittest
done done
...@@ -17,6 +17,7 @@ if [ -z $1 ]; then ...@@ -17,6 +17,7 @@ if [ -z $1 ]; then
base_protostr=$protostr/$file base_protostr=$protostr/$file
new_protostr=$protostr/$file.unittest new_protostr=$protostr/$file.unittest
diff $base_protostr $new_protostr -u diff $base_protostr $new_protostr -u
diff $protostr/$file $protostr/$file.non_file_config.unittest -u
done done
else else
for file in ${configs[*]} for file in ${configs[*]}
...@@ -24,6 +25,9 @@ else ...@@ -24,6 +25,9 @@ else
if ! $1 $protostr/$file.protostr $protostr/$file.protostr.unittest; then if ! $1 $protostr/$file.protostr $protostr/$file.protostr.unittest; then
diff $protostr/$file.protostr $protostr/$file.protostr.unittest -u diff $protostr/$file.protostr $protostr/$file.protostr.unittest -u
fi fi
if ! $1 $protostr/$file.protostr $protostr/$file.protostr.non_file_config.unittest; then
diff $protostr/$file.protostr $protostr/$file.protostr.non_file_config.unittest -u
fi
done done
for file in ${whole_configs[*]} for file in ${whole_configs[*]}
...@@ -31,5 +35,8 @@ else ...@@ -31,5 +35,8 @@ else
if ! $1 $protostr/$file.protostr $protostr/$file.protostr.unittest --whole; then if ! $1 $protostr/$file.protostr $protostr/$file.protostr.unittest --whole; then
diff $protostr/$file.protostr $protostr/$file.protostr.unittest -u diff $protostr/$file.protostr $protostr/$file.protostr.unittest -u
fi fi
if ! $1 $protostr/$file.protostr $protostr/$file.protostr.non_file_config.unittest --whole; then
diff $protostr/$file.protostr $protostr/$file.protostr.non_file_config.unittest -u
fi
done done
fi fi
#!/usr/bin/env python
# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import re
import getopt
def main(print_whole_config, globals, locals):
'''
this test will all test_config.py
'''
cmdstr = """from paddle.trainer.config_parser import parse_config\n"""
importstr = ""
functionstr = ""
for line in sys.stdin:
if re.match("^import", line) or re.match("^from.*import", line):
importstr = importstr + line
else:
functionstr = functionstr + " " + line
cmdstr = cmdstr + importstr + """def configs():\n""" + functionstr
#cmdstr = cmdstr + """def configs():\n""" + importstr + functionstr
if print_whole_config:
cmdstr = cmdstr + """print parse_config(configs, "")"""
else:
cmdstr = cmdstr + """print parse_config(configs, "").model_config"""
exec(cmdstr, globals, locals)
if __name__ == '__main__':
whole = False
opts, args = getopt.getopt(sys.argv[1:], "", ["whole"])
for op, value in opts:
if op == "--whole":
whole = True
main(whole, globals(), locals())
# Copyright PaddlePaddle contributors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from paddle.trainer.config_parser import parse_config
class TestParse(unittest.TestCase):
def test_parse(self):
a = parse_config(
'trainer_config_helpers/tests/layers_test_config.py', '')
b = parse_config(
'trainer_config_helpers/tests/layers_test_config.py', '')
self.assertEqual(a, b)
if __name__ == '__main__':
unittest.main()
cc_library(
name = "main",
srcs = glob(
["src/*.cc"],
exclude = ["src/gtest-all.cc"]
),
hdrs = glob([
"include/**/*.h",
"src/*.h"
]),
copts = ["-Iexternal/gtest/include"],
linkopts = ["-pthread"],
visibility = ["//visibility:public"],
)
licenses(["notice"]) # Apache 2.0
load("@protobuf//:protobuf.bzl", "cc_proto_library")
cc_proto_library(
name = "example_proto",
srcs = ["example.proto"],
protoc = "@protobuf//:protoc",
default_runtime = "@protobuf//:protobuf",
)
cc_library(
name = "example_lib",
srcs = ["example_lib.cc"],
hdrs = ["example_lib.h"],
deps = [":example_proto"],
)
cc_test(
name = "example_lib_test",
srcs = ["example_lib_test.cc"],
copts = ["-Iexternal/gtest/include"],
deps =[
"@gtest//:main",
":example_lib",
],
)
This package tests that Bazel can build protobuf related rules.
syntax = "proto3";
package third_party.protobuf_test;
message Greeting {
string name = 1;
}
#include "third_party/protobuf_test/example_lib.h"
namespace third_party {
namespace protobuf_test {
std::string get_greet(const Greeting& who) {
return "Hello " + who.name();
}
} // namespace protobuf_test
} // namespace thrid_party
#pragma once
#include "third_party/protobuf_test/example.pb.h"
#include <string>
namespace third_party {
namespace protobuf_test {
std::string get_greet(const Greeting &who);
} // namespace protobuf_test
} // namespace third_party
#include "third_party/protobuf_test/example_lib.h"
#include "gtest/gtest.h"
namespace third_party {
namespace protobuf_test {
TEST(ProtobufTest, GetGreet) {
Greeting g;
g.set_name("Paddle");
EXPECT_EQ("Hello Paddle", get_greet(g));
}
} // namespace protobuf_test
} // namespace third_party
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册