Embeddings#
Representation learning utilities for encoding text, images, and multimodal inputs.
API Reference#
Embeddings Module - Representation Learning
Provides utilities for creating and managing embeddings from various modalities (text, images, behavior).
- Usage:
from corerec.embeddings import TextEncoder, MultimodalEncoder
encoder = TextEncoder(model=”sentence-transformers/all-MiniLM-L6-v2”) embeddings = encoder.encode([“red shoes”, “blue jacket”])
- class corerec.embeddings.TextEncoder(model: str | Any | None = None, device: str = 'cpu', normalize: bool = True)[source]#
Bases:
objectEncode text into embeddings using sentence transformers or similar.
Wraps sentence-transformers or other text encoding models with a simple interface.
Example
encoder = TextEncoder(“sentence-transformers/all-MiniLM-L6-v2”)
# single text emb = encoder.encode(“red running shoes”)
# batch embs = encoder.encode([“red shoes”, “blue jacket”, “green hat”])
- __init__(model: str | Any | None = None, device: str = 'cpu', normalize: bool = True)[source]#
- Parameters:
model – model name or pre-loaded model instance
device – ‘cpu’ or ‘cuda’
normalize – whether to L2-normalize embeddings
- encode(texts: str | List[str], batch_size: int = 32, show_progress: bool = False) ndarray[source]#
Encode text(s) into embeddings.
- Parameters:
texts – single string or list of strings
batch_size – batch size for encoding
show_progress – show progress bar
- Returns:
numpy array of shape (n, dim) or (dim,) for single text
- property model#
Lazy load model on first use.
- class corerec.embeddings.MultimodalEncoder(encoders: Dict[str, Any] | None = None, fusion: str = 'concat', weights: Dict[str, float] | None = None, output_dim: int | None = None)[source]#
Bases:
objectCombine embeddings from multiple modalities into a single vector.
Useful when items have multiple representations: - Product: title (text) + image + category (categorical) - Video: title (text) + thumbnail (image) + transcript (text) - Music: artist (text) + audio features + genre
Fusion strategies: -
concat– concatenate all embeddings -average– average embeddings (requires same dim) -weighted– weighted average -attention– learned attention weights (requires training)Example:
encoder = MultimodalEncoder( encoders={ 'text': text_encoder, 'image': image_encoder, }, fusion='concat', ) item_data = { 'text': "red running shoes", 'image': image_array, } embedding = encoder.encode(item_data)
- __init__(encoders: Dict[str, Any] | None = None, fusion: str = 'concat', weights: Dict[str, float] | None = None, output_dim: int | None = None)[source]#
- Parameters:
encoders – dict of modality_name -> encoder
fusion – ‘concat’, ‘average’, or ‘weighted’
weights – weights per modality (for weighted fusion)
output_dim – target output dimension (for projection)
- add_encoder(name: str, encoder: Any, weight: float = 1.0) MultimodalEncoder[source]#
Add a modality encoder.
- Parameters:
name – modality name
encoder – encoder with encode() method
weight – weight for fusion
- class corerec.embeddings.PretrainedEmbeddings(embeddings: ndarray, ids: List[Any], normalize: bool = False)[source]#
Bases:
objectLoad and query pretrained embedding tables.
Supports loading from: - NumPy files (.npy, .npz) - Pickle files (.pkl) - Text files (word2vec format)
Example
embs = PretrainedEmbeddings.load(“item_embeddings.npy”, item_ids)
# get embedding for an item vec = embs.get(item_id=123)
# find similar items similar = embs.most_similar(item_id=123, top_k=10)
- __init__(embeddings: ndarray, ids: List[Any], normalize: bool = False)[source]#
- Parameters:
embeddings – array of shape (n_items, dim)
ids – list of item identifiers (same order as embeddings)
normalize – whether to L2-normalize embeddings
- get(item_id: Any, default: ndarray | None = None) ndarray | None[source]#
Get embedding for an item.
- Parameters:
item_id – item identifier
default – value to return if not found
- Returns:
embedding vector or default
- get_batch(item_ids: List[Any], default: ndarray | None = None) ndarray[source]#
Get embeddings for multiple items.
- Parameters:
item_ids – list of item identifiers
default – default embedding for missing items
- Returns:
array of shape (len(item_ids), dim)
- classmethod load(path: str | Path, ids: List[Any] | None = None, normalize: bool = False) PretrainedEmbeddings[source]#
Load embeddings from file.
- Parameters:
path – path to embedding file
ids – item identifiers (required for .npy, optional for .npz with ‘ids’)
normalize – whether to normalize
- Returns:
PretrainedEmbeddings instance
Text Encoder#
Text Embeddings
Encode text into dense vectors using transformer models.
- class corerec.embeddings.text.TextEncoder(model: str | Any | None = None, device: str = 'cpu', normalize: bool = True)[source]#
Bases:
objectEncode text into embeddings using sentence transformers or similar.
Wraps sentence-transformers or other text encoding models with a simple interface.
Example
encoder = TextEncoder(“sentence-transformers/all-MiniLM-L6-v2”)
# single text emb = encoder.encode(“red running shoes”)
# batch embs = encoder.encode([“red shoes”, “blue jacket”, “green hat”])
- __init__(model: str | Any | None = None, device: str = 'cpu', normalize: bool = True)[source]#
- Parameters:
model – model name or pre-loaded model instance
device – ‘cpu’ or ‘cuda’
normalize – whether to L2-normalize embeddings
- property model#
Lazy load model on first use.
- encode(texts: str | List[str], batch_size: int = 32, show_progress: bool = False) ndarray[source]#
Encode text(s) into embeddings.
- Parameters:
texts – single string or list of strings
batch_size – batch size for encoding
show_progress – show progress bar
- Returns:
numpy array of shape (n, dim) or (dim,) for single text
Multimodal Encoder#
Multimodal Embeddings
Combine embeddings from different modalities (text, image, etc).
- class corerec.embeddings.multimodal.MultimodalEncoder(encoders: Dict[str, Any] | None = None, fusion: str = 'concat', weights: Dict[str, float] | None = None, output_dim: int | None = None)[source]#
Bases:
objectCombine embeddings from multiple modalities into a single vector.
Useful when items have multiple representations: - Product: title (text) + image + category (categorical) - Video: title (text) + thumbnail (image) + transcript (text) - Music: artist (text) + audio features + genre
Fusion strategies: -
concat– concatenate all embeddings -average– average embeddings (requires same dim) -weighted– weighted average -attention– learned attention weights (requires training)Example:
encoder = MultimodalEncoder( encoders={ 'text': text_encoder, 'image': image_encoder, }, fusion='concat', ) item_data = { 'text': "red running shoes", 'image': image_array, } embedding = encoder.encode(item_data)
- __init__(encoders: Dict[str, Any] | None = None, fusion: str = 'concat', weights: Dict[str, float] | None = None, output_dim: int | None = None)[source]#
- Parameters:
encoders – dict of modality_name -> encoder
fusion – ‘concat’, ‘average’, or ‘weighted’
weights – weights per modality (for weighted fusion)
output_dim – target output dimension (for projection)
- add_encoder(name: str, encoder: Any, weight: float = 1.0) MultimodalEncoder[source]#
Add a modality encoder.
- Parameters:
name – modality name
encoder – encoder with encode() method
weight – weight for fusion
- encode(data: Dict[str, Any], missing_ok: bool = True) ndarray[source]#
Encode multimodal data into a single embedding.
- Parameters:
data – dict of modality_name -> modality_data
missing_ok – if True, skip missing modalities
- Returns:
fused embedding vector
Pretrained Embeddings#
Pretrained Embeddings
Load and use pretrained embeddings from various sources.
- class corerec.embeddings.pretrained.PretrainedEmbeddings(embeddings: ndarray, ids: List[Any], normalize: bool = False)[source]#
Bases:
objectLoad and query pretrained embedding tables.
Supports loading from: - NumPy files (.npy, .npz) - Pickle files (.pkl) - Text files (word2vec format)
Example
embs = PretrainedEmbeddings.load(“item_embeddings.npy”, item_ids)
# get embedding for an item vec = embs.get(item_id=123)
# find similar items similar = embs.most_similar(item_id=123, top_k=10)
- __init__(embeddings: ndarray, ids: List[Any], normalize: bool = False)[source]#
- Parameters:
embeddings – array of shape (n_items, dim)
ids – list of item identifiers (same order as embeddings)
normalize – whether to L2-normalize embeddings
- classmethod load(path: str | Path, ids: List[Any] | None = None, normalize: bool = False) PretrainedEmbeddings[source]#
Load embeddings from file.
- Parameters:
path – path to embedding file
ids – item identifiers (required for .npy, optional for .npz with ‘ids’)
normalize – whether to normalize
- Returns:
PretrainedEmbeddings instance
- get(item_id: Any, default: ndarray | None = None) ndarray | None[source]#
Get embedding for an item.
- Parameters:
item_id – item identifier
default – value to return if not found
- Returns:
embedding vector or default
- get_batch(item_ids: List[Any], default: ndarray | None = None) ndarray[source]#
Get embeddings for multiple items.
- Parameters:
item_ids – list of item identifiers
default – default embedding for missing items
- Returns:
array of shape (len(item_ids), dim)