首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

课后练习 之 第五课——Week3

  • 25-02-17 00:02
  • 3790
  • 9060
blog.csdn.net

目录

0 环境配置

1 前言

2 神经机器翻译

2.1 导包

2.2 将人类可读的日期翻译成机器可读的日期

数据集

2.3 使用注意力机制的神经机器翻译

注意机制

one_step_attention

modelf

编译模型

定义输入和输出,然后训练模型

2.4 可视化注意力

从网络中获取注意力权重 

3 触发词检测

3.0 导包

3.1 数据合成:创建语言数据集

聆听数据

从录音到频谱图

生成单个训练样例 

全部训练集

开发(测试)集

3.2 触发词检测模型

导包

构建模型

训练模型

测试模型

3.3 做预测

插入一个报时以确认“activate”的出现

开发示例测试

3.4 试试你自己的例子!


0 环境配置

如果你在开始本节前遇到了环境配置方面的一些问题,欢迎阅读我之前写的一篇很详细文章:

⭐⭐[ pytorch+tensorflow ]⭐⭐配置两大框架下的GPU训练环境

1 前言

本文为2021吴恩达学习笔记deeplearning.ai《深度学习专项课程》篇——“第五课——Week3”章节的课后练习,完整内容参见:

深度学习入门指南——2021吴恩达学习笔记deeplearning.ai《深度学习专项课程》篇

2 神经机器翻译

欢迎你们完成本周的第一个编程作业!

  1. 你将建立一个神经机器翻译(NMT)模型,将人类可读的日期(“25 of June, 2009”)翻译成机器可读的日期(“2009-06-25”)。
  2. 你将使用注意力模型,这是最复杂的序列到序列模型之一。

2.1 导包

  1. from tensorflow.keras.layers import Bidirectional, Concatenate, Permute, Dot, Input, LSTM, Multiply
  2. from tensorflow.keras.layers import RepeatVector, Dense, Activation, Lambda
  3. from tensorflow.keras.optimizers import Adam
  4. from tensorflow.keras.utils import to_categorical
  5. from tensorflow.keras.models import load_model, Model
  6. import tensorflow.keras.backend as K
  7. import tensorflow as tf
  8. import numpy as np
  9. from faker import Faker
  10. import random
  11. from tqdm import tqdm
  12. from babel.dates import format_date
  13. from nmt_utils import *
  14. import matplotlib.pyplot as plt
  15. # 解决模型加载显存占满的问题
  16. physical_gpus = tf.config.list_physical_devices("GPU")
  17. tf.config.experimental.set_memory_growth(physical_gpus[0], True)
  18. logical_gpus = tf.config.list_logical_devices("GPU")
  19. %matplotlib inline

2.2 将人类可读的日期翻译成机器可读的日期

  1. * 您将在这里建立的模型可用于从一种语言翻译到另一种语言,例如从英语翻译到印地语。
  2. * 然而,语言翻译需要大量的数据集,通常需要在gpu上进行数天的训练。
  3. * 为了给你一个在不使用海量数据集的情况下实验这些模型的地方,我们将执行一个更简单的“日期翻译”任务。
  4. * 网络将输入以各种可能的格式书写的日期(例如:“1958年8月29日”、“1968年3月30日”、“1987年6月24日”*)
  5. * 网络将它们转换成标准化的、机器可读的日期(例如:“1958-08-29”、“1968-03-30”、“1987-06-24”*)。
  6. * 我们将让网络学习以常见的机器可读格式YYYY-MM-DD输出日期。
数据集

我们将在10000个人类可读日期和它们等效的、标准化的、机器可读日期的数据集上训练模型。让我们运行以下单元格来加载数据集并打印一些示例。

  1. m = 10000
  2. dataset, human_vocab, machine_vocab, inv_machine_vocab = load_dataset(m)
dataset[:10]

[('9 may 1998', '1998-05-09'),
 ('10.11.19', '2019-11-10'),
 ('9/10/70', '1970-09-10'),
 ('monday august 19 2024', '2024-08-19'),
 ('saturday april 28 1990', '1990-04-28'),
 ('thursday january 26 1995', '1995-01-26'),
 ('monday march 7 1983', '1983-03-07'),
 ('22 may 1988', '1988-05-22'),
 ('8 jul 2008', '2008-07-08'),
 ('wednesday september 8 1999', '1999-09-08')]

你加载了:

  1. - ' dataset ':一个元组列表(人类可读日期,机器可读日期)。
  2. - ' human_vocab ':一个python字典,将人类可读日期中使用的所有字符映射到整数值索引。
  3. - ' machine_vocab ':一个python字典,将机器可读日期中使用的所有字符映射到整数值索引。
  4. - **注**:这些指标不一定与“human_vocab”一致。
  5. - ' inv_machine_vocab ': ‘ machine_vocab ’的逆字典,从索引映射回字符。

让我们对数据进行预处理,并将原始文本数据映射到索引值。

  1. - 我们将设置Tx=30
  2. - 我们假设Tx是人类可读日期的最大长度。
  3. - 如果我们得到一个更长的输入,我们将不得不截断它。
  4. - 我们将设置Ty=10
  5. - “YYYY-MM-DD”长度为10个字符。
human_vocab
  1. {' ': 0,
  2. '.': 1,
  3. '/': 2,
  4. '0': 3,
  5. '1': 4,
  6. '2': 5,
  7. '3': 6,
  8. '4': 7,
  9. '5': 8,
  10. '6': 9,
  11. '7': 10,
  12. '8': 11,
  13. '9': 12,
  14. 'a': 13,
  15. 'b': 14,
  16. 'c': 15,
  17. 'd': 16,
  18. 'e': 17,
  19. 'f': 18,
  20. 'g': 19,
  21. 'h': 20,
  22. 'i': 21,
  23. 'j': 22,
  24. 'l': 23,
  25. 'm': 24,
  26. 'n': 25,
  27. 'o': 26,
  28. 'p': 27,
  29. 'r': 28,
  30. 's': 29,
  31. 't': 30,
  32. 'u': 31,
  33. 'v': 32,
  34. 'w': 33,
  35. 'y': 34,
  36. '': 35,
  37. '': 36}
tf.config.list_physical_devices()

[PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU'),
 PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')] 

  1. Tx = 30
  2. Ty = 10
  3. X, Y, Xoh, Yoh = preprocess_data(dataset, human_vocab, machine_vocab, Tx, Ty)
  4. print("X.shape:", X.shape)
  5. print("Y.shape:", Y.shape)
  6. print("Xoh.shape:", Xoh.shape)
  7. print("Yoh.shape:", Yoh.shape)

X.shape: (10000, 30)
Y.shape: (10000, 10)
Xoh.shape: (10000, 30, 37)
Yoh.shape: (10000, 10, 11)

你现在有:

1)' X ':训练集中人类可读日期的处理版本。

  • - X中的每个字符都被使用‘ human_vocab ’映射到该字符的索引(整数)替换。
  • - 使用特殊字符(< pad >)填充每个日期以确保$T_x$的长度。
  • - “X.shape = (m, Tx) ',其中m为批处理中训练样例的个数。

2)' Y ':训练集中机器可读日期的处理版本。

  • - 每个字符被替换为索引(整数),它被映射到‘ machine_vocab ’。
  • - “Y.shape = (m, Ty) '。

3) ‘ Xoh ’: ‘ X ’的一个独热编码版本

  • - “X”中的每个索引都转换为one-hot表示(如果索引为2,则one-hot版本将索引位置2设置为1,其余位置为0)。
  • - “Xoh.shape = (m, Tx, len(human_vocab)) '

4)“Yoh”:“Y”的一个独热编码版本

  • - “Y”中的每个索引都转换为1 -hot表示。
  • - “Toh.shape = (m, Ty, len(machine_vocab)) '。
  • - ‘ len(machine_vocab) = 11 ‘,因为有10个数字(0到9)和’ - ’符号。

* 让我们再看一些预处理训练样本的例子。

* 请随意使用下面单元格中的“index”来导航数据集,并查看源/目标日期是如何预处理的。

  1. index = 0
  2. print("Source date:", dataset[index][0])
  3. print("Target date:", dataset[index][1])
  4. print()
  5. print("Source after preprocessing (indices):", X[index])
  6. print("Target after preprocessing (indices):", Y[index])
  7. print()
  8. print("Source after preprocessing (one-hot):", Xoh[index])
  9. print("Target after preprocessing (one-hot):", Yoh[index])

Source date: 9 may 1998
Target date: 1998-05-09

Source after preprocessing (indices): [12  0 24 13 34  0  4 12 12 11 36 36 36 36 36 36 36 36 36 36 36 36 36 36
 36 36 36 36 36 36]
Target after preprocessing (indices): [ 2 10 10  9  0  1  6  0  1 10]

Source after preprocessing (one-hot): [[0. 0. 0. ... 0. 0. 0.]
 [1. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 ...
 [0. 0. 0. ... 0. 0. 1.]
 [0. 0. 0. ... 0. 0. 1.]
 [0. 0. 0. ... 0. 0. 1.]]
Target after preprocessing (one-hot): [[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]] 

2.3 使用注意力机制的神经机器翻译

* 如果你必须把一本书的一段话从法语翻译成英语,你不会读整个段落,然后合上书翻译。

* 即使在翻译过程中,你也会反复阅读和关注法语段落中与你所写的英语部分相对应的部分。

* 注意机制告诉神经机器翻译模型在任何步骤中应该注意的地方。

注意机制

Neural machine translation with attention

以下是你可能会注意到的模型的一些属性:

1)注意机制两侧的前注意和后注意lstm

2)LSTM同时具有隐藏状态和单元状态

3)每个时间步并不使用前一个时间步的预测

  • * 与课程前面的文本生成示例不同,在这个模型中,时间$t$的后关注LSTM不将前一个时间步长的预测$y^{\langle t-1 \rangle}$作为输入。
  • * 后注意LSTM在时刻‘t’只接受隐藏状态$s^{\langle t\rangle}$和单元格状态$c^{\langle t\rangle}$作为输入。
  • * 我们这样设计模型是因为与语言生成(相邻字符高度相关)不同,在YYYY-MM-DD日期中,前一个字符和下一个字符之间没有那么强的依赖性。
