基礎語音識別-食物語音識別baseline(CNN)
MFCC
梅爾倒譜系數(shù)(Mel-scaleFrequency Cepstral Coefficients,簡稱MFCC)。
MFCC通常有以下之過程:
- 將一段語音信號分解為多個訊框。
- 將語音信號預強化,通過一個高通濾波器。
- 進行傅立葉變換,將信號變換至頻域。
- 將每個訊框獲得的頻譜通過梅爾濾波器(三角重疊窗口),得到梅爾刻度。
- 在每個梅爾刻度上提取對數(shù)能量。
- 對上面獲得的結果進行離散傅里葉反變換,變換到倒頻譜域。
- MFCC就是這個倒頻譜圖的幅度(amplitudes)。一般使用12個系數(shù),與訊框能量疊加得13維的系數(shù)。
數(shù)據(jù)集
數(shù)據(jù)集來自Eating Sound Collection,數(shù)據(jù)集中包含20種不同食物的咀嚼聲音,賽題任務是給這些聲音數(shù)據(jù)建模,準確分類。
類別包括: aloe, ice-cream, ribs, chocolate, cabbage, candied_fruits, soup, jelly, grapes, pizza, gummies, salmon, wings, burger, pickles, carrots, fries, chips, noodles, drinks
訓練集的大小: 750
測試集的大小: 250
1 下載和解壓數(shù)據(jù)集
!wget http://tianchi-competition.oss-cn-hangzhou.aliyuncs.com/531887/train_sample.zip !unzip -qq train_sample.zip !\rm train_sample.zip !wget http://tianchi-competition.oss-cn-hangzhou.aliyuncs.com/531887/test_a.zip !unzip -qq test_a.zip !\rm test_a.zip
2 加載庫函數(shù)
# 基本庫 import pandas as pd import numpy as np from sklearn.model_selection import train_test_split #劃分數(shù)據(jù)集 from sklearn.metrics import classification_report #用于顯示主要分類指標的文本報告 from sklearn.model_selection import GridSearchCV #自動調(diào)參 from sklearn.preprocessing import MinMaxScaler #歸一化
加載深度學習框架
# 搭建分類模型所需要的庫 from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, Flatten, Dense, MaxPool2D, Dropout from tensorflow.keras.utils import to_categorical from sklearn.ensemble import RandomForestClassifier from sklearn.svm import SVC #支持向量分類 !pip install librosa --user #加載音頻處理庫 # 其他庫 import os import librosa #音頻處理庫 import librosa.display import glob
3 特征提取以及數(shù)據(jù)集的建立
建立類別標簽字典
feature = [] label = [] # 建立類別標簽,不同類別對應不同的數(shù)字。 label_dict = {'aloe': 0, 'burger': 1, 'cabbage': 2,'candied_fruits':3, 'carrots': 4, 'chips':5, 'chocolate': 6, 'drinks': 7, 'fries': 8, 'grapes': 9, 'gummies': 10, 'ice-cream':11, 'jelly': 12, 'noodles': 13, 'pickles': 14, 'pizza': 15, 'ribs': 16, 'salmon':17, 'soup': 18, 'wings': 19} label_dict_inv = {v:k for k,v in label_dict.items()}
提取梅爾頻譜特征
from tqdm import tqdm def extract_features(parent_dir, sub_dirs, max_file=10, file_ext="*.wav"): c = 0 label, feature = [], [] for sub_dir in sub_dirs: for fn in tqdm(glob.glob(os.path.join(parent_dir, sub_dir, file_ext))[:max_file]): # 遍歷數(shù)據(jù)集的所有文件 # segment_log_specgrams, segment_labels = [], [] #sound_clip,sr = librosa.load(fn) #print(fn) label_name = fn.split('/')[-2] label.extend([label_dict[label_name]]) X, sample_rate = librosa.load(fn,res_type='kaiser_fast') mels = np.mean(librosa.feature.melspectrogram(y=X,sr=sample_rate).T,axis=0) # 計算梅爾頻譜(mel spectrogram),并把它作為特征 feature.extend([mels]) return [feature, label]
# 自己更改目錄 parent_dir = './train_sample/' save_dir = "./" folds = sub_dirs = np.array(['aloe','burger','cabbage','candied_fruits', 'carrots','chips','chocolate','drinks','fries', 'grapes','gummies','ice-cream','jelly','noodles','pickles', 'pizza','ribs','salmon','soup','wings']) # 獲取特征feature以及類別的label temp = extract_features(parent_dir,sub_dirs,max_file=100) temp = np.array(temp) data = temp.transpose()
獲取特征和標簽
# 獲取特征 X = np.vstack(data[:, 0]) # 獲取標簽 Y = np.array(data[:, 1]) print('X的特征尺寸是:',X.shape) print('Y的特征尺寸是:',Y.shape)
X的特征尺寸是: (1000, 128)
Y的特征尺寸是: (1000,)
獨熱編碼
# 在Keras庫中:to_categorical就是將類別向量轉(zhuǎn)換為二進制(只有0和1)的矩陣類型表示 Y = to_categorical(Y) print(X.shape) print(Y.shape)
(1000, 128)
(1000, 20)
把數(shù)據(jù)集劃分為訓練集和測試集
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, random_state = 1, stratify=Y) print('訓練集的大小',len(X_train)) print('測試集的大小',len(X_test))
訓練集的大小 750
測試集的大小 250
X_train = X_train.reshape(-1, 16, 8, 1) X_test = X_test.reshape(-1, 16, 8, 1)
4 建立模型
搭建CNN網(wǎng)絡
model = Sequential() # 輸入的大小 input_dim = (16, 8, 1) model.add(Conv2D(64, (3, 3), padding = "same", activation = "tanh", input_shape = input_dim))# 卷積層 model.add(MaxPool2D(pool_size=(2, 2)))# 最大池化 model.add(Conv2D(128, (3, 3), padding = "same", activation = "tanh")) #卷積層 model.add(MaxPool2D(pool_size=(2, 2))) # 最大池化層 model.add(Dropout(0.1)) model.add(Flatten()) # 展開 model.add(Dense(1024, activation = "tanh")) model.add(Dense(20, activation = "softmax")) # 輸出層:20個units輸出20個類的概率 # 編譯模型,設置損失函數(shù),優(yōu)化方法以及評價標準 model.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy']) model.summary()
訓練模型
# 訓練模型 model.fit(X_train, Y_train, epochs = 100, batch_size = 15, validation_data = (X_test, Y_test))
5 預測測試集
def extract_features(test_dir, file_ext="*.wav"): feature = [] for fn in tqdm(glob.glob(os.path.join(test_dir, file_ext))[:]): # 遍歷數(shù)據(jù)集的所有文件 X, sample_rate = librosa.load(fn,res_type='kaiser_fast') mels = np.mean(librosa.feature.melspectrogram(y=X,sr=sample_rate).T,axis=0) # 計算梅爾頻譜(mel spectrogram),并把它作為特征 feature.extend([mels]) return feature X_test = extract_features('./test_a/') X_test = np.vstack(X_test) predictions = model.predict(X_test.reshape(-1, 16, 8, 1)) preds = np.argmax(predictions, axis = 1) preds = [label_dict_inv[x] for x in preds] path = glob.glob('./test_a/*.wav') result = pd.DataFrame({'name':path, 'label': preds}) result['name'] = result['name'].apply(lambda x: x.split('/')[-1]) result.to_csv('submit.csv',index=None) !ls ./test_a/*.wav | wc -l !wc -l submit.csv
6 結果
到此這篇關于基礎語音識別-食物語音識別baseline(CNN)的文章就介紹到這了,更多相關語音識別的內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持腳本之家!
相關文章
Python實現(xiàn)大數(shù)據(jù)收集至excel的思路詳解
這篇文章主要介紹了Python實現(xiàn)大數(shù)據(jù)收集至excel的思路,本文通過完整代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-01-01Python實戰(zhàn)基礎之Pandas統(tǒng)計某個數(shù)據(jù)列的空值個數(shù)
我們在處理數(shù)據(jù)的時候,經(jīng)常需要檢查數(shù)據(jù)的質(zhì)量,也需要知道出問題的數(shù)據(jù)在哪個位置,下面這篇文章主要給大家介紹了關于Python實戰(zhàn)基礎之利用Pandas統(tǒng)計某個數(shù)據(jù)列空值個數(shù)的相關資料,需要的朋友可以參考下2022-08-08詳解Python如何利用pdfplumber提取PDF中的表格
pdfplumber 是一個開源的 python 工具庫 ,它可以輕松的獲取 PDF 文本內(nèi)容、標題、表格、尺寸等各種信息,今天來介紹如何使用它來提取 PDF 中的表格,文中通過代碼和圖片講解的非常詳細,需要的朋友可以參考下2024-04-04基于python + django + whoosh + jieba 分詞器實現(xiàn)站內(nèi)檢索功能
這篇文章主要介紹了基于python + django + whoosh + jieba 分詞器實現(xiàn)站內(nèi)檢索功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-08-08