自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

用 Python 訓(xùn)練自己的語音識(shí)別系統(tǒng),這波操作穩(wěn)了

人工智能 語音識(shí)別
近幾年來語音識(shí)別技術(shù)得到了迅速發(fā)展,從手機(jī)中的Siri語音智能助手、微軟的小娜以及各種平臺(tái)的智能音箱等等,各種語音識(shí)別的項(xiàng)目得到了廣泛應(yīng)用。

近幾年來語音識(shí)別技術(shù)得到了迅速發(fā)展,從手機(jī)中的Siri語音智能助手、微軟的小娜以及各種平臺(tái)的智能音箱等等,各種語音識(shí)別的項(xiàng)目得到了廣泛應(yīng)用。

語音識(shí)別屬于感知智能,而讓機(jī)器從簡單的識(shí)別語音到理解語音,則上升到了認(rèn)知智能層面,機(jī)器的自然語言理解能力如何,也成為了其是否有智慧的標(biāo)志,而自然語言理解正是目前難點(diǎn)。

同時(shí)考慮到目前大多數(shù)的語音識(shí)別平臺(tái)都是借助于智能云,對(duì)于語音識(shí)別的訓(xùn)練對(duì)于大多數(shù)人而言還較為神秘,故今天我們將利用python搭建自己的語音識(shí)別系統(tǒng)。

最終模型的識(shí)別效果如下:

[[396315]]

實(shí)驗(yàn)前的準(zhǔn)備

首先我們使用的python版本是3.6.5所用到的庫有cv2庫用來圖像處理;

Numpy庫用來矩陣運(yùn)算;Keras框架用來訓(xùn)練和加載模型。Librosa和python_speech_features庫用于提取音頻特征。Glob和pickle庫用來讀取本地?cái)?shù)據(jù)集。

[[396316]]

數(shù)據(jù)集準(zhǔn)備
首先數(shù)據(jù)集使用的是清華大學(xué)的thchs30中文數(shù)據(jù)。

這些錄音根據(jù)其文本內(nèi)容分成了四部分,A(句子的ID是1~250),B(句子的ID是251~500),C(501~750),D(751~1000)。ABC三組包括30個(gè)人的10893句發(fā)音,用來做訓(xùn)練,D包括10個(gè)人的2496句發(fā)音,用來做測(cè)試。

data文件夾中包含(.wav文件和.trn文件;trn文件里存放的是.wav文件的文字描述:第一行為詞,第二行為拼音,第三行為音素);

數(shù)據(jù)集如下:

[[396317]]

模型訓(xùn)練

1、提取語音數(shù)據(jù)集的MFCC特征:
首先人的聲音是通過聲道產(chǎn)生的,聲道的形狀決定了發(fā)出怎樣的聲音。如果我們可以準(zhǔn)確的知道這個(gè)形狀,那么我們就可以對(duì)產(chǎn)生的音素進(jìn)行準(zhǔn)確的描述。聲道的形狀在語音短時(shí)功率譜的包絡(luò)中顯示出來。而MFCCs就是一種準(zhǔn)確描述這個(gè)包絡(luò)的一種特征。

其中提取的MFCC特征如下圖可見。

故我們?cè)谧x取數(shù)據(jù)集的基礎(chǔ)上,要將其語音特征提取存儲(chǔ)以方便加載入神經(jīng)網(wǎng)絡(luò)進(jìn)行訓(xùn)練。

