test.py 4.9 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 11 12
from models.model import DeepSpeech2Model
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 21
add_arg('num_proc_bsearch', int,    12,     "# of CPUs for beam search.")
add_arg('num_proc_data',    int,    12,     "# 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.")
25 26 27
add_arg('alpha',            float,  0.36,   "Coef of LM for beam search.")
add_arg('beta',             float,  0.25,   "Coef of WC for beam search.")
add_arg('cutoff_prob',      float,  0.99,   "Cutoff probability for pruning.")
28
add_arg('use_gru',          bool,   False,  "Use GRUs instead of simple RNNs.")
29
add_arg('use_gpu',          bool,   True,   "Use GPU or not.")
30 31 32
add_arg('share_rnn_weights',bool,   True,   "Share input-hidden weights across "
                                            "bi-directional RNNs. Not for GRU.")
add_arg('test_manifest',   str,
33
        'data/librispeech/manifest.test-clean',
34 35
        "Filepath of manifest to evaluate.")
add_arg('mean_std_path',    str,
36
        'data/librispeech/mean_std.npz',
37 38
        "Filepath of normalizer's mean & std.")
add_arg('vocab_path',       str,
39
        'data/librispeech/eng_vocab.txt',
40 41 42 43 44
        "Filepath of vocabulary.")
add_arg('model_path',       str,
        './checkpoints/params.latest.tar.gz',
        "If None, the training starts from scratch, "
        "otherwise, it resumes from the pre-trained model.")
45 46 47
add_arg('lang_model_path',  str,
        'lm/data/common_crawl_00.prune01111.trie.klm',
        "Filepath for language model.")
48
add_arg('decoding_method',  str,
49
        'ctc_beam_search',
50
        "Decoding method. Options: ctc_beam_search, ctc_greedy",
51 52 53 54 55 56 57 58 59
        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'])
60
# yapf: disable
X
Xinghai Sun 已提交
61
args = parser.parse_args()
62 63 64


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

79 80 81 82 83
    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 已提交
84
        use_gru=args.use_gru,
85
        pretrained_model_path=args.model_path,
86
        share_rnn_weights=args.share_rnn_weights)
87

Y
yangyaming 已提交
88
    error_rate_func = cer if args.error_rate_type == 'cer' else wer
Y
yangyaming 已提交
89
    error_sum, num_ins = 0.0, 0
Y
Yibing Liu 已提交
90
    for infer_data in batch_reader():
91 92
        result_transcripts = ds2_model.infer_batch(
            infer_data=infer_data,
93
            decoding_method=args.decoding_method,
94 95 96 97 98
            beam_alpha=args.alpha,
            beam_beta=args.beta,
            beam_size=args.beam_size,
            cutoff_prob=args.cutoff_prob,
            vocab_list=data_generator.vocab_list,
99
            language_model_path=args.lang_model_path,
100
            num_processes=args.num_proc_bsearch)
101 102 103
        target_transcripts = [
            ''.join([data_generator.vocab_list[token] for token in transcript])
            for _, transcript in infer_data
104
        ]
105
        for target, result in zip(target_transcripts, result_transcripts):
Y
yangyaming 已提交
106
            error_sum += error_rate_func(target, result)
107
            num_ins += 1
Y
yangyaming 已提交
108 109 110 111
        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))
112 113 114


def main():
115
    print_arguments(args)
116
    paddle.init(use_gpu=args.use_gpu, trainer_count=args.trainer_count)
117 118 119 120 121
    evaluate()


if __name__ == '__main__':
    main()