MarkTechPost新闻
Google Research MSEB 编码指南:编写符合基准规范的音频编码器并评估多任务性能
本文是 Google Research Massive Sound Embedding Benchmark (MSEB) 的综合编程教程。文章演示了如何根据基准规范实现自定义音频编码器,驱动分类、聚类、检索和分割评估器,并分析多任务基准测试的性能表现。
在本教程中,我们使用来自 Google Research 的大规模声音嵌入基准(MSEB),并从排行榜分数的实际含义——即评估器表面(evaluator surface)——的角度来探讨它。我们安装该软件包并梳理其三个层级,然后针对框架自带的抽象基类编写两个故意设计不同的编码器:一个用于测量随时间变化的响度,另一个用于测量音色,并在笔记本中对我们生成的少量合成语料库进行编码,从而无需下载任何数据。我们利用这些嵌入向量驱动分类、聚类、检索和分割评估器,直接调用度量函数以观察各项指标所奖励的特征,最后组装真实提交任务所需的 TaskMetadata。结果呈现出一种对比:两个编码器在针对不同评估器时互换优势地位,这用数字而非文字论证了多任务基准的价值。
import os
import sys
import json
import math
import traceback
import subprocess
import numpy as np
RESULTS = {}
BENCH = {}
def banner(title):
print("\n" + "=" * 78)
print(title)
print("=" * 78)
def section(name):
def wrap(fn):
def run(*a, **kw):
banner(name)
try:
out = fn(*a, **kw)
RESULTS[name] = out if isinstance(out, str) else "ok"
return out
except Exception as e:
RESULTS[name] = f"SKIPPED / FAILED -> {type(e).__name__}: {e}"
print(f"\n[!] {name} did not complete: {type(e).__name__}: {e}")
traceback.print_exc(limit=3)
return None
return run
return wrap
banner("0. Install MSEB and map the three layers we will use")
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "mseb==0.1.0"], check=True)
import mseb
from mseb import types, encoder as encoder_lib, evaluator as evaluator_lib, metrics
from mseb.evaluators import (
classification_evaluator,
clustering_evaluator,
retrieval_evaluator,
segmentation_evaluator,
)
print(f" mseb {mseb.__version__} | Python {sys.version.split()[0]} | numpy {np.__version__}")
print("\n MSEB is three layers, and a benchmark run walks down them:")
print(" types -> Sound, SoundEmbedding, Score, TaskMetadata: the shapes every task speaks")
print(" encoder -> MultiModalEncoder: the contract YOUR model implements")
print(" evaluators -> classification, clustering, retrieval, reranking, transcription, segmentation, ...")
print("\n evaluator entry points we will drive:")
for module, cls in [(classification_evaluator, "ClassificationEvaluator"),
(clustering_evaluator, "ClusteringEvaluator"),
(retrieval_evaluator, "RetrievalEvaluator"),
(segmentation_evaluator, "SegmentationEvaluator")]:
print(f" {module.__name__.split('.')[-1]:28s} {cls}")
print("\n Everything below runs on CPU with no dataset download: we synthesise the audio.")我们安装了 mseb 并导入了基准运行所涉及的三个层级。types 模块包含了每个任务所使用的数据结构形状,包括 Sound、SoundEmbedding、Score 和 TaskMetadata;encoder 模块包含了 MultiModalEncoder,即我们的模型需要实现的契约;evaluators 包则为每个任务家族提供了一个独立的模块。我们仅导入本笔记本所驱动的四个评估器,因为分类、聚类、检索和分割模块仅依赖 NumPy 和 scikit-learn,并无其他重型依赖。相比之下,重排序和转录评估器会引入 Whisper,而任务运行器则会引入 TensorFlow 和 apache-beam。因此,下文所有内容均在免费 CPU 运行时环境下执行,无需下载数据集,也无需加速器。
SR = 16000
@section("1. The type contract: Sound, SoundEmbedding, Score") def type_contract(): t = np.arange(SR) / SR waveform = (0.5 * np.sin(2 * np.pi * 440 * t)).astype(np.float32) sound = types.Sound( waveform=waveform, context=types.SoundContextParams(id="demo_000", sample_rate=SR, length=len(waveform), language="en_us", text="a 440 Hz tone"), ) print(f" Sound id={sound.context.id!r} {sound.waveform.shape} @ {sound.context.sample_rate} Hz" f" -> {sound.size_bytes:,} bytes")
embedding = types.SoundEmbedding(
embedding=np.zeros((1, 16), dtype=np.float32), # (N, D): one utterance-level vector
timestamps=np.array([[0.0, 1.0]], dtype=np.float32), # (M, 2): [start, end] in seconds
context=sound.context,
encoding_stats=types.EncodingStats(input_size_bytes=sound.size_bytes, embedding_size_bytes=16 * 4),
)
print(f" SoundEmbedding embedding{embedding.embedding.shape} timestamps{embedding.timestamps.shape}"
f" -> {embedding.size_bytes} bytes")
print(f" compression_ratio = {embedding.encoding_stats.compression_ratio:.5f}"
f" ({1 / embedding.encoding_stats.compression_ratio:,.0f}x smaller than the audio)")
print(" N embeddings and M timestamps: M == N is frame-aligned, M == 1 is utterance-level.")
print(" embedding may also hold N strings instead of vectors - step 8 uses exactly that.")
score = types.Score(metric="Accuracy", description="Overall classification accuracy", value=0.875, min=0.0, max=1.0) print(f"\n Score {score.metric}={score.value} in [{score.min}, {score.max}] :: {score.description}") for bad, why in [(dict(metric="", description="d", value=0.5, min=0.0, max=1.0), "empty metric name"), (dict(metric="m", description="d", value=0.5, min=1.0, max=0.0), "min > max")]: try: types.Score(**bad) except Exception as e: print(f" rejected at construction ({why}): {type(e).__name__}: {e}") return f"Sound {sound.size_bytes:,} B -> embedding {embedding.size_bytes} B"
type_contract()
我们从类型契约开始,因为其他所有层都基于它进行表达。Sound 携带波形数据以及 SoundContextParams(包含标识符、采样率、长度、语言和可选转录文本),这些元数据将伴随音频贯穿整个处理流程。SoundEmbedding 携带一个包含 N 个嵌入向量的数组和一个包含 M 个时间戳对的数组;N 与 M 之间的关系构成了基准测试的词汇表:当 M 等于 N 时,表示每一帧对应一个向量;而当 M 等于 1 时,表示仅有一个话语级别的向量,这正是我们的编码器所生成的结果。EncodingStats 记录输入和嵌入的大小,并暴露出压缩比,在此示例中,从音频到向量的压缩达到了千分之一。Score 由指标名称、数值及其上下界组成,它在构造时进行自我验证,拒绝空白的指标名称或最小值大于最大值的非法情况,从而确保格式错误的数值无法进入排行榜。此外,embedding 字段也接受 N 个字符串而非 N 个向量,这为第 8 步提供了入口。
class EnergyEnvelopeEncoder(encoder_lib.MultiModalEncoder):
"""基线:将 n_bins 个等长时间片内的能量取平均值。仅描述响度/安静程度,不涉及音色。”
def __init__(self, n_bins: int = 16): super().__init__() self.n_bins = n_bins
def _setup(self): self._ready = True # 实际的编码器在此处加载权重
def _check_input_types(self, batch): for item in batch: if not isinstance(item, types.Sound): raise ValueError(f"{type(self).__name__} 接受 types.Sound 类型,实际收到 {type(item).__name__}")
def _encode(self, batch) -> list[types.SoundEmbedding]: out = [] for sound in batch: slices = np.array_split(sound.waveform.astype(np.float32), self.n_bins) vec = np.array([[float(np.sqrt(np.mean(s ** 2) + 1e-12)) for s in slices]], dtype=np.float32) vec /= np.linalg.norm(vec) + 1e-9 out.append(types.SoundEmbedding( embedding=vec, timestamps=np.array([[0.0, sound.context.length / sound.context.sample_rate]], dtype=np.float32), context=sound.context)) return out
class SpectralProfileEncoder(encoder_lib.MultiModalEncoder):
"""竞争者:将平均对数幅度谱池化到 n_bands 个频带中。描述音色。”
def __init__(self, n_bands: int = 16, frame: int = 512): super().__init__() self.n_bands, self.frame = n_bands, frame
def _setup(self): self._window = np.hanning(self.frame).astype(np.float32)
def _check_input_types(self, batch): for item in batch: if not isinstance(item, types.Sound): raise ValueError(f"{type(self).__name__} 接受 types.Sound 类型,实际收到 {type(item).__name__}")
def _encode(self, batch) -> list[types.SoundEmbedding]: out = [] for sound in batch: w = sound.waveform.astype(np.float32) n_frames = max(1, len(w) // self.frame) spectra = [np.abs(np.fft.rfft(w[i * self.frame:(i + 1) * self.frame] * self._window)) for i in range(n_frames)] mean_spectrum = np.log1p(np.mean(spectra, axis=0)) vec = np.array([[float(b.mean()) for b in np.array_split(mean_spectrum, self.n_bands)]], dtype=np.float32) vec /= np.linalg.norm(vec) + 1e-9 out.append(types.SoundEmbedding( embedding=vec, timestamps=np.array([[0.0, sound.context.length / sound.context.sample_rate]], dtype=np.float32), context=sound.context)) return out
@section("2. 编码器契约:三个方法,框架处理其余部分") def encoder_contract(): print(" MultiModalEncoder 抽象方法(子类必须实现):") for name in sorted(encoder_lib.MultiModalEncoder.__abstractmethods__): print(f" {name}") print(" final(由框架拥有,请勿重写):setup(), encode()")
t = np.arange(SR) / SR fade = np.exp(-2.5 * t).astype(np.float32) # 一个衰减的音符,以便包络线不是平坦的 sound = types.Sound(waveform=(0.5 * fade * np.sin(2 * np.pi * 440 * t)).astype(np.float32), context=types.SoundContextParams(id="demo_000", sample_rate=SR, length=SR)) for enc in (EnergyEnvelopeEncoder(), SpectralProfileEncoder()): enc.setup() emb = enc.encode([sound])[0] stats = emb.encoding_stats # 由 encode() 附加,而非我们的代码 print(f"\n {type(enc).__name__:24s} -> {emb.embedding.shape} {emb.embedding.dtype}" f" output_type={enc.output_type().__name__}") print(f" {'':24s} EncodingStats(input={stats.input_size_bytes:,} B, " f"embedding={stats.embedding_size_bytes} B, flops={stats.flops})") print(f" {'':24s} 前 6 维: {np.round(emb.embedding[0][:6]
, 3)}") print("\n 包络编码器观察到音符的衰减;频谱编码器在 440 Hz 处看到一个峰值。")
try: EnergyEnvelopeEncoder().encode(["not a Sound"]) except ValueError as e: print(f"\n _check_input_types 捕获了错误的输入类型:{e}") return "two encoders satisfying MultiModalEncoder"
encoder_contract()
``
我们通过继承 MultiModalEncoder 来编写两个编码器,其抽象方法恰好有三个:_setup 加载模型所需的任何内容,_check_input_types 拒绝任何非 Sound 类型的数据,而 _encode 将一批数据转换为 SoundEmbedding 对象。框架负责 setup 和 encode,其中 encode 会为每个结果附加 EncodingStats,因此我们的代码无需手动填充该部分。EnergyEnvelopeEncoder 在十六个相等的时间切片中计算能量平均值,因此仅描述响度的变化;SpectralProfileEncoder 将平均对数幅度频谱池化到十六个频带中,因此描述音色。两者均对其输出进行 L2 归一化,使得点积即为余弦相似度。通过分别让这两种编码器处理一个衰减音符,差异便一目了然:包络编码器观察到的是衰减过程,而频谱编码器则看到 440 Hz 处的单一峰值。
CLASSES = ["tone", "chirp", "noise"]
N_PER_CLASS = 12
def synthesize(kind: str, index: int, take: int) -> types.Sound:
"""一秒钟的音频。take 为 0 表示原始文档,take 为 1 表示同一剪辑的噪声更大的录音。
刻意分离了两个线索:频谱指示其所属类别,而振幅包络线——针对每个项目单独绘制且独立于类别——指示其具体项目。
"""
item = np.random.default_rng(1000 + CLASSES.index(kind) * 100 + index)
control = 0.25 + 0.75 * item.random(8)
envelope = np.interp(np.linspace(0, 7, SR), np.arange(8), control).astype(np.float32)
t = np.arange(SR) / SR
if kind == "tone":
w = np.sin(2 * np.pi * (380 + 80 * item.random()) * t)
elif kind == "chirp":
f0, f1 = 200 + 50 * item.random(), 3200 + 400 * item.random()
w = np.sin(2 * np.pi * (f0 * t + 0.5 * (f1 - f0) * t ** 2))
else:
w = item.standard_normal(SR)
w /= np.sqrt(np.mean(w ** 2)) + 1e-9 # 单位均方根值:包络线是唯一的响度线索
take_rng = np.random.default_rng(50_000 + take * 10_000 + CLASSES.index(kind) * 100 + index)
w = (0.4 + 0.2 * take_rng.random()) * envelope * (w + 0.02 * take_rng.standard_normal(SR))
return types.Sound(waveform=w.astype(np.float32), context=types.SoundContextParams(
id=f"{kind}_{index:02d}" + ("" if take == 0 else "_take2"), sample_rate=SR,
length=SR, language="en_us", text=kind))
@section("3. 一个合成语料库,编码为 MSEB 嵌入缓存")
def build_corpus():
corpus = [synthesize(k, i, 0) for k in CLASSES for i in range(N_PER_CLASS)]
queries = [synthesize(k, i, 1) for k in CLASSES for i in range(N_PER_CLASS)]
labels = {s.context.id: s.context.text for s in corpus + queries}
print(f" {len(corpus)} 个文档 + {len(queries)} 个相同剪辑的第二轮录音,"
f" {len(CLASSES)} 个类别,每个时长 1.0 秒 @ {SR} Hz")
caches, query_caches = {}, {}
for enc in (EnergyEnvelopeEncoder(), SpectralProfileEncoder()):
enc.setup()
embeddings = enc.encode(corpus) # 一次批量调用,如同真实运行器
caches[type(enc).__name__] = {e.context.id: e for e in embeddings}
query_caches[type(enc).__name__] = {e.context.id: e for e in enc.encode(queries)}
matrix = np.vstack([e.embedding for e in embeddings])
within, between = [], []
for i in range(len(corpus)):
for j in range(i + 1, len(corpus)):
sim = float(matrix[i] @ matrix[j])
(within if labels[corpus[i].context.id] == labels[corpus[j].context.id] else between).append(sim)
print(f" {type(enc).__name__:24s} 包含 {len(embeddings)} 个嵌入的缓存,维度 {matrix.shape[1]}"
f" 平均余弦相似度:同类别 {np.mean(within):.3f} vs 其他类别 {np.mean(between):.3f}"
f" (差距 {np.mean(within) - np.mean(between):+.3f})")
print("\n 将该差距解读为预测结果:只有频谱编码器能够区分这些类别。")
print(" 步骤 4-6 检查评估者是否达成一致——以及该差距是否是全部真相。")
globals().update(CORPUS=corpus, QUERIES=queries, LABELS=labels, CACHES=caches, QCACHES=query_caches)
return f"{len(corpus)} 个文档 + {len(queries)} 个由 2 个编码器编码的查询"
build_corpus()
我们合成一个语料库,其中两个线索被刻意分离。频谱指示片段属于哪个类别——音调、啁啾声或噪声,而振幅包络则是针对每个项目单独绘制的,与类别无关,因此它标识的是具体是哪个片段,而不涉及其内容是什么。在应用包络之前,我们将每个波形归一化为单位均方根(RMS),使包络成为唯一的响度线索。我们对这36个项目中的每一个分别渲染两次:一次作为文档,另一次作为同一音片的带有更多噪声的第二遍录制,并使用两种编码器将这两组数据编码到MSEB嵌入缓存中,即从声音ID到SoundEmbedding的普通字典,这是所有评估器所消费的数据结构。此处打印的平均同类余弦相似度和异类余弦相似度可解读为对接下来三个步骤的预测:只有频谱编码器能够区分这些类别。
``php
def class_prototypes(cache, labels):
"""Class embedding table (C, D): the mean unit vector of each class, as the evaluator's weights."""
rows = []
for name in CLASSES:
vecs = np.vstack([cache[i].embedding for i in cache if labels[i] == name])
mean = vecs.mean(axis=0)
rows.append(mean / (np.linalg.norm(mean) + 1e-9))
return np.vstack(rows).astype(np.float32)
@section("4. ClassificationEvaluator: prototypes in, Score objects out") def classification(): table, example = {}, None for name, cache in CACHES.items(): evaluator = classification_evaluator.ClassificationEvaluator( class_labels=CLASSES, weights=class_prototypes(cache, LABELS), distance_fn=evaluator_lib.dot_product, # embeddings are L2-normalised -> cosine top_k_value=2, ) predictions = evaluator.compute_predictions(cache) # {id: per-class score vector} references = [classification_evaluator.ClassificationReference(i, LABELS[i]) for i in cache] table[name] = {s.metric: s.value for s in evaluator.compute_metrics(predictions, references)} if name == "SpectralProfileEncoder": key = next(iter(predictions)) example = (key, np.round(list(predictions[key]), 3))
metric_names = list(next(iter(table.values())))[:6] print(f" {'encoder':26s}" + "".join(f"{m[:14]:>16s}" for m in metric_names)) for name, row in table.items(): print(f" {name:26s}" + "".join(f"{row[m]:16.3f}" for m in metric_names))
print(f"\n compute_predictions returns one raw score per class, e.g. {example[0]!r} -> {example[1]}") print(f" ({CLASSES} - the argmax is the prediction, and top_k_value=2 also scores Top-2 Accuracy.)") print(" compute_metrics turns those into types.Score objects, which is what the leaderboard stores.") for name, row in table.items(): BENCH.setdefault(name, {})["Accuracy"] = row["Accuracy"] winner = max(table, key=lambda k: table[k]["Accuracy"]) return "Accuracy: " + ", ".join(f"{k} {v['Accuracy']:.3f}" for k, v in table.items()) + f" (winner {winner})"
classification()
``
ClassificationEvaluator 以一组类别嵌入表作为其权重,并需要一个距离函数;我们构建的权重是各类别的原型,即每个类别的平均单位向量。它的两个方法界限清晰:compute_predictions 为每个缓存嵌入返回每个类别的原始得分,而 compute_metrics 则将这些得分与 ClassificationReference 标签结合,转换为排行榜存储的 Score 对象列表。将 top_k_value 设置为 2 会在准确率之外增加 Top-2 准确率、平衡准确率以及加权精确率、召回率和 F1 分数。频谱编码器对该语料库实现了完美分类,而包络编码器的表现虽远高于随机水平,但远低于频谱编码器,这正是余弦差距所预测的顺序。
第 5 节:ClusteringEvaluator:编码时无标签,评分时使用 V-measure
def clustering():
evaluator = clustering_evaluator.ClusteringEvaluator()
examples = [clustering_evaluator.ClusteringExample(sound_id=i, label=LABELS[i])
for i in next(iter(CACHES.values()))]
print(f" {len(examples)} examples, KMeans with k = {len(CLASSES)} (inferred from the labels)")
for name, cache in CACHES.items():
np.random.seed(0) # MiniBatchKMeans 在此处不接受 random_state 参数:
scores = evaluator(cache, examples) # 它会回退到 NumPy 的全局随机数生成器,因此需要固定该生成器
# 否则未结构化的嵌入空间得分会在 0.01-0.08 之间随机波动
# 评估器是可调用对象。
BENCH.setdefault(name, {})["VMeasure"] = scores[0].value
print(f" {name:26s} {scores[0].metric:12s} {scores[0].value:6.3f}"
f" [{scores[0].min}, {scores[0].max}] :: {scores[0].description}")
print("\n V-measure 是同质性(homogeneity)和完整性(completeness)的调和平均数:1.0 表示聚类")
print(" 完全恢复类别,0.0 表示它们不包含关于类别的任何信息。请注意它对包络编码器(envelope encoder)")
print(" 的惩罚比准确率更严厉——聚类无法依赖任何标签。")
return ", ".join(f"{k} V={v['VMeasure']:.3f}" for k, v in BENCH.items())
clustering()
ClusteringEvaluator 提出了同一问题的更难版本,因为它在编码时从未见过标签:它在缓存上运行 KMeans。它使用 V-measure 对聚类结果与标签进行评分,V-measure 是同质性和完整性的调和平均数。与分类任务相比,此处两个编码器之间的差距急剧扩大,因为监督式的原型读取可以利用无监督聚类无法自行发现的微弱线索。一个值得复制到任何可复现基准测试中的实践细节是:评估器在构建 MiniBatchKMeans 时未指定 random_state,因此它会回退到 NumPy 的全局生成器;如果不对该生成器进行种子设置,未结构化的嵌入空间的得分在每次运行中都会在大约 0.01 到 0.08 之间波动。
@section("6. RetrievalEvaluator:索引语料库,用第二次录制进行查询,对排名评分")
def retrieval():
print(" 任务:每个查询都是某一份文档的更嘈杂的录音版本,且仅有一份文档是正确的。")
print(" 这是身份识别,而非类别分类——这与步骤 4 和 5 中的问题不同。\n")
out = {}
for name, cache in CACHES.items():
doc_ids = list(cache)
docs = np.vstack([cache[i].embedding for i in doc_ids]).astype(np.float32)
queries = QCACHES[name]
searcher = retrieval_evaluator.BruteForceSearcher(candidates=docs, num_neighbors=10)
evaluator = retrieval_evaluator.RetrievalEvaluator(searcher=searcher, id_by_index_id=doc_ids, top_k=5)
predictions = evaluator.compute_predictions(queries)
references = [retrieval_evaluator.RetrievalReferenceId(
sound_id=q, reference_id=q.removesuffix("_take2")) for q in queries]
out[name] = {s.metric: s.value for s in evaluator.compute_metrics(predictions, references)}
q0 = next(iter(queries))
top = [item["id"] for item in predictions[q0].items[:5]]
print(f" 查询 {q0!r} 在 {name} 下的前 5 名结果:")
print(f" {top}")
print(f" 正确文档排在第 {top.index(q0.removesuffix('_take2')) + 1} 位"
f" | 同类别邻居数量:{sum(LABELS[i] == LABELS[q0] for i in top)}/5\n")
metric_names = ["MRR", "EM", "RecallAt5", "NDCG@10"]
print(f" {'编码器':26s}" + "".join(f"{m:>14s}" for m in metric_names))
for name, row in out.items():
print(f" {name:26s}" + "".join(f"{row[m]:14.3f}" for m in metric_names))
BENCH.setdefault(name, {})["MRR"] = row["MRR"]
print("\n MRR 是正确文档排名的倒数,EM 表示‘它是否排在第 1 位’,RecallAt5 表示‘它是否在前 5 名中’。")
print(" 此处的 NDCG@10 是对同一份相关文档给予的分级信用评分。")
return ", ".join(f"{k} MRR={v['MRR']:.3f}" for k, v in out.items())
retrieval()
RetrievalEvaluator 回答的问题与前两者不同,我们设置任务以使这种差异显而易见。每个查询都是恰好一份文档的更嘈杂的第二次录制版本,因此目标是身份识别而非类别分类。我们将文档嵌入索引到 BruteForceSearcher 中,针对查询缓存请求预测,并为每个查询传递一个 RetrievalReferenceId,指明其唯一的正确文档。评估器返回 MRR、精确匹配率、top_k 召回率以及 10 个结果的 NDCG。结果与之前两个步骤相反:包络编码器将每个片段都排在第一位,因为包络是一种物品指纹。相比之下,频谱编码器的排名略差,因为同类别的片段对它来说看起来相似。打印出的前五名列表清晰地展示了这一机制:一个是类随机的邻域,另一个是类纯净的邻域。
@section("7. 仅指标层:WER、CER、精确匹配、MRR、nDCG")
def metric_layer():
truth = "the quick brown fox jumps over the lazy dog"
for hypothesis in [truth, "the quick brown fox jumped over a lazy dog", "quick brown fox over lazy dog"]:
werrors, wtotal = metrics.compute_word_errors(truth, hypothesis)
cerrors, ctotal = metrics.compute_character_errors(truth, hypothesis)
print(f" WER {werrors / wtotal:5.3f} ({werrors}/{wtotal} words) "
f"CER {cerrors / ctotal:5.3f} ({cerrors}/{ctotal} chars) {hypothesis!r}")
print("\n ranking metrics take (reference, ranked_ids):")
ranked = ["doc_b", "doc_a", "doc_c", "doc_d"]
for reference in ["doc_b", "doc_a", "doc_c", "doc_z"]:
rank = ranked.index(reference) + 1 if reference in ranked else None
print(f" reference {reference!r:8s} rank {str(rank):4s}"
f" EM {metrics.compute_exact_match(reference, ranked):.1f}"
f" MRR {metrics.compute_reciprocal_rank(reference, ranked):.3f}"
f" nDCG@4 {metrics.compute_ndcg_at_k(reference, ranked, k=4):.3f}")
print(" compute_ndcg_at_k assumes ONE relevant document and compares it by equality, so pass a")
print(" string, not a list - a list reference silently scores 0.0 while MRR still looks fine.")
print("\n embedding-space distances used by the reconstruction and stability tasks:")
a = np.random.default_rng(1).standard_normal((8, 4)).astype(np.float32)
for label, b in [("identical", a), ("noisy", a + 0.1 * np.random.default_rng(2).standard_normal(a.shape))]:
lp = metrics.compute_lp_norm(a, b, p=2)
dtw = metrics.compute_dynamic_time_warping_distance(a, b)
print(f" {label:10s} L2 {json.dumps({k: round(float(v), 3) for k, v in lp.items()})}"
f" DTW {json.dumps({k: round(float(v), 3) for k, v in dtw.items()})}")
return "WER/CER, EM/MRR/nDCG, Lp and DTW distances"
metric_layer()
我们直接调用这些指标函数,而不将它们包裹在评估器中,因为它们是任务族共享的层级。compute_word_errors 和 compute_character_errors 接受两个字符串并分别返回错误数和总数,因此调用者决定如何聚合语料库。排名指标接受一个参考项和一个按排名排序的标识符列表,对同一排名进行精确匹配、倒数排名和 nDCG 的比较展示了每个指标对位置的侧重。有一个尖锐的边缘情况值得指出:compute_ndcg_at_k 假设只有一个相关文档并通过相等性进行比较,因此传递相关 ID 的列表会静默地得分为零。相比之下,MRR 虽然接受列表,但看起来仍然正确。最后以 compute_lp_norm 和 compute_dynamic_time_warping_distance 结束,它们是重建任务和稳定性任务背后的嵌入空间距离。
第 8 节:SegmentationEvaluator:分别对“说了什么”和“在哪里说”进行评分
``python
def segmentation(): evaluator = segmentation_evaluator.SegmentationEvaluator(tau=0.05) print(" 在这里,'segment'(片段)携带的是一个术语(TERM),而不是向量:SoundEmbedding.embedding 持有 N 个字符串") print(" 而 timestamps 持有它们的 N 个 [开始, 结束] 时间跨度。tau=0.05 -> 边界误差可达 50 毫秒。\n")
TERMS = [("weather", 0.00, 0.30), ("in", 0.30, 0.65), ("boston", 0.65, 1.00)] truth = [segmentation_evaluator.Segment(embedding=term, start_time=s, end_time=e, confidence=1.0) for term, s, e in TERMS] references = [segmentation_evaluator.SegmentationReference(example_id="utt_0", segments=truth)]
def prediction(spans): return {"utt_0": types.SoundEmbedding( embedding=np.array([term for term, _, _ in spans]), # N 个字符串 timestamps=np.array([[s, e] for _, s, e in spans], dtype=np.float32), # N 个 [开始, 结束] context=types.SoundContextParams(id="utt_0", sample_rate=SR, length=SR), scores=np.ones(len(spans), dtype=np.float32))} # 置信度
candidates = { "exact": TERMS, "50 ms out": [("weather", 0.00, 0.28), ("in", 0.28, 0.67), ("boston", 0.67, 1.00)], "right words, wrong places": [("weather", 0.00, 0.45), ("in", 0.45, 0.80), ("boston", 0.80, 1.00)], "right places, wrong words": [("weather", 0.00, 0.30), ("on", 0.30, 0.65), ("austin", 0.65, 1.00)], } shown = ["TimestampsAccuracy", "EmbeddingsAccuracy", "TimestampsAndEmbeddingsAccuracy", "WordErrorRate", "mAP"] print(f" {'prediction':28s}" + "".join(f"{m[:13]:>15s}" for m in shown)) for label, spans in candidates.items(): result = evaluator.compute_scores(prediction(spans), references) # 逐样本得分 scores = {s.metric: s.value for s in evaluator.compute_metrics(result)} # 聚合后的得分 print(f" {label:28s}" + "".join(f"{scores[m]:15.3f}" for m in shown))
print("\n 最后两行的要点在于:单一指标无法区分‘词对了但时间没对上’") print(" 与‘时间对了但词听错了’的区别。时间戳和嵌入向量是分开评分的,") print(" 只有 TimestampsAndEmbeddings 指标会对同时做对的情况给予认可。") return "boundary + term scoring at tau=50 ms"
segmentation() ``` SegmentationEvaluator 将“说了什么”和“在哪里说”作为两个独立的量进行评分,并使用第一步中提到的 SoundEmbedding 的字符串形式:嵌入数组每个片段持有一个术语,时间戳数组持有它们的时间跨度。其流程分为两个阶段:首先对预测值和参考值计算 compute_scores,然后对该结果计算 compute_metrics。我们针对一个真实标签,以五十毫秒的容差对同一短语的四种候选分割方案进行评分。精确匹配(Exact)和误差在五十毫秒内(fifty-milliseconds-out)的方案均获得完美评分,这正是设置容差的用途。最后两行揭示了关键教训:词对但位置错,在嵌入向量上得分为一,而在时间戳上得分为零;位置对但词错,则反之;只有组合指标才会对同时做对的情况给予认可。 @section("9. 任务元数据与自相矛盾的排行榜") def task_metadata(): cache = CACHES["SpectralProfileEncoder"] evaluator = classification_evaluator.ClassificationEvaluator( class_labels=CLASSES, weights=class_prototypes(cache, LABELS), top_k_value=2) references = [classification_evaluator.ClassificationReference(i, LABELS[i]) for i in cache] scores = [s for s in evaluator.compute_metrics(evaluator.compute_predictions(cache), references) if s.metric in ("Accuracy", "Weighted F1-Score")] metadata = types.TaskMetadata( name="SyntheticToneClassification", description="Three-way classification of synthetic tones, chirps and noise", reference="https://github.com/google-research/mseb", type="Classification", category="sound", main_score="Accuracy", revision="1", dataset=types.Dataset(path="synthetic/in-notebook", revision="1"), scores=scores, eval_splits=["test"], eval_langs=["en_us"], ) print(f" TaskMetadata: {metadata.name} type={metadata.type} main_score={metadata.main_score!r}") print(f" dataset={metadata.dataset.path!r} rev {metadata.dataset.revision}" f" splits={metadata.eval_splits} langs={metadata.eval_langs}") print(f" scores={[f'{s.metric}={s.value:.3f}' for s in metadata.scores]}") try: types.TaskMetadata({{f.name: getattr(metadata, f.name) for f in metadata.__dataclass_fields__.values()}, "scores": []}) except Exception as e: print(f" validated at construction: {type(e).__name__}: {e}") columns = ["Accuracy", "VMeasure", "MRR"] print(f"\n One row per encoder, one column per task family:") print(f" {'encoder':26s}" + "".join(f"{c:>12s}" for c in columns) + " what it measures") for name, row in BENCH.items(): print(f" {name:26s}" + "".join(f"{row[c]:12.3f}" for c in columns) + (" timbre -> class" if "Spectral" in name else " loudness over time -> identity")) flips = [c for c in columns if (max(BENCH, key=lambda n: BENCH[n][c]) != max(BENCH, key=lambda n: BENCH[n]["Accuracy"]))] print(f"\n The winner changes column to column ({', '.join(flips)} goes the other way). That is the whole") print(" argument for a MASSIVE benchmark: a single headline number would have hidden it. An encoder") print(" that cannot name a sound can still recognise it, and vice versa.") print("\n A real submission runs mseb.runner over an mseb.task against a published dataset and writes") print(" these same Score objects to JSON; the layers above are exactly what it exercises.") return f"TaskMetadata + {len(BENCH)} encoders x {len(columns)} task families" task_metadata() 我们组装了真实提交所携带的 TaskMetadata,包括名称、类型、类别、主要分数、数据集路径和版本、评估划分和语言,以及 Score 对象本身。它在构造时进行验证,方式与 Score 相同,会拒绝空的分数列表。然后我们将目前为止的所有结果放入一个表格中:每一行代表一个编码器,每一列代表一个任务族。赢家因列而异:无法命名声音的编码器仍能识别它,而能正确命名所有声音的编码器却会将属于同一组的片段混淆。单一的总体数字会完全掩盖这一点,这正是主张构建在任务规模上而非仅在数据规模上庞大的基准测试的理由。 打印摘要 对于名称、结果在 RESULTS.items() 中: 打印(f" {名称:<74s} {结果}") 打印(""" 下一步去哪里 - 替换为真实编码器:mseb/encoders/ 提供 wav2vec、Whisper、CLAP、EnCodec 和 SoundStream 包装器,以及用于语音到文本到嵌入链的 CascadeEncoder。只有步骤 2 中的三种方法 发生变化;上述每个评估器继续正常工作。 - 运行已发布任务:mseb.runner 使用 apache-beam 在真实数据集上驱动 mseb.task; 任务系列位于 mseb/tasks/(分类、检索、重排序、转录、 分割、聚类、推理、脑编码、稳定性)。 - 与排行榜进行比较:https://huggingface.co/spaces/google/mseb-leaderboard - 阅读您实现的契约:mseb/encoder.py 和 mseb/evaluator.py 总共约 500 行。 """) 摘要打印了每个部分返回的单行结果,然后指出了本笔记本开放的三个方向:替换包中提供的真实编码器之一,即 wav2vec、Whisper、CLAP、EnCodec、SoundStream 或级联包装器,这仅改变步骤 2 中的三种方法,并使所有评估器继续工作;通过 mseb.runner 在真实数据集上运行已发布任务;并将结果与公共排行榜进行比较。 总之,我们将 MSEB 视为其本身,即一个契约加上一组评估器,并在不下载数据集或不接触加速器的情况下端到端地驱动它。实现三种方法足以使我们的代码成为基准的一等公民,框架随后处理批处理、统计和验证。评估器对相同的嵌入提出了真正不同的问题:分类和聚类询问声音是什么,检索询问它是哪种声音,而分割询问说了什么以及在哪里,分别评分,以便时间错误和识别错误不会隐藏在一个平均值中。我们的两个编码器根据所提问题的不同互换位置,我们保留这一结果,因为单个数字无法对声音嵌入进行排名。下一步是用真实编码器替换我们的玩具编码器并重新运行相同的评估器,因为当嵌入改进时,上述所有评分代码都不会改变。 需要与我们合作推广您的 GitHub 仓库或 Hugging Face 页面或产品发布或网络研讨会等?与我们联系 Sana Hassan 是 Marktechpost 的咨询实习生,也是 IIT Madras 的双学位学生,热衷于应用技术和 AI 来解决现实世界的问题。他对解决实际问题有着浓厚的兴趣,为 AI 与现实生活解决方案的交叉点带来了全新的视角。
译文已达到本站中文翻译的字数上限,剩余内容请查看原文。