語音激活檢測(VAD)--前向神經網絡方法(Alex)

這是學習時的筆記,包含相關資料連接,有的當時沒有細看,記錄下來在須要的時候回顧。html

有些較混亂的部分,後續會再更新。python

歡迎感興趣的小夥伴一塊兒討論,跪求大神指點~linux


VAD(ffnn神經網絡)-Alex

tags:voicegit


Documentation(README)中說如今的NN VAD方法比GMM方法效果好的多。github

Material

Paper

Interesting

神經網絡

Alex

Description

VOIP(voice over Internet protocol)網絡電話

ASR(automatic speech recognition)自動語音識別技術

VAD語音激活檢測

SLU口語理解
    獲取輸入語音信號的語義表示
    
DM對話管理
    決定系統如何回覆給定的用戶輸入, 其模式有多種:rule-based plan-based 基於加強學習的
    
NLG天然語言生成
    對話管理器輸出的是抽象表達,咱們要將其轉換爲句法和語義合法的天然語言,同時考慮上下文連貫性。許多天然語言生成系統是基於模板的,模板的某些成分是固定的,另外一些成分須要根據對話管理器的輸出結果進行填充。(省略表達,句子聚合等。除了基於模板外還有基於統計的方式進行)
    
TTS文本生成語音

Install

pyAudio:這是一個跨平臺的音頻 I/O 庫,使用 PyAudio 你能夠在 Python 程序中播放和錄製音頻。網絡

git clone https://github.com/bastibe/PyAudio.gitapp

flite:在linux下經過flite命令可使用文字轉語音功能。

wget http://www.festvox.org/flite/packed/flite-1.4/flite-1.4-release.tar.bz2

flite -t hello  //讀單詞hello
flite hello  //讀文本hello.txt
flite -voice slt -f hello.txt  //換女聲語音庫

HTK:隱馬爾可夫模型工具包,HTK的開發也主要是針對語音識別的應用及研究。

http://htk.eng.cam.ac.uk/download.shtml

Kaldi:是一個很是強大的語音識別工具庫。目前支持GMM-HMM、SGMM-HMM、DNN-HMM等多種語音識別的模型的訓練和預測。其中DNN-HMM中的神經網絡還能夠由配置文件自定義,DNN、CNN、TDNN、LSTM以及Bidirectional-LSTM等神經網絡結構都可支持。

$ git clone https://github.com/kaldi-asr/kaldi

SRILM:用來構建和應用統計語言模型,主要用於語音識別,統計標註和切分,以及機器翻譯,可運行在UNIX及Windows平臺上。支持語言模型的估計和評測。估計是從訓練數據(訓練集)中獲得一個模型,包括最大似然估計及相應的平滑算法;而評測則是從測試 集中計算其困惑度。

http://www.speech.sri.com/projects/srilm/

pjsip:是一個開源的SIP協議庫。PJSIP做爲基於SIP的一個多媒體通訊框架提供了很是清晰的API,以及NAT穿越的功能。PJSIP具備很是好的移植性,幾乎支持現今全部系統:從桌面系統、嵌入式系統到智能手機。

git clone git@github.com:UFAL-DSG/pjsip.git

MorphoDiTa:天然語言文本的形態學分析。

git clone git@github.com:ufal/morphodita.git

python讀.wav文件

# -*- coding: utf-8 -*-  
import wave  
import numpy   
import pylab as pl  
  
#打開wav文件  
#open返回一個的是一個Wave_read類的實例,經過調用它的方法讀取WAV文件的格式和數據  
f = wave.open(r"D:\1.wav","rb")  
  
#讀取格式信息  
#一次性返回全部的WAV文件的格式信息,它返回的是一個組元(tuple):聲道數, 量化位數(byte單位), 採  
#樣頻率, 採樣點數, 壓縮類型, 壓縮類型的描述。wave模塊只支持非壓縮的數據,所以能夠忽略最後兩個信息  
params = f.getparams()  
nchannels, sampwidth, framerate, nframes = params[:4]  
  
#讀取波形數據  
#讀取聲音數據,傳遞一個參數指定須要讀取的長度(以取樣點爲單位)  
str_data  = f.readframes(nframes)  
f.close()  
  
