test.py 5.2 KB
Newer Older
Y
Yibing Liu 已提交
1 2 3 4
"""Evaluation for DeepSpeech2 model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
5 6

import argparse
X
Xinghai Sun 已提交
7
import functools
Y
Yibing Liu 已提交
8
import paddle.v2 as paddle
Y
Yibing Liu 已提交
9
from data_utils.data import DataGenerator
10
from model_utils.model import DeepSpeech2Model
11 12
from utils.error_rate import wer, cer
from utils.utility import add_arguments, print_arguments
13

14
parser = argparse.ArgumentParser(description=__doc__)
X
Xinghai Sun 已提交
15 16
add_arg = functools.partial(add_arguments, argparser=parser)
# yapf: disable
17 18 19
add_arg('batch_size',       int,    128,    "Minibatch size.")
add_arg('trainer_count',    int,    8,      "# of Trainers (CPUs or GPUs).")
add_arg('beam_size',        int,    500,    "Beam search width.")
20
add_arg('num_proc_bsearch', int,    12,     "# of CPUs for beam search.")
21
add_arg('num_proc_data',    int,    4,      "# of CPUs for data preprocessing.")
22 23 24
add_arg('num_conv_layers',  int,    2,      "# of convolution layers.")
add_arg('num_rnn_layers',   int,    3,      "# of recurrent layers.")
add_arg('rnn_layer_size',   int,    2048,   "# of recurrent cells per layer.")
Y
Yibing Liu 已提交
25 26
add_arg('alpha',            float,  2.15,   "Coef of LM for beam search.")
add_arg('beta',             float,  0.35,   "Coef of WC for beam search.")
Y
Yibing Liu 已提交
27 28
add_arg('cutoff_prob',      float,  1.0,    "Cutoff probability for pruning.")
add_arg('cutoff_top_n',     int,    40,     "Cutoff number for pruning.")
29
add_arg('use_gru',          bool,   False,  "Use GRUs instead of simple RNNs.")
30
add_arg('use_gpu',          bool,   True,   "Use GPU or not.")
31 32 33
add_arg('share_rnn_weights',bool,   True,   "Share input-hidden weights across "
                                            "bi-directional RNNs. Not for GRU.")
add_arg('test_manifest',   str,
34
        'data/librispeech/manifest.test-clean',
35 36
        "Filepath of manifest to evaluate.")
add_arg('mean_std_path',    str,
37
        'data/librispeech/mean_std.npz',
38 39
        "Filepath of normalizer's mean & std.")
add_arg('vocab_path',       str,
40
        'data/librispeech/vocab.txt',
41 42
        "Filepath of vocabulary.")
add_arg('model_path',       str,
43
        './checkpoints/libri/params.latest.tar.gz',
44 45
        "If None, the training starts from scratch, "
        "otherwise, it resumes from the pre-trained model.")
46
add_arg('lang_model_path',  str,
47
        'models/lm/common_crawl_00.prune01111.trie.klm',
48
        "Filepath for language model.")
49
add_arg('decoding_method',  str,
50
        'ctc_beam_search',
51
        "Decoding method. Options: ctc_beam_search, ctc_greedy",
52 53 54 55 56 57 58 59 60
        choices = ['ctc_beam_search', 'ctc_greedy'])
add_arg('error_rate_type',  str,
        'wer',
        "Error rate type for evaluation.",
        choices=['wer', 'cer'])
add_arg('specgram_type',    str,
        'linear',
        "Audio feature type. Options: linear, mfcc.",
        choices=['linear', 'mfcc'])
61
# yapf: disable
X
Xinghai Sun 已提交
62
args = parser.parse_args()
63 64 65


def evaluate():
Y
Yibing Liu 已提交
66
    """Evaluate on whole test data for DeepSpeech2."""
67
    data_generator = DataGenerator(
68 69
        vocab_filepath=args.vocab_path,
        mean_std_filepath=args.mean_std_path,
Y
Yibing Liu 已提交
70
        augmentation_config='{}',
71
        specgram_type=args.specgram_type,
72
        num_threads=args.num_proc_data)
Y
Yibing Liu 已提交
73
    batch_reader = data_generator.batch_reader_creator(
74
        manifest_path=args.test_manifest,
Y
Yibing Liu 已提交
75
        batch_size=args.batch_size,
Y
Yibing Liu 已提交
76
        min_batch_size=1,
Y
Yibing Liu 已提交
77 78
        sortagrad=False,
        shuffle_method=None)
79

80 81 82 83 84
    ds2_model = DeepSpeech2Model(
        vocab_size=data_generator.vocab_size,
        num_conv_layers=args.num_conv_layers,
        num_rnn_layers=args.num_rnn_layers,
        rnn_layer_size=args.rnn_layer_size,
X
Xinghai Sun 已提交
85
        use_gru=args.use_gru,
86
        pretrained_model_path=args.model_path,
87
        share_rnn_weights=args.share_rnn_weights)
88

Y
Yibing Liu 已提交
89 90 91
    # decoders only accept string encoded in utf-8
    vocab_list = [chars.encode("utf-8") for chars in data_generator.vocab_list]

Y
yangyaming 已提交
92
    error_rate_func = cer if args.error_rate_type == 'cer' else wer
Y
yangyaming 已提交
93
    error_sum, num_ins = 0.0, 0
Y
Yibing Liu 已提交
94
    for infer_data in batch_reader():
95 96
        result_transcripts = ds2_model.infer_batch(
            infer_data=infer_data,
97
            decoding_method=args.decoding_method,
98 99 100 101
            beam_alpha=args.alpha,
            beam_beta=args.beta,
            beam_size=args.beam_size,
            cutoff_prob=args.cutoff_prob,
Y
Yibing Liu 已提交
102 103
            cutoff_top_n=args.cutoff_top_n,
            vocab_list=vocab_list,
104
            language_model_path=args.lang_model_path,
105
            num_processes=args.num_proc_bsearch)
106 107 108
        target_transcripts = [
            ''.join([data_generator.vocab_list[token] for token in transcript])
            for _, transcript in infer_data
109
        ]
110
        for target, result in zip(target_transcripts, result_transcripts):
Y
yangyaming 已提交
111
            error_sum += error_rate_func(target, result)
112
            num_ins += 1
Y
yangyaming 已提交
113 114 115 116
        print("Error rate [%s] (%d/?) = %f" %
              (args.error_rate_type, num_ins, error_sum / num_ins))
    print("Final error rate [%s] (%d/%d) = %f" %
          (args.error_rate_type, num_ins, num_ins, error_sum / num_ins))
117

118
    ds2_model.logger.info("finish evaluation")
119 120

def main():
121
    print_arguments(args)
122 123 124
    paddle.init(use_gpu=args.use_gpu,
                rnn_use_batch=True,
                trainer_count=args.trainer_count)
125 126 127 128 129
    evaluate()


if __name__ == '__main__':
    main()