|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +import pandas as pd |
| 5 | + |
| 6 | +from quorabust.preprocess import clean_text |
| 7 | + |
| 8 | +try: |
| 9 | + from sentence_transformers import CrossEncoder |
| 10 | +except ImportError: |
| 11 | + CrossEncoder = None # type: ignore[misc, assignment] |
| 12 | + |
| 13 | + |
| 14 | +class PairCrossEncoderBuilder: |
| 15 | + """Cross-encoder pair scores plus simple length features (optional ``nlp`` extra).""" |
| 16 | + |
| 17 | + def __init__(self, model_name: str = "cross-encoder/quora-distilroberta-base") -> None: |
| 18 | + if CrossEncoder is None: |
| 19 | + raise RuntimeError( |
| 20 | + 'Missing dependency: install with pip install "Quorabust[nlp]"', |
| 21 | + ) |
| 22 | + self.model_name = model_name |
| 23 | + self._model = CrossEncoder(model_name) |
| 24 | + self._fitted = True |
| 25 | + |
| 26 | + def fit(self, corpus: list[str] | None = None) -> PairCrossEncoderBuilder: |
| 27 | + return self |
| 28 | + |
| 29 | + def feature_names(self) -> list[str]: |
| 30 | + return ["cross_score", "len_ratio", "abs_len_diff", "len_sum"] |
| 31 | + |
| 32 | + def fit_from_frame( |
| 33 | + self, |
| 34 | + df: pd.DataFrame, |
| 35 | + col_q1: str = "question1", |
| 36 | + col_q2: str = "question2", |
| 37 | + ) -> PairCrossEncoderBuilder: |
| 38 | + return self |
| 39 | + |
| 40 | + def transform_pairs( |
| 41 | + self, |
| 42 | + q1: list[str], |
| 43 | + q2: list[str], |
| 44 | + ) -> np.ndarray: |
| 45 | + if len(q1) != len(q2): |
| 46 | + raise ValueError("q1 and q2 must have the same length.") |
| 47 | + t1 = [clean_text(x) for x in q1] |
| 48 | + t2 = [clean_text(x) for x in q2] |
| 49 | + scores = np.asarray( |
| 50 | + self._model.predict(list(zip(t1, t2, strict=True)), show_progress_bar=False), |
| 51 | + dtype=np.float64, |
| 52 | + ).reshape(-1) |
| 53 | + |
| 54 | + rows: list[list[float]] = [] |
| 55 | + for idx, (a, b) in enumerate(zip(t1, t2, strict=True)): |
| 56 | + la, lb = len(a.split()), len(b.split()) |
| 57 | + max_len = max(la, lb, 1) |
| 58 | + len_ratio = min(la, lb) / max_len |
| 59 | + rows.append([float(scores[idx]), len_ratio, float(abs(la - lb)), float(la + lb)]) |
| 60 | + return np.asarray(rows, dtype=np.float64) |
| 61 | + |
| 62 | + def transform_frame( |
| 63 | + self, |
| 64 | + df: pd.DataFrame, |
| 65 | + col_q1: str = "question1", |
| 66 | + col_q2: str = "question2", |
| 67 | + ) -> np.ndarray: |
| 68 | + return self.transform_pairs( |
| 69 | + df[col_q1].astype(str).tolist(), |
| 70 | + df[col_q2].astype(str).tolist(), |
| 71 | + ) |
0 commit comments