逻辑回归练习(音乐分析)
问题详情
根据已给的数据预测出测试数据的音乐风格
代码实现
'''
Date:2019-08-04 16:53
User:ChenXi
E-mail:15091630326@163.com
'''
import numpy as np
from sklearn.linear_model import LogisticRegression
from scipy import fft
from scipy.io import wavfile
from tqdm import tqdm
# 准备音乐数据
def create_fit(g, n):
# zfill返回指定长度的字符串,原字符串右对齐,前面填充0
rad = './genres/' + g + '/converted/' + g + '.' + str(n).zfill(5) + '.au.wav'
# sample_rate:采样率
# 模电(连续的信号)变数电(数字的表达)
# 采样率越高,如果单位时间采样点越多,信息损失的越少
# x是音乐文件
sample_rate, X = wavfile.read(rad)
fft_features = abs(fft(X)[:1000])
sad = './genres/' + g + '.' + str(n).zfill(5) + '.fft'
np.save(sad, fft_features)
if __name__ == '__main__':
genre_list = ["classical", "blues", "country", "disco"]
X, Y = [], []
for g in tqdm(genre_list):
for n in range(100):
rad = "./genres/"+g + "." + str(n).zfill(5) + ".fft.npy"
fft_features = np.load(rad)
X.append(fft_features)
Y.append(genre_list.index(g))
X = np.array(X)
Y = np.array(Y)
# test file
rad_test = "wudizirong" + ".fft.npy"
fft_features = np.load(rad_test)
X_test = np.array([fft_features])
# study
log_reg = LogisticRegression(multi_class='ovr', solver='sag')
log_reg.fit(X, Y)
print(log_reg.score(X, Y))
print(log_reg.predict(X_test))
#
# #处理测试数据
# rad_test = "./genres/heibao-wudizirong-remix.wav"
# sample_rate, X_test = wavfile.read(rad_test)
# fft_features = abs(fft(X_test)[:1000])
# sad = 'wudizirong' + ".fft"
# np.save(sad, fft_features)