Manage model state with fit and transform
masterWhen building custom models that involve expensive computations (like generating embeddings), you can use the fit and transform pattern to avoid redundant calculations.
fit(from_list): Use this to pre-calculate and store state (e.g., embeddings) for thefrom_list.transform(to_list): Use this to match a new list against the state already stored during thefitstep.
To support this, your custom match method should handle a re_train parameter. When re_train=False (typically during a transform call), the model should leverage previously stored attributes (like self.embeddings_to) instead of re-calculating them.
# Example pattern for stateful models
class SentenceEmbeddings(BaseMatcher):
def __init__(self, model_id):
super().__init__(model_id)
self.embeddings_to = None
def match(self, from_list, to_list, re_train=True) -> pd.DataFrame:
# 1. Always calculate embeddings for the 'from' side
embeddings_from = self.embedding_model.encode(from_list)
# 2. Use stored embeddings if re_train is False
if not re_train:
embeddings_to = self.embeddings_to
else:
embeddings_to = self.embedding_model.encode(to_list)
# 3. Store for future transform calls
self.embeddings_to = embeddings_to
# ... perform matching ...
# Usage pattern
model = PolyFuzz(custom_matcher).fit(from_list)
results = model.transform(to_list)