one_step_attention
  1. # Defined shared layers as global variables
  2. repeator = RepeatVector(Tx)
  3. concatenator = Concatenate(axis=-1)
  4. densor1 = Dense(10, activation = "tanh")
  5. densor2 = Dense(1, activation = "relu")
  6. activator = Activation(softmax, name='attention_weights') # We are using a custom softmax(axis = 1) loaded in this notebook
  7. dotor = Dot(axes = 1)
  1. # UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
  2. # GRADED FUNCTION: one_step_attention
  3. def one_step_attention(a, s_prev):
  4. # Use repeator to repeat s_prev to be of shape (m, Tx, n_s) so that you can concatenate it with all hidden states "a" (≈ 1 line)
  5. s_prev = repeator(s_prev)
  6. # Use concatenator to concatenate a and s_prev on the last axis (≈ 1 line)
  7. # For grading purposes, please list 'a' first and 's_prev' second, in this order.
  8. concat = concatenator([a,s_prev])
  9. # Use densor1 to propagate concat through a small fully-connected neural network to compute the "intermediate energies" variable e. (≈1 lines)
  10. e = densor1(concat)
  11. # Use densor2 to propagate e through a small fully-connected neural network to compute the "energies" variable energies. (≈1 lines)
  12. energies = densor2(e)
  13. # Use "activator" on "energies" to compute the attention weights "alphas" (≈ 1 line)
  14. alphas = activator(energies)
  15. # Use dotor together with "alphas" and "a", in this order, to compute the context vector to be given to the next (post-attention) LSTM-cell (≈ 1 line)
  16. context = dotor([alphas,a])
  17. return context
  1. from tensorflow.python import framework as myframework
  2. # UNIT TEST
  3. def one_step_attention_test(target):
  4. m = 10
  5. Tx = 30
  6. n_a = 32
  7. n_s = 64
  8. #np.random.seed(10)
  9. a = np.random.uniform(1, 0, (m, Tx, 2 * n_a)).astype(np.float32)
  10. s_prev =np.random.uniform(1, 0, (m, n_s)).astype(np.float32) * 1
  11. context = target(a, s_prev)
  12. assert type(context) == myframework.ops.EagerTensor, "Unexpected type. It should be a Tensor"
  13. assert tuple(context.shape) == (m, 1, n_s), "Unexpected output shape"
  14. assert np.all(context.numpy() > 0), "All output values must be > 0 in this example"
  15. assert np.all(context.numpy() < 1), "All output values must be < 1 in this example"
  16. #assert np.allclose(context[0][0][0:5].numpy(), [0.50877404, 0.57160693, 0.45448175, 0.50074816, 0.53651875]), "Unexpected values in the result"
  17. print("\033[92mAll tests passed!")
  18. one_step_attention_test(one_step_attention)

All tests passed!

modelf
  1. n_a = 32 # number of units for the pre-attention, bi-directional LSTM's hidden state 'a'
  2. n_s = 64 # number of units for the post-attention LSTM's hidden state "s"
  3. # Please note, this is the post attention LSTM cell.
  4. post_activation_LSTM_cell = LSTM(n_s, return_state = True) # Please do not modify this global variable.
  5. output_layer = Dense(len(machine_vocab), activation=softmax)
  1. # UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
  2. # GRADED FUNCTION: model
  3. def modelf(Tx, Ty, n_a, n_s, human_vocab_size, machine_vocab_size):
  4. # Define the inputs of your model with a shape (Tx,)
  5. # Define s0 (initial hidden state) and c0 (initial cell state)
  6. # for the decoder LSTM with shape (n_s,)
  7. X = Input(shape=(Tx, human_vocab_size))
  8. s0 = Input(shape=(n_s,), name='s0')
  9. c0 = Input(shape=(n_s,), name='c0')
  10. s = s0
  11. c = c0
  12. # Initialize empty list of outputs
  13. outputs = []
  14. # Step 1: Define your pre-attention Bi-LSTM. (≈ 1 line)
  15. a = Bidirectional(LSTM(n_a, return_sequences=True))(X)
  16. # Step 2: Iterate for Ty steps
  17. for t in range(Ty):
  18. # Step 2.A: Perform one step of the attention mechanism to get back the context vector at step t (≈ 1 line)
  19. context = one_step_attention(a, s)
  20. # Step 2.B: Apply the post-attention LSTM cell to the "context" vector.
  21. # Don't forget to pass: initial_state = [hidden state, cell state] (≈ 1 line)
  22. s, _, c = post_activation_LSTM_cell(context,initial_state=[s, c])
  23. # Step 2.C: Apply Dense layer to the hidden state output of the post-attention LSTM (≈ 1 line)
  24. out = output_layer(s)
  25. # Step 2.D: Append "out" to the "outputs" list (≈ 1 line)
  26. outputs.append(out)
  27. # Step 3: Create model instance taking three inputs and returning the list of outputs. (≈ 1 line)
  28. model = Model(inputs=[X, s0, c0],outputs=outputs)
  29. return model
  1. # UNIT TEST
  2. from test_utils import *
  3. def modelf_test(target):
  4. m = 10
  5. Tx = 30
  6. n_a = 32
  7. n_s = 64
  8. len_human_vocab = 37
  9. len_machine_vocab = 11
  10. model = target(Tx, Ty, n_a, n_s, len_human_vocab, len_machine_vocab)
  11. print(summary(model))
  12. expected_summary = [['InputLayer', [(None, 30, 37)], 0],
  13. ['InputLayer', [(None, 64)], 0],
  14. ['Bidirectional', (None, 30, 64), 17920],
  15. ['RepeatVector', (None, 30, 64), 0, 30],
  16. ['Concatenate', (None, 30, 128), 0],
  17. ['Dense', (None, 30, 10), 1290, 'tanh'],
  18. ['Dense', (None, 30, 1), 11, 'relu'],
  19. ['Activation', (None, 30, 1), 0],
  20. ['Dot', (None, 1, 64), 0],
  21. ['InputLayer', [(None, 64)], 0],
  22. ['LSTM',[(None, 64), (None, 64), (None, 64)], 33024,[(None, 1, 64), (None, 64), (None, 64)],'tanh'],
  23. ['Dense', (None, 11), 715, 'softmax']]
  24. comparator(summary(model), expected_summary)
  25. modelf_test(modelf)

[['InputLayer', [(None, 30, 37)], 0], ['InputLayer', [(None, 64)], 0], ['Bidirectional', (None, 30, 64), 17920], ['RepeatVector', (None, 30, 64), 0, 30], ['Concatenate', (None, 30, 128), 0], ['Dense', (None, 30, 10), 1290, 'tanh'], ['Dense', (None, 30, 1), 11, 'relu'], ['Activation', (None, 30, 1), 0], ['Dot', (None, 1, 64), 0], ['InputLayer', [(None, 64)], 0], ['LSTM', [(None, 64), (None, 64), (None, 64)], 33024, [(None, 1, 64), (None, 64), (None, 64)], 'tanh'], ['Dense', (None, 11), 715, 'softmax']]
All tests passed!

model = modelf(Tx, Ty, n_a, n_s, len(human_vocab), len(machine_vocab))

 让我们获取模型的摘要,以检查它是否与预期输出匹配。