#將波形數據轉換成數組  
#須要根據聲道數和量化單位,將讀取的二進制數據轉換爲一個能夠計算的數組  
wave_data = numpy.fromstring(str_data,dtype = numpy.short)  
wave_data.shape = -1,2  
wave_data = wave_data.T  
time = numpy.arange(0,nframes)*(1.0/framerate)  
len_time = len(time)/2  
time = time[0:len_time]  
  
##print "time length = ",len(time)  
##print "wave_data[0] length = ",len(wave_data[0])  
  
#繪製波形  
  
pl.subplot(211)  
pl.plot(time,wave_data[0])  
pl.subplot(212)  
pl.plot(time, wave_data[1],c="r")  
pl.xlabel("time")  
pl.show()

train model

生成.mlf

  1. 語音標記
    alex/tools/vad_train/data_voip/*.txt
  2. 生成.mlf
"alex/tools/htk/bin/make_mlf_train.sh"
#!/bin/bash
WORK_DIR=alex/tools/vad_train
TRAIN_DATA=$WORK_DIR/data_voip
TRAIN_SCRIPTS=alex/tools/htk/bin
LOG_DIR=$WORK_DIR/model_voip
TEMP_DIR=$WORK_DIR/temp
find $TRAIN_DATA -iname '*.mfc' > $WORK_DIR/train_mfc_files.txt
python $TRAIN_SCRIPTS/CreateMLF.py "-" $WORK_DIR/train_words.mlf $WORK_DIR/train.scp $TRAIN_DATA $TRAIN_DATA'/*.txt' > $LOG_DIR/train_missing_words.log

"alex/tools/htk/bin/CreateMLF.py"
部分修改以下:
for fn in fns:
    with open(fn, 'r') as f:
        lines = f.readlines()
        lines = ''.join(lines)  //把本來''中的空格去掉
        words = lines.strip().split('\n')  //本來split默認按空格切分,改成按轉行符切分

# 運行
~/path/to/VAD/alex-master$ sh alex/tools/htk/bin/make_mlf_train.sh 

#生成.mlf
#!MLF!#
"alex/tools/vad_train/data_voip/2.txt"
0    19296    sil
19296    37600    speech
37600    57248    sil
.
"alex/tools/vad_train/data_voip/1.txt"
0 14400 sil
14400 23200 speech
23200 49984 sil
.

訓練模型

"path/to/VAD/alex-master/alex/tools/vad/train_vad_nn_theano.py"
# 1.train_vad_nn_theano.py
# load_mlf改成
    #mlf.times_to_frames()
    mlf.bits_to_frames(16000)
    mlf.trim_segments(trim_segments)
    //trim_segments如今是0,能夠修改成n(1/2/3)
    //表示刪除end-start(幀)<=2n部分,較短部分不進行訓練
    
# main文件地址
    train_speech.append('alex/tools/vad_train/data_voip/*.wav')
    train_speech_alignment.append('alex/tools/vad_train/train_words.mlf')
     features_file_name = "alex/tools/vad_train/model_voip/vad_sds_mfcc_mfr%d_mfl%d_mfps%d_ts%d_usec0%d_usedelta%d_useacc%d_mbo%d.npc" % \
            (max_frames, max_files, max_frames_per_segment, trim_segments,
            usec0, usedelta, useacc, mel_banks_only)
    
# 2.htk.py
# .mlf中的bit值轉幀(注意:窗口移動值是frame_shift,與targetrate相關)
def bits_to_frames(self, sample_rate):
    self.frame_shift = int(sample_rate * self.targetrate / 10000000)
        for f in self.mlf:
            for i in range(len(self.mlf[f])):
                self.mlf[f][i][0] = int(self.mlf[f][i][0] / self.frame_shift)   
                self.mlf[f][i][1] = int(self.mlf[f][i][1] / self.frame_shift)
            ## 後面的不加會致使錯誤4    
            # shorten the last segment by 10 frames as there may not be enough data for a final frame
            self.mlf[f][i][1] -= 10

            # remove the zero or negative length segments that could be created by the previous step
            if self.mlf[f][i][0] >= self.mlf[f][i][1]:
                del self.mlf[f][i]

# 3.log錯誤
 Traceback
 File "./alex/tools/vad/train_vad_nn_theano.py", line 316, in train_nn
    e.train(method = method, learning_rate=learning_rate*learning_rate_decay/(learning_rate_decay+epoch))
  File "/path/to/VAD/alex-master/alex/ml/tffnn.py", line 302, in train
    log_lik = self.f_train_ret_loss(mini_x, mini_y, learning_rate)

 TypeError: ('Bad input argument to theano function with name "/path/to/VAD/alex-master/alex/ml/tffnn.py:131"  at index 2(0-based)', 'TensorType(float32, scalar) cannot store accurately value 0.019801980198, it would be represented as 0.0198019798845. If you do not mind this precision loss, you can: 1) explicitly convert your data to a numpy array of dtype float32, or 2) set "allow_input_downcast=True" when calling "function".', 0.019801980198019802)

# 修改tffnn.py
self.f_train_ret_loss = function([x, true_y, learning_rate], loss, updates = updates, allow_input_downcast=True)

# 4. htk.py 最後frame不足512個語音節點問題
ValueError: operands could not be broadcast together with shapes (512,) (465,)
# 修改(失敗)
MLFMFCCOnlineAlignedArray(MLFFeaturesAlignedArray):
def __init__(+ framesize=512)
self.framesize=framesize

def get_frame(self, file_name, frame_id):
    if len(frame) == self.framesize:
        try:
            mfcc_params = self.mfcc_front_end.param(frame)
        except ValueError:
            print file_name, frame_id, len(frame)
            raise
    else:
        pass
    return mfcc_params
//進行mfcc_front_end.param前先判斷frame是否足幀,不足幀捨棄
UnboundLocalError: local variable 'mfcc_params' referenced before assignment
# 錯誤,當len(frame) != framesize時執行else後的pass,此時沒有mfcc_params變量
# pass改爲exit()則會致使執行exit()時整個程序中止。因此放棄該改動方法。
# 修改辦法見代碼2

## 運行
$ cd /path/to/VAD/alex-master
$ python alex/tools/vad/train_vad_nn_theano.py
  1. 爲何len(mfcc[0])=26
  2. 語音en和cs分別指什麼————指English 和 Chinese

使用模型進行檢測

"path/to/VAD/alex-master/alex/components/vad/__init__.py"
#!/usr/bin/env python
# coding: utf-8

import sys
sys.path.append("/path/to/VAD/alex-master")

import wave
import numpy as np
from alex.components.vad.ffnn import FFNNVADGeneral, FFNNVAD
from alex.utils.htk import Features

def main():

    f = wave.open(r"/path/to/VAD/sound/12.wav","rb")  
       
    soundParams = f.getparams()  
    nchannels, sampwidth, framerate, nframes = soundParams[:4]  

    str_data  = f.readframes(nframes)  
    f.close()  
    # wave_data = np.fromstring(str_data,dtype = np.short)  
    # ffnn.py文件中調用的是原始語音,是c語言數據格式,因此不用這一步。
    # ffnn.py中的struct.unpack進行數據格式轉換,由c轉換成python
    
    vad = FFNNVADGeneral('/path/to/VAD/alex-master/alex/tools/vad_train/model_voip/vad_nnt_546_hu32_hl1_hla0_pf10_nf10_acf_1.0_mfr20000_mfl20000_mfps0_ts0_usec00_usedelta0_useacc0_mbo1_bs1000.tffnn', 
            filter_length=2, sample_rate=16000, framesize=512, frameshift=160,
            usehamming=True, preemcoef=0.97, numchans=26, ceplifter=22, numceps=12, 
            enormalise=True, zmeansource=True, usepower=True, usec0=False, 
            usecmn=False, usedelta=False, useacc=False, n_last_frames=10, 
            n_prev_frames=10, lofreq=125, hifreq=3800, mel_banks_only=True)

    result = vad.decide(str_data)
    
if __name__ == "__main__":
    main()

# 運行
$ cd path/to/VAD/alex-master
$ python alex/components/vad/__init__.py >alex/components/vad/output/output*.txt

# 圖形化
$ gnuplot
$ plot "/path/to/VAD/alex-master/alex/components/vad/output/output*.txt" using 4:6 title "*.wav:time-prob" with line

(若非特別聲明,文章是Vanessa的我的筆記,轉載請註明出處。文章若有侵權內容,請聯繫我,我會及時刪除)

相關文章
相關標籤/搜索