其對(duì)應(yīng)的代碼如下:

  1. #讀取數(shù)據(jù)集文件 
  2.  
  3. text_paths = glob.glob('data/*.trn'
  4.  
  5. total = len(text_paths) 
  6.  
  7. print(total) 
  8.  
  9. with open(text_paths[0], 'r', encoding='utf8') as fr: 
  10.  
  11. lines = fr.readlines 
  12.  
  13. print(lines) 
  14.  
  15. #數(shù)據(jù)集文件trn內(nèi)容讀取保存到數(shù)組中 
  16.  
  17. texts =  
  18.  
  19. paths =  
  20.  
  21. for path in text_paths: 
  22.  
  23. with open(path, 'r', encoding='utf8') as fr: 
  24.  
  25. lines = fr.readlines 
  26.  
  27. line = lines[0].strip('\n').replace(' '''
  28.  
  29. texts.append(line) 
  30.  
  31. paths.append(path.rstrip('.trn')) 
  32.  
  33. print(paths[0], texts[0]) 
  34.  
  35. #定義mfcc數(shù) 
  36.  
  37. mfcc_dim = 13 
  38.  
  39. #根據(jù)數(shù)據(jù)集標(biāo)定的音素讀入 
  40.  
  41. def load_and_trim(path): 
  42.  
  43. audio, sr = librosa.load(path) 
  44.  
  45. energy = librosa.feature.rmse(audio) 
  46.  
  47. frames = np.nonzero(energy >= np.max(energy) / 5
  48.  
  49. indices = librosa.core.frames_to_samples(frames)[1
  50.  
  51. audio = audio[indices[0]:indices[-1]] if indices.size else audio[0:0
  52.  
  53. return audio, sr 
  54.  
  55. #提取音頻特征并存儲(chǔ) 
  56.  
  57. features =  
  58.  
  59. for i in tqdm(range(total)): 
  60.  
  61. path = paths[i] 
  62.  
  63. audio, sr = load_and_trim(path) 
  64.  
  65. features.append(mfcc(audio, sr, numcep=mfcc_dim, nfft=551)) 
  66.  
  67. print(len(features), features[0].shape) 

2、神經(jīng)網(wǎng)絡(luò)預(yù)處理:
在進(jìn)行神經(jīng)網(wǎng)絡(luò)加載訓(xùn)練前,我們需要對(duì)讀取的MFCC特征進(jìn)行歸一化,主要目的是為了加快收斂,提高效果和減少干擾。然后處理好數(shù)據(jù)集和標(biāo)簽定義輸入和輸出即可。

對(duì)應(yīng)代碼如下:

  1. #隨機(jī)選擇100個(gè)數(shù)據(jù)集 
  2.  
  3. samples = random.sample(features, 100
  4.  
  5. samples = np.vstack(samples) 
  6.  
  7. #平均MFCC的值為了歸一化處理 
  8.  
  9. mfcc_mean = np.mean(samples, axis=0
  10.  
  11. #計(jì)算標(biāo)準(zhǔn)差為了歸一化 
  12.  
  13. mfcc_std = np.std(samples, axis=0
  14.  
  15. print(mfcc_mean) 
  16.  
  17. print(mfcc_std) 
  18.  
  19. #歸一化特征 
  20.  
  21. features = [(feature - mfcc_mean) / (mfcc_std + 1e-14for feature in features] 
  22.  
  23. #將數(shù)據(jù)集讀入的標(biāo)簽和對(duì)應(yīng)id存儲(chǔ)列表 
  24.  
  25. chars = {} 
  26.  
  27. for text in texts: 
  28.  
  29. for c in text: 
  30.  
  31. chars[c] = chars.get(c, 0) + 1 
  32.  
  33. chars = sorted(chars.items, key=lambda x: x[1], reverse=True
  34.  
  35. chars = [char[0for char in chars] 
  36.  
  37. print(len(chars), chars[:100]) 
  38.  
  39. char2id = {c: i for i, c in enumerate(chars)} 
  40.  
  41. id2char = {i: c for i, c in enumerate(chars)} 
  42.  
  43. data_index = np.arange(total) 
  44.  
  45. np.random.shuffle(data_index) 
  46.  
  47. train_size = int(0.9 * total) 
  48.  
  49. test_size = total - train_size 
  50.  
  51. train_index = data_index[:train_size] 
  52.  
  53. test_index = data_index[train_size:] 
  54.  
  55. #神經(jīng)網(wǎng)絡(luò)輸入和輸出X,Y的讀入數(shù)據(jù)集特征 
  56.  
  57. X_train = [features[i] for i in train_index] 
  58.  
  59. Y_train = [texts[i] for i in train_index] 
  60.  
  61. X_test = [features[i] for i in test_index] 
  62.  
  63. Y_test = [texts[i] for i in test_index] 

3、神經(jīng)網(wǎng)絡(luò)函數(shù)定義:
其中包括訓(xùn)練的批次,卷積層函數(shù)、標(biāo)準(zhǔn)化函數(shù)、激活層函數(shù)等等。

其中第⼀個(gè)維度為⼩⽚段的個(gè)數(shù),原始語⾳越長,第⼀個(gè)維度也越⼤, 第⼆個(gè)維度為 MFCC 特征的維度。得到原始語⾳的數(shù)值表⽰后,就可以使⽤ WaveNet 實(shí)現(xiàn)。由于 MFCC 特征為⼀維序列,所以使⽤ Conv1D 進(jìn)⾏卷積。 因果是指,卷積的輸出只和當(dāng)前位置之前的輸⼊有關(guān),即不使⽤未來的 特征,可以理解為將卷積的位置向前偏移。WaveNet 模型結(jié)構(gòu)如下所⽰:

具體如下可見:

  1. batch_size = 16 
  2.  
  3. #定義訓(xùn)練批次的產(chǎn)生,一次訓(xùn)練16個(gè) 
  4.  
  5. def batch_generator(x, y, batch_size=batch_size): 
  6.  
  7. offset = 0 
  8.  
  9. while True
  10.  
  11. offset += batch_size 
  12.  
  13. if offset == batch_size or offset >= len(x): 
  14.  
  15. data_index = np.arange(len(x)) 
  16.  
  17. np.random.shuffle(data_index) 
  18.  
  19. x = [x[i] for i in data_index] 
  20.  
  21. y = [y[i] for i in data_index] 
  22.  
  23. offset = batch_size 
  24.  
  25. X_data = x[offset - batch_size: offset] 
  26.  
  27. Y_data = y[offset - batch_size: offset] 
  28.  
  29. X_maxlen = max([X_data[i].shape[0for i in range(batch_size)]) 
  30.  
  31. Y_maxlen = max([len(Y_data[i]) for i in range(batch_size)]) 
  32.  
  33. X_batch = np.zeros([batch_size, X_maxlen, mfcc_dim]) 
  34.  
  35. Y_batch = np.ones([batch_size, Y_maxlen]) * len(char2id) 
  36.  
  37. X_length = np.zeros([batch_size, 1], dtype='int32'
  38.  
  39. Y_length = np.zeros([batch_size, 1], dtype='int32'
  40.  
  41. for i in range(batch_size): 
  42.  
  43. X_length[i, 0] = X_data[i].shape[0
  44.  
  45. X_batch[i, :X_length[i, 0], :] = X_data[i] 
  46.  
  47. Y_length[i, 0] = len(Y_data[i]) 
  48.  
  49. Y_batch[i, :Y_length[i, 0]] = [char2id[c] for c in Y_data[i]] 
  50.  
  51. inputs = {'X': X_batch, 'Y': Y_batch, 'X_length': X_length, 'Y_length': Y_length} 
  52.  
  53. outputs = {'ctc': np.zeros([batch_size])} 
  54.  
  55. epochs = 50 
  56.  
  57. num_blocks = 3 
  58.  
  59. filters = 128 
  60.  
  61. X = Input(shape=(None, mfcc_dim,), dtype='float32', name='X'
  62.  
  63. Y = Input(shape=(None,), dtype='float32', name='Y'
  64.  
  65. X_length = Input(shape=(1,), dtype='int32', name='X_length'
  66.  
  67. Y_length = Input(shape=(1,), dtype='int32', name='Y_length'
  68.  
  69. #卷積1層 
  70.  
  71. def conv1d(inputs, filters, kernel_size, dilation_rate): 
  72.  
  73. return Conv1D(filters=filters, kernel_size=kernel_size, strides=1, padding='causal', activation=None
  74.  
  75. dilation_rate=dilation_rate)(inputs) 
  76.  
  77. #標(biāo)準(zhǔn)化函數(shù) 
  78.  
  79. def batchnorm(inputs): 
  80.  
  81. return BatchNormalization(inputs) 
  82.  
  83. #激活層函數(shù) 
  84.  
  85. def activation(inputs, activation): 
  86.  
  87. return Activation(activation)(inputs) 
  88.  
  89. #全連接層函數(shù) 
  90.  
  91. def res_block(inputs, filters, kernel_size, dilation_rate): 
  92.  
  93. hf = activation(batchnorm(conv1d(inputs, filters, kernel_size, dilation_rate)), 'tanh'
  94.  
  95. hg = activation(batchnorm(conv1d(inputs, filters, kernel_size, dilation_rate)), 'sigmoid'
  96.  
  97. h0 = Multiply([hf, hg]) 
  98.  
  99. ha = activation(batchnorm(conv1d(h0, filters, 11)), 'tanh'
  100.  
  101. hs = activation(batchnorm(conv1d(h0, filters, 11)), 'tanh'
  102.  
  103. return Add([ha, inputs]), hs 
  104.  
  105. h0 = activation(batchnorm(conv1d(X, filters, 11)), 'tanh'
  106.  
  107. shortcut =  
  108.  
  109. for i in range(num_blocks): 
  110.  
  111. for r in [124816]: 
  112.  
  113. h0, s = res_block(h0, filters, 7, r) 
  114.  
  115. shortcut.append(s) 
  116.  
  117. h1 = activation(Add(shortcut), 'relu'
  118.  
  119. h1 = activation(batchnorm(conv1d(h1, filters, 11)), 'relu'
  120.  
  121. #softmax損失函數(shù)輸出結(jié)果 
  122.  
  123. Y_pred = activation(batchnorm(conv1d(h1, len(char2id) + 111)), 'softmax'
  124.  
  125. sub_model = Model(inputs=X, outputs=Y_pred) 
  126.  
  127. #計(jì)算損失函數(shù) 
  128.  
  129. def calc_ctc_loss(args): 
  130.  
  131. y, yp, ypl, yl = args 
  132.  
  133. return K.ctc_batch_cost(y, yp, ypl, yl) 

4、模型的訓(xùn)練:
訓(xùn)練的過程如下可見:

 

  1. ctc_loss = Lambda(calc_ctc_loss, output_shape=(1,), name='ctc')([Y, Y_pred, X_length, Y_length]) 
  2.  
  3. #加載模型訓(xùn)練 
  4.  
  5. model = Model(inputs=[X, Y, X_length, Y_length], outputs=ctc_loss) 
  6.  
  7. #建立優(yōu)化器 
  8.  
  9. optimizer = SGD(lr=0.02, momentum=0.9, nesterov=True, clipnorm=5
  10.  
  11. #激活模型開始計(jì)算 
  12.  
  13. model.compile(loss={'ctc'lambda ctc_true, ctc_pred: ctc_pred}, optimizer=optimizer) 
  14.  
  15. checkpointer = ModelCheckpoint(filepath='asr.h5', verbose=0
  16.  
  17. lr_decay = ReduceLROnPlateau(monitor='loss', factor=0.2, patience=1, min_lr=0.000
  18.  
  19. #開始訓(xùn)練 
  20.  
  21. history = model.fit_generator( 
  22.  
  23. generator=batch_generator(X_train, Y_train), 
  24.  
  25. steps_per_epoch=len(X_train) // batch_size, 
  26.  
  27. epochs=epochs, 
  28.  
  29. validation_data=batch_generator(X_test, Y_test), 
  30.  
  31. validation_steps=len(X_test) // batch_size, 
  32.  
  33. callbacks=[checkpointer, lr_decay]) 
  34.  
  35. #保存模型 
  36.  
  37. sub_model.save('asr.h5'
  38.  
  39. #將字保存在pl=pkl中 
  40.  
  41. with open('dictionary.pkl''wb') as fw: 
  42.  
  43. pickle.dump([char2id, id2char, mfcc_mean, mfcc_std], fw) 
  44.  
  45. train_loss = history.history['loss'
  46.  
  47. valid_loss = history.history['val_loss'
  48.  
  49. plt.plot(np.linspace(1, epochs, epochs), train_loss, label='train'
  50.  
  51. plt.plot(np.linspace(1, epochs, epochs), valid_loss, label='valid'
  52.  
  53. plt.legend(loc='upper right'
  54.  
  55. plt.xlabel('Epoch'
  56.  
  57. plt.ylabel('Loss'
  58.  
  59. plt.show 

[[396319]]

測(cè)試模型
讀取我們語音數(shù)據(jù)集生成的字典,通過調(diào)用模型來對(duì)音頻特征識(shí)別。

代碼如下:

  1. wavs = glob.glob('A2_103.wav'
  2.  
  3. print(wavs) 
  4.  
  5. with open('dictionary.pkl''rb') as fr: 
  6.  
  7. [char2id, id2char, mfcc_mean, mfcc_std] = pickle.load(fr) 
  8.  
  9. mfcc_dim = 13 
  10.  
  11. model = load_model('asr.h5'
  12.  
  13. index = np.random.randint(len(wavs)) 
  14.  
  15. print(wavs[index]) 
  16.  
  17. audio, sr = librosa.load(wavs[index]) 
  18.  
  19. energy = librosa.feature.rmse(audio) 
  20.  
  21. frames = np.nonzero(energy >= np.max(energy) / 5
  22.  
  23. indices = librosa.core.frames_to_samples(frames)[1
  24.  
  25. audio = audio[indices[0]:indices[-1]] if indices.size else audio[0:0
  26.  
  27. X_data = mfcc(audio, sr, numcep=mfcc_dim, nfft=551
  28.  
  29. X_data = (X_data - mfcc_mean) / (mfcc_std + 1e-14
  30.  
  31. print(X_data.shape) 
  32.  
  33. pred = model.predict(np.expand_dims(X_data, axis=0)) 
  34.  
  35. pred_ids = K.eval(K.ctc_decode(pred, [X_data.shape[0]], greedy=False, beam_width=10, top_paths=1)[0][0]) 
  36.  
  37. pred_ids = pred_ids.flatten.tolist 
  38.  
  39. print(''.join([id2char[i] for i in pred_ids])) 
  40.  
  41. yield (inputs, outputs) 

到這里,我們整體的程序就搭建完成,下面為我們程序的運(yùn)行結(jié)果:

源碼地址:

https://pan.baidu.com/s/1tFlZkMJmrMTD05cd_zxmAg

提取碼:ndrr

數(shù)據(jù)集需要自行下載。

 

責(zé)任編輯:梁菲 來源: 今日頭條
相關(guān)推薦

2018-05-02 11:38:14

語音識(shí)別法院

2021-06-28 10:06:21

開源文本識(shí)別pyWhat

2020-08-19 09:25:32

Python人臉識(shí)別人工智能

2020-10-23 14:14:54

語音識(shí)別ASR錯(cuò)誤率

2021-06-24 13:15:35

開源技術(shù) 圖像識(shí)別

2022-05-06 10:21:22

Python人臉識(shí)別

2019-06-25 13:47:50

人臉識(shí)別AI人工智能

2025-04-01 09:31:34

PyTorch自動(dòng)語音識(shí)別ASR系統(tǒng)

2019-11-20 12:30:21

Python編程語言語音識(shí)別

2025-04-03 09:30:56

RedisAI模型

2019-12-10 10:40:44

AI 數(shù)據(jù)人工智能

2024-03-04 15:37:39

2022-05-11 07:41:31

Python驗(yàn)證碼

2017-03-27 16:18:30

神經(jīng)網(wǎng)絡(luò)TensorFlow人工智能

2021-12-08 14:06:19

Python語音識(shí)別開發(fā)

2018-05-11 14:10:17

Python人臉識(shí)別

2019-10-23 09:48:46

RedisMySQLMongoDB

2021-11-03 10:49:33

人臉識(shí)別人工智能技術(shù)

2023-05-08 15:48:13

智能音箱鴻蒙

2021-10-02 10:48:05

密碼微軟無密碼登入
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)