model.summary()
  1. Model: "model_1"
  2. __________________________________________________________________________________________________
  3. Layer (type) Output Shape Param # Connected to
  4. ==================================================================================================
  5. input_2 (InputLayer) [(None, 30, 37)] 0
  6. __________________________________________________________________________________________________
  7. s0 (InputLayer) [(None, 64)] 0
  8. __________________________________________________________________________________________________
  9. bidirectional_1 (Bidirectional) (None, 30, 64) 17920 input_2[0][0]
  10. __________________________________________________________________________________________________
  11. repeat_vector (RepeatVector) (None, 30, 64) 0 s0[0][0]
  12. lstm[10][0]
  13. lstm[11][0]
  14. lstm[12][0]
  15. lstm[13][0]
  16. lstm[14][0]
  17. lstm[15][0]
  18. lstm[16][0]
  19. lstm[17][0]
  20. lstm[18][0]
  21. __________________________________________________________________________________________________
  22. concatenate (Concatenate) (None, 30, 128) 0 bidirectional_1[0][0]
  23. repeat_vector[10][0]
  24. bidirectional_1[0][0]
  25. repeat_vector[11][0]
  26. bidirectional_1[0][0]
  27. repeat_vector[12][0]
  28. bidirectional_1[0][0]
  29. repeat_vector[13][0]
  30. bidirectional_1[0][0]
  31. repeat_vector[14][0]
  32. bidirectional_1[0][0]
  33. repeat_vector[15][0]
  34. bidirectional_1[0][0]
  35. repeat_vector[16][0]
  36. bidirectional_1[0][0]
  37. repeat_vector[17][0]
  38. bidirectional_1[0][0]
  39. repeat_vector[18][0]
  40. bidirectional_1[0][0]
  41. repeat_vector[19][0]
  42. __________________________________________________________________________________________________
  43. dense (Dense) (None, 30, 10) 1290 concatenate[10][0]
  44. concatenate[11][0]
  45. concatenate[12][0]
  46. concatenate[13][0]
  47. concatenate[14][0]
  48. concatenate[15][0]
  49. concatenate[16][0]
  50. concatenate[17][0]
  51. concatenate[18][0]
  52. concatenate[19][0]
  53. __________________________________________________________________________________________________
  54. dense_1 (Dense) (None, 30, 1) 11 dense[10][0]
  55. dense[11][0]
  56. dense[12][0]
  57. dense[13][0]
  58. dense[14][0]
  59. dense[15][0]
  60. dense[16][0]
  61. dense[17][0]
  62. dense[18][0]
  63. dense[19][0]
  64. __________________________________________________________________________________________________
  65. attention_weights (Activation) (None, 30, 1) 0 dense_1[10][0]
  66. dense_1[11][0]
  67. dense_1[12][0]
  68. dense_1[13][0]
  69. dense_1[14][0]
  70. dense_1[15][0]
  71. dense_1[16][0]
  72. dense_1[17][0]
  73. dense_1[18][0]
  74. dense_1[19][0]
  75. __________________________________________________________________________________________________
  76. dot (Dot) (None, 1, 64) 0 attention_weights[10][0]
  77. bidirectional_1[0][0]
  78. attention_weights[11][0]
  79. bidirectional_1[0][0]
  80. attention_weights[12][0]
  81. bidirectional_1[0][0]
  82. attention_weights[13][0]
  83. bidirectional_1[0][0]
  84. attention_weights[14][0]
  85. bidirectional_1[0][0]
  86. attention_weights[15][0]
  87. bidirectional_1[0][0]
  88. attention_weights[16][0]
  89. bidirectional_1[0][0]
  90. attention_weights[17][0]
  91. bidirectional_1[0][0]
  92. attention_weights[18][0]
  93. bidirectional_1[0][0]
  94. attention_weights[19][0]
  95. bidirectional_1[0][0]
  96. __________________________________________________________________________________________________
  97. c0 (InputLayer) [(None, 64)] 0
  98. __________________________________________________________________________________________________
  99. lstm (LSTM) [(None, 64), (None, 33024 dot[10][0]
  100. s0[0][0]
  101. c0[0][0]
  102. dot[11][0]
  103. lstm[10][0]
  104. lstm[10][2]
  105. dot[12][0]
  106. lstm[11][0]
  107. lstm[11][2]
  108. dot[13][0]
  109. lstm[12][0]
  110. lstm[12][2]
  111. dot[14][0]
  112. lstm[13][0]
  113. lstm[13][2]
  114. dot[15][0]
  115. lstm[14][0]
  116. lstm[14][2]
  117. dot[16][0]
  118. lstm[15][0]
  119. lstm[15][2]
  120. dot[17][0]
  121. lstm[16][0]
  122. lstm[16][2]
  123. dot[18][0]
  124. lstm[17][0]
  125. lstm[17][2]
  126. dot[19][0]
  127. lstm[18][0]
  128. lstm[18][2]
  129. __________________________________________________________________________________________________
  130. dense_2 (Dense) (None, 11) 715 lstm[10][0]
  131. lstm[11][0]
  132. lstm[12][0]
  133. lstm[13][0]
  134. lstm[14][0]
  135. lstm[15][0]
  136. lstm[16][0]
  137. lstm[17][0]
  138. lstm[18][0]
  139. lstm[19][0]
  140. ==================================================================================================
  141. Total params: 52,960
  142. Trainable params: 52,960
  143. Non-trainable params: 0
  144. __________________________________________________________________________________________________
编译模型
  1. opt = Adam(lr=0.005, beta_1=0.9, beta_2=0.999, decay=0.01)
  2. model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
  1. # UNIT TESTS
  2. assert opt.lr == 0.005, "Set the lr parameter to 0.005"
  3. assert opt.beta_1 == 0.9, "Set the beta_1 parameter to 0.9"
  4. assert opt.beta_2 == 0.999, "Set the beta_2 parameter to 0.999"
  5. assert opt.decay == 0.01, "Set the decay parameter to 0.01"
  6. assert model.loss == "categorical_crossentropy", "Wrong loss. Use 'categorical_crossentropy'"
  7. assert model.optimizer == opt, "Use the optimizer that you have instantiated"
  8. assert model.compiled_metrics._user_metrics[0] == 'accuracy', "set metrics to ['accuracy']"
  9. print("\033[92mAll tests passed!")

All tests passed!

定义输入和输出,然后训练模型
  1. s0 = np.zeros((m, n_s))
  2. c0 = np.zeros((m, n_s))
  3. outputs = list(Yoh.swapaxes(0,1))
model.fit([Xoh, s0, c0], outputs, epochs=1, batch_size=100)

100/100 [==============================] - 20s 49ms/step - loss: 19.9715 - dense_2_loss: 1.8134 - dense_2_1_loss: 1.6386 - dense_2_2_loss: 2.1659 - dense_2_3_loss: 2.7257 - dense_2_4_loss: 1.2834 - dense_2_5_loss: 1.6420 - dense_2_6_loss: 2.7552 - dense_2_7_loss: 1.3648 - dense_2_8_loss: 1.8986 - dense_2_9_loss: 2.6840 - dense_2_accuracy: 0.1713 - dense_2_1_accuracy: 0.4065 - dense_2_2_accuracy: 0.1710 - dense_2_3_accuracy: 0.0674 - dense_2_4_accuracy: 0.8328 - dense_2_5_accuracy: 0.1359 - dense_2_6_accuracy: 0.0128 - dense_2_7_accuracy: 0.8703 - dense_2_8_accuracy: 0.1518 - dense_2_9_accuracy: 0.0724

在训练时,您可以看到输出的10个位置中的每个位置的损失和准确性。下表给出了一个例子,说明如果批处理有2个例子,准确度可能是多少:

‘ dense_2_acc_8: 0.89 ’意味着您在当前批数据中正确预测输出的第7个字符的概率为89%.

我们运行这个模型的时间更长,并且保存了权重。运行下一个单元格来加载权重。(通过训练模型几分钟,您应该能够获得类似精度的模型,但加载我们的模型将节省您的时间。)

model.load_weights('models/model.h5')

现在可以在新的示例上看到结果。

  1. EXAMPLES = ['3 May 1979', '5 April 09', '21th of August 2016', 'Tue 10 Jul 2007', 'Saturday May 9 2018', 'March 3 2001', 'March 3rd 2001', '1 March 2001']
  2. s00 = np.zeros((1, n_s))
  3. c00 = np.zeros((1, n_s))
  4. for example in EXAMPLES:
  5. source = string_to_int(example, Tx, human_vocab)
  6. #print(source)
  7. source = np.array(list(map(lambda x: to_categorical(x, num_classes=len(human_vocab)), source))).swapaxes(0,1)
  8. source = np.swapaxes(source, 0, 1)
  9. source = np.expand_dims(source, axis=0)
  10. prediction = model.predict([source, s00, c00])
  11. prediction = np.argmax(prediction, axis = -1)
  12. output = [inv_machine_vocab[int(i)] for i in prediction]
  13. print("source:", example)
  14. print("output:", ''.join(output),"\n")

source: 3 May 1979
output: 1979-05-33 

source: 5 April 09
output: 2009-04-05 

source: 21th of August 2016
output: 2016-08-20 

source: Tue 10 Jul 2007
output: 2007-07-10 

source: Saturday May 9 2018
output: 2018-05-09 

source: March 3 2001
output: 2001-03-03 

source: March 3rd 2001
output: 2001-03-03 

source: 1 March 2001
output: 2001-03-01 

  1. def translate_date(sentence):
  2. source = string_to_int(sentence, Tx, human_vocab)
  3. source = np.array(list(map(lambda x: to_categorical(x, num_classes=len(human_vocab)), source))).swapaxes(0,1)
  4. source = np.swapaxes(source, 0, 1)
  5. source = np.expand_dims(source, axis=0)
  6. prediction = model.predict([source, s00, c00])
  7. prediction = np.argmax(prediction, axis = -1)
  8. output = [inv_machine_vocab[int(i)] for i in prediction]
  9. print("source:", sentence)
  10. print("output:", ''.join(output),"\n")
  11. example = "4th of july 2001"
  12. translate_date(example)

source: 4th of july 2001
output: 2001-07-04 

您还可以更改这些示例,以便用您自己的示例进行测试。下一部分会让你更好地理解注意力机制的作用。当生成一个特定的输出字符时,网络关注的是输入的哪个部分。 

2.4 可视化注意力

由于问题的输出长度固定为10,因此也可以使用10个不同的softmax单元来生成输出的10个字符来执行此任务。但是注意力模型的一个优点是,输出的每个部分(比如月份)都知道它只需要依赖于输入的一小部分(输入中给出月份的字符)。我们可以看到输出的每一部分在看输入的哪一部分。

考虑将"Saturday 9 May 2018"翻译为“2018-05-09”的任务。如果我们把计算$\alpha^{\langle t, t' \rangle}$ 我们可以得到:

注意输出是如何忽略输入的“Saturday”部分的。所有的输出时间步都不太关注这部分输入。我们还看到9被翻译成了09,May被正确地翻译成了05,输出注意到了输入中需要翻译的部分。年主要要求它注意输入的“18”,以便生成“2018”。" 

从网络中获取注意力权重 

现在让我们可视化你的网络中的注意力值。我们将通过网络传播一个示例,然后可视化$\alpha^{\langle t, t' \rangle}$的值。

为了找出注意力值的位置,让我们从打印模型摘要开始。

model.summary()
  1. Model: "model_1"
  2. __________________________________________________________________________________________________
  3. Layer (type) Output Shape Param # Connected to
  4. ==================================================================================================
  5. input_2 (InputLayer) [(None, 30, 37)] 0
  6. __________________________________________________________________________________________________
  7. s0 (InputLayer) [(None, 64)] 0
  8. __________________________________________________________________________________________________
  9. bidirectional_1 (Bidirectional) (None, 30, 64) 17920 input_2[0][0]
  10. __________________________________________________________________________________________________
  11. repeat_vector (RepeatVector) (None, 30, 64) 0 s0[0][0]
  12. lstm[10][0]
  13. lstm[11][0]
  14. lstm[12][0]
  15. lstm[13][0]
  16. lstm[14][0]
  17. lstm[15][0]
  18. lstm[16][0]
  19. lstm[17][0]
  20. lstm[18][0]
  21. __________________________________________________________________________________________________
  22. concatenate (Concatenate) (None, 30, 128) 0 bidirectional_1[0][0]
  23. repeat_vector[10][0]
  24. bidirectional_1[0][0]
  25. repeat_vector[11][0]
  26. bidirectional_1[0][0]
  27. repeat_vector[12][0]
  28. bidirectional_1[0][0]
  29. repeat_vector[13][0]
  30. bidirectional_1[0][0]
  31. repeat_vector[14][0]
  32. bidirectional_1[0][0]
  33. repeat_vector[15][0]
  34. bidirectional_1[0][0]
  35. repeat_vector[16][0]
  36. bidirectional_1[0][0]
  37. repeat_vector[17][0]
  38. bidirectional_1[0][0]
  39. repeat_vector[18][0]
  40. bidirectional_1[0][0]
  41. repeat_vector[19][0]
  42. __________________________________________________________________________________________________
  43. dense (Dense) (None, 30, 10) 1290 concatenate[10][0]
  44. concatenate[11][0]
  45. concatenate[12][0]
  46. concatenate[13][0]
  47. concatenate[14][0]
  48. concatenate[15][0]
  49. concatenate[16][0]
  50. concatenate[17][0]
  51. concatenate[18][0]
  52. concatenate[19][0]
  53. __________________________________________________________________________________________________
  54. dense_1 (Dense) (None, 30, 1) 11 dense[10][0]
  55. dense[11][0]
  56. dense[12][0]
  57. dense[13][0]
  58. dense[14][0]
  59. dense[15][0]
  60. dense[16][0]
  61. dense[17][0]
  62. dense[18][0]
  63. dense[19][0]
  64. __________________________________________________________________________________________________
  65. attention_weights (Activation) (None, 30, 1) 0 dense_1[10][0]
  66. dense_1[11][0]
  67. dense_1[12][0]
  68. dense_1[13][0]
  69. dense_1[14][0]
  70. dense_1[15][0]
  71. dense_1[16][0]
  72. dense_1[17][0]
  73. dense_1[18][0]
  74. dense_1[19][0]
  75. __________________________________________________________________________________________________
  76. dot (Dot) (None, 1, 64) 0 attention_weights[10][0]
  77. bidirectional_1[0][0]
  78. attention_weights[11][0]
  79. bidirectional_1[0][0]
  80. attention_weights[12][0]
  81. bidirectional_1[0][0]
  82. attention_weights[13][0]
  83. bidirectional_1[0][0]
  84. attention_weights[14][0]
  85. bidirectional_1[0][0]
  86. attention_weights[15][0]
  87. bidirectional_1[0][0]
  88. attention_weights[16][0]
  89. bidirectional_1[0][0]
  90. attention_weights[17][0]
  91. bidirectional_1[0][0]
  92. attention_weights[18][0]
  93. bidirectional_1[0][0]
  94. attention_weights[19][0]
  95. bidirectional_1[0][0]
  96. __________________________________________________________________________________________________
  97. c0 (InputLayer) [(None, 64)] 0
  98. __________________________________________________________________________________________________
  99. lstm (LSTM) [(None, 64), (None, 33024 dot[10][0]
  100. s0[0][0]
  101. c0[0][0]
  102. dot[11][0]
  103. lstm[10][0]
  104. lstm[10][2]
  105. dot[12][0]
  106. lstm[11][0]
  107. lstm[11][2]
  108. dot[13][0]
  109. lstm[12][0]
  110. lstm[12][2]
  111. dot[14][0]
  112. lstm[13][0]
  113. lstm[13][2]
  114. dot[15][0]
  115. lstm[14][0]
  116. lstm[14][2]
  117. dot[16][0]
  118. lstm[15][0]
  119. lstm[15][2]
  120. dot[17][0]
  121. lstm[16][0]
  122. lstm[16][2]
  123. dot[18][0]
  124. lstm[17][0]
  125. lstm[17][2]
  126. dot[19][0]
  127. lstm[18][0]
  128. lstm[18][2]
  129. __________________________________________________________________________________________________
  130. dense_2 (Dense) (None, 11) 715 lstm[10][0]
  131. lstm[11][0]
  132. lstm[12][0]
  133. lstm[13][0]
  134. lstm[14][0]
  135. lstm[15][0]
  136. lstm[16][0]
  137. lstm[17][0]
  138. lstm[18][0]
  139. lstm[19][0]
  140. ==================================================================================================
  141. Total params: 52,960
  142. Trainable params: 52,960
  143. Non-trainable params: 0
  144. __________________________________________________________________________________________________

浏览上面‘ model.summary() ’的输出。你可以看到,名为 `attention_weights`的层在`alphas`计算每个时间步$t = 0, \ldots, T_y-1$之前,输出形状(m, 30,1)的‘ alpha ’。让我们从这一层得到注意力权重。

函数‘ attention_map() ’从模型中提取注意力值并绘制它们。

attention_map = plot_attention_map(model, human_vocab, inv_machine_vocab, "Tuesday 09 Oct 1993", num = 7, n_s = 64);

在生成的图上,您可以观察到预测输出的每个字符的注意权重值。检查这张图,并检查网络关注的地方是否对你有意义。

在日期翻译应用程序中,您将观察到大多数时间注意力有助于预测年份,而对预测日期或月份没有太大影响。

恭喜你!你的任务已经完成了

下面是你应该记住的:

  1. - 机器翻译模型可用于从一个序列映射到另一个序列。它们不仅适用于翻译人类语言(如法语->英语),也适用于日期格式翻译等任务。
  2. - 注意机制允许网络在产生输出的特定部分时专注于输入中最相关的部分。
  3. - 使用注意机制的网络可以从长度$T_x$的输入转换为长度$T_y$的输出,其中$T_x$和$T_y$可以不同。
  4. - 你可以可视化注意力权重$\alpha^{\langle t,t' \rangle}$,以查看网络在生成每个输出时关注的内容。

祝贺你完成了这个作业!现在,您可以实现一个注意力模型,并使用它来学习从一个序列到另一个序列的复杂映射。

3 触发词检测

欢迎来到第三周的第二个也是最后一个编程作业!

在本周的视频中,你学习了如何将深度学习应用于语音识别。在本作业中,您将构建一个语音数据集并实现触发词检测(有时也称为关键字检测或唤醒词检测)的算法。

  1. * 触发词检测是一项技术,允许亚马逊Alexa、b谷歌Home、苹果Siri和百度DuerOS等设备在听到某个单词时醒来。
  2. * 在这个练习中,我们的触发词是“activate”。每次听到你说“激活”,它就会发出“报时”的声音。
  3. * 在这项任务结束时,你将能够录制自己说话的片段,并让算法在检测到你说“激活”时触发铃声。
  4. * 完成这个任务后,也许你也可以扩展它在你的笔记本电脑上运行,这样每次你说“激活”,它就会启动你最喜欢的应用程序,或者打开你家里的网络连接灯,或者触发其他一些事件?

在本作业中,你将学习:

  1. - 构建一个语音识别项目
  2. - 合成和处理音频记录,以创建训练/开发数据集
  3. - 训练触发词检测模型并进行预测

让我们开始吧!

3.0 导包

  1. import numpy as np
  2. from pydub import AudioSegment
  3. import tensorflow as tf
  4. import random
  5. import sys
  6. import io
  7. import os
  8. import glob
  9. import IPython
  10. from td_utils import *
  11. # 解决模型加载显存占满的问题
  12. physical_gpus = tf.config.list_physical_devices("GPU")
  13. tf.config.experimental.set_memory_growth(physical_gpus[0], True)
  14. logical_gpus = tf.config.list_logical_devices("GPU")
  15. %matplotlib inline

3.1 数据合成:创建语言数据集

让我们首先为您的触发词检测算法构建一个数据集。

  1. * 理想情况下,语音数据集应该尽可能接近你想要运行它的应用程序。
  2. * 在这种情况下,你想在工作环境(图书馆,家里,办公室,开放空间…)中检测单词“activate”。
  3. * 因此,你需要在不同的背景声音中混合积极的词("activate")和消极的词(除了激活之外的随机词)来创建录音。让我们看看如何创建这样的数据集。
聆听数据
  • * 你的一个朋友正在帮助你完成这个项目,他们已经去了图书馆、咖啡馆、餐馆、家庭和办公室的所有区域,以记录背景噪音,以及人们说positive/negative的话的音频片段。这个数据集包括用各种口音说话的人。
  • * 在raw_data目录中,您可以找到积极词、消极词和背景噪声的原始音频文件的子集。您将使用这些音频文件合成一个数据集来训练模型。
  • * “activate”目录包含人们说“activate”这个词的积极例子。
  • * “negatives”目录包含否定的例子,人们说随机单词,而不是“activate”。
  • *每个音频记录有一个单词。
  • * “backgrounds”目录包含10秒的背景噪音剪辑在不同的环境。

运行下面的单元格来听一些例子。

IPython.display.Audio("./raw_data/activates/1.wav")

您将使用这三种类型的记录(positives/negatives/backgrounds)来创建标记的数据集。

从录音到频谱图

1)录音到底是什么?

  1. * 麦克风会记录气压随时间的微小变化,而你的耳朵也会将这些气压的微小变化感知为声音。
  2. * 你可以把录音想象成一长串数字,用来测量麦克风检测到的气压变化。
  3. * 我们将使用44100 Hz(或44100赫兹)的音频采样。
  4. * 这意味着麦克风每秒输出44100个数字。
  5. * 因此,一个10秒的音频片段由441,000个数字表示(= $10 \times 44,100$).

2)频谱图

  1. * 很难从音频的“原始”表示中判断是否说了单词“activate”。
  2. * 为了帮助你的序列模型更容易地学习检测触发词,我们将计算音频的频谱图。
  3. * 频谱图告诉我们在任何时刻音频片段中存在多少不同的频率。
  4. * 如果你上过信号处理或傅里叶变换的高级课程:
  5. * 频谱图是通过在原始音频信号上滑动窗口来计算的,并使用傅里叶变换计算每个窗口中最活跃的频率。
  6. *  如果你不明白前面的句子,不要担心。让我们来看一个例子。
x = graph_spectrogram("audio_examples/example_train.wav")

上面的图表表示每个频率(y轴)在多个时间步长(x轴)上的活跃程度。

录音的频谱图
  • * 频谱图中的颜色表示在不同时间点音频中不同频率存在的程度(大声)。
  • * 绿色表示某个频率更活跃或在音频片段中更存在(更大声)。
  • * 蓝色方块表示较低的活跃频率。
  • * 输出谱图的尺寸取决于谱图软件的超参数和输入的长度。
  • * 在本笔记本中,我们将使用10秒音频剪辑作为我们训练示例的“标准长度”。
  • * 频谱图的时间步长为5511。
  • * 稍后您将看到,频谱图将是网络的输入$x$,因此$T_x = 5511$。
  1. _, data = wavfile.read("audio_examples/example_train.wav")
  2. print("Time steps in audio recording before spectrogram", data[:,0].shape)
  3. print("Time steps in input after spectrogram", x.shape)

Time steps in audio recording before spectrogram (441000,)
Time steps in input after spectrogram (101, 5511) 

现在,你可以定义:

  1. Tx = 5511 # 从谱图输入到模型的时间步长数
  2. n_freq = 101 # 在频谱图的每个时间步输入到模型的频率数

3)划分时间间隔

  • 注意,我们可以用不同的单位(步)来划分10秒的时间间隔。
  • * 原始音频将10秒分成441,000个单位。
  • * 谱图将10秒分成5511个单位。
  • * $T_x = 5511$
  • * 您将使用Python模块‘ pydub ’来合成音频,它将10秒分成10,000个单元。
  • * 我们型号的输出将把10秒分成1375个单位。
  • * $T_y = 1375$
  • * 对于1375个时间步骤中的每一个,该模型预测某人最近是否说出了触发词“activate”。
  • * 所有这些都是超参数,可以更改(441000除外,这是麦克风的功能)。
  • * 我们选择的值在语音系统使用的标准范围内。
Ty = 1375 # 我们模型输出的时间步数

综合数据的好处

* 由于语音数据很难获取和标记,因此您将使用positives/negatives/backgrounds的音频剪辑来合成您的训练数据。

* 当有随机“positives”在时记录大量的10秒音频剪辑是相当慢的。

* 相反,更容易记录大量的positive和negative的单词,并记录background噪音(或从免费的在线资源下载背景噪音)。

合成音频剪辑的过程

* 要综合单个训练示例,您将:

- 选择一个随机的10秒背景音频剪辑

- 随机插入0-4音频剪辑“activate”到这个10秒的剪辑

- 随机插入0-2个"negative"的音频剪辑到这个10秒的剪辑

* 因为你已经将单词“activate”合成到背景剪辑中,你知道在10秒剪辑中“activate”出现的确切时间。

稍后您将看到,这也使得生成标签$y^{\langle t \rangle}$变得更加容易。

Pydub

* 您将使用pydub包来操作音频。

* Pydub将原始音频文件转换为Pydub数据结构列表。

* 不要担心数据结构的细节。

* Pydub使用1ms作为离散间隔(1ms = 1毫秒= 1/1000秒)。

* 这就是为什么一个10秒的剪辑总是用10000步来表示。

  1. # Load audio segments using pydub
  2. activates, negatives, backgrounds = load_raw_audio('./raw_data/')
  3. print("background len should be 10,000, since it is a 10 sec clip\n" + str(len(backgrounds[0])),"\n")
  4. print("activate[0] len may be around 1000, since an `activate` audio clip is usually around 1 second (but varies a lot) \n" + str(len(activates[0])),"\n")
  5. print("activate[1] len: different `activate` clips can have different lengths\n" + str(len(activates[1])),"\n")

background len should be 10,000, since it is a 10 sec clip
10000 

activate[0] len may be around 1000, since an `activate` audio clip is usually around 1 second (but varies a lot) 
721 

activate[1] len: different `activate` clips can have different lengths
731 

生成单个训练样例 

1)叠加positives/negatives的“单词”音频剪辑在背景音频的顶部

  • * 给定一个10秒的背景剪辑和一个简短的音频剪辑包含一个积极或消极的词,你需要能够“添加”单词音频剪辑在背景音频的顶部。
  • * 你将插入多个剪辑的积极/消极的单词到背景中,你不想插入一个“激活”或一个随机的单词,与你之前添加的另一个剪辑重叠的地方。
  • * 为了确保“word”音频段在插入时不重叠,您将跟踪以前插入的音频剪辑的时间。
  • * 要明确的是,当你插入一个1秒的“激活”到一个10秒的咖啡馆噪音剪辑,你不会以一个11秒的剪辑结束
  • * 产生的音频剪辑仍然是10秒长。
  • * 稍后您将看到pydub如何允许您这样做。

2)给积极/消极的词语贴上标签

例子:

合成数据更容易标记

  1. * 这是合成训练数据的另一个原因:如上所述,生成这些标签$y^{\langle t \rangle}$相对简单。
  2. * 相比之下,如果你在麦克风上录制了10秒的音频,那么对于一个人来说,听它并手动标记“激活”完成的时间是非常耗时的。

3)可视化标签

* 这张图说明了一个剪辑中的标签$y^{\langle t \rangle}$。

* 我们插入了“activate”, “innocent”, “activate”, “baby ”。

* 注意,积极的标签“1”只与积极的单词相关联。

4)辅助函数

