├── .gitignore ├── LICENSE ├── README.md ├── USER_DIR ├── __init__.py ├── librispeech_specaugment.py └── speech_recognition.py ├── loss.png ├── no_WER.png └── spec_WER.png /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SpecAugment 2 | 3 | Implementation of [SpecAugment: A Simple Data Augmentation Method for Automatic Speech Recognition](https://arxiv.org/abs/1904.08779) 4 | 5 | ## Notes 6 | * The paper introduces three techniques for augmenting speech data in speech recognition. 7 | * They come from the observation that spectrograms which often used as input can be treated as images, so various image augmentation methods can be applied. 8 | * I find the idea interesting. 9 | * It covers three methods: time warping, frequency masking, and time masking. 10 | * Details are clearly explained in the paper. 11 | * While the first one, time warping, looks salient apparently, [Daniel](danielspark@google.com), the first author, told me that indeed the other two are much more important than time warping, so it can be ignored if necessary. (Thanks for the advice, Daniel!) 12 | * I found that implementing time warping with TensorFlow is tricky because the relevant functions are based on the static shape of the melspectrogram tensor, which is hard to get from the pre-defined graph. 13 | * I test frequency / time masking on [Tensor2tensor](https://github.com/tensorflow/tensor2tensor)'s LibriSpeech Clean Small Task. 14 | * The paper used the LAS model, but I stick to Transformer. 15 | * To compare the effect of specAugment, I also run a base model, which is without augmentation. 16 | * With 4 GPUs, training (for 500K) seems to take more than a week. 17 | 18 | 19 | ## Requirements 20 | * TensorFlow==1.12.0 21 | * tensor2tensor==1.12.0 22 | 23 | ## Script 24 | ``` 25 | echo "No specAugment" 26 | # Set Paths 27 | MODEL=transformer 28 | HPARAMS=transformer_librispeech_v1 29 | 30 | PROBLEM=librispeech_clean_small 31 | DATA_DIR=data/no_spec 32 | TMP_DIR=tmp 33 | TRAIN_DIR=train/$PROBLEM 34 | 35 | mkdir -p $DATA_DIR $TMP_DIR $TRAIN_DIR 36 | 37 | # Generate data 38 | t2t-datagen \ 39 | --data_dir=$DATA_DIR \ 40 | --tmp_dir=$TMP_DIR \ 41 | --problem=$PROBLEM 42 | 43 | # Train 44 | t2t-trainer \ 45 | --data_dir=$DATA_DIR \ 46 | --problem=$PROBLEM \ 47 | --model=$MODEL \ 48 | --hparams_set=$HPARAMS \ 49 | --output_dir=$TRAIN_DIR \ 50 | --train_steps=500000 \ 51 | --eval_steps=3 \ 52 | --local_eval_frequency=5000 \ 53 | --worker_gpu=4 54 | 55 | echo "specAugment" 56 | # Set Paths 57 | PROBLEM=librispeech_specaugment 58 | DATA_DIR=data/spec 59 | TMP_DIR=tmp 60 | TRAIN_DIR=train/$PROBLEM 61 | USER_DIR=USER_DIR 62 | 63 | mkdir -p $DATA_DIR $TMP_DIR $TRAIN_DIR 64 | 65 | # Generate data 66 | t2t-datagen \ 67 | --data_dir=$DATA_DIR \ 68 | --tmp_dir=$TMP_DIR \ 69 | --problem=$PROBLEM 70 | 71 | # Train 72 | t2t-trainer \ 73 | --t2t_usr_dir=$USER_DIR \ 74 | --data_dir=$DATA_DIR \ 75 | --problem=$PROBLEM \ 76 | --model=$MODEL \ 77 | --hparams_set=$HPARAMS \ 78 | --output_dir=$TRAIN_DIR \ 79 | --train_steps=500000 \ 80 | --eval_steps=3 \ 81 | --local_eval_frequency=5000 \ 82 | --worker_gpu=4 83 | ``` 84 | 85 | ## Results 86 | ### Training loss 87 | 88 | 89 | * Apparently augmentation seems to do harm on training loss. It is understandable and expected. 90 | 91 | ### Word Error Rate (SpecAugment (top) vs. No augmentation (bottom)) 92 | 93 | 94 | 95 | 96 | * The base model looks messy. The WER hangs around 26%, which is bad. 97 | * The specAugment model looks much neater. The WER reached 20% after 500k of training. I don't think it is good enough, though. -------------------------------------------------------------------------------- /USER_DIR/__init__.py: -------------------------------------------------------------------------------- 1 | from . import librispeech_specaugment -------------------------------------------------------------------------------- /USER_DIR/librispeech_specaugment.py: -------------------------------------------------------------------------------- 1 | 2 | # coding=utf-8 3 | # Copyright 2018 The Tensor2Tensor Authors. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """Librispeech dataset.""" 18 | 19 | import os 20 | import tarfile 21 | from tensor2tensor.data_generators import generator_utils 22 | from tensor2tensor.data_generators import problem 23 | # from tensor2tensor.data_generators import speech_recognition 24 | from tensor2tensor.utils import registry 25 | 26 | import tensorflow as tf 27 | 28 | from USER_DIR import speech_recognition 29 | 30 | _LIBRISPEECH_TRAIN_DATASETS = [ 31 | [ 32 | "http://www.openslr.org/resources/12/train-clean-100.tar.gz", # pylint: disable=line-too-long 33 | "train-clean-100" 34 | ], 35 | [ 36 | "http://www.openslr.org/resources/12/train-clean-360.tar.gz", 37 | "train-clean-360" 38 | ], 39 | [ 40 | "http://www.openslr.org/resources/12/train-other-500.tar.gz", 41 | "train-other-500" 42 | ], 43 | ] 44 | _LIBRISPEECH_DEV_DATASETS = [ 45 | [ 46 | "http://www.openslr.org/resources/12/dev-clean.tar.gz", 47 | "dev-clean" 48 | ], 49 | [ 50 | "http://www.openslr.org/resources/12/dev-other.tar.gz", 51 | "dev-other" 52 | ], 53 | ] 54 | _LIBRISPEECH_TEST_DATASETS = [ 55 | [ 56 | "http://www.openslr.org/resources/12/test-clean.tar.gz", 57 | "test-clean" 58 | ], 59 | [ 60 | "http://www.openslr.org/resources/12/test-other.tar.gz", 61 | "test-other" 62 | ], 63 | ] 64 | 65 | 66 | def _collect_data(directory, input_ext, transcription_ext): 67 | """Traverses directory collecting input and target files.""" 68 | # Directory from string to tuple pair of strings 69 | # key: the filepath to a datafile including the datafile's basename. Example, 70 | # if the datafile was "/path/to/datafile.wav" then the key would be 71 | # "/path/to/datafile" 72 | # value: a pair of strings (media_filepath, label) 73 | data_files = dict() 74 | for root, _, filenames in os.walk(directory): 75 | transcripts = [filename for filename in filenames 76 | if transcription_ext in filename] 77 | for transcript in transcripts: 78 | transcript_path = os.path.join(root, transcript) 79 | with open(transcript_path, "r") as transcript_file: 80 | for transcript_line in transcript_file: 81 | line_contents = transcript_line.strip().split(" ", 1) 82 | media_base, label = line_contents 83 | key = os.path.join(root, media_base) 84 | assert key not in data_files 85 | media_name = "%s.%s"%(media_base, input_ext) 86 | media_path = os.path.join(root, media_name) 87 | data_files[key] = (media_base, media_path, label) 88 | return data_files 89 | 90 | 91 | @registry.register_problem() 92 | class LibrispeechSpecaugment(speech_recognition.SpeechRecognitionProblem): 93 | """Problem spec for Librispeech using clean and noisy data.""" 94 | 95 | # Select only the clean data 96 | TRAIN_DATASETS = _LIBRISPEECH_TRAIN_DATASETS[:1] 97 | DEV_DATASETS = _LIBRISPEECH_DEV_DATASETS[:1] 98 | TEST_DATASETS = _LIBRISPEECH_TEST_DATASETS[:1] 99 | 100 | @property 101 | def num_shards(self): 102 | return 100 103 | 104 | @property 105 | def use_subword_tokenizer(self): 106 | return False 107 | 108 | @property 109 | def num_dev_shards(self): 110 | return 1 111 | 112 | @property 113 | def num_test_shards(self): 114 | return 1 115 | 116 | @property 117 | def use_train_shards_for_dev(self): 118 | """If true, we only generate training data and hold out shards for dev.""" 119 | return False 120 | 121 | def generator(self, data_dir, tmp_dir, datasets, 122 | eos_list=None, start_from=0, how_many=0): 123 | del eos_list 124 | i = 0 125 | for url, subdir in datasets: 126 | filename = os.path.basename(url) 127 | compressed_file = generator_utils.maybe_download(tmp_dir, filename, url) 128 | 129 | read_type = "r:gz" if filename.endswith("tgz") else "r" 130 | with tarfile.open(compressed_file, read_type) as corpus_tar: 131 | # Create a subset of files that don't already exist. 132 | # tarfile.extractall errors when encountering an existing file 133 | # and tarfile.extract is extremely slow 134 | members = [] 135 | for f in corpus_tar: 136 | if not os.path.isfile(os.path.join(tmp_dir, f.name)): 137 | members.append(f) 138 | corpus_tar.extractall(tmp_dir, members=members) 139 | 140 | raw_data_dir = os.path.join(tmp_dir, "LibriSpeech", subdir) 141 | data_files = _collect_data(raw_data_dir, "flac", "txt") 142 | data_pairs = data_files.values() 143 | 144 | encoders = self.feature_encoders(data_dir) 145 | audio_encoder = encoders["waveforms"] 146 | text_encoder = encoders["targets"] 147 | 148 | for utt_id, media_file, text_data in sorted(data_pairs)[start_from:]: 149 | if how_many > 0 and i == how_many: 150 | return 151 | i += 1 152 | wav_data = audio_encoder.encode(media_file) 153 | spk_id, unused_book_id, _ = utt_id.split("-") 154 | yield { 155 | "waveforms": wav_data, 156 | "waveform_lens": [len(wav_data)], 157 | "targets": text_encoder.encode(text_data), 158 | "raw_transcript": [text_data], 159 | "utt_id": [utt_id], 160 | "spk_id": [spk_id], 161 | } 162 | 163 | def generate_data(self, data_dir, tmp_dir, task_id=-1): 164 | train_paths = self.training_filepaths( 165 | data_dir, self.num_shards, shuffled=False) 166 | dev_paths = self.dev_filepaths( 167 | data_dir, self.num_dev_shards, shuffled=False) 168 | test_paths = self.test_filepaths( 169 | data_dir, self.num_test_shards, shuffled=True) 170 | 171 | generator_utils.generate_files( 172 | self.generator(data_dir, tmp_dir, self.TEST_DATASETS), test_paths) 173 | 174 | if self.use_train_shards_for_dev: 175 | all_paths = train_paths + dev_paths 176 | generator_utils.generate_files( 177 | self.generator(data_dir, tmp_dir, self.TRAIN_DATASETS), all_paths) 178 | generator_utils.shuffle_dataset(all_paths) 179 | else: 180 | generator_utils.generate_dataset_and_shuffle( 181 | self.generator(data_dir, tmp_dir, self.TRAIN_DATASETS), train_paths, 182 | self.generator(data_dir, tmp_dir, self.DEV_DATASETS), dev_paths) 183 | 184 | -------------------------------------------------------------------------------- /USER_DIR/speech_recognition.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 The Tensor2Tensor Authors. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | """Common classes for automatic speech recognition (ASR) datasets. 17 | 18 | The audio import uses sox to generate normalized waveforms, please install 19 | it as appropriate (e.g. using apt-get or yum). 20 | """ 21 | 22 | import numpy as np 23 | 24 | from tensor2tensor.data_generators import audio_encoder 25 | from tensor2tensor.data_generators import problem 26 | from tensor2tensor.data_generators import text_encoder 27 | from tensor2tensor.layers import common_audio 28 | from tensor2tensor.layers import common_layers 29 | from tensor2tensor.layers import modalities 30 | from tensor2tensor.utils import metrics 31 | 32 | import tensorflow as tf 33 | 34 | def time_warp(mel_fbanks, W=80): 35 | ''' 36 | mel_fbanks: melspectrogram tensor. 37 | (1, timesteps or n or τ, number of mel freq bins or v, 1) 38 | W: int. time warp parameter. 39 | ''' 40 | fbank_size = tf.shape(mel_fbanks) 41 | n, v = fbank_size[1], fbank_size[2] 42 | 43 | # Source 44 | pt = tf.random_uniform([], W, n-W, tf.int32) # radnom point along the time axis 45 | src_ctr_pt_freq = tf.range(v // 2) # control points on freq-axis 46 | src_ctr_pt_time = tf.ones_like(src_ctr_pt_freq) * pt # control points on time-axis 47 | src_ctr_pts = tf.stack((src_ctr_pt_time, src_ctr_pt_freq), -1) 48 | src_ctr_pts = tf.to_float(src_ctr_pts) 49 | 50 | # Destination 51 | w = tf.random_uniform([], -W, W, tf.int32) # distance 52 | dest_ctr_pt_freq = src_ctr_pt_freq 53 | dest_ctr_pt_time = src_ctr_pt_time + w 54 | dest_ctr_pts = tf.stack((dest_ctr_pt_time, dest_ctr_pt_freq), -1) 55 | dest_ctr_pts = tf.to_float(dest_ctr_pts) 56 | 57 | # warp 58 | source_control_point_locations = tf.expand_dims(src_ctr_pts, 0) # (1, v//2, 2) 59 | dest_control_point_locations = tf.expand_dims(dest_ctr_pts, 0) # (1, v//2, 2) 60 | 61 | warped_image, _ = tf.contrib.image.sparse_image_warp(mel_fbanks, source_control_point_locations, dest_control_point_locations) 62 | return warped_image 63 | 64 | def freq_mask(mel_fbanks, F=27): 65 | ''' 66 | mel_fbanks: melspectrogram tensor. 67 | (1, timesteps or n, number of mel freq bins or v, 1) 68 | F: int. freqeuncy mask parameter. 69 | ''' 70 | fbank_size = tf.shape(mel_fbanks) 71 | n, v = fbank_size[1], fbank_size[2] 72 | 73 | f = tf.random_uniform([], 0, F, tf.int32) 74 | f0 = tf.random_uniform([], 0, v-f, tf.int32) 75 | mask = tf.concat((tf.ones(shape=(1, n, v-f0-f, 1)), 76 | tf.zeros(shape=(1, n, f, 1)), 77 | tf.ones(shape=(1, n, f0, 1)), 78 | ), 2) 79 | masked = mel_fbanks * mask 80 | return tf.to_float(masked) 81 | 82 | def time_mask(mel_fbanks, T=100): 83 | ''' 84 | mel_fbanks: melspectrogram tensor. 85 | (1, timesteps or n, number of mel freq bins or v, 1) 86 | T: int. time mask parameter. 87 | ''' 88 | fbank_size = tf.shape(mel_fbanks) 89 | n, v = fbank_size[1], fbank_size[2] 90 | 91 | t = tf.random_uniform([], 0, T, tf.int32) 92 | t0 = tf.random_uniform([], 0, n-T, tf.int32) 93 | mask = tf.concat((tf.ones(shape=(1, n-t0-t, v, 1)), 94 | tf.zeros(shape=(1, t, v, 1)), 95 | tf.ones(shape=(1, t0, v, 1)), 96 | ), 1) 97 | masked = mel_fbanks * mask 98 | return tf.to_float(masked) 99 | 100 | class ByteTextEncoderWithEos(text_encoder.ByteTextEncoder): 101 | """Encodes each byte to an id and appends the EOS token.""" 102 | 103 | def encode(self, s): 104 | return super(ByteTextEncoderWithEos, self).encode(s) + [text_encoder.EOS_ID] 105 | 106 | 107 | class SpeechRecognitionProblem(problem.Problem): 108 | """Base class for speech recognition problems.""" 109 | 110 | def hparams(self, defaults, model_hparams): 111 | p = model_hparams 112 | # Filterbank extraction in bottom instead of preprocess_example is faster. 113 | p.add_hparam("audio_preproc_in_bottom", False) 114 | # The trainer seems to reserve memory for all members of the input dict 115 | p.add_hparam("audio_keep_example_waveforms", False) 116 | p.add_hparam("audio_sample_rate", 16000) 117 | p.add_hparam("audio_preemphasis", 0.97) 118 | p.add_hparam("audio_dither", 1.0 / np.iinfo(np.int16).max) 119 | p.add_hparam("audio_frame_length", 25.0) 120 | p.add_hparam("audio_frame_step", 10.0) 121 | p.add_hparam("audio_lower_edge_hertz", 20.0) 122 | p.add_hparam("audio_upper_edge_hertz", 8000.0) 123 | p.add_hparam("audio_num_mel_bins", 80) 124 | p.add_hparam("audio_add_delta_deltas", True) 125 | p.add_hparam("num_zeropad_frames", 250) 126 | 127 | p = defaults 128 | p.modality = {"inputs": modalities.SpeechRecognitionModality, 129 | "targets": modalities.SymbolModality} 130 | p.vocab_size = {"inputs": None, 131 | "targets": 256} 132 | 133 | @property 134 | def is_character_level(self): 135 | return True 136 | 137 | @property 138 | def input_space_id(self): 139 | return problem.SpaceID.AUDIO_SPECTRAL 140 | 141 | @property 142 | def target_space_id(self): 143 | return problem.SpaceID.EN_CHR 144 | 145 | def feature_encoders(self, _): 146 | return { 147 | "inputs": None, # Put None to make sure that the logic in 148 | # decoding.py doesn't try to convert the floats 149 | # into text... 150 | "waveforms": audio_encoder.AudioEncoder(), 151 | "targets": ByteTextEncoderWithEos(), 152 | } 153 | 154 | def example_reading_spec(self): 155 | data_fields = { 156 | "waveforms": tf.VarLenFeature(tf.float32), 157 | "targets": tf.VarLenFeature(tf.int64), 158 | } 159 | 160 | data_items_to_decoders = None 161 | 162 | return data_fields, data_items_to_decoders 163 | 164 | def preprocess_example(self, example, mode, hparams): 165 | p = hparams 166 | if p.audio_preproc_in_bottom: 167 | example["inputs"] = tf.expand_dims( 168 | tf.expand_dims(example["waveforms"], -1), -1) 169 | else: 170 | waveforms = tf.expand_dims(example["waveforms"], 0) 171 | mel_fbanks = common_audio.compute_mel_filterbank_features( 172 | waveforms, 173 | sample_rate=p.audio_sample_rate, 174 | dither=p.audio_dither, 175 | preemphasis=p.audio_preemphasis, 176 | frame_length=p.audio_frame_length, 177 | frame_step=p.audio_frame_step, 178 | lower_edge_hertz=p.audio_lower_edge_hertz, 179 | upper_edge_hertz=p.audio_upper_edge_hertz, 180 | num_mel_bins=p.audio_num_mel_bins, 181 | apply_mask=False) 182 | if p.audio_add_delta_deltas: 183 | mel_fbanks = common_audio.add_delta_deltas(mel_fbanks) 184 | fbank_size = common_layers.shape_list(mel_fbanks) 185 | assert fbank_size[0] == 1 186 | 187 | # This replaces CMVN estimation on data 188 | var_epsilon = 1e-09 189 | mean = tf.reduce_mean(mel_fbanks, keepdims=True, axis=1) 190 | variance = tf.reduce_mean(tf.square(mel_fbanks - mean), 191 | keepdims=True, axis=1) 192 | mel_fbanks = (mel_fbanks - mean) * tf.rsqrt(variance + var_epsilon) 193 | 194 | ######### specaugment added by kyubyong ######### 195 | if mode == tf.estimator.ModeKeys.TRAIN: 196 | # mel_fbanks = time_warp(mel_fbanks) 197 | mel_fbanks = freq_mask(mel_fbanks) 198 | mel_fbanks = time_mask(mel_fbanks) 199 | 200 | ######### /specaugment added by kyubyong ######### 201 | 202 | # Later models like to flatten the two spatial dims. Instead, we add a 203 | # unit spatial dim and flatten the frequencies and channels. 204 | example["inputs"] = tf.concat([ 205 | tf.reshape(mel_fbanks, [fbank_size[1], fbank_size[2], fbank_size[3]]), 206 | tf.zeros((p.num_zeropad_frames, fbank_size[2], fbank_size[3]))], 0) 207 | 208 | if not p.audio_keep_example_waveforms: 209 | del example["waveforms"] 210 | return super(SpeechRecognitionProblem, self 211 | ).preprocess_example(example, mode, hparams) 212 | 213 | def eval_metrics(self): 214 | defaults = super(SpeechRecognitionProblem, self).eval_metrics() 215 | return defaults + [ 216 | metrics.Metrics.EDIT_DISTANCE, 217 | metrics.Metrics.WORD_ERROR_RATE 218 | ] 219 | -------------------------------------------------------------------------------- /loss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kyubyong/specAugment/a59119d7e6fa9649961a0c57852c08f320d767cc/loss.png -------------------------------------------------------------------------------- /no_WER.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kyubyong/specAugment/a59119d7e6fa9649961a0c57852c08f320d767cc/no_WER.png -------------------------------------------------------------------------------- /spec_WER.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kyubyong/specAugment/a59119d7e6fa9649961a0c57852c08f320d767cc/spec_WER.png --------------------------------------------------------------------------------