|
| 1 | +import abc |
| 2 | +from typing import Any, Dict, Generic, List, Optional, TypeVar |
| 3 | + |
| 4 | +import numpy as np |
| 5 | +from flair.data import Sentence |
| 6 | +from numpy import typing as nptyping |
| 7 | +from sklearn.base import BaseEstimator, TransformerMixin |
| 8 | +from sklearn.feature_extraction.text import _VectorizerMixin |
| 9 | + |
| 10 | +from embeddings.embedding.flair_embedding import FlairEmbedding |
| 11 | +from embeddings.utils.array_like import ArrayLike |
| 12 | + |
| 13 | +Output = TypeVar("Output") |
| 14 | + |
| 15 | + |
| 16 | +# ignoring the mypy error due to no types (Any) in TransformerMixin and BaseEstimator classes |
| 17 | +class FlairVectorizer(TransformerMixin, _VectorizerMixin, BaseEstimator, Generic[Output]): # type: ignore |
| 18 | + def __init__(self, flair_embedding: FlairEmbedding) -> None: |
| 19 | + self.embedder = flair_embedding |
| 20 | + |
| 21 | + def fit(self, x: ArrayLike, y: Optional[ArrayLike] = None) -> None: |
| 22 | + pass |
| 23 | + |
| 24 | + @abc.abstractmethod |
| 25 | + def transform(self, x: ArrayLike) -> Output: |
| 26 | + pass |
| 27 | + |
| 28 | + def fit_transform(self, x: ArrayLike, y: Optional[ArrayLike] = None, **kwargs: Any) -> Output: |
| 29 | + return self.transform(x) |
| 30 | + |
| 31 | + |
| 32 | +class FlairDocumentVectorizer(FlairVectorizer[nptyping.NDArray[np.float_]]): |
| 33 | + def transform(self, x: ArrayLike) -> nptyping.NDArray[np.float_]: |
| 34 | + sentences = [Sentence(example) for example in x] |
| 35 | + embeddings = [sentence.embedding.numpy() for sentence in self.embedder.embed(sentences)] |
| 36 | + return np.vstack(embeddings) |
| 37 | + |
| 38 | + |
| 39 | +class FlairWordVectorizer(FlairVectorizer[List[List[Dict[int, float]]]]): |
| 40 | + def transform(self, x: ArrayLike) -> List[List[Dict[int, float]]]: |
| 41 | + sentences = [Sentence(example) for example in x] |
| 42 | + embeddings = [sentence for sentence in self.embedder.embed(sentences)] |
| 43 | + return [ |
| 44 | + [{i: value for i, value in enumerate(word.embedding.numpy())} for word in sent] |
| 45 | + for sent in embeddings |
| 46 | + ] |
0 commit comments