Skip to content

Commit 81e2579

Browse files
authored
Merge pull request #538 from gangliao/latest
Refine quick start index.rst chinese docs
2 parents db37981 + bedf7bf commit 81e2579

File tree

1 file changed

+395
-0
lines changed

1 file changed

+395
-0
lines changed

doc_cn/demo/quick_start/index.rst

+395
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,395 @@
1+
PaddlePaddle快速入门教程
2+
========================
3+
4+
我们将以 `文本分类问题 <https://en.wikipedia.org/wiki/Document_classification>`_ 为例,
5+
介绍PaddlePaddle的基本使用方法。
6+
7+
安装
8+
====
9+
10+
请参考 `安装教程 <../../build_and_install/index.html>`_ 安装PaddlePaddle。
11+
12+
使用概述
13+
========
14+
15+
**文本分类问题**:对于给定的一条文本,我们从提前给定的类别集合中选择其所属类别。
16+
17+
比如, 在购物网站上,通过查看买家对某个产品的评价反馈, 评估该产品的质量。
18+
19+
- 这个显示器很棒! (好评)
20+
- 用了两个月之后这个显示器屏幕碎了。(差评)
21+
22+
使用PaddlePaddle, 每一个任务流程都可以被划分为如下五个步骤。
23+
24+
.. image:: Pipeline.jpg
25+
:align: center
26+
:scale: 80%
27+
28+
1. 数据格式准备
29+
- 本例每行保存一条样本,类别Id和文本信息用 ``Tab`` 间隔,文本中的单词用空格分隔(如果不切词,则字与字之间用空格分隔),例如:``类别Id '\t' 这 个 显 示 器 很 棒 !``
30+
2. 向系统传送数据
31+
- PaddlePaddle可以执行用户的python脚本程序来读取各种格式的数据文件。
32+
- 本例的所有字符都将转换为连续整数表示的Id传给模型。
33+
3. 描述网络结构和优化算法
34+
- 本例由易到难展示4种不同的文本分类网络配置:逻辑回归模型,词向量模型,卷积模型,时序模型。
35+
- 常用优化算法包括Momentum, RMSProp,AdaDelta,AdaGrad,Adam,Adamax等,本例采用Adam优化方法,加了L2正则和梯度截断。
36+
4. 训练模型
37+
5. 应用模型
38+
39+
数据格式准备
40+
------------
41+
42+
接下来我们将展示如何用PaddlePaddle训练一个文本分类模型,将 `Amazon电子产品评论数据 <http://jmcauley.ucsd.edu/data/amazon/>`_ 分为好评(正样本)和差评(负样本)两种类别。
43+
`源代码 <https://github.com/PaddlePaddle/Paddle>`_ 的 ``demo/quick_start`` 目录里提供了该数据的下载脚本和预处理脚本,你只需要在命令行输入以下命令,就能够很方便的完成数据下载和相应的预处理工作。
44+
45+
.. code-block:: bash
46+
47+
cd demo/quick_start
48+
./data/get_data.sh
49+
./preprocess.sh
50+
51+
数据预处理完成之后,通过配置类似于 ``dataprovider_*.py`` 的数据读取脚本和类似于 ``trainer_config.*.py`` 的训练模型脚本,PaddlePaddle将以设置参数的方式来设置
52+
相应的数据读取脚本和训练模型脚本。接下来,我们将对这两个步骤给出了详细的解释,你也可以先跳过本文的解释环节,直接进入训练模型章节, 使用 ``sh train.sh`` 开始训练模型,
53+
查看`train.sh`内容,通过 **自底向上法** (bottom-up approach)来帮助你理解PaddlePaddle的内部运行机制。
54+
55+
56+
向系统传送数据
57+
==============
58+
59+
Python脚本读取数据
60+
------------------
61+
62+
`DataProvider <../../ui/data_provider/index.html>`_ 是PaddlePaddle负责提供数据的模块。``DataProvider`` 主要职责在于将训练数据传入内存或者显存,让模型能够得到训练更新,其包括两个函数:
63+
64+
* initializer:PaddlePaddle会在调用读取数据的Python脚本之前,先调用initializer函数。在下面例子里,我们在initialzier函数里初始化词表,并且在随后的读取数据过程中填充词表。
65+
* process:PaddlePaddle调用process函数来读取数据。每次读取一条数据后,process函数会用yield语句输出这条数据,从而能够被PaddlePaddle 捕获 (harvest)。
66+
67+
``dataprovider_bow.py`` 文件给出了完整例子:
68+
69+
.. literalinclude:: ../../../demo/quick_start/dataprovider_bow.py
70+
:language: python
71+
:lines: 21-70
72+
:linenos:
73+
:emphasize-lines: 8,33
74+
75+
76+
配置中的数据加载定义
77+
--------------------
78+
79+
在模型配置中通过 ``define_py_data_sources2`` 接口来加载数据:
80+
81+
.. literalinclude:: ../../../demo/quick_start/trainer_config.emb.py
82+
:language: python
83+
:lines: 19-35
84+
:linenos:
85+
:emphasize-lines: 12
86+
87+
88+
以下是对上述数据加载的解释:
89+
90+
- data/train.list,data/test.list: 指定训练数据和测试数据
91+
- module="dataprovider_bow": 处理数据的Python脚本文件
92+
- obj="process": 指定生成数据的函数
93+
- args={"dictionary": word_dict}: 额外的参数,这里指定词典
94+
95+
更详细数据格式和用例请参考 `PyDataProvider2 <../../ui/data_provider/pydataprovider2.html>`_ 。
96+
97+
模型网络结构
98+
============
99+
100+
本小节我们将介绍模型网络结构。
101+
102+
.. image:: PipelineNetwork.jpg
103+
:align: center
104+
:scale: 80%
105+
106+
107+
我们将以最基本的逻辑回归网络作为起点,并逐渐展示更加深入的功能。更详细的网络配置连接请参考 `Layer文档 <../../../doc/layer.html>`_ 。
108+
所有配置都能在 `源代码 <https://github.com/PaddlePaddle/Paddle>`_ 的 ``demo/quick_start`` 目录下找到。
109+
110+
逻辑回归模型
111+
------------
112+
113+
具体流程如下:
114+
115+
.. image:: NetLR.jpg
116+
:align: center
117+
:scale: 80%
118+
119+
- 获取利用 `one-hot vector <https://en.wikipedia.org/wiki/One-hot>`_ 表示的每个单词,维度是词典大小
120+
121+
.. code-block:: python
122+
123+
word = data_layer(name="word", size=word_dim)
124+
125+
- 获取该条样本类别Id,维度是类别个数。
126+
127+
.. code-block:: python
128+
129+
label = data_layer(name="label", size=label_dim)
130+
131+
- 利用逻辑回归模型对该向量进行分类,同时会计算分类准确率
132+
133+
.. code-block:: python
134+
135+
# Define a fully connected layer with logistic activation (also called softmax activation).
136+
output = fc_layer(input=word,
137+
size=label_dim,
138+
act_type=SoftmaxActivation())
139+
# Define cross-entropy classification loss and error.
140+
classification_cost(input=output, label=label)
141+
142+
143+
- input: 除去data层,每个层都有一个或多个input,多个input以list方式输入
144+
- size: 该层神经元个数
145+
- act_type: 激活函数类型
146+
147+
**效果总结**:我们将在后面介绍训练和预测流程的脚本。在此为方便对比不同网络结构,我们总结了各个网络的复杂度和效果。
148+
149+
===================== =============================== =================
150+
网络名称 参数数量 错误率
151+
===================== =============================== =================
152+
逻辑回归 252 KB 8.652 %
153+
===================== =============================== =================
154+
155+
词向量模型
156+
----------
157+
158+
embedding模型需要稍微改变提供数据的Python脚本,即 ``dataprovider_emb.py``,词向量模型、
159+
卷积模型、时序模型均使用该脚本。其中文本输入类型定义为整数时序类型integer_value_sequence。
160+
161+
.. code-block:: python
162+
163+
def initializer(settings, dictionary, **kwargs):
164+
settings.word_dict = dictionary
165+
settings.input_types = [
166+
# Define the type of the first input as sequence of integer.
167+
# The value of the integers range from 0 to len(dictrionary)-1
168+
integer_value_sequence(len(dictionary)),
169+
# Define the second input for label id
170+
integer_value(2)]
171+
172+
@provider(init_hook=initializer)
173+
def process(settings, file_name):
174+
...
175+
# omitted, it is same as the data provider for LR model
176+
177+
该模型依然使用逻辑回归分类网络的框架, 只是将句子用连续向量表示替换为用稀疏向量表示, 即对第三步进行替换。句子表示的计算更新为两步:
178+
179+
.. image:: NetContinuous.jpg
180+
:align: center
181+
:scale: 80%
182+
183+
- 利用单词Id查找该单词对应的连续向量(维度为word_dim), 输入N个单词,输出为N个word_dim维度向量
184+
185+
.. code-block:: python
186+
187+
emb = embedding_layer(input=word, size=word_dim)
188+
189+
- 将该句话包含的所有单词向量求平均, 得到句子的表示
190+
191+
.. code-block:: python
192+
193+
avg = pooling_layer(input=emb, pooling_type=AvgPooling())
194+
195+
其它部分和逻辑回归网络结构一致。
196+
197+
**效果总结:**
198+
199+
===================== =============================== ==================
200+
网络名称 参数数量 错误率
201+
===================== =============================== ==================
202+
词向量模型 15 MB 8.484 %
203+
===================== =============================== ==================
204+
205+
卷积模型
206+
-----------
207+
208+
卷积网络是一种特殊的从词向量表示到句子表示的方法, 也就是将词向量模型进一步演化为三个新步骤。
209+
210+
.. image:: NetConv.jpg
211+
:align: center
212+
:scale: 80%
213+
214+
文本卷积分可为三个步骤:
215+
216+
1. 首先,从每个单词左右两端分别获取k个相邻的单词, 拼接成一个新的向量;
217+
218+
2. 其次,对该向量进行非线性变换(例如Sigmoid变换), 使其转变为维度为hidden_dim的新向量;
219+
220+
3. 最后,对整个新向量集合的每一个维度取最大值来表示最后的句子。
221+
222+
这三个步骤可配置为:
223+
224+
.. code-block:: python
225+
226+
text_conv = sequence_conv_pool(input=emb,
227+
context_start=k,
228+
context_len=2 * k + 1)
229+
230+
**效果总结:**
231+
232+
===================== =============================== ========================
233+
网络名称 参数数量 错误率
234+
===================== =============================== ========================
235+
卷积模型 16 MB 5.628 %
236+
===================== =============================== ========================
237+
238+
时序模型
239+
----------
240+
241+
.. image:: NetRNN.jpg
242+
:align: center
243+
:scale: 80%
244+
245+
时序模型,也称为RNN模型, 包括简单的 `RNN模型 <https://en.wikipedia.org/wiki/Recurrent_neural_network>`_, `GRU模型 <https://en.wikipedia.org/wiki/Gated_recurrent_unit>`_ 和 `LSTM模型 <https://en.wikipedia.org/wiki/Long_short-term_memory>`_ 等等。
246+
247+
- GRU模型配置:
248+
249+
.. code-block:: python
250+
251+
gru = simple_gru(input=emb, size=gru_size)
252+
253+
254+
- LSTM模型配置:
255+
256+
.. code-block:: python
257+
258+
lstm = simple_lstm(input=emb, size=lstm_size)
259+
260+
本次试验,我们采用单层LSTM模型,并使用了Dropout,**效果总结:**
261+
262+
===================== =============================== =========================
263+
网络名称 参数数量 错误率
264+
===================== =============================== =========================
265+
时序模型 16 MB 4.812 %
266+
===================== =============================== =========================
267+
268+
优化算法
269+
=========
270+
271+
`优化算法 <http://www.paddlepaddle.org/doc/ui/api/trainer_config_helpers/optimizers_index.html>`_ 包括
272+
Momentum, RMSProp,AdaDelta,AdaGrad,ADAM,Adamax等,这里采用Adam优化方法,同时使用了L2正则(L2 Regularization)和梯度截断(Gradient Clipping)。
273+
274+
.. code-block:: python
275+
276+
settings(batch_size=128,
277+
learning_rate=2e-3,
278+
learning_method=AdamOptimizer(),
279+
regularization=L2Regularization(8e-4),
280+
gradient_clipping_threshold=25)
281+
282+
训练模型
283+
=========
284+
285+
在数据加载和网络配置完成之后, 我们就可以训练模型了。
286+
287+
.. image:: PipelineTrain.jpg
288+
:align: center
289+
:scale: 80%
290+
291+
训练模型,我们只需要运行 ``train.sh`` 训练脚本:
292+
293+
.. code-block:: bash
294+
295+
./train.sh
296+
297+
``train.sh``中包含了训练模型的基本命令。训练时所需设置的主要参数如下:
298+
299+
.. code-block:: bash
300+
301+
paddle train \
302+
--config=trainer_config.py \
303+
--log_period=20 \
304+
--save_dir=./output \
305+
--num_passes=15 \
306+
--use_gpu=false
307+
308+
这里只简单介绍了单机训练,如何进行分布式训练,可以参考教程 `分布式训练 <../../cluster/index.html>`_ 。
309+
310+
预测
311+
=====
312+
313+
当模型训练好了之后,我们就可以进行预测了。
314+
315+
.. image:: PipelineTest.jpg
316+
:align: center
317+
:scale: 80%
318+
319+
之前配置文件中 ``test.list`` 指定的数据将会被测试,这里直接通过预测脚本 ``predict.sh`` 进行预测,
320+
更详细的说明,可以参考 `Python API预测 <../../ui/predict/swig_py_paddle.html>`_ 教程。
321+
322+
.. code-block:: bash
323+
324+
model="output/pass-00003"
325+
paddle train \
326+
--config=trainer_config.lstm.py \
327+
--use_gpu=false \
328+
--job=test \
329+
--init_model_path=$model \
330+
--config_args=is_predict=1 \
331+
--predict_output_dir=. \
332+
333+
mv rank-00000 result.txt
334+
335+
这里以 ``output/pass-00003`` 为例进行预测,用户可以根据训练日志,选择测试结果最好的模型来预测。
336+
337+
预测结果以文本的形式保存在 ``result.txt`` 中,一行为一个样本,格式如下:
338+
339+
.. code-block:: bash
340+
341+
预测ID;ID为0的概率 ID为1的概率
342+
预测ID;ID为0的概率 ID为1的概率
343+
344+
总体效果总结
345+
==============
346+
347+
在 ``/demo/quick_start`` 目录下,能够找到这里使用的所有数据, 网络配置, 训练脚本等等。
348+
对于Amazon-Elec测试集(25k), 如下表格,展示了上述网络模型的训练效果:
349+
350+
===================== =============================== ============= ==================================
351+
网络名称 参数数量 错误率 配置文件
352+
===================== =============================== ============= ==================================
353+
逻辑回归模型 252 KB 8.652% trainer_config.lr.py
354+
词向量模型 15 MB 8.484% trainer_config.emb.py
355+
卷积模型 16 MB 5.628% trainer_config.cnn.py
356+
时序模型 16 MB 4.812% trainer_config.lstm.py
357+
===================== =============================== ============= ==================================
358+
359+
360+
附录
361+
=====
362+
363+
命令行参数
364+
----------
365+
366+
* \--config:网络配置
367+
* \--save_dir:模型存储路径
368+
* \--log_period:每隔多少batch打印一次日志
369+
* \--num_passes:训练轮次,一个pass表示过一遍所有训练样本
370+
* \--config_args:命令指定的参数会传入网络配置中。
371+
* \--init_model_path:指定初始化模型路径,可用在测试或训练时指定初始化模型。
372+
373+
默认一个pass保存一次模型,也可以通过saving_period_by_batches设置每隔多少batch保存一次模型。
374+
可以通过show_parameter_stats_period设置打印参数信息等。
375+
其他参数请参考 `命令行参数文档 <../../ui/index.html#command-line-argument>`_ 。
376+
377+
输出日志
378+
---------
379+
380+
.. code-block:: bash
381+
382+
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
383+
384+
模型训练会看到类似上面这样的日志信息,详细的参数解释,请参考如下表格:
385+
386+
=========================================== ==============================================================
387+
名称 解释
388+
=========================================== ==============================================================
389+
Batch=20 表示过了20个batch
390+
samples=2560 表示过了2560个样本
391+
AvgCost 每个pass的第0个batch到当前batch所有样本的平均cost
392+
CurrentCost 当前log_period个batch所有样本的平均cost
393+
Eval: classification_error_evaluator 每个pass的第0个batch到当前batch所有样本的平均分类错误率
394+
CurrentEval: classification_error_evaluator 当前log_period个batch所有样本的平均分类错误率
395+
=========================================== ==============================================================

0 commit comments

Comments
 (0)