# 机器翻译
-本教程源代码目录在[book/machine_translation](https://github.com/PaddlePaddle/book/tree/develop/machine_translation), 初次使用请参考PaddlePaddle[安装教程](http://www.paddlepaddle.org/doc_cn/build_and_install/index.html)。
+本教程源代码目录在[book/machine_translation](https://github.com/PaddlePaddle/book/tree/develop/machine_translation), 初次使用请参考PaddlePaddle[安装教程](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_cn.rst)。
## 背景介绍
@@ -194,54 +194,8 @@ e_{ij}&=align(z_i,h_j)\\\\
## 数据介绍
-### 下载与解压缩
-
本教程使用[WMT-14](http://www-lium.univ-lemans.fr/~schwenk/cslm_joint_paper/)数据集中的[bitexts(after selection)](http://www-lium.univ-lemans.fr/~schwenk/cslm_joint_paper/data/bitexts.tgz)作为训练集,[dev+test data](http://www-lium.univ-lemans.fr/~schwenk/cslm_joint_paper/data/dev+test.tgz)作为测试集和生成集。
-在Linux下,只需简单地运行以下命令:
-
-```bash
-cd data
-./wmt14_data.sh
-```
-
-得到的数据集`data/wmt14`包含如下三个文件夹:
-
-
-
-文件夹名 |
-法英平行语料文件 |
-文件数 |
-文件大小 |
-
-
-
-train |
-ccb2_pc30.src, ccb2_pc30.trg, etc |
-12 |
-3.55G |
-
-
-
-test |
-ntst1213.src, ntst1213.trg |
-2 |
-1636k |
-
-
-
-
-gen |
-ntst14.src, ntst14.trg |
-2 |
-864k |
-
-
-
-
-- `XXX.src`是源法语文件,`XXX.trg`是目标英语文件,文件中的每行存放一个句子
-- `XXX.src`和`XXX.trg`的行数一致,且两者任意第$i$行的句子之间都有着一一对应的关系。
-
### 数据预处理
我们的预处理流程包括两步:
@@ -262,6 +216,7 @@ cd data
```python
# 加载 paddle的python包
+import sys
import paddle.v2 as paddle
# 配置只使用cpu,并且使用一个cpu进行训练
@@ -298,17 +253,16 @@ wmt14_reader = paddle.batch(
decoder_size = 512 # 解码器中的GRU隐层大小
```
-2. 其次,实现编码器框架。分为三步:
+1. 其次,实现编码器框架。分为三步:
- 2.1 将在dataset reader中生成的用每个单词在字典中的索引表示的源语言序列
- 转换成one-hot vector表示的源语言序列$\mathbf{w}$,其类型为integer_value_sequence。
+ 1 输入是一个文字序列,被表示成整型的序列。序列中每个元素是文字在字典中的索引。所以,我们定义数据层的数据类型为`integer_value_sequence`(整型序列),序列中每个元素的范围是`[0, source_dict_dim)`。
```python
src_word_id = paddle.layer.data(
name='source_language_word',
type=paddle.data_type.integer_value_sequence(source_dict_dim))
```
- 2.2 将上述编码映射到低维语言空间的词向量$\mathbf{s}$。
+ 1. 将上述编码映射到低维语言空间的词向量$\mathbf{s}$。
```python
src_embedding = paddle.layer.embedding(
@@ -316,7 +270,7 @@ wmt14_reader = paddle.batch(
size=word_vector_dim,
param_attr=paddle.attr.ParamAttr(name='_source_language_embedding'))
```
- 2.3 用双向GRU编码源语言序列,拼接两个GRU的编码结果得到$\mathbf{h}$。
+ 1. 用双向GRU编码源语言序列,拼接两个GRU的编码结果得到$\mathbf{h}$。
```python
src_forward = paddle.networks.simple_gru(
@@ -326,16 +280,17 @@ wmt14_reader = paddle.batch(
encoded_vector = paddle.layer.concat(input=[src_forward, src_backward])
```
-3. 接着,定义基于注意力机制的解码器框架。分为三步:
+1. 接着,定义基于注意力机制的解码器框架。分为三步:
- 3.1 对源语言序列编码后的结果(见2.3),过一个前馈神经网络(Feed Forward Neural Network),得到其映射。
+ 1. 对源语言序列编码后的结果(见2.3),过一个前馈神经网络(Feed Forward Neural Network),得到其映射。
```python
with paddle.layer.mixed(size=decoder_size) as encoded_proj:
encoded_proj += paddle.layer.full_matrix_projection(
input=encoded_vector)
```
- 3.2 构造解码器RNN的初始状态。由于解码器需要预测时序目标序列,但在0时刻并没有初始值,所以我们希望对其进行初始化。这里采用的是将源语言序列逆序编码后的最后一个状态进行非线性映射,作为该初始值,即$c_0=h_T$。
+
+ 1. 构造解码器RNN的初始状态。由于解码器需要预测时序目标序列,但在0时刻并没有初始值,所以我们希望对其进行初始化。这里采用的是将源语言序列逆序编码后的最后一个状态进行非线性映射,作为该初始值,即$c_0=h_T$。
```python
backward_first = paddle.layer.first_seq(input=src_backward)
@@ -344,7 +299,8 @@ wmt14_reader = paddle.batch(
decoder_boot += paddle.layer.full_matrix_projection(
input=backward_first)
```
- 3.3 定义解码阶段每一个时间步的RNN行为,即根据当前时刻的源语言上下文向量$c_i$、解码器隐层状态$z_i$和目标语言中第$i$个词$u_i$,来预测第$i+1$个词的概率$p_{i+1}$。
+
+ 1. 定义解码阶段每一个时间步的RNN行为,即根据当前时刻的源语言上下文向量$c_i$、解码器隐层状态$z_i$和目标语言中第$i$个词$u_i$,来预测第$i+1$个词的概率$p_{i+1}$。
- decoder_mem记录了前一个时间步的隐层状态$z_i$,其初始状态是decoder_boot。
- context通过调用`simple_attention`函数,实现公式$c_i=\sum {j=1}^{T}a_{ij}h_j$。其中,enc_vec是$h_j$,enc_proj是$h_j$的映射(见3.1),权重$a_{ij}$的计算已经封装在`simple_attention`函数中。
- decoder_inputs融合了$c_i$和当前目标词current_word(即$u_i$)的表示。
@@ -381,24 +337,23 @@ wmt14_reader = paddle.batch(
return out
```
-4. 训练模式与生成模式下的解码器调用区别。
+1. 定义解码器框架名字,和`gru_decoder_with_attention`函数的前两个输入。注意:这两个输入使用`StaticInput`,具体说明可见[StaticInput文档](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/howto/deep_model/rnn/recurrent_group_cn.md#输入)。
- 4.1 定义解码器框架名字,和`gru_decoder_with_attention`函数的前两个输入。注意:这两个输入使用`StaticInput`,具体说明可见[StaticInput文档](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/howto/deep_model/rnn/recurrent_group_cn.md#输入)。
-
- ```python
+ ```python
decoder_group_name = "decoder_group"
group_input1 = paddle.layer.StaticInputV2(input=encoded_vector, is_seq=True)
group_input2 = paddle.layer.StaticInputV2(input=encoded_proj, is_seq=True)
group_inputs = [group_input1, group_input2]
- ```
- 4.2 训练模式下的解码器调用:
+ ```
- - 首先,将目标语言序列的词向量trg_embedding,直接作为训练模式下的current_word传给`gru_decoder_with_attention`函数。
- - 其次,使用`recurrent_group`函数循环调用`gru_decoder_with_attention`函数。
- - 接着,使用目标语言的下一个词序列作为标签层lbl,即预测目标词。
- - 最后,用多类交叉熵损失函数`classification_cost`来计算损失值。
+1. 训练模式下的解码器调用:
- ```python
+ - 首先,将目标语言序列的词向量trg_embedding,直接作为训练模式下的current_word传给`gru_decoder_with_attention`函数。
+ - 其次,使用`recurrent_group`函数循环调用`gru_decoder_with_attention`函数。
+ - 接着,使用目标语言的下一个词序列作为标签层lbl,即预测目标词。
+ - 最后,用多类交叉熵损失函数`classification_cost`来计算损失值。
+
+ ```python
trg_embedding = paddle.layer.embedding(
input=paddle.layer.data(
name='target_language_word',
@@ -421,7 +376,8 @@ wmt14_reader = paddle.batch(
name='target_language_next_word',
type=paddle.data_type.integer_value_sequence(target_dict_dim))
cost = paddle.layer.classification_cost(input=decoder, label=lbl)
- ```
+ ```
+
注意:我们提供的配置在Bahdanau的论文\[[4](#参考文献)\]上做了一些简化,可参考[issue #1133](https://github.com/PaddlePaddle/Paddle/issues/1133)。
### 参数定义
@@ -429,7 +385,6 @@ wmt14_reader = paddle.batch(
首先依据模型配置的`cost`定义模型参数。
```python
-# create parameters
parameters = paddle.parameters.create(cost)
```
@@ -447,24 +402,30 @@ for param in parameters.keys():
根据优化目标cost,网络拓扑结构和模型参数来构造出trainer用来训练,在构造时还需指定优化方法,这里使用最基本的SGD方法。
```python
- optimizer = paddle.optimizer.Adam(learning_rate=1e-4)
+ optimizer = paddle.optimizer.Adam(
+ learning_rate=5e-5,
+ regularization=paddle.optimizer.L2Regularization(rate=1e-3))
trainer = paddle.trainer.SGD(cost=cost,
parameters=parameters,
update_equation=optimizer)
```
-2. 构造event_handler
+1. 构造event_handler
可以通过自定义回调函数来评估训练过程中的各种状态,比如错误率等。下面的代码通过event.batch_id % 10 == 0 指定没10个batch打印一次日志,包含cost等信息。
+
```python
def event_handler(event):
if isinstance(event, paddle.event.EndIteration):
if event.batch_id % 10 == 0:
- print "Pass %d, Batch %d, Cost %f, %s" % (
+ print "\nPass %d, Batch %d, Cost %f, %s" % (
event.pass_id, event.batch_id, event.cost, event.metrics)
+ else:
+ sys.stdout.write('.')
+ sys.stdout.flush()
```
-3. 启动训练:
+1. 启动训练:
```python
trainer.train(
@@ -473,30 +434,29 @@ for param in parameters.keys():
num_passes=10000,
feeding=feeding)
```
- 训练开始后,可以观察到event_handler输出的日志如下:
- ```text
- Pass 0, Batch 0, Cost 247.408008, {'classification_error_evaluator': 1.0}
- Pass 0, Batch 10, Cost 212.058789, {'classification_error_evaluator': 0.8737863898277283}
- ...
- ```
+训练开始后,可以观察到event_handler输出的日志如下:
+
+```text
+Pass 0, Batch 0, Cost 148.444983, {'classification_error_evaluator': 1.0}
+.........
+Pass 0, Batch 10, Cost 335.896802, {'classification_error_evaluator': 0.9325153231620789}
+.........
+```
+
+ 当`classification_error_evaluator`的值低于0.35的时候,表示训练成功。
## 应用模型
### 下载预训练的模型
由于NMT模型的训练非常耗时,我们在50个物理节点(每节点含有2颗6核CPU)的集群中,花了5天时间训练了16个pass,其中每个pass耗时7个小时。因此,我们提供了一个预先训练好的模型(pass-00012)供大家直接下载使用。该模型大小为205MB,在所有16个模型中有最高的[BLEU评估](#BLEU评估)值26.92。下载并解压模型的命令如下:
+
```bash
cd pretrained
./wmt14_model.sh
```
-### 应用命令与结果
-
-新版api尚未支持机器翻译的翻译过程,尽请期待。
-
-翻译结果请见[效果展示](#效果展示)。
-
### BLEU评估
BLEU(Bilingual Evaluation understudy)是一种广泛使用的机器翻译自动评测指标,由IBM的watson研究中心于2002年提出\[[5](#参考文献)\],基本出发点是:机器译文越接近专业翻译人员的翻译结果,翻译系统的性能越好。其中,机器译文与人工参考译文之间的接近程度,采用句子精确度(precision)的计算方法,即比较两者的n元词组相匹配的个数,匹配的个数越多,BLEU得分越好。
diff --git a/machine_translation/seqToseq_net.py b/machine_translation/seqToseq_net.py
index 750d35c0c6b62801d70802ac4dc97f89d09fc612..fce466870f9c46525d460efa897e22e795862caa 100644
--- a/machine_translation/seqToseq_net.py
+++ b/machine_translation/seqToseq_net.py
@@ -110,8 +110,7 @@ group_inputs = [group_input1, group_input2]
if not is_generating:
trg_embedding = embedding_layer(
- input=data_layer(
- name='target_language_word', size=target_dict_dim),
+ input=data_layer(name='target_language_word', size=target_dict_dim),
size=word_vector_dim,
param_attr=ParamAttr(name='_target_language_embedding'))
group_inputs.append(trg_embedding)
@@ -156,8 +155,7 @@ else:
seqtext_printer_evaluator(
input=beam_gen,
- id_input=data_layer(
- name="sent_id", size=1),
+ id_input=data_layer(name="sent_id", size=1),
dict_file=trg_lang_dict,
result_file=gen_trans_file)
outputs(beam_gen)
diff --git a/pre-commit-hooks/convert_markdown_into_ipynb.sh b/pre-commit-hooks/convert_markdown_into_ipynb.sh
new file mode 100755
index 0000000000000000000000000000000000000000..41ea1d8135989a4150456ff8bca0fc29bd8b293f
--- /dev/null
+++ b/pre-commit-hooks/convert_markdown_into_ipynb.sh
@@ -0,0 +1,9 @@
+#!/bin/sh
+for file in $@ ; do
+ /tmp/go/bin/markdown-to-ipynb < $file > ${file%.*}".ipynb"
+ if [ $? -ne 0 ]; then
+ echo >&2 "markdown-to-ipynb $file error"
+ exit 1
+ fi
+done
+
diff --git a/recognize_digits/README.en.md b/recognize_digits/README.en.md
index 9ae2d36d8042430b7e8a2dc94b222c86aa39b27d..98ce6158439f61d1e5a4337c58f3e6027fa8fea7 100644
--- a/recognize_digits/README.en.md
+++ b/recognize_digits/README.en.md
@@ -1,6 +1,6 @@
# Recognize Digits
-The source code for this tutorial is under [book/recognize_digits](https://github.com/PaddlePaddle/book/tree/develop/recognize_digits). First-time readers, please refer to PaddlePaddle [installation instructions](http://www.paddlepaddle.org/doc_cn/build_and_install/index.html).
+The source code for this tutorial is under [book/recognize_digits](https://github.com/PaddlePaddle/book/tree/develop/recognize_digits). First-time readers, please refer to PaddlePaddle [installation instructions](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_en.rst).
## Introduction
When we learn a new programming language, the first task is usually to write a program that prints "Hello World." In Machine Learning or Deep Learning, the equivalent task is to train a model to perform handwritten digit recognition with [MNIST](http://yann.lecun.com/exdb/mnist/) dataset. Handwriting recognition is a typical image classification problem. The problem is relatively easy, and MNIST is a complete dataset. As a simple Computer Vision dataset, MNIST contains images of handwritten digits and their corresponding labels (Fig. 1). The input image is a 28x28 matrix, and the label is one of the digits from 0 to 9. Each image is normalized in size and centered.
@@ -240,7 +240,7 @@ def event_handler(event):
print "Pass %d, Batch %d, Cost %f, %s" % (
event.pass_id, event.batch_id, event.cost, event.metrics)
if isinstance(event, paddle.event.EndPass):
- result = trainer.test(reader=paddle.reader.batched(
+ result = trainer.test(reader=paddle.batch(
paddle.dataset.mnist.test(), batch_size=128))
print "Test with Pass %d, Cost %f, %s\n" % (
event.pass_id, result.cost, result.metrics)
@@ -248,7 +248,7 @@ def event_handler(event):
result.metrics['classification_error_evaluator']))
trainer.train(
- reader=paddle.reader.batched(
+ reader=paddle.batch(
paddle.reader.shuffle(
paddle.dataset.mnist.train(), buf_size=8192),
batch_size=128),
@@ -293,7 +293,7 @@ This tutorial describes a few basic Deep Learning models viz. Softmax regression
7. Deng, Li, Michael L. Seltzer, Dong Yu, Alex Acero, Abdel-rahman Mohamed, and Geoffrey E. Hinton. ["Binary coding of speech spectrograms using a deep auto-encoder."](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.185.1908&rep=rep1&type=pdf) In Interspeech, pp. 1692-1695. 2010.
8. Kégl, Balázs, and Róbert Busa-Fekete. ["Boosting products of base classifiers."](http://dl.acm.org/citation.cfm?id=1553439) In Proceedings of the 26th Annual International Conference on Machine Learning, pp. 497-504. ACM, 2009.
9. Rosenblatt, Frank. ["The perceptron: A probabilistic model for information storage and organization in the brain."](http://psycnet.apa.org/journals/rev/65/6/386/) Psychological review 65, no. 6 (1958): 386.
-10. Bishop, Christopher M. ["Pattern recognition."](http://s3.amazonaws.com/academia.edu.documents/30428242/bg0137.pdf?AWSAccessKeyId=AKIAJ56TQJRTWSMTNPEA&Expires=1484816640&Signature=85Ad6%2Fca8T82pmHzxaSXermovIA%3D&response-content-disposition=inline%3B%20filename%3DPattern_recognition_and_machine_learning.pdf) Machine Learning 128 (2006): 1-58.
+10. Bishop, Christopher M. ["Pattern recognition."](http://users.isr.ist.utl.pt/~wurmd/Livros/school/Bishop%20-%20Pattern%20Recognition%20And%20Machine%20Learning%20-%20Springer%20%202006.pdf) Machine Learning 128 (2006): 1-58.
-
This book is created by
PaddlePaddle, and uses
Shared knowledge signature - non commercial use-Sharing 4.0 International Licensing Protocal.
+This tutorial is contributed by
PaddlePaddle, and licensed under a
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
diff --git a/recognize_digits/README.md b/recognize_digits/README.md
index 2efb7906849335b07709c066f63f4f714fdfdc98..cb78486c027a615e5d96373256ba602509899396 100644
--- a/recognize_digits/README.md
+++ b/recognize_digits/README.md
@@ -1,6 +1,6 @@
# 识别数字
-本教程源代码目录在[book/recognize_digits](https://github.com/PaddlePaddle/book/tree/develop/recognize_digits), 初次使用请参考PaddlePaddle[安装教程](http://www.paddlepaddle.org/doc_cn/build_and_install/index.html)。
+本教程源代码目录在[book/recognize_digits](https://github.com/PaddlePaddle/book/tree/develop/recognize_digits), 初次使用请参考PaddlePaddle[安装教程](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_cn.rst)。
## 背景介绍
当我们学习编程的时候,编写的第一个程序一般是实现打印"Hello World"。而机器学习(或深度学习)的入门教程,一般都是 [MNIST](http://yann.lecun.com/exdb/mnist/) 数据库上的手写识别问题。原因是手写识别属于典型的图像分类问题,比较简单,同时MNIST数据集也很完备。MNIST数据集作为一个简单的计算机视觉数据集,包含一系列如图1所示的手写数字图片和对应的标签。图片是28x28的像素矩阵,标签则对应着0~9的10个数字。每张图片都经过了大小归一化和居中处理。
@@ -245,7 +245,7 @@ def event_handler(event):
print "Pass %d, Batch %d, Cost %f, %s" % (
event.pass_id, event.batch_id, event.cost, event.metrics)
if isinstance(event, paddle.event.EndPass):
- result = trainer.test(reader=paddle.reader.batched(
+ result = trainer.test(reader=paddle.batch(
paddle.dataset.mnist.test(), batch_size=128))
print "Test with Pass %d, Cost %f, %s\n" % (
event.pass_id, result.cost, result.metrics)
@@ -253,7 +253,7 @@ def event_handler(event):
result.metrics['classification_error_evaluator']))
trainer.train(
- reader=paddle.reader.batched(
+ reader=paddle.batch(
paddle.reader.shuffle(
paddle.dataset.mnist.train(), buf_size=8192),
batch_size=128),
@@ -289,7 +289,7 @@ trainer.train(
7. Deng, Li, Michael L. Seltzer, Dong Yu, Alex Acero, Abdel-rahman Mohamed, and Geoffrey E. Hinton. ["Binary coding of speech spectrograms using a deep auto-encoder."](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.185.1908&rep=rep1&type=pdf) In Interspeech, pp. 1692-1695. 2010.
8. Kégl, Balázs, and Róbert Busa-Fekete. ["Boosting products of base classifiers."](http://dl.acm.org/citation.cfm?id=1553439) In Proceedings of the 26th Annual International Conference on Machine Learning, pp. 497-504. ACM, 2009.
9. Rosenblatt, Frank. ["The perceptron: A probabilistic model for information storage and organization in the brain."](http://psycnet.apa.org/journals/rev/65/6/386/) Psychological review 65, no. 6 (1958): 386.
-10. Bishop, Christopher M. ["Pattern recognition."](http://s3.amazonaws.com/academia.edu.documents/30428242/bg0137.pdf?AWSAccessKeyId=AKIAJ56TQJRTWSMTNPEA&Expires=1484816640&Signature=85Ad6%2Fca8T82pmHzxaSXermovIA%3D&response-content-disposition=inline%3B%20filename%3DPattern_recognition_and_machine_learning.pdf) Machine Learning 128 (2006): 1-58.
+10. Bishop, Christopher M. ["Pattern recognition."](http://users.isr.ist.utl.pt/~wurmd/Livros/school/Bishop%20-%20Pattern%20Recognition%20And%20Machine%20Learning%20-%20Springer%20%202006.pdf) Machine Learning 128 (2006): 1-58.
本教程 由
PaddlePaddle 创作,采用
知识共享 署名-非商业性使用-相同方式共享 4.0 国际 许可协议进行许可。
diff --git a/recognize_digits/index.en.html b/recognize_digits/index.en.html
index 42b0816abb880052a19235f6d6d4d8028a0077ed..62b49dfdd6442858ff13593e5f77d9d2deba518d 100644
--- a/recognize_digits/index.en.html
+++ b/recognize_digits/index.en.html
@@ -42,7 +42,7 @@
# Recognize Digits
-The source code for this tutorial is under [book/recognize_digits](https://github.com/PaddlePaddle/book/tree/develop/recognize_digits). First-time readers, please refer to PaddlePaddle [installation instructions](http://www.paddlepaddle.org/doc_cn/build_and_install/index.html).
+The source code for this tutorial is under [book/recognize_digits](https://github.com/PaddlePaddle/book/tree/develop/recognize_digits). First-time readers, please refer to PaddlePaddle [installation instructions](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_en.rst).
## Introduction
When we learn a new programming language, the first task is usually to write a program that prints "Hello World." In Machine Learning or Deep Learning, the equivalent task is to train a model to perform handwritten digit recognition with [MNIST](http://yann.lecun.com/exdb/mnist/) dataset. Handwriting recognition is a typical image classification problem. The problem is relatively easy, and MNIST is a complete dataset. As a simple Computer Vision dataset, MNIST contains images of handwritten digits and their corresponding labels (Fig. 1). The input image is a 28x28 matrix, and the label is one of the digits from 0 to 9. Each image is normalized in size and centered.
@@ -282,7 +282,7 @@ def event_handler(event):
print "Pass %d, Batch %d, Cost %f, %s" % (
event.pass_id, event.batch_id, event.cost, event.metrics)
if isinstance(event, paddle.event.EndPass):
- result = trainer.test(reader=paddle.reader.batched(
+ result = trainer.test(reader=paddle.batch(
paddle.dataset.mnist.test(), batch_size=128))
print "Test with Pass %d, Cost %f, %s\n" % (
event.pass_id, result.cost, result.metrics)
@@ -290,7 +290,7 @@ def event_handler(event):
result.metrics['classification_error_evaluator']))
trainer.train(
- reader=paddle.reader.batched(
+ reader=paddle.batch(
paddle.reader.shuffle(
paddle.dataset.mnist.train(), buf_size=8192),
batch_size=128),
@@ -335,10 +335,10 @@ This tutorial describes a few basic Deep Learning models viz. Softmax regression
7. Deng, Li, Michael L. Seltzer, Dong Yu, Alex Acero, Abdel-rahman Mohamed, and Geoffrey E. Hinton. ["Binary coding of speech spectrograms using a deep auto-encoder."](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.185.1908&rep=rep1&type=pdf) In Interspeech, pp. 1692-1695. 2010.
8. Kégl, Balázs, and Róbert Busa-Fekete. ["Boosting products of base classifiers."](http://dl.acm.org/citation.cfm?id=1553439) In Proceedings of the 26th Annual International Conference on Machine Learning, pp. 497-504. ACM, 2009.
9. Rosenblatt, Frank. ["The perceptron: A probabilistic model for information storage and organization in the brain."](http://psycnet.apa.org/journals/rev/65/6/386/) Psychological review 65, no. 6 (1958): 386.
-10. Bishop, Christopher M. ["Pattern recognition."](http://s3.amazonaws.com/academia.edu.documents/30428242/bg0137.pdf?AWSAccessKeyId=AKIAJ56TQJRTWSMTNPEA&Expires=1484816640&Signature=85Ad6%2Fca8T82pmHzxaSXermovIA%3D&response-content-disposition=inline%3B%20filename%3DPattern_recognition_and_machine_learning.pdf) Machine Learning 128 (2006): 1-58.
+10. Bishop, Christopher M. ["Pattern recognition."](http://users.isr.ist.utl.pt/~wurmd/Livros/school/Bishop%20-%20Pattern%20Recognition%20And%20Machine%20Learning%20-%20Springer%20%202006.pdf) Machine Learning 128 (2006): 1-58.
-
This book is created by
PaddlePaddle, and uses
Shared knowledge signature - non commercial use-Sharing 4.0 International Licensing Protocal.
+This tutorial is contributed by
PaddlePaddle, and licensed under a
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
diff --git a/recognize_digits/index.html b/recognize_digits/index.html
index 39f72da305e5fdd80fb34f79a1f3d95e3fb4529d..9ed4d220920437cbd5699e62b5686bc44a466eeb 100644
--- a/recognize_digits/index.html
+++ b/recognize_digits/index.html
@@ -42,7 +42,7 @@
# 识别数字
-本教程源代码目录在[book/recognize_digits](https://github.com/PaddlePaddle/book/tree/develop/recognize_digits), 初次使用请参考PaddlePaddle[安装教程](http://www.paddlepaddle.org/doc_cn/build_and_install/index.html)。
+本教程源代码目录在[book/recognize_digits](https://github.com/PaddlePaddle/book/tree/develop/recognize_digits), 初次使用请参考PaddlePaddle[安装教程](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_cn.rst)。
## 背景介绍
当我们学习编程的时候,编写的第一个程序一般是实现打印"Hello World"。而机器学习(或深度学习)的入门教程,一般都是 [MNIST](http://yann.lecun.com/exdb/mnist/) 数据库上的手写识别问题。原因是手写识别属于典型的图像分类问题,比较简单,同时MNIST数据集也很完备。MNIST数据集作为一个简单的计算机视觉数据集,包含一系列如图1所示的手写数字图片和对应的标签。图片是28x28的像素矩阵,标签则对应着0~9的10个数字。每张图片都经过了大小归一化和居中处理。
@@ -287,7 +287,7 @@ def event_handler(event):
print "Pass %d, Batch %d, Cost %f, %s" % (
event.pass_id, event.batch_id, event.cost, event.metrics)
if isinstance(event, paddle.event.EndPass):
- result = trainer.test(reader=paddle.reader.batched(
+ result = trainer.test(reader=paddle.batch(
paddle.dataset.mnist.test(), batch_size=128))
print "Test with Pass %d, Cost %f, %s\n" % (
event.pass_id, result.cost, result.metrics)
@@ -295,7 +295,7 @@ def event_handler(event):
result.metrics['classification_error_evaluator']))
trainer.train(
- reader=paddle.reader.batched(
+ reader=paddle.batch(
paddle.reader.shuffle(
paddle.dataset.mnist.train(), buf_size=8192),
batch_size=128),
@@ -331,7 +331,7 @@ trainer.train(
7. Deng, Li, Michael L. Seltzer, Dong Yu, Alex Acero, Abdel-rahman Mohamed, and Geoffrey E. Hinton. ["Binary coding of speech spectrograms using a deep auto-encoder."](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.185.1908&rep=rep1&type=pdf) In Interspeech, pp. 1692-1695. 2010.
8. Kégl, Balázs, and Róbert Busa-Fekete. ["Boosting products of base classifiers."](http://dl.acm.org/citation.cfm?id=1553439) In Proceedings of the 26th Annual International Conference on Machine Learning, pp. 497-504. ACM, 2009.
9. Rosenblatt, Frank. ["The perceptron: A probabilistic model for information storage and organization in the brain."](http://psycnet.apa.org/journals/rev/65/6/386/) Psychological review 65, no. 6 (1958): 386.
-10. Bishop, Christopher M. ["Pattern recognition."](http://s3.amazonaws.com/academia.edu.documents/30428242/bg0137.pdf?AWSAccessKeyId=AKIAJ56TQJRTWSMTNPEA&Expires=1484816640&Signature=85Ad6%2Fca8T82pmHzxaSXermovIA%3D&response-content-disposition=inline%3B%20filename%3DPattern_recognition_and_machine_learning.pdf) Machine Learning 128 (2006): 1-58.
+10. Bishop, Christopher M. ["Pattern recognition."](http://users.isr.ist.utl.pt/~wurmd/Livros/school/Bishop%20-%20Pattern%20Recognition%20And%20Machine%20Learning%20-%20Springer%20%202006.pdf) Machine Learning 128 (2006): 1-58.
本教程 由
PaddlePaddle 创作,采用
知识共享 署名-非商业性使用-相同方式共享 4.0 国际 许可协议进行许可。
diff --git a/recognize_digits/train.py b/recognize_digits/train.py
index 7ee1c83ad1bd8ec25b78687493a84d79afe05ac3..b90e93a6d578fbb47e6bae8dfb0ea77ea4cee9eb 100644
--- a/recognize_digits/train.py
+++ b/recognize_digits/train.py
@@ -2,9 +2,8 @@ import paddle.v2 as paddle
def softmax_regression(img):
- predict = paddle.layer.fc(input=img,
- size=10,
- act=paddle.activation.Softmax())
+ predict = paddle.layer.fc(
+ input=img, size=10, act=paddle.activation.Softmax())
return predict
@@ -12,14 +11,12 @@ def multilayer_perceptron(img):
# The first fully-connected layer
hidden1 = paddle.layer.fc(input=img, size=128, act=paddle.activation.Relu())
# The second fully-connected layer and the according activation function
- hidden2 = paddle.layer.fc(input=hidden1,
- size=64,
- act=paddle.activation.Relu())
+ hidden2 = paddle.layer.fc(
+ input=hidden1, size=64, act=paddle.activation.Relu())
# The thrid fully-connected layer, note that the hidden size should be 10,
# which is the number of unique digits
- predict = paddle.layer.fc(input=hidden2,
- size=10,
- act=paddle.activation.Softmax())
+ predict = paddle.layer.fc(
+ input=hidden2, size=10, act=paddle.activation.Softmax())
return predict
@@ -43,14 +40,12 @@ def convolutional_neural_network(img):
pool_stride=2,
act=paddle.activation.Tanh())
# The first fully-connected layer
- fc1 = paddle.layer.fc(input=conv_pool_2,
- size=128,
- act=paddle.activation.Tanh())
+ fc1 = paddle.layer.fc(
+ input=conv_pool_2, size=128, act=paddle.activation.Tanh())
# The softmax layer, note that the hidden size should be 10,
# which is the number of unique digits
- predict = paddle.layer.fc(input=fc1,
- size=10,
- act=paddle.activation.Softmax())
+ predict = paddle.layer.fc(
+ input=fc1, size=10, act=paddle.activation.Softmax())
return predict
@@ -76,9 +71,8 @@ optimizer = paddle.optimizer.Momentum(
momentum=0.9,
regularization=paddle.optimizer.L2Regularization(rate=0.0005 * 128))
-trainer = paddle.trainer.SGD(cost=cost,
- parameters=parameters,
- update_equation=optimizer)
+trainer = paddle.trainer.SGD(
+ cost=cost, parameters=parameters, update_equation=optimizer)
lists = []
@@ -89,7 +83,7 @@ def event_handler(event):
print "Pass %d, Batch %d, Cost %f, %s" % (
event.pass_id, event.batch_id, event.cost, event.metrics)
if isinstance(event, paddle.event.EndPass):
- result = trainer.test(reader=paddle.reader.batched(
+ result = trainer.test(reader=paddle.batch(
paddle.dataset.mnist.test(), batch_size=128))
print "Test with Pass %d, Cost %f, %s\n" % (event.pass_id, result.cost,
result.metrics)
@@ -98,9 +92,8 @@ def event_handler(event):
trainer.train(
- reader=paddle.reader.batched(
- paddle.reader.shuffle(
- paddle.dataset.mnist.train(), buf_size=8192),
+ reader=paddle.batch(
+ paddle.reader.shuffle(paddle.dataset.mnist.train(), buf_size=8192),
batch_size=128),
event_handler=event_handler,
num_passes=100)
diff --git a/recommender_system/README.en.ipynb b/recommender_system/README.en.ipynb
new file mode 100644
index 0000000000000000000000000000000000000000..8c9addf7c8dcedc37f018f8621c98077e59fb3ff
--- /dev/null
+++ b/recommender_system/README.en.ipynb
@@ -0,0 +1,740 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Personalized Recommendation\n",
+ "\n",
+ "The source code of this tutorial is in [book/recommender_system](https://github.com/PaddlePaddle/book/tree/develop/recommender_system).\n",
+ "\n",
+ "For instructions on getting started with PaddlePaddle, see [PaddlePaddle installation guide](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_en.rst).\n",
+ "\n",
+ "\n",
+ "## Background\n",
+ "\n",
+ "With the fast growth of e-commerce, online videos, and online reading business, users have to rely on recommender systems to avoid manually browsing tremendous volume of choices. Recommender systems understand users' interest by mining user behavior and other properties of users and products.\n",
+ "\n",
+ "Some well know approaches include:\n",
+ "\n",
+ "- User behavior-based approach. A well-known method is collaborative filtering. The underlying assumption is that if a person A has the same opinion as a person B on an issue, A is more likely to have B's opinion on a different issue than that of a randomly chosen person.\n",
+ "\n",
+ "- Content-based recommendation[[1](#reference)]. This approach infers feature vectors that represent products from their descriptions. It also infers feature vectors that represent users' interests. Then it measures the relevance of users and products by some distances between these feature vectors.\n",
+ "\n",
+ "- Hybrid approach[[2](#reference)]: This approach uses the content-based information to help address the cold start problem[[6](#reference)] in behavior-based approach.\n",
+ "\n",
+ "Among these options, collaborative filtering might be the most studied one. Some of its variants include user-based[[3](#reference)], item-based [[4](#reference)], social network based[[5](#reference)], and model-based.\n",
+ "\n",
+ "This tutorial explains a deep learning based approach and how to implement it using PaddlePaddle. We will train a model using a dataset that includes user information, movie information, and ratings. Once we train the model, we will be able to get a predicted rating given a pair of user and movie IDs.\n",
+ "\n",
+ "\n",
+ "## Model Overview\n",
+ "\n",
+ "To know more about deep learning based recommendation, let us start from going over the Youtube recommender system[[7](#参考文献)] before introducing our hybrid model.\n",
+ "\n",
+ "\n",
+ "### YouTube's Deep Learning Recommendation Model\n",
+ "\n",
+ "YouTube is a video-sharing Web site with one of the largest user base in the world. Its recommender system serves more than a billion users. This system is composed of two major parts: candidate generation and ranking. The former selects few hundreds of candidates from millions of videos, and the latter ranks and outputs the top 10.\n",
+ "\n",
+ "\u003cp align=\"center\"\u003e\n",
+ "\u003cimg src=\"image/YouTube_Overview.en.png\" width=\"70%\" \u003e\u003cbr/\u003e\n",
+ "Figure 1. YouTube recommender system overview.\n",
+ "\u003c/p\u003e\n",
+ "\n",
+ "#### Candidate Generation Network\n",
+ "\n",
+ "Youtube models candidate generation as a multiclass classification problem with a huge number of classes equal to the number of videos. The architecture of the model is as follows:\n",
+ "\n",
+ "\u003cp align=\"center\"\u003e\n",
+ "\u003cimg src=\"image/Deep_candidate_generation_model_architecture.en.png\" width=\"70%\" \u003e\u003cbr/\u003e\n",
+ "Figure. Deep candidate geeration model.\n",
+ "\u003c/p\u003e\n",
+ "\n",
+ "The first stage of this model maps watching history and search queries into fixed-length representative features. Then, an MLP (multi-layer perceptron, as described in the [Recognize Digits](https://github.com/PaddlePaddle/book/blob/develop/recognize_digits/README.md) tutorial) takes the concatenation of all representative vectors. The output of the MLP represents the user' *intrinsic interests*. At training time, it is used together with a softmax output layer for minimizing the classification error. At serving time, it is used to compute the relevance of the user with all movies.\n",
+ "\n",
+ "For a user $U$, the predicted watching probability of video $i$ is\n",
+ "\n",
+ "$$P(\\omega=i|u)=\\frac{e^{v_{i}u}}{\\sum_{j \\in V}e^{v_{j}u}}$$\n",
+ "\n",
+ "where $u$ is the representative vector of user $U$, $V$ is the corpus of all videos, $v_i$ is the representative vector of the $i$-th video. $u$ and $v_i$ are vectors of the same length, so we can compute their dot product using a fully connected layer.\n",
+ "\n",
+ "This model could have a performance issue as the softmax output covers millions of classification labels. To optimize performance, at the training time, the authors down-sample negative samples, so the actual number of classes is reduced to thousands. At serving time, the authors ignore the normalization of the softmax outputs, because the results are just for ranking.\n",
+ "\n",
+ "\n",
+ "#### Ranking Network\n",
+ "\n",
+ "The architecture of the ranking network is similar to that of the candidate generation network. Similar to ranking models widely used in online advertising, it uses rich features like video ID, last watching time, etc. The output layer of the ranking network is a weighted logistic regression, which rates all candidate videos.\n",
+ "\n",
+ "\n",
+ "### Hybrid Model\n",
+ "\n",
+ "In the section, let us introduce our movie recommendation system.\n",
+ "\n",
+ "In our network, the input includes features of users and movies. The user feature includes four properties: user ID, gender, occupation, and age. Movie features include their IDs, genres, and titles.\n",
+ "\n",
+ "We use fully-connected layers to map user features into representative feature vectors and concatenate them. The process of movie features is similar, except that for movie titles -- we feed titles into a text convolution network as described in the [sentiment analysis tutorial](https://github.com/PaddlePaddle/book/blob/develop/understand_sentiment/README.md))to get a fixed-length representative feature vector.\n",
+ "\n",
+ "Given the feature vectors of users and movies, we compute the relevance using cosine similarity. We minimize the squared error at training time.\n",
+ "\n",
+ "\u003cp align=\"center\"\u003e\n",
+ "\n",
+ "\u003cimg src=\"image/rec_regression_network_en.png\" width=\"90%\" \u003e\u003cbr/\u003e\n",
+ "Figure 3. A hybrid recommendation model.\n",
+ "\u003c/p\u003e\n",
+ "\n",
+ "## Dataset\n",
+ "\n",
+ "We use the [MovieLens ml-1m](http://files.grouplens.org/datasets/movielens/ml-1m.zip) to train our model. This dataset includes 10,000 ratings of 4,000 movies from 6,000 users to 4,000 movies. Each rate is in the range of 1~5. Thanks to GroupLens Research for collecting, processing and publishing the dataset.\n",
+ "\n",
+ "`paddle.v2.datasets` package encapsulates multiple public datasets, including `cifar`, `imdb`, `mnist`, `moivelens` and `wmt14`, etc. There's no need for us to manually download and preprocess `MovieLens` dataset.\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "# Run this block to show dataset's documentation\n",
+ "help(paddle.v2.dataset.movielens)\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "The raw `MoiveLens` contains movie ratings, relevant features from both movies and users.\n",
+ "For instance, one movie's feature could be:\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "movie_info = paddle.dataset.movielens.movie_info()\n",
+ "print movie_info.values()[0]\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "```text\n",
+ "\u003cMovieInfo id(1), title(Toy Story), categories(['Animation', \"Children's\", 'Comedy'])\u003e\n",
+ "```\n",
+ "\n",
+ "One user's feature could be:\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "user_info = paddle.dataset.movielens.user_info()\n",
+ "print user_info.values()[0]\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "```text\n",
+ "\u003cUserInfo id(1), gender(F), age(1), job(10)\u003e\n",
+ "```\n",
+ "\n",
+ "In this dateset, the distribution of age is shown as follows:\n",
+ "\n",
+ "```text\n",
+ "1: \"Under 18\"\n",
+ "18: \"18-24\"\n",
+ "25: \"25-34\"\n",
+ "35: \"35-44\"\n",
+ "45: \"45-49\"\n",
+ "50: \"50-55\"\n",
+ "56: \"56+\"\n",
+ "```\n",
+ "\n",
+ "User's occupation is selected from the following options:\n",
+ "\n",
+ "```text\n",
+ "0: \"other\" or not specified\n",
+ "1: \"academic/educator\"\n",
+ "2: \"artist\"\n",
+ "3: \"clerical/admin\"\n",
+ "4: \"college/grad student\"\n",
+ "5: \"customer service\"\n",
+ "6: \"doctor/health care\"\n",
+ "7: \"executive/managerial\"\n",
+ "8: \"farmer\"\n",
+ "9: \"homemaker\"\n",
+ "10: \"K-12 student\"\n",
+ "11: \"lawyer\"\n",
+ "12: \"programmer\"\n",
+ "13: \"retired\"\n",
+ "14: \"sales/marketing\"\n",
+ "15: \"scientist\"\n",
+ "16: \"self-employed\"\n",
+ "17: \"technician/engineer\"\n",
+ "18: \"tradesman/craftsman\"\n",
+ "19: \"unemployed\"\n",
+ "20: \"writer\"\n",
+ "```\n",
+ "\n",
+ "Each record consists of three main components: user features, movie features and movie ratings.\n",
+ "Likewise, as a simple example, consider the following:\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "train_set_creator = paddle.dataset.movielens.train()\n",
+ "train_sample = next(train_set_creator())\n",
+ "uid = train_sample[0]\n",
+ "mov_id = train_sample[len(user_info[uid].value())]\n",
+ "print \"User %s rates Movie %s with Score %s\"%(user_info[uid], movie_info[mov_id], train_sample[-1])\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "```text\n",
+ "User \u003cUserInfo id(1), gender(F), age(1), job(10)\u003e rates Movie \u003cMovieInfo id(1193), title(One Flew Over the Cuckoo's Nest), categories(['Drama'])\u003e with Score [5.0]\n",
+ "```\n",
+ "\n",
+ "The output shows that user 1 gave movie `1193` a rating of 5.\n",
+ "\n",
+ "After issuing a command `python train.py`, training will start immediately. The details will be unpacked by the following sessions to see how it works.\n",
+ "\n",
+ "## Model Architecture\n",
+ "\n",
+ "### Initialize PaddlePaddle\n",
+ "\n",
+ "First, we must import and initialize PaddlePaddle (enable/disable GPU, set the number of trainers, etc).\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "import matplotlib.pyplot as plt\n",
+ "from IPython import display\n",
+ "import cPickle\n",
+ "\n",
+ "import paddle.v2 as paddle\n",
+ "\n",
+ "paddle.init(use_gpu=False)\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "### Model Configuration\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "uid = paddle.layer.data(\n",
+ " name='user_id',\n",
+ " type=paddle.data_type.integer_value(\n",
+ " paddle.dataset.movielens.max_user_id() + 1))\n",
+ "usr_emb = paddle.layer.embedding(input=uid, size=32)\n",
+ "\n",
+ "usr_gender_id = paddle.layer.data(\n",
+ " name='gender_id', type=paddle.data_type.integer_value(2))\n",
+ "usr_gender_emb = paddle.layer.embedding(input=usr_gender_id, size=16)\n",
+ "\n",
+ "usr_age_id = paddle.layer.data(\n",
+ " name='age_id',\n",
+ " type=paddle.data_type.integer_value(\n",
+ " len(paddle.dataset.movielens.age_table)))\n",
+ "usr_age_emb = paddle.layer.embedding(input=usr_age_id, size=16)\n",
+ "\n",
+ "usr_job_id = paddle.layer.data(\n",
+ " name='job_id',\n",
+ " type=paddle.data_type.integer_value(paddle.dataset.movielens.max_job_id(\n",
+ " ) + 1))\n",
+ "usr_job_emb = paddle.layer.embedding(input=usr_job_id, size=16)\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "As shown in the above code, the input is four dimension integers for each user, that is, `user_id`,`gender_id`, `age_id` and `job_id`. In order to deal with these features conveniently, we use the language model in NLP to transform these discrete values into embedding vaules `usr_emb`, `usr_gender_emb`, `usr_age_emb` and `usr_job_emb`.\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "usr_combined_features = paddle.layer.fc(\n",
+ " input=[usr_emb, usr_gender_emb, usr_age_emb, usr_job_emb],\n",
+ " size=200,\n",
+ " act=paddle.activation.Tanh())\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "Then, employing user features as input, directly connecting to a fully-connected layer, which is used to reduce dimension to 200.\n",
+ "\n",
+ "Furthermore, we do a similar transformation for each movie feature. The model configuration is:\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "mov_id = paddle.layer.data(\n",
+ " name='movie_id',\n",
+ " type=paddle.data_type.integer_value(\n",
+ " paddle.dataset.movielens.max_movie_id() + 1))\n",
+ "mov_emb = paddle.layer.embedding(input=mov_id, size=32)\n",
+ "\n",
+ "mov_categories = paddle.layer.data(\n",
+ " name='category_id',\n",
+ " type=paddle.data_type.sparse_binary_vector(\n",
+ " len(paddle.dataset.movielens.movie_categories())))\n",
+ "\n",
+ "mov_categories_hidden = paddle.layer.fc(input=mov_categories, size=32)\n",
+ "\n",
+ "\n",
+ "movie_title_dict = paddle.dataset.movielens.get_movie_title_dict()\n",
+ "mov_title_id = paddle.layer.data(\n",
+ " name='movie_title',\n",
+ " type=paddle.data_type.integer_value_sequence(len(movie_title_dict)))\n",
+ "mov_title_emb = paddle.layer.embedding(input=mov_title_id, size=32)\n",
+ "mov_title_conv = paddle.networks.sequence_conv_pool(\n",
+ " input=mov_title_emb, hidden_size=32, context_len=3)\n",
+ "\n",
+ "mov_combined_features = paddle.layer.fc(\n",
+ " input=[mov_emb, mov_categories_hidden, mov_title_conv],\n",
+ " size=200,\n",
+ " act=paddle.activation.Tanh())\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "Movie title, a sequence of words represented by an integer word index sequence, will be feed into a `sequence_conv_pool` layer, which will apply convolution and pooling on time dimension. Because pooling is done on time dimension, the output will be a fixed-length vector regardless the length of the input sequence.\n",
+ "\n",
+ "Finally, we can use cosine similarity to calculate the similarity between user characteristics and movie features.\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "inference = paddle.layer.cos_sim(a=usr_combined_features, b=mov_combined_features, size=1, scale=5)\n",
+ "cost = paddle.layer.regression_cost(\n",
+ " input=inference,\n",
+ " label=paddle.layer.data(\n",
+ " name='score', type=paddle.data_type.dense_vector(1)))\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "## Model Training\n",
+ "\n",
+ "### Define Parameters\n",
+ "\n",
+ "First, we define the model parameters according to the previous model configuration `cost`.\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "# Create parameters\n",
+ "parameters = paddle.parameters.create(cost)\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "### Create Trainer\n",
+ "\n",
+ "Before jumping into creating a training module, algorithm setting is also necessary. Here we specified Adam optimization algorithm via `paddle.optimizer`.\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "trainer = paddle.trainer.SGD(cost=cost, parameters=parameters,\n",
+ " update_equation=paddle.optimizer.Adam(learning_rate=1e-4))\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "```text\n",
+ "[INFO 2017-03-06 17:12:13,378 networks.py:1472] The input order is [user_id, gender_id, age_id, job_id, movie_id, category_id, movie_title, score]\n",
+ "[INFO 2017-03-06 17:12:13,379 networks.py:1478] The output order is [__regression_cost_0__]\n",
+ "```\n",
+ "\n",
+ "### Training\n",
+ "\n",
+ "`paddle.dataset.movielens.train` will yield records during each pass, after shuffling, a batch input is generated for training.\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "reader=paddle.reader.batch(\n",
+ " paddle.reader.shuffle(\n",
+ " paddle.dataset.movielens.trai(), buf_size=8192),\n",
+ " batch_size=256)\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "`feeding` is devoted to specifying the correspondence between each yield record and `paddle.layer.data`. For instance, the first column of data generated by `movielens.train` corresponds to `user_id` feature.\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "feeding = {\n",
+ " 'user_id': 0,\n",
+ " 'gender_id': 1,\n",
+ " 'age_id': 2,\n",
+ " 'job_id': 3,\n",
+ " 'movie_id': 4,\n",
+ " 'category_id': 5,\n",
+ " 'movie_title': 6,\n",
+ " 'score': 7\n",
+ "}\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "Callback function `event_handler` will be called during training when a pre-defined event happens.\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "step=0\n",
+ "\n",
+ "train_costs=[],[]\n",
+ "test_costs=[],[]\n",
+ "\n",
+ "def event_handler(event):\n",
+ " global step\n",
+ " global train_costs\n",
+ " global test_costs\n",
+ " if isinstance(event, paddle.event.EndIteration):\n",
+ " need_plot = False\n",
+ " if step % 10 == 0: # every 10 batches, record a train cost\n",
+ " train_costs[0].append(step)\n",
+ " train_costs[1].append(event.cost)\n",
+ "\n",
+ " if step % 1000 == 0: # every 1000 batches, record a test cost\n",
+ " result = trainer.test(reader=paddle.batch(\n",
+ " paddle.dataset.movielens.test(), batch_size=256))\n",
+ " test_costs[0].append(step)\n",
+ " test_costs[1].append(result.cost)\n",
+ "\n",
+ " if step % 100 == 0: # every 100 batches, update cost plot\n",
+ " plt.plot(*train_costs)\n",
+ " plt.plot(*test_costs)\n",
+ " plt.legend(['Train Cost', 'Test Cost'], loc='upper left')\n",
+ " display.clear_output(wait=True)\n",
+ " display.display(plt.gcf())\n",
+ " plt.gcf().clear()\n",
+ " step += 1\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "Finally, we can invoke `trainer.train` to start training:\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "trainer.train(\n",
+ " reader=reader,\n",
+ " event_handler=event_handler,\n",
+ " feeding=feeding,\n",
+ " num_passes=200)\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "## Conclusion\n",
+ "\n",
+ "This tutorial goes over traditional approaches in recommender system and a deep learning based approach. We also show that how to train and use the model with PaddlePaddle. Deep learning has been well used in computer vision and NLP, we look forward to its new successes in recommender systems.\n",
+ "\n",
+ "## Reference\n",
+ "\n",
+ "1. [Peter Brusilovsky](https://en.wikipedia.org/wiki/Peter_Brusilovsky) (2007). *The Adaptive Web*. p. 325.\n",
+ "2. Robin Burke , [Hybrid Web Recommender Systems](http://www.dcs.warwick.ac.uk/~acristea/courses/CS411/2010/Book%20-%20The%20Adaptive%20Web/HybridWebRecommenderSystems.pdf), pp. 377-408, The Adaptive Web, Peter Brusilovsky, Alfred Kobsa, Wolfgang Nejdl (Ed.), Lecture Notes in Computer Science, Springer-Verlag, Berlin, Germany, Lecture Notes in Computer Science, Vol. 4321, May 2007, 978-3-540-72078-2.\n",
+ "3. P. Resnick, N. Iacovou, etc. “[GroupLens: An Open Architecture for Collaborative Filtering of Netnews](http://ccs.mit.edu/papers/CCSWP165.html)”, Proceedings of ACM Conference on Computer Supported Cooperative Work, CSCW 1994. pp.175-186.\n",
+ "4. Sarwar, Badrul, et al. \"[Item-based collaborative filtering recommendation algorithms.](http://files.grouplens.org/papers/www10_sarwar.pdf)\" *Proceedings of the 10th International Conference on World Wide Web*. ACM, 2001.\n",
+ "5. Kautz, Henry, Bart Selman, and Mehul Shah. \"[Referral Web: Combining Social networks and collaborative filtering.](http://www.cs.cornell.edu/selman/papers/pdf/97.cacm.refweb.pdf)\" Communications of the ACM 40.3 (1997): 63-65. APA\n",
+ "6. Yuan, Jianbo, et al. [\"Solving Cold-Start Problem in Large-scale Recommendation Engines: A Deep Learning Approach.\"](https://arxiv.org/pdf/1611.05480v1.pdf) *arXiv preprint arXiv:1611.05480* (2016).\n",
+ "7. Covington P, Adams J, Sargin E. [Deep neural networks for youtube recommendations](https://static.googleusercontent.com/media/research.google.com/zh-CN//pubs/archive/45530.pdf)[C]//Proceedings of the 10th ACM Conference on Recommender Systems. ACM, 2016: 191-198.\n",
+ "\n",
+ "\u003cbr/\u003e\n",
+ "This tutorial is contributed by \u003ca xmlns:cc=\"http://creativecommons.org/ns#\" href=\"http://book.paddlepaddle.org\" property=\"cc:attributionName\" rel=\"cc:attributionURL\"\u003ePaddlePaddle\u003c/a\u003e, and licensed under a \u003ca rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"\u003eCreative Commons Attribution-NonCommercial-ShareAlike 4.0 International License\u003c/a\u003e.\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.0"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 0
+}
diff --git a/recommender_system/README.en.md b/recommender_system/README.en.md
index d393352cccc4170bf12e977bd1f1fcbfe4d97947..d9b925193c7935087ca649abf190595754dd7d47 100644
--- a/recommender_system/README.en.md
+++ b/recommender_system/README.en.md
@@ -2,6 +2,9 @@
The source code of this tutorial is in [book/recommender_system](https://github.com/PaddlePaddle/book/tree/develop/recommender_system).
+For instructions on getting started with PaddlePaddle, see [PaddlePaddle installation guide](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_en.rst).
+
+
## Background
With the fast growth of e-commerce, online videos, and online reading business, users have to rely on recommender systems to avoid manually browsing tremendous volume of choices. Recommender systems understand users' interest by mining user behavior and other properties of users and products.
@@ -76,22 +79,287 @@ Figure 3. A hybrid recommendation model.
## Dataset
-We use the [MovieLens ml-1m](http://files.grouplens.org/datasets/movielens/ml-1m.zip) to train our model. This dataset includes 10,000 ratings of 4,000 movies from 6,000 users to 4,000 movies. Each rate is in the range of 1~5. Thanks to GroupLens Research for collecting, processing and publishing the dataset.
-
-We don't have to download and preprocess the data. Instead, we can use PaddlePaddle's dataset module `paddle.v2.dataset.movielens`.
-
-
-## Model Specification
-
-
-
-## Training
-
-
-
-## Inference
-
+We use the [MovieLens ml-1m](http://files.grouplens.org/datasets/movielens/ml-1m.zip) to train our model. This dataset includes 10,000 ratings of 4,000 movies from 6,000 users to 4,000 movies. Each rate is in the range of 1~5. Thanks to GroupLens Research for collecting, processing and publishing the dataset.
+
+`paddle.v2.datasets` package encapsulates multiple public datasets, including `cifar`, `imdb`, `mnist`, `moivelens` and `wmt14`, etc. There's no need for us to manually download and preprocess `MovieLens` dataset.
+
+```python
+# Run this block to show dataset's documentation
+help(paddle.v2.dataset.movielens)
+```
+The raw `MoiveLens` contains movie ratings, relevant features from both movies and users.
+For instance, one movie's feature could be:
+
+```python
+movie_info = paddle.dataset.movielens.movie_info()
+print movie_info.values()[0]
+```
+
+```text
+
+```
+
+One user's feature could be:
+
+```python
+user_info = paddle.dataset.movielens.user_info()
+print user_info.values()[0]
+```
+
+```text
+
+```
+
+In this dateset, the distribution of age is shown as follows:
+
+```text
+1: "Under 18"
+18: "18-24"
+25: "25-34"
+35: "35-44"
+45: "45-49"
+50: "50-55"
+56: "56+"
+```
+
+User's occupation is selected from the following options:
+
+```text
+0: "other" or not specified
+1: "academic/educator"
+2: "artist"
+3: "clerical/admin"
+4: "college/grad student"
+5: "customer service"
+6: "doctor/health care"
+7: "executive/managerial"
+8: "farmer"
+9: "homemaker"
+10: "K-12 student"
+11: "lawyer"
+12: "programmer"
+13: "retired"
+14: "sales/marketing"
+15: "scientist"
+16: "self-employed"
+17: "technician/engineer"
+18: "tradesman/craftsman"
+19: "unemployed"
+20: "writer"
+```
+
+Each record consists of three main components: user features, movie features and movie ratings.
+Likewise, as a simple example, consider the following:
+
+```python
+train_set_creator = paddle.dataset.movielens.train()
+train_sample = next(train_set_creator())
+uid = train_sample[0]
+mov_id = train_sample[len(user_info[uid].value())]
+print "User %s rates Movie %s with Score %s"%(user_info[uid], movie_info[mov_id], train_sample[-1])
+```
+
+```text
+User rates Movie with Score [5.0]
+```
+
+The output shows that user 1 gave movie `1193` a rating of 5.
+
+After issuing a command `python train.py`, training will start immediately. The details will be unpacked by the following sessions to see how it works.
+
+## Model Architecture
+
+### Initialize PaddlePaddle
+
+First, we must import and initialize PaddlePaddle (enable/disable GPU, set the number of trainers, etc).
+
+```python
+%matplotlib inline
+
+import matplotlib.pyplot as plt
+from IPython import display
+import cPickle
+
+import paddle.v2 as paddle
+
+paddle.init(use_gpu=False)
+```
+
+### Model Configuration
+
+```python
+uid = paddle.layer.data(
+ name='user_id',
+ type=paddle.data_type.integer_value(
+ paddle.dataset.movielens.max_user_id() + 1))
+usr_emb = paddle.layer.embedding(input=uid, size=32)
+
+usr_gender_id = paddle.layer.data(
+ name='gender_id', type=paddle.data_type.integer_value(2))
+usr_gender_emb = paddle.layer.embedding(input=usr_gender_id, size=16)
+
+usr_age_id = paddle.layer.data(
+ name='age_id',
+ type=paddle.data_type.integer_value(
+ len(paddle.dataset.movielens.age_table)))
+usr_age_emb = paddle.layer.embedding(input=usr_age_id, size=16)
+
+usr_job_id = paddle.layer.data(
+ name='job_id',
+ type=paddle.data_type.integer_value(paddle.dataset.movielens.max_job_id(
+ ) + 1))
+usr_job_emb = paddle.layer.embedding(input=usr_job_id, size=16)
+```
+
+As shown in the above code, the input is four dimension integers for each user, that is, `user_id`,`gender_id`, `age_id` and `job_id`. In order to deal with these features conveniently, we use the language model in NLP to transform these discrete values into embedding vaules `usr_emb`, `usr_gender_emb`, `usr_age_emb` and `usr_job_emb`.
+
+```python
+usr_combined_features = paddle.layer.fc(
+ input=[usr_emb, usr_gender_emb, usr_age_emb, usr_job_emb],
+ size=200,
+ act=paddle.activation.Tanh())
+```
+
+Then, employing user features as input, directly connecting to a fully-connected layer, which is used to reduce dimension to 200.
+
+Furthermore, we do a similar transformation for each movie feature. The model configuration is:
+
+```python
+mov_id = paddle.layer.data(
+ name='movie_id',
+ type=paddle.data_type.integer_value(
+ paddle.dataset.movielens.max_movie_id() + 1))
+mov_emb = paddle.layer.embedding(input=mov_id, size=32)
+
+mov_categories = paddle.layer.data(
+ name='category_id',
+ type=paddle.data_type.sparse_binary_vector(
+ len(paddle.dataset.movielens.movie_categories())))
+
+mov_categories_hidden = paddle.layer.fc(input=mov_categories, size=32)
+
+
+movie_title_dict = paddle.dataset.movielens.get_movie_title_dict()
+mov_title_id = paddle.layer.data(
+ name='movie_title',
+ type=paddle.data_type.integer_value_sequence(len(movie_title_dict)))
+mov_title_emb = paddle.layer.embedding(input=mov_title_id, size=32)
+mov_title_conv = paddle.networks.sequence_conv_pool(
+ input=mov_title_emb, hidden_size=32, context_len=3)
+
+mov_combined_features = paddle.layer.fc(
+ input=[mov_emb, mov_categories_hidden, mov_title_conv],
+ size=200,
+ act=paddle.activation.Tanh())
+```
+
+Movie title, a sequence of words represented by an integer word index sequence, will be feed into a `sequence_conv_pool` layer, which will apply convolution and pooling on time dimension. Because pooling is done on time dimension, the output will be a fixed-length vector regardless the length of the input sequence.
+
+Finally, we can use cosine similarity to calculate the similarity between user characteristics and movie features.
+
+```python
+inference = paddle.layer.cos_sim(a=usr_combined_features, b=mov_combined_features, size=1, scale=5)
+cost = paddle.layer.regression_cost(
+ input=inference,
+ label=paddle.layer.data(
+ name='score', type=paddle.data_type.dense_vector(1)))
+```
+
+## Model Training
+
+### Define Parameters
+
+First, we define the model parameters according to the previous model configuration `cost`.
+
+```python
+# Create parameters
+parameters = paddle.parameters.create(cost)
+```
+
+### Create Trainer
+
+Before jumping into creating a training module, algorithm setting is also necessary. Here we specified Adam optimization algorithm via `paddle.optimizer`.
+
+```python
+trainer = paddle.trainer.SGD(cost=cost, parameters=parameters,
+ update_equation=paddle.optimizer.Adam(learning_rate=1e-4))
+```
+
+```text
+[INFO 2017-03-06 17:12:13,378 networks.py:1472] The input order is [user_id, gender_id, age_id, job_id, movie_id, category_id, movie_title, score]
+[INFO 2017-03-06 17:12:13,379 networks.py:1478] The output order is [__regression_cost_0__]
+```
+
+### Training
+
+`paddle.dataset.movielens.train` will yield records during each pass, after shuffling, a batch input is generated for training.
+
+```python
+reader=paddle.reader.batch(
+ paddle.reader.shuffle(
+ paddle.dataset.movielens.trai(), buf_size=8192),
+ batch_size=256)
+```
+
+`feeding` is devoted to specifying the correspondence between each yield record and `paddle.layer.data`. For instance, the first column of data generated by `movielens.train` corresponds to `user_id` feature.
+
+```python
+feeding = {
+ 'user_id': 0,
+ 'gender_id': 1,
+ 'age_id': 2,
+ 'job_id': 3,
+ 'movie_id': 4,
+ 'category_id': 5,
+ 'movie_title': 6,
+ 'score': 7
+}
+```
+
+Callback function `event_handler` will be called during training when a pre-defined event happens.
+
+```python
+step=0
+
+train_costs=[],[]
+test_costs=[],[]
+
+def event_handler(event):
+ global step
+ global train_costs
+ global test_costs
+ if isinstance(event, paddle.event.EndIteration):
+ need_plot = False
+ if step % 10 == 0: # every 10 batches, record a train cost
+ train_costs[0].append(step)
+ train_costs[1].append(event.cost)
+
+ if step % 1000 == 0: # every 1000 batches, record a test cost
+ result = trainer.test(reader=paddle.batch(
+ paddle.dataset.movielens.test(), batch_size=256))
+ test_costs[0].append(step)
+ test_costs[1].append(result.cost)
+
+ if step % 100 == 0: # every 100 batches, update cost plot
+ plt.plot(*train_costs)
+ plt.plot(*test_costs)
+ plt.legend(['Train Cost', 'Test Cost'], loc='upper left')
+ display.clear_output(wait=True)
+ display.display(plt.gcf())
+ plt.gcf().clear()
+ step += 1
+```
+
+Finally, we can invoke `trainer.train` to start training:
+
+```python
+trainer.train(
+ reader=reader,
+ event_handler=event_handler,
+ feeding=feeding,
+ num_passes=200)
+```
## Conclusion
@@ -99,13 +367,13 @@ This tutorial goes over traditional approaches in recommender system and a deep
## Reference
-1. [Peter Brusilovsky](https://en.wikipedia.org/wiki/Peter_Brusilovsky) (2007). *The Adaptive Web*. p. 325.
-2. Robin Burke , [Hybrid Web Recommender Systems](http://www.dcs.warwick.ac.uk/~acristea/courses/CS411/2010/Book%20-%20The%20Adaptive%20Web/HybridWebRecommenderSystems.pdf), pp. 377-408, The Adaptive Web, Peter Brusilovsky, Alfred Kobsa, Wolfgang Nejdl (Ed.), Lecture Notes in Computer Science, Springer-Verlag, Berlin, Germany, Lecture Notes in Computer Science, Vol. 4321, May 2007, 978-3-540-72078-2.
+1. [Peter Brusilovsky](https://en.wikipedia.org/wiki/Peter_Brusilovsky) (2007). *The Adaptive Web*. p. 325.
+2. Robin Burke , [Hybrid Web Recommender Systems](http://www.dcs.warwick.ac.uk/~acristea/courses/CS411/2010/Book%20-%20The%20Adaptive%20Web/HybridWebRecommenderSystems.pdf), pp. 377-408, The Adaptive Web, Peter Brusilovsky, Alfred Kobsa, Wolfgang Nejdl (Ed.), Lecture Notes in Computer Science, Springer-Verlag, Berlin, Germany, Lecture Notes in Computer Science, Vol. 4321, May 2007, 978-3-540-72078-2.
3. P. Resnick, N. Iacovou, etc. “[GroupLens: An Open Architecture for Collaborative Filtering of Netnews](http://ccs.mit.edu/papers/CCSWP165.html)”, Proceedings of ACM Conference on Computer Supported Cooperative Work, CSCW 1994. pp.175-186.
-4. Sarwar, Badrul, et al. "[Item-based collaborative filtering recommendation algorithms.](http://files.grouplens.org/papers/www10_sarwar.pdf)" *Proceedings of the 10th International Conference on World Wide Web*. ACM, 2001.
+4. Sarwar, Badrul, et al. "[Item-based collaborative filtering recommendation algorithms.](http://files.grouplens.org/papers/www10_sarwar.pdf)" *Proceedings of the 10th International Conference on World Wide Web*. ACM, 2001.
5. Kautz, Henry, Bart Selman, and Mehul Shah. "[Referral Web: Combining Social networks and collaborative filtering.](http://www.cs.cornell.edu/selman/papers/pdf/97.cacm.refweb.pdf)" Communications of the ACM 40.3 (1997): 63-65. APA
-6. Yuan, Jianbo, et al. ["Solving Cold-Start Problem in Large-scale Recommendation Engines: A Deep Learning Approach."](https://arxiv.org/pdf/1611.05480v1.pdf) *arXiv preprint arXiv:1611.05480* (2016).
+6. Yuan, Jianbo, et al. ["Solving Cold-Start Problem in Large-scale Recommendation Engines: A Deep Learning Approach."](https://arxiv.org/pdf/1611.05480v1.pdf) *arXiv preprint arXiv:1611.05480* (2016).
7. Covington P, Adams J, Sargin E. [Deep neural networks for youtube recommendations](https://static.googleusercontent.com/media/research.google.com/zh-CN//pubs/archive/45530.pdf)[C]//Proceedings of the 10th ACM Conference on Recommender Systems. ACM, 2016: 191-198.
-
This tutorial was created by the PaddlePaddle community and published under Common Creative 4.0 License。
+This tutorial is contributed by PaddlePaddle, and licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
diff --git a/recommender_system/README.ipynb b/recommender_system/README.ipynb
index 084e587b9aa20c6284cdd9aaf25c72cd556232c9..24833340333d7bf2415cc229e8a86a3383b60d1d 100644
--- a/recommender_system/README.ipynb
+++ b/recommender_system/README.ipynb
@@ -1,797 +1,795 @@
{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {
- "collapsed": true,
- "deletable": true,
- "editable": true
- },
- "source": [
- "# 个性化推荐\n",
- "\n",
- "本教程源代码目录在[book/recommender_system](https://github.com/PaddlePaddle/book/tree/develop/recommender_system), 初次使用请参考PaddlePaddle[安装教程](http://www.paddlepaddle.org/doc_cn/build_and_install/index.html)。\n",
- "\n",
- "## 背景介绍\n",
- "\n",
- "在网络技术不断发展和电子商务规模不断扩大的背景下,商品数量和种类快速增长,用户需要花费大量时间才能找到自己想买的商品,这就是信息超载问题。为了解决这个难题,推荐系统(Recommender System)应运而生。\n",
- "\n",
- "个性化推荐系统是信息过滤系统(Information Filtering System)的子集,它可以用在很多领域,如电影、音乐、电商和 Feed 流推荐等。推荐系统通过分析、挖掘用户行为,发现用户的个性化需求与兴趣特点,将用户可能感兴趣的信息或商品推荐给用户。与搜索引擎不同,推荐系统不需要用户准确地描述出自己的需求,而是根据分析历史行为建模,主动提供满足用户兴趣和需求的信息。\n",
- "\n",
- "传统的推荐系统方法主要有:\n",
- "\n",
- "- 协同过滤推荐(Collaborative Filtering Recommendation):该方法收集分析用户历史行为、活动、偏好,计算一个用户与其他用户的相似度,利用目标用户的相似用户对商品评价的加权评价值,来预测目标用户对特定商品的喜好程度。优点是可以给用户推荐未浏览过的新产品;缺点是对于没有任何行为的新用户存在冷启动的问题,同时也存在用户与商品之间的交互数据不够多造成的稀疏问题,会导致模型难以找到相近用户。\n",
- "- 基于内容过滤推荐[[1](#参考文献)](Content-based Filtering Recommendation):该方法利用商品的内容描述,抽象出有意义的特征,通过计算用户的兴趣和商品描述之间的相似度,来给用户做推荐。优点是简单直接,不需要依据其他用户对商品的评价,而是通过商品属性进行商品相似度度量,从而推荐给用户所感兴趣商品的相似商品;缺点是对于没有任何行为的新用户同样存在冷启动的问题。\n",
- "- 组合推荐[[2](#参考文献)](Hybrid Recommendation):运用不同的输入和技术共同进行推荐,以弥补各自推荐技术的缺点。\n",
- "\n",
- "其中协同过滤是应用最广泛的技术之一,它又可以分为多个子类:基于用户 (User-Based)的推荐[[3](#参考文献)] 、基于物品(Item-Based)的推荐[[4](#参考文献)]、基于社交网络关系(Social-Based)的推荐[[5](#参考文献)]、基于模型(Model-based)的推荐等。1994年明尼苏达大学推出的GroupLens系统[[3](#参考文献)]一般被认为是推荐系统成为一个相对独立的研究方向的标志。该系统首次提出了基于协同过滤来完成推荐任务的思想,此后,基于该模型的协同过滤推荐引领了推荐系统十几年的发展方向。\n",
- "\n",
- "深度学习具有优秀的自动提取特征的能力,能够学习多层次的抽象特征表示,并对异质或跨域的内容信息进行学习,可以一定程度上处理推荐系统冷启动问题[[6](#参考文献)]。本教程主要介绍个性化推荐的深度学习模型,以及如何使用PaddlePaddle实现模型。\n",
- "\n",
- "## 效果展示\n",
- "\n",
- "我们使用包含用户信息、电影信息与电影评分的数据集作为个性化推荐的应用场景。当我们训练好模型后,只需要输入对应的用户ID和电影ID,就可以得出一个匹配的分数(范围[1,5],分数越高视为兴趣越大),然后根据所有电影的推荐得分排序,推荐给用户可能感兴趣的电影。\n",
- "\n",
- "```\n",
- "Input movie_id: 1962\n",
- "Input user_id: 1\n",
- "Prediction Score is 4.25\n",
- "```\n",
- "\n",
- "## 模型概览\n",
- "\n",
- "本章中,我们首先介绍YouTube的视频推荐系统[[7](#参考文献)],然后介绍我们实现的融合推荐模型。\n",
- "\n",
- "### YouTube的深度神经网络推荐系统\n",
- "\n",
- "YouTube是世界上最大的视频上传、分享和发现网站,YouTube推荐系统为超过10亿用户从不断增长的视频库中推荐个性化的内容。整个系统由两个神经网络组成:候选生成网络和排序网络。候选生成网络从百万量级的视频库中生成上百个候选,排序网络对候选进行打分排序,输出排名最高的数十个结果。系统结构如图1所示:\n",
- "\n",
- "\n",
- "
\n",
- "图1. YouTube 推荐系统结构\n",
- "
\n",
- "\n",
- "#### 候选生成网络(Candidate Generation Network)\n",
- "\n",
- "候选生成网络将推荐问题建模为一个类别数极大的多类分类问题:对于一个Youtube用户,使用其观看历史(视频ID)、搜索词记录(search tokens)、人口学信息(如地理位置、用户登录设备)、二值特征(如性别,是否登录)和连续特征(如用户年龄)等,对视频库中所有视频进行多分类,得到每一类别的分类结果(即每一个视频的推荐概率),最终输出概率较高的几百个视频。\n",
- "\n",
- "首先,将观看历史及搜索词记录这类历史信息,映射为向量后取平均值得到定长表示;同时,输入人口学特征以优化新用户的推荐效果,并将二值特征和连续特征归一化处理到[0, 1]范围。接下来,将所有特征表示拼接为一个向量,并输入给非线形多层感知器(MLP,详见[识别数字](https://github.com/PaddlePaddle/book/blob/develop/recognize_digits/README.md)教程)处理。最后,训练时将MLP的输出给softmax做分类,预测时计算用户的综合特征(MLP的输出)与所有视频的相似度,取得分最高的$k$个作为候选生成网络的筛选结果。图2显示了候选生成网络结构。\n",
- "\n",
- "\n",
- "
\n",
- "图2. 候选生成网络结构\n",
- "
\n",
- "\n",
- "对于一个用户$U$,预测此刻用户要观看的视频$\\omega$为视频$i$的概率公式为:\n",
- "\n",
- "$$P(\\omega=i|u)=\\frac{e^{v_{i}u}}{\\sum_{j \\in V}e^{v_{j}u}}$$\n",
- "\n",
- "其中$u$为用户$U$的特征表示,$V$为视频库集合,$v_i$为视频库中第$i$个视频的特征表示。$u$和$v_i$为长度相等的向量,两者点积可以通过全连接层实现。\n",
- "\n",
- "考虑到softmax分类的类别数非常多,为了保证一定的计算效率:1)训练阶段,使用负样本类别采样将实际计算的类别数缩小至数千;2)推荐(预测)阶段,忽略softmax的归一化计算(不影响结果),将类别打分问题简化为点积(dot product)空间中的最近邻(nearest neighbor)搜索问题,取与$u$最近的$k$个视频作为生成的候选。\n",
- "\n",
- "#### 排序网络(Ranking Network)\n",
- "排序网络的结构类似于候选生成网络,但是它的目标是对候选进行更细致的打分排序。和传统广告排序中的特征抽取方法类似,这里也构造了大量的用于视频排序的相关特征(如视频 ID、上次观看时间等)。这些特征的处理方式和候选生成网络类似,不同之处是排序网络的顶部是一个加权逻辑回归(weighted logistic regression),它对所有候选视频进行打分,从高到底排序后将分数较高的一些视频返回给用户。\n",
- "\n",
- "### 融合推荐模型\n",
- "\n",
- "在下文的电影推荐系统中:\n",
- "\n",
- "1. 首先,使用用户特征和电影特征作为神经网络的输入,其中:\n",
- "\n",
- " - 用户特征融合了四个属性信息,分别是用户ID、性别、职业和年龄。\n",
- "\n",
- " - 电影特征融合了三个属性信息,分别是电影ID、电影类型ID和电影名称。\n",
- "\n",
- "2. 对用户特征,将用户ID映射为维度大小为256的向量表示,输入全连接层,并对其他三个属性也做类似的处理。然后将四个属性的特征表示分别全连接并相加。\n",
- "\n",
- "3. 对电影特征,将电影ID以类似用户ID的方式进行处理,电影类型ID以向量的形式直接输入全连接层,电影名称用文本卷积神经网络(详见[第5章](https://github.com/PaddlePaddle/book/blob/develop/understand_sentiment/README.md))得到其定长向量表示。然后将三个属性的特征表示分别全连接并相加。\n",
- "\n",
- "4. 得到用户和电影的向量表示后,计算二者的余弦相似度作为推荐系统的打分。最后,用该相似度打分和用户真实打分的差异的平方作为该回归模型的损失函数。\n",
- "\n",
- "\n",
- "\n",
- "
\n",
- "图3. 融合推荐模型 \n",
- "
"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "## 数据准备\n",
- "\n",
- "### 数据介绍与下载\n",
- "\n",
- "我们以 [MovieLens 百万数据集(ml-1m)](http://files.grouplens.org/datasets/movielens/ml-1m.zip)为例进行介绍。ml-1m 数据集包含了 6,000 位用户对 4,000 部电影的 1,000,000 条评价(评分范围 1~5 分,均为整数),由 GroupLens Research 实验室搜集整理。\n",
- "\n",
- "Paddle在API中提供了自动加载数据的模块。数据模块为 `paddle.dataset.movielens`"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {
- "collapsed": false,
- "deletable": true,
- "editable": true
- },
- "outputs": [],
- "source": [
- "import paddle.v2 as paddle\n",
- "paddle.init(use_gpu=False)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {
- "collapsed": false,
- "deletable": true,
- "editable": true
- },
- "outputs": [],
- "source": [
- "# Run this block to show dataset's documentation\n",
- "# help(paddle.dataset.movielens)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "在原始数据中包含电影的特征数据,用户的特征数据,和用户对电影的评分。\n",
- "\n",
- "例如,其中某一个电影特征为:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {
- "collapsed": false,
- "deletable": true,
- "editable": true
- },
- "outputs": [
+ "cells": [
{
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\n"
- ]
- }
- ],
- "source": [
- "movie_info = paddle.dataset.movielens.movie_info()\n",
- "print movie_info.values()[0]"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "这表示,电影的id是1,标题是《Toy Story》,该电影被分为到三个类别中。这三个类别是动画,儿童,喜剧。"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {
- "collapsed": false,
- "deletable": true,
- "editable": true
- },
- "outputs": [
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# 个性化推荐\n",
+ "\n",
+ "本教程源代码目录在[book/recommender_system](https://github.com/PaddlePaddle/book/tree/develop/recommender_system), 初次使用请参考PaddlePaddle[安装教程](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_cn.rst)。\n",
+ "\n",
+ "## 背景介绍\n",
+ "\n",
+ "在网络技术不断发展和电子商务规模不断扩大的背景下,商品数量和种类快速增长,用户需要花费大量时间才能找到自己想买的商品,这就是信息超载问题。为了解决这个难题,推荐系统(Recommender System)应运而生。\n",
+ "\n",
+ "个性化推荐系统是信息过滤系统(Information Filtering System)的子集,它可以用在很多领域,如电影、音乐、电商和 Feed 流推荐等。推荐系统通过分析、挖掘用户行为,发现用户的个性化需求与兴趣特点,将用户可能感兴趣的信息或商品推荐给用户。与搜索引擎不同,推荐系统不需要用户准确地描述出自己的需求,而是根据分析历史行为建模,主动提供满足用户兴趣和需求的信息。\n",
+ "\n",
+ "传统的推荐系统方法主要有:\n",
+ "\n",
+ "- 协同过滤推荐(Collaborative Filtering Recommendation):该方法收集分析用户历史行为、活动、偏好,计算一个用户与其他用户的相似度,利用目标用户的相似用户对商品评价的加权评价值,来预测目标用户对特定商品的喜好程度。优点是可以给用户推荐未浏览过的新产品;缺点是对于没有任何行为的新用户存在冷启动的问题,同时也存在用户与商品之间的交互数据不够多造成的稀疏问题,会导致模型难以找到相近用户。\n",
+ "- 基于内容过滤推荐[[1](#参考文献)](Content-based Filtering Recommendation):该方法利用商品的内容描述,抽象出有意义的特征,通过计算用户的兴趣和商品描述之间的相似度,来给用户做推荐。优点是简单直接,不需要依据其他用户对商品的评价,而是通过商品属性进行商品相似度度量,从而推荐给用户所感兴趣商品的相似商品;缺点是对于没有任何行为的新用户同样存在冷启动的问题。\n",
+ "- 组合推荐[[2](#参考文献)](Hybrid Recommendation):运用不同的输入和技术共同进行推荐,以弥补各自推荐技术的缺点。\n",
+ "\n",
+ "其中协同过滤是应用最广泛的技术之一,它又可以分为多个子类:基于用户 (User-Based)的推荐[[3](#参考文献)] 、基于物品(Item-Based)的推荐[[4](#参考文献)]、基于社交网络关系(Social-Based)的推荐[[5](#参考文献)]、基于模型(Model-based)的推荐等。1994年明尼苏达大学推出的GroupLens系统[[3](#参考文献)]一般被认为是推荐系统成为一个相对独立的研究方向的标志。该系统首次提出了基于协同过滤来完成推荐任务的思想,此后,基于该模型的协同过滤推荐引领了推荐系统十几年的发展方向。\n",
+ "\n",
+ "深度学习具有优秀的自动提取特征的能力,能够学习多层次的抽象特征表示,并对异质或跨域的内容信息进行学习,可以一定程度上处理推荐系统冷启动问题[[6](#参考文献)]。本教程主要介绍个性化推荐的深度学习模型,以及如何使用PaddlePaddle实现模型。\n",
+ "\n",
+ "## 效果展示\n",
+ "\n",
+ "我们使用包含用户信息、电影信息与电影评分的数据集作为个性化推荐的应用场景。当我们训练好模型后,只需要输入对应的用户ID和电影ID,就可以得出一个匹配的分数(范围[1,5],分数越高视为兴趣越大),然后根据所有电影的推荐得分排序,推荐给用户可能感兴趣的电影。\n",
+ "\n",
+ "```\n",
+ "Input movie_id: 1962\n",
+ "Input user_id: 1\n",
+ "Prediction Score is 4.25\n",
+ "```\n",
+ "\n",
+ "## 模型概览\n",
+ "\n",
+ "本章中,我们首先介绍YouTube的视频推荐系统[[7](#参考文献)],然后介绍我们实现的融合推荐模型。\n",
+ "\n",
+ "### YouTube的深度神经网络推荐系统\n",
+ "\n",
+ "YouTube是世界上最大的视频上传、分享和发现网站,YouTube推荐系统为超过10亿用户从不断增长的视频库中推荐个性化的内容。整个系统由两个神经网络组成:候选生成网络和排序网络。候选生成网络从百万量级的视频库中生成上百个候选,排序网络对候选进行打分排序,输出排名最高的数十个结果。系统结构如图1所示:\n",
+ "\n",
+ "\u003cp align=\"center\"\u003e\n",
+ "\u003cimg src=\"image/YouTube_Overview.png\" width=\"70%\" \u003e\u003cbr/\u003e\n",
+ "图1. YouTube 推荐系统结构\n",
+ "\u003c/p\u003e\n",
+ "\n",
+ "#### 候选生成网络(Candidate Generation Network)\n",
+ "\n",
+ "候选生成网络将推荐问题建模为一个类别数极大的多类分类问题:对于一个Youtube用户,使用其观看历史(视频ID)、搜索词记录(search tokens)、人口学信息(如地理位置、用户登录设备)、二值特征(如性别,是否登录)和连续特征(如用户年龄)等,对视频库中所有视频进行多分类,得到每一类别的分类结果(即每一个视频的推荐概率),最终输出概率较高的几百个视频。\n",
+ "\n",
+ "首先,将观看历史及搜索词记录这类历史信息,映射为向量后取平均值得到定长表示;同时,输入人口学特征以优化新用户的推荐效果,并将二值特征和连续特征归一化处理到[0, 1]范围。接下来,将所有特征表示拼接为一个向量,并输入给非线形多层感知器(MLP,详见[识别数字](https://github.com/PaddlePaddle/book/blob/develop/recognize_digits/README.md)教程)处理。最后,训练时将MLP的输出给softmax做分类,预测时计算用户的综合特征(MLP的输出)与所有视频的相似度,取得分最高的$k$个作为候选生成网络的筛选结果。图2显示了候选生成网络结构。\n",
+ "\n",
+ "\u003cp align=\"center\"\u003e\n",
+ "\u003cimg src=\"image/Deep_candidate_generation_model_architecture.png\" width=\"70%\" \u003e\u003cbr/\u003e\n",
+ "图2. 候选生成网络结构\n",
+ "\u003c/p\u003e\n",
+ "\n",
+ "对于一个用户$U$,预测此刻用户要观看的视频$\\omega$为视频$i$的概率公式为:\n",
+ "\n",
+ "$$P(\\omega=i|u)=\\frac{e^{v_{i}u}}{\\sum_{j \\in V}e^{v_{j}u}}$$\n",
+ "\n",
+ "其中$u$为用户$U$的特征表示,$V$为视频库集合,$v_i$为视频库中第$i$个视频的特征表示。$u$和$v_i$为长度相等的向量,两者点积可以通过全连接层实现。\n",
+ "\n",
+ "考虑到softmax分类的类别数非常多,为了保证一定的计算效率:1)训练阶段,使用负样本类别采样将实际计算的类别数缩小至数千;2)推荐(预测)阶段,忽略softmax的归一化计算(不影响结果),将类别打分问题简化为点积(dot product)空间中的最近邻(nearest neighbor)搜索问题,取与$u$最近的$k$个视频作为生成的候选。\n",
+ "\n",
+ "#### 排序网络(Ranking Network)\n",
+ "排序网络的结构类似于候选生成网络,但是它的目标是对候选进行更细致的打分排序。和传统广告排序中的特征抽取方法类似,这里也构造了大量的用于视频排序的相关特征(如视频 ID、上次观看时间等)。这些特征的处理方式和候选生成网络类似,不同之处是排序网络的顶部是一个加权逻辑回归(weighted logistic regression),它对所有候选视频进行打分,从高到底排序后将分数较高的一些视频返回给用户。\n",
+ "\n",
+ "### 融合推荐模型\n",
+ "\n",
+ "在下文的电影推荐系统中:\n",
+ "\n",
+ "1. 首先,使用用户特征和电影特征作为神经网络的输入,其中:\n",
+ "\n",
+ " - 用户特征融合了四个属性信息,分别是用户ID、性别、职业和年龄。\n",
+ "\n",
+ " - 电影特征融合了三个属性信息,分别是电影ID、电影类型ID和电影名称。\n",
+ "\n",
+ "2. 对用户特征,将用户ID映射为维度大小为256的向量表示,输入全连接层,并对其他三个属性也做类似的处理。然后将四个属性的特征表示分别全连接并相加。\n",
+ "\n",
+ "3. 对电影特征,将电影ID以类似用户ID的方式进行处理,电影类型ID以向量的形式直接输入全连接层,电影名称用文本卷积神经网络(详见[第5章](https://github.com/PaddlePaddle/book/blob/develop/understand_sentiment/README.md))得到其定长向量表示。然后将三个属性的特征表示分别全连接并相加。\n",
+ "\n",
+ "4. 得到用户和电影的向量表示后,计算二者的余弦相似度作为推荐系统的打分。最后,用该相似度打分和用户真实打分的差异的平方作为该回归模型的损失函数。\n",
+ "\n",
+ "\u003cp align=\"center\"\u003e\n",
+ "\n",
+ "\u003cimg src=\"image/rec_regression_network.png\" width=\"90%\" \u003e\u003cbr/\u003e\n",
+ "图3. 融合推荐模型\n",
+ "\u003c/p\u003e\n",
+ "\n",
+ "## 数据准备\n",
+ "\n",
+ "### 数据介绍与下载\n",
+ "\n",
+ "我们以 [MovieLens 百万数据集(ml-1m)](http://files.grouplens.org/datasets/movielens/ml-1m.zip)为例进行介绍。ml-1m 数据集包含了 6,000 位用户对 4,000 部电影的 1,000,000 条评价(评分范围 1~5 分,均为整数),由 GroupLens Research 实验室搜集整理。\n",
+ "\n",
+ "Paddle在API中提供了自动加载数据的模块。数据模块为 `paddle.dataset.movielens`\n",
+ "\n",
+ "\n"
+ ]
+ },
{
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\n"
- ]
- }
- ],
- "source": [
- "user_info = paddle.dataset.movielens.user_info()\n",
- "print user_info.values()[0]"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "这表示,该用户ID是1,女性,年龄比18岁还年轻。职业ID是10。\n",
- "\n",
- "\n",
- "其中,年龄使用下列分布\n",
- "* 1: \"Under 18\"\n",
- "* 18: \"18-24\"\n",
- "* 25: \"25-34\"\n",
- "* 35: \"35-44\"\n",
- "* 45: \"45-49\"\n",
- "* 50: \"50-55\"\n",
- "* 56: \"56+\"\n",
- "\n",
- "职业是从下面几种选项里面选则得出:\n",
- "* 0: \"other\" or not specified\n",
- "* 1: \"academic/educator\"\n",
- "* 2: \"artist\"\n",
- "* 3: \"clerical/admin\"\n",
- "* 4: \"college/grad student\"\n",
- "* 5: \"customer service\"\n",
- "* 6: \"doctor/health care\"\n",
- "* 7: \"executive/managerial\"\n",
- "* 8: \"farmer\"\n",
- "* 9: \"homemaker\"\n",
- "* 10: \"K-12 student\"\n",
- "* 11: \"lawyer\"\n",
- "* 12: \"programmer\"\n",
- "* 13: \"retired\"\n",
- "* 14: \"sales/marketing\"\n",
- "* 15: \"scientist\"\n",
- "* 16: \"self-employed\"\n",
- "* 17: \"technician/engineer\"\n",
- "* 18: \"tradesman/craftsman\"\n",
- "* 19: \"unemployed\"\n",
- "* 20: \"writer\""
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "而对于每一条训练/测试数据,均为 <用户特征> + <电影特征> + 评分。\n",
- "\n",
- "例如,我们获得第一条训练数据:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {
- "collapsed": false,
- "deletable": true,
- "editable": true
- },
- "outputs": [
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "import paddle.v2 as paddle\n",
+ "paddle.init(use_gpu=False)\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
{
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "User rates Movie with Score [5.0]\n"
- ]
- }
- ],
- "source": [
- "train_set_creator = paddle.dataset.movielens.train()\n",
- "train_sample = next(train_set_creator())\n",
- "uid = train_sample[0]\n",
- "mov_id = train_sample[len(user_info[uid].value())]\n",
- "print \"User %s rates Movie %s with Score %s\"%(user_info[uid], movie_info[mov_id], train_sample[-1])"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "即用户1对电影1193的评价为5分。"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "## 模型配置说明\n",
- "\n",
- "下面我们开始根据输入数据的形式配置模型。"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {
- "collapsed": true,
- "deletable": true,
- "editable": true
- },
- "outputs": [],
- "source": [
- "uid = paddle.layer.data(\n",
- " name='user_id',\n",
- " type=paddle.data_type.integer_value(\n",
- " paddle.dataset.movielens.max_user_id() + 1))\n",
- "usr_emb = paddle.layer.embedding(input=uid, size=32)\n",
- "\n",
- "usr_gender_id = paddle.layer.data(\n",
- " name='gender_id', type=paddle.data_type.integer_value(2))\n",
- "usr_gender_emb = paddle.layer.embedding(input=usr_gender_id, size=16)\n",
- "\n",
- "usr_age_id = paddle.layer.data(\n",
- " name='age_id',\n",
- " type=paddle.data_type.integer_value(\n",
- " len(paddle.dataset.movielens.age_table)))\n",
- "usr_age_emb = paddle.layer.embedding(input=usr_age_id, size=16)\n",
- "\n",
- "usr_job_id = paddle.layer.data(\n",
- " name='job_id',\n",
- " type=paddle.data_type.integer_value(paddle.dataset.movielens.max_job_id(\n",
- " ) + 1))\n",
- "usr_job_emb = paddle.layer.embedding(input=usr_job_id, size=16)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "如上述代码所示,对于每个用户,我们输入4维特征。其中包括`user_id`,`gender_id`,`age_id`,`job_id`。这几维特征均是简单的整数值。为了后续神经网络处理这些特征方便,我们借鉴NLP中的语言模型,将这几维离散的整数值,变换成embedding取出。分别形成`usr_emb`, `usr_gender_emb`, `usr_age_emb`, `usr_job_emb`。"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {
- "collapsed": true,
- "deletable": true,
- "editable": true
- },
- "outputs": [],
- "source": [
- "usr_combined_features = paddle.layer.fc(\n",
- " input=[usr_emb, usr_gender_emb, usr_age_emb, usr_job_emb],\n",
- " size=200,\n",
- " act=paddle.activation.Tanh())"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "然后,我们对于所有的用户特征,均输入到一个全连接层(fc)中。将所有特征融合为一个200维度的特征。"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "进而,我们对每一个电影特征做类似的变换,网络配置为:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {
- "collapsed": false,
- "deletable": true,
- "editable": true
- },
- "outputs": [],
- "source": [
- "mov_id = paddle.layer.data(\n",
- " name='movie_id',\n",
- " type=paddle.data_type.integer_value(\n",
- " paddle.dataset.movielens.max_movie_id() + 1))\n",
- "mov_emb = paddle.layer.embedding(input=mov_id, size=32)\n",
- "\n",
- "mov_categories = paddle.layer.data(\n",
- " name='category_id',\n",
- " type=paddle.data_type.sparse_binary_vector(\n",
- " len(paddle.dataset.movielens.movie_categories())))\n",
- "\n",
- "mov_categories_hidden = paddle.layer.fc(input=mov_categories, size=32)\n",
- "\n",
- "\n",
- "movie_title_dict = paddle.dataset.movielens.get_movie_title_dict()\n",
- "mov_title_id = paddle.layer.data(\n",
- " name='movie_title',\n",
- " type=paddle.data_type.integer_value_sequence(len(movie_title_dict)))\n",
- "mov_title_emb = paddle.layer.embedding(input=mov_title_id, size=32)\n",
- "mov_title_conv = paddle.networks.sequence_conv_pool(\n",
- " input=mov_title_emb, hidden_size=32, context_len=3)\n",
- "\n",
- "mov_combined_features = paddle.layer.fc(\n",
- " input=[mov_emb, mov_categories_hidden, mov_title_conv],\n",
- " size=200,\n",
- " act=paddle.activation.Tanh())"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "电影ID和电影类型分别映射到其对应的特征隐层。对于电影标题名称(title),一个ID序列表示的词语序列,在输入卷积层后,将得到每个时间窗口的特征(序列特征),然后通过在时间维度降采样得到固定维度的特征,整个过程在text_conv_pool实现。\n",
- "\n",
- "最后再将电影的特征融合进`mov_combined_features`中。"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {
- "collapsed": true,
- "deletable": true,
- "editable": true
- },
- "outputs": [],
- "source": [
- "inference = paddle.layer.cos_sim(a=usr_combined_features, b=mov_combined_features, size=1, scale=5)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "进而,我们使用余弦相似度计算用户特征与电影特征的相似性。并将这个相似性拟合(回归)到用户评分上。"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 10,
- "metadata": {
- "collapsed": true,
- "deletable": true,
- "editable": true
- },
- "outputs": [],
- "source": [
- "cost = paddle.layer.regression_cost(\n",
- " input=inference,\n",
- " label=paddle.layer.data(\n",
- " name='score', type=paddle.data_type.dense_vector(1)))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "至此,我们的优化目标就是这个网络配置中的`cost`了。"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "## 训练模型\n",
- "\n",
- "### 定义参数\n",
- "神经网络的模型,我们可以简单的理解为网络拓朴结构+参数。之前一节,我们定义出了优化目标`cost`。这个`cost`即为网络模型的拓扑结构。我们开始训练模型,需要先定义出参数。定义方法为:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 11,
- "metadata": {
- "collapsed": false,
- "deletable": true,
- "editable": true
- },
- "outputs": [
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n"
+ ]
+ },
{
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "[INFO 2017-03-06 17:12:13,284 networks.py:1472] The input order is [user_id, gender_id, age_id, job_id, movie_id, category_id, movie_title, score]\n",
- "[INFO 2017-03-06 17:12:13,287 networks.py:1478] The output order is [__regression_cost_0__]\n"
- ]
- }
- ],
- "source": [
- "parameters = paddle.parameters.create(cost)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "`parameters`是模型的所有参数集合。他是一个python的dict。我们可以查看到这个网络中的所有参数名称。因为之前定义模型的时候,我们没有指定参数名称,这里参数名称是自动生成的。当然,我们也可以指定每一个参数名称,方便日后维护。"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 12,
- "metadata": {
- "collapsed": false,
- "deletable": true,
- "editable": true
- },
- "outputs": [
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "# Run this block to show dataset's documentation\n",
+ "# help(paddle.dataset.movielens)\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
{
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "[u'___fc_layer_2__.wbias', u'___fc_layer_2__.w2', u'___embedding_layer_3__.w0', u'___embedding_layer_5__.w0', u'___embedding_layer_2__.w0', u'___embedding_layer_1__.w0', u'___fc_layer_1__.wbias', u'___fc_layer_0__.wbias', u'___fc_layer_1__.w0', u'___fc_layer_0__.w2', u'___fc_layer_0__.w3', u'___fc_layer_0__.w0', u'___fc_layer_0__.w1', u'___fc_layer_2__.w1', u'___fc_layer_2__.w0', u'___embedding_layer_4__.w0', u'___sequence_conv_pool_0___conv_fc.w0', u'___embedding_layer_0__.w0', u'___sequence_conv_pool_0___conv_fc.wbias']\n"
- ]
- }
- ],
- "source": [
- "print parameters.keys()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "### 构造训练(trainer)\n",
- "\n",
- "下面,我们根据网络拓扑结构和模型参数来构造出一个本地训练(trainer)。在构造本地训练的时候,我们还需要指定这个训练的优化方法。这里我们使用Adam来作为优化算法。"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "metadata": {
- "collapsed": false,
- "deletable": true,
- "editable": true
- },
- "outputs": [
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "在原始数据中包含电影的特征数据,用户的特征数据,和用户对电影的评分。\n",
+ "\n",
+ "例如,其中某一个电影特征为:\n",
+ "\n",
+ "\n"
+ ]
+ },
{
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "[INFO 2017-03-06 17:12:13,378 networks.py:1472] The input order is [user_id, gender_id, age_id, job_id, movie_id, category_id, movie_title, score]\n",
- "[INFO 2017-03-06 17:12:13,379 networks.py:1478] The output order is [__regression_cost_0__]\n"
- ]
- }
- ],
- "source": [
- "trainer = paddle.trainer.SGD(cost=cost, parameters=parameters, \n",
- " update_equation=paddle.optimizer.Adam(learning_rate=1e-4))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "### 训练\n",
- "\n",
- "下面我们开始训练过程。\n",
- "\n",
- "我们直接使用Paddle提供的数据集读取程序。`paddle.dataset.movielens.train()`和`paddle.dataset.movielens.test()`分别做训练和预测数据集。并且通过`reader_dict`来指定每一个数据和data_layer的对应关系。\n",
- "\n",
- "例如,这里的reader_dict表示的是,对于数据层 `user_id`,使用了reader中每一条数据的第0个元素。`gender_id`数据层使用了第1个元素。以此类推。\n",
- "\n",
- "训练过程是完全自动的。我们可以使用event_handler来观察训练过程,或进行测试等。这里我们在event_handler里面绘制了训练误差曲线和测试误差曲线。并且保存了模型。"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "metadata": {
- "collapsed": false,
- "deletable": true,
- "editable": true
- },
- "outputs": [
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "movie_info = paddle.dataset.movielens.movie_info()\n",
+ "print movie_info.values()[0]\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
{
- "data": {
- "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXQAAAD8CAYAAABn919SAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzsnXd4HNX1v987s0VarbptuVvucpcLYGOaKQm2CRACKQQI\nEEpCEgL8EkIKIUC+hEBCEkIIMSWVTmgBjI0pxmCwccW9N7mrd22b3x+zMzu7Oyutula+7/P4sXbq\n3dndzz333HPOFZqmIZFIJJLUR+nuBkgkEomkY5CCLpFIJL0EKegSiUTSS5CCLpFIJL0EKegSiUTS\nS5CCLpFIJL0EKegSiUTSS5CCLpFIJL0EKegSiUTSS3B05c369OmjFRYWduUtJRKJJOVZvXp1qaZp\nfVs6rksFvbCwkFWrVnXlLSUSiSTlEULsS+Y46XKRSCSSXoIUdIlEIuklSEGXSCSSXkKX+tDt8Pv9\nlJSU0NjY2N1N6TWkpaUxePBgnE5ndzdFIpF0Id0u6CUlJWRmZlJYWIgQorubk/JomkZZWRklJSUM\nHz68u5sjkUi6kG53uTQ2NpKfny/FvIMQQpCfny9HPBLJCUi3CzogxbyDkc9TIjkx6RGC3hIVdT7K\napu6uxkSiUTSo0kJQa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XpdiW1gDjAM/8HTWdyUtStS1kiHgcS+3zbcIAb0QWPbTmtSQIc0wcVpqvmY2YWbryXq/m4F3tVmp\nKpI+BoyZ2ZF2u9TBNjPbCOwAviBpe/nKhNrCfLK05nfMbAPwX7KUxSQJuU7i10tuB35Wua7VvkUI\n6BeAVWXLK70uBV6W1A/g72NeP51zy76Lqk+clqxvCTN7FXiWLG3RJ6l0N3P5sSe9fH0v8O8W+d4M\n3C7pHPATsrTLQ4m6AmBmF/x9DHiK7AczxbZwHjhvZqVpuJ8kC/ApupazAzhqZi/7ctt8ixDQ/wIM\n+CiCHrJTm/1tdiqxHyhdkd5Nlqsu1X/Kr2pvAV7zU7CDwKCkxX7le9DrckWSgO8BZ8zsGwXwXSap\nz8tvIcv3nyEL7HdO41v6HncCz3hPaD8w5CNL1gADwHN5uprZPjNbaWarydriM2b2yRRdASQtUvZE\nMTx9MQicIsG2YGaXgJck3ehVtwGnU3StYBdX0i0lr/b4NvNCQY4XHHaSjdR4EXigTQ6PAxeBy2Q9\nic+Q5UKfBs4CvweW+LYCvu2+J4FNZfv5NDDqr7ua5LqN7DTveeC4v3Ym7Pte4Jj7ngIe9Pq1ZEFu\nlOx0doHXL/TlUV+/tmxfD/j3GAF2NLlN3MKVUS5JurrXCX+9UPr/SbgtrAeGvS38kmzUR5KufpxF\nZGdcvWV1bfONO0WDIAg6hCKkXIIgCIJZEAE9CIKgQ4iAHgRB0CFEQA+CIOgQIqAHQRB0CBHQgyAI\nOoQI6EEQBB1CBPQgCIIO4X9iGnorp+WAJQAAAABJRU5ErkJggg==\n",
- "text/plain": [
- ""
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ " \u003cMovieInfo id(1), title(Toy Story ), categories(['Animation', \"Children's\", 'Comedy'])\u003e\n",
+ "\n",
+ "\n",
+ "这表示,电影的id是1,标题是《Toy Story》,该电影被分为到三个类别中。这三个类别是动画,儿童,喜剧。\n",
+ "\n",
+ "\n"
]
- },
- "metadata": {},
- "output_type": "display_data"
},
{
- "data": {
- "text/plain": [
- ""
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "user_info = paddle.dataset.movielens.user_info()\n",
+ "print user_info.values()[0]\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ " \u003cUserInfo id(1), gender(F), age(1), job(10)\u003e\n",
+ "\n",
+ "\n",
+ "这表示,该用户ID是1,女性,年龄比18岁还年轻。职业ID是10。\n",
+ "\n",
+ "\n",
+ "其中,年龄使用下列分布\n",
+ "* 1: \"Under 18\"\n",
+ "* 18: \"18-24\"\n",
+ "* 25: \"25-34\"\n",
+ "* 35: \"35-44\"\n",
+ "* 45: \"45-49\"\n",
+ "* 50: \"50-55\"\n",
+ "* 56: \"56+\"\n",
+ "\n",
+ "职业是从下面几种选项里面选则得出:\n",
+ "* 0: \"other\" or not specified\n",
+ "* 1: \"academic/educator\"\n",
+ "* 2: \"artist\"\n",
+ "* 3: \"clerical/admin\"\n",
+ "* 4: \"college/grad student\"\n",
+ "* 5: \"customer service\"\n",
+ "* 6: \"doctor/health care\"\n",
+ "* 7: \"executive/managerial\"\n",
+ "* 8: \"farmer\"\n",
+ "* 9: \"homemaker\"\n",
+ "* 10: \"K-12 student\"\n",
+ "* 11: \"lawyer\"\n",
+ "* 12: \"programmer\"\n",
+ "* 13: \"retired\"\n",
+ "* 14: \"sales/marketing\"\n",
+ "* 15: \"scientist\"\n",
+ "* 16: \"self-employed\"\n",
+ "* 17: \"technician/engineer\"\n",
+ "* 18: \"tradesman/craftsman\"\n",
+ "* 19: \"unemployed\"\n",
+ "* 20: \"writer\"\n",
+ "\n",
+ "而对于每一条训练/测试数据,均为 \u003c用户特征\u003e + \u003c电影特征\u003e + 评分。\n",
+ "\n",
+ "例如,我们获得第一条训练数据:\n",
+ "\n",
+ "\n"
]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "%matplotlib inline\n",
- "\n",
- "import matplotlib.pyplot as plt\n",
- "from IPython import display\n",
- "import cPickle\n",
- "\n",
- "feeding = {\n",
- " 'user_id': 0,\n",
- " 'gender_id': 1,\n",
- " 'age_id': 2,\n",
- " 'job_id': 3,\n",
- " 'movie_id': 4,\n",
- " 'category_id': 5,\n",
- " 'movie_title': 6,\n",
- " 'score': 7\n",
- "}\n",
- "\n",
- "step=0\n",
- "\n",
- "train_costs=[],[]\n",
- "test_costs=[],[]\n",
- "\n",
- "def event_handler(event):\n",
- " global step\n",
- " global train_costs\n",
- " global test_costs\n",
- " if isinstance(event, paddle.event.EndIteration):\n",
- " need_plot = False\n",
- " if step % 10 == 0: # every 10 batches, record a train cost\n",
- " train_costs[0].append(step)\n",
- " train_costs[1].append(event.cost)\n",
- " \n",
- " if step % 1000 == 0: # every 1000 batches, record a test cost\n",
- " result = trainer.test(reader=paddle.batch(\n",
- " paddle.dataset.movielens.test(), batch_size=256))\n",
- " test_costs[0].append(step)\n",
- " test_costs[1].append(result.cost)\n",
- " \n",
- " if step % 100 == 0: # every 100 batches, update cost plot\n",
- " plt.plot(*train_costs)\n",
- " plt.plot(*test_costs)\n",
- " plt.legend(['Train Cost', 'Test Cost'], loc='upper left')\n",
- " display.clear_output(wait=True)\n",
- " display.display(plt.gcf())\n",
- " plt.gcf().clear()\n",
- " step += 1\n",
- "\n",
- "trainer.train(\n",
- " reader=paddle.batch(\n",
- " paddle.reader.shuffle(\n",
- " paddle.dataset.movielens.train(), buf_size=8192),\n",
- " batch_size=256),\n",
- " event_handler=event_handler,\n",
- " feeding=feeding,\n",
- " num_passes=2)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "## 应用模型\n",
- "\n",
- "在训练了几轮以后,您可以对模型进行推断。我们可以使用任意一个用户ID和电影ID,来预测该用户对该电影的评分。示例程序为:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 15,
- "metadata": {
- "collapsed": false,
- "deletable": true,
- "editable": true
- },
- "outputs": [
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "train_set_creator = paddle.dataset.movielens.train()\n",
+ "train_sample = next(train_set_creator())\n",
+ "uid = train_sample[0]\n",
+ "mov_id = train_sample[len(user_info[uid].value())]\n",
+ "print \"User %s rates Movie %s with Score %s\"%(user_info[uid], movie_info[mov_id], train_sample[-1])\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ " User \u003cUserInfo id(1), gender(F), age(1), job(10)\u003e rates Movie \u003cMovieInfo id(1193), title(One Flew Over the Cuckoo's Nest ), categories(['Drama'])\u003e with Score [5.0]\n",
+ "\n",
+ "\n",
+ "即用户1对电影1193的评价为5分。\n",
+ "\n",
+ "## 模型配置说明\n",
+ "\n",
+ "下面我们开始根据输入数据的形式配置模型。\n",
+ "\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "uid = paddle.layer.data(\n",
+ " name='user_id',\n",
+ " type=paddle.data_type.integer_value(\n",
+ " paddle.dataset.movielens.max_user_id() + 1))\n",
+ "usr_emb = paddle.layer.embedding(input=uid, size=32)\n",
+ "\n",
+ "usr_gender_id = paddle.layer.data(\n",
+ " name='gender_id', type=paddle.data_type.integer_value(2))\n",
+ "usr_gender_emb = paddle.layer.embedding(input=usr_gender_id, size=16)\n",
+ "\n",
+ "usr_age_id = paddle.layer.data(\n",
+ " name='age_id',\n",
+ " type=paddle.data_type.integer_value(\n",
+ " len(paddle.dataset.movielens.age_table)))\n",
+ "usr_age_emb = paddle.layer.embedding(input=usr_age_id, size=16)\n",
+ "\n",
+ "usr_job_id = paddle.layer.data(\n",
+ " name='job_id',\n",
+ " type=paddle.data_type.integer_value(paddle.dataset.movielens.max_job_id(\n",
+ " ) + 1))\n",
+ "usr_job_emb = paddle.layer.embedding(input=usr_job_id, size=16)\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "如上述代码所示,对于每个用户,我们输入4维特征。其中包括`user_id`,`gender_id`,`age_id`,`job_id`。这几维特征均是简单的整数值。为了后续神经网络处理这些特征方便,我们借鉴NLP中的语言模型,将这几维离散的整数值,变换成embedding取出。分别形成`usr_emb`, `usr_gender_emb`, `usr_age_emb`, `usr_job_emb`。\n",
+ "\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "usr_combined_features = paddle.layer.fc(\n",
+ " input=[usr_emb, usr_gender_emb, usr_age_emb, usr_job_emb],\n",
+ " size=200,\n",
+ " act=paddle.activation.Tanh())\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "然后,我们对于所有的用户特征,均输入到一个全连接层(fc)中。将所有特征融合为一个200维度的特征。\n",
+ "\n",
+ "进而,我们对每一个电影特征做类似的变换,网络配置为:\n",
+ "\n",
+ "\n"
+ ]
+ },
{
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "[INFO 2017-03-06 17:17:08,132 networks.py:1472] The input order is [user_id, gender_id, age_id, job_id, movie_id, category_id, movie_title]\n",
- "[INFO 2017-03-06 17:17:08,134 networks.py:1478] The output order is [__cos_sim_0__]\n"
- ]
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "mov_id = paddle.layer.data(\n",
+ " name='movie_id',\n",
+ " type=paddle.data_type.integer_value(\n",
+ " paddle.dataset.movielens.max_movie_id() + 1))\n",
+ "mov_emb = paddle.layer.embedding(input=mov_id, size=32)\n",
+ "\n",
+ "mov_categories = paddle.layer.data(\n",
+ " name='category_id',\n",
+ " type=paddle.data_type.sparse_binary_vector(\n",
+ " len(paddle.dataset.movielens.movie_categories())))\n",
+ "\n",
+ "mov_categories_hidden = paddle.layer.fc(input=mov_categories, size=32)\n",
+ "\n",
+ "\n",
+ "movie_title_dict = paddle.dataset.movielens.get_movie_title_dict()\n",
+ "mov_title_id = paddle.layer.data(\n",
+ " name='movie_title',\n",
+ " type=paddle.data_type.integer_value_sequence(len(movie_title_dict)))\n",
+ "mov_title_emb = paddle.layer.embedding(input=mov_title_id, size=32)\n",
+ "mov_title_conv = paddle.networks.sequence_conv_pool(\n",
+ " input=mov_title_emb, hidden_size=32, context_len=3)\n",
+ "\n",
+ "mov_combined_features = paddle.layer.fc(\n",
+ " input=[mov_emb, mov_categories_hidden, mov_title_conv],\n",
+ " size=200,\n",
+ " act=paddle.activation.Tanh())\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "电影ID和电影类型分别映射到其对应的特征隐层。对于电影标题名称(title),一个ID序列表示的词语序列,在输入卷积层后,将得到每个时间窗口的特征(序列特征),然后通过在时间维度降采样得到固定维度的特征,整个过程在text_conv_pool实现。\n",
+ "\n",
+ "最后再将电影的特征融合进`mov_combined_features`中。\n",
+ "\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "inference = paddle.layer.cos_sim(a=usr_combined_features, b=mov_combined_features, size=1, scale=5)\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "进而,我们使用余弦相似度计算用户特征与电影特征的相似性。并将这个相似性拟合(回归)到用户评分上。\n",
+ "\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "cost = paddle.layer.regression_cost(\n",
+ " input=inference,\n",
+ " label=paddle.layer.data(\n",
+ " name='score', type=paddle.data_type.dense_vector(1)))\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "至此,我们的优化目标就是这个网络配置中的`cost`了。\n",
+ "\n",
+ "## 训练模型\n",
+ "\n",
+ "### 定义参数\n",
+ "神经网络的模型,我们可以简单的理解为网络拓朴结构+参数。之前一节,我们定义出了优化目标`cost`。这个`cost`即为网络模型的拓扑结构。我们开始训练模型,需要先定义出参数。定义方法为:\n",
+ "\n",
+ "\n"
+ ]
},
{
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "[Predict] User 234 Rating Movie 345 With Score 4.16\n"
- ]
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "parameters = paddle.parameters.create(cost)\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ " [INFO 2017-03-06 17:12:13,284 networks.py:1472] The input order is [user_id, gender_id, age_id, job_id, movie_id, category_id, movie_title, score]\n",
+ " [INFO 2017-03-06 17:12:13,287 networks.py:1478] The output order is [__regression_cost_0__]\n",
+ "\n",
+ "\n",
+ "`parameters`是模型的所有参数集合。他是一个python的dict。我们可以查看到这个网络中的所有参数名称。因为之前定义模型的时候,我们没有指定参数名称,这里参数名称是自动生成的。当然,我们也可以指定每一个参数名称,方便日后维护。\n",
+ "\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "print parameters.keys()\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ " [u'___fc_layer_2__.wbias', u'___fc_layer_2__.w2', u'___embedding_layer_3__.w0', u'___embedding_layer_5__.w0', u'___embedding_layer_2__.w0', u'___embedding_layer_1__.w0', u'___fc_layer_1__.wbias', u'___fc_layer_0__.wbias', u'___fc_layer_1__.w0', u'___fc_layer_0__.w2', u'___fc_layer_0__.w3', u'___fc_layer_0__.w0', u'___fc_layer_0__.w1', u'___fc_layer_2__.w1', u'___fc_layer_2__.w0', u'___embedding_layer_4__.w0', u'___sequence_conv_pool_0___conv_fc.w0', u'___embedding_layer_0__.w0', u'___sequence_conv_pool_0___conv_fc.wbias']\n",
+ "\n",
+ "\n",
+ "### 构造训练(trainer)\n",
+ "\n",
+ "下面,我们根据网络拓扑结构和模型参数来构造出一个本地训练(trainer)。在构造本地训练的时候,我们还需要指定这个训练的优化方法。这里我们使用Adam来作为优化算法。\n",
+ "\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "trainer = paddle.trainer.SGD(cost=cost, parameters=parameters,\n",
+ " update_equation=paddle.optimizer.Adam(learning_rate=1e-4))\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ " [INFO 2017-03-06 17:12:13,378 networks.py:1472] The input order is [user_id, gender_id, age_id, job_id, movie_id, category_id, movie_title, score]\n",
+ " [INFO 2017-03-06 17:12:13,379 networks.py:1478] The output order is [__regression_cost_0__]\n",
+ "\n",
+ "\n",
+ "### 训练\n",
+ "\n",
+ "下面我们开始训练过程。\n",
+ "\n",
+ "我们直接使用Paddle提供的数据集读取程序。`paddle.dataset.movielens.train()`和`paddle.dataset.movielens.test()`分别做训练和预测数据集。并且通过`reader_dict`来指定每一个数据和data_layer的对应关系。\n",
+ "\n",
+ "例如,这里的reader_dict表示的是,对于数据层 `user_id`,使用了reader中每一条数据的第0个元素。`gender_id`数据层使用了第1个元素。以此类推。\n",
+ "\n",
+ "训练过程是完全自动的。我们可以使用event_handler来观察训练过程,或进行测试等。这里我们在event_handler里面绘制了训练误差曲线和测试误差曲线。并且保存了模型。\n",
+ "\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "import matplotlib.pyplot as plt\n",
+ "from IPython import display\n",
+ "import cPickle\n",
+ "\n",
+ "feeding = {\n",
+ " 'user_id': 0,\n",
+ " 'gender_id': 1,\n",
+ " 'age_id': 2,\n",
+ " 'job_id': 3,\n",
+ " 'movie_id': 4,\n",
+ " 'category_id': 5,\n",
+ " 'movie_title': 6,\n",
+ " 'score': 7\n",
+ "}\n",
+ "\n",
+ "step=0\n",
+ "\n",
+ "train_costs=[],[]\n",
+ "test_costs=[],[]\n",
+ "\n",
+ "def event_handler(event):\n",
+ " global step\n",
+ " global train_costs\n",
+ " global test_costs\n",
+ " if isinstance(event, paddle.event.EndIteration):\n",
+ " need_plot = False\n",
+ " if step % 10 == 0: # every 10 batches, record a train cost\n",
+ " train_costs[0].append(step)\n",
+ " train_costs[1].append(event.cost)\n",
+ "\n",
+ " if step % 1000 == 0: # every 1000 batches, record a test cost\n",
+ " result = trainer.test(reader=paddle.batch(\n",
+ " paddle.dataset.movielens.test(), batch_size=256))\n",
+ " test_costs[0].append(step)\n",
+ " test_costs[1].append(result.cost)\n",
+ "\n",
+ " if step % 100 == 0: # every 100 batches, update cost plot\n",
+ " plt.plot(*train_costs)\n",
+ " plt.plot(*test_costs)\n",
+ " plt.legend(['Train Cost', 'Test Cost'], loc='upper left')\n",
+ " display.clear_output(wait=True)\n",
+ " display.display(plt.gcf())\n",
+ " plt.gcf().clear()\n",
+ " step += 1\n",
+ "\n",
+ "trainer.train(\n",
+ " reader=paddle.batch(\n",
+ " paddle.reader.shuffle(\n",
+ " paddle.dataset.movielens.train(), buf_size=8192),\n",
+ " batch_size=256),\n",
+ " event_handler=event_handler,\n",
+ " feeding=feeding,\n",
+ " num_passes=2)\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "![png](./image/output_32_0.png)\n",
+ "\n",
+ "## 应用模型\n",
+ "\n",
+ "在训练了几轮以后,您可以对模型进行推断。我们可以使用任意一个用户ID和电影ID,来预测该用户对该电影的评分。示例程序为:\n",
+ "\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "import copy\n",
+ "user_id = 234\n",
+ "movie_id = 345\n",
+ "\n",
+ "user = user_info[user_id]\n",
+ "movie = movie_info[movie_id]\n",
+ "\n",
+ "feature = user.value() + movie.value()\n",
+ "\n",
+ "infer_dict = copy.copy(feeding)\n",
+ "del infer_dict['score']\n",
+ "\n",
+ "prediction = paddle.infer(output=inference, parameters=parameters, input=[feature], feeding=infer_dict)\n",
+ "score = (prediction[0][0] + 5.0) / 2\n",
+ "print \"[Predict] User %d Rating Movie %d With Score %.2f\"%(user_id, movie_id, score)\n"
+ ],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "execution_count": 1
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ " [INFO 2017-03-06 17:17:08,132 networks.py:1472] The input order is [user_id, gender_id, age_id, job_id, movie_id, category_id, movie_title]\n",
+ " [INFO 2017-03-06 17:17:08,134 networks.py:1478] The output order is [__cos_sim_0__]\n",
+ "\n",
+ "\n",
+ " [Predict] User 234 Rating Movie 345 With Score 4.16\n",
+ "\n",
+ "\n",
+ "## 总结\n",
+ "\n",
+ "本章介绍了传统的推荐系统方法和YouTube的深度神经网络推荐系统,并以电影推荐为例,使用PaddlePaddle训练了一个个性化推荐神经网络模型。推荐系统几乎涵盖了电商系统、社交网络、广告推荐、搜索引擎等领域的方方面面,而在图像处理、自然语言处理等领域已经发挥重要作用的深度学习技术,也将会在推荐系统领域大放异彩。\n",
+ "\n",
+ "## 参考文献\n",
+ "\n",
+ "1. [Peter Brusilovsky](https://en.wikipedia.org/wiki/Peter_Brusilovsky) (2007). *The Adaptive Web*. p. 325.\n",
+ "2. Robin Burke , [Hybrid Web Recommender Systems](http://www.dcs.warwick.ac.uk/~acristea/courses/CS411/2010/Book%20-%20The%20Adaptive%20Web/HybridWebRecommenderSystems.pdf), pp. 377-408, The Adaptive Web, Peter Brusilovsky, Alfred Kobsa, Wolfgang Nejdl (Ed.), Lecture Notes in Computer Science, Springer-Verlag, Berlin, Germany, Lecture Notes in Computer Science, Vol. 4321, May 2007, 978-3-540-72078-2.\n",
+ "3. P. Resnick, N. Iacovou, etc. “[GroupLens: An Open Architecture for Collaborative Filtering of Netnews](http://ccs.mit.edu/papers/CCSWP165.html)”, Proceedings of ACM Conference on Computer Supported Cooperative Work, CSCW 1994. pp.175-186.\n",
+ "4. Sarwar, Badrul, et al. \"[Item-based collaborative filtering recommendation algorithms.](http://files.grouplens.org/papers/www10_sarwar.pdf)\" *Proceedings of the 10th international conference on World Wide Web*. ACM, 2001.\n",
+ "5. Kautz, Henry, Bart Selman, and Mehul Shah. \"[Referral Web: combining social networks and collaborative filtering.](http://www.cs.cornell.edu/selman/papers/pdf/97.cacm.refweb.pdf)\" Communications of the ACM 40.3 (1997): 63-65. APA\n",
+ "6. Yuan, Jianbo, et al. [\"Solving Cold-Start Problem in Large-scale Recommendation Engines: A Deep Learning Approach.\"](https://arxiv.org/pdf/1611.05480v1.pdf) *arXiv preprint arXiv:1611.05480* (2016).\n",
+ "7. Covington P, Adams J, Sargin E. [Deep neural networks for youtube recommendations](https://static.googleusercontent.com/media/research.google.com/zh-CN//pubs/archive/45530.pdf)[C]//Proceedings of the 10th ACM Conference on Recommender Systems. ACM, 2016: 191-198.\n",
+ "\n",
+ "\u003cbr/\u003e\n",
+ "\u003ca rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"\u003e\u003cimg alt=\"知识共享许可协议\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /\u003e\u003c/a\u003e\u003cbr /\u003e\u003cspan xmlns:dct=\"http://purl.org/dc/terms/\" href=\"http://purl.org/dc/dcmitype/Text\" property=\"dct:title\" rel=\"dct:type\"\u003e本教程\u003c/span\u003e 由 \u003ca xmlns:cc=\"http://creativecommons.org/ns#\" href=\"http://book.paddlepaddle.org\" property=\"cc:attributionName\" rel=\"cc:attributionURL\"\u003ePaddlePaddle\u003c/a\u003e 创作,采用 \u003ca rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"\u003e知识共享 署名-非商业性使用-相同方式共享 4.0 国际 许可协议\u003c/a\u003e进行许可。\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.0"
}
- ],
- "source": [
- "import copy\n",
- "user_id = 234\n",
- "movie_id = 345\n",
- "\n",
- "user = user_info[user_id]\n",
- "movie = movie_info[movie_id]\n",
- "\n",
- "feature = user.value() + movie.value()\n",
- "\n",
- "infer_dict = copy.copy(feeding)\n",
- "del infer_dict['score']\n",
- "\n",
- "prediction = paddle.infer(output=inference, parameters=parameters, input=[feature], feeding=infer_dict)\n",
- "score = (prediction[0][0] + 5.0) / 2\n",
- "print \"[Predict] User %d Rating Movie %d With Score %.2f\"%(user_id, movie_id, score)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "deletable": true,
- "editable": true
- },
- "source": [
- "## 总结\n",
- "\n",
- "本章介绍了传统的推荐系统方法和YouTube的深度神经网络推荐系统,并以电影推荐为例,使用PaddlePaddle训练了一个个性化推荐神经网络模型。推荐系统几乎涵盖了电商系统、社交网络、广告推荐、搜索引擎等领域的方方面面,而在图像处理、自然语言处理等领域已经发挥重要作用的深度学习技术,也将会在推荐系统领域大放异彩。\n",
- "\n",
- "## 参考文献\n",
- "\n",
- "1. [Peter Brusilovsky](https://en.wikipedia.org/wiki/Peter_Brusilovsky) (2007). *The Adaptive Web*. p. 325.\n",
- "2. Robin Burke , [Hybrid Web Recommender Systems](http://www.dcs.warwick.ac.uk/~acristea/courses/CS411/2010/Book%20-%20The%20Adaptive%20Web/HybridWebRecommenderSystems.pdf), pp. 377-408, The Adaptive Web, Peter Brusilovsky, Alfred Kobsa, Wolfgang Nejdl (Ed.), Lecture Notes in Computer Science, Springer-Verlag, Berlin, Germany, Lecture Notes in Computer Science, Vol. 4321, May 2007, 978-3-540-72078-2.\n",
- "3. P. Resnick, N. Iacovou, etc. “[GroupLens: An Open Architecture for Collaborative Filtering of Netnews](http://ccs.mit.edu/papers/CCSWP165.html)”, Proceedings of ACM Conference on Computer Supported Cooperative Work, CSCW 1994. pp.175-186.\n",
- "4. Sarwar, Badrul, et al. \"[Item-based collaborative filtering recommendation algorithms.](http://files.grouplens.org/papers/www10_sarwar.pdf)\" *Proceedings of the 10th international conference on World Wide Web*. ACM, 2001.\n",
- "5. Kautz, Henry, Bart Selman, and Mehul Shah. \"[Referral Web: combining social networks and collaborative filtering.](http://www.cs.cornell.edu/selman/papers/pdf/97.cacm.refweb.pdf)\" Communications of the ACM 40.3 (1997): 63-65. APA\n",
- "6. Yuan, Jianbo, et al. [\"Solving Cold-Start Problem in Large-scale Recommendation Engines: A Deep Learning Approach.\"](https://arxiv.org/pdf/1611.05480v1.pdf) *arXiv preprint arXiv:1611.05480* (2016).\n",
- "7. Covington P, Adams J, Sargin E. [Deep neural networks for youtube recommendations](https://static.googleusercontent.com/media/research.google.com/zh-CN//pubs/archive/45530.pdf)[C]//Proceedings of the 10th ACM Conference on Recommender Systems. ACM, 2016: 191-198.\n",
- "\n",
- "
\n",
- "
本教程 由 PaddlePaddle 创作,采用 知识共享 署名-非商业性使用-相同方式共享 4.0 国际 许可协议进行许可。\n"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 2",
- "language": "python",
- "name": "python2"
},
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 2
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython2",
- "version": "2.7.13"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 0
+ "nbformat": 4,
+ "nbformat_minor": 0
}
diff --git a/recommender_system/README.md b/recommender_system/README.md
index 6f25182b7cc4cfa03e018572d1e6d005cd70a666..2e4ce1722840a56e151def6a4634a8cd3857216b 100644
--- a/recommender_system/README.md
+++ b/recommender_system/README.md
@@ -1,6 +1,6 @@
# 个性化推荐
-本教程源代码目录在[book/recommender_system](https://github.com/PaddlePaddle/book/tree/develop/recommender_system), 初次使用请参考PaddlePaddle[安装教程](http://www.paddlepaddle.org/doc_cn/build_and_install/index.html)。
+本教程源代码目录在[book/recommender_system](https://github.com/PaddlePaddle/book/tree/develop/recommender_system), 初次使用请参考PaddlePaddle[安装教程](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_cn.rst)。
## 背景介绍
diff --git a/recommender_system/common_utils.py b/recommender_system/common_utils.py
deleted file mode 100755
index c20c65286621d701ad58409b539bbe9c813d453a..0000000000000000000000000000000000000000
--- a/recommender_system/common_utils.py
+++ /dev/null
@@ -1,30 +0,0 @@
-# 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.
-from paddle.trainer.PyDataProvider2 import *
-
-
-def meta_to_header(meta, name):
- metas = meta[name]['__meta__']['raw_meta']
- for each_meta in metas:
- slot_name = each_meta.get('name', '%s_id' % name)
- if each_meta['type'] == 'id':
- yield slot_name, integer_value(each_meta['max'])
- elif each_meta['type'] == 'embedding':
- is_seq = each_meta['seq'] == 'sequence'
- yield slot_name, integer_value(
- len(each_meta['dict']),
- seq_type=SequenceType.SEQUENCE
- if is_seq else SequenceType.NO_SEQUENCE)
- elif each_meta['type'] == 'one_hot_dense':
- yield slot_name, dense_vector(len(each_meta['dict']))
diff --git a/recommender_system/data/config.json b/recommender_system/data/config.json
deleted file mode 100644
index f26e74ce47bb7843a571e6033f051c046b31f054..0000000000000000000000000000000000000000
--- a/recommender_system/data/config.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "user": {
- "file": {
- "name": "users.dat",
- "delimiter": "::"
- },
- "fields": ["id", "gender", "age", "occupation"]
- },
- "movie": {
- "file": {
- "name": "movies.dat",
- "delimiter": "::"
- },
- "fields": ["id", "title", "genres"]
- }
-}
diff --git a/recommender_system/data/config_generator.py b/recommender_system/data/config_generator.py
deleted file mode 100644
index 4ca496a252dffc62ed62bb8f2a5ee1661a940580..0000000000000000000000000000000000000000
--- a/recommender_system/data/config_generator.py
+++ /dev/null
@@ -1,127 +0,0 @@
-#!/bin/env python2
-# 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.
-"""
-config_generator.py
-
-Usage:
- ./config_generator.py [--output_format=]
- ./config_generator.py -h | --help
-
-Options:
- -h --help Show this screen.
- --output_format= Output Config format(json or yaml) [default: json].
-"""
-
-import json
-import docopt
-import copy
-
-DEFAULT_FILE = {"type": "split", "delimiter": ","}
-
-DEFAULT_FIELD = {
- "id": {
- "type": "id"
- },
- "gender": {
- "name": "gender",
- "type": "embedding",
- "dict": {
- "type": "char_based"
- }
- },
- "age": {
- "name": "age",
- "type": "embedding",
- "dict": {
- "type": "whole_content",
- "sort": True
- }
- },
- "occupation": {
- "name": "occupation",
- "type": "embedding",
- "dict": {
- "type": "whole_content",
- "sort": "true"
- }
- },
- "title": {
- "regex": {
- "pattern": r"^(.*)\((\d+)\)$",
- "group_id": 1,
- "strip": True
- },
- "name": "title",
- "type": {
- "name": "embedding",
- "seq_type": "sequence",
- },
- "dict": {
- "type": "char_based"
- }
- },
- "genres": {
- "type": "one_hot_dense",
- "dict": {
- "type": "split",
- "delimiter": "|"
- },
- "name": "genres"
- }
-}
-
-
-def merge_dict(master_dict, slave_dict):
- return dict(((k, master_dict.get(k) or slave_dict.get(k))
- for k in set(slave_dict) | set(master_dict)))
-
-
-def main(filename, fmt):
- with open(filename, 'r') as f:
- conf = json.load(f)
- obj = dict()
- for k in conf:
- val = conf[k]
- file_dict = val['file']
- file_dict = merge_dict(file_dict, DEFAULT_FILE)
-
- fields = []
- for pos, field_key in enumerate(val['fields']):
- assert isinstance(field_key, basestring)
- field = copy.deepcopy(DEFAULT_FIELD[field_key])
- field['pos'] = pos
- fields.append(field)
- obj[k] = {"file": file_dict, "fields": fields}
- meta = {"meta": obj}
- # print meta
- if fmt == 'json':
-
- def formatter(x):
- import json
- return json.dumps(x, indent=2)
- elif fmt == 'yaml':
-
- def formatter(x):
- import yaml
- return yaml.safe_dump(x, default_flow_style=False)
- else:
- raise NotImplementedError("Dump format %s is not implemented" % fmt)
-
- print formatter(meta)
-
-
-if __name__ == '__main__':
- args = docopt.docopt(__doc__, version="0.1.0")
- main(args[""], args["--output_format"])
diff --git a/recommender_system/data/getdata.sh b/recommender_system/data/getdata.sh
deleted file mode 100755
index 2268d876389e0bdf5ead405e74d278d276626f82..0000000000000000000000000000000000000000
--- a/recommender_system/data/getdata.sh
+++ /dev/null
@@ -1,23 +0,0 @@
-#!/bin/bash
-# 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.
-
-set -ex
-cd "$(dirname "$0")"
-# download the dataset
-wget http://files.grouplens.org/datasets/movielens/ml-1m.zip
-# unzip the dataset
-unzip ml-1m.zip
-# remove the unused zip file
-rm ml-1m.zip
diff --git a/recommender_system/data/meta_generator.py b/recommender_system/data/meta_generator.py
deleted file mode 100644
index 38e4679d266c331a751114cd13f0e3453016cf26..0000000000000000000000000000000000000000
--- a/recommender_system/data/meta_generator.py
+++ /dev/null
@@ -1,430 +0,0 @@
-#!/bin/env python2
-# 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.
-"""
-Preprocess Movielens dataset, to get movie/user object.
-
-Usage:
- ./preprocess.py [--config=]
- ./preprocess.py -h | --help
-
-Options:
- -h --help Show this screen.
- --version Show version.
- --config= Get MetaData config file [default: config.json].
-"""
-import docopt
-import os
-import sys
-import re
-import collections
-
-try:
- import cPickle as pickle
-except ImportError:
- import pickle
-
-
-class UniqueIDGenerator(object):
- def __init__(self):
- self.pool = collections.defaultdict(self.__next_id__)
- self.next_id = 0
-
- def __next_id__(self):
- tmp = self.next_id
- self.next_id += 1
- return tmp
-
- def __call__(self, k):
- return self.pool[k]
-
- def to_list(self):
- ret_val = [None] * len(self.pool)
- for k in self.pool.keys():
- ret_val[self.pool[k]] = k
- return ret_val
-
-
-class SortedIDGenerator(object):
- def __init__(self):
- self.__key_set__ = set()
- self.dict = None
-
- def scan(self, key):
- self.__key_set__.add(key)
-
- def finish_scan(self, compare=None, key=None, reverse=False):
- self.__key_set__ = sorted(
- list(self.__key_set__), cmp=compare, key=key, reverse=reverse)
- self.dict = dict()
- for idx, each_key in enumerate(self.__key_set__):
- self.dict[each_key] = idx
-
- def __call__(self, key):
- return self.dict[key]
-
- def to_list(self):
- return self.__key_set__
-
-
-class SplitFileReader(object):
- def __init__(self, work_dir, config):
- assert isinstance(config, dict)
- self.filename = config['name']
- self.delimiter = config.get('delimiter', ',')
- self.work_dir = work_dir
-
- def read(self):
- with open(os.path.join(self.work_dir, self.filename), 'r') as f:
- for line in f:
- line = line.strip()
- if isinstance(self.delimiter, unicode):
- self.delimiter = str(self.delimiter)
- yield line.split(self.delimiter)
-
- @staticmethod
- def create(work_dir, config):
- assert isinstance(config, dict)
- if config['type'] == 'split':
- return SplitFileReader(work_dir, config)
-
-
-class IFileReader(object):
- READERS = [SplitFileReader]
-
- def read(self):
- raise NotImplementedError()
-
- @staticmethod
- def create(work_dir, config):
- for reader_cls in IFileReader.READERS:
- val = reader_cls.create(work_dir, config)
- if val is not None:
- return val
-
-
-class IDFieldParser(object):
- TYPE = 'id'
-
- def __init__(self, config):
- self.__max_id__ = -sys.maxint - 1
- self.__min_id__ = sys.maxint
- self.__id_count__ = 0
-
- def scan(self, line):
- idx = int(line)
- self.__max_id__ = max(self.__max_id__, idx)
- self.__min_id__ = min(self.__min_id__, idx)
- self.__id_count__ += 1
-
- def parse(self, line):
- return int(line)
-
- def meta_field(self):
- return {
- "is_key": True,
- 'max': self.__max_id__,
- 'min': self.__min_id__,
- 'count': self.__id_count__,
- 'type': 'id'
- }
-
-
-class SplitEmbeddingDict(object):
- def __init__(self, delimiter):
- self.__id__ = UniqueIDGenerator()
- self.delimiter = delimiter
-
- def scan(self, multi):
- for val in multi.split(self.delimiter):
- self.__id__(val)
-
- def parse(self, multi):
- return map(self.__id__, multi.split(self.delimiter))
-
- def meta_field(self):
- return self.__id__.to_list()
-
-
-class EmbeddingFieldParser(object):
- TYPE = 'embedding'
-
- NO_SEQUENCE = "no_sequence"
- SEQUENCE = "sequence"
-
- class CharBasedEmbeddingDict(object):
- def __init__(self, is_seq=True):
- self.__id__ = UniqueIDGenerator()
- self.is_seq = is_seq
-
- def scan(self, s):
- for ch in s:
- self.__id__(ch)
-
- def parse(self, s):
- return map(self.__id__, s) if self.is_seq else self.__id__(s[0])
-
- def meta_field(self):
- return self.__id__.to_list()
-
- class WholeContentDict(object):
- def __init__(self, need_sort=True):
- assert need_sort
- self.__id__ = SortedIDGenerator()
- self.__has_finished__ = False
-
- def scan(self, txt):
- self.__id__.scan(txt)
-
- def meta_field(self):
- if not self.__has_finished__:
- self.__id__.finish_scan()
- self.__has_finished__ = True
- return self.__id__.to_list()
-
- def parse(self, txt):
- return self.__id__(txt)
-
- def __init__(self, config):
- try:
- self.seq_type = config['type']['seq_type']
- except TypeError:
- self.seq_type = EmbeddingFieldParser.NO_SEQUENCE
-
- if config['dict']['type'] == 'char_based':
- self.dict = EmbeddingFieldParser.CharBasedEmbeddingDict(
- self.seq_type == EmbeddingFieldParser.SEQUENCE)
- elif config['dict']['type'] == 'split':
- self.dict = SplitEmbeddingDict(config['dict'].get('delimiter', ','))
- elif config['dict']['type'] == 'whole_content':
- self.dict = EmbeddingFieldParser.WholeContentDict(config['dict'][
- 'sort'])
- else:
- print config
- assert False
-
- self.name = config['name']
-
- def scan(self, s):
- self.dict.scan(s)
-
- def meta_field(self):
- return {
- 'name': self.name,
- 'dict': self.dict.meta_field(),
- 'type': 'embedding',
- 'seq': self.seq_type
- }
-
- def parse(self, s):
- return self.dict.parse(s)
-
-
-class OneHotDenseFieldParser(object):
- TYPE = 'one_hot_dense'
-
- def __init__(self, config):
- if config['dict']['type'] == 'split':
- self.dict = SplitEmbeddingDict(config['dict']['delimiter'])
- self.name = config['name']
-
- def scan(self, s):
- self.dict.scan(s)
-
- def meta_field(self):
- # print self.dict.meta_field()
- return {
- 'dict': self.dict.meta_field(),
- 'name': self.name,
- 'type': 'one_hot_dense'
- }
-
- def parse(self, s):
- ids = self.dict.parse(s)
- retv = [0.0] * len(self.dict.meta_field())
- for idx in ids:
- retv[idx] = 1.0
- # print retv
- return retv
-
-
-class FieldParserFactory(object):
- PARSERS = [IDFieldParser, EmbeddingFieldParser, OneHotDenseFieldParser]
-
- @staticmethod
- def create(config):
- if isinstance(config['type'], basestring):
- config_type = config['type']
- elif isinstance(config['type'], dict):
- config_type = config['type']['name']
-
- assert config_type is not None
-
- for each_parser_cls in FieldParserFactory.PARSERS:
- if config_type == each_parser_cls.TYPE:
- return each_parser_cls(config)
- print config
-
-
-class CompositeFieldParser(object):
- def __init__(self, parser, extractor):
- self.extractor = extractor
- self.parser = parser
-
- def scan(self, *args, **kwargs):
- self.parser.scan(self.extractor.extract(*args, **kwargs))
-
- def parse(self, *args, **kwargs):
- return self.parser.parse(self.extractor.extract(*args, **kwargs))
-
- def meta_field(self):
- return self.parser.meta_field()
-
-
-class PositionContentExtractor(object):
- def __init__(self, pos):
- self.pos = pos
-
- def extract(self, line):
- assert isinstance(line, list)
- return line[self.pos]
-
-
-class RegexPositionContentExtractor(PositionContentExtractor):
- def __init__(self, pos, pattern, group_id, strip=True):
- PositionContentExtractor.__init__(self, pos)
- pattern = pattern.strip()
- self.pattern = re.compile(pattern)
- self.group_id = group_id
- self.strip = strip
-
- def extract(self, line):
- line = PositionContentExtractor.extract(self, line)
- match = self.pattern.match(line)
- # print line, self.pattern.pattern, match
- assert match is not None
- txt = match.group(self.group_id)
- if self.strip:
- txt.strip()
- return txt
-
-
-class ContentExtractorFactory(object):
- def extract(self, line):
- pass
-
- @staticmethod
- def create(config):
- if 'pos' in config:
- if 'regex' not in config:
- return PositionContentExtractor(config['pos'])
- else:
- extra_args = config['regex']
- return RegexPositionContentExtractor(
- pos=config['pos'], **extra_args)
-
-
-class MetaFile(object):
- def __init__(self, work_dir):
- self.work_dir = work_dir
- self.obj = dict()
-
- def parse(self, config):
- config = config['meta']
-
- ret_obj = dict()
- for key in config.keys():
- val = config[key]
- assert 'file' in val
- reader = IFileReader.create(self.work_dir, val['file'])
- assert reader is not None
- assert 'fields' in val and isinstance(val['fields'], list)
- fields_config = val['fields']
- field_parsers = map(MetaFile.__field_config_mapper__, fields_config)
-
- for each_parser in field_parsers:
- assert each_parser is not None
-
- for each_block in reader.read():
- for each_parser in field_parsers:
- each_parser.scan(each_block)
-
- metas = map(lambda x: x.meta_field(), field_parsers)
- # print metas
- key_index = filter(
- lambda x: x is not None,
- map(lambda (idx, meta): idx if 'is_key' in meta and meta['is_key'] else None,
- enumerate(metas)))[0]
-
- key_map = []
- for i in range(min(key_index, len(metas))):
- key_map.append(i)
- for i in range(key_index + 1, len(metas)):
- key_map.append(i)
-
- obj = {'__meta__': {'raw_meta': metas, 'feature_map': key_map}}
-
- for each_block in reader.read():
- idx = field_parsers[key_index].parse(each_block)
- val = []
- for i, each_parser in enumerate(field_parsers):
- if i != key_index:
- val.append(each_parser.parse(each_block))
- obj[idx] = val
- ret_obj[key] = obj
- self.obj = ret_obj
- return ret_obj
-
- @staticmethod
- def __field_config_mapper__(conf):
- assert isinstance(conf, dict)
- extrator = ContentExtractorFactory.create(conf)
- field_parser = FieldParserFactory.create(conf)
- assert extrator is not None
- assert field_parser is not None
- return CompositeFieldParser(field_parser, extrator)
-
- def dump(self, fp):
- pickle.dump(self.obj, fp, pickle.HIGHEST_PROTOCOL)
-
-
-def preprocess(binary_filename, dataset_dir, config, **kwargs):
- assert isinstance(config, str)
- with open(config, 'r') as config_file:
- file_loader = None
- if config.lower().endswith('.yaml'):
- import yaml
- file_loader = yaml
- elif config.lower().endswith('.json'):
- import json
- file_loader = json
- config = file_loader.load(config_file)
- meta = MetaFile(dataset_dir)
- meta.parse(config)
- with open(binary_filename, 'wb') as outf:
- meta.dump(outf)
-
-
-if __name__ == '__main__':
- args = docopt.docopt(__doc__, version='0.1.0')
- kwargs = dict()
- for key in args.keys():
- if key != '--help':
- param_name = key
- assert isinstance(param_name, str)
- param_name = param_name.replace('<', '')
- param_name = param_name.replace('>', '')
- param_name = param_name.replace('--', '')
- kwargs[param_name] = args[key]
- preprocess(**kwargs)
diff --git a/recommender_system/data/requirements.txt b/recommender_system/data/requirements.txt
deleted file mode 100644
index 1ea154584a428b6a389309f1f8def502e0aadfce..0000000000000000000000000000000000000000
--- a/recommender_system/data/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-PyYAML
-docopt
diff --git a/recommender_system/data/split.py b/recommender_system/data/split.py
deleted file mode 100644
index be6869c22f04be1db0f8e9c35c73c851e4c490b0..0000000000000000000000000000000000000000
--- a/recommender_system/data/split.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/bin/env python2
-# 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.
-"""
-Separate movielens 1m dataset to train/test file.
-
-Usage:
- ./separate.py [--test_ratio=] [--delimiter=]
- ./separate.py -h | --help
-
-Options:
- -h --help Show this screen.
- --version Show version.
- --test_ratio= Test ratio for separate [default: 0.1].
- --delimiter= File delimiter [default: ,].
-"""
-import docopt
-import collections
-import random
-
-
-def process(test_ratio, input_file, delimiter, **kwargs):
- test_ratio = float(test_ratio)
- rating_dict = collections.defaultdict(list)
- with open(input_file, 'r') as f:
- for line in f:
- user_id = int(line.split(delimiter)[0])
- rating_dict[user_id].append(line.strip())
-
- with open(input_file + ".train", 'w') as train_file:
- with open(input_file + ".test", 'w') as test_file:
- for k in rating_dict.keys():
- lines = rating_dict[k]
- assert isinstance(lines, list)
- random.shuffle(lines)
- test_len = int(len(lines) * test_ratio)
- for line in lines[:test_len]:
- print >> test_file, line
-
- for line in lines[test_len:]:
- print >> train_file, line
-
-
-if __name__ == '__main__':
- args = docopt.docopt(__doc__, version='0.1.0')
- kwargs = dict()
- for key in args.keys():
- if key != '--help':
- param_name = key
- assert isinstance(param_name, str)
- param_name = param_name.replace('<', '')
- param_name = param_name.replace('>', '')
- param_name = param_name.replace('--', '')
- kwargs[param_name] = args[key]
- process(**kwargs)
diff --git a/recommender_system/dataprovider.py b/recommender_system/dataprovider.py
deleted file mode 100755
index 54a5ea6fb8e59fa559a394a0c2ec7ac07d89c2f8..0000000000000000000000000000000000000000
--- a/recommender_system/dataprovider.py
+++ /dev/null
@@ -1,87 +0,0 @@
-# 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.
-
-from paddle.trainer.PyDataProvider2 import *
-from common_utils import meta_to_header
-
-
-def __list_to_map__(lst):
- ret_val = dict()
- for each in lst:
- k, v = each
- ret_val[k] = v
- return ret_val
-
-
-def hook(settings, meta, **kwargs):
- """
- Init hook is invoked before process data. It will set obj.slots and store
- data meta.
-
- :param obj: global object. It will passed to process routine.
- :type obj: object
- :param meta: the meta file object, which passed from trainer_config. Meta
- file record movie/user features.
- :param kwargs: unused other arguments.
- """
-
- # Header define slots that used for paddle.
- # first part is movie features.
- # second part is user features.
- # final part is rating score.
- # header is a list of [USE_SEQ_OR_NOT?, SlotType]
- movie_headers = list(meta_to_header(meta, 'movie'))
- settings.movie_names = [h[0] for h in movie_headers]
- headers = movie_headers
- user_headers = list(meta_to_header(meta, 'user'))
- settings.user_names = [h[0] for h in user_headers]
- headers.extend(user_headers)
- headers.append(("rating", dense_vector(1))) # Score
-
- # slot types.
- settings.input_types = __list_to_map__(headers)
- settings.meta = meta
-
-
-@provider(init_hook=hook, cache=CacheType.CACHE_PASS_IN_MEM)
-def process(settings, filename):
- with open(filename, 'r') as f:
- for line in f:
- # Get a rating from file.
- user_id, movie_id, score = map(int, line.split('::')[:-1])
-
- # Scale score to [-2, +2]
- score = float(score - 3)
-
- # Get movie/user features by movie_id, user_id
- movie_meta = settings.meta['movie'][movie_id]
- user_meta = settings.meta['user'][user_id]
-
- outputs = [('movie_id', movie_id - 1)]
-
- # Then add movie features
- for i, each_meta in enumerate(movie_meta):
- outputs.append((settings.movie_names[i + 1], each_meta))
-
- # Then add user id.
- outputs.append(('user_id', user_id - 1))
-
- # Then add user features.
- for i, each_meta in enumerate(user_meta):
- outputs.append((settings.user_names[i + 1], each_meta))
-
- # Finally, add score
- outputs.append(('rating', [score]))
- # Return data to paddle
- yield __list_to_map__(outputs)
diff --git a/recommender_system/evaluate.py b/recommender_system/evaluate.py
deleted file mode 100755
index 3afa7a1e9db5fefb1bbf5aaa174b8168afae4058..0000000000000000000000000000000000000000
--- a/recommender_system/evaluate.py
+++ /dev/null
@@ -1,37 +0,0 @@
-#!/usr/bin/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 math
-
-
-def get_best_pass(log_filename):
- with open(log_filename, 'r') as f:
- text = f.read()
- pattern = re.compile('Test.*? cost=([0-9]+\.[0-9]+).*?pass-([0-9]+)',
- re.S)
- results = re.findall(pattern, text)
- sorted_results = sorted(results, key=lambda result: float(result[0]))
- return sorted_results[0]
-
-
-log_filename = sys.argv[1]
-log = get_best_pass(log_filename)
-predict_error = math.sqrt(float(log[0])) / 2
-print 'Best pass is %s, error is %s, which means predict get error as %f' % (
- log[1], log[0], predict_error)
-
-evaluate_pass = "output/pass-%s" % log[1]
-print "evaluating from pass %s" % evaluate_pass
diff --git a/recommender_system/index.en.html b/recommender_system/index.en.html
index 5b4e9ae391b1b6a16a8a99c6c4e2dbddaeb29851..46b4682750597d26be6486a3f7763dc77c171b48 100644
--- a/recommender_system/index.en.html
+++ b/recommender_system/index.en.html
@@ -44,6 +44,9 @@
The source code of this tutorial is in [book/recommender_system](https://github.com/PaddlePaddle/book/tree/develop/recommender_system).
+For instructions on getting started with PaddlePaddle, see [PaddlePaddle installation guide](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_en.rst).
+
+
## Background
With the fast growth of e-commerce, online videos, and online reading business, users have to rely on recommender systems to avoid manually browsing tremendous volume of choices. Recommender systems understand users' interest by mining user behavior and other properties of users and products.
@@ -118,22 +121,287 @@ Figure 3. A hybrid recommendation model.
## Dataset
-We use the [MovieLens ml-1m](http://files.grouplens.org/datasets/movielens/ml-1m.zip) to train our model. This dataset includes 10,000 ratings of 4,000 movies from 6,000 users to 4,000 movies. Each rate is in the range of 1~5. Thanks to GroupLens Research for collecting, processing and publishing the dataset.
+We use the [MovieLens ml-1m](http://files.grouplens.org/datasets/movielens/ml-1m.zip) to train our model. This dataset includes 10,000 ratings of 4,000 movies from 6,000 users to 4,000 movies. Each rate is in the range of 1~5. Thanks to GroupLens Research for collecting, processing and publishing the dataset.
+
+`paddle.v2.datasets` package encapsulates multiple public datasets, including `cifar`, `imdb`, `mnist`, `moivelens` and `wmt14`, etc. There's no need for us to manually download and preprocess `MovieLens` dataset.
+
+```python
+# Run this block to show dataset's documentation
+help(paddle.v2.dataset.movielens)
+```
+
+The raw `MoiveLens` contains movie ratings, relevant features from both movies and users.
+For instance, one movie's feature could be:
+
+```python
+movie_info = paddle.dataset.movielens.movie_info()
+print movie_info.values()[0]
+```
+
+```text
+
+```
+
+One user's feature could be:
+
+```python
+user_info = paddle.dataset.movielens.user_info()
+print user_info.values()[0]
+```
+
+```text
+
+```
+
+In this dateset, the distribution of age is shown as follows:
+
+```text
+1: "Under 18"
+18: "18-24"
+25: "25-34"
+35: "35-44"
+45: "45-49"
+50: "50-55"
+56: "56+"
+```
+
+User's occupation is selected from the following options:
+
+```text
+0: "other" or not specified
+1: "academic/educator"
+2: "artist"
+3: "clerical/admin"
+4: "college/grad student"
+5: "customer service"
+6: "doctor/health care"
+7: "executive/managerial"
+8: "farmer"
+9: "homemaker"
+10: "K-12 student"
+11: "lawyer"
+12: "programmer"
+13: "retired"
+14: "sales/marketing"
+15: "scientist"
+16: "self-employed"
+17: "technician/engineer"
+18: "tradesman/craftsman"
+19: "unemployed"
+20: "writer"
+```
+
+Each record consists of three main components: user features, movie features and movie ratings.
+Likewise, as a simple example, consider the following:
+
+```python
+train_set_creator = paddle.dataset.movielens.train()
+train_sample = next(train_set_creator())
+uid = train_sample[0]
+mov_id = train_sample[len(user_info[uid].value())]
+print "User %s rates Movie %s with Score %s"%(user_info[uid], movie_info[mov_id], train_sample[-1])
+```
+
+```text
+User rates Movie with Score [5.0]
+```
+
+The output shows that user 1 gave movie `1193` a rating of 5.
+
+After issuing a command `python train.py`, training will start immediately. The details will be unpacked by the following sessions to see how it works.
+
+## Model Architecture
+
+### Initialize PaddlePaddle
+
+First, we must import and initialize PaddlePaddle (enable/disable GPU, set the number of trainers, etc).
+
+```python
+%matplotlib inline
+
+import matplotlib.pyplot as plt
+from IPython import display
+import cPickle
+
+import paddle.v2 as paddle
+
+paddle.init(use_gpu=False)
+```
+
+### Model Configuration
+
+```python
+uid = paddle.layer.data(
+ name='user_id',
+ type=paddle.data_type.integer_value(
+ paddle.dataset.movielens.max_user_id() + 1))
+usr_emb = paddle.layer.embedding(input=uid, size=32)
+
+usr_gender_id = paddle.layer.data(
+ name='gender_id', type=paddle.data_type.integer_value(2))
+usr_gender_emb = paddle.layer.embedding(input=usr_gender_id, size=16)
+
+usr_age_id = paddle.layer.data(
+ name='age_id',
+ type=paddle.data_type.integer_value(
+ len(paddle.dataset.movielens.age_table)))
+usr_age_emb = paddle.layer.embedding(input=usr_age_id, size=16)
+
+usr_job_id = paddle.layer.data(
+ name='job_id',
+ type=paddle.data_type.integer_value(paddle.dataset.movielens.max_job_id(
+ ) + 1))
+usr_job_emb = paddle.layer.embedding(input=usr_job_id, size=16)
+```
+
+As shown in the above code, the input is four dimension integers for each user, that is, `user_id`,`gender_id`, `age_id` and `job_id`. In order to deal with these features conveniently, we use the language model in NLP to transform these discrete values into embedding vaules `usr_emb`, `usr_gender_emb`, `usr_age_emb` and `usr_job_emb`.
+
+```python
+usr_combined_features = paddle.layer.fc(
+ input=[usr_emb, usr_gender_emb, usr_age_emb, usr_job_emb],
+ size=200,
+ act=paddle.activation.Tanh())
+```
+
+Then, employing user features as input, directly connecting to a fully-connected layer, which is used to reduce dimension to 200.
+
+Furthermore, we do a similar transformation for each movie feature. The model configuration is:
+
+```python
+mov_id = paddle.layer.data(
+ name='movie_id',
+ type=paddle.data_type.integer_value(
+ paddle.dataset.movielens.max_movie_id() + 1))
+mov_emb = paddle.layer.embedding(input=mov_id, size=32)
+
+mov_categories = paddle.layer.data(
+ name='category_id',
+ type=paddle.data_type.sparse_binary_vector(
+ len(paddle.dataset.movielens.movie_categories())))
+
+mov_categories_hidden = paddle.layer.fc(input=mov_categories, size=32)
+
-We don't have to download and preprocess the data. Instead, we can use PaddlePaddle's dataset module `paddle.v2.dataset.movielens`.
+movie_title_dict = paddle.dataset.movielens.get_movie_title_dict()
+mov_title_id = paddle.layer.data(
+ name='movie_title',
+ type=paddle.data_type.integer_value_sequence(len(movie_title_dict)))
+mov_title_emb = paddle.layer.embedding(input=mov_title_id, size=32)
+mov_title_conv = paddle.networks.sequence_conv_pool(
+ input=mov_title_emb, hidden_size=32, context_len=3)
+mov_combined_features = paddle.layer.fc(
+ input=[mov_emb, mov_categories_hidden, mov_title_conv],
+ size=200,
+ act=paddle.activation.Tanh())
+```
-## Model Specification
+Movie title, a sequence of words represented by an integer word index sequence, will be feed into a `sequence_conv_pool` layer, which will apply convolution and pooling on time dimension. Because pooling is done on time dimension, the output will be a fixed-length vector regardless the length of the input sequence.
+Finally, we can use cosine similarity to calculate the similarity between user characteristics and movie features.
+```python
+inference = paddle.layer.cos_sim(a=usr_combined_features, b=mov_combined_features, size=1, scale=5)
+cost = paddle.layer.regression_cost(
+ input=inference,
+ label=paddle.layer.data(
+ name='score', type=paddle.data_type.dense_vector(1)))
+```
-## Training
+## Model Training
+### Define Parameters
+First, we define the model parameters according to the previous model configuration `cost`.
-## Inference
+```python
+# Create parameters
+parameters = paddle.parameters.create(cost)
+```
+### Create Trainer
+
+Before jumping into creating a training module, algorithm setting is also necessary. Here we specified Adam optimization algorithm via `paddle.optimizer`.
+```python
+trainer = paddle.trainer.SGD(cost=cost, parameters=parameters,
+ update_equation=paddle.optimizer.Adam(learning_rate=1e-4))
+```
+
+```text
+[INFO 2017-03-06 17:12:13,378 networks.py:1472] The input order is [user_id, gender_id, age_id, job_id, movie_id, category_id, movie_title, score]
+[INFO 2017-03-06 17:12:13,379 networks.py:1478] The output order is [__regression_cost_0__]
+```
+
+### Training
+
+`paddle.dataset.movielens.train` will yield records during each pass, after shuffling, a batch input is generated for training.
+
+```python
+reader=paddle.reader.batch(
+ paddle.reader.shuffle(
+ paddle.dataset.movielens.trai(), buf_size=8192),
+ batch_size=256)
+```
+
+`feeding` is devoted to specifying the correspondence between each yield record and `paddle.layer.data`. For instance, the first column of data generated by `movielens.train` corresponds to `user_id` feature.
+
+```python
+feeding = {
+ 'user_id': 0,
+ 'gender_id': 1,
+ 'age_id': 2,
+ 'job_id': 3,
+ 'movie_id': 4,
+ 'category_id': 5,
+ 'movie_title': 6,
+ 'score': 7
+}
+```
+
+Callback function `event_handler` will be called during training when a pre-defined event happens.
+
+```python
+step=0
+
+train_costs=[],[]
+test_costs=[],[]
+
+def event_handler(event):
+ global step
+ global train_costs
+ global test_costs
+ if isinstance(event, paddle.event.EndIteration):
+ need_plot = False
+ if step % 10 == 0: # every 10 batches, record a train cost
+ train_costs[0].append(step)
+ train_costs[1].append(event.cost)
+
+ if step % 1000 == 0: # every 1000 batches, record a test cost
+ result = trainer.test(reader=paddle.batch(
+ paddle.dataset.movielens.test(), batch_size=256))
+ test_costs[0].append(step)
+ test_costs[1].append(result.cost)
+
+ if step % 100 == 0: # every 100 batches, update cost plot
+ plt.plot(*train_costs)
+ plt.plot(*test_costs)
+ plt.legend(['Train Cost', 'Test Cost'], loc='upper left')
+ display.clear_output(wait=True)
+ display.display(plt.gcf())
+ plt.gcf().clear()
+ step += 1
+```
+
+Finally, we can invoke `trainer.train` to start training:
+
+```python
+trainer.train(
+ reader=reader,
+ event_handler=event_handler,
+ feeding=feeding,
+ num_passes=200)
+```
## Conclusion
@@ -141,16 +409,16 @@ This tutorial goes over traditional approaches in recommender system and a deep
## Reference
-1. [Peter Brusilovsky](https://en.wikipedia.org/wiki/Peter_Brusilovsky) (2007). *The Adaptive Web*. p. 325.
-2. Robin Burke , [Hybrid Web Recommender Systems](http://www.dcs.warwick.ac.uk/~acristea/courses/CS411/2010/Book%20-%20The%20Adaptive%20Web/HybridWebRecommenderSystems.pdf), pp. 377-408, The Adaptive Web, Peter Brusilovsky, Alfred Kobsa, Wolfgang Nejdl (Ed.), Lecture Notes in Computer Science, Springer-Verlag, Berlin, Germany, Lecture Notes in Computer Science, Vol. 4321, May 2007, 978-3-540-72078-2.
+1. [Peter Brusilovsky](https://en.wikipedia.org/wiki/Peter_Brusilovsky) (2007). *The Adaptive Web*. p. 325.
+2. Robin Burke , [Hybrid Web Recommender Systems](http://www.dcs.warwick.ac.uk/~acristea/courses/CS411/2010/Book%20-%20The%20Adaptive%20Web/HybridWebRecommenderSystems.pdf), pp. 377-408, The Adaptive Web, Peter Brusilovsky, Alfred Kobsa, Wolfgang Nejdl (Ed.), Lecture Notes in Computer Science, Springer-Verlag, Berlin, Germany, Lecture Notes in Computer Science, Vol. 4321, May 2007, 978-3-540-72078-2.
3. P. Resnick, N. Iacovou, etc. “[GroupLens: An Open Architecture for Collaborative Filtering of Netnews](http://ccs.mit.edu/papers/CCSWP165.html)”, Proceedings of ACM Conference on Computer Supported Cooperative Work, CSCW 1994. pp.175-186.
-4. Sarwar, Badrul, et al. "[Item-based collaborative filtering recommendation algorithms.](http://files.grouplens.org/papers/www10_sarwar.pdf)" *Proceedings of the 10th International Conference on World Wide Web*. ACM, 2001.
+4. Sarwar, Badrul, et al. "[Item-based collaborative filtering recommendation algorithms.](http://files.grouplens.org/papers/www10_sarwar.pdf)" *Proceedings of the 10th International Conference on World Wide Web*. ACM, 2001.
5. Kautz, Henry, Bart Selman, and Mehul Shah. "[Referral Web: Combining Social networks and collaborative filtering.](http://www.cs.cornell.edu/selman/papers/pdf/97.cacm.refweb.pdf)" Communications of the ACM 40.3 (1997): 63-65. APA
-6. Yuan, Jianbo, et al. ["Solving Cold-Start Problem in Large-scale Recommendation Engines: A Deep Learning Approach."](https://arxiv.org/pdf/1611.05480v1.pdf) *arXiv preprint arXiv:1611.05480* (2016).
+6. Yuan, Jianbo, et al. ["Solving Cold-Start Problem in Large-scale Recommendation Engines: A Deep Learning Approach."](https://arxiv.org/pdf/1611.05480v1.pdf) *arXiv preprint arXiv:1611.05480* (2016).
7. Covington P, Adams J, Sargin E. [Deep neural networks for youtube recommendations](https://static.googleusercontent.com/media/research.google.com/zh-CN//pubs/archive/45530.pdf)[C]//Proceedings of the 10th ACM Conference on Recommender Systems. ACM, 2016: 191-198.
-
This tutorial was created by the PaddlePaddle community and published under Common Creative 4.0 License。
+This tutorial is contributed by PaddlePaddle, and licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
diff --git a/recommender_system/index.html b/recommender_system/index.html
index 20846ca39e84847e08aaa794fe4ca0e9d4b81a50..9d5e1ba25224e19e7d21493b2ac2e8119e04a7d9 100644
--- a/recommender_system/index.html
+++ b/recommender_system/index.html
@@ -42,7 +42,7 @@
# 个性化推荐
-本教程源代码目录在[book/recommender_system](https://github.com/PaddlePaddle/book/tree/develop/recommender_system), 初次使用请参考PaddlePaddle[安装教程](http://www.paddlepaddle.org/doc_cn/build_and_install/index.html)。
+本教程源代码目录在[book/recommender_system](https://github.com/PaddlePaddle/book/tree/develop/recommender_system), 初次使用请参考PaddlePaddle[安装教程](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_cn.rst)。
## 背景介绍
diff --git a/recommender_system/prediction.py b/recommender_system/prediction.py
deleted file mode 100755
index 9824d132d276dfe4ff4ea336d8c6b483949b9d08..0000000000000000000000000000000000000000
--- a/recommender_system/prediction.py
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/bin/env python2
-# 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.
-
-from py_paddle import swig_paddle, DataProviderConverter
-
-from common_utils import *
-from paddle.trainer.config_parser import parse_config
-
-try:
- import cPickle as pickle
-except ImportError:
- import pickle
-import sys
-
-if __name__ == '__main__':
- model_path = sys.argv[1]
- swig_paddle.initPaddle('--use_gpu=0')
- conf = parse_config("trainer_config.py", "is_predict=1")
- network = swig_paddle.GradientMachine.createFromConfigProto(
- conf.model_config)
- assert isinstance(network, swig_paddle.GradientMachine)
- network.loadParameters(model_path)
- with open('./data/meta.bin', 'rb') as f:
- meta = pickle.load(f)
- headers = [h[1] for h in meta_to_header(meta, 'movie')]
- headers.extend([h[1] for h in meta_to_header(meta, 'user')])
- cvt = DataProviderConverter(headers)
- while True:
- movie_id = int(raw_input("Input movie_id: "))
- user_id = int(raw_input("Input user_id: "))
- movie_meta = meta['movie'][movie_id] # Query Data From Meta.
- user_meta = meta['user'][user_id]
- data = [movie_id - 1]
- data.extend(movie_meta)
- data.append(user_id - 1)
- data.extend(user_meta)
- print "Prediction Score is %.2f" % (
- network.forwardTest(cvt.convert([data]))[0]['value'][0][0] + 3)
diff --git a/recommender_system/preprocess.sh b/recommender_system/preprocess.sh
deleted file mode 100755
index 9603f7997d6fb46411b169e780a262def7a398b3..0000000000000000000000000000000000000000
--- a/recommender_system/preprocess.sh
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/bin/bash
-# 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.
-set -e
-
-UNAME_STR=`uname`
-
-if [[ ${UNAME_STR} == 'Linux' ]]; then
- SHUF_PROG='shuf'
-else
- SHUF_PROG='gshuf'
-fi
-
-
-cd "$(dirname "$0")"
-delimiter='::'
-dir=ml-1m
-cd data
-echo 'generate meta config file'
-python config_generator.py config.json > meta_config.json
-echo 'generate meta file'
-python meta_generator.py $dir meta.bin --config=meta_config.json
-echo 'split train/test file'
-python split.py $dir/ratings.dat --delimiter=${delimiter} --test_ratio=0.1
-echo 'shuffle train file'
-${SHUF_PROG} $dir/ratings.dat.train > ratings.dat.train
-cp $dir/ratings.dat.test .
-echo "./data/ratings.dat.train" > train.list
-echo "./data/ratings.dat.test" > test.list
diff --git a/recommender_system/train.py b/recommender_system/train.py
new file mode 100644
index 0000000000000000000000000000000000000000..62af9921feec5269e723ad6df8cbaaa9b0098bfe
--- /dev/null
+++ b/recommender_system/train.py
@@ -0,0 +1,124 @@
+import paddle.v2 as paddle
+import cPickle
+import copy
+
+
+def main():
+ paddle.init(use_gpu=False)
+ movie_title_dict = paddle.dataset.movielens.get_movie_title_dict()
+ uid = paddle.layer.data(
+ name='user_id',
+ type=paddle.data_type.integer_value(
+ paddle.dataset.movielens.max_user_id() + 1))
+ usr_emb = paddle.layer.embedding(input=uid, size=32)
+
+ usr_gender_id = paddle.layer.data(
+ name='gender_id', type=paddle.data_type.integer_value(2))
+ usr_gender_emb = paddle.layer.embedding(input=usr_gender_id, size=16)
+
+ usr_age_id = paddle.layer.data(
+ name='age_id',
+ type=paddle.data_type.integer_value(
+ len(paddle.dataset.movielens.age_table)))
+ usr_age_emb = paddle.layer.embedding(input=usr_age_id, size=16)
+
+ usr_job_id = paddle.layer.data(
+ name='job_id',
+ type=paddle.data_type.integer_value(
+ paddle.dataset.movielens.max_job_id() + 1))
+
+ usr_job_emb = paddle.layer.embedding(input=usr_job_id, size=16)
+
+ usr_combined_features = paddle.layer.fc(
+ input=[usr_emb, usr_gender_emb, usr_age_emb, usr_job_emb],
+ size=200,
+ act=paddle.activation.Tanh())
+
+ mov_id = paddle.layer.data(
+ name='movie_id',
+ type=paddle.data_type.integer_value(
+ paddle.dataset.movielens.max_movie_id() + 1))
+ mov_emb = paddle.layer.embedding(input=mov_id, size=32)
+
+ mov_categories = paddle.layer.data(
+ name='category_id',
+ type=paddle.data_type.sparse_binary_vector(
+ len(paddle.dataset.movielens.movie_categories())))
+
+ mov_categories_hidden = paddle.layer.fc(input=mov_categories, size=32)
+
+ mov_title_id = paddle.layer.data(
+ name='movie_title',
+ type=paddle.data_type.integer_value_sequence(len(movie_title_dict)))
+ mov_title_emb = paddle.layer.embedding(input=mov_title_id, size=32)
+ mov_title_conv = paddle.networks.sequence_conv_pool(
+ input=mov_title_emb, hidden_size=32, context_len=3)
+
+ mov_combined_features = paddle.layer.fc(
+ input=[mov_emb, mov_categories_hidden, mov_title_conv],
+ size=200,
+ act=paddle.activation.Tanh())
+
+ inference = paddle.layer.cos_sim(
+ a=usr_combined_features, b=mov_combined_features, size=1, scale=5)
+ cost = paddle.layer.regression_cost(
+ input=inference,
+ label=paddle.layer.data(
+ name='score', type=paddle.data_type.dense_vector(1)))
+
+ parameters = paddle.parameters.create(cost)
+
+ trainer = paddle.trainer.SGD(
+ cost=cost,
+ parameters=parameters,
+ update_equation=paddle.optimizer.Adam(learning_rate=1e-4))
+ feeding = {
+ 'user_id': 0,
+ 'gender_id': 1,
+ 'age_id': 2,
+ 'job_id': 3,
+ 'movie_id': 4,
+ 'category_id': 5,
+ 'movie_title': 6,
+ 'score': 7
+ }
+
+ def event_handler(event):
+ if isinstance(event, paddle.event.EndIteration):
+ if event.batch_id % 100 == 0:
+ print "Pass %d Batch %d Cost %.2f" % (
+ event.pass_id, event.batch_id, event.cost)
+
+ trainer.train(
+ reader=paddle.batch(
+ paddle.reader.shuffle(
+ paddle.dataset.movielens.train(), buf_size=8192),
+ batch_size=256),
+ event_handler=event_handler,
+ feeding=feeding,
+ num_passes=1)
+
+ user_id = 234
+ movie_id = 345
+
+ user = paddle.dataset.movielens.user_info()[user_id]
+ movie = paddle.dataset.movielens.movie_info()[movie_id]
+
+ feature = user.value() + movie.value()
+
+ def reader():
+ yield feature
+
+ infer_dict = copy.copy(feeding)
+ del infer_dict['score']
+
+ prediction = paddle.infer(
+ output_layer=inference,
+ parameters=parameters,
+ input=[feature],
+ feeding=infer_dict)
+ print(prediction + 5) / 2
+
+
+if __name__ == '__main__':
+ main()
diff --git a/recommender_system/train.sh b/recommender_system/train.sh
deleted file mode 100755
index e341d1cc7a3267bef9db916719b2e4b1981e31bc..0000000000000000000000000000000000000000
--- a/recommender_system/train.sh
+++ /dev/null
@@ -1,24 +0,0 @@
-#!/bin/bash
-# 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.
-set -e
-paddle train \
- --config=trainer_config.py \
- --save_dir=./output \
- --use_gpu=false \
- --trainer_count=4\
- --test_all_data_in_one_period=true \
- --log_period=100 \
- --dot_period=1 \
- --num_passes=50 2>&1 | tee 'log.txt'
diff --git a/recommender_system/trainer_config.py b/recommender_system/trainer_config.py
deleted file mode 100755
index c2eeb7b874c7667809a401347f43b873b8dea92a..0000000000000000000000000000000000000000
--- a/recommender_system/trainer_config.py
+++ /dev/null
@@ -1,92 +0,0 @@
-# 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.
-
-from paddle.trainer_config_helpers import *
-
-try:
- import cPickle as pickle
-except ImportError:
- import pickle
-
-is_predict = get_config_arg('is_predict', bool, False)
-
-META_FILE = 'data/meta.bin'
-
-with open(META_FILE, 'rb') as f:
- # load meta file
- meta = pickle.load(f)
-
-if not is_predict:
- define_py_data_sources2(
- 'data/train.list',
- 'data/test.list',
- module='dataprovider',
- obj='process',
- args={'meta': meta})
-
-settings(
- batch_size=1600, learning_rate=1e-3, learning_method=RMSPropOptimizer())
-
-movie_meta = meta['movie']['__meta__']['raw_meta']
-user_meta = meta['user']['__meta__']['raw_meta']
-
-movie_id = data_layer('movie_id', size=movie_meta[0]['max'])
-title = data_layer('title', size=len(movie_meta[1]['dict']))
-genres = data_layer('genres', size=len(movie_meta[2]['dict']))
-user_id = data_layer('user_id', size=user_meta[0]['max'])
-gender = data_layer('gender', size=len(user_meta[1]['dict']))
-age = data_layer('age', size=len(user_meta[2]['dict']))
-occupation = data_layer('occupation', size=len(user_meta[3]['dict']))
-
-embsize = 256
-
-# construct movie feature
-movie_id_emb = embedding_layer(input=movie_id, size=embsize)
-movie_id_hidden = fc_layer(input=movie_id_emb, size=embsize)
-
-genres_emb = fc_layer(input=genres, size=embsize)
-
-title_emb = embedding_layer(input=title, size=embsize)
-title_hidden = text_conv_pool(
- input=title_emb, context_len=5, hidden_size=embsize)
-
-movie_feature = fc_layer(
- input=[movie_id_hidden, title_hidden, genres_emb], size=embsize)
-
-# construct user feature
-user_id_emb = embedding_layer(input=user_id, size=embsize)
-user_id_hidden = fc_layer(input=user_id_emb, size=embsize)
-
-gender_emb = embedding_layer(input=gender, size=embsize)
-gender_hidden = fc_layer(input=gender_emb, size=embsize)
-
-age_emb = embedding_layer(input=age, size=embsize)
-age_hidden = fc_layer(input=age_emb, size=embsize)
-
-occup_emb = embedding_layer(input=occupation, size=embsize)
-occup_hidden = fc_layer(input=occup_emb, size=embsize)
-
-user_feature = fc_layer(
- input=[user_id_hidden, gender_hidden, age_hidden, occup_hidden],
- size=embsize)
-
-similarity = cos_sim(a=movie_feature, b=user_feature, scale=2)
-
-if not is_predict:
- lbl = data_layer('rating', size=1)
- cost = regression_cost(input=similarity, label=lbl)
- outputs(cost)
-
-else:
- outputs(similarity)
diff --git a/tools/convert-markdown-into-ipynb-and-test.sh b/tools/convert-markdown-into-ipynb-and-test.sh
new file mode 100755
index 0000000000000000000000000000000000000000..32ba98a8275d8e8277caf5893f35d1b9726d4714
--- /dev/null
+++ b/tools/convert-markdown-into-ipynb-and-test.sh
@@ -0,0 +1,36 @@
+#!/bin/sh
+command -v go >/dev/null 2>&1
+if [ $? -ne 0 ]; then
+ echo >&2 "Please install go https://golang.org/doc/install#install"
+ exit 1
+fi
+
+GOPATH=/tmp/go go get -u github.com/wangkuiyi/ipynb/markdown-to-ipynb
+
+cur_path=$(dirname $(readlink -f $0))
+cd $cur_path/../
+
+#convert md to ipynb
+for file in */{README,README\.en}.md ; do
+ /tmp/go/bin/markdown-to-ipynb < $file > ${file%.*}".ipynb"
+ if [ $? -ne 0 ]; then
+ echo >&2 "markdown-to-ipynb $file error"
+ exit 1
+ fi
+done
+
+if [[ -z $TEST_EMBEDDED_PYTHON_SCRIPTS ]]; then
+ exit 0
+fi
+
+#exec ipynb's py file
+for file in */{README,README\.en}.ipynb ; do
+ pushd $PWD > /dev/null
+ cd $(dirname $file) > /dev/null
+
+ echo "begin test $file"
+ jupyter nbconvert --to python $(basename $file) --stdout | python
+
+ popd > /dev/null
+ #break
+done
diff --git a/understand_sentiment/README.en.md b/understand_sentiment/README.en.md
index 95664eb4b04f7c5fbadc2cc4f64b6b35ec18413d..105a851b3537cb100d3d47a4c47e1b2c06f1e685 100644
--- a/understand_sentiment/README.en.md
+++ b/understand_sentiment/README.en.md
@@ -1,8 +1,9 @@
# Sentiment Analysis
-The source codes of this section can be located at [book/understand_sentiment](https://github.com/PaddlePaddle/book/tree/develop/understand_sentiment). First-time users may refer to PaddlePaddle for [Installation guide](http://www.paddlepaddle.org/doc_cn/build_and_install/index.html).
+The source codes of this section can be located at [book/understand_sentiment](https://github.com/PaddlePaddle/book/tree/develop/understand_sentiment). First-time users may refer to PaddlePaddle for [Installation guide](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_en.rst).
+
+## Background
-## Background Introduction
In natural language processing, sentiment analysis refers to describing emotion status in texts. The texts may refer to a sentence, a paragraph or a document. Emotion status can be a binary classification problem (positive/negative or happy/sad), or a three-class problem (positive/neutral/negative). Sentiment analysis can be applied widely in various situations, such as online shopping (Amazon, Taobao), travel and movie websites. It can be used to grasp from the reviews how the customers feel about the product. Table 1 is an example of sentiment analysis in movie reviews:
| Movie Review | Category |
@@ -22,10 +23,12 @@ For a piece of text, BOW model ignores its word order, grammar and syntax, and r
In this chapter, we introduce our deep learning model which handles these issues in BOW. Our model embeds texts into a low-dimensional space and takes word order into consideration. It is an end-to-end framework, and has large performance improvement over traditional methods \[[1](#Reference)\].
## Model Overview
+
The model we used in this chapter is the CNN (Convolutional Neural Networks) and RNN (Recurrent Neural Networks) with some specific extension.
### Convolutional Neural Networks for Texts (CNN)
+
Convolutional Neural Networks are always applied in data with grid-like topology, such as 2-d images and 1-d texts. CNN can combine extracted multiple local features to produce higher-level abstract semantics. Experimentally, CNN is very efficient for image and text modeling.
CNN mainly contains convolution and pooling operation, with various extensions. We briefly describe CNN here with an example \[[1](#Refernce)\]. As shown in Figure 1:
@@ -55,7 +58,8 @@ Finally, the CNN features are concatenated together to produce a fixed-length re
For short texts, above CNN model can achieve high accuracy \[[1](#Reference)\]. If we want to extract more abstract representation, we may apply a deeper CNN model \[[2](#Reference),[3](#Reference)\].
-### Recurrent Neural Network(RNN)
+### Recurrent Neural Network (RNN)
+
RNN is an effective model for sequential data. Theoretical, the computational ability of RNN is Turing-complete \[[4](#Reference)\]. NLP is a classical sequential data, and RNN (especially its variant LSTM\[[5](#Reference)\]) achieves State-of-the-Art performance on various tasks in NLP, such as language modeling, syntax parsing, POS-tagging, image captioning, dialog, machine translation and so forth.
@@ -70,8 +74,9 @@ where $W_{xh}$ is the weight matrix from input to latent; $W_{hh}$ is the latent
In NLP, words are first represented as a one-hot vector and then mapped to an embedding. The embedded feature goes through an RNN as input $x_t$ at every time step. Moreover, we can add other layers on top of RNN. e.g., a deep or stacked RNN. Also, the last latent state can be used as a feature for sentence classification.
-### Long-Short Term Memory
-For data of long sequence, training RNN sometimes has gradient vanishing and explosion problem \[[6](#)\]. To solve this problem Hochreiter S, Schmidhuber J. (1997) proposed the LSTM(long short term memory\[[5](#Refernce)\]).
+### Long-Short Term Memory (LSTM)
+
+For data of long sequence, training RNN sometimes has gradient vanishing and explosion problem \[[6](#)\]. To solve this problem Hochreiter S, Schmidhuber J. (1997) proposed the LSTM(long short term memory\[[5](#Reference)\]).
Compared with simple RNN, the structrue of LSTM has included memory cell $c$, input gate $i$, forget gate $f$ and output gate $o$. These gates and memory cells largely improves the ability of handling long sequences. We can formulate LSTM-RNN as a function $F$ as:
@@ -99,6 +104,7 @@ $$ h_t=Recrurent(x_t,h_{t-1})$$
where $Recrurent$ is a simple RNN, GRU or LSTM.
### Stacked Bidirectional LSTM
+
For vanilla LSTM, $h_t$ contains input information from previous time-step $1..t-1$ context. We can also apply an RNN with reverse-direction to take successive context $t+1…n$ into consideration. Combining constructing deep RNN (deeper RNN can contain more abstract and higher level semantic), we can design structures with deep stacked bidirectional LSTM to model sequential data\[[9](#Reference)\].
As shown in Figure 4 (3-layer RNN), odd/even layers are forward/reverse LSTM. Higher layers of LSTM take lower-layers LSTM as input, and the top-layer LSTM produces a fixed length vector by max-pooling (this representation considers contexts from previous and successive words for higher-level abstractions). Finally, we concatenate the output to a softmax layer for classification.
@@ -108,377 +114,247 @@ As shown in Figure 4 (3-layer RNN), odd/even layers are forward/reverse LSTM. Hi
Figure 4. Stacked Bidirectional LSTM for NLP modeling.
-## Data Preparation
-### Data introduction and Download
-We taks the [IMDB sentiment analysis dataset](http://ai.stanford.edu/%7Eamaas/data/sentiment/) as an example. IMDB dataset contains training and testing set, with 25000 movie reviews. With a 1-10 score, negative reviews are those with score<=4, while positives are those with score>=7. You may use following scripts to download the IMDB dataset and [Moses](http://www.statmt.org/moses/) toolbox:
+## Dataset
+We use [IMDB](http://ai.stanford.edu/%7Eamaas/data/sentiment/) dataset for sentiment analysis in this tutorial, which consists of 50,000 movie reviews split evenly into 25k train and 25k test sets. In the labeled train/test sets, a negative review has a score <= 4 out of 10, and a positive review has a score >= 7 out of 10.
-```bash
-./data/get_imdb.sh
-```
-If successful, you should see the directory ```data``` with following files:
+`paddle.datasets` package encapsulates multiple public datasets, including `cifar`, `imdb`, `mnist`, `moivelens`, and `wmt14`, etc. There's no need for us to manually download and preprocess IMDB.
-```
-aclImdb get_imdb.sh imdb mosesdecoder-master
-```
+After issuing a command `python train.py`, training will start immediately. The details will be unpacked by the following sessions to see how it works.
-* aclImdb: original data downloaded from the website;
-* imdb: containing only training and testing data
-* mosesdecoder-master: Moses tool
-### Data Preprocessing
-We use the script `preprocess.py` to preprocess the data. It will call `tokenizer.perl` in the Moses toolbox to split words and punctuations, randomly shuffle training set and construct the dictionary. Notice: we only use labeled training and testing set. Executing following commands will preprocess the data:
+## Model Structure
-```
-data_dir="./data/imdb"
-python preprocess.py -i $data_dir
-```
+### Initialize PaddlePaddle
-If it runs successfully, `./data/pre-imdb` will contain:
+We must import and initialize PaddlePaddle (enable/disable GPU, set the number of trainers, etc).
-```
-dict.txt labels.list test.list test_part_000 train.list train_part_000
+```python
+import sys
+import paddle.v2 as paddle
+
+# PaddlePaddle init
+paddle.init(use_gpu=False, trainer_count=1)
```
-* test\_part\_000 和 train\_part\_000: all labeled training and testing set, and the training set is shuffled.
-* train.list and test.list: training and testing file-list (containing list of file names).
-* dict.txt: dictionary generated from training set.
-* labels.list: class label, 0 stands for negative while 1 for positive.
+As alluded to in section [Model Overview](#model-overview), here we provide the implementations of both Text CNN and Stacked-bidirectional LSTM models.
-### Data Provider for PaddlePaddle
-PaddlePaddle can read Python-style script for configuration. The following `dataprovider.py` provides a detailed example, consisting of two parts:
+### Text Convolution Neural Network (Text CNN)
-* hook: define text information and class Id. Texts are defined as `integer_value_sequence` while class Ids are defined as `integer_value`.
-* process: read line by line for ID and text information split by `’\t\t’`, and yield the data as a generator.
+We create a neural network `convolution_net` as the following snippet code.
-```python
-from paddle.trainer.PyDataProvider2 import *
-
-def hook(settings, dictionary, **kwargs):
-settings.word_dict = dictionary
-settings.input_types = {
-'word': integer_value_sequence(len(settings.word_dict)),
-'label': integer_value(2)
-}
-settings.logger.info('dict len : %d' % (len(settings.word_dict)))
-
-@provider(init_hook=hook)
-def process(settings, file_name):
-with open(file_name, 'r') as fdata:
-for line_count, line in enumerate(fdata):
-label, comment = line.strip().split('\t\t')
-label = int(label)
-words = comment.split()
-word_slot = [
-settings.word_dict[w] for w in words if w in settings.word_dict
-]
-yield {
-'word': word_slot,
-'label': label
-}
-```
+Note: `paddle.networks.sequence_conv_pool` includes both convolution and pooling layer operations.
-## Model Setup
-`trainer_config.py` is an example of a setup file.
-### Data Definition
```python
-from os.path import join as join_path
-from paddle.trainer_config_helpers import *
-# if it is “test” mode
-is_test = get_config_arg('is_test', bool, False)
-# if it is “predict” mode
-is_predict = get_config_arg('is_predict', bool, False)
-
-# Data path
-data_dir = "./data/pre-imdb"
-# File names
-train_list = "train.list"
-test_list = "test.list"
-dict_file = "dict.txt"
-
-# Dictionary size
-dict_dim = len(open(join_path(data_dir, "dict.txt")).readlines())
-# class number
-class_dim = len(open(join_path(data_dir, 'labels.list')).readlines())
-
-if not is_predict:
-train_list = join_path(data_dir, train_list)
-test_list = join_path(data_dir, test_list)
-dict_file = join_path(data_dir, dict_file)
-train_list = train_list if not is_test else None
-# construct the dictionary
-word_dict = dict()
-with open(dict_file, 'r') as f:
-for i, line in enumerate(open(dict_file, 'r')):
-word_dict[line.split('\t')[0]] = i
-# Call the function “define_py_data_sources2” in the file dataprovider.py to extract features
-define_py_data_sources2(
-train_list,
-test_list,
-module="dataprovider",
-obj="process", # function to generate data
-args={'dictionary': word_dict}) # extra parameters, here refers to dictionary
+def convolution_net(input_dim, class_dim=2, emb_dim=128, hid_dim=128):
+ data = paddle.layer.data("word",
+ paddle.data_type.integer_value_sequence(input_dim))
+ emb = paddle.layer.embedding(input=data, size=emb_dim)
+ conv_3 = paddle.networks.sequence_conv_pool(
+ input=emb, context_len=3, hidden_size=hid_dim)
+ conv_4 = paddle.networks.sequence_conv_pool(
+ input=emb, context_len=4, hidden_size=hid_dim)
+ output = paddle.layer.fc(input=[conv_3, conv_4],
+ size=class_dim,
+ act=paddle.activation.Softmax())
+ lbl = paddle.layer.data("label", paddle.data_type.integer_value(2))
+ cost = paddle.layer.classification_cost(input=output, label=lbl)
+ return cost
```
-### Algorithm Setup
+1. Define input data and its dimension
-```python
-settings(
-batch_size=128,
-learning_rate=2e-3,
-learning_method=AdamOptimizer(),
-regularization=L2Regularization(8e-4),
-gradient_clipping_threshold=25)
-```
+ Parameter `input_dim` denotes the dictionary size, and `class_dim` is the number of categories. In `convolution_net`, the input to the network is defined in `paddle.layer.data`.
-* Batch size set as 128;
-* Set global learning rate;
-* Apply ADAM algorithm for optimization;
-* Set up L2 regularization;
-* Set up gradient clipping threshold;
+1. Define Classifier
-### Model Structure
-We use PaddlePaddle to implement two classification algorithms, based on above mentioned model [Text-CNN](#Text-CNN(CNN))和[Stacked-bidirectional LSTM](#Stacked-bidirectional LSTM(Stacked Bidirectional LSTM))。
-#### Implementation of Text CNN
-```python
-def convolution_net(input_dim,
-class_dim=2,
-emb_dim=128,
-hid_dim=128,
-is_predict=False):
-# network input: id denotes word order, dictionary size as input_dim
-data = data_layer("word", input_dim)
-# Embed one-hot id to embedding subspace
-emb = embedding_layer(input=data, size=emb_dim)
-# Convolution and max-pooling operation, convolution kernel size set as 3
-conv_3 = sequence_conv_pool(input=emb, context_len=3, hidden_size=hid_dim)
-# Convolution and max-pooling, convolution kernel size set as 4
-conv_4 = sequence_conv_pool(input=emb, context_len=4, hidden_size=hid_dim)
-# Concatenate conv_3 and conv_4 as input for softmax classification, class number as class_dim
-output = fc_layer(
-input=[conv_3, conv_4], size=class_dim, act=SoftmaxActivation())
-
-if not is_predict:
-lbl = data_layer("label", 1) #network input: class label
-outputs(classification_cost(input=output, label=lbl))
-else:
-outputs(output)
-```
+ The above Text CNN network extracts high-level features and maps them to a vector of the same size as the categories. `paddle.activation.Softmax` function or classifier is then used for calculating the probability of the sentence belonging to each category.
+
+1. Define Loss Function
+
+ In the context of supervised learning, labels of the training set are defined in `paddle.layer.data`, too. During training, cross-entropy is used as loss function in `paddle.layer.classification_cost` and as the output of the network; During testing, the outputs are the probabilities calculated in the classifier.
-In our implementation, we can use just a single layer [`sequence_conv_pool`](https://github.com/PaddlePaddle/Paddle/blob/develop/python/paddle/trainer_config_helpers/networks.py) to do convolution and pooling operation, convolution kernel size set as hidden_size parameters.
+#### Stacked bidirectional LSTM
-#### Implementation of Stacked bidirectional LSTM
+We create a neural network `stacked_lstm_net` as below.
```python
def stacked_lstm_net(input_dim,
-class_dim=2,
-emb_dim=128,
-hid_dim=512,
-stacked_num=3,
-is_predict=False):
-
-# layer number of LSTM “stacked_num” is an odd number to confirm the top-layer LSTM is forward
-assert stacked_num % 2 == 1
-# network attributes setup
-layer_attr = ExtraLayerAttribute(drop_rate=0.5)
-# parameter attributes setup
-fc_para_attr = ParameterAttribute(learning_rate=1e-3)
-lstm_para_attr = ParameterAttribute(initial_std=0., learning_rate=1.)
-para_attr = [fc_para_attr, lstm_para_attr]
-bias_attr = ParameterAttribute(initial_std=0., l2_rate=0.)
-# Activation functions
-relu = ReluActivation()
-linear = LinearActivation()
-
-
-# Network input: id as word order, dictionary size is set as input_dim
-data = data_layer("word", input_dim)
-# Mapping id from word to the embedding subspace
-emb = embedding_layer(input=data, size=emb_dim)
-
-fc1 = fc_layer(input=emb, size=hid_dim, act=linear, bias_attr=bias_attr)
-# LSTM-based RNN
-lstm1 = lstmemory(
-input=fc1, act=relu, bias_attr=bias_attr, layer_attr=layer_attr)
-
-# Construct stacked bidirectional LSTM with fc_layer and lstmemory with layer depth as stacked_num:
-inputs = [fc1, lstm1]
-for i in range(2, stacked_num + 1):
-fc = fc_layer(
-input=inputs,
-size=hid_dim,
-act=linear,
-param_attr=para_attr,
-bias_attr=bias_attr)
-lstm = lstmemory(
-input=fc,
-# Odd number-th layer: forward, Even number-th reverse.
-reverse=(i % 2) == 0,
-act=relu,
-bias_attr=bias_attr,
-layer_attr=layer_attr)
-inputs = [fc, lstm]
-
-# Apply max-pooling along the temporal dimension on the last fc_layer to produce a fixed length vector
-fc_last = pooling_layer(input=inputs[0], pooling_type=MaxPooling())
-# Apply max-pooling along tempoeral dim of lstmemory to obtain fixed length feature vector
-lstm_last = pooling_layer(input=inputs[1], pooling_type=MaxPooling())
-# concatenate fc_last and lstm_last as input for a softmax classification layer, with class number equals class_dim
-output = fc_layer(
-input=[fc_last, lstm_last],
-size=class_dim,
-act=SoftmaxActivation(),
-bias_attr=bias_attr,
-param_attr=para_attr)
-
-if is_predict:
-outputs(output)
-else:
-outputs(classification_cost(input=output, label=data_layer('label', 1)))
+ class_dim=2,
+ emb_dim=128,
+ hid_dim=512,
+ stacked_num=3):
+ """
+ A Wrapper for sentiment classification task.
+ This network uses bi-directional recurrent network,
+ consisting three LSTM layers. This configure is referred to
+ the paper as following url, but use fewer layrs.
+ http://www.aclweb.org/anthology/P15-1109
+ input_dim: here is word dictionary dimension.
+ class_dim: number of categories.
+ emb_dim: dimension of word embedding.
+ hid_dim: dimension of hidden layer.
+ stacked_num: number of stacked lstm-hidden layer.
+ """
+ assert stacked_num % 2 == 1
+
+ layer_attr = paddle.attr.Extra(drop_rate=0.5)
+ fc_para_attr = paddle.attr.Param(learning_rate=1e-3)
+ lstm_para_attr = paddle.attr.Param(initial_std=0., learning_rate=1.)
+ para_attr = [fc_para_attr, lstm_para_attr]
+ bias_attr = paddle.attr.Param(initial_std=0., l2_rate=0.)
+ relu = paddle.activation.Relu()
+ linear = paddle.activation.Linear()
+
+ data = paddle.layer.data("word",
+ paddle.data_type.integer_value_sequence(input_dim))
+ emb = paddle.layer.embedding(input=data, size=emb_dim)
+
+ fc1 = paddle.layer.fc(input=emb,
+ size=hid_dim,
+ act=linear,
+ bias_attr=bias_attr)
+ lstm1 = paddle.layer.lstmemory(
+ input=fc1, act=relu, bias_attr=bias_attr, layer_attr=layer_attr)
+
+ inputs = [fc1, lstm1]
+ for i in range(2, stacked_num + 1):
+ fc = paddle.layer.fc(input=inputs,
+ size=hid_dim,
+ act=linear,
+ param_attr=para_attr,
+ bias_attr=bias_attr)
+ lstm = paddle.layer.lstmemory(
+ input=fc,
+ reverse=(i % 2) == 0,
+ act=relu,
+ bias_attr=bias_attr,
+ layer_attr=layer_attr)
+ inputs = [fc, lstm]
+
+ fc_last = paddle.layer.pooling(
+ input=inputs[0], pooling_type=paddle.pooling.Max())
+ lstm_last = paddle.layer.pooling(
+ input=inputs[1], pooling_type=paddle.pooling.Max())
+ output = paddle.layer.fc(input=[fc_last, lstm_last],
+ size=class_dim,
+ act=paddle.activation.Softmax(),
+ bias_attr=bias_attr,
+ param_attr=para_attr)
+
+ lbl = paddle.layer.data("label", paddle.data_type.integer_value(2))
+ cost = paddle.layer.classification_cost(input=output, label=lbl)
+ return cost
```
-Our model defined in `trainer_config.py` uses the `stacked_lstm_net` structure as default. If you want to use `convolution_net`, you can comment related lines.
+1. Define input data and its dimension
+
+ Parameter `input_dim` denotes the dictionary size, and `class_dim` is the number of categories. In `stacked_lstm_net`, the input to the network is defined in `paddle.layer.data`.
+
+1. Define Classifier
+
+ The above stacked bidirectional LSTM network extracts high-level features and maps them to a vector of the same size as the categories. `paddle.activation.Softmax` function or classifier is then used for calculating the probability of the sentence belonging to each category.
+
+1. Define Loss Function
+
+ In the context of supervised learning, labels of the training set are defined in `paddle.layer.data`, too. During training, cross-entropy is used as loss function in `paddle.layer.classification_cost` and as the output of the network; During testing, the outputs are the probabilities calculated in the classifier.
+
+
+To reiterate, we can either invoke `convolution_net` or `stacked_lstm_net`.
```python
-stacked_lstm_net(
-dict_dim, class_dim=class_dim, stacked_num=3, is_predict=is_predict)
-# convolution_net(dict_dim, class_dim=class_dim, is_predict=is_predict)
+word_dict = paddle.dataset.imdb.word_dict()
+dict_dim = len(word_dict)
+class_dim = 2
+
+# option 1
+cost = convolution_net(dict_dim, class_dim=class_dim)
+# option 2
+# cost = stacked_lstm_net(dict_dim, class_dim=class_dim, stacked_num=3)
```
## Model Training
-Use `train.sh` script to run local training:
-```
-./train.sh
-```
+### Define Parameters
-train.sh is as following:
-
-```bash
-paddle train --config=trainer_config.py \
---save_dir=./model_output \
---job=train \
---use_gpu=false \
---trainer_count=4 \
---num_passes=10 \
---log_period=20 \
---dot_period=20 \
---show_parameter_stats_period=100 \
---test_all_data_in_one_period=1 \
-2>&1 | tee 'train.log'
+First, we create the model parameters according to the previous model configuration `cost`.
+
+```python
+# create parameters
+parameters = paddle.parameters.create(cost)
```
-* \--config=trainer_config.py: set up model configuration.
-* \--save\_dir=./model_output: set up output folder to save model parameters.
-* \--job=train: set job mode as training.
-* \--use\_gpu=false: Use CPU for training. If you have installed GPU-version PaddlePaddle and want to try GPU training, you may set this term as true.
-* \--trainer\_count=4: setup thread number (or GPU numer).
-* \--num\_passes=15: Setup pass. In PaddlePaddle, a pass means a training epoch over all samples.
-* \--log\_period=20: print log every 20 batches.
-* \--show\_parameter\_stats\_period=100: Print statistics to screen every 100 batch.
-* \--test\_all_data\_in\_one\_period=1: Predict all testing data every time.
+### Create Trainer
-If it is running sussefully, the output log will be saved at `train.log`, model parameters will be saved at the directory `model_output/`. Output log will be as following:
+Before jumping into creating a training module, algorithm setting is also necessary.
+Here we specified `Adam` optimization algorithm via `paddle.optimizer`.
+```python
+# create optimizer
+adam_optimizer = paddle.optimizer.Adam(
+ learning_rate=2e-3,
+ regularization=paddle.optimizer.L2Regularization(rate=8e-4),
+ model_average=paddle.optimizer.ModelAverage(average_window=0.5))
+
+# create trainer
+trainer = paddle.trainer.SGD(cost=cost,
+ parameters=parameters,
+ update_equation=adam_optimizer)
```
-Batch=20 samples=2560 AvgCost=0.681644 CurrentCost=0.681644 Eval: classification_error_evaluator=0.36875 CurrentEval: classification_error_evaluator=0.36875
-...
-Pass=0 Batch=196 samples=25000 AvgCost=0.418964 Eval: classification_error_evaluator=0.1922
-Test samples=24999 cost=0.39297 Eval: classification_error_evaluator=0.149406
-```
-
-* Batch=xx: Already |xx| Batch trained.
-* samples=xx: xx samples have been processed during training.
-* AvgCost=xx: Average loss from 0-th batch to the current batch.
-* CurrentCost=xx: loss of the latest |log_period|-th batch;
-* Eval: classification\_error\_evaluator=xx: Average accuracy from 0-th batch to current batch;
-* CurrentEval: classification\_error\_evaluator: latest |log_period| batches of classification error;
-* Pass=0: Running over all data in the training set is called as a Pass. Pass “0” denotes the first round.
+### Training
-## Application models
-### Testing
+`paddle.dataset.imdb.train()` will yield records during each pass, after shuffling, a batch input is generated for training.
-Testing refers to use trained model to evaluate labeled dataset.
+```python
+train_reader = paddle.batch(
+ paddle.reader.shuffle(
+ lambda: paddle.dataset.imdb.train(word_dict), buf_size=1000),
+ batch_size=100)
+test_reader = paddle.batch(
+ lambda: paddle.dataset.imdb.test(word_dict), batch_size=100)
```
-./test.sh
-```
-Scripts for testing `test.sh` is as following, where the function `get_best_pass` ranks classification accuracy to obtain the best model:
-
-```bash
-function get_best_pass() {
-cat $1 | grep -Pzo 'Test .*\n.*pass-.*' | \
-sed -r 'N;s/Test.* error=([0-9]+\.[0-9]+).*\n.*pass-([0-9]+)/\1 \2/g' | \
-sort | head -n 1
-}
-
-log=train.log
-LOG=`get_best_pass $log`
-LOG=(${LOG})
-evaluate_pass="model_output/pass-${LOG[1]}"
-
-echo 'evaluating from pass '$evaluate_pass
-
-model_list=./model.list
-touch $model_list | echo $evaluate_pass > $model_list
-net_conf=trainer_config.py
-paddle train --config=$net_conf \
---model_list=$model_list \
---job=test \
---use_gpu=false \
---trainer_count=4 \
---config_args=is_test=1 \
-2>&1 | tee 'test.log'
+`feeding` is devoted to specifying the correspondence between each yield record and `paddle.layer.data`. For instance, the first column of data generated by `paddle.dataset.imdb.train()` corresponds to `word` feature.
+
+```python
+feeding = {'word': 0, 'label': 1}
```
-Different from training, testing requires denoting `--job = test` and model path `--model_list = $model_list`. If successful, log will be saved at `test.log`. In our test, the best model is `model_output/pass-00002`, with classification error rate as 0.115645:
+Callback function `event_handler` will be invoked to track training progress when a pre-defined event happens.
-```
-Pass=0 samples=24999 AvgCost=0.280471 Eval: classification_error_evaluator=0.115645
+```python
+def event_handler(event):
+ if isinstance(event, paddle.event.EndIteration):
+ if event.batch_id % 100 == 0:
+ print "\nPass %d, Batch %d, Cost %f, %s" % (
+ event.pass_id, event.batch_id, event.cost, event.metrics)
+ else:
+ sys.stdout.write('.')
+ sys.stdout.flush()
+ if isinstance(event, paddle.event.EndPass):
+ result = trainer.test(reader=test_reader, reader_dict=reader_dict)
+ print "\nTest with Pass %d, %s" % (event.pass_id, result.metrics)
```
-### Prediction
-`predict.py` script provides an API. Predicting IMDB data without labels as following:
+Finally, we can invoke `trainer.train` to start training:
+```python
+trainer.train(
+ reader=train_reader,
+ event_handler=event_handler,
+ feeding=feedig,
+ num_passes=10)
```
-./predict.sh
-```
-predict.sh is as following(default model path `model_output/pass-00002` may exist or modified to others):
-
-```bash
-model=model_output/pass-00002/
-config=trainer_config.py
-label=data/pre-imdb/labels.list
-cat ./data/aclImdb/test/pos/10007_10.txt | python predict.py \
---tconf=$config \
---model=$model \
---label=$label \
---dict=./data/pre-imdb/dict.txt \
---batch_size=1
-```
-
-* `cat ./data/aclImdb/test/pos/10007_10.txt` : Input prediction samples.
-* `predict.py` : Prediction script.
-* `--tconf=$config` : Network set up.
-* `--model=$model` : Model path set up.
-* `--label=$label` : set up the label dictionary, mapping integer IDs to string labels.
-* `--dict=data/pre-imdb/dict.txt` : set up the dictionary file.
-* `--batch_size=1` : batch size during prediction.
-Prediction result of our example:
+## Conclusion
-```
-Loading parameters from model_output/pass-00002/
-predicting label is pos
-```
+In this chapter, we use sentiment analysis as an example to introduce applying deep learning models on end-to-end short text classification, as well as how to use PaddlePaddle to implement the model. Meanwhile, we briefly introduce two models for text processing: CNN and RNN. In following chapters, we will see how these models can be applied in other tasks.
-`10007_10.txt` in folder`./data/aclImdb/test/pos`, the predicted label is also pos,so the prediction is correct.
-## Summary
-In this chapter, we use sentiment analysis as an example to introduce applying deep learning models on end-to-end short text classification, as well as how to use PaddlePaddle to implement the model. Meanwhile, we briefly introduce two models for text processing: CNN and RNN. In following chapters we will see how these models can be applied in other tasks.
## Reference
+
1. Kim Y. [Convolutional neural networks for sentence classification](http://arxiv.org/pdf/1408.5882)[J]. arXiv preprint arXiv:1408.5882, 2014.
2. Kalchbrenner N, Grefenstette E, Blunsom P. [A convolutional neural network for modelling sentences](http://arxiv.org/pdf/1404.2188.pdf?utm_medium=App.net&utm_source=PourOver)[J]. arXiv preprint arXiv:1404.2188, 2014.
3. Yann N. Dauphin, et al. [Language Modeling with Gated Convolutional Networks](https://arxiv.org/pdf/1612.08083v1.pdf)[J] arXiv preprint arXiv:1612.08083, 2016.
@@ -490,4 +366,4 @@ In this chapter, we use sentiment analysis as an example to introduce applying d
9. Zhou J, Xu W. [End-to-end learning of semantic role labeling using recurrent neural networks](http://www.aclweb.org/anthology/P/P15/P15-1109.pdf)[C]//Proceedings of the Annual Meeting of the Association for Computational Linguistics. 2015.
-
本教程 由
PaddlePaddle 创作,采用
知识共享 署名-非商业性使用-相同方式共享 4.0 国际 许可协议进行许可。
+This tutorial is contributed by
PaddlePaddle, and licensed under a
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
diff --git a/understand_sentiment/README.md b/understand_sentiment/README.md
index 3e437f2d5f68e3cb163b0864f92d251ae6b603f3..3da65a419c0bc4146d2c2b55c4d446ef93706a8d 100644
--- a/understand_sentiment/README.md
+++ b/understand_sentiment/README.md
@@ -1,6 +1,6 @@
# 情感分析
-本教程源代码目录在[book/understand_sentiment](https://github.com/PaddlePaddle/book/tree/develop/understand_sentiment), 初次使用请参考PaddlePaddle[安装教程](http://www.paddlepaddle.org/doc_cn/build_and_install/index.html)。
+本教程源代码目录在[book/understand_sentiment](https://github.com/PaddlePaddle/book/tree/develop/understand_sentiment), 初次使用请参考PaddlePaddle[安装教程](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_cn.rst)。
## 背景介绍
在自然语言处理中,情感分析一般是指判断一段文本所表达的情绪状态。其中,一段文本可以是一个句子,一个段落或一个文档。情绪状态可以是两类,如(正面,负面),(高兴,悲伤);也可以是三类,如(积极,消极,中性)等等。情感分析的应用场景十分广泛,如把用户在购物网站(亚马逊、天猫、淘宝等)、旅游网站、电影评论网站上发表的评论分成正面评论和负面评论;或为了分析用户对于某一产品的整体使用感受,抓取产品的用户评论并进行情感分析等等。表格1展示了对电影评论进行情感分析的例子:
@@ -108,14 +108,14 @@ aclImdb
```
Paddle在`dataset/imdb.py`中提实现了imdb数据集的自动下载和读取,并提供了读取字典、训练数据、测试数据等API。
-```
+```python
import sys
import paddle.v2 as paddle
```
## 配置模型
在该示例中,我们实现了两种文本分类算法,分别基于上文所述的[文本卷积神经网络](#文本卷积神经网络(CNN))和[栈式双向LSTM](#栈式双向LSTM(Stacked Bidirectional LSTM))。
### 文本卷积神经网络
-```
+```python
def convolution_net(input_dim,
class_dim=2,
emb_dim=128,
@@ -136,7 +136,7 @@ def convolution_net(input_dim,
```
网络的输入`input_dim`表示的是词典的大小,`class_dim`表示类别数。这里,我们使用[`sequence_conv_pool`](https://github.com/PaddlePaddle/Paddle/blob/develop/python/paddle/trainer_config_helpers/networks.py) API实现了卷积和池化操作。
### 栈式双向LSTM
-```
+```python
def stacked_lstm_net(input_dim,
class_dim=2,
emb_dim=128,
@@ -205,7 +205,7 @@ def stacked_lstm_net(input_dim,
```
网络的输入`stacked_num`表示的是LSTM的层数,需要是奇数,确保最高层LSTM正向。Paddle里面是通过一个fc和一个lstmemory来实现基于LSTM的循环神经网络。
## 训练模型
-```
+```python
if __name__ == '__main__':
# init
paddle.init(use_gpu=False)
@@ -213,14 +213,14 @@ if __name__ == '__main__':
启动paddle程序,use_gpu=False表示用CPU训练,如果系统支持GPU也可以修改成True使用GPU训练。
### 训练数据
使用Paddle提供的数据集`dataset.imdb`中的API来读取训练数据。
-```
+```python
print 'load dictionary...'
word_dict = paddle.dataset.imdb.word_dict()
dict_dim = len(word_dict)
class_dim = 2
```
加载数据字典,这里通过`word_dict()`API可以直接构造字典。`class_dim`是指样本类别数,该示例中样本只有正负两类。
-```
+```python
train_reader = paddle.batch(
paddle.reader.shuffle(
lambda: paddle.dataset.imdb.train(word_dict), buf_size=1000),
@@ -230,12 +230,12 @@ if __name__ == '__main__':
batch_size=100)
```
这里,`dataset.imdb.train()`和`dataset.imdb.test()`分别是`dataset.imdb`中的训练数据和测试数据API。`train_reader`在训练时使用,意义是将读取的训练数据进行shuffle后,组成一个batch数据。同理,`test_reader`是在测试的时候使用,将读取的测试数据组成一个batch。
-```
+```python
feeding={'word': 0, 'label': 1}
```
`feeding`用来指定`train_reader`和`test_reader`返回的数据与模型配置中data_layer的对应关系。这里表示reader返回的第0列数据对应`word`层,第1列数据对应`label`层。
### 构造模型
-```
+```python
# Please choose the way to build the network
# by uncommenting the corresponding line.
cost = convolution_net(dict_dim, class_dim=class_dim)
@@ -243,13 +243,13 @@ if __name__ == '__main__':
```
该示例中默认使用`convolution_net`网络,如果使用`stacked_lstm_net`网络,注释相应的行即可。其中cost是网络的优化目标,同时cost包含了整个网络的拓扑信息。
### 网络参数
-```
+```python
# create parameters
parameters = paddle.parameters.create(cost)
```
根据网络的拓扑构造网络参数。这里parameters是整个网络的参数集。
### 优化算法
-```
+```python
# create optimizer
adam_optimizer = paddle.optimizer.Adam(
learning_rate=2e-3,
@@ -259,7 +259,7 @@ if __name__ == '__main__':
Paddle中提供了一系列优化算法的API,这里使用Adam优化算法。
### 训练
可以通过`paddle.trainer.SGD`构造一个sgd trainer,并调用`trainer.train`来训练模型。
-```
+```python
# End batch and end pass event handler
def event_handler(event):
if isinstance(event, paddle.event.EndIteration):
@@ -274,7 +274,7 @@ Paddle中提供了一系列优化算法的API,这里使用Adam优化算法。
print "\nTest with Pass %d, %s" % (event.pass_id, result.metrics)
```
可以通过给train函数传递一个`event_handler`来获取每个batch和每个pass结束的状态。比如构造如下一个`event_handler`可以在每100个batch结束后输出cost和error;在每个pass结束后调用`trainer.test`计算一遍测试集并获得当前模型在测试集上的error。
-```
+```python
# create trainer
trainer = paddle.trainer.SGD(cost=cost,
parameters=parameters,
@@ -287,7 +287,7 @@ Paddle中提供了一系列优化算法的API,这里使用Adam优化算法。
num_passes=2)
```
程序运行之后的输出如下。
-```
+```text
Pass 0, Batch 0, Cost 0.693721, {'classification_error_evaluator': 0.5546875}
...................................................................................................
Pass 0, Batch 100, Cost 0.294321, {'classification_error_evaluator': 0.1015625}
diff --git a/understand_sentiment/index.en.html b/understand_sentiment/index.en.html
index 6bbdbd9ea55bf852c81ea254c09f8b6de1a779ae..1a99aa90a600167484c081da68813e02775dc156 100644
--- a/understand_sentiment/index.en.html
+++ b/understand_sentiment/index.en.html
@@ -42,9 +42,10 @@
# Sentiment Analysis
-The source codes of this section can be located at [book/understand_sentiment](https://github.com/PaddlePaddle/book/tree/develop/understand_sentiment). First-time users may refer to PaddlePaddle for [Installation guide](http://www.paddlepaddle.org/doc_cn/build_and_install/index.html).
+The source codes of this section can be located at [book/understand_sentiment](https://github.com/PaddlePaddle/book/tree/develop/understand_sentiment). First-time users may refer to PaddlePaddle for [Installation guide](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_en.rst).
+
+## Background
-## Background Introduction
In natural language processing, sentiment analysis refers to describing emotion status in texts. The texts may refer to a sentence, a paragraph or a document. Emotion status can be a binary classification problem (positive/negative or happy/sad), or a three-class problem (positive/neutral/negative). Sentiment analysis can be applied widely in various situations, such as online shopping (Amazon, Taobao), travel and movie websites. It can be used to grasp from the reviews how the customers feel about the product. Table 1 is an example of sentiment analysis in movie reviews:
| Movie Review | Category |
@@ -64,10 +65,12 @@ For a piece of text, BOW model ignores its word order, grammar and syntax, and r
In this chapter, we introduce our deep learning model which handles these issues in BOW. Our model embeds texts into a low-dimensional space and takes word order into consideration. It is an end-to-end framework, and has large performance improvement over traditional methods \[[1](#Reference)\].
## Model Overview
+
The model we used in this chapter is the CNN (Convolutional Neural Networks) and RNN (Recurrent Neural Networks) with some specific extension.
### Convolutional Neural Networks for Texts (CNN)
+
Convolutional Neural Networks are always applied in data with grid-like topology, such as 2-d images and 1-d texts. CNN can combine extracted multiple local features to produce higher-level abstract semantics. Experimentally, CNN is very efficient for image and text modeling.
CNN mainly contains convolution and pooling operation, with various extensions. We briefly describe CNN here with an example \[[1](#Refernce)\]. As shown in Figure 1:
@@ -97,7 +100,8 @@ Finally, the CNN features are concatenated together to produce a fixed-length re
For short texts, above CNN model can achieve high accuracy \[[1](#Reference)\]. If we want to extract more abstract representation, we may apply a deeper CNN model \[[2](#Reference),[3](#Reference)\].
-### Recurrent Neural Network(RNN)
+### Recurrent Neural Network (RNN)
+
RNN is an effective model for sequential data. Theoretical, the computational ability of RNN is Turing-complete \[[4](#Reference)\]. NLP is a classical sequential data, and RNN (especially its variant LSTM\[[5](#Reference)\]) achieves State-of-the-Art performance on various tasks in NLP, such as language modeling, syntax parsing, POS-tagging, image captioning, dialog, machine translation and so forth.
@@ -112,8 +116,9 @@ where $W_{xh}$ is the weight matrix from input to latent; $W_{hh}$ is the latent
In NLP, words are first represented as a one-hot vector and then mapped to an embedding. The embedded feature goes through an RNN as input $x_t$ at every time step. Moreover, we can add other layers on top of RNN. e.g., a deep or stacked RNN. Also, the last latent state can be used as a feature for sentence classification.
-### Long-Short Term Memory
-For data of long sequence, training RNN sometimes has gradient vanishing and explosion problem \[[6](#)\]. To solve this problem Hochreiter S, Schmidhuber J. (1997) proposed the LSTM(long short term memory\[[5](#Refernce)\]).
+### Long-Short Term Memory (LSTM)
+
+For data of long sequence, training RNN sometimes has gradient vanishing and explosion problem \[[6](#)\]. To solve this problem Hochreiter S, Schmidhuber J. (1997) proposed the LSTM(long short term memory\[[5](#Reference)\]).
Compared with simple RNN, the structrue of LSTM has included memory cell $c$, input gate $i$, forget gate $f$ and output gate $o$. These gates and memory cells largely improves the ability of handling long sequences. We can formulate LSTM-RNN as a function $F$ as:
@@ -141,6 +146,7 @@ $$ h_t=Recrurent(x_t,h_{t-1})$$
where $Recrurent$ is a simple RNN, GRU or LSTM.
### Stacked Bidirectional LSTM
+
For vanilla LSTM, $h_t$ contains input information from previous time-step $1..t-1$ context. We can also apply an RNN with reverse-direction to take successive context $t+1…n$ into consideration. Combining constructing deep RNN (deeper RNN can contain more abstract and higher level semantic), we can design structures with deep stacked bidirectional LSTM to model sequential data\[[9](#Reference)\].
As shown in Figure 4 (3-layer RNN), odd/even layers are forward/reverse LSTM. Higher layers of LSTM take lower-layers LSTM as input, and the top-layer LSTM produces a fixed length vector by max-pooling (this representation considers contexts from previous and successive words for higher-level abstractions). Finally, we concatenate the output to a softmax layer for classification.
@@ -150,377 +156,247 @@ As shown in Figure 4 (3-layer RNN), odd/even layers are forward/reverse LSTM. Hi
Figure 4. Stacked Bidirectional LSTM for NLP modeling.
-## Data Preparation
-### Data introduction and Download
-We taks the [IMDB sentiment analysis dataset](http://ai.stanford.edu/%7Eamaas/data/sentiment/) as an example. IMDB dataset contains training and testing set, with 25000 movie reviews. With a 1-10 score, negative reviews are those with score<=4, while positives are those with score>=7. You may use following scripts to download the IMDB dataset and [Moses](http://www.statmt.org/moses/) toolbox:
+## Dataset
+We use [IMDB](http://ai.stanford.edu/%7Eamaas/data/sentiment/) dataset for sentiment analysis in this tutorial, which consists of 50,000 movie reviews split evenly into 25k train and 25k test sets. In the labeled train/test sets, a negative review has a score <= 4 out of 10, and a positive review has a score >= 7 out of 10.
-```bash
-./data/get_imdb.sh
-```
-If successful, you should see the directory ```data``` with following files:
+`paddle.datasets` package encapsulates multiple public datasets, including `cifar`, `imdb`, `mnist`, `moivelens`, and `wmt14`, etc. There's no need for us to manually download and preprocess IMDB.
-```
-aclImdb get_imdb.sh imdb mosesdecoder-master
-```
+After issuing a command `python train.py`, training will start immediately. The details will be unpacked by the following sessions to see how it works.
-* aclImdb: original data downloaded from the website;
-* imdb: containing only training and testing data
-* mosesdecoder-master: Moses tool
-### Data Preprocessing
-We use the script `preprocess.py` to preprocess the data. It will call `tokenizer.perl` in the Moses toolbox to split words and punctuations, randomly shuffle training set and construct the dictionary. Notice: we only use labeled training and testing set. Executing following commands will preprocess the data:
+## Model Structure
-```
-data_dir="./data/imdb"
-python preprocess.py -i $data_dir
-```
+### Initialize PaddlePaddle
-If it runs successfully, `./data/pre-imdb` will contain:
+We must import and initialize PaddlePaddle (enable/disable GPU, set the number of trainers, etc).
-```
-dict.txt labels.list test.list test_part_000 train.list train_part_000
-```
+```python
+import sys
+import paddle.v2 as paddle
-* test\_part\_000 和 train\_part\_000: all labeled training and testing set, and the training set is shuffled.
-* train.list and test.list: training and testing file-list (containing list of file names).
-* dict.txt: dictionary generated from training set.
-* labels.list: class label, 0 stands for negative while 1 for positive.
+# PaddlePaddle init
+paddle.init(use_gpu=False, trainer_count=1)
+```
-### Data Provider for PaddlePaddle
-PaddlePaddle can read Python-style script for configuration. The following `dataprovider.py` provides a detailed example, consisting of two parts:
+As alluded to in section [Model Overview](#model-overview), here we provide the implementations of both Text CNN and Stacked-bidirectional LSTM models.
-* hook: define text information and class Id. Texts are defined as `integer_value_sequence` while class Ids are defined as `integer_value`.
-* process: read line by line for ID and text information split by `’\t\t’`, and yield the data as a generator.
+### Text Convolution Neural Network (Text CNN)
-```python
-from paddle.trainer.PyDataProvider2 import *
+We create a neural network `convolution_net` as the following snippet code.
-def hook(settings, dictionary, **kwargs):
-settings.word_dict = dictionary
-settings.input_types = {
-'word': integer_value_sequence(len(settings.word_dict)),
-'label': integer_value(2)
-}
-settings.logger.info('dict len : %d' % (len(settings.word_dict)))
-
-@provider(init_hook=hook)
-def process(settings, file_name):
-with open(file_name, 'r') as fdata:
-for line_count, line in enumerate(fdata):
-label, comment = line.strip().split('\t\t')
-label = int(label)
-words = comment.split()
-word_slot = [
-settings.word_dict[w] for w in words if w in settings.word_dict
-]
-yield {
-'word': word_slot,
-'label': label
-}
-```
+Note: `paddle.networks.sequence_conv_pool` includes both convolution and pooling layer operations.
-## Model Setup
-`trainer_config.py` is an example of a setup file.
-### Data Definition
```python
-from os.path import join as join_path
-from paddle.trainer_config_helpers import *
-# if it is “test” mode
-is_test = get_config_arg('is_test', bool, False)
-# if it is “predict” mode
-is_predict = get_config_arg('is_predict', bool, False)
-
-# Data path
-data_dir = "./data/pre-imdb"
-# File names
-train_list = "train.list"
-test_list = "test.list"
-dict_file = "dict.txt"
-
-# Dictionary size
-dict_dim = len(open(join_path(data_dir, "dict.txt")).readlines())
-# class number
-class_dim = len(open(join_path(data_dir, 'labels.list')).readlines())
-
-if not is_predict:
-train_list = join_path(data_dir, train_list)
-test_list = join_path(data_dir, test_list)
-dict_file = join_path(data_dir, dict_file)
-train_list = train_list if not is_test else None
-# construct the dictionary
-word_dict = dict()
-with open(dict_file, 'r') as f:
-for i, line in enumerate(open(dict_file, 'r')):
-word_dict[line.split('\t')[0]] = i
-# Call the function “define_py_data_sources2” in the file dataprovider.py to extract features
-define_py_data_sources2(
-train_list,
-test_list,
-module="dataprovider",
-obj="process", # function to generate data
-args={'dictionary': word_dict}) # extra parameters, here refers to dictionary
+def convolution_net(input_dim, class_dim=2, emb_dim=128, hid_dim=128):
+ data = paddle.layer.data("word",
+ paddle.data_type.integer_value_sequence(input_dim))
+ emb = paddle.layer.embedding(input=data, size=emb_dim)
+ conv_3 = paddle.networks.sequence_conv_pool(
+ input=emb, context_len=3, hidden_size=hid_dim)
+ conv_4 = paddle.networks.sequence_conv_pool(
+ input=emb, context_len=4, hidden_size=hid_dim)
+ output = paddle.layer.fc(input=[conv_3, conv_4],
+ size=class_dim,
+ act=paddle.activation.Softmax())
+ lbl = paddle.layer.data("label", paddle.data_type.integer_value(2))
+ cost = paddle.layer.classification_cost(input=output, label=lbl)
+ return cost
```
-### Algorithm Setup
+1. Define input data and its dimension
-```python
-settings(
-batch_size=128,
-learning_rate=2e-3,
-learning_method=AdamOptimizer(),
-regularization=L2Regularization(8e-4),
-gradient_clipping_threshold=25)
-```
+ Parameter `input_dim` denotes the dictionary size, and `class_dim` is the number of categories. In `convolution_net`, the input to the network is defined in `paddle.layer.data`.
-* Batch size set as 128;
-* Set global learning rate;
-* Apply ADAM algorithm for optimization;
-* Set up L2 regularization;
-* Set up gradient clipping threshold;
+1. Define Classifier
-### Model Structure
-We use PaddlePaddle to implement two classification algorithms, based on above mentioned model [Text-CNN](#Text-CNN(CNN))和[Stacked-bidirectional LSTM](#Stacked-bidirectional LSTM(Stacked Bidirectional LSTM))。
-#### Implementation of Text CNN
-```python
-def convolution_net(input_dim,
-class_dim=2,
-emb_dim=128,
-hid_dim=128,
-is_predict=False):
-# network input: id denotes word order, dictionary size as input_dim
-data = data_layer("word", input_dim)
-# Embed one-hot id to embedding subspace
-emb = embedding_layer(input=data, size=emb_dim)
-# Convolution and max-pooling operation, convolution kernel size set as 3
-conv_3 = sequence_conv_pool(input=emb, context_len=3, hidden_size=hid_dim)
-# Convolution and max-pooling, convolution kernel size set as 4
-conv_4 = sequence_conv_pool(input=emb, context_len=4, hidden_size=hid_dim)
-# Concatenate conv_3 and conv_4 as input for softmax classification, class number as class_dim
-output = fc_layer(
-input=[conv_3, conv_4], size=class_dim, act=SoftmaxActivation())
-
-if not is_predict:
-lbl = data_layer("label", 1) #network input: class label
-outputs(classification_cost(input=output, label=lbl))
-else:
-outputs(output)
-```
+ The above Text CNN network extracts high-level features and maps them to a vector of the same size as the categories. `paddle.activation.Softmax` function or classifier is then used for calculating the probability of the sentence belonging to each category.
+
+1. Define Loss Function
-In our implementation, we can use just a single layer [`sequence_conv_pool`](https://github.com/PaddlePaddle/Paddle/blob/develop/python/paddle/trainer_config_helpers/networks.py) to do convolution and pooling operation, convolution kernel size set as hidden_size parameters.
+ In the context of supervised learning, labels of the training set are defined in `paddle.layer.data`, too. During training, cross-entropy is used as loss function in `paddle.layer.classification_cost` and as the output of the network; During testing, the outputs are the probabilities calculated in the classifier.
-#### Implementation of Stacked bidirectional LSTM
+#### Stacked bidirectional LSTM
+
+We create a neural network `stacked_lstm_net` as below.
```python
def stacked_lstm_net(input_dim,
-class_dim=2,
-emb_dim=128,
-hid_dim=512,
-stacked_num=3,
-is_predict=False):
-
-# layer number of LSTM “stacked_num” is an odd number to confirm the top-layer LSTM is forward
-assert stacked_num % 2 == 1
-# network attributes setup
-layer_attr = ExtraLayerAttribute(drop_rate=0.5)
-# parameter attributes setup
-fc_para_attr = ParameterAttribute(learning_rate=1e-3)
-lstm_para_attr = ParameterAttribute(initial_std=0., learning_rate=1.)
-para_attr = [fc_para_attr, lstm_para_attr]
-bias_attr = ParameterAttribute(initial_std=0., l2_rate=0.)
-# Activation functions
-relu = ReluActivation()
-linear = LinearActivation()
-
-
-# Network input: id as word order, dictionary size is set as input_dim
-data = data_layer("word", input_dim)
-# Mapping id from word to the embedding subspace
-emb = embedding_layer(input=data, size=emb_dim)
-
-fc1 = fc_layer(input=emb, size=hid_dim, act=linear, bias_attr=bias_attr)
-# LSTM-based RNN
-lstm1 = lstmemory(
-input=fc1, act=relu, bias_attr=bias_attr, layer_attr=layer_attr)
-
-# Construct stacked bidirectional LSTM with fc_layer and lstmemory with layer depth as stacked_num:
-inputs = [fc1, lstm1]
-for i in range(2, stacked_num + 1):
-fc = fc_layer(
-input=inputs,
-size=hid_dim,
-act=linear,
-param_attr=para_attr,
-bias_attr=bias_attr)
-lstm = lstmemory(
-input=fc,
-# Odd number-th layer: forward, Even number-th reverse.
-reverse=(i % 2) == 0,
-act=relu,
-bias_attr=bias_attr,
-layer_attr=layer_attr)
-inputs = [fc, lstm]
-
-# Apply max-pooling along the temporal dimension on the last fc_layer to produce a fixed length vector
-fc_last = pooling_layer(input=inputs[0], pooling_type=MaxPooling())
-# Apply max-pooling along tempoeral dim of lstmemory to obtain fixed length feature vector
-lstm_last = pooling_layer(input=inputs[1], pooling_type=MaxPooling())
-# concatenate fc_last and lstm_last as input for a softmax classification layer, with class number equals class_dim
-output = fc_layer(
-input=[fc_last, lstm_last],
-size=class_dim,
-act=SoftmaxActivation(),
-bias_attr=bias_attr,
-param_attr=para_attr)
-
-if is_predict:
-outputs(output)
-else:
-outputs(classification_cost(input=output, label=data_layer('label', 1)))
+ class_dim=2,
+ emb_dim=128,
+ hid_dim=512,
+ stacked_num=3):
+ """
+ A Wrapper for sentiment classification task.
+ This network uses bi-directional recurrent network,
+ consisting three LSTM layers. This configure is referred to
+ the paper as following url, but use fewer layrs.
+ http://www.aclweb.org/anthology/P15-1109
+ input_dim: here is word dictionary dimension.
+ class_dim: number of categories.
+ emb_dim: dimension of word embedding.
+ hid_dim: dimension of hidden layer.
+ stacked_num: number of stacked lstm-hidden layer.
+ """
+ assert stacked_num % 2 == 1
+
+ layer_attr = paddle.attr.Extra(drop_rate=0.5)
+ fc_para_attr = paddle.attr.Param(learning_rate=1e-3)
+ lstm_para_attr = paddle.attr.Param(initial_std=0., learning_rate=1.)
+ para_attr = [fc_para_attr, lstm_para_attr]
+ bias_attr = paddle.attr.Param(initial_std=0., l2_rate=0.)
+ relu = paddle.activation.Relu()
+ linear = paddle.activation.Linear()
+
+ data = paddle.layer.data("word",
+ paddle.data_type.integer_value_sequence(input_dim))
+ emb = paddle.layer.embedding(input=data, size=emb_dim)
+
+ fc1 = paddle.layer.fc(input=emb,
+ size=hid_dim,
+ act=linear,
+ bias_attr=bias_attr)
+ lstm1 = paddle.layer.lstmemory(
+ input=fc1, act=relu, bias_attr=bias_attr, layer_attr=layer_attr)
+
+ inputs = [fc1, lstm1]
+ for i in range(2, stacked_num + 1):
+ fc = paddle.layer.fc(input=inputs,
+ size=hid_dim,
+ act=linear,
+ param_attr=para_attr,
+ bias_attr=bias_attr)
+ lstm = paddle.layer.lstmemory(
+ input=fc,
+ reverse=(i % 2) == 0,
+ act=relu,
+ bias_attr=bias_attr,
+ layer_attr=layer_attr)
+ inputs = [fc, lstm]
+
+ fc_last = paddle.layer.pooling(
+ input=inputs[0], pooling_type=paddle.pooling.Max())
+ lstm_last = paddle.layer.pooling(
+ input=inputs[1], pooling_type=paddle.pooling.Max())
+ output = paddle.layer.fc(input=[fc_last, lstm_last],
+ size=class_dim,
+ act=paddle.activation.Softmax(),
+ bias_attr=bias_attr,
+ param_attr=para_attr)
+
+ lbl = paddle.layer.data("label", paddle.data_type.integer_value(2))
+ cost = paddle.layer.classification_cost(input=output, label=lbl)
+ return cost
```
-Our model defined in `trainer_config.py` uses the `stacked_lstm_net` structure as default. If you want to use `convolution_net`, you can comment related lines.
+1. Define input data and its dimension
+
+ Parameter `input_dim` denotes the dictionary size, and `class_dim` is the number of categories. In `stacked_lstm_net`, the input to the network is defined in `paddle.layer.data`.
+
+1. Define Classifier
+
+ The above stacked bidirectional LSTM network extracts high-level features and maps them to a vector of the same size as the categories. `paddle.activation.Softmax` function or classifier is then used for calculating the probability of the sentence belonging to each category.
+
+1. Define Loss Function
+
+ In the context of supervised learning, labels of the training set are defined in `paddle.layer.data`, too. During training, cross-entropy is used as loss function in `paddle.layer.classification_cost` and as the output of the network; During testing, the outputs are the probabilities calculated in the classifier.
+
+
+To reiterate, we can either invoke `convolution_net` or `stacked_lstm_net`.
```python
-stacked_lstm_net(
-dict_dim, class_dim=class_dim, stacked_num=3, is_predict=is_predict)
-# convolution_net(dict_dim, class_dim=class_dim, is_predict=is_predict)
+word_dict = paddle.dataset.imdb.word_dict()
+dict_dim = len(word_dict)
+class_dim = 2
+
+# option 1
+cost = convolution_net(dict_dim, class_dim=class_dim)
+# option 2
+# cost = stacked_lstm_net(dict_dim, class_dim=class_dim, stacked_num=3)
```
## Model Training
-Use `train.sh` script to run local training:
-```
-./train.sh
-```
+### Define Parameters
-train.sh is as following:
-
-```bash
-paddle train --config=trainer_config.py \
---save_dir=./model_output \
---job=train \
---use_gpu=false \
---trainer_count=4 \
---num_passes=10 \
---log_period=20 \
---dot_period=20 \
---show_parameter_stats_period=100 \
---test_all_data_in_one_period=1 \
-2>&1 | tee 'train.log'
+First, we create the model parameters according to the previous model configuration `cost`.
+
+```python
+# create parameters
+parameters = paddle.parameters.create(cost)
```
-* \--config=trainer_config.py: set up model configuration.
-* \--save\_dir=./model_output: set up output folder to save model parameters.
-* \--job=train: set job mode as training.
-* \--use\_gpu=false: Use CPU for training. If you have installed GPU-version PaddlePaddle and want to try GPU training, you may set this term as true.
-* \--trainer\_count=4: setup thread number (or GPU numer).
-* \--num\_passes=15: Setup pass. In PaddlePaddle, a pass means a training epoch over all samples.
-* \--log\_period=20: print log every 20 batches.
-* \--show\_parameter\_stats\_period=100: Print statistics to screen every 100 batch.
-* \--test\_all_data\_in\_one\_period=1: Predict all testing data every time.
+### Create Trainer
-If it is running sussefully, the output log will be saved at `train.log`, model parameters will be saved at the directory `model_output/`. Output log will be as following:
+Before jumping into creating a training module, algorithm setting is also necessary.
+Here we specified `Adam` optimization algorithm via `paddle.optimizer`.
+```python
+# create optimizer
+adam_optimizer = paddle.optimizer.Adam(
+ learning_rate=2e-3,
+ regularization=paddle.optimizer.L2Regularization(rate=8e-4),
+ model_average=paddle.optimizer.ModelAverage(average_window=0.5))
+
+# create trainer
+trainer = paddle.trainer.SGD(cost=cost,
+ parameters=parameters,
+ update_equation=adam_optimizer)
```
-Batch=20 samples=2560 AvgCost=0.681644 CurrentCost=0.681644 Eval: classification_error_evaluator=0.36875 CurrentEval: classification_error_evaluator=0.36875
-...
-Pass=0 Batch=196 samples=25000 AvgCost=0.418964 Eval: classification_error_evaluator=0.1922
-Test samples=24999 cost=0.39297 Eval: classification_error_evaluator=0.149406
-```
-
-* Batch=xx: Already |xx| Batch trained.
-* samples=xx: xx samples have been processed during training.
-* AvgCost=xx: Average loss from 0-th batch to the current batch.
-* CurrentCost=xx: loss of the latest |log_period|-th batch;
-* Eval: classification\_error\_evaluator=xx: Average accuracy from 0-th batch to current batch;
-* CurrentEval: classification\_error\_evaluator: latest |log_period| batches of classification error;
-* Pass=0: Running over all data in the training set is called as a Pass. Pass “0” denotes the first round.
+### Training
-## Application models
-### Testing
+`paddle.dataset.imdb.train()` will yield records during each pass, after shuffling, a batch input is generated for training.
-Testing refers to use trained model to evaluate labeled dataset.
+```python
+train_reader = paddle.batch(
+ paddle.reader.shuffle(
+ lambda: paddle.dataset.imdb.train(word_dict), buf_size=1000),
+ batch_size=100)
+test_reader = paddle.batch(
+ lambda: paddle.dataset.imdb.test(word_dict), batch_size=100)
```
-./test.sh
-```
-
-Scripts for testing `test.sh` is as following, where the function `get_best_pass` ranks classification accuracy to obtain the best model:
-```bash
-function get_best_pass() {
-cat $1 | grep -Pzo 'Test .*\n.*pass-.*' | \
-sed -r 'N;s/Test.* error=([0-9]+\.[0-9]+).*\n.*pass-([0-9]+)/\1 \2/g' | \
-sort | head -n 1
-}
+`feeding` is devoted to specifying the correspondence between each yield record and `paddle.layer.data`. For instance, the first column of data generated by `paddle.dataset.imdb.train()` corresponds to `word` feature.
-log=train.log
-LOG=`get_best_pass $log`
-LOG=(${LOG})
-evaluate_pass="model_output/pass-${LOG[1]}"
-
-echo 'evaluating from pass '$evaluate_pass
-
-model_list=./model.list
-touch $model_list | echo $evaluate_pass > $model_list
-net_conf=trainer_config.py
-paddle train --config=$net_conf \
---model_list=$model_list \
---job=test \
---use_gpu=false \
---trainer_count=4 \
---config_args=is_test=1 \
-2>&1 | tee 'test.log'
+```python
+feeding = {'word': 0, 'label': 1}
```
-Different from training, testing requires denoting `--job = test` and model path `--model_list = $model_list`. If successful, log will be saved at `test.log`. In our test, the best model is `model_output/pass-00002`, with classification error rate as 0.115645:
+Callback function `event_handler` will be invoked to track training progress when a pre-defined event happens.
-```
-Pass=0 samples=24999 AvgCost=0.280471 Eval: classification_error_evaluator=0.115645
+```python
+def event_handler(event):
+ if isinstance(event, paddle.event.EndIteration):
+ if event.batch_id % 100 == 0:
+ print "\nPass %d, Batch %d, Cost %f, %s" % (
+ event.pass_id, event.batch_id, event.cost, event.metrics)
+ else:
+ sys.stdout.write('.')
+ sys.stdout.flush()
+ if isinstance(event, paddle.event.EndPass):
+ result = trainer.test(reader=test_reader, reader_dict=reader_dict)
+ print "\nTest with Pass %d, %s" % (event.pass_id, result.metrics)
```
-### Prediction
-`predict.py` script provides an API. Predicting IMDB data without labels as following:
+Finally, we can invoke `trainer.train` to start training:
+```python
+trainer.train(
+ reader=train_reader,
+ event_handler=event_handler,
+ feeding=feedig,
+ num_passes=10)
```
-./predict.sh
-```
-predict.sh is as following(default model path `model_output/pass-00002` may exist or modified to others):
-
-```bash
-model=model_output/pass-00002/
-config=trainer_config.py
-label=data/pre-imdb/labels.list
-cat ./data/aclImdb/test/pos/10007_10.txt | python predict.py \
---tconf=$config \
---model=$model \
---label=$label \
---dict=./data/pre-imdb/dict.txt \
---batch_size=1
-```
-
-* `cat ./data/aclImdb/test/pos/10007_10.txt` : Input prediction samples.
-* `predict.py` : Prediction script.
-* `--tconf=$config` : Network set up.
-* `--model=$model` : Model path set up.
-* `--label=$label` : set up the label dictionary, mapping integer IDs to string labels.
-* `--dict=data/pre-imdb/dict.txt` : set up the dictionary file.
-* `--batch_size=1` : batch size during prediction.
-Prediction result of our example:
+## Conclusion
-```
-Loading parameters from model_output/pass-00002/
-predicting label is pos
-```
+In this chapter, we use sentiment analysis as an example to introduce applying deep learning models on end-to-end short text classification, as well as how to use PaddlePaddle to implement the model. Meanwhile, we briefly introduce two models for text processing: CNN and RNN. In following chapters, we will see how these models can be applied in other tasks.
-`10007_10.txt` in folder`./data/aclImdb/test/pos`, the predicted label is also pos,so the prediction is correct.
-## Summary
-In this chapter, we use sentiment analysis as an example to introduce applying deep learning models on end-to-end short text classification, as well as how to use PaddlePaddle to implement the model. Meanwhile, we briefly introduce two models for text processing: CNN and RNN. In following chapters we will see how these models can be applied in other tasks.
## Reference
+
1. Kim Y. [Convolutional neural networks for sentence classification](http://arxiv.org/pdf/1408.5882)[J]. arXiv preprint arXiv:1408.5882, 2014.
2. Kalchbrenner N, Grefenstette E, Blunsom P. [A convolutional neural network for modelling sentences](http://arxiv.org/pdf/1404.2188.pdf?utm_medium=App.net&utm_source=PourOver)[J]. arXiv preprint arXiv:1404.2188, 2014.
3. Yann N. Dauphin, et al. [Language Modeling with Gated Convolutional Networks](https://arxiv.org/pdf/1612.08083v1.pdf)[J] arXiv preprint arXiv:1612.08083, 2016.
@@ -532,7 +408,7 @@ In this chapter, we use sentiment analysis as an example to introduce applying d
9. Zhou J, Xu W. [End-to-end learning of semantic role labeling using recurrent neural networks](http://www.aclweb.org/anthology/P/P15/P15-1109.pdf)[C]//Proceedings of the Annual Meeting of the Association for Computational Linguistics. 2015.
-
本教程 由
PaddlePaddle 创作,采用
知识共享 署名-非商业性使用-相同方式共享 4.0 国际 许可协议进行许可。
+This tutorial is contributed by
PaddlePaddle, and licensed under a
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
diff --git a/understand_sentiment/index.html b/understand_sentiment/index.html
index 7a2d23da6c88d02551326d65b7ead6cf486e6013..6340f3b509def6d132942b8d95a63c36d5caa718 100644
--- a/understand_sentiment/index.html
+++ b/understand_sentiment/index.html
@@ -42,7 +42,7 @@
# 情感分析
-本教程源代码目录在[book/understand_sentiment](https://github.com/PaddlePaddle/book/tree/develop/understand_sentiment), 初次使用请参考PaddlePaddle[安装教程](http://www.paddlepaddle.org/doc_cn/build_and_install/index.html)。
+本教程源代码目录在[book/understand_sentiment](https://github.com/PaddlePaddle/book/tree/develop/understand_sentiment), 初次使用请参考PaddlePaddle[安装教程](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_cn.rst)。
## 背景介绍
在自然语言处理中,情感分析一般是指判断一段文本所表达的情绪状态。其中,一段文本可以是一个句子,一个段落或一个文档。情绪状态可以是两类,如(正面,负面),(高兴,悲伤);也可以是三类,如(积极,消极,中性)等等。情感分析的应用场景十分广泛,如把用户在购物网站(亚马逊、天猫、淘宝等)、旅游网站、电影评论网站上发表的评论分成正面评论和负面评论;或为了分析用户对于某一产品的整体使用感受,抓取产品的用户评论并进行情感分析等等。表格1展示了对电影评论进行情感分析的例子:
@@ -150,14 +150,14 @@ aclImdb
```
Paddle在`dataset/imdb.py`中提实现了imdb数据集的自动下载和读取,并提供了读取字典、训练数据、测试数据等API。
-```
+```python
import sys
import paddle.v2 as paddle
```
## 配置模型
在该示例中,我们实现了两种文本分类算法,分别基于上文所述的[文本卷积神经网络](#文本卷积神经网络(CNN))和[栈式双向LSTM](#栈式双向LSTM(Stacked Bidirectional LSTM))。
### 文本卷积神经网络
-```
+```python
def convolution_net(input_dim,
class_dim=2,
emb_dim=128,
@@ -178,7 +178,7 @@ def convolution_net(input_dim,
```
网络的输入`input_dim`表示的是词典的大小,`class_dim`表示类别数。这里,我们使用[`sequence_conv_pool`](https://github.com/PaddlePaddle/Paddle/blob/develop/python/paddle/trainer_config_helpers/networks.py) API实现了卷积和池化操作。
### 栈式双向LSTM
-```
+```python
def stacked_lstm_net(input_dim,
class_dim=2,
emb_dim=128,
@@ -247,7 +247,7 @@ def stacked_lstm_net(input_dim,
```
网络的输入`stacked_num`表示的是LSTM的层数,需要是奇数,确保最高层LSTM正向。Paddle里面是通过一个fc和一个lstmemory来实现基于LSTM的循环神经网络。
## 训练模型
-```
+```python
if __name__ == '__main__':
# init
paddle.init(use_gpu=False)
@@ -255,14 +255,14 @@ if __name__ == '__main__':
启动paddle程序,use_gpu=False表示用CPU训练,如果系统支持GPU也可以修改成True使用GPU训练。
### 训练数据
使用Paddle提供的数据集`dataset.imdb`中的API来读取训练数据。
-```
+```python
print 'load dictionary...'
word_dict = paddle.dataset.imdb.word_dict()
dict_dim = len(word_dict)
class_dim = 2
```
加载数据字典,这里通过`word_dict()`API可以直接构造字典。`class_dim`是指样本类别数,该示例中样本只有正负两类。
-```
+```python
train_reader = paddle.batch(
paddle.reader.shuffle(
lambda: paddle.dataset.imdb.train(word_dict), buf_size=1000),
@@ -272,12 +272,12 @@ if __name__ == '__main__':
batch_size=100)
```
这里,`dataset.imdb.train()`和`dataset.imdb.test()`分别是`dataset.imdb`中的训练数据和测试数据API。`train_reader`在训练时使用,意义是将读取的训练数据进行shuffle后,组成一个batch数据。同理,`test_reader`是在测试的时候使用,将读取的测试数据组成一个batch。
-```
+```python
feeding={'word': 0, 'label': 1}
```
`feeding`用来指定`train_reader`和`test_reader`返回的数据与模型配置中data_layer的对应关系。这里表示reader返回的第0列数据对应`word`层,第1列数据对应`label`层。
### 构造模型
-```
+```python
# Please choose the way to build the network
# by uncommenting the corresponding line.
cost = convolution_net(dict_dim, class_dim=class_dim)
@@ -285,13 +285,13 @@ if __name__ == '__main__':
```
该示例中默认使用`convolution_net`网络,如果使用`stacked_lstm_net`网络,注释相应的行即可。其中cost是网络的优化目标,同时cost包含了整个网络的拓扑信息。
### 网络参数
-```
+```python
# create parameters
parameters = paddle.parameters.create(cost)
```
根据网络的拓扑构造网络参数。这里parameters是整个网络的参数集。
### 优化算法
-```
+```python
# create optimizer
adam_optimizer = paddle.optimizer.Adam(
learning_rate=2e-3,
@@ -301,7 +301,7 @@ if __name__ == '__main__':
Paddle中提供了一系列优化算法的API,这里使用Adam优化算法。
### 训练
可以通过`paddle.trainer.SGD`构造一个sgd trainer,并调用`trainer.train`来训练模型。
-```
+```python
# End batch and end pass event handler
def event_handler(event):
if isinstance(event, paddle.event.EndIteration):
@@ -316,7 +316,7 @@ Paddle中提供了一系列优化算法的API,这里使用Adam优化算法。
print "\nTest with Pass %d, %s" % (event.pass_id, result.metrics)
```
可以通过给train函数传递一个`event_handler`来获取每个batch和每个pass结束的状态。比如构造如下一个`event_handler`可以在每100个batch结束后输出cost和error;在每个pass结束后调用`trainer.test`计算一遍测试集并获得当前模型在测试集上的error。
-```
+```python
# create trainer
trainer = paddle.trainer.SGD(cost=cost,
parameters=parameters,
@@ -329,7 +329,7 @@ Paddle中提供了一系列优化算法的API,这里使用Adam优化算法。
num_passes=2)
```
程序运行之后的输出如下。
-```
+```text
Pass 0, Batch 0, Cost 0.693721, {'classification_error_evaluator': 0.5546875}
...................................................................................................
Pass 0, Batch 100, Cost 0.294321, {'classification_error_evaluator': 0.1015625}
diff --git a/understand_sentiment/train.py b/understand_sentiment/train.py
index 1c856556bd0cb32f60eba322469b3621c37e1349..7878f00b6401ed0e6a0863d2cec129b6e51b163d 100644
--- a/understand_sentiment/train.py
+++ b/understand_sentiment/train.py
@@ -24,9 +24,8 @@ def convolution_net(input_dim, class_dim=2, emb_dim=128, hid_dim=128):
input=emb, context_len=3, hidden_size=hid_dim)
conv_4 = paddle.networks.sequence_conv_pool(
input=emb, context_len=4, hidden_size=hid_dim)
- output = paddle.layer.fc(input=[conv_3, conv_4],
- size=class_dim,
- act=paddle.activation.Softmax())
+ output = paddle.layer.fc(
+ input=[conv_3, conv_4], size=class_dim, act=paddle.activation.Softmax())
lbl = paddle.layer.data("label", paddle.data_type.integer_value(2))
cost = paddle.layer.classification_cost(input=output, label=lbl)
return cost
@@ -64,20 +63,19 @@ def stacked_lstm_net(input_dim,
paddle.data_type.integer_value_sequence(input_dim))
emb = paddle.layer.embedding(input=data, size=emb_dim)
- fc1 = paddle.layer.fc(input=emb,
- size=hid_dim,
- act=linear,
- bias_attr=bias_attr)
+ fc1 = paddle.layer.fc(
+ input=emb, size=hid_dim, act=linear, bias_attr=bias_attr)
lstm1 = paddle.layer.lstmemory(
input=fc1, act=relu, bias_attr=bias_attr, layer_attr=layer_attr)
inputs = [fc1, lstm1]
for i in range(2, stacked_num + 1):
- fc = paddle.layer.fc(input=inputs,
- size=hid_dim,
- act=linear,
- param_attr=para_attr,
- bias_attr=bias_attr)
+ fc = paddle.layer.fc(
+ input=inputs,
+ size=hid_dim,
+ act=linear,
+ param_attr=para_attr,
+ bias_attr=bias_attr)
lstm = paddle.layer.lstmemory(
input=fc,
reverse=(i % 2) == 0,
@@ -90,11 +88,12 @@ def stacked_lstm_net(input_dim,
input=inputs[0], pooling_type=paddle.pooling.Max())
lstm_last = paddle.layer.pooling(
input=inputs[1], pooling_type=paddle.pooling.Max())
- output = paddle.layer.fc(input=[fc_last, lstm_last],
- size=class_dim,
- act=paddle.activation.Softmax(),
- bias_attr=bias_attr,
- param_attr=para_attr)
+ output = paddle.layer.fc(
+ input=[fc_last, lstm_last],
+ size=class_dim,
+ act=paddle.activation.Softmax(),
+ bias_attr=bias_attr,
+ param_attr=para_attr)
lbl = paddle.layer.data("label", paddle.data_type.integer_value(2))
cost = paddle.layer.classification_cost(input=output, label=lbl)
@@ -148,9 +147,8 @@ if __name__ == '__main__':
print "\nTest with Pass %d, %s" % (event.pass_id, result.metrics)
# create trainer
- trainer = paddle.trainer.SGD(cost=cost,
- parameters=parameters,
- update_equation=adam_optimizer)
+ trainer = paddle.trainer.SGD(
+ cost=cost, parameters=parameters, update_equation=adam_optimizer)
trainer.train(
reader=train_reader,
diff --git a/word2vec/README.en.md b/word2vec/README.en.md
index bb55cf92d8202e7879fe25ac4abb6af7ddbd0772..4c1ba71137e21d2a980bc0fda1ac3be6b158b7e2 100644
--- a/word2vec/README.en.md
+++ b/word2vec/README.en.md
@@ -2,7 +2,7 @@
This is intended as a reference tutorial. The source code of this tutorial lives on [book/word2vec](https://github.com/PaddlePaddle/book/tree/develop/word2vec).
-For instructions on getting started with PaddlePaddle, see [PaddlePaddle installation guide](http://www.paddlepaddle.org/doc_cn/build_and_install/index.html).
+For instructions on getting started with PaddlePaddle, see [PaddlePaddle installation guide](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_en.rst).
## Background Introduction
@@ -149,19 +149,257 @@ The advantages of CBOW is that it smooths over the word embeddings of the contex
As illustrated in the figure above, skip-gram model maps the word embedding of the given word onto $2n$ word embeddings (including $n$ words before and $n$ words after the given word), and then combine the classification loss of all those $2n$ words by softmax.
-## Data Preparation
+## Dataset
+
+We will use Peen Treebank (PTB) (Tomas Mikolov's pre-processed version) dataset. PTB is a small dataset, used in Recurrent Neural Network Language Modeling Toolkit\[[2](#reference)\]. Its statistics are as follows:
+
+
+
+
+ training set |
+ validation set |
+ test set |
+
+
+ ptb.train.txt |
+ ptb.valid.txt |
+ ptb.test.txt |
+
+
+ 42068 lines |
+ 3370 lines |
+ 3761 lines |
+
+
+
+
+### Python Dataset Module
+
+We encapsulated the PTB Data Set in our Python module `paddle.dataset.imikolov`. This module can
+
+1. download the dataset to `~/.cache/paddle/dataset/imikolov`, if not yet, and
+2. [preprocesses](#preprocessing) the dataset.
+
+### Preprocessing
+
+We will be training a 5-gram model. Given five words in a window, we will predict the fifth word given the first four words.
+
+Beginning and end of a sentence have a special meaning, so we will add begin token `
` in the front of the sentence. And end token `` in the end of the sentence. By moving the five word window in the sentence, data instances are generated.
+
+For example, the sentence "I have a dream that one day" generates five data instances:
+
+```text
+ I have a dream
+I have a dream that
+have a dream that one
+a dream that one day
+dream that one day
+```
+
+At last, each data instance will be converted into an integer sequence according it's words' index inside the dictionary.
+
+## Training
+
+The neural network that we will be using is illustrated in the graph below:
-## Model Configuration
Figure 5. N-gram neural network model in model configuration
+`word2vec/train.py` demonstrates training word2vec using PaddlePaddle:
+
+- Import packages.
+
+```python
+import math
+import paddle.v2 as paddle
+```
+
+- Configure parameter.
+
+```python
+embsize = 32 # word vector dimension
+hiddensize = 256 # hidden layer dimension
+N = 5 # train 5-gram
+```
+
+- Map the $n-1$ words $w_{t-n+1},...w_{t-1}$ before $w_t$ to a D-dimensional vector though matrix of dimention $|V|\times D$ (D=32 in this example).
+
+```python
+def wordemb(inlayer):
+ wordemb = paddle.layer.table_projection(
+ input=inlayer,
+ size=embsize,
+ param_attr=paddle.attr.Param(
+ name="_proj",
+ initial_std=0.001,
+ learning_rate=1,
+ l2_rate=0, ))
+ return wordemb
+```
+
+- Define name and type for input to data layer.
+
+```python
+paddle.init(use_gpu=False, trainer_count=3)
+word_dict = paddle.dataset.imikolov.build_dict()
+dict_size = len(word_dict)
+# Every layer takes integer value of range [0, dict_size)
+firstword = paddle.layer.data(
+ name="firstw", type=paddle.data_type.integer_value(dict_size))
+secondword = paddle.layer.data(
+ name="secondw", type=paddle.data_type.integer_value(dict_size))
+thirdword = paddle.layer.data(
+ name="thirdw", type=paddle.data_type.integer_value(dict_size))
+fourthword = paddle.layer.data(
+ name="fourthw", type=paddle.data_type.integer_value(dict_size))
+nextword = paddle.layer.data(
+ name="fifthw", type=paddle.data_type.integer_value(dict_size))
+
+Efirst = wordemb(firstword)
+Esecond = wordemb(secondword)
+Ethird = wordemb(thirdword)
+Efourth = wordemb(fourthword)
+```
+
+- Concatenate n-1 word embedding vectors into a single feature vector.
+
+```python
+contextemb = paddle.layer.concat(input=[Efirst, Esecond, Ethird, Efourth])
+```
+
+- Feature vector will go through a fully connected layer which outputs a hidden feature vector.
+
+```python
+hidden1 = paddle.layer.fc(input=contextemb,
+ size=hiddensize,
+ act=paddle.activation.Sigmoid(),
+ layer_attr=paddle.attr.Extra(drop_rate=0.5),
+ bias_attr=paddle.attr.Param(learning_rate=2),
+ param_attr=paddle.attr.Param(
+ initial_std=1. / math.sqrt(embsize * 8),
+ learning_rate=1))
+```
+
+- Hidden feature vector will go through another fully conected layer, turn into a $|V|$ dimensional vector. At the same time softmax will be applied to get the probability of each word being generated.
+
+```python
+predictword = paddle.layer.fc(input=hidden1,
+ size=dict_size,
+ bias_attr=paddle.attr.Param(learning_rate=2),
+ act=paddle.activation.Softmax())
+```
+
+- We will use cross-entropy cost function.
+
+```python
+cost = paddle.layer.classification_cost(input=predictword, label=nextword)
+```
+
+- Create parameter, optimizer and trainer.
+
+```python
+parameters = paddle.parameters.create(cost)
+adam_optimizer = paddle.optimizer.Adam(
+ learning_rate=3e-3,
+ regularization=paddle.optimizer.L2Regularization(8e-4))
+trainer = paddle.trainer.SGD(cost, parameters, adam_optimizer)
+```
+
+Next, we will begin the training process. `paddle.dataset.imikolov.train()` and `paddle.dataset.imikolov.test()` is our training set and test set. Both of the function will return a **reader**: In PaddlePaddle, reader is a python function which returns a Python iterator which output a single data instance at a time.
+
+`paddle.batch` takes reader as input, outputs a **batched reader**: In PaddlePaddle, a reader outputs a single data instance at a time but batched reader outputs a minibatch of data instances.
+
+```python
+import gzip
+
+def event_handler(event):
+ if isinstance(event, paddle.event.EndIteration):
+ if event.batch_id % 100 == 0:
+ print "Pass %d, Batch %d, Cost %f, %s" % (
+ event.pass_id, event.batch_id, event.cost, event.metrics)
+
+ if isinstance(event, paddle.event.EndPass):
+ result = trainer.test(
+ paddle.batch(
+ paddle.dataset.imikolov.test(word_dict, N), 32))
+ print "Pass %d, Testing metrics %s" % (event.pass_id, result.metrics)
+ with gzip.open("model_%d.tar.gz"%event.pass_id, 'w') as f:
+ parameters.to_tar(f)
+
+trainer.train(
+ paddle.batch(paddle.dataset.imikolov.train(word_dict, N), 32),
+ num_passes=100,
+ event_handler=event_handler)
+```
+
+`trainer.train` will start training, the output of `event_handler` will be similar to following:
+```text
+Pass 0, Batch 0, Cost 7.870579, {'classification_error_evaluator': 1.0}, Testing metrics {'classification_error_evaluator': 0.999591588973999}
+Pass 0, Batch 100, Cost 6.136420, {'classification_error_evaluator': 0.84375}, Testing metrics {'classification_error_evaluator': 0.8328699469566345}
+Pass 0, Batch 200, Cost 5.786797, {'classification_error_evaluator': 0.8125}, Testing metrics {'classification_error_evaluator': 0.8328542709350586}
+...
+```
+
+After 30 passes, we can get average error rate around 0.735611.
-## Model Training
## Model Application
+After the model is trained, we can load saved model parameters and uses it for other models. We can also use the parameters in applications.
+
+### Viewing Word Vector
+
+Parameters trained by PaddlePaddle can be viewed by `parameters.get()`. For example, we can check the word vector for word `apple`.
+
+```python
+embeddings = parameters.get("_proj").reshape(len(word_dict), embsize)
+
+print embeddings[word_dict['apple']]
+```
+
+```text
+[-0.38961065 -0.02392169 -0.00093231 0.36301503 0.13538605 0.16076435
+-0.0678709 0.1090285 0.42014077 -0.24119169 -0.31847557 0.20410083
+0.04910378 0.19021918 -0.0122014 -0.04099389 -0.16924137 0.1911236
+-0.10917275 0.13068172 -0.23079982 0.42699069 -0.27679482 -0.01472992
+0.2069038 0.09005053 -0.3282454 0.12717034 -0.24218646 0.25304323
+0.19072419 -0.24286366]
+```
+
+### Modifying Word Vector
+
+Word vectors (`embeddings`) that we get is a numpy array. We can modify this array and set it back to `parameters`.
+
+
+```python
+def modify_embedding(emb):
+ # Add your modification here.
+ pass
+
+modify_embedding(embeddings)
+parameters.set("_proj", embeddings)
+```
+
+### Calculating Cosine Similarity
+
+Cosine similarity is one way of quantifying the similarity between two vectors. The range of result is $[-1, 1]$. The bigger the value, the similar two vectors are:
+
+
+```python
+from scipy import spatial
+
+emb_1 = embeddings[word_dict['world']]
+emb_2 = embeddings[word_dict['would']]
+
+print spatial.distance.cosine(emb_1, emb_2)
+```
+
+```text
+0.99375076448
+```
+
## Conclusion
This chapter introduces word embedding, the relationship between language model and word embedding, and how to train neural networks to learn word embedding.
@@ -177,4 +415,4 @@ In information retrieval, the relevance between the query and document keyword c
5. https://en.wikipedia.org/wiki/Singular_value_decomposition
-
本教程 由 PaddlePaddle 创作,采用 知识共享 署名-非商业性使用-相同方式共享 4.0 国际 许可协议进行许可。
+This tutorial is contributed by PaddlePaddle, and licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
diff --git a/word2vec/README.md b/word2vec/README.md
index 414c7839d8b81834a75ae1d51db840804edaa77c..eaf1feb77417307f9cb925240bad836631f22e09 100644
--- a/word2vec/README.md
+++ b/word2vec/README.md
@@ -1,7 +1,7 @@
# 词向量
-本教程源代码目录在[book/word2vec](https://github.com/PaddlePaddle/book/tree/develop/word2vec), 初次使用请参考PaddlePaddle[安装教程](http://www.paddlepaddle.org/doc_cn/build_and_install/index.html)。
+本教程源代码目录在[book/word2vec](https://github.com/PaddlePaddle/book/tree/develop/word2vec), 初次使用请参考PaddlePaddle[安装教程](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_cn.rst)。
## 背景介绍
@@ -32,8 +32,8 @@ $$X = USV^T$$
本章中,当词向量训练好后,我们可以用数据可视化算法t-SNE\[[4](#参考文献)\]画出词语特征在二维上的投影(如下图所示)。从图中可以看出,语义相关的词语(如a, the, these; big, huge)在投影上距离很近,语意无关的词(如say, business; decision, japan)在投影上的距离很远。
-
- 图1. 词向量的二维投影
+
+ 图1. 词向量的二维投影
另一方面,我们知道两个向量的余弦值在$[-1,1]$的区间内:两个完全相同的向量余弦值为1, 两个相互垂直的向量之间余弦值为0,两个方向完全相反的向量余弦值为-1,即相关性和余弦值大小成正比。因此我们还可以计算两个词向量的余弦相似度:
@@ -86,8 +86,8 @@ $$\frac{1}{T}\sum_t f(w_t, w_{t-1}, ..., w_{t-n+1};\theta) + R(\theta)$$
其中$f(w_t, w_{t-1}, ..., w_{t-n+1})$表示根据历史n-1个词得到当前词$w_t$的条件概率,$R(\theta)$表示参数正则项。
-
- 图2. N-gram神经网络模型
+
+ 图2. N-gram神经网络模型
图2展示了N-gram神经网络模型,从下往上看,该模型分为以下几个部分:
@@ -97,7 +97,7 @@ $$\frac{1}{T}\sum_t f(w_t, w_{t-1}, ..., w_{t-n+1};\theta) + R(\theta)$$
- 然后所有词语的词向量连接成一个大向量,并经过一个非线性映射得到历史词语的隐层表示:
- $$g=Utanh(\theta^Tx + b_1) + Wx + b_2$$
+ $$g=Utanh(\theta^Tx + b_1) + Wx + b_2$$
其中,$x$为所有词语的词向量连接成的大向量,表示文本历史特征;$\theta$、$U$、$b_1$、$b_2$和$W$分别为词向量层到隐层连接的参数。$g$表示未经归一化的所有输出单词概率,$g_i$表示未经归一化的字典中第$i$个单词的输出概率。
@@ -118,8 +118,8 @@ $$\frac{1}{T}\sum_t f(w_t, w_{t-1}, ..., w_{t-n+1};\theta) + R(\theta)$$
CBOW模型通过一个词的上下文(各N个词)预测当前词。当N=2时,模型如下图所示:
-
- 图3. CBOW模型
+
+ 图3. CBOW模型
具体来说,不考虑上下文的词语输入顺序,CBOW是用上下文词语的词向量的均值来预测当前词。即:
@@ -133,8 +133,8 @@ $$context = \frac{x_{t-1} + x_{t-2} + x_{t+1} + x_{t+2}}{4}$$
CBOW的好处是对上下文词语的分布在词向量上进行了平滑,去掉了噪声,因此在小数据集上很有效。而Skip-gram的方法中,用一个词预测其上下文,得到了当前词上下文的很多样本,因此可用于更大的数据集。
-
- 图4. Skip-gram模型
+
+ 图4. Skip-gram模型
如上图所示,Skip-gram模型的具体做法是,将一个词的词向量映射到$2n$个词的词向量($2n$表示当前输入词的前后各$n$个词),然后分别通过softmax得到这$2n$个词的分类损失值之和。
@@ -144,25 +144,25 @@ CBOW的好处是对上下文词语的分布在词向量上进行了平滑,去
### 数据介绍
-本教程使用Penn Tree Bank (PTB)数据集。PTB数据集较小,训练速度快,应用于Mikolov的公开语言模型训练工具\[[2](#参考文献)\]中。其统计情况如下:
+本教程使用Penn Treebank (PTB)(经Tomas Mikolov预处理过的版本)数据集。PTB数据集较小,训练速度快,应用于Mikolov的公开语言模型训练工具\[[2](#参考文献)\]中。其统计情况如下:
-
- 训练数据 |
- 验证数据 |
- 测试数据 |
-
-
- ptb.train.txt |
- ptb.valid.txt |
- ptb.test.txt |
-
-
- 42068句 |
- 3370句 |
- 3761句 |
-
+
+ 训练数据 |
+ 验证数据 |
+ 测试数据 |
+
+
+ ptb.train.txt |
+ ptb.valid.txt |
+ ptb.test.txt |
+
+
+ 42068句 |
+ 3370句 |
+ 3761句 |
+
@@ -183,13 +183,14 @@ a dream that one day
dream that one day
```
+最后,每个输入会按其单词次在字典里的位置,转化成整数的索引序列,作为PaddlePaddle的输入。
## 编程实现
本配置的模型结构如下图所示:
-
- 图5. 模型配置中的N-gram神经网络模型
+
+ 图5. 模型配置中的N-gram神经网络模型
首先,加载所需要的包:
@@ -245,7 +246,6 @@ Efirst = wordemb(firstword)
Esecond = wordemb(secondword)
Ethird = wordemb(thirdword)
Efourth = wordemb(fourthword)
-
```
- 将这n-1个词向量经过concat_layer连接成一个大向量作为历史文本特征。
@@ -323,11 +323,12 @@ trainer.train(
event_handler=event_handler)
```
- ...
- Pass 0, Batch 25000, Cost 4.251861, {'classification_error_evaluator': 0.84375}
- Pass 0, Batch 25100, Cost 4.847692, {'classification_error_evaluator': 0.8125}
- Pass 0, Testing metrics {'classification_error_evaluator': 0.7417652606964111}
-
+```text
+Pass 0, Batch 0, Cost 7.870579, {'classification_error_evaluator': 1.0}, Testing metrics {'classification_error_evaluator': 0.999591588973999}
+Pass 0, Batch 100, Cost 6.136420, {'classification_error_evaluator': 0.84375}, Testing metrics {'classification_error_evaluator': 0.8328699469566345}
+Pass 0, Batch 200, Cost 5.786797, {'classification_error_evaluator': 0.8125}, Testing metrics {'classification_error_evaluator': 0.8328542709350586}
+...
+```
训练过程是完全自动的,event_handler里打印的日志类似如上所示:
@@ -340,22 +341,23 @@ trainer.train(
### 查看词向量
-PaddlePaddle训练出来的参数可以直接使用`parameters.get()`获取出来。例如查看单词的word的词向量,即为
+PaddlePaddle训练出来的参数可以直接使用`parameters.get()`获取出来。例如查看单词`apple`的词向量,即为
```python
embeddings = parameters.get("_proj").reshape(len(word_dict), embsize)
-print embeddings[word_dict['word']]
+print embeddings[word_dict['apple']]
```
- [-0.38961065 -0.02392169 -0.00093231 0.36301503 0.13538605 0.16076435
- -0.0678709 0.1090285 0.42014077 -0.24119169 -0.31847557 0.20410083
- 0.04910378 0.19021918 -0.0122014 -0.04099389 -0.16924137 0.1911236
- -0.10917275 0.13068172 -0.23079982 0.42699069 -0.27679482 -0.01472992
- 0.2069038 0.09005053 -0.3282454 0.12717034 -0.24218646 0.25304323
- 0.19072419 -0.24286366]
-
+```text
+[-0.38961065 -0.02392169 -0.00093231 0.36301503 0.13538605 0.16076435
+-0.0678709 0.1090285 0.42014077 -0.24119169 -0.31847557 0.20410083
+0.04910378 0.19021918 -0.0122014 -0.04099389 -0.16924137 0.1911236
+-0.10917275 0.13068172 -0.23079982 0.42699069 -0.27679482 -0.01472992
+0.2069038 0.09005053 -0.3282454 0.12717034 -0.24218646 0.25304323
+0.19072419 -0.24286366]
+```
### 修改词向量
@@ -387,8 +389,9 @@ emb_2 = embeddings[word_dict['would']]
print spatial.distance.cosine(emb_1, emb_2)
```
- 0.99375076448
-
+```text
+0.99375076448
+```
## 总结
本章中,我们介绍了词向量、语言模型和词向量的关系、以及如何通过训练神经网络模型获得词向量。在信息检索中,我们可以根据向量间的余弦夹角,来判断query和文档关键词这二者间的相关性。在句法分析和语义分析中,训练好的词向量可以用来初始化模型,以得到更好的效果。在文档分类中,有了词向量之后,可以用聚类的方法将文档中同义词进行分组。希望大家在本章后能够自行运用词向量进行相关领域的研究。
diff --git a/word2vec/index.en.html b/word2vec/index.en.html
index 52a1b902e0d6d551ff4a382a98f30d00b6ec3fc0..1a4940012a583d422238336b712c8342b7a023eb 100644
--- a/word2vec/index.en.html
+++ b/word2vec/index.en.html
@@ -44,7 +44,7 @@
This is intended as a reference tutorial. The source code of this tutorial lives on [book/word2vec](https://github.com/PaddlePaddle/book/tree/develop/word2vec).
-For instructions on getting started with PaddlePaddle, see [PaddlePaddle installation guide](http://www.paddlepaddle.org/doc_cn/build_and_install/index.html).
+For instructions on getting started with PaddlePaddle, see [PaddlePaddle installation guide](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_en.rst).
## Background Introduction
@@ -191,19 +191,257 @@ The advantages of CBOW is that it smooths over the word embeddings of the contex
As illustrated in the figure above, skip-gram model maps the word embedding of the given word onto $2n$ word embeddings (including $n$ words before and $n$ words after the given word), and then combine the classification loss of all those $2n$ words by softmax.
-## Data Preparation
+## Dataset
+
+We will use Peen Treebank (PTB) (Tomas Mikolov's pre-processed version) dataset. PTB is a small dataset, used in Recurrent Neural Network Language Modeling Toolkit\[[2](#reference)\]. Its statistics are as follows:
+
+
+
+
+ training set |
+ validation set |
+ test set |
+
+
+ ptb.train.txt |
+ ptb.valid.txt |
+ ptb.test.txt |
+
+
+ 42068 lines |
+ 3370 lines |
+ 3761 lines |
+
+
+
+
+### Python Dataset Module
+
+We encapsulated the PTB Data Set in our Python module `paddle.dataset.imikolov`. This module can
+
+1. download the dataset to `~/.cache/paddle/dataset/imikolov`, if not yet, and
+2. [preprocesses](#preprocessing) the dataset.
+
+### Preprocessing
+
+We will be training a 5-gram model. Given five words in a window, we will predict the fifth word given the first four words.
+
+Beginning and end of a sentence have a special meaning, so we will add begin token `` in the front of the sentence. And end token `` in the end of the sentence. By moving the five word window in the sentence, data instances are generated.
+
+For example, the sentence "I have a dream that one day" generates five data instances:
+
+```text
+ I have a dream
+I have a dream that
+have a dream that one
+a dream that one day
+dream that one day
+```
+
+At last, each data instance will be converted into an integer sequence according it's words' index inside the dictionary.
+
+## Training
+
+The neural network that we will be using is illustrated in the graph below:
-## Model Configuration
Figure 5. N-gram neural network model in model configuration
+`word2vec/train.py` demonstrates training word2vec using PaddlePaddle:
+
+- Import packages.
+
+```python
+import math
+import paddle.v2 as paddle
+```
+
+- Configure parameter.
+
+```python
+embsize = 32 # word vector dimension
+hiddensize = 256 # hidden layer dimension
+N = 5 # train 5-gram
+```
+
+- Map the $n-1$ words $w_{t-n+1},...w_{t-1}$ before $w_t$ to a D-dimensional vector though matrix of dimention $|V|\times D$ (D=32 in this example).
+
+```python
+def wordemb(inlayer):
+ wordemb = paddle.layer.table_projection(
+ input=inlayer,
+ size=embsize,
+ param_attr=paddle.attr.Param(
+ name="_proj",
+ initial_std=0.001,
+ learning_rate=1,
+ l2_rate=0, ))
+ return wordemb
+```
+
+- Define name and type for input to data layer.
+
+```python
+paddle.init(use_gpu=False, trainer_count=3)
+word_dict = paddle.dataset.imikolov.build_dict()
+dict_size = len(word_dict)
+# Every layer takes integer value of range [0, dict_size)
+firstword = paddle.layer.data(
+ name="firstw", type=paddle.data_type.integer_value(dict_size))
+secondword = paddle.layer.data(
+ name="secondw", type=paddle.data_type.integer_value(dict_size))
+thirdword = paddle.layer.data(
+ name="thirdw", type=paddle.data_type.integer_value(dict_size))
+fourthword = paddle.layer.data(
+ name="fourthw", type=paddle.data_type.integer_value(dict_size))
+nextword = paddle.layer.data(
+ name="fifthw", type=paddle.data_type.integer_value(dict_size))
+
+Efirst = wordemb(firstword)
+Esecond = wordemb(secondword)
+Ethird = wordemb(thirdword)
+Efourth = wordemb(fourthword)
+```
+
+- Concatenate n-1 word embedding vectors into a single feature vector.
+
+```python
+contextemb = paddle.layer.concat(input=[Efirst, Esecond, Ethird, Efourth])
+```
+
+- Feature vector will go through a fully connected layer which outputs a hidden feature vector.
+
+```python
+hidden1 = paddle.layer.fc(input=contextemb,
+ size=hiddensize,
+ act=paddle.activation.Sigmoid(),
+ layer_attr=paddle.attr.Extra(drop_rate=0.5),
+ bias_attr=paddle.attr.Param(learning_rate=2),
+ param_attr=paddle.attr.Param(
+ initial_std=1. / math.sqrt(embsize * 8),
+ learning_rate=1))
+```
+
+- Hidden feature vector will go through another fully conected layer, turn into a $|V|$ dimensional vector. At the same time softmax will be applied to get the probability of each word being generated.
+
+```python
+predictword = paddle.layer.fc(input=hidden1,
+ size=dict_size,
+ bias_attr=paddle.attr.Param(learning_rate=2),
+ act=paddle.activation.Softmax())
+```
+
+- We will use cross-entropy cost function.
+
+```python
+cost = paddle.layer.classification_cost(input=predictword, label=nextword)
+```
+
+- Create parameter, optimizer and trainer.
+
+```python
+parameters = paddle.parameters.create(cost)
+adam_optimizer = paddle.optimizer.Adam(
+ learning_rate=3e-3,
+ regularization=paddle.optimizer.L2Regularization(8e-4))
+trainer = paddle.trainer.SGD(cost, parameters, adam_optimizer)
+```
+
+Next, we will begin the training process. `paddle.dataset.imikolov.train()` and `paddle.dataset.imikolov.test()` is our training set and test set. Both of the function will return a **reader**: In PaddlePaddle, reader is a python function which returns a Python iterator which output a single data instance at a time.
+
+`paddle.batch` takes reader as input, outputs a **batched reader**: In PaddlePaddle, a reader outputs a single data instance at a time but batched reader outputs a minibatch of data instances.
+
+```python
+import gzip
+
+def event_handler(event):
+ if isinstance(event, paddle.event.EndIteration):
+ if event.batch_id % 100 == 0:
+ print "Pass %d, Batch %d, Cost %f, %s" % (
+ event.pass_id, event.batch_id, event.cost, event.metrics)
+
+ if isinstance(event, paddle.event.EndPass):
+ result = trainer.test(
+ paddle.batch(
+ paddle.dataset.imikolov.test(word_dict, N), 32))
+ print "Pass %d, Testing metrics %s" % (event.pass_id, result.metrics)
+ with gzip.open("model_%d.tar.gz"%event.pass_id, 'w') as f:
+ parameters.to_tar(f)
+
+trainer.train(
+ paddle.batch(paddle.dataset.imikolov.train(word_dict, N), 32),
+ num_passes=100,
+ event_handler=event_handler)
+```
+
+`trainer.train` will start training, the output of `event_handler` will be similar to following:
+```text
+Pass 0, Batch 0, Cost 7.870579, {'classification_error_evaluator': 1.0}, Testing metrics {'classification_error_evaluator': 0.999591588973999}
+Pass 0, Batch 100, Cost 6.136420, {'classification_error_evaluator': 0.84375}, Testing metrics {'classification_error_evaluator': 0.8328699469566345}
+Pass 0, Batch 200, Cost 5.786797, {'classification_error_evaluator': 0.8125}, Testing metrics {'classification_error_evaluator': 0.8328542709350586}
+...
+```
+
+After 30 passes, we can get average error rate around 0.735611.
-## Model Training
## Model Application
+After the model is trained, we can load saved model parameters and uses it for other models. We can also use the parameters in applications.
+
+### Viewing Word Vector
+
+Parameters trained by PaddlePaddle can be viewed by `parameters.get()`. For example, we can check the word vector for word `apple`.
+
+```python
+embeddings = parameters.get("_proj").reshape(len(word_dict), embsize)
+
+print embeddings[word_dict['apple']]
+```
+
+```text
+[-0.38961065 -0.02392169 -0.00093231 0.36301503 0.13538605 0.16076435
+-0.0678709 0.1090285 0.42014077 -0.24119169 -0.31847557 0.20410083
+0.04910378 0.19021918 -0.0122014 -0.04099389 -0.16924137 0.1911236
+-0.10917275 0.13068172 -0.23079982 0.42699069 -0.27679482 -0.01472992
+0.2069038 0.09005053 -0.3282454 0.12717034 -0.24218646 0.25304323
+0.19072419 -0.24286366]
+```
+
+### Modifying Word Vector
+
+Word vectors (`embeddings`) that we get is a numpy array. We can modify this array and set it back to `parameters`.
+
+
+```python
+def modify_embedding(emb):
+ # Add your modification here.
+ pass
+
+modify_embedding(embeddings)
+parameters.set("_proj", embeddings)
+```
+
+### Calculating Cosine Similarity
+
+Cosine similarity is one way of quantifying the similarity between two vectors. The range of result is $[-1, 1]$. The bigger the value, the similar two vectors are:
+
+
+```python
+from scipy import spatial
+
+emb_1 = embeddings[word_dict['world']]
+emb_2 = embeddings[word_dict['would']]
+
+print spatial.distance.cosine(emb_1, emb_2)
+```
+
+```text
+0.99375076448
+```
+
## Conclusion
This chapter introduces word embedding, the relationship between language model and word embedding, and how to train neural networks to learn word embedding.
@@ -219,7 +457,7 @@ In information retrieval, the relevance between the query and document keyword c
5. https://en.wikipedia.org/wiki/Singular_value_decomposition
-
本教程 由 PaddlePaddle 创作,采用 知识共享 署名-非商业性使用-相同方式共享 4.0 国际 许可协议进行许可。
+This tutorial is contributed by PaddlePaddle, and licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
diff --git a/word2vec/index.html b/word2vec/index.html
index 75c43662e3c027b7dcec5100912bff913319ea7d..ebc7d4f47d8bfb783be55df2723d7b057537506d 100644
--- a/word2vec/index.html
+++ b/word2vec/index.html
@@ -43,7 +43,7 @@
# 词向量
-本教程源代码目录在[book/word2vec](https://github.com/PaddlePaddle/book/tree/develop/word2vec), 初次使用请参考PaddlePaddle[安装教程](http://www.paddlepaddle.org/doc_cn/build_and_install/index.html)。
+本教程源代码目录在[book/word2vec](https://github.com/PaddlePaddle/book/tree/develop/word2vec), 初次使用请参考PaddlePaddle[安装教程](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_cn.rst)。
## 背景介绍
@@ -74,8 +74,8 @@ $$X = USV^T$$
本章中,当词向量训练好后,我们可以用数据可视化算法t-SNE\[[4](#参考文献)\]画出词语特征在二维上的投影(如下图所示)。从图中可以看出,语义相关的词语(如a, the, these; big, huge)在投影上距离很近,语意无关的词(如say, business; decision, japan)在投影上的距离很远。
-
- 图1. 词向量的二维投影
+
+ 图1. 词向量的二维投影
另一方面,我们知道两个向量的余弦值在$[-1,1]$的区间内:两个完全相同的向量余弦值为1, 两个相互垂直的向量之间余弦值为0,两个方向完全相反的向量余弦值为-1,即相关性和余弦值大小成正比。因此我们还可以计算两个词向量的余弦相似度:
@@ -128,8 +128,8 @@ $$\frac{1}{T}\sum_t f(w_t, w_{t-1}, ..., w_{t-n+1};\theta) + R(\theta)$$
其中$f(w_t, w_{t-1}, ..., w_{t-n+1})$表示根据历史n-1个词得到当前词$w_t$的条件概率,$R(\theta)$表示参数正则项。
-
- 图2. N-gram神经网络模型
+
+ 图2. N-gram神经网络模型
图2展示了N-gram神经网络模型,从下往上看,该模型分为以下几个部分:
@@ -139,7 +139,7 @@ $$\frac{1}{T}\sum_t f(w_t, w_{t-1}, ..., w_{t-n+1};\theta) + R(\theta)$$
- 然后所有词语的词向量连接成一个大向量,并经过一个非线性映射得到历史词语的隐层表示:
- $$g=Utanh(\theta^Tx + b_1) + Wx + b_2$$
+ $$g=Utanh(\theta^Tx + b_1) + Wx + b_2$$
其中,$x$为所有词语的词向量连接成的大向量,表示文本历史特征;$\theta$、$U$、$b_1$、$b_2$和$W$分别为词向量层到隐层连接的参数。$g$表示未经归一化的所有输出单词概率,$g_i$表示未经归一化的字典中第$i$个单词的输出概率。
@@ -160,8 +160,8 @@ $$\frac{1}{T}\sum_t f(w_t, w_{t-1}, ..., w_{t-n+1};\theta) + R(\theta)$$
CBOW模型通过一个词的上下文(各N个词)预测当前词。当N=2时,模型如下图所示:
-
- 图3. CBOW模型
+
+ 图3. CBOW模型
具体来说,不考虑上下文的词语输入顺序,CBOW是用上下文词语的词向量的均值来预测当前词。即:
@@ -175,8 +175,8 @@ $$context = \frac{x_{t-1} + x_{t-2} + x_{t+1} + x_{t+2}}{4}$$
CBOW的好处是对上下文词语的分布在词向量上进行了平滑,去掉了噪声,因此在小数据集上很有效。而Skip-gram的方法中,用一个词预测其上下文,得到了当前词上下文的很多样本,因此可用于更大的数据集。
-
- 图4. Skip-gram模型
+
+ 图4. Skip-gram模型
如上图所示,Skip-gram模型的具体做法是,将一个词的词向量映射到$2n$个词的词向量($2n$表示当前输入词的前后各$n$个词),然后分别通过softmax得到这$2n$个词的分类损失值之和。
@@ -186,25 +186,25 @@ CBOW的好处是对上下文词语的分布在词向量上进行了平滑,去
### 数据介绍
-本教程使用Penn Tree Bank (PTB)数据集。PTB数据集较小,训练速度快,应用于Mikolov的公开语言模型训练工具\[[2](#参考文献)\]中。其统计情况如下:
+本教程使用Penn Treebank (PTB)(经Tomas Mikolov预处理过的版本)数据集。PTB数据集较小,训练速度快,应用于Mikolov的公开语言模型训练工具\[[2](#参考文献)\]中。其统计情况如下:
-
- 训练数据 |
- 验证数据 |
- 测试数据 |
-
-
- ptb.train.txt |
- ptb.valid.txt |
- ptb.test.txt |
-
-
- 42068句 |
- 3370句 |
- 3761句 |
-
+
+ 训练数据 |
+ 验证数据 |
+ 测试数据 |
+
+
+ ptb.train.txt |
+ ptb.valid.txt |
+ ptb.test.txt |
+
+
+ 42068句 |
+ 3370句 |
+ 3761句 |
+
@@ -225,13 +225,14 @@ a dream that one day
dream that one day
```
+最后,每个输入会按其单词次在字典里的位置,转化成整数的索引序列,作为PaddlePaddle的输入。
## 编程实现
本配置的模型结构如下图所示:
-
- 图5. 模型配置中的N-gram神经网络模型
+
+ 图5. 模型配置中的N-gram神经网络模型
首先,加载所需要的包:
@@ -287,7 +288,6 @@ Efirst = wordemb(firstword)
Esecond = wordemb(secondword)
Ethird = wordemb(thirdword)
Efourth = wordemb(fourthword)
-
```
- 将这n-1个词向量经过concat_layer连接成一个大向量作为历史文本特征。
@@ -365,11 +365,12 @@ trainer.train(
event_handler=event_handler)
```
- ...
- Pass 0, Batch 25000, Cost 4.251861, {'classification_error_evaluator': 0.84375}
- Pass 0, Batch 25100, Cost 4.847692, {'classification_error_evaluator': 0.8125}
- Pass 0, Testing metrics {'classification_error_evaluator': 0.7417652606964111}
-
+```text
+Pass 0, Batch 0, Cost 7.870579, {'classification_error_evaluator': 1.0}, Testing metrics {'classification_error_evaluator': 0.999591588973999}
+Pass 0, Batch 100, Cost 6.136420, {'classification_error_evaluator': 0.84375}, Testing metrics {'classification_error_evaluator': 0.8328699469566345}
+Pass 0, Batch 200, Cost 5.786797, {'classification_error_evaluator': 0.8125}, Testing metrics {'classification_error_evaluator': 0.8328542709350586}
+...
+```
训练过程是完全自动的,event_handler里打印的日志类似如上所示:
@@ -382,22 +383,23 @@ trainer.train(
### 查看词向量
-PaddlePaddle训练出来的参数可以直接使用`parameters.get()`获取出来。例如查看单词的word的词向量,即为
+PaddlePaddle训练出来的参数可以直接使用`parameters.get()`获取出来。例如查看单词`apple`的词向量,即为
```python
embeddings = parameters.get("_proj").reshape(len(word_dict), embsize)
-print embeddings[word_dict['word']]
+print embeddings[word_dict['apple']]
```
- [-0.38961065 -0.02392169 -0.00093231 0.36301503 0.13538605 0.16076435
- -0.0678709 0.1090285 0.42014077 -0.24119169 -0.31847557 0.20410083
- 0.04910378 0.19021918 -0.0122014 -0.04099389 -0.16924137 0.1911236
- -0.10917275 0.13068172 -0.23079982 0.42699069 -0.27679482 -0.01472992
- 0.2069038 0.09005053 -0.3282454 0.12717034 -0.24218646 0.25304323
- 0.19072419 -0.24286366]
-
+```text
+[-0.38961065 -0.02392169 -0.00093231 0.36301503 0.13538605 0.16076435
+-0.0678709 0.1090285 0.42014077 -0.24119169 -0.31847557 0.20410083
+0.04910378 0.19021918 -0.0122014 -0.04099389 -0.16924137 0.1911236
+-0.10917275 0.13068172 -0.23079982 0.42699069 -0.27679482 -0.01472992
+0.2069038 0.09005053 -0.3282454 0.12717034 -0.24218646 0.25304323
+0.19072419 -0.24286366]
+```
### 修改词向量
@@ -429,8 +431,9 @@ emb_2 = embeddings[word_dict['would']]
print spatial.distance.cosine(emb_1, emb_2)
```
- 0.99375076448
-
+```text
+0.99375076448
+```
## 总结
本章中,我们介绍了词向量、语言模型和词向量的关系、以及如何通过训练神经网络模型获得词向量。在信息检索中,我们可以根据向量间的余弦夹角,来判断query和文档关键词这二者间的相关性。在句法分析和语义分析中,训练好的词向量可以用来初始化模型,以得到更好的效果。在文档分类中,有了词向量之后,可以用聚类的方法将文档中同义词进行分组。希望大家在本章后能够自行运用词向量进行相关领域的研究。
diff --git a/word2vec/train.py b/word2vec/train.py
index 15ad6a01cc2230ad1c8a6a44c1d3d828331a0d1d..3600025863cd91e9b2e2c1c0ffb19af9fc28070d 100644
--- a/word2vec/train.py
+++ b/word2vec/train.py
@@ -40,18 +40,19 @@ def main():
Efourth = wordemb(fourthword)
contextemb = paddle.layer.concat(input=[Efirst, Esecond, Ethird, Efourth])
- hidden1 = paddle.layer.fc(input=contextemb,
- size=hiddensize,
- act=paddle.activation.Sigmoid(),
- layer_attr=paddle.attr.Extra(drop_rate=0.5),
- bias_attr=paddle.attr.Param(learning_rate=2),
- param_attr=paddle.attr.Param(
- initial_std=1. / math.sqrt(embsize * 8),
- learning_rate=1))
- predictword = paddle.layer.fc(input=hidden1,
- size=dict_size,
- bias_attr=paddle.attr.Param(learning_rate=2),
- act=paddle.activation.Softmax())
+ hidden1 = paddle.layer.fc(
+ input=contextemb,
+ size=hiddensize,
+ act=paddle.activation.Sigmoid(),
+ layer_attr=paddle.attr.Extra(drop_rate=0.5),
+ bias_attr=paddle.attr.Param(learning_rate=2),
+ param_attr=paddle.attr.Param(
+ initial_std=1. / math.sqrt(embsize * 8), learning_rate=1))
+ predictword = paddle.layer.fc(
+ input=hidden1,
+ size=dict_size,
+ bias_attr=paddle.attr.Param(learning_rate=2),
+ act=paddle.activation.Softmax())
def event_handler(event):
if isinstance(event, paddle.event.EndIteration):