Skip to content

Commit c8d0791

Browse files
committed
Add common.h and remove DisableCopy and Typedefs
1 parent 99e43d1 commit c8d0791

25 files changed

+277
-107
lines changed
Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
图像分类教程
2+
==========
3+
4+
在本教程中,我们将使用CIFAR-10数据集训练一个卷积神经网络,并使用这个神经网络来对图片进行分类。如下图所示,卷积神经网络可以辨识图片中的主体,并给出分类结果。
5+
<center>![Image Classification](./image_classification.png)</center>
6+
7+
## 数据准备
8+
首先下载CIFAR-10数据集。下面是CIFAR-10数据集的官方网址:
9+
10+
<https://www.cs.toronto.edu/~kriz/cifar.html>
11+
12+
我们准备了一个脚本,可以用于从官方网站上下载CIFAR-10数据集,转为jpeg文件并存入特定的目录。使用这个脚本前请确认已经安装了pillow及相关依赖模块。可以参照下面的命令进行安装:
13+
14+
1. 安装pillow
15+
16+
```bash
17+
sudo apt-get install libjpeg-dev
18+
pip install pillow
19+
```
20+
21+
2. 下载数据集
22+
23+
```bash
24+
cd demo/image_classification/data/
25+
sh download_cifar.sh
26+
```
27+
28+
CIFAR-10数据集包含60000张32x32的彩色图片。图片分为10类,每个类包含6000张。其中50000张图片作为训练集,10000张作为测试集。
29+
30+
下图展示了所有的图片类别,每个类别中随机抽取了10张图片。
31+
<center>![Image Classification](./cifar.png)</center>
32+
33+
脚本运行完成后,我们应当会得到一个名为cifar-out的文件夹,其下子文件夹的结构如下
34+
35+
36+
```
37+
train
38+
---airplane
39+
---automobile
40+
---bird
41+
---cat
42+
---deer
43+
---dog
44+
---frog
45+
---horse
46+
---ship
47+
---truck
48+
test
49+
---airplane
50+
---automobile
51+
---bird
52+
---cat
53+
---deer
54+
---dog
55+
---frog
56+
---horse
57+
---ship
58+
---truck
59+
```
60+
61+
cifar-out下包含`train``test`两个文件夹,其中分别包含了CIFAR-10中的训练集和测试集。这两个文件夹下各自有10个子文件夹,每个子文件夹下存储相应分类的图片。将图片按照上述结构存储好之后,我们就可以着手对分类模型进行训练了。
62+
63+
## 预处理
64+
数据下载之后,还需要进行预处理,将数据转换为Paddle的格式。我们可以通过如下命令进行预处理工作:
65+
66+
```
67+
cd demo/image_classification/
68+
sh preprocess.sh
69+
```
70+
71+
其中`preprocess.sh` 调用 `./demo/image_classification/preprocess.py` 对图片进行预处理
72+
```sh
73+
export PYTHONPATH=$PYTHONPATH:../../
74+
data_dir=./data/cifar-out
75+
python preprocess.py -i $data_dir -s 32 -c 1
76+
```
77+
78+
`./demo/image_classification/preprocess.py` 使用如下参数:
79+
80+
- `-i``--input` 给出输入数据所在路径;
81+
- `-s``--size` 给出图片尺寸;
82+
- `-c``--color` 标示图片是彩色图或灰度图
83+
84+
## 模型训练
85+
在开始训练之前,我们需要先创建一个模型配置文件。下面我们给出了一个配置示例。**注意**,这里的列出的和`vgg_16_cifar.py`文件稍有差别,因为该文件可适用于预测。
86+
87+
```python
88+
from paddle.trainer_config_helpers import *
89+
data_dir='data/cifar-out/batches/'
90+
meta_path=data_dir+'batches.meta'
91+
args = {'meta':meta_path, 'mean_img_size': 32,
92+
'img_size': 32, 'num_classes': 10,
93+
'use_jpeg': 1, 'color': "color"}
94+
define_py_data_sources2(train_list=data_dir+"train.list",
95+
test_list=data_dir+'test.list',
96+
module='image_provider',
97+
obj='processData',
98+
args=args)
99+
settings(
100+
batch_size = 128,
101+
learning_rate = 0.1 / 128.0,
102+
learning_method = MomentumOptimizer(0.9),
103+
regularization = L2Regularization(0.0005 * 128))
104+
105+
img = data_layer(name='image', size=3*32*32)
106+
lbl = data_layer(name="label", size=10)
107+
# small_vgg is predined in trainer_config_helpers.network
108+
predict = small_vgg(input_image=img, num_channels=3)
109+
outputs(classification_cost(input=predict, label=lbl))
110+
```
111+
112+
在第一行中我们载入用于定义网络的函数。
113+
```python
114+
from paddle.trainer_config_helpers import *
115+
```
116+
117+
之后定义的`define_py_data_sources2`使用Python数据提供器,其中 `args`将在`image_provider.py`进行使用,该文件负责产生图片数据并传递给Paddle系统
118+
- `meta`: 训练集平均值。
119+
- `mean_img_size`: 平均特征图的高度及宽度。
120+
- `img_size`:输入图片的高度及宽度。
121+
- `num_classes`:类别个数。
122+
- `use_jpeg`:处理过程中数据存储格式。
123+
- `color`:标示是否为彩色图片。
124+
125+
`settings`用于设置训练算法。在下面的例子中,learning rate被设置为0.1除以batch size,而weight decay则为0.0005乘以batch size。
126+
127+
```python
128+
settings(
129+
batch_size = 128,
130+
learning_rate = 0.1 / 128.0,
131+
learning_method = MomentumOptimizer(0.9),
132+
regularization = L2Regularization(0.0005 * 128)
133+
)
134+
```
135+
136+
`small_vgg`定义了网络结构。这里我们使用的是一个小的VGG网络。关于VGG卷积神经网络的描述可以参考:[http://www.robots.ox.ac.uk/~vgg/research/very_deep/](http://www.robots.ox.ac.uk/~vgg/research/very_deep/)
137+
```python
138+
# small_vgg is predined in trainer_config_helpers.network
139+
predict = small_vgg(input_image=img, num_channels=3)
140+
```
141+
配置创建完毕后,可以运行脚本train.sh来训练模型。
142+
143+
```bash
144+
config=vgg_16_cifar.py
145+
output=./cifar_vgg_model
146+
log=train.log
147+
148+
paddle train \
149+
--config=$config \
150+
--dot_period=10 \
151+
--log_period=100 \
152+
--test_all_data_in_one_period=1 \
153+
--use_gpu=1 \
154+
--save_dir=$output \
155+
2>&1 | tee $log
156+
157+
python -m paddle.utils.plotcurve -i $log > plot.png
158+
```
159+
- 这里我们使用的是GPU模式进行训练。如果你没有GPU环境,可以设置`use_gpu=0`
160+
- `./demo/image_classification/vgg_16_cifar.py`是网络和数据配置文件。各项参数的详细说明可以在命令行参数相关文档中找到。
161+
- 脚本`plotcurve.py`依赖于python的`matplotlib`模块。因此如果这个脚本运行失败,也许是因为需要安装`matplotlib`
162+
在训练完成后,训练及测试误差曲线图会被`plotcurve.py`脚本保存在 `plot.png`中。下面是一个误差曲线图的示例:
163+
164+
<center>![Training and testing curves.](./plot.png)</center>
165+
166+
## 预测
167+
在训练完成后,模型及参数会被保存在路径`./cifar_vgg_model/pass-%05d`下。例如第300个pass的模型会被保存在`./cifar_vgg_model/pass-00299`
168+
169+
要对一个图片的进行分类预测,我们可以使用`predict.sh`,该脚本将输出预测分类的标签:
170+
171+
```
172+
sh predict.sh
173+
```
174+
175+
predict.sh:
176+
```
177+
model=cifar_vgg_model/pass-00299/
178+
image=data/cifar-out/test/airplane/seaplane_s_000978.png
179+
use_gpu=1
180+
python prediction.py $model $image $use_gpu
181+
```
182+
183+
## 练习
184+
在CUB-200数据集上使用VGG模型训练一个鸟类图片分类模型。相关的鸟类数据集可以从如下地址下载,其中包含了200种鸟类的照片(主要来自北美洲)。
185+
186+
<http://www.vision.caltech.edu/visipedia/CUB-200.html>
187+
188+
189+
190+
191+
## 细节探究
192+
### 卷积神经网络
193+
卷积神经网络是一种使用卷积层的前向神经网络,很适合构建用于理解图片内容的模型。一个典型的神经网络如下图所示:
194+
195+
![Convolutional Neural Network](./lenet.png)
196+
197+
一个卷积神经网络包含如下层:
198+
199+
- 卷积层:通过卷积操作从图片或特征图中提取特征
200+
- 池化层:使用max-pooling对特征图下采样
201+
- 全连接层:使输入层到隐藏层的神经元是全部连接的。
202+
203+
卷积神经网络在图片分类上有着惊人的性能,这是因为它发掘出了图片的两类重要信息:局部关联性质和空间不变性质。通过交替使用卷积和池化处理, 卷积神经网络能够很好的表示这两类信息。
204+
205+
关于如何定义网络中的层,以及如何在层之间进行连接,请参考Layer文档。

doc/tutorials/image_classification/index_en.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ for classification. A description of VGG network can be found here [http://www.r
147147
# small_vgg is predined in trainer_config_helpers.network
148148
predict = small_vgg(input_image=img, num_channels=3)
149149
```
150-
After writing the config, we can train the model by running the script train.sh. Notice that the following script assumes the you run the script in the `./demo/image_classification` folder. If you run the script in a different folder, you need to change the paths of the scripts and the configuration files accordingly.
150+
After writing the config, we can train the model by running the script train.sh.
151151

152152
```bash
153153
config=vgg_16_cifar.py

paddle/api/PaddleAPI.h

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,11 @@ limitations under the License. */
2020
#include <string>
2121
#include <vector>
2222
#include "paddle/utils/GlobalConstants.h"
23-
#include "paddle/utils/TypeDefs.h"
23+
#include "paddle/utils/common.h"
2424

2525
/// Import PaddlePaddle's enumeration into global namespace.
2626
using namespace paddle::enumeration_wrapper; // NOLINT
2727

28-
#define DISABLE_COPY_AND_ASSIGN(classname) \
29-
classname(const classname& other); \
30-
classname& operator=(const classname& other)
31-
3228
/**
3329
* @brief Initialize paddle.
3430
*
@@ -102,7 +98,7 @@ const size_t NO_SPARSE_ID = -1UL;
10298
struct MatrixPrivate;
10399
class Matrix {
104100
Matrix(); // User Cannot Create Matrix.
105-
DISABLE_COPY_AND_ASSIGN(Matrix);
101+
DISABLE_COPY(Matrix);
106102
static Matrix* createByPaddleMatrixPtr(void* sharedPtr);
107103

108104
public:
@@ -242,7 +238,7 @@ class Matrix {
242238

243239
struct VectorPrivate;
244240
class Vector {
245-
DISABLE_COPY_AND_ASSIGN(Vector);
241+
DISABLE_COPY(Vector);
246242
Vector();
247243
static Vector* createByPaddleVectorPtr(void* ptr);
248244

@@ -322,7 +318,7 @@ class Vector {
322318
struct IVectorPrivate;
323319
class IVector {
324320
IVector();
325-
DISABLE_COPY_AND_ASSIGN(IVector);
321+
DISABLE_COPY(IVector);
326322
static IVector* createByPaddleVectorPtr(void* ptr);
327323

328324
public:
@@ -402,7 +398,7 @@ struct ArgumentsPrivate;
402398
class Arguments {
403399
private:
404400
Arguments(); // Internal Create.
405-
DISABLE_COPY_AND_ASSIGN(Arguments);
401+
DISABLE_COPY(Arguments);
406402

407403
public:
408404
/**
@@ -472,7 +468,7 @@ enum GradientMatchineCreateMode {
472468

473469
struct ParameterConfigPrivate;
474470
class ParameterConfig {
475-
DISABLE_COPY_AND_ASSIGN(ParameterConfig);
471+
DISABLE_COPY(ParameterConfig);
476472
ParameterConfig();
477473

478474
/**
@@ -502,7 +498,7 @@ class ParameterConfig {
502498

503499
struct OptimizationConfigPrivate;
504500
class OptimizationConfig {
505-
DISABLE_COPY_AND_ASSIGN(OptimizationConfig);
501+
DISABLE_COPY(OptimizationConfig);
506502
OptimizationConfig();
507503

508504
public:
@@ -526,7 +522,7 @@ struct ParameterPrivate;
526522
class Parameter {
527523
private:
528524
Parameter();
529-
DISABLE_COPY_AND_ASSIGN(Parameter);
525+
DISABLE_COPY(Parameter);
530526

531527
public:
532528
virtual ~Parameter();
@@ -568,7 +564,7 @@ struct ModelConfigPrivate;
568564
class ModelConfig {
569565
private:
570566
ModelConfig();
571-
DISABLE_COPY_AND_ASSIGN(ModelConfig);
567+
DISABLE_COPY(ModelConfig);
572568

573569
public:
574570
virtual ~ModelConfig();
@@ -589,7 +585,7 @@ struct TrainerConfigPrivate;
589585
class TrainerConfig {
590586
private:
591587
TrainerConfig();
592-
DISABLE_COPY_AND_ASSIGN(TrainerConfig);
588+
DISABLE_COPY(TrainerConfig);
593589

594590
public:
595591
virtual ~TrainerConfig();
@@ -629,7 +625,7 @@ class UpdateCallback {
629625

630626
struct ParameterTraverseCallbackPrivate;
631627
class ParameterTraverseCallback {
632-
DISABLE_COPY_AND_ASSIGN(ParameterTraverseCallback);
628+
DISABLE_COPY(ParameterTraverseCallback);
633629
ParameterTraverseCallback();
634630

635631
public:
@@ -651,7 +647,7 @@ class ParameterTraverseCallback {
651647
*/
652648
struct ParameterOptimizerPrivate;
653649
class ParameterOptimizer {
654-
DISABLE_COPY_AND_ASSIGN(ParameterOptimizer);
650+
DISABLE_COPY(ParameterOptimizer);
655651
ParameterOptimizer();
656652

657653
public:
@@ -688,7 +684,7 @@ struct GradientMachinePrivate;
688684
class GradientMachine {
689685
private:
690686
GradientMachine();
691-
DISABLE_COPY_AND_ASSIGN(GradientMachine);
687+
DISABLE_COPY(GradientMachine);
692688

693689
public:
694690
virtual ~GradientMachine();
@@ -780,7 +776,7 @@ class Trainer {
780776
TrainerPrivate* m;
781777
Trainer();
782778
Trainer(TrainerConfig* optConfig, GradientMachine* gm);
783-
DISABLE_COPY_AND_ASSIGN(Trainer);
779+
DISABLE_COPY(Trainer);
784780

785781
public:
786782
virtual ~Trainer();
@@ -846,7 +842,7 @@ class ISequenceResults {
846842

847843
struct SequenceGeneratorPrivate;
848844
class SequenceGenerator {
849-
DISABLE_COPY_AND_ASSIGN(SequenceGenerator);
845+
DISABLE_COPY(SequenceGenerator);
850846
SequenceGenerator();
851847

852848
public:

0 commit comments

Comments
 (0)