-
Notifications
You must be signed in to change notification settings - Fork 2.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add text classification models #24
Changes from 27 commits
100796f
dfc100a
a651dc4
31ef20f
046d0a1
868d4cb
dd827a2
20c2ec9
77abc3c
0619165
da0eb4e
5a4ad99
0a39b52
1b01f6a
78531d8
55dc1a3
ac67d5a
947e70d
763615e
304df71
225979c
3a712e0
f18b572
ae6a883
18a4bd9
344a9a4
5a59fcd
55a88ad
b0071ff
631ffdd
e6cfcf1
f46dcb1
6ff3565
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
.DS_Store | ||
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
temp/ | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 这个在目前上传的脚本中,并没有用到 temp 文件夹吧?如果是这样,请先从版本库中删除。 |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,187 @@ | ||
TBD | ||
# 文本分类 | ||
文本分类是机器学习中的一项常见任务,主要目的是根据一条文本的内容,判断该文本所属的类别。在本例子中,我们利用有标注的IMDB语料库训练二分类DNN和CNN模型,完成对语料的简单文本分类。 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 这里稍微用一两句话介绍一下IMDB数据集是一个什么样的数据集。对不了解这个任务的用户更加友好一些。 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 关于IMDB的介绍在后面“实验数据”一节中有。为了避免用户读到这里时迷惑,准备在这里把IMBD去掉,直接表示为“有标注的语料库” |
||
|
||
DNN与CNN模型之间最大的区别在于,CNN模型中存在卷积结构,而DNN大多使用基本的全连接结构。这使得CNN模型可以对语料信息中相邻单词组成的短语进行分析。例如,"The apple is not bad",其中的"not bad"是决定这个句子情感的关键。对于DNN模型来说,只能感知到句子中有一个"not"和一个"bad",而CNN模型则可能直接感知到"not bad"这个关键词组。因此,在大多数文本分类任务上,CNN模型的表现要好于DNN。 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 第一句话的标书仔细地琢磨不完全精确,改成下面这样。 DNN与CNN模型之间最大的区别在于:CNN是一种序列模型,能够提取一个局部区域之内的特征,能够处理变长的序列输入。而DNN大多使用基本的全连接结构,不是一种序列模型,只能接受固定维度的特征向量作为输入。 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 对于DNN模型来说,只能感知到句子中有一个"not"和一个"bad",这句话再补充一些: 对于DNN模型来说,只能感知到句子中有一个"not"和一个"bad",并且在输入时“not”和“bad”之间的顺序关系已经丢失,网络已经不再有机会学习到序列之间蕴含的特征。 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
|
||
## 实验数据 | ||
本例子的实验在IMDB数据集上进行([数据集下载](http://ai.stanford.edu/%7Eamaas/data/sentiment/aclImdb_v1.tar.gz))。IMDB数据集包含了来自IMDb(互联网电影数据库)网站的5万条电影影评,并被标注为正面/负面两种评价。数据集被划分为train和test两部分,各2.5万条数据,正负样本的比例基本为1:1。样本直接以英文原文的形式表示。 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 第二句话中的 , IMDb-->IMDB。把“IMDB数据集包含了来自IMDb(互联网电影数据库)网站的5万条电影影评,并被标注为正面/负面两种评价。” 这句话放在IMDB数据集第一次出现的位置。 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 个人觉得“实验数据”这部分单独成节会比较合适。。。因此准备将上文中IMDB第一次出现的位置删去,让IMDB的概念到“实验数据”这一节里才第一次出现 |
||
|
||
本样例在第一次运行的时候会自动下载IMDB数据集并缓存,用户无需手动下载。 | ||
|
||
## DNN模型 | ||
|
||
**DNN的模型结构入下图所示:** | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. “DNN的模型结构如下图所示:”,有个错别字 |
||
|
||
<p align="center"> | ||
<img src="images/dnn_net.png" width = "90%" align="center"/><br/> | ||
图1. DNN文本分类模型 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
</p> | ||
|
||
**可以看到,模型主要分为如下几个部分:** | ||
|
||
- **词向量层**:IMDB的样本由原始的英文单词组成,为了方便模型的训练,必须将英文单词转化为固定维度的向量。 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. “为了方便模型的训练,必须将英文单词转化为固定维度的向量” 这样解释词向量是粗暴地,会误导用户。词向量的出现并不是为了方便模型的训练。建议修改为更加好的向用户传达词向量价值的表述。 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
|
||
- **最大池化层**:最大池化在时间序列上进行,池化过程消除了不同语料样本在单词数量多少上的差异,并提炼出词向量中每一下标位置上的最大值。经过池化后,样本被转化为一条固定维度的向量。例如,假设最大池化前的矩阵为`[[2,3,5],[7,3,6],[1,4,0]]`,该矩阵每一列代表一个词向量,则最大池化的结果为:`[[5],[7],[4]]`。 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 样本被转化为一条固定维度的向向量 --> 卷积层输出的向量的序列被转化为一条固定维度的向量。 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 假设最大池化前的矩阵为 --> 假设最大池化之前向量的序列为: There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done,此处“卷基层”应该是“词向量层”? |
||
|
||
- **全连接隐层**:经过最大池化后的向量被送入两个连续的隐层,隐层之间为全连接结构。 | ||
|
||
|
||
- **输出层**:输出层的神经元数量和样本的类别数一致,例如在二分类问题中,输出层会有2个神经元。通过Softmax激活函数,我们保证输出层各神经元的输出之和为1,因此第i个神经元的输出就可以认为是样本属于第i类的预测概率。 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Softmax激活函数将输出层神经元的输出结果归一化为一个概率分布,和为1。 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
|
||
**通过PaddlePaddle实现该DNN结构的代码如下:** | ||
|
||
```python | ||
import paddle.v2 as paddle | ||
|
||
def fc_net(input_dim, class_dim=2, emb_dim=256): | ||
# input layers | ||
data = paddle.layer.data("word", | ||
paddle.data_type.integer_value_sequence(input_dim)) | ||
lbl = paddle.layer.data("label", paddle.data_type.integer_value(class_dim)) | ||
|
||
# embedding layer | ||
emb = paddle.layer.embedding(input=data, size=emb_dim) | ||
# max pooling | ||
seq_pool = paddle.layer.pooling( | ||
input=emb, pooling_type=paddle.pooling.Max()) | ||
|
||
# two hidden layers | ||
hd_layer_size = [128, 32] | ||
hd_layer_init_std = [1.0/math.sqrt(s)/3.0 for s in hd_layer_size] | ||
hd1 = paddle.layer.fc( | ||
input=seq_pool, | ||
size=hd_layer_size[0], | ||
act=paddle.activation.Tanh(), | ||
param_attr=paddle.attr.Param(initial_std=hd_layer_init_std[0])) | ||
hd2 = paddle.layer.fc( | ||
input=hd1, | ||
size=hd_layer_size[1], | ||
act=paddle.activation.Tanh(), | ||
param_attr=paddle.attr.Param(initial_std=hd_layer_init_std[1])) | ||
|
||
# output layer | ||
output = paddle.layer.fc( | ||
input=hd2, | ||
size=class_dim, | ||
act=paddle.activation.Softmax(), | ||
param_attr=paddle.attr.Param(initial_std=1.0/math.sqrt(class_dim)/3.0)) | ||
|
||
cost = paddle.layer.classification_cost(input=output, label=lbl) | ||
|
||
return cost, output | ||
|
||
``` | ||
该DNN模型默认对输入的语料进行二分类(`class_dim=2`),embedding的词向量维度默认为256(`emd_dim=256`),两个隐层均使用Tanh激活函数(`act=paddle.activation.Tanh()`)。 | ||
|
||
需要注意的是,该模型的输入数据为整数序列,而不是原始的英文单词序列。事实上,为了处理方便我们一般会事先将单词根据词频顺序进行id化,即将单词用整数替代。这一步一般在DNN模型之外完成。 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 即将单词用整数替代 --> 即将单词用整数替代, 也就是单词在字典中的序号, There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
|
||
## CNN模型 | ||
|
||
**CNN的模型结构如下图所示:** | ||
|
||
<p align="center"> | ||
<img src="images/cnn_net.png" width = "90%" align="center"/><br/> | ||
图2. CNN文本分类模型 | ||
</p> | ||
|
||
**可以看到,模型主要分为如下几个部分:** | ||
|
||
- **词向量层**:与DNN中词向量层的作用一样,将英文单词转化为固定维度的向量。如图2中所示,将得到的词向量定义为行向量,再将语料中所有的单词产生的行向量拼接在一起组成矩阵。假设词向量维度为5,语料“The cat sat on the read mat”包含7个单词,那么得到的矩阵维度为7*5。 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 将英文单词转化为固定维度的向量 --> 建议对词向量的表述进行一些完善。 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
|
||
- **卷积层**: 文本分类中的卷积在时间序列上进行,即卷积核的宽度和词向量层产出的矩阵一致,卷积验证矩阵的高度方向进行。卷积后得到的结果被称为“特征图”(feature map)。假设卷积核的高度为h,矩阵的高度为N,卷积的步长为1,则得到的特征图为一个高度为N+1-h的向量。可以同时使用多个不同高度的卷积核,得到多个特征图。 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 此处为手误,“验证”应该为“沿着”,done |
||
|
||
- **最大池化层**: 对卷积得到的各个特征图分别进行最大池化操作。由于特征图本身已经是向量,因此这里的最大池化实际上就是简单地选出各个向量中的最大元素。各个最大元素又被并置在一起,组成新的向量,显然,该向量的维度等于特征图的数量,也就是卷积核的数量。 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 确实是“拼接”表达得更加精确,done |
||
|
||
- **全连接与输出层**:将最大池化的结果通过全连接层输出,与DNN模型一样,最后输出层的神经元个数与样本的类别数量一致,且输出之和为1。 | ||
|
||
**通过PaddlePaddle实现该CNN结构的代码如下:** | ||
|
||
```python | ||
import paddle.v2 as paddle | ||
|
||
def convolution_net(input_dim, class_dim=2, emb_dim=128, hid_dim=128): | ||
# input layers | ||
data = paddle.layer.data("word", | ||
paddle.data_type.integer_value_sequence(input_dim)) | ||
lbl = paddle.layer.data("label", paddle.data_type.integer_value(2)) | ||
|
||
#embedding layer | ||
emb = paddle.layer.embedding(input=data, size=emb_dim) | ||
|
||
# convolution layers with max pooling | ||
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) | ||
|
||
# fc and output layer | ||
output = paddle.layer.fc( | ||
input=[conv_3, conv_4], size=class_dim, act=paddle.activation.Softmax()) | ||
|
||
cost = paddle.layer.classification_cost(input=output, label=lbl) | ||
|
||
return cost, output | ||
|
||
``` | ||
|
||
该CNN网络的输入数据类型和前面介绍过的DNN一致。`paddle.networks.sequence_conv_pool`为Paddle中已经封装好的带有池化的文本序列卷积模块,该模块的`context_len`参数用于指定卷积核在同一时间覆盖的文本长度,也即图2中的卷积核的高度;`hidden_size`用于指定该类型的卷积核的数量。可以看到,上述代码定义的结构中使用了128个大小为3的卷积核和128个大小为4的卷积核,这些卷积的结果经过最大池化和结果并置后产生一个256维的向量,向量经过一个全连接层输出最终预测结果。 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 150行,Paddle --> PaddlePaddle There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 我有一个建议,PaddleBook 是目前官方唯一可以找到正式托管 V2 API 用法的“教程”,但是PaddleBook读数据直接 import paddle.dataset.×,隐层了读数据的过程。 普通用户如果需要替换自己的数据,还是会比较难以运行这些例子。我们可以简单地增加一节:使用用户数据训练。 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 好的,将在接下来添加这一部分 |
||
## 自定义数据 | ||
上面的代码样例中使用的都是PaddlePaddle自带的样例数据,如果用户希望使用其他数据进行测试,需要自行编写数据读取接口。 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 上面的代码使用了PaddlePaddle自带的样例数据,如果希望使用自己的数据进行训练,需要自行编写数据读取接口。 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
|
||
编写数据读取接口的关键在于实现一个Python生成器,生成器负责解析数据文件中的每一行内容,并组合成适当的数据形式传送给网络中的data layer。例如在本样例中,data layer需要的数据类型为`paddle.data_type.integer_value_sequence`,这本质上是一个Python list。因此我们的生成器需要完成的主要就是“从文件中读取数据”和“转换成适当形式的Python list”这两件事。 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 生成器负责解析数据文件中的每一行内容 --> 生成器负责从原始输入文集中解析出一条训练样本。 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
|
||
假设我们的数据的内容形式为: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 假设原始数据的格式为: There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
|
||
``` | ||
PaddlePaddle is good 1 | ||
What a terrible weather 0 | ||
``` | ||
每一行为一条样本,样本包括了原始语料和标签,语料内部的单词空格分隔,语料和标签之间用`\t`分隔。对于这样的数据我们可以如下编写数据读取接口: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 语料内部的单词空格分隔 --> 语料内部单词以空格分隔 对于这样的数据,可以如下自定义的数据读取接口来为PaddlePaddle返回训练数据: There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
|
||
```python | ||
def encode_word(word, word_dict): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 在代码中为每一个参数添加注释。 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
if word_dict.has_key(word): | ||
return word_dict[word] | ||
else: | ||
return word_dict['<unk>'] | ||
|
||
def data_reader(file_name, word_dict): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 请按照python 的docstring 为每一个参数添加注释。 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
def reader(): | ||
with open(file_name, "r") as f: | ||
for line in f: | ||
ins, label = line.strip('\n').split('\t') | ||
ins_data = [int(encode_word(w, word_dict)) for w in ins.split(' ')] | ||
yield ins_data, int(label) | ||
return reader | ||
``` | ||
|
||
其中`word_dict`为事先准备好的将单词映射为id的词表。该`data_reader`可以替换代码中原先的`Paddle.dataset.imdb.train`用以数据提供。 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
|
||
## 运行与输出 | ||
|
||
本部分以上文介绍的DNN网络为例,介绍如何利用样例中的`text_classification_dnn.py`脚本进行DNN网络的训练和对新样本的预测。 | ||
|
||
`text_classification_dnn.py`中的代码分为四部分: | ||
|
||
- **fc_net函数**:定义dnn网络结构,上文已经有说明。 | ||
|
||
- **train\_dnn\_model函数**:模型训练函数。定义优化方式、训练输出等内容,并组织训练流程。该函数运行完成前会将训练得到的模型数保存至硬盘上的`dnn_params.tar.gz`文件中。本函数接受一个整数类型的参数,表示训练pass的轮数。 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 代码里已经按照pass_id 存储,这里也需要相应修改。 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
|
||
- **dnn_infer函数**:载入已有模型并对新样本进行预测。函数开始运行后会从当前路径下寻找并读取`dnn_params.tar.gz`文件,加载其中的模型参数,并对test数据集中的前100条样本进行预测。 | ||
|
||
- **main函数**:主函数 | ||
|
||
要运行本样例,直接在`text_classification_dnn.py`所在路径下执行`python ./text_classification_dnn.py`即可,样例会自动依次执行数据集下载、数据读取、模型训练和保存、模型读取、新样本预测等步骤。 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 一般运行命令是 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
|
||
预测的输出形式为: | ||
|
||
``` | ||
[ 0.99892634 0.00107362] 0 | ||
[ 0.00107638 0.9989236 ] 1 | ||
[ 0.98185927 0.01814074] 0 | ||
[ 0.31667888 0.68332112] 1 | ||
[ 0.98853314 0.01146684] 0 | ||
``` | ||
|
||
每一行表示一条样本的预测结果。前两列表示该样本属于0、1这两个类别的预测概率,最后一列表示样本的实际label。 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 这里加上一些说明, CNN 模型的训练运行 ×,预测运行×。和DNN是一样的。 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done,感谢曹总的细致review |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
import sys | ||
import paddle.v2 as paddle | ||
import gzip | ||
|
||
|
||
def convolution_net(input_dim, class_dim=2, emb_dim=128, hid_dim=128): | ||
# input layers | ||
data = paddle.layer.data("word", | ||
paddle.data_type.integer_value_sequence(input_dim)) | ||
lbl = paddle.layer.data("label", paddle.data_type.integer_value(2)) | ||
|
||
#embedding layer | ||
emb = paddle.layer.embedding(input=data, size=emb_dim) | ||
|
||
# convolution layers with max pooling | ||
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) | ||
|
||
# fc and output layer | ||
output = paddle.layer.fc( | ||
input=[conv_3, conv_4], size=class_dim, act=paddle.activation.Softmax()) | ||
|
||
cost = paddle.layer.classification_cost(input=output, label=lbl) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could you help with adding more than one evaluators to this configuration, for example, besides an evaluator to calculate the error rate, if it possible to add a precision-recall evaluator? I hope to test a configuration with more than one evaluators. Thanks for your work. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done, added auc evaluator |
||
|
||
return cost, output, lbl | ||
|
||
|
||
def train_cnn_model(num_pass): | ||
# load word dictionary | ||
print 'load dictionary...' | ||
word_dict = paddle.dataset.imdb.word_dict() | ||
|
||
dict_dim = len(word_dict) | ||
class_dim = 2 | ||
# define data reader | ||
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) | ||
|
||
# network config | ||
[cost, output, label] = convolution_net(dict_dim, class_dim=class_dim) | ||
# create parameters | ||
parameters = paddle.parameters.create(cost) | ||
# 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)) | ||
|
||
# add auc evaluator | ||
paddle.evaluator.auc(input=output, label=label) | ||
|
||
# create trainer | ||
trainer = paddle.trainer.SGD( | ||
cost=cost, parameters=parameters, update_equation=adam_optimizer) | ||
|
||
# Define end batch and end pass event handler | ||
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, feeding=feeding) | ||
print "\nTest with Pass %d, %s" % (event.pass_id, result.metrics) | ||
with gzip.open("cnn_params_pass" + str(event.pass_id) + ".tar.gz", | ||
'w') as f: | ||
parameters.to_tar(f) | ||
|
||
# begin training network | ||
feeding = {'word': 0, 'label': 1} | ||
trainer.train( | ||
reader=train_reader, | ||
event_handler=event_handler, | ||
feeding=feeding, | ||
num_passes=num_pass) | ||
|
||
print("Training finished.") | ||
|
||
|
||
def cnn_infer(file_name): | ||
print("Begin to predict...") | ||
|
||
word_dict = paddle.dataset.imdb.word_dict() | ||
dict_dim = len(word_dict) | ||
class_dim = 2 | ||
|
||
[_, output, _] = convolution_net(dict_dim, class_dim=class_dim) | ||
parameters = paddle.parameters.Parameters.from_tar(gzip.open(file_name)) | ||
|
||
infer_data = [] | ||
infer_data_label = [] | ||
for item in paddle.dataset.imdb.test(word_dict): | ||
infer_data.append([item[0]]) | ||
infer_data_label.append(item[1]) | ||
|
||
predictions = paddle.infer( | ||
output_layer=output, | ||
parameters=parameters, | ||
input=infer_data, | ||
field=['value']) | ||
for i, prob in enumerate(predictions): | ||
print prob, infer_data_label[i] | ||
|
||
|
||
if __name__ == "__main__": | ||
paddle.init(use_gpu=False, trainer_count=1) | ||
num_pass = 5 | ||
train_cnn_model(num_pass=num_pass) | ||
param_file_name = "cnn_params_pass" + str(num_pass - 1) + ".tar.gz" | ||
cnn_infer(file_name=param_file_name) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这个文件暂时先删掉吧。ignore mac 的这个文件比较奇怪。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这个文件还没删掉?