要实现训练集合成过程,您将使用以下辅助函数。

* 所有这些函数将使用1ms的离散间隔

* 10秒的音频总是离散成10000步。

1. `get_random_time_segment(segment_ms)`

    * 从背景音频中检索随机时间段。

2. `is_overlapping(segment_time, existing_segments)`

    * 检查一个时间段是否与现有的时间段重叠

3. `insert_audio_clip(background, audio_clip, existing_times)`

    * 插入一个音频段在一个随机的时间在背景音频

    * 使用函数 `get_random_time_segment` and `is_overlapping`

4. `insert_ones(y, segment_end_ms)`

    * 在单词“激活”后的标签向量y中插入额外的1

5)获取随机时间段

* 函数‘ get_random_time_segment(segment_ms) ’返回一个随机时间段,我们可以插入一个持续时间‘ segment_ms ’的音频剪辑。

* 请通读代码以确保你明白它在做什么。

  1. def get_random_time_segment(segment_ms):
  2. """
  3. Gets a random time segment of duration segment_ms in a 10,000 ms audio clip.
  4. Arguments:
  5. segment_ms -- the duration of the audio clip in ms ("ms" stands for "milliseconds")
  6. Returns:
  7. segment_time -- a tuple of (segment_start, segment_end) in ms
  8. """
  9. segment_start = np.random.randint(low=0, high=10000-segment_ms) # Make sure segment doesn't run past the 10sec background
  10. segment_end = segment_start + segment_ms - 1
  11. return (segment_start, segment_end)

