|
| 1 | +import json |
| 2 | +import tempfile |
| 3 | +from collections import OrderedDict |
| 4 | +from pathlib import Path |
| 5 | +from typing import Union |
| 6 | + |
| 7 | +import joblib |
| 8 | +import numpy as np |
| 9 | +from huggingface_hub import HfApi |
| 10 | +from sentence_transformers import SentenceTransformer |
| 11 | +from sklearn.base import BaseEstimator, TransformerMixin |
| 12 | + |
| 13 | +from turftopic.base import Encoder |
| 14 | +from turftopic.encoders.multimodal import MultimodalEncoder |
| 15 | +from turftopic.serialization import create_readme, get_package_versions |
| 16 | + |
| 17 | +Seeds = tuple[list[str], list[str]] |
| 18 | + |
| 19 | + |
| 20 | +class ConceptVectorProjection(BaseEstimator, TransformerMixin): |
| 21 | + """Concept Vector Projection model from [Lyngbæk et al. (2025)](https://doi.org/10.63744/nVu1Zq5gRkuD) |
| 22 | + Can be used to project document embeddings onto a difference projection vector between positive and negative seed phrases. |
| 23 | + The primary use case is sentiment analysis, and continuous sentiment scores, |
| 24 | + especially for languages where dedicated models are not available. |
| 25 | +
|
| 26 | + Parameters |
| 27 | + ---------- |
| 28 | + seeds: (list[str], list[str]) or list of (str, (list[str], list[str])) |
| 29 | + If you want to project to a single concept, then |
| 30 | + a tuple of (list of negative terms, list of positive terms). <br> |
| 31 | + If there are multiple concepts, they should be specified as (name, Seeds) tuples in a list. |
| 32 | + Alternatively, seeds can be an OrderedDict with the names of the concepts being the keys, |
| 33 | + and the tuples of negative and positive seeds as the values. |
| 34 | + encoder: str or SentenceTransformer |
| 35 | + Model to produce document representations, paraphrase-multilingual-mpnet-base-v2 is the default |
| 36 | + per Lyngbæk et al. (2025). |
| 37 | + """ |
| 38 | + |
| 39 | + def __init__( |
| 40 | + self, |
| 41 | + seeds: Union[Seeds, list[tuple[str, Seeds]], OrderedDict[str, Seeds]], |
| 42 | + encoder: Union[ |
| 43 | + Encoder, str, MultimodalEncoder |
| 44 | + ] = "sentence-transformers/paraphrase-multilingual-mpnet-base-v2", |
| 45 | + ): |
| 46 | + self.seeds = seeds |
| 47 | + if isinstance(seeds, OrderedDict): |
| 48 | + self._seeds = seeds |
| 49 | + elif ( |
| 50 | + (len(seeds) == 2) |
| 51 | + and (isinstance(seeds, tuple)) |
| 52 | + and (isinstance(seeds[0][0], str)) |
| 53 | + ): |
| 54 | + self._seeds = OrderedDict([("default", seeds)]) |
| 55 | + else: |
| 56 | + self._seeds = OrderedDict(seeds) |
| 57 | + self.encoder = encoder |
| 58 | + if isinstance(encoder, str): |
| 59 | + self.encoder_ = SentenceTransformer(encoder) |
| 60 | + else: |
| 61 | + self.encoder_ = encoder |
| 62 | + self.classes_ = np.array([name for name in self._seeds]) |
| 63 | + self.concept_matrix_ = [] |
| 64 | + for _, (positive, negative) in self._seeds.items(): |
| 65 | + positive_emb = self.encoder_.encode(positive) |
| 66 | + negative_emb = self.encoder_.encode(negative) |
| 67 | + cv = np.mean(positive_emb, axis=0) - np.mean(negative_emb, axis=0) |
| 68 | + self.concept_matrix_.append(cv / np.linalg.norm(cv)) |
| 69 | + self.concept_matrix_ = np.stack(self.concept_matrix_) |
| 70 | + |
| 71 | + def get_feature_names_out(self): |
| 72 | + """Returns concept names in an array.""" |
| 73 | + return self.classes_ |
| 74 | + |
| 75 | + def fit_transform(self, raw_documents=None, y=None, embeddings=None): |
| 76 | + """Project documents onto the concept vectors. |
| 77 | +
|
| 78 | + Parameters |
| 79 | + ---------- |
| 80 | + raw_documents: list[str] or None |
| 81 | + List of documents to project to the concept vectors. |
| 82 | + embeddings: ndarray of shape (n_documents, n_dimensions) |
| 83 | + Document embeddings (has to be created with the same encoder as the concept vectors.) |
| 84 | +
|
| 85 | + Returns |
| 86 | + ------- |
| 87 | + document_concept_matrix: ndarray of shape (n_documents, n_dimensions) |
| 88 | + Prevalance of each concept in each document. |
| 89 | + """ |
| 90 | + if (raw_documents is None) and (embeddings is None): |
| 91 | + raise ValueError( |
| 92 | + "Either embeddings or raw_documents has to be passed, both are None." |
| 93 | + ) |
| 94 | + if embeddings is None: |
| 95 | + embeddings = self.encoder_.encode(raw_documents) |
| 96 | + return embeddings @ self.concept_matrix_.T |
| 97 | + |
| 98 | + def transform(self, raw_documents=None, embeddings=None): |
| 99 | + """Project documents onto the concept vectors. |
| 100 | +
|
| 101 | + Parameters |
| 102 | + ---------- |
| 103 | + raw_documents: list[str] or None |
| 104 | + List of documents to project to the concept vectors. |
| 105 | + embeddings: ndarray of shape (n_documents, n_dimensions) |
| 106 | + Document embeddings (has to be created with the same encoder as the concept vectors.) |
| 107 | +
|
| 108 | + Returns |
| 109 | + ------- |
| 110 | + document_concept_matrix: ndarray of shape (n_documents, n_dimensions) |
| 111 | + Prevalance of each concept in each document. |
| 112 | + """ |
| 113 | + return self.fit_transform(raw_documents, embeddings=embeddings) |
| 114 | + |
| 115 | + def to_disk(self, out_dir: Union[Path, str]): |
| 116 | + """Persists model to directory on your machine. |
| 117 | +
|
| 118 | + Parameters |
| 119 | + ---------- |
| 120 | + out_dir: Path | str |
| 121 | + Directory to save the model to. |
| 122 | + """ |
| 123 | + out_dir = Path(out_dir) |
| 124 | + out_dir.mkdir(exist_ok=True) |
| 125 | + package_versions = get_package_versions() |
| 126 | + with out_dir.joinpath("package_versions.json").open("w") as ver_file: |
| 127 | + ver_file.write(json.dumps(package_versions)) |
| 128 | + joblib.dump(self, out_dir.joinpath("model.joblib")) |
| 129 | + |
| 130 | + def push_to_hub(self, repo_id: str): |
| 131 | + """Uploads model to HuggingFace Hub |
| 132 | +
|
| 133 | + Parameters |
| 134 | + ---------- |
| 135 | + repo_id: str |
| 136 | + Repository to upload the model to. |
| 137 | + """ |
| 138 | + api = HfApi() |
| 139 | + api.create_repo(repo_id, exist_ok=True) |
| 140 | + with tempfile.TemporaryDirectory() as tmp_dir: |
| 141 | + readme_path = Path(tmp_dir).joinpath("README.md") |
| 142 | + with readme_path.open("w") as readme_file: |
| 143 | + readme_file.write(create_readme(self, repo_id)) |
| 144 | + self.to_disk(tmp_dir) |
| 145 | + api.upload_folder( |
| 146 | + folder_path=tmp_dir, |
| 147 | + repo_id=repo_id, |
| 148 | + repo_type="model", |
| 149 | + ) |
0 commit comments