基于mfcc的实现音乐分类的python代码,包括提供数据集
时间: 2024-02-26 07:54:46 浏览: 149
以下是一个基于MFCC的音乐分类Python代码示例:
```python
import librosa
import numpy as np
import os
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
# 定义MFCC参数
n_mfcc = 20
n_fft = 2048
hop_length = 512
# 加载数据集和标签
def load_data(path):
mfccs = []
labels = []
for filename in os.listdir(path):
label = filename.split('.')[0]
filename = os.path.join(path, filename)
audio, sr = librosa.load(filename)
mfcc = librosa.feature.mfcc(audio, sr=sr, n_mfcc=n_mfcc, n_fft=n_fft, hop_length=hop_length)
mfccs.append(mfcc)
labels.append(label)
return mfccs, labels
# 加载数据集
X, y = load_data('dataset')
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 将MFCC特征转换为一维向量
X_train = np.array([mfcc.reshape(-1) for mfcc in X_train])
X_test = np.array([mfcc.reshape(-1) for mfcc in X_test])
# 训练模型
model = MLPClassifier(hidden_layer_sizes=(256, 128), max_iter=300)
model.fit(X_train, y_train)
# 在测试集上评估模型性能
accuracy = model.score(X_test, y_test)
print("Test accuracy:", accuracy)
```
在这个示例中,我们使用Librosa库来计算MFCC特征,使用Sklearn库中的多层感知机(MLP)分类器来训练模型。这个示例使用的数据集可以从以下链接下载:https://github.com/llSourcell/Music_Genre_Classification_demo/tree/master/data
阅读全文