6)检查音频剪辑是否重叠

* 假设您在片段(1000,1800)和片段(3400,4500)插入了音频剪辑。

* 第一个片段从第1000步开始,到第1800步结束。

* 第二段从3400开始,到4500结束。

* 如果我们正在考虑是否在(3000,3600)插入一个新的音频剪辑,这是否与之前插入的片段重叠?

* 在这种情况下,(3000,3600)和(3400,4500)重叠,所以我们应该决定不插入剪辑在这里。

* 为了这个函数的目的,定义(100,200)和(200,250)是重叠的,因为它们在时间步长200重叠。

* (100,199)和(200,250)不重叠。

  1. # UNQ_C1
  2. # GRADED FUNCTION: is_overlapping
  3. def is_overlapping(segment_time, previous_segments):
  4. """
  5. Checks if the time of a segment overlaps with the times of existing segments.
  6. Arguments:
  7. segment_time -- a tuple of (segment_start, segment_end) for the new segment
  8. previous_segments -- a list of tuples of (segment_start, segment_end) for the existing segments
  9. Returns:
  10. True if the time segment overlaps with any of the existing segments, False otherwise
  11. """
  12. segment_start, segment_end = segment_time
  13. # Step 1: Initialize overlap as a "False" flag. (≈ 1 line)
  14. overlap = False
  15. # Step 2: loop over the previous_segments start and end times.
  16. # Compare start/end times and set the flag to True if there is an overlap (≈ 3 lines)
  17. for previous_start, previous_end in previous_segments: # @KEEP
  18. if segment_start <= previous_end and segment_end >= previous_start:
  19. overlap = True
  20. break
  21. return overlap
  1. # UNIT TEST
  2. def is_overlapping_test(target):
  3. assert target((670, 1430), []) == False, "Overlap with an empty list must be False"
  4. assert target((500, 1000), [(100, 499), (1001, 1100)]) == False, "Almost overlap, but still False"
  5. assert target((750, 1250), [(100, 750), (1001, 1100)]) == True, "Must overlap with the end of first segment"
  6. assert target((750, 1250), [(300, 600), (1250, 1500)]) == True, "Must overlap with the begining of second segment"
  7. assert target((750, 1250), [(300, 600), (600, 1500), (1600, 1800)]) == True, "Is contained in second segment"
  8. print("\033[92m All tests passed!")
  9. is_overlapping_test(is_overlapping)

All tests passed!

  1. overlap1 = is_overlapping((950, 1430), [(2000, 2550), (260, 949)])
  2. overlap2 = is_overlapping((2305, 2950), [(824, 1532), (1900, 2305), (3424, 3656)])
  3. print("Overlap 1 = ", overlap1)
  4. print("Overlap 2 = ", overlap2)

Overlap 1 =  False
Overlap 2 =  True

7)插入音频剪辑

* 让我们使用前面的辅助函数在随机时间插入一个新的音频剪辑到10秒的背景上。

