Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added the DocumentTFIDFEmbeddings #2086

Merged
merged 5 commits into from
Feb 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion flair/embeddings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from .document import DocumentEmbeddings
from .document import TransformerDocumentEmbeddings
from .document import DocumentPoolEmbeddings
from .document import DocumentTFIDFEmbeddings
from .document import DocumentRNNEmbeddings
from .document import DocumentLMEmbeddings
from .document import SentenceTransformerDocumentEmbeddings
Expand All @@ -47,4 +48,4 @@
from .legacy import BertEmbeddings
from .legacy import DocumentMeanEmbeddings
from .legacy import DocumentLSTMEmbeddings
from .legacy import ELMoTransformerEmbeddings
from .legacy import ELMoTransformerEmbeddings
45 changes: 45 additions & 0 deletions flair/embeddings/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
from flair.embeddings.token import TokenEmbeddings, StackedEmbeddings, FlairEmbeddings
from flair.nn import LockedDropout, WordDropout

from sklearn.feature_extraction.text import TfidfVectorizer

log = logging.getLogger("flair")


Expand Down Expand Up @@ -333,6 +335,49 @@ def extra_repr(self):
return f"fine_tune_mode={self.fine_tune_mode}, pooling={self.pooling}"


class DocumentTFIDFEmbeddings(DocumentEmbeddings):
def __init__(
self,
train_dataset,
**vectorizer_params,
):
"""The constructor for DocumentTFIDFEmbeddings.
:param train_dataset: the train dataset which will be used to construct vectorizer
:param vectorizer_params: parameters given to Scikit-learn's TfidfVectorizer constructor
"""
super().__init__()

import numpy as np
self.vectorizer = TfidfVectorizer(dtype=np.float32, **vectorizer_params)
self.vectorizer.fit([s.to_original_text() for s in train_dataset])

self.__embedding_length: int = len(self.vectorizer.vocabulary_)

self.to(flair.device)

self.name: str = f"document_tfidf"

@property
def embedding_length(self) -> int:
return self.__embedding_length

def embed(self, sentences: Union[List[Sentence], Sentence]):
"""Add embeddings to every sentence in the given list of sentences."""

# if only one sentence is passed, convert to list of sentence
if isinstance(sentences, Sentence):
sentences = [sentences]

raw_sentences = [s.to_original_text() for s in sentences]
tfidf_vectors = torch.from_numpy(self.vectorizer.transform(raw_sentences).A)

for sentence_id, sentence in enumerate(sentences):
sentence.set_embedding(self.name, tfidf_vectors[sentence_id])

def _add_embeddings_internal(self, sentences: List[Sentence]):
pass


class DocumentRNNEmbeddings(DocumentEmbeddings):
def __init__(
self,
Expand Down