recognition_en.md 21.5 KB
Newer Older
1
# Text Recognition
Khanh Tran's avatar
Khanh Tran committed
2

3
- [1. Data Preparation](#DATA_PREPARATION)
andyjpaddle's avatar
andyjpaddle committed
4
5
6
7
8
  * [1.1 Costom Dataset](#Costom_Dataset)
  * [1.2 Dataset Download](#Dataset_download)
  * [1.3 Dictionary](#Dictionary)  
  * [1.4 Add Space Category](#Add_space_category)
  * [1.5 Data Augmentation](#Data_Augmentation)
9
- [2. Training](#TRAINING)
andyjpaddle's avatar
andyjpaddle committed
10
11
12
13
14
15
16
17
18
19
20
21
22
  * [2.1 Start Training](#21-start-training)
  * [2.2 Load Trained Model and Continue Training](#22-load-trained-model-and-continue-training)
  * [2.3 Training with New Backbone](#23-training-with-new-backbone)
  * [2.4 Mixed Precision Training](#24-amp-training)
  * [2.5 Distributed Training](#25-distributed-training)
  * [2.6 Training with knowledge distillation](#kd)
  * [2.7 Multi-language Training](#Multi_language)
  * [2.8 Training on other platform(Windows/macOS/Linux DCU)](#28)
- [3. Evaluation and Test](#3-evaluation-and-test)
  * [3.1 Evaluation](#31-evaluation)
  * [3.2 Test](#32-test)
- [4. Inference](#4-inference)
- [5. FAQ](#5-faq)
WenmuZhou's avatar
WenmuZhou committed
23
24

<a name="DATA_PREPARATION"></a>
25
## 1. Data Preparation
Khanh Tran's avatar
Khanh Tran committed
26

WenmuZhou's avatar
WenmuZhou committed
27
### 1.1 DataSet Preparation
Khanh Tran's avatar
Khanh Tran committed
28

WenmuZhou's avatar
WenmuZhou committed
29
To prepare datasets, refer to [ocr_datasets](./dataset/ocr_datasets.md) .
WenmuZhou's avatar
WenmuZhou committed
30
31
32
33
34
35
36
37
38
39

PaddleOCR provides label files for training the icdar2015 dataset, which can be downloaded in the following ways:

```
# Training set label
wget -P ./train_data/ic15_data  https://paddleocr.bj.bcebos.com/dataset/rec_gt_train.txt
# Test Set Label
wget -P ./train_data/ic15_data  https://paddleocr.bj.bcebos.com/dataset/rec_gt_test.txt
```

tink2123's avatar
tink2123 committed
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
PaddleOCR also provides a data format conversion script, which can convert ICDAR official website label to a data format
supported by PaddleOCR. The data conversion tool is in `ppocr/utils/gen_label.py`, here is the training set as an example:

```
# convert the official gt to rec_gt_label.txt
python gen_label.py --mode="rec" --input_path="{path/of/origin/label}" --output_label="rec_gt_label.txt"
```

The data format is as follows, (a) is the original picture, (b) is the Ground Truth text file corresponding to each picture:

![](../datasets/icdar_rec.png)


- Multilingual dataset

The multi-language model training method is the same as the Chinese model. The training data set is 100w synthetic data. A small amount of fonts and test data can be downloaded using the following two methods.
* [Baidu Netdisk](https://pan.baidu.com/s/1bS_u207Rm7YbY33wOECKDA) ,Extraction code:frgi.
* [Google drive](https://drive.google.com/file/d/18cSWX7wXSy4G0tbKJ0d9PuIaiwRLHpjA/view)


WenmuZhou's avatar
WenmuZhou committed
60
<a name="Dictionary"></a>
WenmuZhou's avatar
WenmuZhou committed
61
### 1.2 Dictionary
Khanh Tran's avatar
Khanh Tran committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

Finally, a dictionary ({word_dict_name}.txt) needs to be provided so that when the model is trained, all the characters that appear can be mapped to the dictionary index.

Therefore, the dictionary needs to contain all the characters that you want to be recognized correctly. {word_dict_name}.txt needs to be written in the following format and saved in the `utf-8` encoding format:

```
l
d
a
d
r
n
```

In `word_dict.txt`, there is a single word in each line, which maps characters and numeric indexes together, e.g "and" will be mapped to [2 5 1]

WenmuZhou's avatar
WenmuZhou committed
78
79
PaddleOCR has built-in dictionaries, which can be used on demand.

Khanh Tran's avatar
Khanh Tran committed
80
81
`ppocr/utils/ppocr_keys_v1.txt` is a Chinese dictionary with 6623 characters.

WenmuZhou's avatar
WenmuZhou committed
82
83
84
85
`ppocr/utils/ic15_dict.txt` is an English dictionary with 63 characters

`ppocr/utils/dict/french_dict.txt` is a French dictionary with 118 characters

86
`ppocr/utils/dict/japan_dict.txt` is a Japanese dictionary with 4399 characters
WenmuZhou's avatar
WenmuZhou committed
87

tink2123's avatar
tink2123 committed
88
`ppocr/utils/dict/korean_dict.txt` is a Korean dictionary with 3636 characters
WenmuZhou's avatar
WenmuZhou committed
89

tink2123's avatar
tink2123 committed
90
91
`ppocr/utils/dict/german_dict.txt` is a German dictionary with 131 characters

tink2123's avatar
tink2123 committed
92
`ppocr/utils/en_dict.txt` is a English dictionary with 96 characters
WenmuZhou's avatar
WenmuZhou committed
93

94

WenmuZhou's avatar
WenmuZhou committed
95
The current multi-language model is still in the demo stage and will continue to optimize the model and add languages. **You are very welcome to provide us with dictionaries and fonts in other languages**,
littletomatodonkey's avatar
fix doc  
littletomatodonkey committed
96
If you like, you can submit the dictionary file to [dict](../../ppocr/utils/dict) and we will thank you in the Repo.
Khanh Tran's avatar
Khanh Tran committed
97
98


tink2123's avatar
tink2123 committed
99
To customize the dict file, please modify the `character_dict_path` field in `configs/rec/rec_icdar15_train.yml` .
Khanh Tran's avatar
Khanh Tran committed
100

tink2123's avatar
tink2123 committed
101
102
103
104
- Custom dictionary

If you need to customize dic file, please add character_dict_path field in configs/rec/rec_icdar15_train.yml to point to your dictionary path. And set character_type to ch.

WenmuZhou's avatar
WenmuZhou committed
105
<a name="Add_space_category"></a>
106
### 1.4 Add Space Category
tink2123's avatar
tink2123 committed
107

xmy0916's avatar
xmy0916 committed
108
If you want to support the recognition of the `space` category, please set the `use_space_char` field in the yml file to `True`.
tink2123's avatar
tink2123 committed
109

tink2123's avatar
tink2123 committed
110
<a name="Data_Augmentation"></a>
andyjpaddle's avatar
andyjpaddle committed
111
### 1.5 Data Augmentation
tink2123's avatar
tink2123 committed
112
113
114
115
116
117
118

PaddleOCR provides a variety of data augmentation methods. All the augmentation methods are enabled by default.

The default perturbation methods are: cvtColor, blur, jitter, Gasuss noise, random crop, perspective, color reverse, TIA augmentation.

Each disturbance method is selected with a 40% probability during the training process. For specific code implementation, please refer to: [rec_img_aug.py](../../ppocr/data/imaug/rec_img_aug.py)

andyjpaddle's avatar
andyjpaddle committed
119
120
<a name="TRAINING"></a>
## 2.Training
tink2123's avatar
tink2123 committed
121

Khanh Tran's avatar
Khanh Tran committed
122
123
PaddleOCR provides training scripts, evaluation scripts, and prediction scripts. In this section, the CRNN recognition model will be used as an example:

andyjpaddle's avatar
andyjpaddle committed
124
125
126
<a name="21-start-training"></a>
### 2.1 Start Training

Khanh Tran's avatar
Khanh Tran committed
127
128
129
130
First download the pretrain model, you can download the trained model to finetune on the icdar2015 data:

```
cd PaddleOCR/
tink2123's avatar
tink2123 committed
131
132
# Download the pre-trained model of en_PP-OCRv3
wget -P ./pretrain_models/ https://paddleocr.bj.bcebos.com/PP-OCRv3/english/en_PP-OCRv3_rec_train.tar
Khanh Tran's avatar
Khanh Tran committed
133
134
# Decompress model parameters
cd pretrain_models
tink2123's avatar
tink2123 committed
135
tar -xf en_PP-OCRv3_rec_train.tar && rm -rf en_PP-OCRv3_rec_train.tar
Khanh Tran's avatar
Khanh Tran committed
136
137
138
139
140
```

Start training:

```
tink2123's avatar
tink2123 committed
141
# GPU training Support single card and multi-card training
tink2123's avatar
tink2123 committed
142
# Training icdar15 English data and The training log will be automatically saved as train.log under "{save_model_dir}"
tink2123's avatar
tink2123 committed
143
144

#specify the single card training(Long training time, not recommended)
tink2123's avatar
tink2123 committed
145
146
python3 tools/train.py -c configs/rec/PP-OCRv3/en_PP-OCRv3_rec.yml -o Global.pretrained_model=en_PP-OCRv3_rec_train/best_accuracy

tink2123's avatar
tink2123 committed
147
#specify the card number through --gpus
tink2123's avatar
tink2123 committed
148
python3 -m paddle.distributed.launch --gpus '0,1,2,3'  tools/train.py -c configs/rec/PP-OCRv3/en_PP-OCRv3_rec.yml -o Global.pretrained_model=en_PP-OCRv3_rec_train/best_accuracy
Khanh Tran's avatar
Khanh Tran committed
149
```
tink2123's avatar
tink2123 committed
150
151


Khanh Tran's avatar
Khanh Tran committed
152
153
154
155
PaddleOCR supports alternating training and evaluation. You can modify `eval_batch_step` in `configs/rec/rec_icdar15_train.yml` to set the evaluation frequency. By default, it is evaluated every 500 iter and the best acc model is saved under `output/rec_CRNN/best_accuracy` during the evaluation process.

If the evaluation set is large, the test will be time-consuming. It is recommended to reduce the number of evaluations, or evaluate after training.

tink2123's avatar
tink2123 committed
156
* Tip: You can use the `-c` parameter to select multiple model configurations under the `configs/rec/` path for training. The recognition algorithms supported at [rec_algorithm](https://github.com/PaddlePaddle/PaddleOCR/blob/dygraph/doc/doc_en/algorithm_overview.md):
Khanh Tran's avatar
Khanh Tran committed
157
158


WenmuZhou's avatar
WenmuZhou committed
159
For training Chinese data, it is recommended to use
tink2123's avatar
tink2123 committed
160
[ch_PP-OCRv3_rec_distillation.yml](../../configs/rec/PP-OCRv3/ch_PP-OCRv3_rec_distillation.yml). If you want to try the result of other algorithms on the Chinese data set, please refer to the following instructions to modify the configuration file:
tink2123's avatar
tink2123 committed
161

tink2123's avatar
tink2123 committed
162
Take `ch_PP-OCRv3_rec_distillation.yml` as an example:
Khanh Tran's avatar
Khanh Tran committed
163
164
165
```
Global:
  ...
xmy0916's avatar
xmy0916 committed
166
167
  # Add a custom dictionary, such as modify the dictionary, please point the path to the new dictionary
  character_dict_path: ppocr/utils/ppocr_keys_v1.txt
Khanh Tran's avatar
Khanh Tran committed
168
169
  # Modify character type
  ...
170
  # Whether to recognize spaces
xmy0916's avatar
xmy0916 committed
171
  use_space_char: True
Khanh Tran's avatar
Khanh Tran committed
172

173
174
175
176

Optimizer:
  ...
  # Add learning rate decay strategy
xmy0916's avatar
xmy0916 committed
177
178
179
180
181
182
183
184
185
  lr:
    name: Cosine
    learning_rate: 0.001
  ...

...

Train:
  dataset:
MissPenguin's avatar
MissPenguin committed
186
    # Type of dataset,we support LMDBDataSet and SimpleDataSet
xmy0916's avatar
xmy0916 committed
187
188
189
190
191
192
193
194
195
    name: SimpleDataSet
    # Path of dataset
    data_dir: ./train_data/
    # Path of train list
    label_file_list: ["./train_data/train_list.txt"]
    transforms:
      ...
      - RecResizeImg:
          # Modify image_shape to fit long text
tink2123's avatar
tink2123 committed
196
          image_shape: [3, 48, 320]
xmy0916's avatar
xmy0916 committed
197
198
199
200
201
202
203
204
205
      ...
  loader:
    ...
    # Train batch_size for Single card
    batch_size_per_card: 256
    ...

Eval:
  dataset:
MissPenguin's avatar
MissPenguin committed
206
    # Type of dataset,we support LMDBDataSet and SimpleDataSet
xmy0916's avatar
xmy0916 committed
207
208
209
210
211
212
213
214
215
    name: SimpleDataSet
    # Path of dataset
    data_dir: ./train_data
    # Path of eval list
    label_file_list: ["./train_data/val_list.txt"]
    transforms:
      ...
      - RecResizeImg:
          # Modify image_shape to fit long text
tink2123's avatar
tink2123 committed
216
          image_shape: [3, 48, 320]
xmy0916's avatar
xmy0916 committed
217
218
219
220
221
      ...
  loader:
    # Eval batch_size for Single card
    batch_size_per_card: 256
    ...
Khanh Tran's avatar
Khanh Tran committed
222
223
224
```
**Note that the configuration file for prediction/evaluation must be consistent with the training.**

andyjpaddle's avatar
andyjpaddle committed
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
<a name="22-load-trained-model-and-continue-training"></a>
### 2.2 Load Trained Model and Continue Training

If you expect to load trained model and continue the training again, you can specify the parameter `Global.checkpoints` as the model path to be loaded.

For example:
```shell
python3 tools/train.py -c configs/rec/rec_icdar15_train.yml -o Global.checkpoints=./your/trained/model
```

**Note**: The priority of `Global.checkpoints` is higher than that of `Global.pretrained_model`, that is, when two parameters are specified at the same time, the model specified by `Global.checkpoints` will be loaded first. If the model path specified by `Global.checkpoints` is wrong, the one specified by `Global.pretrained_model` will be loaded.

<a name="23-training-with-new-backbone"></a>
### 2.3 Training with New Backbone

The network part completes the construction of the network, and PaddleOCR divides the network into four parts, which are under [ppocr/modeling](../../ppocr/modeling). The data entering the network will pass through these four parts in sequence(transforms->backbones->
necks->heads).

```bash
├── architectures # Code for building network
├── transforms    # Image Transformation Module
├── backbones     # Feature extraction module
├── necks         # Feature enhancement module
└── heads         # Output module
```

If the Backbone to be replaced has a corresponding implementation in PaddleOCR, you can directly modify the parameters in the `Backbone` part of the configuration yml file.

However, if you want to use a new Backbone, an example of replacing the backbones is as follows:

1. Create a new file under the [ppocr/modeling/backbones](../../ppocr/modeling/backbones) folder, such as my_backbone.py.
2. Add code in the my_backbone.py file, the sample code is as follows:

```python
import paddle
import paddle.nn as nn
import paddle.nn.functional as F


class MyBackbone(nn.Layer):
    def __init__(self, *args, **kwargs):
        super(MyBackbone, self).__init__()
        # your init code
        self.conv = nn.xxxx

    def forward(self, inputs):
        # your network forward
        y = self.conv(inputs)
        return y
```

3. Import the added module in the [ppocr/modeling/backbones/\__init\__.py](../../ppocr/modeling/backbones/__init__.py) file.

After adding the four-part modules of the network, you only need to configure them in the configuration file to use, such as:

```yaml
  Backbone:
    name: MyBackbone
    args1: args1
```

**NOTE**: More details about replace Backbone and other mudule can be found in [doc](add_new_algorithm_en.md).

<a name="24-amp-training"></a>
### 2.4 Mixed Precision Training

If you want to speed up your training further, you can use [Auto Mixed Precision Training](https://www.paddlepaddle.org.cn/documentation/docs/zh/guides/01_paddle2.0_introduction/basic_concept/amp_cn.html), taking a single machine and a single gpu as an example, the commands are as follows:

```shell
python3 tools/train.py -c configs/rec/rec_icdar15_train.yml \
     -o Global.pretrained_model=./pretrain_models/rec_mv3_none_bilstm_ctc_v2.0_train \
     Global.use_amp=True Global.scale_loss=1024.0 Global.use_dynamic_loss_scaling=True
 ```

<a name="25-distributed-training"></a>
### 2.5 Distributed Training

During multi-machine multi-gpu training, use the `--ips` parameter to set the used machine IP address, and the `--gpus` parameter to set the used GPU ID:

```bash
python3 -m paddle.distributed.launch --ips="xx.xx.xx.xx,xx.xx.xx.xx" --gpus '0,1,2,3' tools/train.py -c configs/rec/rec_icdar15_train.yml \
     -o Global.pretrained_model=./pretrain_models/rec_mv3_none_bilstm_ctc_v2.0_train
```

**Note:** When using multi-machine and multi-gpu training, you need to replace the ips value in the above command with the address of your machine, and the machines need to be able to ping each other. In addition, training needs to be launched separately on multiple machines. The command to view the ip address of the machine is `ifconfig`.

<a name="kd"></a>
### 2.6 Training with Knowledge Distillation

Knowledge distillation is supported in PaddleOCR for text recognition training process. For more details, please refer to [doc](./knowledge_distillation_en.md).

WenmuZhou's avatar
WenmuZhou committed
316
<a name="Multi_language"></a>
andyjpaddle's avatar
andyjpaddle committed
317
### 2.7 Multi-language Training
tink2123's avatar
tink2123 committed
318
319
320

Currently, the multi-language algorithms supported by PaddleOCR are:

tink2123's avatar
tink2123 committed
321
322
323
324
325
326
327
328
329
330
331
332
| Configuration file |  Algorithm name |   backbone |   trans   |   seq      |     pred     |  language |
| :--------: |  :-------:   | :-------:  |   :-------:   |   :-----:   |  :-----:   | :-----:  |
| rec_chinese_cht_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | chinese traditional  |
| rec_en_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | English(Case sensitive)   |
| rec_french_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | French |  
| rec_ger_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | German   |
| rec_japan_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | Japanese |
| rec_korean_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | Korean  |
| rec_latin_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | Latin  |
| rec_arabic_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | arabic |
| rec_cyrillic_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | cyrillic   |
| rec_devanagari_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | devanagari  |
tink2123's avatar
tink2123 committed
333

tink2123's avatar
tink2123 committed
334
For more supported languages, please refer to : [Multi-language model](https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.1/doc/doc_en/multi_languages_en.md#4-support-languages-and-abbreviations)
WenmuZhou's avatar
WenmuZhou committed
335
336
337
338
339
340
341
342
343


If you want to finetune on the basis of the existing model effect, please refer to the following instructions to modify the configuration file:

Take `rec_french_lite_train` as an example:

```
Global:
  ...
xmy0916's avatar
xmy0916 committed
344
  # Add a custom dictionary, such as modify the dictionary, please point the path to the new dictionary
WenmuZhou's avatar
WenmuZhou committed
345
346
  character_dict_path: ./ppocr/utils/dict/french_dict.txt
  ...
xmy0916's avatar
xmy0916 committed
347
  # Whether to recognize spaces
xmy0916's avatar
xmy0916 committed
348
  use_space_char: True
xmy0916's avatar
xmy0916 committed
349

WenmuZhou's avatar
WenmuZhou committed
350
...
xmy0916's avatar
xmy0916 committed
351
352
353

Train:
  dataset:
MissPenguin's avatar
MissPenguin committed
354
    # Type of dataset,we support LMDBDataSet and SimpleDataSet
xmy0916's avatar
xmy0916 committed
355
356
357
358
359
360
361
362
363
    name: SimpleDataSet
    # Path of dataset
    data_dir: ./train_data/
    # Path of train list
    label_file_list: ["./train_data/french_train.txt"]
    ...

Eval:
  dataset:
MissPenguin's avatar
MissPenguin committed
364
    # Type of dataset,we support LMDBDataSet and SimpleDataSet
xmy0916's avatar
xmy0916 committed
365
366
367
368
369
370
    name: SimpleDataSet
    # Path of dataset
    data_dir: ./train_data
    # Path of eval list
    label_file_list: ["./train_data/french_val.txt"]
    ...
WenmuZhou's avatar
WenmuZhou committed
371
```
Khanh Tran's avatar
Khanh Tran committed
372

andyjpaddle's avatar
andyjpaddle committed
373
<a name="28"></a>
andyjpaddle's avatar
andyjpaddle committed
374
### 2.8 Training on other platform(Windows/macOS/Linux DCU)
375

andyjpaddle's avatar
andyjpaddle committed
376
377
378
379
- Windows GPU/CPU
The Windows platform is slightly different from the Linux platform:
Windows platform only supports `single gpu` training and inference, specify GPU for training `set CUDA_VISIBLE_DEVICES=0`
On the Windows platform, DataLoader only supports single-process mode, so you need to set `num_workers` to 0;
380

andyjpaddle's avatar
andyjpaddle committed
381
382
- macOS
GPU mode is not supported, you need to set `use_gpu` to False in the configuration file, and the rest of the training evaluation prediction commands are exactly the same as Linux GPU.
383

andyjpaddle's avatar
andyjpaddle committed
384
385
- Linux DCU
Running on a DCU device requires setting the environment variable `export HIP_VISIBLE_DEVICES=0,1,2,3`, and the rest of the training and evaluation prediction commands are exactly the same as the Linux GPU.
386

andyjpaddle's avatar
andyjpaddle committed
387
388
<a name="3-evaluation-and-test"></a>
## 3. Evaluation and Test
389

andyjpaddle's avatar
andyjpaddle committed
390
391
392
<a name="31-evaluation"></a>
### 3.1 Evaluation

393
The model parameters during training are saved in the `Global.save_model_dir` directory by default. When evaluating indicators, you need to set `Global.checkpoints` to point to the saved parameter file. The evaluation dataset can be set by modifying the `Eval.dataset.label_file_list` field in the `configs/rec/PP-OCRv3/en_PP-OCRv3_rec.yml` file.
Khanh Tran's avatar
Khanh Tran committed
394
395
396
397


```
# GPU evaluation, Global.checkpoints is the weight to be tested
tink2123's avatar
tink2123 committed
398
python3 -m paddle.distributed.launch --gpus '0' tools/eval.py -c configs/rec/PP-OCRv3/en_PP-OCRv3_rec.yml -o Global.checkpoints={path/to/weights}/best_accuracy
Khanh Tran's avatar
Khanh Tran committed
399
400
```

andyjpaddle's avatar
andyjpaddle committed
401
402
<a name="32-test"></a>
### 3.2 Test
Khanh Tran's avatar
Khanh Tran committed
403
404
405
406


Using the model trained by paddleocr, you can quickly get prediction through the following script.

tink2123's avatar
tink2123 committed
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
The default prediction picture is stored in `infer_img`, and the trained weight is specified via `-o Global.checkpoints`:


According to the `save_model_dir` and `save_epoch_step` fields set in the configuration file, the following parameters will be saved:

```
output/rec/
├── best_accuracy.pdopt  
├── best_accuracy.pdparams  
├── best_accuracy.states  
├── config.yml  
├── iter_epoch_3.pdopt  
├── iter_epoch_3.pdparams  
├── iter_epoch_3.states  
├── latest.pdopt  
├── latest.pdparams  
├── latest.states  
└── train.log
```

Among them, best_accuracy.* is the best model on the evaluation set; iter_epoch_x.* is the model saved at intervals of `save_epoch_step`; latest.* is the model of the last epoch.
Khanh Tran's avatar
Khanh Tran committed
428
429
430

```
# Predict English results
tink2123's avatar
tink2123 committed
431
python3 tools/infer_rec.py -c configs/rec/PP-OCRv3/en_PP-OCRv3_rec.yml -o Global.pretrained_model={path/to/weights}/best_accuracy  Global.infer_img=doc/imgs_words/en/word_1.png
Khanh Tran's avatar
Khanh Tran committed
432
433
```

tink2123's avatar
tink2123 committed
434

Khanh Tran's avatar
Khanh Tran committed
435
436
Input image:

437
![](../imgs_words/en/word_1.png)
Khanh Tran's avatar
Khanh Tran committed
438
439
440
441
442

Get the prediction result of the input image:

```
infer_img: doc/imgs_words/en/word_1.png
tink2123's avatar
tink2123 committed
443
        result: ('joint', 0.9998967)
Khanh Tran's avatar
Khanh Tran committed
444
445
```

xmy0916's avatar
xmy0916 committed
446
The configuration file used for prediction must be consistent with the training. For example, you completed the training of the Chinese model with `python3 tools/train.py -c configs/rec/ch_ppocr_v2.0/rec_chinese_lite_train_v2.0.yml`, you can use the following command to predict the Chinese model:
Khanh Tran's avatar
Khanh Tran committed
447
448
449

```
# Predict Chinese results
tink2123's avatar
tink2123 committed
450
python3 tools/infer_rec.py -c configs/rec/ch_ppocr_v2.0/rec_chinese_lite_train_v2.0.yml -o Global.pretrained_model={path/to/weights}/best_accuracy Global.infer_img=doc/imgs_words/ch/word_1.jpg
Khanh Tran's avatar
Khanh Tran committed
451
452
453
454
```

Input image:

455
![](../imgs_words/ch/word_1.jpg)
Khanh Tran's avatar
Khanh Tran committed
456
457
458
459
460

Get the prediction result of the input image:

```
infer_img: doc/imgs_words/ch/word_1.jpg
tink2123's avatar
tink2123 committed
461
        result: ('韩国小馆', 0.997218)
Khanh Tran's avatar
Khanh Tran committed
462
```
463

andyjpaddle's avatar
andyjpaddle committed
464
465
466
467
<a name="4-inference"></a>
## 4. Inference

The inference model (the model saved by `paddle.jit.save`) is generally a solidified model saved after the model training is completed, and is mostly used to give prediction in deployment.
468

andyjpaddle's avatar
andyjpaddle committed
469
The model saved during the training process is the checkpoints model, which saves the parameters of the model and is mostly used to resume training.
470

andyjpaddle's avatar
andyjpaddle committed
471
Compared with the checkpoints model, the inference model will additionally save the structural information of the model. Therefore, it is easier to deploy because the model structure and model parameters are already solidified in the inference model file, and is suitable for integration with actual systems.
472
473
474
475
476
477
478
479
480

The recognition model is converted to the inference model in the same way as the detection, as follows:

```
# -c Set the training algorithm yml configuration file
# -o Set optional parameters
# Global.pretrained_model parameter Set the training model address to be converted without adding the file suffix .pdmodel, .pdopt or .pdparams.
# Global.save_inference_dir Set the address where the converted model will be saved.

tink2123's avatar
tink2123 committed
481
python3 tools/export_model.py -c configs/rec/PP-OCRv3/en_PP-OCRv3_rec.yml -o Global.pretrained_model=en_PP-OCRv3_rec_train/best_accuracy  Global.save_inference_dir=./inference/en_PP-OCRv3_rec/
482
483
484
485
486
487
488
```

If you have a model trained on your own dataset with a different dictionary file, please make sure that you modify the `character_dict_path` in the configuration file to your dictionary file path.

After the conversion is successful, there are three files in the model save directory:

```
489

tink2123's avatar
tink2123 committed
490
inference/en_PP-OCRv3_rec/
491
492
493
494
495
496
497
    ├── inference.pdiparams         # The parameter file of recognition inference model
    ├── inference.pdiparams.info    # The parameter information of recognition inference model, which can be ignored
    └── inference.pdmodel           # The program file of recognition model
```

- Text recognition model Inference using custom characters dictionary

WenmuZhou's avatar
WenmuZhou committed
498
  If the text dictionary is modified during training, when using the inference model to predict, you need to specify the dictionary path used by `--rec_char_dict_path`
499
500

  ```
WenmuZhou's avatar
WenmuZhou committed
501
  python3 tools/infer/predict_rec.py --image_dir="./doc/imgs_words_en/word_336.png" --rec_model_dir="./your inference model" --rec_image_shape="3, 32, 100" --rec_char_dict_path="your text dict path"
502
  ```
andyjpaddle's avatar
andyjpaddle committed
503
504
505
506
507
508
509

<a name="5-faq"></a>
## 5. FAQ

Q1: After the training model is transferred to the inference model, the prediction effect is inconsistent?

**A**: There are many such problems, and the problems are mostly caused by inconsistent preprocessing and postprocessing parameters when the trained model predicts and the preprocessing and postprocessing parameters when the inference model predicts. You can compare whether there are differences in preprocessing, postprocessing, and prediction in the configuration files used for training.