* 我们将确保任何新插入的段不会与先前插入的段重叠。

  1. # UNQ_C2
  2. # GRADED FUNCTION: insert_audio_clip
  3. def insert_audio_clip(background, audio_clip, previous_segments):
  4. """
  5. Insert a new audio segment over the background noise at a random time step, ensuring that the
  6. audio segment does not overlap with existing segments.
  7. Arguments:
  8. background -- a 10 second background audio recording.
  9. audio_clip -- the audio clip to be inserted/overlaid.
  10. previous_segments -- times where audio segments have already been placed
  11. Returns:
  12. new_background -- the updated background audio
  13. """
  14. # Get the duration of the audio clip in ms
  15. segment_ms = len(audio_clip)
  16. # Step 1: Use one of the helper functions to pick a random time segment onto which to insert
  17. # the new audio clip. (≈ 1 line)
  18. segment_time = get_random_time_segment(segment_ms)
  19. # Step 2: Check if the new segment_time overlaps with one of the previous_segments. If so, keep
  20. # picking new segment_time at random until it doesn't overlap. To avoid an endless loop
  21. # we retry 5 times(≈ 2 lines)
  22. retry = 5 # @KEEP
  23. while is_overlapping(segment_time, previous_segments) and retry >= 0:
  24. segment_time = get_random_time_segment(segment_ms)
  25. retry = retry - 1
  26. # if last try is not overlaping, insert it to the background
  27. if not is_overlapping(segment_time, previous_segments):
  28. # Step 3: Append the new segment_time to the list of previous_segments (≈ 1 line)
  29. previous_segments.append(segment_time)
  30. # Step 4: Superpose audio segment and background
  31. new_background = background.overlay(audio_clip, position = segment_time[0])
  32. print(segment_time)
  33. else:
  34. print("Timeouted")
  35. new_background = background
  36. segment_time = (10000, 10000)
  37. return new_background, segment_time
  1. # UNIT TEST
  2. def insert_audio_clip_test(target):
  3. np.random.seed(5)
  4. audio_clip, segment_time = target(backgrounds[0], activates[0], [(0, 4400)])
  5. duration = segment_time[1] - segment_time[0]
  6. assert segment_time[0] > 4400, "Error: The audio clip is overlaping with the first segment"
  7. assert duration + 1 == len(activates[0]) , "The segment length must match the audio clip length"
  8. assert audio_clip != backgrounds[0] , "The audio clip must be different than the pure background"
  9. # Not possible to insert clip into background
  10. audio_clip, segment_time = target(backgrounds[0], activates[0], [(0, 9999)])
  11. assert segment_time[0] == 10000 and segment_time[1] == 10000, "Segment must match the out by max-retry mark"
  12. assert audio_clip == backgrounds[0], "output audio clip must be exactly the same input background"
  13. print("\033[92m All tests passed!")
  14. insert_audio_clip_test(insert_audio_clip)

(7286, 8006)
Timeouted
All tests passed!

  1. np.random.seed(5)
  2. audio_clip, segment_time = insert_audio_clip(backgrounds[0], activates[0], [(3790, 4400)])
  3. audio_clip.export("insert_test.wav", format="wav")
  4. print("Segment Time: ", segment_time)
  5. IPython.display.Audio("insert_test.wav")

(2915, 3635)
Segment Time:  (2915, 3635)

  1. # Expected audio
  2. IPython.display.Audio("audio_examples/insert_reference.wav")

8)插入positive目标的标签

* 实现代码来更新标签$y^{\langle t \rangle}$,假设你刚刚插入了一个“激活”的音频剪辑。

* 在下面的代码中,‘ y ’是一个‘(1,1375)’维度向量,因为$T_y = 1375$。

* 如果“激活”音频剪辑在时间步t结束,则设置$y^{\langle t+1 \rangle} = 1$,并设置下一个49个额外的连续值为1。

* 请注意,如果目标单词出现在整个音频剪辑的末尾附近,则可能没有50个额外的时间步长设置为1。

* 确保你没有跑过数组的末尾并尝试更新‘ y[0][1375] ’,因为有效的索引是‘ y[0][0] ’到‘ y[0][1374] ’,因为T_y = 1375$。

* 如果“activate”在第1370步结束,你只会得到“y[0][1371] = y[0][1372] = y[0][1373] = y[0][1374] = 1”

  1. # UNQ_C3
  2. # GRADED FUNCTION: insert_ones
  3. def insert_ones(y, segment_end_ms):
  4. """
  5. Update the label vector y. The labels of the 50 output steps strictly after the end of the segment
  6. should be set to 1. By strictly we mean that the label of segment_end_y should be 0 while, the
  7. 50 following labels should be ones.
  8. Arguments:
  9. y -- numpy array of shape (1, Ty), the labels of the training example
  10. segment_end_ms -- the end time of the segment in ms
  11. Returns:
  12. y -- updated labels
  13. """
  14. _, Ty = y.shape
  15. # duration of the background (in terms of spectrogram time-steps)
  16. segment_end_y = int(segment_end_ms * Ty / 10000.0)
  17. if segment_end_y < Ty:
  18. # Add 1 to the correct index in the background label (y)
  19. for i in range(segment_end_y+1, segment_end_y+51):
  20. if i < Ty:
  21. y[0, i] = 1
  22. return y
  1. # UNIT TEST
  2. import random
  3. def insert_ones_test(target):
  4. segment_end_y = random.randrange(0, Ty - 50)
  5. segment_end_ms = int(segment_end_y * 10000.4) / Ty;
  6. arr1 = target(np.zeros((1, Ty)), segment_end_ms)
  7. assert type(arr1) == np.ndarray, "Wrong type. Output must be a numpy array"
  8. assert arr1.shape == (1, Ty), "Wrong shape. It must match the input shape"
  9. assert np.sum(arr1) == 50, "It must insert exactly 50 ones"
  10. assert arr1[0][segment_end_y - 1] == 0, f"Array at {segment_end_y - 1} must be 0"
  11. assert arr1[0][segment_end_y] == 0, f"Array at {segment_end_y} must be 1"
  12. assert arr1[0][segment_end_y + 1] == 1, f"Array at {segment_end_y + 1} must be 1"
  13. assert arr1[0][segment_end_y + 50] == 1, f"Array at {segment_end_y + 50} must be 1"
  14. assert arr1[0][segment_end_y + 51] == 0, f"Array at {segment_end_y + 51} must be 0"
  15. print("\033[92m All tests passed!")
  16. insert_ones_test(insert_ones)

All tests passed!

  1. arr1 = insert_ones(np.zeros((1, Ty)), 9700)
  2. plt.plot(insert_ones(arr1, 4251)[0,:])
  3. print("sanity checks:", arr1[0][1333], arr1[0][634], arr1[0][635])

sanity checks: 0.0 1.0 0.0

9)创建一个训练示例

最后,您可以使用‘ insert_audio_clip ’和‘ insert_ones ’来创建一个新的训练示例。

  1. # UNQ_C4
  2. # GRADED FUNCTION: create_training_example
  3. def create_training_example(background, activates, negatives, Ty):
  4. """
  5. Creates a training example with a given background, activates, and negatives.
  6. Arguments:
  7. background -- a 10 second background audio recording
  8. activates -- a list of audio segments of the word "activate"
  9. negatives -- a list of audio segments of random words that are not "activate"
  10. Ty -- The number of time steps in the output
  11. Returns:
  12. x -- the spectrogram of the training example
  13. y -- the label at each time step of the spectrogram
  14. """
  15. # Make background quieter
  16. background = background - 20
  17. # Step 1: Initialize y (label vector) of zeros (≈ 1 line)
  18. y = np.zeros((1, Ty))
  19. # Step 2: Initialize segment times as empty list (≈ 1 line)
  20. previous_segments = []
  21. # Select 0-4 random "activate" audio clips from the entire list of "activates" recordings
  22. number_of_activates = np.random.randint(0, 5)
  23. random_indices = np.random.randint(len(activates), size=number_of_activates)
  24. random_activates = [activates[i] for i in random_indices]
  25. # Step 3: Loop over randomly selected "activate" clips and insert in background
  26. for random_activate in random_activates: # @KEEP
  27. # Insert the audio clip on the background
  28. background, segment_time = insert_audio_clip(background, random_activate, previous_segments)
  29. # Retrieve segment_start and segment_end from segment_time
  30. segment_start, segment_end = segment_time
  31. # Insert labels in "y" at segment_end
  32. y = insert_ones(y, segment_end)
  33. # Select 0-2 random negatives audio recordings from the entire list of "negatives" recordings
  34. number_of_negatives = np.random.randint(0, 3)
  35. random_indices = np.random.randint(len(negatives), size=number_of_negatives)
  36. random_negatives = [negatives[i] for i in random_indices]
  37. # Step 4: Loop over randomly selected negative clips and insert in background
  38. for random_negative in random_negatives: # @KEEP
  39. # Insert the audio clip on the background
  40. background, _ = insert_audio_clip(background, random_negative, previous_segments)
  41. # Standardize the volume of the audio clip
  42. background = match_target_amplitude(background, -20.0)
  43. # Export new training example
  44. # file_handle = background.export("train" + ".wav", format="wav")
  45. # Get and plot spectrogram of the new recording (background with superposition of positive and negatives)
  46. x = graph_spectrogram("train.wav")
  47. return x, y
  1. # UNIT TEST
  2. def create_training_example_test(target):
  3. np.random.seed(18)
  4. x, y = target(backgrounds[0], activates, negatives, 1375)
  5. assert type(x) == np.ndarray, "Wrong type for x"
  6. assert type(y) == np.ndarray, "Wrong type for y"
  7. assert tuple(x.shape) == (101, 5511), "Wrong shape for x"
  8. assert tuple(y.shape) == (1, 1375), "Wrong shape for y"
  9. assert np.all(x > 0), "All x values must be higher than 0"
  10. assert np.all(y >= 0), "All y values must be higher or equal than 0"
  11. assert np.all(y < 51), "All y values must be smaller than 51"
  12. assert np.sum(y) % 50 == 0, "Sum of activate marks must be a multiple of 50"
  13. assert np.isclose(np.linalg.norm(x), 39745552.52075), "Spectrogram is wrong. Check the parameters passed to the insert_audio_clip function"
  14. print("\033[92m All tests passed!")
  15. create_training_example_test(create_training_example)

(2885, 3793)
(5294, 7685)
(9105, 9511)
(645, 999)
All tests passed!

  1. # Set the random seed
  2. np.random.seed(18)
  3. x, y = create_training_example(backgrounds[0], activates, negatives, Ty)

(2885, 3793)
(5294, 7685)
(9105, 9511)
(645, 999) 

现在您可以听您创建的训练示例,并将其与上面生成的频谱图进行比较。

IPython.display.Audio("train.wav")

