[Audio processing] 数据集生成 & 性别年龄分类训练 Python
1、重命名,Python中文路径各种错误,所以需要先将所有文件的路径名全都改成中文。用的是MAC系统,所以WIN下的命令行批处理没法解决,所以用C来完成
// Created by Carl on 16.
// Copyright (c) 2016年 Carl. All rights reserved.
// #include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
using namespace std; void getFileList()
{
string sourceDir = "/Users/karl/Work/database/rawdata/children_CN/";
string targetDir = "/Users/karl/Work/database/rawdata/children/";
DIR *dir;
struct dirent *ptr;
int i = ;
if ((dir=opendir(sourceDir.c_str())) == NULL)
{
perror("Open dir error...");
exit();
}
while ((ptr=readdir(dir)) != NULL)
{
if(strcmp(ptr->d_name,".")== || strcmp(ptr->d_name,"..")==) ///current dir OR parrent
continue;
else if(ptr->d_type == )
{
printf("%s %s\n",(sourceDir + ptr->d_name).c_str(),(targetDir + to_string(i) + ".wav").c_str());
if(rename((sourceDir + ptr->d_name).c_str(), (targetDir + to_string(i++) + ".wav").c_str())<)
cout<<"error"<<endl;
else
cout<<"ok"<<endl;
} }
return;
} int main() {
getFileList();
return ;
}
2、然后再使用FFMPEG那篇文章写的Python代码,将所有音频文件转成统一格式
#coding=utf-8
#!/usr/bin/env python
'''CREATED:2016-03-08
Use example of ffmpeg
'''
import argparse
import sys
import os
import string
import subprocess as sp #Full path of ffmpeg
FFMPEG_BIN = "/Users/karl/Documents/python/audio/tool/ffmpeg"
#Full path of sourceDir
sourceDir = "/Users/karl/Work/database/rawdata/male/"
#Full path of targetDir
targetDir = "/Users/karl/Work/database/age/male/"
#Channel setting 1 for mono
ac = 1
#Sample frequency
sf = 16000
#Extension setting
ext = 'wav' def convert(sourceDir, targetDir, ac, sf, ext):
i = 0
if not os.path.exists(targetDir):
os.mkdir(targetDir)
files = os.listdir(sourceDir)
for f in files:
if f.endswith('.wav'):
command = [ FFMPEG_BIN,
'-i', os.path.join(sourceDir, f),
'-ac', str(ac),
'-ar', str(sf), os.path.join(targetDir, str(i) + "." + ext)]
i += 1
print command
pipe = sp.Popen(command, stdout = sp.PIPE, bufsize = 10**8) if __name__ == '__main__':
convert(sourceDir, targetDir, ac, sf, ext)
3、用时域上RMS去除静音帧(Optional)
#---Cut the silent head and tail of audio
def rmsdemo(y):
return np.sqrt((y**2).mean()) def cutheadntail(y, winlen, threshold):
totallen = y.shape[0]
num = totallen / winlen
i = 1
j = num
for i in range(num):
if rmsdemo(y[i * winlen : (i + 1) * winlen - 1]) > threshold:
break
for j in range(-1,0,-1):
if rmsdemo(y[i * winlen : (i + 1) * winlen - 1]) > threshold or j == i:
break
#percentage = (j - i + 1) * 1.0 / num;
#print(i, j, percentage)
yy = y[i * winlen : (j + 1) * winlen - 1]
return yy
4、用librosa提取特征,包括MFCC、DMFCC
from __future__ import print_function
import argparse
import sys
import os
import pprint
import sklearn as sl
import numpy as np
import librosa
import librosa.feature.spectral as f
import svmutil #---Feature extraction and store, including MFCC, DMFCC
def mfcclist(data_dir):
m = []
dm = []
for i in range(300):
filepath = os.path.join(data_dir, str(i) + '.wav')
print(filepath)
am, adm = mfccfile(filepath)
m.append(am)
dm.append(adm)
i += 1
np.savetxt("TrainFemaleMFCC",m,fmt='%s',newline='\n')
np.savetxt("TrainFemaleDMFCC",dm,fmt='%s',newline='\n')
#print(m)
#print(dm)
'''
fout = open(output_file,'w')
fout.write(str(am) + '\n')
fout.write(str(adm))
fout.close()
''' def mfccfile(input_file):
print('Loading ', input_file)
y, sr = librosa.load(input_file)
M = f.mfcc(y, sr, None, 13)
DM = M[::,1::] - M[::,0:-1:1]
am = np.mean(M, axis = 1)
adm = np.mean(DM, axis = 1)
return (am, adm) #---Loading stored features file
def loadfeatures(features_file):
fin = open(features_file, 'r')
features = [map(float,ln.strip().split(' '))
for ln in fin.read().splitlines() if ln.strip()]
#pprint.pprint(features)
print(features)
5、用libsvm训练和预测,包括归一化
#---SVM training and predicting process
def svmtraindemo(x, modelname, scalar):
x = scalar.transform(x)
#x = sl.preprocessing.scale(x)
x = x.tolist()
print(x)
y = [1.0] * 300 + [1] * 300 + [-1.0] * 600
model = svm_train(y, x, '-b 1')
svm_save_model(modelname + str(0), model)
p_label, p_acc, p_val = svm_predict(y[:1200], x[:1200], model, '-b 1') def svmpredictdemo(x, modelname, scalar):
x = scalar.transform(x)
#x = sl.preprocessing.scale(x)
x = x.tolist()
print(len(x))
y = [1.0] * 100 + [1] * 100 + [-1.0] * 200
m = svm_load_model(modelname + str(0))
print(p_label)
p_label, p_acc, p_val = svm_predict(y[:400], x[:400], m, '-b 1')
附:
1、经过试验,发现用无监督的方式,准确来说是基于规则的方式分辨男、女、小孩的声音还是不太靠谱,频域上的分布还是用有监督的方式自己学习应该更可靠。
2、用有噪音的推无噪音的小孩,准确率80%,无噪音推有噪音的,准确率才60+%,所以训练还是最好用噪音环境的数据集吧,之前想的是训练应该用无噪音的样本还是太天真了。其实混合起来效果还不错。
3、男女的准确率也就80%,样本分布还是比较好,而且均有噪音,估计在实际应用中效果也不会比80%差太远。
[Audio processing] 数据集生成 & 性别年龄分类训练 Python的更多相关文章
- keras系列︱图像多分类训练与利用bottleneck features进行微调(三)
引自:http://blog.csdn.net/sinat_26917383/article/details/72861152 中文文档:http://keras-cn.readthedocs.io/ ...
- 使用Python基于TensorFlow的CIFAR-10分类训练
TensorFlow Models GitHub:https://github.com/tensorflow/models Document:https://github.com/jikexueyua ...
- 编程语言分类及python所属类型
编程语言分类及python所属类型 编程语言主要从以下几个角度为进行分类:编译型和解释型.静态语言和动态语言.强类型定义语言和弱类型定义语言. 编译和解释的区别是什么? 编译器是把源程序的每一条语句都 ...
- day02-操作系统、编程语言分类及python安装
目录 操作系统 编程语言分类 安装python解释器 操作系统 操作系统有什么用 操作系统能接受外部指令转化成0和1,并把一些对硬件的复杂操作简化成一个个简单的接口,作为中间人连接硬件和软件 计算机三 ...
- Python生成文本格式的excel\xlwt生成文本格式的excel\Python设置excel单元格格式为文本\Python excel xlwt 文本格式
Python生成文本格式的excel\xlwt生成文本格式的excel\Python设置excel单元格格式为文本\Python excel xlwt 文本格式 解决: xlwt 中设置单元格样式主要 ...
- ctpn+crnn 训练数据集生成
1. https://github.com/Belval/TextRecognitionDataGenerator 2. https://textrecognitiondatagenerator.re ...
- 利用keras自带路透社数据集进行多分类训练
import numpy as np from keras.datasets import reuters from keras import layers from keras import mod ...
- 利用keras自带影评数据集进行评价正面与否的二分类训练
from keras.datasets import imdb from keras import layers from keras import models from keras import ...
- Tensorflow2 自定义数据集图片完成图片分类任务
对于自定义数据集的图片任务,通用流程一般分为以下几个步骤: Load data Train-Val-Test Build model Transfer Learning 其中大部分精力会花在数据的准备 ...
随机推荐
- JAVA DATE解析(时间戳解析为固定格式)
public class SimpleDateFormat extends DateFormat SimpleDateFormat 是一个以国别敏感的方式格式化和分析数据的具体类. 它允许格式化 (d ...
- jquery 银行卡号验证
具体参考:https://github.com/jondavidjohn/payform 插件js: jquery.payform.js 具体操作 alert($.payform.validateCa ...
- GridView中某一列值的总和(web)
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.R ...
- MSSQLSERVER未分离LDF删除情况下的MDF附加
经过网上资料搜索,此方法可以解决. LDF日志不要轻易删除,恢复主数据要用到,如果删除,记得先分离,然后移动到另外的地方. 下面是针对未分离删除日志文件,MDF文件附加,提示找不到日志的问题的解决方法 ...
- 生成四位随机数的PHP代码
纯数字的四位随机数 rand(1000,9999) 数字和字符混搭的四位随机字符串: function GetRandStr($len) { $chars = array( "a" ...
- Fatal error: Class 'ZipArchive' not found的解决办法
今天在Linux底下编写导出EXCEL文件并显示输出时,抛出“ZipArchive library is not enabled” 的异常.而我在本地的windows下的代码则是运行正常的. 原因是: ...
- Flask-SQLALchemy查询
from: http://blog.sina.com.cn/s/blog_633277f90100kpvm.html 似乎ORM最难设计的部分是查询.特别是面向对象的查询,今天学习SQLAlchemy ...
- ObjectiveC1基础代码——类和对象
// // main.m // ObjectiveC1 // // Created by scjy on 15/10/30. // Copyright © 2015年 lizhipeng. A ...
- bzoj3541: Spoj59 Bytelandian Information Agency
Description BIA机构内部使用一个包含N台计算机的网络.每台计算机被标号为1..N,并且1号机是服务器.计算机被一些单向传输线连接着,每条数据线连接两台计算机.服务器可以向任 ...
- libcurl的封装,支持同步异步请求,支持多线程下载,支持https
最近在做一个项目,需要用到http get post等 需求分析需要做到同步和异步,异步请求的返回以可选的回调通知的方式进行. 本人以Linux为例,一步一步的来实现. 配置并且编译libcurl我以 ...