From 0e7d5cdea2de0e5f2d2b051083f6a92956f52ca4 Mon Sep 17 00:00:00 2001 From: liaogang Date: Sun, 20 Nov 2016 14:37:50 +0800 Subject: [PATCH 01/11] Refine quick start index.rst chinese docs --- doc_cn/demo/quick_start/index.md | 545 ------------------------------ doc_cn/demo/quick_start/index.rst | 474 ++++++++++++++++++++++++++ 2 files changed, 474 insertions(+), 545 deletions(-) delete mode 100644 doc_cn/demo/quick_start/index.md create mode 100644 doc_cn/demo/quick_start/index.rst diff --git a/doc_cn/demo/quick_start/index.md b/doc_cn/demo/quick_start/index.md deleted file mode 100644 index 4d9b24ba85..0000000000 --- a/doc_cn/demo/quick_start/index.md +++ /dev/null @@ -1,545 +0,0 @@ -# PaddlePaddle快速入门教程 - -我们以文本分类问题作为背景,介绍PaddlePaddle使用流程和常用的网络基础单元的配置方法。 - -## 安装(Install) - -首先请参考安装教程安装PaddlePaddle。 - -## 使用概述(Overview) - -**文本分类问题**:对于给定的一条文本, 我们从提前给定的类别集合中选择其所属类 -别。比如通过用户对电子商务网站评论,评估产品的质量: - -- 这个显示器很棒! (好评) -- 用了两个月之后这个显示器屏幕碎了。(差评) - -每一个任务流程都可以分为如下5个基础部分。 -
![](./Pipeline.jpg)
- -1. 数据格式准备 - - 每行保存一条样本,类别Id 和文本信息用Tab间隔, 文本中的单词用空格分隔(如果不切词,则字与字之间用空格分隔),例如:```类别Id ‘\t’ 这 个 显 示 器 很 棒 !``` -2. 数据向模型传送 - - PaddlePaddle可以读取Python写的传输数据脚本,所有字符都将转换为连续整数表示的Id传给模型 -3. 网络结构(由易到难展示4种不同的网络配置) - - 逻辑回归模型 - - 词向量模型 - - 卷积模型 - - 时序模型 - - 优化算法 -4. 训练模型 -5. 预测 - -## 数据格式准备(Data Preparation) -在本问题中,我们使用[Amazon电子产品评论数据](http://jmcauley.ucsd.edu/data/amazon/), -将评论分为好评(正样本)和差评(负样本)两类。[源码](https://github.com/baidu/Paddle)的`demo/quick_start`里提供了数据下载脚本 -和预处理脚本。 - -```bash -cd demo/quick_start -./data/get_data.sh -./preprocess.sh -``` - -## 数据向模型传送(Transfer Data to Model) - -### Python数据加载脚本(Data Provider Script) - -下面dataprovider_bow.py文件给出了完整例子,主要包括两部分: - -* initalizer: 定义文本信息、类别Id的数据类型。 -* process: yield文本信息和类别Id,和initalizer里定义顺序一致。 - -```python -from paddle.trainer.PyDataProvider2 import * - -# id of the word not in dictionary -UNK_IDX = 0 - -# initializer is called by the framework during initialization. -# It allows the user to describe the data types and setup the -# necessary data structure for later use. -# `settings` is an object. initializer need to properly fill settings.input_types. -# initializer can also store other data structures needed to be used at process(). -# In this example, dictionary is stored in settings. -# `dictionay` and `kwargs` are arguments passed from trainer_config.lr.py -def initializer(settings, dictionary, **kwargs): - # Put the word dictionary into settings - settings.word_dict = dictionary - - # setting.input_types specifies what the data types the data provider - # generates. - settings.input_types = [ - # The first input is a sparse_binary_vector, - # which means each dimension of the vector is either 0 or 1. It is the - # bag-of-words (BOW) representation of the texts. - sparse_binary_vector(len(dictionary)), - # The second input is an integer. It represents the category id of the - # sample. 2 means there are two labels in the dataset. - # (1 for positive and 0 for negative) - integer_value(2)] - -# Delaring a data provider. It has an initializer 'data_initialzer'. -# It will cache the generated data of the first pass in memory, so that -# during later pass, no on-the-fly data generation will be needed. -# `setting` is the same object used by initializer() -# `file_name` is the name of a file listed train_list or test_list file given -# to define_py_data_sources2(). See trainer_config.lr.py. -@provider(init_hook=initializer, cache=CacheType.CACHE_PASS_IN_MEM) -def process(settings, file_name): - # Open the input data file. - with open(file_name, 'r') as f: - # Read each line. - for line in f: - # Each line contains the label and text of the comment, separated by \t. - label, comment = line.strip().split('\t') - - # Split the words into a list. - words = comment.split() - - # convert the words into a list of ids by looking them up in word_dict. - word_vector = [settings.word_dict.get(w, UNK_IDX) for w in words] - - # Return the features for the current comment. The first is a list - # of ids representing a 0-1 binary sparse vector of the text, - # the second is the integer id of the label. - yield word_vector, int(label) -``` - -### 配置中的数据加载定义(Data Provider in Configure) - -在模型配置中利用`define_py_data_sources2`加载数据: - -```python -from paddle.trainer_config_helpers import * - -file = "data/dict.txt" -word_dict = dict() -with open(dict_file, 'r') as f: - for i, line in enumerate(f): - w = line.strip().split()[0] - word_dict[w] = i -# define the data sources for the model. -# We need to use different process for training and prediction. -# For training, the input data includes both word IDs and labels. -# For prediction, the input data only includs word Ids. -define_py_data_sources2(train_list='data/train.list', - test_list='data/test.list', - module="dataprovider_bow", - obj="process", - args={"dictionary": word_dict}) -``` -* data/train.list,data/test.list: 指定训练、测试数据 -* module="dataprovider": 数据处理Python文件名 -* obj="process": 指定生成数据的函数 -* args={"dictionary": word_dict}: 额外的参数,这里指定词典 - -更详细数据格式和用例请参考 -PyDataProvider2。 - -## 网络结构(Network Architecture) -本节我们将专注于网络结构的介绍。 -
![](./PipelineNetwork.jpg)
- -我们将以基本的逻辑回归网络作为起点,并逐渐展示更加深入的功能。更详细的网络配置 -连接请参考Layer文档。 -所有配置在[源码](https://github.com/baidu/Paddle)`demo/quick_start`目录,首先列举逻辑回归网络。 - -### 逻辑回归模型(Logistic Regression) - -流程如下: -
![](./NetLR.jpg)
- -- 获取利用one-hot vector表示的每个单词,维度是词典大小 - -```python -word = data_layer(name="word", size=word_dim) -``` - -- 获取该条样本类别Id,维度是类别个数。 - -```python -label = data_layer(name="label", size=label_dim) -``` - -- 利用逻辑回归模型对该向量进行分类,同时会计算分类准确率 - -```python -# Define a fully connected layer with logistic activation (also called softmax activation). -output = fc_layer(input=word, - size=label_dim, - act_type=SoftmaxActivation()) -# Define cross-entropy classification loss and error. -classification_cost(input=output, label=label) -``` - - - input: 除过data层,每个层都有一个或多个input,多个input以list方式输入 - - size: 该层神经元个数 - - act_type: 激活函数类型 - -效果总结:我们将在后面介绍训练和预测的流程的脚本。在此为方便对比不同网络结构, -我们随时总结了各个网络的复杂度和效果。 - - -
- - - - - - - - - - - - - - - - - -
网络名称参数数量错误率
逻辑回归252 KB8.652%
- -
- -### 词向量模型(Word Vector) - -embedding模型需要稍微改变数据提供的脚本,即`dataprovider_emb.py`,词向量模型、 -卷积模型、时序模型均使用该脚本。其中文本输入类型定义为整数时序类型integer_value_sequence。 - -``` -def initializer(settings, dictionary, **kwargs): - settings.word_dict = dictionary - settings.input_types = [ - # Define the type of the first input as sequence of integer. - # The value of the integers range from 0 to len(dictrionary)-1 - integer_value_sequence(len(dictionary)), - # Define the second input for label id - integer_value(2)] - -@provider(init_hook=initializer) -def process(settings, file_name): - ... - # omitted, it is same as the data provider for LR model -``` - -该模型依然是使用逻辑回归分类网络的框架, 只是将句子利用连续向量表示替换稀疏 -向量表示, 即对第3步进行替换。句子表示的计算更新为2步: -
![](./NetContinuous.jpg)
- -- 利用单词Id查找对应的该单词的连续表示向量(维度为word_dim), 输入N个单词,输出为N个word_dim维度向量 - -```python -emb = embedding_layer(input=word, size=word_dim) -``` - -- 将该句话包含的所有单词向量求平均得到句子的表示 - -```python -avg = pooling_layer(input=emb, pooling_type=AvgPooling()) -``` - -其它部分和逻辑回归网络结构一致。 -效果总结: - - -
- - - - - - - - - - - - - - - - - -
网络名称参数数量错误率
词向量模型15 MB8.484%
-
-
- -### 卷积模型(Convolution) -卷积网络是一种特殊的从词向量表示到句子表示的方法, 也就是将词向量模型额步 -骤3-2进行进一步演化, 变为3个新的子步骤。 -
![](./NetConv.jpg)
- -文本卷积分为三个步骤: -1. 获取每个单词左右各k个近邻, 拼接成一个新的向量表示; -2. 对该表示进行非线性变换 (例如Sigmoid变换), 成为维度为hidden_dim的新的向量; -3. 在每个维度上取出在该句话新的向量集合上该维度的最大值作为最后的句子表示向量。 这3个子步骤可配置为: - -```python -text_conv = sequence_conv_pool(input=emb, - context_start=k, - context_len=2 * k + 1) -``` - -效果总结: - - -
- - - - - - - - - - - - - - - - - -
网络名称参数数量错误率
卷积模型16 MB5.628%
-
- -### 时序模型(Time Sequence) -
![](./NetRNN.jpg)
- -时序模型即为RNN模型, 包括简单的RNN模型、GRU模型、LSTM模型等。 - -- GRU模型配置: - -```python -gru = simple_gru(input=emb, size=gru_size) -``` - -- LSTM模型配置: - -```python -lstm = simple_lstm(input=emb, size=lstm_size) -``` - -针对本问题,我们采用单层LSTM模型,并使用了Dropout,效果总结: - - -
- - - - - - - - - - - - - - - - - -
网络名称参数数量错误率
时序模型16 MB4.812%
- -
- -## 优化算法(Optimization Algorithm) -优化算法包括 -Momentum, RMSProp,AdaDelta,AdaGrad,ADAM,Adamax等,这里采用Adam优化方法,加了L2正则和梯度截断。 - -```python -settings(batch_size=128, - learning_rate=2e-3, - learning_method=AdamOptimizer(), - regularization=L2Regularization(8e-4), - gradient_clipping_threshold=25) -``` - -## 训练模型(Training Model) -在完成了数据和网络结构搭建之后, 我们进入到训练部分。 -
![](./PipelineTrain.jpg)
- -训练脚本:我们将训练的命令行保存在了 `train.sh`文件中。训练时所需设置的主要参数如下: - -```bash -paddle train \ ---config=trainer_config.py \ ---log_period=20 \ ---save_dir=./output \ ---num_passes=15 \ ---use_gpu=false -``` -这里没有介绍多机分布式训练,可以参考分布式训练的demo学习如何进行多机训练。 - -## 预测(Prediction) -可以使用训练好的模型评估带有label的验证集,也可以预测没有label的测试集。 -
![](./PipelineTest.jpg)
- -测试脚本如下,将会测试配置文件中test.list指定的数据。 - -```bash -paddle train \ ---use_gpu=false \ ---job=test \ ---init_model_path=./output/pass-0000x -``` - -可以参考Python API预测 -教程,或其他demo的Python预测过程。也可以通过如下方式预测。 - -预测脚本(`predict.sh`): - -```bash -model="output/pass-00003" -paddle train \ - --config=trainer_config.lstm.py \ - --use_gpu=false \ - --job=test \ - --init_model_path=$model \ - --config_args=is_predict=1 \ - --predict_output_dir=. \ - -mv rank-00000 result.txt -``` -这里以`output/pass-00003`为例进行预测,用户可以根据训练log选择test结果最好的模型来预测。与训练网络配置不同的是:无需label相关的层,指定outputs输出概率层(softmax输出), -指定batch_size=1,数据传输无需label数据,预测数据指定test_list的位置。 - -预测结果以文本的形式保存在`result.txt`中,一行为一个样本,格式如下: - -``` -预测ID;ID为0的概率 ID为1的概率 -预测ID;ID为0的概率 ID为1的概率 -``` - -``` -is_predict = get_config_arg('is_predict', bool, False) -trn = 'data/train.list' if not is_predict else None -tst = 'data/test.list' if not is_predict else 'data/pred.list' -obj = 'process' if not is_predict else 'process_pre' -batch_size = 128 if not is_predict else 1 -if is_predict: - maxid = maxid_layer(output) - outputs([maxid,output]) -else: - label = data_layer(name="label", size=2) - cls = classification_cost(input=output, label=label) - outputs(cls) -``` - -## 总体效果总结(Summary) -这些流程中的数据下载、网络配置、训练脚本在`/demo/quick_start`目录,我们在此总 -结上述网络结构在Amazon-Elec测试集(25k)上的效果: - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
网络名称参数数量错误率配置文件
逻辑回归模型 252KB 8.652%trainer_config.lr.py
词向量模型 15MB 8.484%trainer_config.emb.py
卷积模型 16MB 5.628%trainer_config.cnn.py
时序模型 16MB 4.812%trainer_config.lstm.py
-
-
- -## 附录(Appendix) -### 命令行参数(Command Line Argument) - -* \--config:网络配置 -* \--save_dir:模型存储路径 -* \--log_period:每隔多少batch打印一次日志 -* \--num_passes:训练轮次,一个pass表示过一遍所有训练样本 -* \--config_args:命令指定的参数会传入网络配置中。 -* \--init_model_path:指定初始化模型路径,可用在测试或训练时指定初始化模型。 - -默认一个pass保存一次模型,也可以通过saving_period_by_batches设置每隔多少batch保存一次模型。 -可以通过show_parameter_stats_period设置打印参数信息等。 -其他参数请参考令行参数文档。 - -### 输出日志(Log) - -``` -TrainerInternal.cpp:160] Batch=20 samples=2560 AvgCost=0.628761 CurrentCost=0.628761 Eval: classification_error_evaluator=0.304297 CurrentEval: classification_error_evaluator=0.304297 -``` -模型训练会看到这样的日志,详细的参数解释如下面表格: -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
名称解释
Batch=20 表示过了20个batch
samples=2560 表示过了2560个样本
AvgCost 每个pass的第0个batch到当前batch所有样本的平均cost
CurrentCost 当前log_period个batch所有样本的平均cost
Eval: classification_error_evaluator 每个pass的第0个batch到当前batch所有样本的平均分类错误率
CurrentEval: classification_error_evaluator 当前log_period个batch所有样本的平均分类错误率
-
-
diff --git a/doc_cn/demo/quick_start/index.rst b/doc_cn/demo/quick_start/index.rst new file mode 100644 index 0000000000..9dabf1f661 --- /dev/null +++ b/doc_cn/demo/quick_start/index.rst @@ -0,0 +1,474 @@ +PaddlePaddle快速入门教程 +======================== + +我们将以 `文本分类问题 `_ 为例, +介绍PaddlePaddle的基本使用方法。 + +安装 +==== + +请参考 `安装教程 <../../build_and_install/index.html>`_ 安装PaddlePaddle。 + +使用概述 +======== + +**文本分类问题**:对于给定的一条文本,我们从提前给定的类别集合中选择其所属类别。 + +比如, 在购物网站上,通过查看买家对某个产品的评价反馈, 评估该产品的质量。 + +- 这个显示器很棒! (好评) +- 用了两个月之后这个显示器屏幕碎了。(差评) + +使用PaddlePaddle, 每一个任务流程都可以被划分为如下五个步骤。 + + .. image:: Pipeline.jpg + :align: center + :scale: 80% + +1. 数据格式准备 + - 本例每行保存一条样本,类别Id和文本信息用 ``Tab`` 间隔,文本中的单词用空格分隔(如果不切词,则字与字之间用空格分隔),例如:``类别Id '\t' 这 个 显 示 器 很 棒 !`` +2. 向系统传送数据 + - PaddlePaddle可以执行用户的python脚本程序来读取各种格式的数据文件。 + - 本例的所有字符都将转换为连续整数表示的Id传给模型。 +3. 描述网络结构和优化算法 + - 本例由易到难展示4种不同的文本分类网络配置:逻辑回归模型,词向量模型,卷积模型,时序模型。 + - 常用优化算法包括Momentum, RMSProp,AdaDelta,AdaGrad,Adam,Adamax等,本例采用Adam优化方法,加了L2正则和梯度截断。 +4. 训练模型 +5. 应用模型 + +数据格式准备 +------------ + +接下来我们将展示如何用PaddlePaddle训练一个文本分类模型,将 `Amazon电子产品评论数据 `_ 分为好评(正样本)和差评(负样本)两种类别。 +`源代码 `_ 的 ``demo/quick_start`` 目录里提供了该数据的下载脚本和预处理脚本。 + +.. code-block:: bash + + cd demo/quick_start + ./data/get_data.sh + ./preprocess.sh + +向系统传送数据 +============== + +Python数据读取脚本 +------------------ + +`DataProvider <../../ui/data_provider/index.html>`_ 是PaddlePaddle负责提供数据的模块。``DataProvider`` 主要职责在于将训练数据传入内存或者显存,让模型能够得到训练更新,其包括两个函数: + +* initializer:PaddlePaddle会在调用读取数据的Python脚本之前,先调用initializer函数。在下面例子里,我们在initialzier函数里初始化词表,并且在随后的读取数据过程中填充词表。 +* process:PaddlePaddle调用process函数来读取数据。每次读取一条数据后,process函数会用yield语句输出这条数据,从而能够被PaddlePaddle 捕获 (harvest)。 + +``dataprovider_bow.py`` 文件给出了完整例子: + +.. code-block:: python + + from paddle.trainer.PyDataProvider2 import * + + # id of the word not in dictionary + UNK_IDX = 0 + + # initializer is called by the framework during initialization. + # It allows the user to describe the data types and setup the + # necessary data structure for later use. + # `settings` is an object. initializer need to properly fill settings.input_types. + # initializer can also store other data structures needed to be used at process(). + # In this example, dictionary is stored in settings. + # `dictionay` and `kwargs` are arguments passed from trainer_config.lr.py + def initializer(settings, dictionary, **kwargs): + # Put the word dictionary into settings + settings.word_dict = dictionary + + # setting.input_types specifies what the data types the data provider + # generates. + settings.input_types = [ + # The first input is a sparse_binary_vector, + # which means each dimension of the vector is either 0 or 1. It is the + # bag-of-words (BOW) representation of the texts. + sparse_binary_vector(len(dictionary)), + # The second input is an integer. It represents the category id of the + # sample. 2 means there are two labels in the dataset. + # (1 for positive and 0 for negative) + integer_value(2)] + + # Delaring a data provider. It has an initializer 'data_initialzer'. + # It will cache the generated data of the first pass in memory, so that + # during later pass, no on-the-fly data generation will be needed. + # `setting` is the same object used by initializer() + # `file_name` is the name of a file listed train_list or test_list file given + # to define_py_data_sources2(). See trainer_config.lr.py. + @provider(init_hook=initializer, cache=CacheType.CACHE_PASS_IN_MEM) + def process(settings, file_name): + # Open the input data file. + with open(file_name, 'r') as f: + # Read each line. + for line in f: + # Each line contains the label and text of the comment, separated by \t. + label, comment = line.strip().split('\t') + + # Split the words into a list. + words = comment.split() + + # convert the words into a list of ids by looking them up in word_dict. + word_vector = [settings.word_dict.get(w, UNK_IDX) for w in words] + + # Return the features for the current comment. The first is a list + # of ids representing a 0-1 binary sparse vector of the text, + # the second is the integer id of the label. + yield word_vector, int(label) + +配置中的数据加载定义 +-------------------- + +在模型配置中通过 ``define_py_data_sources2`` 接口来加载数据: + +.. code-block:: python + + from paddle.trainer_config_helpers import * + + file = "data/dict.txt" + word_dict = dict() + with open(dict_file, 'r') as f: + for i, line in enumerate(f): + w = line.strip().split()[0] + word_dict[w] = i + # define the data sources for the model. + # We need to use different process for training and prediction. + # For training, the input data includes both word IDs and labels. + # For prediction, the input data only includs word Ids. + define_py_data_sources2(train_list='data/train.list', + test_list='data/test.list', + module="dataprovider_bow", + obj="process", + args={"dictionary": word_dict}) + + +以下是对上述数据加载的解释: + +- data/train.list,data/test.list: 指定训练数据和测试数据 +- module="dataprovider_bow": 数据处理的Python脚本文件名 +- obj="process": 指定生成数据的函数 +- args={"dictionary": word_dict}: 额外的参数,这里指定词典 + +更详细数据格式和用例请参考 `PyDataProvider2 <../../ui/data_provider/pydataprovider2.html>`_ 。 + +模型网络结构 +============ + +本小节我们将介绍模型网络结构。 + + .. image:: PipelineNetwork.jpg + :align: center + :scale: 80% + + +我们将以基本的逻辑回归网络作为起点,并逐渐展示更加深入的功能。更详细的网络配置连接请参考 `Layer文档 <../../../doc/layer.html>`_ 。 +所有配置都在 `源代码 `_ 的 ``demo/quick_start`` 目录下。 + +逻辑回归模型 +------------ + +具体流程如下: + + .. image:: NetLR.jpg + :align: center + :scale: 80% + +- 获取利用one-hot vector表示的每个单词,维度是词典大小 + + .. code-block:: python + + word = data_layer(name="word", size=word_dim) + +- 获取该条样本类别Id,维度是类别个数。 + + .. code-block:: python + + label = data_layer(name="label", size=label_dim) + +- 利用逻辑回归模型对该向量进行分类,同时会计算分类准确率 + + .. code-block:: python + + # Define a fully connected layer with logistic activation (also called softmax activation). + output = fc_layer(input=word, + size=label_dim, + act_type=SoftmaxActivation()) + # Define cross-entropy classification loss and error. + classification_cost(input=output, label=label) + + + - input: 除过data层,每个层都有一个或多个input,多个input以list方式输入 + - size: 该层神经元个数 + - act_type: 激活函数类型 + +**效果总结**:我们将在后面介绍训练和预测流程的脚本。在此为方便对比不同网络结构,我们总结了各个网络的复杂度和效果。 + + ===================== =============================== ================= + 网络名称 参数数量 错误率 + ===================== =============================== ================= + 逻辑回归 252 KB 8.652 % + ===================== =============================== ================= + +词向量模型 +---------- + +embedding模型需要稍微改变数据提供的脚本,即 ``dataprovider_emb.py``,词向量模型、 +卷积模型、时序模型均使用该脚本。其中文本输入类型定义为整数时序类型integer_value_sequence。 + +.. code-block:: python + + def initializer(settings, dictionary, **kwargs): + settings.word_dict = dictionary + settings.input_types = [ + # Define the type of the first input as sequence of integer. + # The value of the integers range from 0 to len(dictrionary)-1 + integer_value_sequence(len(dictionary)), + # Define the second input for label id + integer_value(2)] + + @provider(init_hook=initializer) + def process(settings, file_name): + ... + # omitted, it is same as the data provider for LR model + +该模型依然是使用逻辑回归分类网络的框架, 只是将句子利用连续向量表示替换稀疏 +向量表示, 即对第3步进行替换。句子表示的计算更新为2步: + +.. image:: NetContinuous.jpg + :align: center + :scale: 80% + +- 利用单词Id查找对应的该单词的连续表示向量(维度为word_dim), 输入N个单词,输出为N个word_dim维度向量 + + .. code-block:: python + + emb = embedding_layer(input=word, size=word_dim) + +- 将该句话包含的所有单词向量求平均得到句子的表示 + + .. code-block:: python + + avg = pooling_layer(input=emb, pooling_type=AvgPooling()) + +其它部分和逻辑回归网络结构一致。 + +**效果总结:** + + ===================== =============================== ================== + 网络名称 参数数量 错误率 + ===================== =============================== ================== + 词向量模型 15 MB 8.484 % + ===================== =============================== ================== + +卷积模型 +----------- + +卷积网络是一种特殊的从词向量表示到句子表示的方法, 也就是将词向量模型额步 +骤3-2进行进一步演化, 变为3个新的子步骤。 + +.. image:: NetConv.jpg + :align: center + :scale: 80% + +文本卷积分为三个步骤: + +1. 获取每个单词左右各k个近邻, 拼接成一个新的向量表示; + +2. 对该表示进行非线性变换 (例如Sigmoid变换), 成为维度为hidden_dim的新的向量; + +3. 在每个维度上取出在该句话新的向量集合上该维度的最大值作为最后的句子表示向量。 这3个子步骤可配置为: + +.. code-block:: python + + text_conv = sequence_conv_pool(input=emb, + context_start=k, + context_len=2 * k + 1) + +**效果总结:** + + ===================== =============================== ======================== + 网络名称 参数数量 错误率 + ===================== =============================== ======================== + 卷积模型 16 MB 5.628 % + ===================== =============================== ======================== + +时序模型 +---------- + +.. image:: NetRNN.jpg + :align: center + :scale: 80% + +时序模型即为RNN模型, 包括简单的RNN模型、GRU模型、LSTM模型等。 + +- GRU模型配置: + + .. code-block:: python + + gru = simple_gru(input=emb, size=gru_size) + + +- LSTM模型配置: + + .. code-block:: python + + lstm = simple_lstm(input=emb, size=lstm_size) + +针对本问题,我们采用单层LSTM模型,并使用了Dropout,**效果总结:** + + ===================== =============================== ========================= + 网络名称 参数数量 错误率 + ===================== =============================== ========================= + 时序模型 16 MB 4.812 % + ===================== =============================== ========================= + +优化算法 +========= + +`优化算法 <../../../doc/ui/trainer_config_helpers_api.html#module-paddle.trainer_config_helpers.optimizers>`_ 包括 +Momentum, RMSProp,AdaDelta,AdaGrad,ADAM,Adamax等,这里采用Adam优化方法,加了L2正则和梯度截断。 + +.. code-block:: python + + settings(batch_size=128, + learning_rate=2e-3, + learning_method=AdamOptimizer(), + regularization=L2Regularization(8e-4), + gradient_clipping_threshold=25) + +训练模型 +========= + +在完成了数据和网络结构搭建之后, 我们进入到训练部分。 + +.. image:: PipelineTrain.jpg + :align: center + :scale: 80% + +训练脚本:我们将训练的命令行保存在了 ``train.sh`` 文件中。训练时所需设置的主要参数如下: + + .. code-block:: bash + + paddle train \ + --config=trainer_config.py \ + --log_period=20 \ + --save_dir=./output \ + --num_passes=15 \ + --use_gpu=false + +这里没有介绍多机分布式训练,可以参考 `分布式训练 <../../cluster/index.html>`_ 的demo学习如何进行多机训练。 + +预测 +===== + +可以使用训练好的模型评估带有label的验证集,也可以预测没有label的测试集。 + +.. image:: PipelineTest.jpg + :align: center + :scale: 80% + +测试脚本如下,将会测试配置文件中test.list指定的数据。 + + .. code-block:: bash + + paddle train \ + --use_gpu=false \ + --job=test \ + --init_model_path=./output/pass-0000x + +可以参考 `Python API预测 <../../ui/predict/swig_py_paddle.html>`_ +教程,或其他 `demo <../../demo/index.html>`_ 的Python预测过程。也可以通过如下方式预测。 + +预测脚本(``predict.sh``): + + .. code-block:: bash + + model="output/pass-00003" + paddle train \ + --config=trainer_config.lstm.py \ + --use_gpu=false \ + --job=test \ + --init_model_path=$model \ + --config_args=is_predict=1 \ + --predict_output_dir=. \ + + mv rank-00000 result.txt + +这里以 ``output/pass-00003`` 为例进行预测,用户可以根据训练log选择test结果最好的模型来预测。与训练网络配置不同的是:无需label相关的层,指定outputs输出概率层(softmax输出), +指定batch_size=1,数据传输无需label数据,预测数据指定test_list的位置。 + +预测结果以文本的形式保存在 ``result.txt`` 中,一行为一个样本,格式如下: + + .. code-block:: bash + + 预测ID;ID为0的概率 ID为1的概率 + 预测ID;ID为0的概率 ID为1的概率 + + .. code-block:: python + + is_predict = get_config_arg('is_predict', bool, False) + trn = 'data/train.list' if not is_predict else None + tst = 'data/test.list' if not is_predict else 'data/pred.list' + obj = 'process' if not is_predict else 'process_pre' + batch_size = 128 if not is_predict else 1 + if is_predict: + maxid = maxid_layer(output) + outputs([maxid,output]) + else: + label = data_layer(name="label", size=2) + cls = classification_cost(input=output, label=label) + outputs(cls) + +总体效果总结 +============== + +这些流程中的数据下载、网络配置、训练脚本在 ``/demo/quick_start`` 目录,我们在此总 +结上述网络结构在Amazon-Elec测试集(25k)上的效果: + + ===================== =============================== ============= ================================== + 网络名称 参数数量 错误率 配置文件 + ===================== =============================== ============= ================================== + 逻辑回归模型 252 KB 8.652% trainer_config.lr.py + 词向量模型 15 MB 8.484% trainer_config.emb.py + 卷积模型 16 MB 5.628% trainer_config.cnn.py + 时序模型 16 MB 4.812% trainer_config.lstm.py + ===================== =============================== ============= ================================== + + +附录 +===== + +命令行参数 +---------- + +* \--config:网络配置 +* \--save_dir:模型存储路径 +* \--log_period:每隔多少batch打印一次日志 +* \--num_passes:训练轮次,一个pass表示过一遍所有训练样本 +* \--config_args:命令指定的参数会传入网络配置中。 +* \--init_model_path:指定初始化模型路径,可用在测试或训练时指定初始化模型。 + +默认一个pass保存一次模型,也可以通过saving_period_by_batches设置每隔多少batch保存一次模型。 +可以通过show_parameter_stats_period设置打印参数信息等。 +其他参数请参考 `命令行参数文档 <../../ui/index.html#command-line-argument>`_ 。 + +输出日志 +--------- + +.. code-block:: bash + + TrainerInternal.cpp:160] Batch=20 samples=2560 AvgCost=0.628761 CurrentCost=0.628761 Eval: classification_error_evaluator=0.304297 CurrentEval: classification_error_evaluator=0.304297 + +模型训练会看到这样的日志,详细的参数解释如下面表格: + + =========================================== ========================================================== + 名称 解释 + =========================================== ========================================================== + Batch=20 表示过了20个batch + samples=2560 表示过了2560个样本 + AvgCost 每个pass的第0个batch到当前batch所有样本的平均cost + CurrentCost 当前log_period个batch所有样本的平均cost + Eval: classification_error_evaluator 每个pass的第0个batch到当前batch所有样本的平均分类错误率 + CurrentEval: classification_error_evaluator 当前log_period个batch所有样本的平均分类错误率 + =========================================== ========================================================== From a61bf5a65f62b2ef2aec153dc7fd01d22543df87 Mon Sep 17 00:00:00 2001 From: liaogang Date: Tue, 22 Nov 2016 20:51:59 +0800 Subject: [PATCH 02/11] Refine quick start index.rst --- doc_cn/demo/quick_start/index.rst | 105 ++++++++++++------------------ 1 file changed, 42 insertions(+), 63 deletions(-) diff --git a/doc_cn/demo/quick_start/index.rst b/doc_cn/demo/quick_start/index.rst index 9dabf1f661..08c1c8413b 100644 --- a/doc_cn/demo/quick_start/index.rst +++ b/doc_cn/demo/quick_start/index.rst @@ -40,7 +40,7 @@ PaddlePaddle快速入门教程 ------------ 接下来我们将展示如何用PaddlePaddle训练一个文本分类模型,将 `Amazon电子产品评论数据 `_ 分为好评(正样本)和差评(负样本)两种类别。 -`源代码 `_ 的 ``demo/quick_start`` 目录里提供了该数据的下载脚本和预处理脚本。 +`源代码 `_ 的 ``demo/quick_start`` 目录里提供了该数据的下载脚本和预处理脚本,你只需要在命令行输入以下命令,就能够很方便的完成数据下载和相应的预处理工作。 .. code-block:: bash @@ -51,7 +51,7 @@ PaddlePaddle快速入门教程 向系统传送数据 ============== -Python数据读取脚本 +Python脚本读取数据 ------------------ `DataProvider <../../ui/data_provider/index.html>`_ 是PaddlePaddle负责提供数据的模块。``DataProvider`` 主要职责在于将训练数据传入内存或者显存,让模型能够得到训练更新,其包括两个函数: @@ -146,7 +146,7 @@ Python数据读取脚本 以下是对上述数据加载的解释: - data/train.list,data/test.list: 指定训练数据和测试数据 -- module="dataprovider_bow": 数据处理的Python脚本文件名 +- module="dataprovider_bow": 处理数据的Python脚本文件 - obj="process": 指定生成数据的函数 - args={"dictionary": word_dict}: 额外的参数,这里指定词典 @@ -162,8 +162,8 @@ Python数据读取脚本 :scale: 80% -我们将以基本的逻辑回归网络作为起点,并逐渐展示更加深入的功能。更详细的网络配置连接请参考 `Layer文档 <../../../doc/layer.html>`_ 。 -所有配置都在 `源代码 `_ 的 ``demo/quick_start`` 目录下。 +我们将以最基本的逻辑回归网络作为起点,并逐渐展示更加深入的功能。更详细的网络配置连接请参考 `Layer文档 <../../../doc/layer.html>`_ 。 +所有配置都能在 `源代码 `_ 的 ``demo/quick_start`` 目录下找到。 逻辑回归模型 ------------ @@ -174,7 +174,7 @@ Python数据读取脚本 :align: center :scale: 80% -- 获取利用one-hot vector表示的每个单词,维度是词典大小 +- 获取利用 `one-hot vector `_ 表示的每个单词,维度是词典大小 .. code-block:: python @@ -198,7 +198,7 @@ Python数据读取脚本 classification_cost(input=output, label=label) - - input: 除过data层,每个层都有一个或多个input,多个input以list方式输入 + - input: 除去data层,每个层都有一个或多个input,多个input以list方式输入 - size: 该层神经元个数 - act_type: 激活函数类型 @@ -213,7 +213,7 @@ Python数据读取脚本 词向量模型 ---------- -embedding模型需要稍微改变数据提供的脚本,即 ``dataprovider_emb.py``,词向量模型、 +embedding模型需要稍微改变提供数据的Python脚本,即 ``dataprovider_emb.py``,词向量模型、 卷积模型、时序模型均使用该脚本。其中文本输入类型定义为整数时序类型integer_value_sequence。 .. code-block:: python @@ -232,20 +232,19 @@ embedding模型需要稍微改变数据提供的脚本,即 ``dataprovider_emb. ... # omitted, it is same as the data provider for LR model -该模型依然是使用逻辑回归分类网络的框架, 只是将句子利用连续向量表示替换稀疏 -向量表示, 即对第3步进行替换。句子表示的计算更新为2步: +该模型依然使用逻辑回归分类网络的框架, 只是将句子用连续向量表示替换为用稀疏向量表示, 即对第三步进行替换。句子表示的计算更新为两步: .. image:: NetContinuous.jpg :align: center :scale: 80% -- 利用单词Id查找对应的该单词的连续表示向量(维度为word_dim), 输入N个单词,输出为N个word_dim维度向量 +- 利用单词Id查找该单词对应的连续向量(维度为word_dim), 输入N个单词,输出为N个word_dim维度向量 .. code-block:: python emb = embedding_layer(input=word, size=word_dim) -- 将该句话包含的所有单词向量求平均得到句子的表示 +- 将该句话包含的所有单词向量求平均, 得到句子的表示 .. code-block:: python @@ -264,20 +263,21 @@ embedding模型需要稍微改变数据提供的脚本,即 ``dataprovider_emb. 卷积模型 ----------- -卷积网络是一种特殊的从词向量表示到句子表示的方法, 也就是将词向量模型额步 -骤3-2进行进一步演化, 变为3个新的子步骤。 +卷积网络是一种特殊的从词向量表示到句子表示的方法, 也就是将词向量模型进一步演化为三个新步骤。 .. image:: NetConv.jpg :align: center :scale: 80% -文本卷积分为三个步骤: +文本卷积分可为三个步骤: -1. 获取每个单词左右各k个近邻, 拼接成一个新的向量表示; +1. 首先,从每个单词左右两端分别获取k个相邻的单词, 拼接成一个新的向量; -2. 对该表示进行非线性变换 (例如Sigmoid变换), 成为维度为hidden_dim的新的向量; +2. 其次,对该向量进行非线性变换(例如Sigmoid变换), 使其转变为维度为hidden_dim的新向量; -3. 在每个维度上取出在该句话新的向量集合上该维度的最大值作为最后的句子表示向量。 这3个子步骤可配置为: +3. 最后,对整个新向量集合的每一个维度取最大值来表示最后的句子。 + +这三个步骤可配置为: .. code-block:: python @@ -300,7 +300,7 @@ embedding模型需要稍微改变数据提供的脚本,即 ``dataprovider_emb. :align: center :scale: 80% -时序模型即为RNN模型, 包括简单的RNN模型、GRU模型、LSTM模型等。 +时序模型,也称为RNN模型, 包括简单的RNN模型, GRU模型和LSTM模型等等。 - GRU模型配置: @@ -315,7 +315,7 @@ embedding模型需要稍微改变数据提供的脚本,即 ``dataprovider_emb. lstm = simple_lstm(input=emb, size=lstm_size) -针对本问题,我们采用单层LSTM模型,并使用了Dropout,**效果总结:** +本次试验,我们采用单层LSTM模型,并使用了Dropout,**效果总结:** ===================== =============================== ========================= 网络名称 参数数量 错误率 @@ -326,8 +326,8 @@ embedding模型需要稍微改变数据提供的脚本,即 ``dataprovider_emb. 优化算法 ========= -`优化算法 <../../../doc/ui/trainer_config_helpers_api.html#module-paddle.trainer_config_helpers.optimizers>`_ 包括 -Momentum, RMSProp,AdaDelta,AdaGrad,ADAM,Adamax等,这里采用Adam优化方法,加了L2正则和梯度截断。 +`优化算法 `_ 包括 +Momentum, RMSProp,AdaDelta,AdaGrad,ADAM,Adamax等,这里采用Adam优化方法,同时使用了L2正则和梯度截断。 .. code-block:: python @@ -340,13 +340,19 @@ Momentum, RMSProp,AdaDelta,AdaGrad,ADAM,Adamax等,这里采用Adam优 训练模型 ========= -在完成了数据和网络结构搭建之后, 我们进入到训练部分。 +在数据加载和网络配置完成之后, 我们就可以训练模型了。 .. image:: PipelineTrain.jpg :align: center :scale: 80% -训练脚本:我们将训练的命令行保存在了 ``train.sh`` 文件中。训练时所需设置的主要参数如下: +训练模型,我们只需要运行 ``train.sh`` 训练脚本: + + .. code-block:: bash + + ./train.sh + +``train.sh``中包含了训练模型的基本命令。训练时所需设置的主要参数如下: .. code-block:: bash @@ -357,30 +363,19 @@ Momentum, RMSProp,AdaDelta,AdaGrad,ADAM,Adamax等,这里采用Adam优 --num_passes=15 \ --use_gpu=false -这里没有介绍多机分布式训练,可以参考 `分布式训练 <../../cluster/index.html>`_ 的demo学习如何进行多机训练。 +这里只简单介绍了单机训练,如何进行分布式训练,可以参考教程 `分布式训练 <../../cluster/index.html>`_ 。 预测 ===== -可以使用训练好的模型评估带有label的验证集,也可以预测没有label的测试集。 +当模型训练好了之后,我们就可以进行预测了。 .. image:: PipelineTest.jpg :align: center :scale: 80% -测试脚本如下,将会测试配置文件中test.list指定的数据。 - - .. code-block:: bash - - paddle train \ - --use_gpu=false \ - --job=test \ - --init_model_path=./output/pass-0000x - -可以参考 `Python API预测 <../../ui/predict/swig_py_paddle.html>`_ -教程,或其他 `demo <../../demo/index.html>`_ 的Python预测过程。也可以通过如下方式预测。 - -预测脚本(``predict.sh``): +之前配置文件中 ``test.list`` 指定的数据将会被测试,这里直接通过预测脚本 ``predict.sh`` 进行预测, +更详细的说明,可以参考 `Python API预测 <../../ui/predict/swig_py_paddle.html>`_ 教程。 .. code-block:: bash @@ -395,8 +390,7 @@ Momentum, RMSProp,AdaDelta,AdaGrad,ADAM,Adamax等,这里采用Adam优 mv rank-00000 result.txt -这里以 ``output/pass-00003`` 为例进行预测,用户可以根据训练log选择test结果最好的模型来预测。与训练网络配置不同的是:无需label相关的层,指定outputs输出概率层(softmax输出), -指定batch_size=1,数据传输无需label数据,预测数据指定test_list的位置。 +这里以 ``output/pass-00003`` 为例进行预测,用户可以根据训练日志,选择测试结果最好的模型来预测。 预测结果以文本的形式保存在 ``result.txt`` 中,一行为一个样本,格式如下: @@ -405,29 +399,14 @@ Momentum, RMSProp,AdaDelta,AdaGrad,ADAM,Adamax等,这里采用Adam优 预测ID;ID为0的概率 ID为1的概率 预测ID;ID为0的概率 ID为1的概率 - .. code-block:: python - - is_predict = get_config_arg('is_predict', bool, False) - trn = 'data/train.list' if not is_predict else None - tst = 'data/test.list' if not is_predict else 'data/pred.list' - obj = 'process' if not is_predict else 'process_pre' - batch_size = 128 if not is_predict else 1 - if is_predict: - maxid = maxid_layer(output) - outputs([maxid,output]) - else: - label = data_layer(name="label", size=2) - cls = classification_cost(input=output, label=label) - outputs(cls) - 总体效果总结 ============== -这些流程中的数据下载、网络配置、训练脚本在 ``/demo/quick_start`` 目录,我们在此总 -结上述网络结构在Amazon-Elec测试集(25k)上的效果: +在 ``/demo/quick_start`` 目录下,能够找到这里使用的所有数据, 网络配置, 训练脚本等等。 +对于Amazon-Elec测试集(25k), 如下表格,展示了上述网络模型的训练效果: ===================== =============================== ============= ================================== - 网络名称 参数数量 错误率 配置文件 + 网络名称 参数数量 错误率 配置文件 ===================== =============================== ============= ================================== 逻辑回归模型 252 KB 8.652% trainer_config.lr.py 词向量模型 15 MB 8.484% trainer_config.emb.py @@ -460,15 +439,15 @@ Momentum, RMSProp,AdaDelta,AdaGrad,ADAM,Adamax等,这里采用Adam优 TrainerInternal.cpp:160] Batch=20 samples=2560 AvgCost=0.628761 CurrentCost=0.628761 Eval: classification_error_evaluator=0.304297 CurrentEval: classification_error_evaluator=0.304297 -模型训练会看到这样的日志,详细的参数解释如下面表格: +模型训练会看到类似上面这样的日志信息,详细的参数解释,请参考如下表格: - =========================================== ========================================================== + =========================================== ============================================================== 名称 解释 - =========================================== ========================================================== + =========================================== ============================================================== Batch=20 表示过了20个batch samples=2560 表示过了2560个样本 AvgCost 每个pass的第0个batch到当前batch所有样本的平均cost CurrentCost 当前log_period个batch所有样本的平均cost Eval: classification_error_evaluator 每个pass的第0个batch到当前batch所有样本的平均分类错误率 CurrentEval: classification_error_evaluator 当前log_period个batch所有样本的平均分类错误率 - =========================================== ========================================================== + =========================================== ============================================================== From d853a43f67cc91c3b50dbbe04cc0a7853c3fabd6 Mon Sep 17 00:00:00 2001 From: liaogang Date: Mon, 28 Nov 2016 16:41:33 +0800 Subject: [PATCH 03/11] Refine quick start index.rst --- doc_cn/demo/quick_start/index.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/doc_cn/demo/quick_start/index.rst b/doc_cn/demo/quick_start/index.rst index 08c1c8413b..b38b8ca999 100644 --- a/doc_cn/demo/quick_start/index.rst +++ b/doc_cn/demo/quick_start/index.rst @@ -48,6 +48,11 @@ PaddlePaddle快速入门教程 ./data/get_data.sh ./preprocess.sh +数据预处理完成之后,通过配置类似于 ``dataprovider_*.py`` 的数据读取脚本和类似于 ``trainer_config.*.py`` 的训练模型脚本,PaddlePaddle将以设置参数的方式来设置 +相应的数据读取脚本和训练模型脚本。接下来,我们将对这两个步骤给出了详细的解释,你也可以先跳过本文的解释环节,直接进入训练环节, 使用 ``sh train.sh`` 开始训练模型, +查看`train.sh`内容,通过 **自底向上法** (bottom-up approach)来帮助你理解PaddlePaddle的内部运行机制。 + + 向系统传送数据 ============== From 11f97c93b2a0ffa4a6eb23e7af3439e5d5b8c224 Mon Sep 17 00:00:00 2001 From: liaogang Date: Mon, 28 Nov 2016 19:45:54 +0800 Subject: [PATCH 04/11] Change explicit code into literalinclude syntax --- doc_cn/demo/quick_start/index.rst | 85 ++++--------------------------- 1 file changed, 11 insertions(+), 74 deletions(-) diff --git a/doc_cn/demo/quick_start/index.rst b/doc_cn/demo/quick_start/index.rst index b38b8ca999..db73cb3f34 100644 --- a/doc_cn/demo/quick_start/index.rst +++ b/doc_cn/demo/quick_start/index.rst @@ -49,7 +49,7 @@ PaddlePaddle快速入门教程 ./preprocess.sh 数据预处理完成之后,通过配置类似于 ``dataprovider_*.py`` 的数据读取脚本和类似于 ``trainer_config.*.py`` 的训练模型脚本,PaddlePaddle将以设置参数的方式来设置 -相应的数据读取脚本和训练模型脚本。接下来,我们将对这两个步骤给出了详细的解释,你也可以先跳过本文的解释环节,直接进入训练环节, 使用 ``sh train.sh`` 开始训练模型, +相应的数据读取脚本和训练模型脚本。接下来,我们将对这两个步骤给出了详细的解释,你也可以先跳过本文的解释环节,直接进入训练模型章节, 使用 ``sh train.sh`` 开始训练模型, 查看`train.sh`内容,通过 **自底向上法** (bottom-up approach)来帮助你理解PaddlePaddle的内部运行机制。 @@ -66,86 +66,23 @@ Python脚本读取数据 ``dataprovider_bow.py`` 文件给出了完整例子: -.. code-block:: python - - from paddle.trainer.PyDataProvider2 import * - - # id of the word not in dictionary - UNK_IDX = 0 - - # initializer is called by the framework during initialization. - # It allows the user to describe the data types and setup the - # necessary data structure for later use. - # `settings` is an object. initializer need to properly fill settings.input_types. - # initializer can also store other data structures needed to be used at process(). - # In this example, dictionary is stored in settings. - # `dictionay` and `kwargs` are arguments passed from trainer_config.lr.py - def initializer(settings, dictionary, **kwargs): - # Put the word dictionary into settings - settings.word_dict = dictionary +.. literalinclude:: ../../../demo/quick_start/dataprovider_bow.py + :language: python + :lines: 21-70 + :linenos: + :emphasize-lines: 8,33 - # setting.input_types specifies what the data types the data provider - # generates. - settings.input_types = [ - # The first input is a sparse_binary_vector, - # which means each dimension of the vector is either 0 or 1. It is the - # bag-of-words (BOW) representation of the texts. - sparse_binary_vector(len(dictionary)), - # The second input is an integer. It represents the category id of the - # sample. 2 means there are two labels in the dataset. - # (1 for positive and 0 for negative) - integer_value(2)] - - # Delaring a data provider. It has an initializer 'data_initialzer'. - # It will cache the generated data of the first pass in memory, so that - # during later pass, no on-the-fly data generation will be needed. - # `setting` is the same object used by initializer() - # `file_name` is the name of a file listed train_list or test_list file given - # to define_py_data_sources2(). See trainer_config.lr.py. - @provider(init_hook=initializer, cache=CacheType.CACHE_PASS_IN_MEM) - def process(settings, file_name): - # Open the input data file. - with open(file_name, 'r') as f: - # Read each line. - for line in f: - # Each line contains the label and text of the comment, separated by \t. - label, comment = line.strip().split('\t') - - # Split the words into a list. - words = comment.split() - - # convert the words into a list of ids by looking them up in word_dict. - word_vector = [settings.word_dict.get(w, UNK_IDX) for w in words] - - # Return the features for the current comment. The first is a list - # of ids representing a 0-1 binary sparse vector of the text, - # the second is the integer id of the label. - yield word_vector, int(label) 配置中的数据加载定义 -------------------- 在模型配置中通过 ``define_py_data_sources2`` 接口来加载数据: -.. code-block:: python - - from paddle.trainer_config_helpers import * - - file = "data/dict.txt" - word_dict = dict() - with open(dict_file, 'r') as f: - for i, line in enumerate(f): - w = line.strip().split()[0] - word_dict[w] = i - # define the data sources for the model. - # We need to use different process for training and prediction. - # For training, the input data includes both word IDs and labels. - # For prediction, the input data only includs word Ids. - define_py_data_sources2(train_list='data/train.list', - test_list='data/test.list', - module="dataprovider_bow", - obj="process", - args={"dictionary": word_dict}) +.. literalinclude:: ../../../demo/quick_start/trainer_config.emb.py + :language: python + :lines: 19-35 + :linenos: + :emphasize-lines: 12 以下是对上述数据加载的解释: From 63df7ae65d5f003f0166d5a403991b73081db83f Mon Sep 17 00:00:00 2001 From: liaogang Date: Wed, 30 Nov 2016 12:51:13 +0800 Subject: [PATCH 05/11] Refine docker install doc and FAQ for gpu driver --- .../build_and_install/docker_install.rst | 33 +++++++++++++------ .../install/docker_install.rst | 33 ++++++++++++++----- doc_cn/faq/index.rst | 15 +++++++++ 3 files changed, 63 insertions(+), 18 deletions(-) diff --git a/doc/getstarted/build_and_install/docker_install.rst b/doc/getstarted/build_and_install/docker_install.rst index e95de35f4d..88d8357304 100644 --- a/doc/getstarted/build_and_install/docker_install.rst +++ b/doc/getstarted/build_and_install/docker_install.rst @@ -56,25 +56,38 @@ The PaddlePaddle images don't contain any entry command. You need to write your Download and Run Docker images ------------------------------ -You have to install Docker in your machine which has linux kernel version 3.10+ first. You can refer to the official guide https://docs.docker.com/engine/installation/ for further information. +Currently, Docker is supported on macOS, Windows and Linux distributions. Please check out `Install Docker Engine `_ to find out much more details. -You can use :code:`docker pull ` to download images first, or just launch a container with :code:`docker run` \: +PaddlePaddle on CPU +..................... -.. code-block:: bash +You can use :code:`docker pull ` to download images, or directly launch a container with :code:`docker run` \: - docker run -it paddledev/paddle:cpu-latest + .. code-block:: bash + docker run -it paddledev/paddle:cpu-latest -If you want to launch container with GPU support, you need to set some environment variables at the same time: +PaddlePaddle on GPU +..................... -.. code-block:: bash +To build GPU version, you will need the following installed: + + .. code-block:: bash + + 1. a CUDA-capable GPU + 2. NVIDIA CUDA Toolkit (available at http://developer.nvidia.com/cuda-downloads) + + +Then, you will need to mount related CUDA driver and library into container. + + .. code-block:: bash - export CUDA_SO="$(\ls /usr/lib64/libcuda* | xargs -I{} echo '-v {}:{}') $(\ls /usr/lib64/libnvidia* | xargs -I{} echo '-v {}:{}')" - export DEVICES=$(\ls /dev/nvidia* | xargs -I{} echo '--device {}:{}') - docker run ${CUDA_SO} ${DEVICES} -it paddledev/paddle:gpu-latest + export CUDA_SO="$(\ls /usr/lib64/libcuda* | xargs -I{} echo '-v {}:{}') $(\ls /usr/lib64/libnvidia* | xargs -I{} echo '-v {}:{}')" + export DEVICES=$(\ls /dev/nvidia* | xargs -I{} echo '--device {}:{}') + docker run ${CUDA_SO} ${DEVICES} -it paddledev/paddle:gpu-latest -Some notes for docker +Some notes for Docker --------------------- Performance diff --git a/doc_cn/build_and_install/install/docker_install.rst b/doc_cn/build_and_install/install/docker_install.rst index 40339659be..90a5c93709 100644 --- a/doc_cn/build_and_install/install/docker_install.rst +++ b/doc_cn/build_and_install/install/docker_install.rst @@ -60,21 +60,38 @@ mac osx或者是windows机器,请参考 `mac osx的安装文档 `_ 和 `windows 的安装文档 `_ 。 + +启动CPU版Docker镜像 +................... + 您可以使用 :code:`docker pull` 命令预先下载镜像,也可以直接执行 :code:`docker run` 命令运行镜像。执行方法如下: -.. code-block:: bash + .. code-block:: bash + + $ docker run -it paddledev/paddlepaddle:cpu-latest + +即可启动和进入PaddlePaddle的container。 + +启动GPU版Docker镜像 +................... + +首先, 请参考以下链接,在机器上安装CUDA Toolkit。 + + .. code-block:: bash - $ docker run -it paddledev/paddle:cpu-latest + NVIDIA CUDA Toolkit (available at http://developer.nvidia.com/cuda-downloads) -即可启动和进入PaddlePaddle的container。如果运行GPU版本的PaddlePaddle,则需要先将 -cuda相关的Driver和设备映射进container中,脚本类似于 +其次,需要将cuda相关的驱动和设备映射进container中,脚本类似于 -.. code-block:: bash + .. code-block:: bash + + $ export CUDA_SO="$(\ls /usr/lib64/libcuda* | xargs -I{} echo '-v {}:{}') $(\ls /usr/lib64/libnvidia* | xargs -I{} echo '-v {}:{}')" + $ export DEVICES=$(\ls /dev/nvidia* | xargs -I{} echo '--device {}:{}') + $ docker run ${CUDA_SO} ${DEVICES} -it paddledev/paddlepaddle:latest-gpu - $ export CUDA_SO="$(\ls /usr/lib64/libcuda* | xargs -I{} echo '-v {}:{}') $(\ls /usr/lib64/libnvidia* | xargs -I{} echo '-v {}:{}')" - $ export DEVICES=$(\ls /dev/nvidia* | xargs -I{} echo '--device {}:{}') - $ docker run ${CUDA_SO} ${DEVICES} -it paddledev/paddle:gpu-latest +使用PaddlePaddle +.................. 进入Docker container后,运行 :code:`paddle version` 即可打印出PaddlePaddle的版本和构建 信息。安装完成的PaddlePaddle主体包括三个部分, :code:`paddle` 脚本, python的 diff --git a/doc_cn/faq/index.rst b/doc_cn/faq/index.rst index 551430eb41..838fa651d8 100644 --- a/doc_cn/faq/index.rst +++ b/doc_cn/faq/index.rst @@ -202,3 +202,18 @@ PaddlePaddle的参数使用名字 :code:`name` 作为参数的ID,相同名字 解决办法是: * 卸载PaddlePaddle包 :code:`pip uninstall paddle`, 清理掉老旧的PaddlePaddle安装包,使得单元测试有一个干净的环境。如果PaddlePaddle包已经在python的site-packages里面,单元测试会引用site-packages里面的python包,而不是源码目录里 :code:`/python` 目录下的python包。同时,即便设置 :code:`PYTHONPATH` 到 :code:`/python` 也没用,因为python的搜索路径是优先已经安装的python包。 + + +9. 运行Docker GPU镜像出现 "CUDA driver version is insufficient" +---------------------------------------------------------------- + +用户在使用PaddlePaddle GPU的Docker镜像的时候,常常出现 `Cuda Error: CUDA driver version is insufficient for CUDA runtime version`, 原因在于没有把机器上CUDA相关的驱动和库映射到容器内部。 +具体的解决方法是: + +.. code-block:: bash + + $ export CUDA_SO="$(\ls usr/lib64/libcuda* | xargs -I{} echo '-v {}:{}') $(\ls /usr/lib64/libnvidia* | xargs -I{} echo '-v {}:{}')" + $ export DEVICES=$(\ls /dev/nvidia* | xargs -I{} echo '--device {}:{}') + $ docker run ${CUDA_SO} ${DEVICES} -it paddledev/paddlepaddle:latest-gpu + +更多关于Docker的安装与使用, 请参考 `PaddlePaddle Docker 文档 `_ 。 From f340f37f021274598c2561e2346987ec50463541 Mon Sep 17 00:00:00 2001 From: liaogang Date: Wed, 30 Nov 2016 20:00:51 +0800 Subject: [PATCH 06/11] Change atomicAdd to paddleAtomicAdd --- paddle/cuda/src/hl_cuda_cnn.cu | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/paddle/cuda/src/hl_cuda_cnn.cu b/paddle/cuda/src/hl_cuda_cnn.cu index ae387a8bc0..7f2f6897b4 100644 --- a/paddle/cuda/src/hl_cuda_cnn.cu +++ b/paddle/cuda/src/hl_cuda_cnn.cu @@ -16,6 +16,7 @@ limitations under the License. */ #include #include "hl_base.h" #include "hl_cnn.h" +#include "hl_device_functions.cuh" __global__ void KeFeature2col(size_t n, size_t height, const real* data_im, size_t blockH, size_t blockW, size_t width, @@ -641,10 +642,10 @@ __global__ void KeBilinearInterpBw(real* in, real* inPos = &in[outIdH * inputW + channelId * inImgSize + inImgIdy * inImgW + inImgIdx]; const real* outPos = &out[outIdH * outputW + outIdW]; - atomicAdd(&inPos[0], h2lambda * w2lambda * outPos[0]); - atomicAdd(&inPos[wId], h2lambda * w1lambda * outPos[0]); - atomicAdd(&inPos[hId * inImgW], h1lambda * w2lambda * outPos[0]); - atomicAdd(&inPos[hId * inImgW + wId], h1lambda * w1lambda * outPos[0]); + paddle::paddleAtomicAdd(&inPos[0], h2lambda * w2lambda * outPos[0]); + paddle::paddleAtomicAdd(&inPos[wId], h2lambda * w1lambda * outPos[0]); + paddle::paddleAtomicAdd(&inPos[hId * inImgW], h1lambda * w2lambda * outPos[0]); + paddle::paddleAtomicAdd(&inPos[hId * inImgW + wId], h1lambda * w1lambda * outPos[0]); } } From 26b2996b0ac231a1df54d5a1c9b6ce258dcd6fa8 Mon Sep 17 00:00:00 2001 From: liaogang Date: Mon, 5 Dec 2016 16:57:09 +0800 Subject: [PATCH 07/11] =?UTF-8?q?Upgrade=20compiler=E2=80=98s=20minimum=20?= =?UTF-8?q?version?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * for modern language properties --- CMakeLists.txt | 13 ++--------- cmake/enableCXX11.cmake | 13 ----------- cmake/flags.cmake | 46 +++++++++++++++++++++++++++++++++++--- paddle/cuda/CMakeLists.txt | 3 --- 4 files changed, 45 insertions(+), 30 deletions(-) delete mode 100644 cmake/enableCXX11.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index 7b42423749..5b36088b75 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -51,13 +51,7 @@ option(ON_TRAVIS "Running test on travis-ci or not." OFF) option(ON_COVERALLS "Generating code coverage data on coveralls or not." OFF) option(COVERALLS_UPLOAD "Uploading the generated coveralls json." ON) -if(NOT CMAKE_BUILD_TYPE) - set(CMAKE_BUILD_TYPE "RelWithDebInfo" CACHE STRING - "Choose the type of build, options are: Debug Release RelWithDebInfo MinSizeRel" - FORCE) -endif() -include(enableCXX11) include(cpplint) include(ccache) if(WITH_RDMA) @@ -84,17 +78,14 @@ if(NOT WITH_GPU) list(APPEND CMAKE_CXX_SOURCE_FILE_EXTENSIONS cu) else() if(${CUDA_VERSION_MAJOR} GREATER 6) - if(COMPILER_SUPPORT_CXX11) - LIST(APPEND CUDA_NVCC_FLAGS -std=c++11) - endif() + LIST(APPEND CUDA_NVCC_FLAGS -std=c++11) endif() - # TODO(yuyang18): Change it to remove std=c++11 in cuda compile. set(CUDA_PROPAGATE_HOST_FLAGS OFF) + if(NOT CUDNN_FOUND) message(FATAL_ERROR "Paddle need cudnn to compile") endif() - set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS} "-g -O3 --use_fast_math") if(WITH_AVX) set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS} "-Xcompiler ${AVX_FLAG}") diff --git a/cmake/enableCXX11.cmake b/cmake/enableCXX11.cmake deleted file mode 100644 index dc8cc3371a..0000000000 --- a/cmake/enableCXX11.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# Enable C++ 11 for GCC. -# NOTE: It's only tested for gcc. -include(CheckCXXCompilerFlag) -CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORT_CXX11) -CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORT_CXX0X) - -if(COMPILER_SUPPORT_CXX11) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") -elseif(COMPILER_SUPPORT_CXX0X) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") -else() - message(FATAL_ERROR "Your compiler must support c++11") -endif() \ No newline at end of file diff --git a/cmake/flags.cmake b/cmake/flags.cmake index e087770991..4531efb1d5 100644 --- a/cmake/flags.cmake +++ b/cmake/flags.cmake @@ -2,6 +2,37 @@ include(CheckCXXCompilerFlag) include(CheckCCompilerFlag) include(CheckCXXSymbolExists) + +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE "RelWithDebInfo" CACHE STRING + "Choose the type of build, options are: Debug Release RelWithDebInfo MinSizeRel" + FORCE) +endif() + +function(CheckCompilerCXX11Flag) + if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + if(${CMAKE_CXX_COMPILER_VERSION} VERSION_LESS 4.8) + message(FATAL_ERROR "Unsupported GCC version. GCC >= 4.8 required.") + endif() + elseif(CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang" OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + # cmake >= 3.0 compiler id "AppleClang" on Mac OS X, otherwise "Clang" + # Apple Clang is a different compiler than upstream Clang which havs different version numbers. + # https://gist.github.com/yamaya/2924292 + if(APPLE) # cmake < 3.0 compiler id "Clang" on Mac OS X + if(${CMAKE_CXX_COMPILER_VERSION} VERSION_LESS 5.1) + message(FATAL_ERROR "Unsupported AppleClang version. AppleClang >= 5.1 required.") + endif() + else() + if (${CMAKE_CXX_COMPILER_VERSION} VERSION_LESS 3.3) + message(FATAL_ERROR "Unsupported Clang version. Clang >= 3.3 required.") + endif() + endif() + endif() +endfunction() + +CheckCompilerCXX11Flag() +LIST(APPEND CMAKE_CXX_FLAGS -std=c++11) + # safe_set_flag # # Set a compile flag only if compiler is support @@ -41,9 +72,7 @@ macro(safe_set_nvflag flag_name) CHECK_C_COMPILER_FLAG(${flag_name} C_COMPILER_SUPPORT_FLAG_${safe_name}) set(safe_name C_COMPILER_SUPPORT_FLAG_${safe_name}) if(${safe_name}) - set(CUDA_NVCC_FLAGS - --compiler-options;${flag_name} - ${CUDA_NVCC_FLAGS}) + LIST(APPEND CUDA_NVCC_FLAGS -Xcompiler ${flag_name}) endif() endmacro() @@ -111,6 +140,17 @@ endforeach() # Release/Debug flags set by cmake. Such as -O3 -g -DNDEBUG etc. # So, don't set these flags here. +LIST(APPEND CUDA_NVCC_FLAGS --use_fast_math) + +if(CMAKE_BUILD_TYPE STREQUAL "Debug") + LIST(APPEND CUDA_NVCC_FLAGS ${CMAKE_CXX_FLAGS_DEBUG}) +elseif(CMAKE_BUILD_TYPE STREQUAL "Release") + LIST(APPEND CUDA_NVCC_FLAGS ${CMAKE_CXX_FLAGS_RELEASE}) +elseif(CMAKE_BUILD_TYPE STREQUAL "RelWithDebInfo") + LIST(APPEND CUDA_NVCC_FLAGS ${CMAKE_CXX_FLAGS_RELWITHDEBINFO}) +elseif(CMAKE_BUILD_TYPE STREQUAL "MinSizeRel") + LIST(APPEND CUDA_NVCC_FLAGS ${CMAKE_CXX_FLAGS_MINSIZEREL}) +endif() function(specify_cuda_arch cuda_version cuda_arch) if(${cuda_version} VERSION_GREATER "8.0") diff --git a/paddle/cuda/CMakeLists.txt b/paddle/cuda/CMakeLists.txt index 11dbfb54b2..2a1eb307de 100755 --- a/paddle/cuda/CMakeLists.txt +++ b/paddle/cuda/CMakeLists.txt @@ -22,9 +22,6 @@ set(CUDA_CXX_WITH_GPU_SOURCES set_source_files_properties(${CUDA_CXX_WITH_GPU_SOURCES} PROPERTIES COMPILE_FLAGS "-D__NVCC__") -set_source_files_properties(${AVX_SOURCES} - PROPERTIES COMPILE_FLAGS "-mavx") - set(CUDA_DSO_SOURCES src/hl_dso_loader.cc src/hl_cudart_wrap.cc) From aef68475b8f9b31641d94c6fb61c2d03dc881d1b Mon Sep 17 00:00:00 2001 From: liaogang Date: Mon, 5 Dec 2016 17:21:27 +0800 Subject: [PATCH 08/11] Add docs for compiler version --- doc/getstarted/build_and_install/build_from_source.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/doc/getstarted/build_and_install/build_from_source.md b/doc/getstarted/build_and_install/build_from_source.md index b932fbc0fa..a71a9c3143 100644 --- a/doc/getstarted/build_and_install/build_from_source.md +++ b/doc/getstarted/build_and_install/build_from_source.md @@ -15,13 +15,15 @@ cd paddle ## Requirements -To compile the source code, your computer must be equipped with GCC >=4.6 or Clang compiler. +To compile the source code, your computer must be equipped with the following dependencies. + ### Dependencies +- **Compiler**: GCC >= 4.8 or Clang >= 3.3 (AppleClang >= 5.1) - **CMake**: version >= 2.8 - **BLAS**: MKL, OpenBlas or ATLAS -- **protobuf**: version >= 2.4, **Note: 3.x is not supported** -- **python**: only python 2.7 is supported currently +- **Protocol Buffers**: version >= 2.4, **Note: 3.x is not supported** +- **Python**: only python 2.7 is supported currently ### Options From 4453d767593d15d8f6486a1e99bc7a0482081178 Mon Sep 17 00:00:00 2001 From: liaogang Date: Tue, 6 Dec 2016 14:01:54 +0800 Subject: [PATCH 09/11] Upgrade cuda minimum version to 7.0 --- CMakeLists.txt | 6 ++---- cmake/flags.cmake | 3 +++ doc/getstarted/build_and_install/build_from_source.md | 9 +++++---- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5b36088b75..ba6fb95315 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -77,12 +77,10 @@ if(NOT WITH_GPU) add_definitions(-DHPPL_STUB_FUNC) list(APPEND CMAKE_CXX_SOURCE_FILE_EXTENSIONS cu) else() - if(${CUDA_VERSION_MAJOR} GREATER 6) - LIST(APPEND CUDA_NVCC_FLAGS -std=c++11) + if(${CUDA_VERSION_MAJOR} VERSION_LESS 7) + message(FATAL_ERROR "Paddle need CUDA >= 7.0 to compile") endif() - set(CUDA_PROPAGATE_HOST_FLAGS OFF) - if(NOT CUDNN_FOUND) message(FATAL_ERROR "Paddle need cudnn to compile") endif() diff --git a/cmake/flags.cmake b/cmake/flags.cmake index 4531efb1d5..0983d83b73 100644 --- a/cmake/flags.cmake +++ b/cmake/flags.cmake @@ -138,8 +138,11 @@ foreach(flag ${GPU_COMMON_FLAGS}) endforeach() +set(CUDA_PROPAGATE_HOST_FLAGS OFF) + # Release/Debug flags set by cmake. Such as -O3 -g -DNDEBUG etc. # So, don't set these flags here. +LIST(APPEND CUDA_NVCC_FLAGS -std=c++11) LIST(APPEND CUDA_NVCC_FLAGS --use_fast_math) if(CMAKE_BUILD_TYPE STREQUAL "Debug") diff --git a/doc/getstarted/build_and_install/build_from_source.md b/doc/getstarted/build_and_install/build_from_source.md index a71a9c3143..92389905e5 100644 --- a/doc/getstarted/build_and_install/build_from_source.md +++ b/doc/getstarted/build_and_install/build_from_source.md @@ -17,14 +17,15 @@ cd paddle To compile the source code, your computer must be equipped with the following dependencies. -### Dependencies - - **Compiler**: GCC >= 4.8 or Clang >= 3.3 (AppleClang >= 5.1) - **CMake**: version >= 2.8 - **BLAS**: MKL, OpenBlas or ATLAS - **Protocol Buffers**: version >= 2.4, **Note: 3.x is not supported** - **Python**: only python 2.7 is supported currently +**Note:** For CUDA 7.0 and CUDA 7.5, GCC 5.0 and up are not supported! +For CUDA 8.0, GCC versions later than 5.3 are not supported! + ### Options PaddlePaddle supports some build options. To enable it, first you need to install the related libraries. @@ -51,8 +52,8 @@ PaddlePaddle supports some build options. To enable it, first you need to instal **Note:** - - The GPU version works best with Cuda Toolkit 7.5 and cuDNN v5. - - Other versions like Cuda Toolkit 6.5, 7.0, 8.0 and cuDNN v2, v3, v4 are also supported. + - The GPU version works best with Cuda Toolkit 8.0 and cuDNN v5. + - Other versions like Cuda Toolkit 7.0, 7.5 and cuDNN v3, v4 are also supported. - **To utilize cuDNN v5, Cuda Toolkit 7.5 is prerequisite and vice versa.** As a simple example, consider the following: From 75351f586d08c110f0dd2489a29875f4fc77eef9 Mon Sep 17 00:00:00 2001 From: gangliao Date: Tue, 6 Dec 2016 14:17:18 +0800 Subject: [PATCH 10/11] Revert test_Matrix.cpp when merge with the develop branch, some mistakes happened --- paddle/math/tests/{test_matrix.cpp => test_Matrix.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename paddle/math/tests/{test_matrix.cpp => test_Matrix.cpp} (100%) diff --git a/paddle/math/tests/test_matrix.cpp b/paddle/math/tests/test_Matrix.cpp similarity index 100% rename from paddle/math/tests/test_matrix.cpp rename to paddle/math/tests/test_Matrix.cpp From dc577f0e79471ff422a097b880a2a07f8674e65a Mon Sep 17 00:00:00 2001 From: liaogang Date: Thu, 8 Dec 2016 14:36:51 +0800 Subject: [PATCH 11/11] Add links for terminology --- doc_cn/demo/quick_start/index.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_cn/demo/quick_start/index.rst b/doc_cn/demo/quick_start/index.rst index db73cb3f34..0536936dc4 100644 --- a/doc_cn/demo/quick_start/index.rst +++ b/doc_cn/demo/quick_start/index.rst @@ -242,7 +242,7 @@ embedding模型需要稍微改变提供数据的Python脚本,即 ``dataprovide :align: center :scale: 80% -时序模型,也称为RNN模型, 包括简单的RNN模型, GRU模型和LSTM模型等等。 +时序模型,也称为RNN模型, 包括简单的 `RNN模型 `_, `GRU模型 `_ 和 `LSTM模型 `_ 等等。 - GRU模型配置: @@ -269,7 +269,7 @@ embedding模型需要稍微改变提供数据的Python脚本,即 ``dataprovide ========= `优化算法 `_ 包括 -Momentum, RMSProp,AdaDelta,AdaGrad,ADAM,Adamax等,这里采用Adam优化方法,同时使用了L2正则和梯度截断。 +Momentum, RMSProp,AdaDelta,AdaGrad,ADAM,Adamax等,这里采用Adam优化方法,同时使用了L2正则(L2 Regularization)和梯度截断(Gradient Clipping)。 .. code-block:: python