最后,您可以绘制生成的训练示例的相关标签。

plt.plot(y[0])

全部训练集
  1. * 您现在已经实现了生成单个训练示例所需的代码。
  2. * 我们使用这个过程来生成一个大的训练集。
  3. * 为了节省时间,我们生成一个较小的32个示例的训练集。
  1. # START SKIP FOR GRADING
  2. np.random.seed(4543)
  3. nsamples = 32
  4. X = []
  5. Y = []
  6. for i in range(0, nsamples):
  7. if i%10 == 0:
  8. print(i)
  9. x, y = create_training_example(backgrounds[i % 2], activates, negatives, Ty)
  10. X.append(x.swapaxes(0,1))
  11. Y.append(y.swapaxes(0,1))
  12. X = np.array(X)
  13. Y = np.array(Y)
  14. # END SKIP FOR GRADING
  1. 0
  2. (5817, 6471)
  3. (2497, 4075)
  4. (9151, 9871)
  5. (3385, 4963)
  6. (5426, 6080)
  7. (2047, 2771)
  8. (6979, 7385)
  9. (2647, 3367)
  10. (1698, 2613)
  11. (8049, 8957)
  12. (4926, 5650)
  13. (5665, 6264)
  14. (8635, 9359)
  15. (1288, 3028)
  16. (4924, 6260)
  17. (4537, 4891)
  18. (6835, 7565)
  19. (1747, 2401)
  20. (4272, 4626)
  21. (6573, 7297)
  22. (7488, 8208)
  23. (1934, 4325)
  24. (4585, 6163)
  25. (8235, 8775)
  26. Timeouted
  27. (1750, 2404)
  28. (9469, 9823)
  29. (3454, 4369)
  30. (399, 1129)
  31. (7335, 8913)
  32. (2066, 2472)
  33. (5838, 6492)
  34. (2884, 4462)
  35. (1642, 2241)
  36. (2326, 3050)
  37. (7830, 8745)
  38. (5093, 5692)
  39. 10
  40. (6266, 6986)
  41. (7157, 8897)
  42. (236, 1151)
  43. (3471, 5211)
  44. (8859, 9513)
  45. (1615, 3193)
  46. (6421, 8812)
  47. (4022, 5600)
  48. Timeouted
  49. (3944, 5522)
  50. (8843, 9497)
  51. (90, 668)
  52. (1378, 2045)
  53. (7328, 8048)
  54. (112, 766)
  55. (6579, 7119)
  56. (7100, 7640)
  57. (8605, 9259)
  58. (4776, 7167)
  59. (2991, 4731)
  60. (206, 2597)
  61. (8109, 9017)
  62. (7328, 7868)
  63. Timeouted
  64. (1742, 2409)
  65. (4311, 4965)
  66. (3867, 4224)
  67. (2713, 3437)
  68. (5484, 6208)
  69. (7089, 7756)
  70. (4882, 5241)
  71. (8605, 8964)
  72. 20
  73. (5746, 8137)
  74. (7766, 8486)
  75. (2788, 5179)
  76. Timeouted
  77. (6662, 7202)
  78. (2144, 2695)
  79. (2132, 2799)
  80. (8383, 9961)
  81. (156, 1064)
  82. (8543, 9197)
  83. (4702, 5426)
  84. (6594, 7324)
  85. (8048, 8963)
  86. (2261, 2981)
  87. (6108, 6775)
  88. (8593, 9247)
  89. (3330, 4054)
  90. (4339, 5917)
  91. (765, 1305)
  92. (8004, 8410)
  93. (6125, 7865)
  94. (1308, 2028)
  95. (2544, 3268)
  96. (3912, 5490)
  97. (2916, 3640)
  98. (5031, 5939)
  99. (4099, 4766)
  100. (777, 1131)
  101. (2074, 2728)
  102. 30
  103. (6855, 7509)
  104. (5053, 5961)
  105. (242, 896)
  106. (1220, 1874)
  107. (2899, 3305)
  108. (3467, 4045)
  109. (4692, 6270)
  110. (6808, 7532)
  111. (8937, 9488)

您希望将数据集保存到一个文件中,以便在更实际的环境中稍后加载。我们给你提供以下代码供参考。

  1. # Save the data for further uses
  2. # np.save(f'./XY_train/X.npy', X)
  3. # np.save(f'./XY_train/Y.npy', Y)
  4. # Load the preprocessed training examples
  5. # X = np.load("./XY_train/X.npy")
  6. # Y = np.load("./XY_train/Y.npy")
开发(测试)集
  • * 为了测试我们的模型,我们记录了一个包含25个示例的开发集。
  • * 虽然我们的训练数据是合成的,但我们希望创建一个与实际输入相同分布的开发集。
  • * 因此,我们录制了25个10秒的音频片段,人们说“激活”和其他随机单词,并手工标记。
  • * 这遵循课程3“结构化机器学习项目”中描述的原则,我们应该创建开发集尽可能与测试集分布相似
  • * 这就是为什么我们的开发团队使用真实音频而不是合成音频的原因。
  1. # Load preprocessed dev set examples
  2. X_dev = np.load("./XY_dev/X_dev.npy")
  3. Y_dev = np.load("./XY_dev/Y_dev.npy")

3.2 触发词检测模型

  1. * 现在你已经建立了一个数据集,让我们来编写和训练一个触发词检测模型!
  2. * 模型将使用1-D卷积层、GRU层和dense层。
  3. * 让我们加载允许你在Keras中使用这些层的包。这可能需要一分钟来加载。
导包
  1. from tensorflow.keras.callbacks import ModelCheckpoint
  2. from tensorflow.keras.models import Model, load_model, Sequential
  3. from tensorflow.keras.layers import Dense, Activation, Dropout, Input, Masking, TimeDistributed, LSTM, Conv1D
  4. from tensorflow.keras.layers import GRU, Bidirectional, BatchNormalization, Reshape
  5. from tensorflow.keras.optimizers import Adam
构建模型

我们的目标是建立一个网络,当它检测到触发词时,它将摄取频谱图并输出信号。该网络将使用4层:

* 卷积层

* 两个GRU层

* dense层。

下面是我们将要使用的架构。

1D 卷积 layer

该模型的一个关键层是1D卷积步骤(接近图3的底部)。

* 输入5511阶跃谱图。每一步都是101个单位的向量。

* 输出1375步进输出

* 该输出由多个层进一步处理以获得最终的$T_y = 1375$ step输出。

* 这个1D卷积层的作用类似于您在课程4中看到的2D卷积,提取低级特征,然后可能生成较小维度的输出。

* 计算上,一维转换层也有助于加速模型,因为现在GRU只能处理1375个时间步长,而不是5511个时间步长。

GRU, dense and sigmoid

* 两个GRU层从左到右读取输入序列。

* dense层 + sigmod层对$y^{\langle t \rangle}$进行预测。

* 因为y是一个二进制值(0或1),我们在最后一层使用sigmoid输出来估计输出为1的可能性,对应于用户刚刚说“activate”。

单向RNN

* 注意,我们使用的是单向RNN,而不是双向RNN。

* 这对于触发词检测非常重要,因为我们希望能够在触发词说出来后几乎立即检测到它。

* 如果我们使用双向RNN,我们将不得不等待整个10秒的音频被记录下来,然后我们才能判断在音频剪辑的第一秒是否说了“激活”。

在下面的模型中,每一层的输入都是前一层的输出。模型的实现可以通过四个步骤来完成。

**Step 1**: CONV层。使用‘ Conv1D() ’来实现这一点,有196个过滤器,过滤器大小为15 (' kernel_size=15 '),步长为4.

**Step 2**: 第一个GRU层。为了生成GRU层,使用128个单元。

**Step 3**: 第二个GRU层。这与第一个GRU层具有相同的规格。

* 接下来是dropout,批处理规范化,然后是另一个dropout。

**Step 4**: 创建一个时间分布的dense层

  1. # UNQ_C5
  2. # GRADED FUNCTION: modelf
  3. def modelf(input_shape):
  4. """
  5. Function creating the model's graph in Keras.
  6. Argument:
  7. input_shape -- shape of the model's input data (using Keras conventions)
  8. Returns:
  9. model -- Keras model instance
  10. """
  11. X_input = Input(shape = input_shape)
  12. # Step 1: CONV layer (≈4 lines)
  13. # Add a Conv1D with 196 units, kernel size of 15 and stride of 4
  14. X = Conv1D(196, 15, strides=4)(X_input)
  15. # Batch normalization
  16. X = BatchNormalization()(X)
  17. # ReLu activation
  18. X = Activation('relu')(X)
  19. # dropout (use 0.8)
  20. X = Dropout(0.8)(X)
  21. # Step 2: First GRU Layer (≈4 lines)
  22. # GRU (use 128 units and return the sequences)
  23. X = GRU(units = 128, return_sequences=True)(X)
  24. # dropout (use 0.8)
  25. X = Dropout(0.8)(X)
  26. # Batch normalization.
  27. X = BatchNormalization()(X)
  28. # Step 3: Second GRU Layer (≈4 lines)
  29. # GRU (use 128 units and return the sequences)
  30. X = GRU(units = 128, return_sequences=True)(X)
  31. # dropout (use 0.8)
  32. X = Dropout(0.8)(X)
  33. # Batch normalization
  34. X = BatchNormalization()(X)
  35. # dropout (use 0.8)
  36. X = Dropout(0.8)(X)
  37. # Step 4: Time-distributed dense layer (≈1 line)
  38. # TimeDistributed with sigmoid activation
  39. X = TimeDistributed(Dense(1, activation = "sigmoid"))(X)
  40. model = Model(inputs = X_input, outputs = X)
  41. return model
  1. # UNIT TEST
  2. from test_utils import *
  3. def modelf_test(target):
  4. Tx = 5511
  5. n_freq = 101
  6. model = target(input_shape = (Tx, n_freq))
  7. expected_model = [['InputLayer', [(None, 5511, 101)], 0],
  8. ['Conv1D', (None, 1375, 196), 297136, 'valid', 'linear', (4,), (15,), 'GlorotUniform'],
  9. ['BatchNormalization', (None, 1375, 196), 784],
  10. ['Activation', (None, 1375, 196), 0],
  11. ['Dropout', (None, 1375, 196), 0, 0.8],
  12. ['GRU', (None, 1375, 128), 125184, True],
  13. ['Dropout', (None, 1375, 128), 0, 0.8],
  14. ['BatchNormalization', (None, 1375, 128), 512],
  15. ['GRU', (None, 1375, 128), 99072, True],
  16. ['Dropout', (None, 1375, 128), 0, 0.8],
  17. ['BatchNormalization', (None, 1375, 128), 512],
  18. ['Dropout', (None, 1375, 128), 0, 0.8],
  19. ['TimeDistributed', (None, 1375, 1), 129, 'sigmoid']]
  20. comparator(summary(model), expected_model)
  21. modelf_test(modelf)

