语音识别核心技术,-2.2 Whisper的核心算法 | 《Whisper语音识别实战专栏》 - 5 Mel滤波

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力网站平台 👁️ 283 次阅读

引言

在前一篇文章中,我们深入剖析了Whisper的架构设计,了解了Whisper的整体架构、各组件的功能和工作原理。现在,我们将继续探讨Whisper的核心算法,包括音频特征提取、位置编码、注意力机制和解码策略。

核心算法是Whisper模型的关键组成部分,它们决定了模型的性能和效率。通过本文的学习,您将了解Whisper的核心算法原理和实现细节,以及它们如何协同工作来实现高效的语音识别。

音频特征提取

音频特征提取是语音识别的第一步,它将原始音频信号转换为模型可处理的特征表示。Whisper采用了Mel频谱图作为输入特征,这是一种模拟人类听觉系统的特征表示方法。

1.1 音频采样与量化

原始音频信号是连续的模拟信号,需要经过采样和量化转换为数字信号:

采样:将连续的音频信号在时间轴上离散化,采样率通常为16kHz量化:将采样得到的振幅值转换为离散的数值,通常使用16位整数表示

1.2 预加重

预加重是为了提升高频部分的能量,补偿语音信号在传输过程中的高频衰减。预加重通常使用一阶高通滤波器实现:

# 预加重滤波器

def preemphasis(signal, coeff=0.97):

return np.append(signal[0], signal[1:] - coeff * signal[:-1])

1.3 分帧与加窗

将音频信号分割成固定长度的帧,通常为25ms,帧移为10ms。为了减少帧边界的频谱泄漏,对每一帧应用汉明窗:

# 分帧与加窗

def frame_signal(signal, frame_length, frame_step, window_fn=np.hamming):

signal_length = len(signal)

frame_length = int(round(frame_length))

frame_step = int(round(frame_step))

if signal_length <= frame_length:

num_frames = 1

else:

num_frames = 1 + int(math.ceil((1.0 * signal_length - frame_length) / frame_step))

pad_signal_length = (num_frames - 1) * frame_step + frame_length

z = np.zeros((pad_signal_length - signal_length))

pad_signal = np.append(signal, z)

indices = np.tile(np.arange(0, frame_length), (num_frames, 1)) + np.tile(np.arange(0, num_frames * frame_step, frame_step), (frame_length, 1)).T

indices = np.array(indices, dtype=np.int32)

frames = pad_signal[indices]

window = window_fn(frame_length)

frames *= window

return frames

1.4 傅里叶变换

对每一帧进行快速傅里叶变换(FFT),将时域信号转换为频域信号:

# 傅里叶变换

def compute_fft(frames, n_fft=400):

mag_frames = np.absolute(np.fft.rfft(frames, n_fft))

pow_frames = ((1.0 / n_fft) * ((mag_frames) ** 2))

return pow_frames

1.5 Mel滤波

将线性频谱转换为Mel频谱,模拟人类听觉系统的频率响应:

# Mel滤波器组

def compute_mel_fbank(n_fft=400, n_mels=128, sample_rate=16000):

low_freq_mel = 0

high_freq_mel = 2595 * np.log10(1 + (sample_rate / 2) / 700)

mel_points = np.linspace(low_freq_mel, high_freq_mel, n_mels + 2)

hz_points = 700 * (10**(mel_points / 2595) - 1)

bin = np.floor((n_fft + 1) * hz_points / sample_rate)

fbank = np.zeros((n_mels, int(np.floor(n_fft / 2 + 1))))

for m in range(1, n_mels + 1):

f_m_minus = int(bin[m - 1])

f_m = int(bin[m])

f_m_plus = int(bin[m + 1])

for k in range(f_m_minus, f_m):

fbank[m - 1, k] = (k - bin[m - 1]) / (bin[m] - bin[m - 1])

for k in range(f_m, f_m_plus):

fbank[m - 1, k] = (bin[m + 1] - k) / (bin[m + 1] - bin[m])

return fbank

# 应用Mel滤波

def apply_mel_filter(pow_frames, fbank):

filter_banks = np.dot(pow_frames, fbank.T)

filter_banks = np.where(filter_banks == 0, np.finfo(float).eps, filter_banks) 拼多多帮助力入口

filter_banks = 20 * np.log10(filter_banks) # dB转换

return filter_banks

1.6 对数Mel频谱图

Whisper最终使用对数Mel频谱图作为输入特征:

# 计算对数Mel频谱图

def log_mel_spectrogram(audio, n_mels=128, n_fft=400, hop_length=160, sample_rate=16000):

# 预加重

audio = preemphasis(audio)

# 分帧与加窗

frames = frame_signal(audio, frame_length=0.025, frame_step=0.01, window_fn=np.hamming)

# FFT

pow_frames = compute_fft(frames, n_fft=n_fft)

# Mel滤波

fbank = compute_mel_fbank(n_fft=n_fft, n_mels=n_mels, sample_rate=sample_rate)

