<jupyter_start><jupyter_text>Speech recognition Simple sppeech recognition system can be implemented using DTW + MFCC.<jupyter_code>%matplotlib inline

import os
import glob
import librosa
import numpy as np<jupyter_output><empty_output><jupyter_text>We will use the [data-speech-commands database](https://storage.cloud.google.com/download.tensorflow.org/data/speech_commands_v0.02.tar.gz) composed of 105,000 WAVE audio files of people saying thirty different words. We will use only a subset of this database.We assume that you have previously downloaded and extracted the database. You need to specify the path to the folder where you extracted it.<jupyter_code>DATABASE_PATH = '/Users/pierrerouanet/Downloads/data-speech_commands_v0.02'
labels = {'cat', 'dog', 'house', 'happy', 'zero'}
labels
# We will use only N occurences per word
N = 25<jupyter_output><empty_output><jupyter_text>Precompute all MFCCs<jupyter_code>mfccs = []
true_labels = []

for l in labels:
    sounds = glob.glob(os.path.join(DATABASE_PATH, l, '*.wav'))
    np.random.shuffle(sounds)
    sounds = sounds[:N]
    
    for s in sounds:
        y, sr = librosa.load(s)
        mfcc = librosa.feature.mfcc(y, sr, n_mfcc=13)
        mfccs.append(mfcc.T)
        true_labels.append(l)
        
mfccs = np.array(mfccs)
true_labels = np.array(true_labels)<jupyter_output><empty_output><jupyter_text>Prepare train/val dataset<jupyter_code>val_percent = 0.2
n_val = int(val_percent * len(true_labels))

I = np.random.permutation(len(true_labels))
I_val, I_train = I[:n_val], I[n_val:]<jupyter_output><empty_output><jupyter_text>Leave P Out Cross Validation<jupyter_code>from dtw import dtw


def cross_validation(train_indices, val_indices):
    score = 0.0

    for i in val_indices:
        x = mfccs[i]

        dmin, jmin = np.inf, -1
        for j in train_indices:
            y = mfccs[j]
            d, _, _, _ = dtw(x, y, dist=lambda x, y: np.linalg.norm(x - y, ord=1))

            if d < dmin:
                dmin = d
                jmin = j

        score += 1.0 if (true_labels[i] == true_labels[jmin]) else 0.0
        
    return score / len(val_indices)
rec_rate = cross_validation(I_train, I_val)
print('Recognition rate {}%'.format(100. * rec_rate))<jupyter_output>Recognition rate 52.0%
{'fraction_non_alphanumeric': 0.1111111111111111, 'fraction_numerical': 0.014053579270970576, 'mean_word_length': 3.735966735966736, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 20, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '258769', 'license': 'MIT', 'n_tokens_mistral': 845, 'n_tokens_neox': 807, 'n_words': 196, 'path': 'KWS/examples/speech-recognition.ipynb', 'repo_name': 'xrick/DTW-Tutorial', 'size': '2277'}