最近公司要上语音识别的功能,想着最近tensorflow比较火热,遍着手开始研究,网上也找了很多的案例,一一去实现,结果一直都出各种问题,比如tensorflow版本不一样,或者数据集不可用,或者准确率极低,或者是看的我云里雾里的一些问题 等各种坑爹的问题,后面经过一些整理和修改,这里记录一下:
使用的训练数据
已上传百度网盘,直接下载,没有密码:https://pan.baidu.com/s/1Au85kI_oeDjode2hWumUvQ
开发环境
tensorflow 1.9.0
python 3.6.6
numpy 1.15.0
librosa 0.6.2
代码
训练的代码
#coding=utf-8
import tensorflow as tf
import numpy as np
import os
from collections import Counter
import librosa
import time
# 训练样本路径【这里我单独选择了 seven 语音的包】
wav_path = 'D:/AI/seven/'
# 语音文件对应的标签
wav_title='seven'
# 获得训练用的wav文件路径列表
def get_wave_files(wav_path=wav_path):
wav_files = []
for (dirpath,dirnames,filenames) in os.walk(wav_path):#访问文件夹下的所有文件
#os.walk() 方法用于通过在目录树种游走输出在目录中的文件名,向上或者向下
for filename in filenames:
if filename.endswith('.wav') or filename.endswith('.WAV'):
#endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False
filename_path = os.sep.join([dirpath,filename])#定义文件路径(连)
# print(os.stat(filename_path).st_size)
# if os.stat(filename_path).st_size < 32000:#st_size文件的大小,以位为单位
# continue
wav_files.append(filename_path)#加载文件
return wav_files
wav_files = get_wave_files()#获取文件名列表
#读取wav文件对应的label
def get_wav_label(wav_files=wav_files):
labels=[]
new_wav_files = []
for wav_file in wav_files:
wav_id = os.path.basename(wav_file).split('.')[0]
labels.append(wav_title)# 每条语音对应的标签
new_wav_files.append(wav_file)
return new_wav_files,labels#返回标签和对应的文件
wav_files,labels = get_wav_label()#得到标签和对应的语音文件
print("加载训练样本:",time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
print("样本数:",len(wav_files))
#词汇表(参考对话、诗词生成)
all_words = []
for label in labels:
all_words += [word for word in label]
counter = Counter(all_words)
count_pairs =sorted(counter.items(),key=lambda x: -x[1])
words,_=zip(*count_pairs)
words_size =len(words)#词汇表尺寸
print('词汇表大小:',words_size)
#词汇映射成id表示
word_num_map = dict(zip(words,range(len(words))))
to_num = lambda word: word_num_map.get(word,len(words))#词汇映射函数
labels_vector =[list(map(to_num,label)) for label in labels]
label_max_len= np.max([len(label) for label in labels_vector])#获取最长字数
print('最长句子的字数:',label_max_len)
wav_max_len=0
for wav in wav_files:
wav,sr = librosa.load(wav,mono=True)#处理语音信号的库librosa
#加载音频文件作为a floating point time series.(可以是wav,mp3等格式)mono=True:signal->mono
mfcc=np.transpose(librosa.feature.mfcc(wav,sr),[1,0])#转置特征参数
#librosa.feature.mfcc特征提取函数
if len(mfcc)>wav_max_len:
wav_max_len = len(mfcc)
print("最长的语音:",wav_max_len)
batch_size=100#每批次取100个文件
n_batch = len(wav_files)//batch_size#总批次数
pointer =0#全局变量初值为0,定义该变量用以逐步确定batch
def get_next_batches(batch_size):
global pointer
batches_wavs = []
batches_labels = []
for i in range(batch_size):
wav,sr=librosa.load(wav_files[pointer],mono=True)
mfcc =np.transpose(librosa.feature.mfcc(wav,sr),[1,0])
batches_wavs.append(mfcc.tolist())#转换成列表表存入
batches_labels.append(labels_vector[pointer])
pointer+=1
#补0对齐
for mfcc in batches_wavs:
while len(mfcc)<wav_max_len:
mfcc.append([0]*20)#补一个全0列表
for label in batches_labels:
while len(label)<label_max_len:
label.append(0)
return batches_wavs,batches_labels
X=tf.placeholder(dtype=tf.float32,shape=[batch_size,None,20])#定义输入格式
sequence_len = tf.reduce_sum(tf.cast(tf.not_equal(tf.reduce_sum(X,reduction_indices=2), 0.), tf.int32), reduction_indices=1)
Y= tf.placeholder(dtype=tf.int32,shape=[batch_size,None])#输出格式
#第一层卷积
conv1d_index = 0
def conv1d_layer(input_tensor,size,dim,activation,scale,bias):