filter_banks = apply_mel_filter(pow_frames, fbank)

# 均值归一化

filter_banks -= (np.mean(filter_banks, axis=0) + 1e-8)

return filter_banks

位置编码

位置编码用于为Transformer模型提供序列中元素的位置信息,因为Transformer的自注意力机制是位置无关的。Whisper使用了正弦位置编码:

# 位置编码

def get_position_encoding(seq_len, d_model, max_len=5000):

position = np.arange(seq_len)[:, np.newaxis]

div_term = np.exp(np.arange(0, d_model, 2) * (-np.log(max_len) / d_model))

pos_encoding = np.zeros((seq_len, d_model))

pos_encoding[:, 0::2] = np.sin(position * div_term)

pos_encoding[:, 1::2] = np.cos(position * div_term)

return pos_encoding

注意力机制

注意力机制是Transformer模型的核心,它允许模型关注输入序列中的不同位置。Whisper使用了多种注意力机制,包括自注意力、多头注意力和交叉注意力。

3.1 自注意力

自注意力机制允许序列中的每个元素关注序列中的其他所有元素:

# 自注意力机制

def self_attention(Q, K, V, mask=None):

d_k = Q.shape[-1]

# 计算注意力分数

scores = np.matmul(Q, K.T) / np.sqrt(d_k)

# 应用掩码

if mask is not None:

scores = scores + mask

# 计算注意力权重

attn_weights = np.softmax(scores, axis=-1)

# 计算上下文向量

context = np.matmul(attn_weights, V)

return context, attn_weights

3.2 多头注意力

多头注意力将注意力机制分为多个头,每个头关注输入的不同表示子空间:

# 多头注意力机制

def multi_head_attention(Q, K, V, num_heads, d_model, mask=None):

d_k = d_model // num_heads

d_v = d_model // num_heads

# 线性投影

Q_proj = np.dot(Q, W_q).reshape(-1, num_heads, d_k)

K_proj = np.dot(K, W_k).reshape(-1, num_heads, d_k)

V_proj = np.dot(V, W_v).reshape(-1, num_heads, d_v)

# 转置为 (num_heads, seq_len, d_k)

Q_proj = Q_proj.transpose(1, 0, 2)

K_proj = K_proj.transpose(1, 0, 2)

V_proj = V_proj.transpose(1, 0, 2)

# 计算自注意力

context_list = []

attn_weights_list = []

for i in range(num_heads):

context, attn_weights = self_attention(Q_proj[i], K_proj[i], V_proj[i], mask)

context_list.append(context)

attn_weights_list.append(attn_weights)

# 拼接多头结果

context_concat = np.concatenate(context_list, axis=-1)

# 输出投影

output = np.dot(context_concat, W_o)

return output, np.stack(attn_weights_list)

3.3 交叉注意力

交叉注意力用于编码器-解码器架构中,允许解码器关注编码器的输出:

# 交叉注意力机制

def cross_attention(Q, K_enc, V_enc, mask=None):

d_k = Q.shape[-1]

# 计算注意力分数

scores = np.matmul(Q, K_enc.T) / np.sqrt(d_k)

# 应用掩码

if mask is not None:

scores = scores + mask

# 计算注意力权重

attn_weights = np.softmax(scores, axis=-1)

# 计算上下文向量

context = np.matmul(attn_weights, V_enc)

return context, attn_weights

解码器策略

解码器策略决定了模型如何生成输出序列。Whisper支持多种解码策略,包括贪婪解码、束搜索、温度采样和核采样。

4.1 贪婪解码

贪婪解码是最简单的解码策略,每次选择概率最高的词作为输出:

# 贪婪解码

def greedy_decode(model, input_features, max_length=225):

# 初始化输出序列

output = [model.decoder.tokenizer.bos_token_id]

for _ in range(max_length):

# 生成掩码

attention_mask = torch.ones_like(input_features[:, :, 0])

decoder_mask = generate_square_subsequent_mask(len(output)).to(model.device)

# 模型推理

logits = model(input_features, attention_mask=attention_mask, decoder_input_ids=torch.tensor([output]).to(model.device), decoder_attention_mask=decoder_mask)

# 选择概率最高的词

next_token = torch.argmax(logits[:, -1, :], dim=-1).item()

# 添加到输出序列

output.append(next_token)

# 如果遇到结束符,停止生成

if next_token == model.decoder.tokenizer.eos_token_id:

break

# 解码为文本

text = model.decoder.tokenizer.decode(output, skip_special_tokens=True)

return text

4.2 束搜索

束搜索通过维护多个候选序列来平衡贪婪解码和随机采样:

# 束搜索

def beam_search(model, input_features, beam_size=5, max_length=225):

# 初始化束

bos_token_id = model.decoder.tokenizer.bos_token_id

eos_token_id = model.decoder.tokenizer.eos_token_id

# 初始状态:(序列, 分数, 已完成)

beams = [( [bos_token_id], 0.0, False )]