All tests passed!

model = modelf(input_shape = (Tx, n_freq))

 让我们打印模型摘要以跟踪形状。

model.summary()
  1. Model: "model_1"
  2. _________________________________________________________________
  3. Layer (type) Output Shape Param #
  4. =================================================================
  5. input_2 (InputLayer) [(None, 5511, 101)] 0
  6. _________________________________________________________________
  7. conv1d_1 (Conv1D) (None, 1375, 196) 297136
  8. _________________________________________________________________
  9. batch_normalization_3 (Batch (None, 1375, 196) 784
  10. _________________________________________________________________
  11. activation_1 (Activation) (None, 1375, 196) 0
  12. _________________________________________________________________
  13. dropout_4 (Dropout) (None, 1375, 196) 0
  14. _________________________________________________________________
  15. gru_2 (GRU) (None, 1375, 128) 125184
  16. _________________________________________________________________
  17. dropout_5 (Dropout) (None, 1375, 128) 0
  18. _________________________________________________________________
  19. batch_normalization_4 (Batch (None, 1375, 128) 512
  20. _________________________________________________________________
  21. gru_3 (GRU) (None, 1375, 128) 99072
  22. _________________________________________________________________
  23. dropout_6 (Dropout) (None, 1375, 128) 0
  24. _________________________________________________________________
  25. batch_normalization_5 (Batch (None, 1375, 128) 512
  26. _________________________________________________________________
  27. dropout_7 (Dropout) (None, 1375, 128) 0
  28. _________________________________________________________________
  29. time_distributed_1 (TimeDist (None, 1375, 1) 129
  30. =================================================================
  31. Total params: 523,329
  32. Trainable params: 522,425
  33. Non-trainable params: 904
  34. _________________________________________________________________

网络的输出形状为(None, 1375,1),而输入形状为(None, 5511,101)。Conv1D将步骤数从5511减少到1375。 

训练模型
  1. * 触发词检测需要很长时间来训练。
  2. * 为了节省时间,我们已经使用你上面构建的架构在GPU上训练了大约3个小时的模型,以及大约4000个示例的大型训练集。
  3. * 让我们加载模型。
  1. from tensorflow.keras.models import model_from_json
  2. json_file = open('./models/model.json', 'r')
  3. loaded_model_json = json_file.read()
  4. json_file.close()
  5. model = model_from_json(loaded_model_json)
  6. model.load_weights('./models/model.h5')

如果要对预训练模型进行微调,那么阻塞所有批处理归一化层的权重是很重要的。如果您打算从头开始训练一个新模型,请跳过下一个单元格。 

  1. model.layers[2].trainable = False
  2. model.layers[7].trainable = False
  3. model.layers[10].trainable = False

您可以使用Adam优化器和二元交叉熵损失进一步训练模型,如下所示。这将运行得很快,因为我们只训练了两个epoch,并且训练集很小,只有32个样本。

  1. opt = Adam(lr=1e-6, beta_1=0.9, beta_2=0.999)
  2. model.compile(loss='binary_crossentropy', optimizer=opt, metrics=["accuracy"])
model.fit(X, Y, batch_size = 16, epochs=1)

2/2 [==============================] - 8s 176ms/step - loss: 0.4388 - accuracy: 0.8713 

测试模型

最后,让我们看看模型在开发集上的表现。

  1. loss, acc, = model.evaluate(X_dev, Y_dev)
  2. print("Dev set accuracy = ", acc)

1/1 [==============================] - 1s 883ms/step - loss: 0.1883 - accuracy: 0.9238
Dev set accuracy =  0.9237818121910095 

看起来很不错!

  1. * 然而,准确性并不是这项任务的重要指标
  2. * 由于标签严重偏向于0,因此只输出0的神经网络将获得略高于90%的准确率。
  3. * 我们可以定义更有用的指标,如F1分数或Precision/Recall。
  4. *  这里我们就不讨论这个了,我们来看看这个模型是如何预测的。

3.3 做预测

现在您已经为触发词检测构建了一个工作模型,让我们使用它来进行预测。这个代码片段通过网络运行音频(保存在wav文件中)

  1. def detect_triggerword(filename):
  2. plt.subplot(2, 1, 1)
  3. # Correct the amplitude of the input file before prediction
  4. audio_clip = AudioSegment.from_wav(filename)
  5. audio_clip = match_target_amplitude(audio_clip, -20.0)
  6. file_handle = audio_clip.export("tmp.wav", format="wav")
  7. filename = "tmp.wav"
  8. x = graph_spectrogram(filename)
  9. # the spectrogram outputs (freqs, Tx) and we want (Tx, freqs) to input into the model
  10. x = x.swapaxes(0,1)
  11. x = np.expand_dims(x, axis=0)
  12. predictions = model.predict(x)
  13. plt.subplot(2, 1, 2)
  14. plt.plot(predictions[0,:,0])
  15. plt.ylabel('probability')
  16. plt.show()
  17. return predictions
插入一个报时以确认“activate”的出现
  • *一旦你估算出在每个输出步骤中检测到单词“activate”的概率,你就可以在概率高于某个阈值时触发“chiming”声音播放。
  • * $y^{\langle t \rangle}$可能在“activate”之后连续许多值接近1,但我们只想发出一次报时。
  • * 因此,我们将每75个输出步骤最多插入一次编钟声音。
  • * 这将有助于防止我们为一个“activate”实例插入两个编钟。
  • * 这与计算机视觉的非最大抑制作用类似。
  1. chime_file = "audio_examples/chime.wav"
  2. def chime_on_activate(filename, predictions, threshold):
  3. audio_clip = AudioSegment.from_wav(filename)
  4. chime = AudioSegment.from_wav(chime_file)
  5. Ty = predictions.shape[1]
  6. # Step 1: Initialize the number of consecutive output steps to 0
  7. consecutive_timesteps = 0
  8. # Step 2: Loop over the output steps in the y
  9. for i in range(Ty):
  10. # Step 3: Increment consecutive output steps
  11. consecutive_timesteps += 1
  12. # Step 4: If prediction is higher than the threshold and more than 20 consecutive output steps have passed
  13. if consecutive_timesteps > 20:
  14. # Step 5: Superpose audio and background using pydub
  15. audio_clip = audio_clip.overlay(chime, position = ((i / Ty) * audio_clip.duration_seconds) * 1000)
  16. # Step 6: Reset consecutive output steps to 0
  17. consecutive_timesteps = 0
  18. # if amplitude is smaller than the threshold reset the consecutive_timesteps counter
  19. if predictions[0, i, 0] < threshold:
  20. consecutive_timesteps = 0
  21. audio_clip.export("chime_output.wav", format='wav')
开发示例测试

让我们来探索我们的模型如何处理来自开发集的两个未见过的音频剪辑。让我们先来听两个开发集的剪辑。

IPython.display.Audio("./raw_data/dev/1.wav")

现在让我们在这些音频片段上运行模型,看看它是否在“activate”之后添加了一个编钟!

  1. filename = "./raw_data/dev/1.wav"
  2. prediction = detect_triggerword(filename)
  3. chime_on_activate(filename, prediction, 0.5)
  4. IPython.display.Audio("./chime_output.wav")

这是你应该记住的:

- 数据合成是为语音问题创建大型训练集的有效方法,特别是触发词检测。

- 在将音频数据传递给RNN, GRU或LSTM之前,使用频谱图和可选的1D转换层是常见的预处理步骤。

- 端到端深度学习方法可用于构建非常有效的触发词检测系统。

3.4 试试你自己的例子!

您可以在自己的音频剪辑上尝试您的模型!

  1. * 录制一段10秒的你说“激活”和其他随机单词的音频片段,并将其上传到Coursera中心,命名为“myaudio.wav”。
  2. * 请确保以wav文件上传音频。
  3. * 如果你的音频是以不同的格式录制的(如mp3),你可以在网上找到免费的软件将其转换为wav。
  4. * 如果你的音频记录不是10秒,下面的代码将根据需要修剪或填充它,使它成为10秒。
  1. # Preprocess the audio to the correct format
  2. def preprocess_audio(filename):
  3. # Trim or pad audio segment to 10000ms
  4. padding = AudioSegment.silent(duration=10000)
  5. segment = AudioSegment.from_wav(filename)[:10000]
  6. segment = padding.overlay(segment)
  7. # Set frame rate to 44100
  8. segment = segment.set_frame_rate(44100)
  9. # Export as wav
  10. segment.export(filename, format='wav')

 将音频文件上传到Coursera后,将文件的路径放在下面的变量中。

your_filename = "audio_examples/my_audio.wav"
  1. preprocess_audio(your_filename)
  2. IPython.display.Audio(your_filename) # listen to the audio you uploaded

最后,使用这个模型来预测你在10秒的音频片段中说激活的时间,并触发一个编钟。如果没有适当地添加蜂鸣声,请尝试调整chime_threshold。 

  1. chime_threshold = 0.3 # 触发蜂鸣器的阈值
  2. prediction = detect_triggerword(your_filename)
  3. chime_on_activate(your_filename, prediction, chime_threshold)
  4. IPython.display.Audio("./chime_output.wav")

注:本文转载自blog.csdn.net的笨笨sg的文章"https://blog.csdn.net/a131529/article/details/143941506"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2491) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top