Python實現(xiàn)WAV音頻分析與線性回歸建模
1. 音頻數(shù)據(jù)處理流程
1.1 WAV文件讀取與預(yù)處理
使用scipy.io.wavfile讀取音頻文件,獲取采樣率與時域信號數(shù)據(jù):
from scipy.io import wavfile
sample_rate, audio_data = wavfile.read("sound/cat/1-47819-C-5.wav")
- 自動識別單聲道/立體聲:單聲道返回一維數(shù)組,立體聲返回二維數(shù)組(左/右聲道)
- 關(guān)鍵指標(biāo):采樣率(Hz)、數(shù)據(jù)類型(如int16)、數(shù)據(jù)形狀(樣本數(shù)×聲道數(shù))
1.2 聲道分離與標(biāo)準(zhǔn)化
# 立體聲分離 left_channel = audio_data[:, 0] right_channel = audio_data[:, 1] # 標(biāo)準(zhǔn)化(均值歸零、方差歸一) left_norm = (left_channel - np.mean(left_channel)) / np.std(left_channel) right_norm = (right_channel - np.mean(right_channel)) / np.std(right_channel)
標(biāo)準(zhǔn)化消除量綱差異,提升模型收斂效率。
2. 線性回歸建模核心
2.1 回歸參數(shù)計算
基于最小二乘法直接求解斜率與截距:
def linear_regression(x, y):
n = len(x)
sum_x, sum_y = np.sum(x), np.sum(y)
sum_xy = np.sum(x * y)
sum_x2 = np.sum(x ** 2)
slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x ** 2)
intercept = (sum_y - slope * sum_x) / n
return slope, intercept
該方法避免迭代計算,效率顯著高于梯度下降法。
2.2 滑動窗口分塊分析
sim_list = []
for i in range(0, len(left_norm)-800, 800):
x = left_norm[i:i+800:2] # 左聲道隔點采樣
y = right_norm[i:i+800:1] # 右聲道連續(xù)采樣
slope, intercept = linear_regression(x, y)
y_pred = slope * x + intercept
sim = cosine_similarity(y_pred, y) # 余弦相似度評估擬合效果
sim_list.append(sim)
- 創(chuàng)新點:通過800樣本滑動窗口捕捉局部特征
- 輸出指標(biāo):各窗口回歸方程的余弦相似度序列
3. 模型評估與可視化
3.1 誤差指標(biāo)計算
def calculate_fit_error(y_true, y_pred):
mse = np.mean((y_true - y_pred) ** 2) # 均方誤差
rmse = np.sqrt(mse) # 均方根誤差
mae = np.mean(np.abs(y_true - y_pred)) # 平均絕對誤差
return mse, rmse, mae
多維度評估模型精度。
3.2 動態(tài)效果可視化
plt.figure(figsize=(12, 4))
plt.plot(sim_list, marker='o', linestyle='-', color='#FF7043')
plt.title("雙聲道線性擬合相似度變化趨勢", fontsize=14)
plt.xlabel("時間窗口索引", fontsize=12)
plt.ylabel("余弦相似度", fontsize=12)
plt.grid(alpha=0.3)
plt.show()
4. 完整代碼實現(xiàn)
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
# 中文顯示支持
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False
def cosine_similarity(a, b):
"""計算余弦相似度"""
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
def linear_regression(x, y):
"""最小二乘法線性回歸"""
n = len(x)
sum_x, sum_y = np.sum(x), np.sum(y)
sum_xy = np.sum(x * y)
sum_x2 = np.sum(x ** 2)
slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x ** 2)
intercept = (sum_y - slope * sum_x) / n
return slope, intercept
def main():
# 數(shù)據(jù)讀取
_, audio = wavfile.read("sound/cat/1-47819-C-5.wav")
left = (audio[:,0]-np.mean(audio[:,0]))/np.std(audio[:,0])
right = (audio[:,1]-np.mean(audio[:,1]))/np.std(audio[:,1])
# 滑動窗口分析
sim_list = []
for i in range(0, len(left)-800, 800):
x, y = left[i:i+800:2], right[i:i+800:1]
if len(x) > len(y): x = x[:len(y)]
slope, intercept = linear_regression(x, y)
sim_list.append(cosine_similarity(slope*x+intercept, y))
# 可視化
plt.plot(sim_list)
plt.show()
if __name__ == "__main__":
main()
5. 應(yīng)用場景與擴(kuò)展
聲音特征分析:通過回歸斜率變化識別音頻中的突發(fā)事件(如爆破音、重音節(jié))
音頻質(zhì)量評估:雙聲道擬合相似度越高,說明聲道一致性越好(適用于設(shè)備測試)
擴(kuò)展方向
- 引入MFCC(梅爾頻率倒譜系數(shù))替代原始信號
- 結(jié)合LSTM模型捕捉長期依賴關(guān)系
- 遷移至帕金森病語音診斷等醫(yī)療場景
到此這篇關(guān)于Python實現(xiàn)WAV音頻分析與線性回歸建模的文章就介紹到這了,更多相關(guān)Python音頻分析內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解django+django-celery+celery的整合實戰(zhàn)
這篇文章主要介紹了詳解django+django-celery+celery的整合實戰(zhàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
簡單掌握Python中g(shù)lob模塊查找文件路徑的用法
glob模塊遵循Unix的shell規(guī)則來匹配文件名進(jìn)行文件查找,下面我們結(jié)合匹配相關(guān)的字符區(qū)間與通配符知識,來簡單掌握Python中g(shù)lob模塊查找文件路徑的用法2016-07-07
Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)在字典中將鍵映射到多個值上的方法
這篇文章主要介紹了Python在字典中將鍵映射到多個值上的方法,涉及Python針對字典的相關(guān)映射與初始化相關(guān)操作技巧,需要的朋友可以參考下2018-02-02
Python解決IndexError: list index out of&nb
IndexError是一種常見的異常類型,它通常發(fā)生在嘗試訪問列表(list)中不存在的索引時,錯誤信息“IndexError: list index out of range”意味著你試圖訪問的列表索引超出了列表的實際范圍,所以本文給大家介紹了Python成功解決IndexError: list index out of range2024-05-05
Python使用moviepy讀取字幕srt文件報錯的解決方法詳解
這篇文章主要為大家詳細(xì)介紹了Python使用moviepy讀取字幕srt文件報錯‘gbk‘?codec?can‘t?decode的兩種解決辦法,有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-01-01
Python實現(xiàn)實時顯示進(jìn)度條的六種方法
這篇文章主要為大家介紹了Python實現(xiàn)實時顯示進(jìn)度條,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助<BR>2021-12-12

