Neural Mastery
← Practice
Dense + Sparse Score Fusionmedium

Dense + Sparse Score Fusion

medium RAG & Retrieval 15 min

NumPy allowed · plain Python earns 10 bonus points

RAG step 1/4

A query retrieves context

Embedding similarity ranks the documents before generation.
Open lesson →
01query
02embed
03retrieve
04context
What is RAG?→ embed →top context
retrieval.md44%
rag-systems.md33%
agents.md24%

Cosine-like similarity scores ranked before context assembly

Implement weighted score fusion between dense (embedding) and sparse (BM25-style) retrieval, the real backbone of hybrid search.

Task

Implement fuse_scores(dense_scores, sparse_scores, alpha). For every doc id in either dict, fused score is alpha*dense_scores.get(id,0) + (1-alpha)*sparse_scores.get(id,0). Return a dict of id -> fused score.

Function Signature

fuse_scores(dense_scores: dict[str, float], sparse_scores: dict[str, float], alpha: float) -> dict[str, float]

Examples

Example 1: equal weight blend
Input: dense_scores = {'a': 0.8} sparse_scores = {'a': 0.4} alpha = 0.5
Output: {'a': 0.6000000000000001}
Example 2: doc only in sparse
Input: dense_scores = {} sparse_scores = {'b': 0.9} alpha = 0.5
Output: {'b': 0.45}
Example 3: pure dense weight
Input: dense_scores = {'a': 0.7} sparse_scores = {'a': 0.2} alpha = 1
Output: {'a': 0.7}

Constraints

  • 0 <= alpha <= 1
Python3Saved ✓
def fuse_scores(dense_scores, sparse_scores, alpha):
# Your implementation here
pass

Case 1: equal weight blend
Input: dense_scores = {'a': 0.8} sparse_scores = {'a': 0.4} alpha = 0.5
Expected: {'a': 0.6000000000000001}
Case 2: doc only in sparse
Input: dense_scores = {} sparse_scores = {'b': 0.9} alpha = 0.5
Expected: {'b': 0.45}
Case 3: pure dense weight
Input: dense_scores = {'a': 0.7} sparse_scores = {'a': 0.2} alpha = 1
Expected: {'a': 0.7}