for _ in range(max_length):

# 生成新的候选序列

new_beams = []

for seq, score, done in beams:

if done:

new_beams.append((seq, score, done))

continue

# 生成掩码

attention_mask = torch.ones_like(input_features[:, :, 0])

decoder_mask = generate_square_subsequent_mask(len(seq)).to(model.device)

# 模型推理

logits = model(input_features, attention_mask=attention_mask, decoder_input_ids=torch.tensor([seq]).to(model.device), decoder_attention_mask=decoder_mask)

# 计算概率分布

probs = torch.softmax(logits[:, -1, :], dim=-1)

# 选择top-k个词

top_k_probs, top_k_tokens = torch.topk(probs, beam_size, dim=-1)

# 生成新的候选序列

for i in range(beam_size):

token = top_k_tokens[0, i].item()

token_prob = top_k_probs[0, i].item()

new_seq = seq + [token]

new_score = score + np.log(token_prob)

new_done = (token == eos_token_id)

new_beams.append((new_seq, new_score, new_done))

# 按分数排序,保留前beam_size个序列

new_beams.sort(key=lambda x: x[1], reverse=True)

beams = new_beams[:beam_size]

# 检查是否所有序列都已完成

if all(done for _, _, done in beams):

break

# 选择分数最高的序列

best_seq = max(beams, key=lambda x: x[1])[0]

# 解码为文本

text = model.decoder.tokenizer.decode(best_seq, skip_special_tokens=True)

return text

4.3 温度采样

温度采样通过调整概率分布的温度参数来控制生成的随机性:

# 温度采样

def temperature_sampling(model, input_features, temperature=1.0, max_length=225):

# 初始化输出序列

output = [model.decoder.tokenizer.bos_token_id]

for _ in range(max_length):

# 生成掩码

attention_mask = torch.ones_like(input_features[:, :, 0])

decoder_mask = generate_square_subsequent_mask(len(output)).to(model.device)

# 模型推理

logits = model(input_features, attention_mask=attention_mask, decoder_input_ids=torch.tensor([output]).to(model.device), decoder_attention_mask=decoder_mask)

# 应用温度缩放

logits = logits[:, -1, :] / temperature

# 计算概率分布

probs = torch.softmax(logits, dim=-1)

# 采样下一个词

next_token = torch.multinomial(probs, num_samples=1).item()

# 添加到输出序列

output.append(next_token)

# 如果遇到结束符,停止生成

if next_token == model.decoder.tokenizer.eos_token_id:

break

# 解码为文本

text = model.decoder.tokenizer.decode(output, skip_special_tokens=True)

return text

4.4 核采样

核采样通过限制采样范围来平衡随机性和可控性:

# 核采样

def nucleus_sampling(model, input_features, p=0.9, max_length=225):

# 初始化输出序列

output = [model.decoder.tokenizer.bos_token_id]

for _ in range(max_length):

# 生成掩码

attention_mask = torch.ones_like(input_features[:, :, 0])

decoder_mask = generate_square_subsequent_mask(len(output)).to(model.device)

# 模型推理

logits = model(input_features, attention_mask=attention_mask, decoder_input_ids=torch.tensor([output]).to(model.device), decoder_attention_mask=decoder_mask)

# 计算概率分布

probs = torch.softmax(logits[:, -1, :], dim=-1)

# 核采样

sorted_probs, sorted_indices = torch.sort(probs, descending=True)

cumulative_probs = torch.cumsum(sorted_probs, dim=-1)

# 找到需要保留的概率质量

keep_indices = cumulative_probs <= p

keep_indices[0] = True # 至少保留一个词

# 归一化概率

filtered_probs = sorted_probs[keep_indices]

filtered_indices = sorted_indices[keep_indices]

normalized_probs = filtered_probs / torch.sum(filtered_probs)

# 采样下一个词

next_token_index = torch.multinomial(normalized_probs, num_samples=1).item()

next_token = filtered_indices[next_token_index].item()

# 添加到输出序列

output.append(next_token)

# 如果遇到结束符,停止生成

if next_token == model.decoder.tokenizer.eos_token_id:

break

# 解码为文本

text = model.decoder.tokenizer.decode(output, skip_special_tokens=True)

return text

总结

本文详细介绍了Whisper的核心算法,包括音频特征提取、位置编码、注意力机制和解码策略。这些算法共同构成了Whisper模型的基础,使它能够实现高效、准确的语音识别。

音频特征提取将原始音频信号转换为模型可处理的Mel频谱图;位置编码为Transformer提供位置信息;注意力机制允许模型关注输入序列中的不同位置;解码策略决定了模型如何生成输出序列。

通过了解这些核心算法,您将能够更好地理解Whisper模型的工作原理,并根据实际需求调整模型参数,提高识别准确率和性能。

在下一篇文章中,我们将介绍Whisper的模型变体,包括不同规模模型的比较、English-only模型与多语言模型的区别,以及各模型的性能指标和适用场景。,语音识别核心技术

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