-
Notifications
You must be signed in to change notification settings - Fork 237
Support for Flair Embeddings: hero.embed(s, flair_embedding) function #146
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
Draft
henrifroese
wants to merge
17
commits into
jbesomi:master
Choose a base branch
from
SummerOfCode-NoHate:Flair_Embeddings
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 9 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
78e668e
first implementation of flair embeddings in `hero.embed`
henrifroese 30b4c55
- Add tests
henrifroese 2447bf1
Use --user option for travis installation to not require root privileges
henrifroese 14b6488
Switch to virtual environment to be able to install packages
henrifroese bba8f7c
install pip again
henrifroese 8128e09
Roll back travis changes
henrifroese e92c19f
Configure only MacOS to use --user flag
henrifroese c571e3c
integrate direct torch download for windows with correct command in t…
henrifroese ee73958
install with --no-deps flag
henrifroese def237d
Switch flair to dev dependency
henrifroese 40794b9
Incorporate suggested Travis changes
henrifroese 764c513
Incorporate other suggestions from review.
henrifroese dc07e85
move macOS install up
henrifroese df89d71
install black for macOS; pipeline fixed
henrifroese 6fc15f6
Move embeddings to representation (and test_embeddings tests to test_…
henrifroese c28c3af
Merge branch 'master' into Flair_Embeddings
henrifroese 2af6608
bugfix
henrifroese File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| import pandas as pd | ||
| import numpy as np | ||
| from flair.embeddings import ( | ||
| WordEmbeddings, | ||
| DocumentPoolEmbeddings, | ||
| DocumentRNNEmbeddings, | ||
| TransformerDocumentEmbeddings, | ||
| SentenceTransformerDocumentEmbeddings, | ||
| ) | ||
|
|
||
| from . import PandasTestCase | ||
|
|
||
| import doctest | ||
| import unittest | ||
| import string | ||
| import math | ||
| import warnings | ||
| from parameterized import parameterized | ||
|
|
||
| from texthero import embeddings, preprocessing, _types | ||
|
|
||
|
|
||
| """ | ||
| Test doctest | ||
| """ | ||
|
|
||
|
|
||
| def load_tests(loader, tests, ignore): | ||
| tests.addTests(doctest.DocTestSuite(embeddings)) | ||
| return tests | ||
|
|
||
|
|
||
| s_tokenized = pd.Series( | ||
| [["Test", "Test2", "!", "yes", "hä", "^°"], ["Test3", "wow ", "aha", "super"]], | ||
| index=[5, 7], | ||
| ) | ||
|
|
||
|
|
||
| """ | ||
| Test embeddings functions. | ||
| """ | ||
|
|
||
|
|
||
| class TestEmbeddings(PandasTestCase): | ||
| """ | ||
| Test embed function. | ||
|
|
||
| There are three types of Document Embeddings that | ||
| don't require additional dependencies | ||
| (the SentenceTransformerDocumentEmbeddings requires extra | ||
| dependencies), | ||
| see `here https://github.com/flairNLP/flair/blob/master/resources/docs/TUTORIAL_5_DOCUMENT_EMBEDDINGS.md`_. | ||
| We test all of them here. | ||
| """ | ||
|
|
||
| def test_embed_document_pool_embedding(self): | ||
| word_embedding = WordEmbeddings("turian") | ||
| document_embedding = DocumentPoolEmbeddings([word_embedding]) | ||
|
|
||
| s_return = embeddings.embed(s_tokenized, document_embedding) | ||
|
|
||
| self.assertTrue(isinstance(s_return.iloc[0], list)) | ||
| self.assertTrue(isinstance(s_return.iloc[1], list)) | ||
| self.assertTrue(len(s_return.iloc[0]) == len(s_return.iloc[1]) > 0) | ||
|
|
||
| pd.testing.assert_index_equal(s_return.index, s_return.index) | ||
|
|
||
| # check if output is valid VectorSeries | ||
| try: | ||
| _types.VectorSeries.check_series(s_return) | ||
| except: | ||
| self.fail("Output is not a valid VectorSeries.") | ||
|
|
||
| del word_embedding | ||
|
|
||
| def test_embed_document_rnn_embedding(self): | ||
| word_embedding = WordEmbeddings("turian") | ||
| document_embedding = DocumentPoolEmbeddings([word_embedding]) | ||
|
|
||
| s_return = embeddings.embed(s_tokenized, document_embedding) | ||
|
|
||
| self.assertTrue(isinstance(s_return.iloc[0], list)) | ||
| self.assertTrue(isinstance(s_return.iloc[1], list)) | ||
| self.assertTrue(len(s_return.iloc[0]) == len(s_return.iloc[1]) > 0) | ||
|
|
||
| pd.testing.assert_index_equal(s_return.index, s_return.index) | ||
|
|
||
| # check if output is valid VectorSeries | ||
| try: | ||
| _types.VectorSeries.check_series(s_return) | ||
| except: | ||
| self.fail("Output is not a valid VectorSeries.") | ||
|
|
||
| del word_embedding | ||
|
|
||
| def test_embed_transformer_document_embedding(self): | ||
| # load smallest available transformer model | ||
| document_embedding = TransformerDocumentEmbeddings( | ||
| "google/reformer-crime-and-punishment" | ||
| ) | ||
|
|
||
| s_return = embeddings.embed(s_tokenized, document_embedding) | ||
|
|
||
| self.assertTrue(isinstance(s_return.iloc[0], list)) | ||
| self.assertTrue(isinstance(s_return.iloc[1], list)) | ||
| self.assertTrue(len(s_return.iloc[0]) == len(s_return.iloc[1]) > 0) | ||
|
|
||
| pd.testing.assert_index_equal(s_return.index, s_return.index) | ||
|
|
||
| # check if output is valid VectorSeries | ||
| try: | ||
| _types.VectorSeries.check_series(s_return) | ||
| except: | ||
| self.fail("Output is not a valid VectorSeries.") | ||
|
|
||
| del document_embedding |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,4 +15,7 @@ | |
| from . import nlp | ||
| from .nlp import * | ||
|
|
||
| from . import embeddings | ||
| from .embeddings import * | ||
|
|
||
| from . import stopwords | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| """ | ||
| embeddings.py | ||
| ------------- | ||
|
|
||
| Embed documents and work with the embeddings to find similar documents, | ||
|
henrifroese marked this conversation as resolved.
Outdated
|
||
| find topics, ... . | ||
|
|
||
| There are many different ways to transform text data into vectors to gain | ||
| insights from them. The resulting vectors are called _embeddings_. | ||
| A _word embedding_ assigns a vector to each word, a _document embedding_ | ||
| (sometimes called thought _thought vector_) | ||
|
henrifroese marked this conversation as resolved.
Outdated
|
||
| assigns a vector to each document. | ||
|
|
||
| One way to get embeddings is to use a function such as tfidf, | ||
| count, or term_frequency that creates vectors depending | ||
| on which words occur how frequently. | ||
|
|
||
| Another option is to use embeddings that try to directly capture | ||
| the semantic relationship between words or sentences. For example, | ||
| the vector of 'biochemistry' minus the vector of 'chemistry' is | ||
| close to the vector of 'biology'. | ||
|
|
||
| In Texthero, both options are supported. The second option is | ||
| implemented through the `Flair library <https://github.com/flairNLP/flair>`_ | ||
| """ | ||
|
henrifroese marked this conversation as resolved.
Outdated
|
||
|
|
||
| import pandas as pd | ||
| import numpy as np | ||
|
|
||
| # We only `import flair` and | ||
| # call everything from flair directly, | ||
| # e.g. flair.data.Tokens, to not pollute our | ||
|
henrifroese marked this conversation as resolved.
Outdated
|
||
| # namespace with similarly sounding names. | ||
| import flair | ||
|
|
||
| from typing import List, Union | ||
|
|
||
| from texthero._types import InputSeries, TokenSeries, VectorSeries | ||
|
|
||
|
|
||
| """ | ||
| Helper functions. | ||
| """ | ||
|
|
||
|
|
||
| def _texthero_init_for_flair_sentence(self, already_tokenized_text: List[str]): | ||
|
henrifroese marked this conversation as resolved.
Outdated
|
||
| """ | ||
| To use Flair embeddings, Flair needs as input a | ||
| 'flair.Sentence' object. Creating such an object | ||
| only works from strings in flair. However, we want | ||
| our embeddings to work on TokenSeries, so we | ||
| overwrite the 'flair Sentence' __init__ method with | ||
| this method to create Sentence objects from already | ||
| tokenized text. | ||
| """ | ||
|
|
||
| super(flair.data.Sentence, self).__init__() | ||
|
|
||
| self.tokens: List[flair.data.Token] = [] | ||
| self._embeddings: Dict = {} | ||
| self.language_code: str = None | ||
| self.tokenized = None | ||
|
|
||
| # already tokenized -> simply add the tokens | ||
| for token in already_tokenized_text: | ||
|
henrifroese marked this conversation as resolved.
Outdated
|
||
| self.add_token(token) | ||
|
|
||
|
|
||
| # Overwrite flair Sentence __init__ method to handle already tokenized text | ||
| flair.data.Sentence.__init__ = _texthero_init_for_flair_sentence | ||
|
|
||
|
|
||
| """ | ||
| Support for flair embeddings. | ||
| """ | ||
|
|
||
|
|
||
| @InputSeries(TokenSeries) | ||
| def embed( | ||
|
henrifroese marked this conversation as resolved.
Outdated
|
||
| s: TokenSeries, flair_embedding: flair.embeddings.DocumentEmbeddings | ||
| ) -> VectorSeries: | ||
| """ | ||
| Generate a vector for each document using the given flair_embedding. | ||
|
|
||
| Given a tokenized Series and a | ||
| `Flair Document Embedding https://github.com/flairNLP/flair/blob/master/resources/docs/TUTORIAL_5_DOCUMENT_EMBEDDINGS.md`_, | ||
| return the document embedding for every | ||
| document in the tokenized Series. | ||
|
|
||
|
henrifroese marked this conversation as resolved.
Outdated
|
||
| Examples | ||
| -------- | ||
| >>> import texthero as hero | ||
| >>> import pandas as pd | ||
| >>> from flair.embeddings import TransformerDocumentEmbeddings | ||
| >>> embedding = TransformerDocumentEmbeddings('bert-base-uncased') | ||
| >>> s = pd.Series(["Text of doc 1", "Text of doc 2"]).pipe(hero.tokenize) | ||
| >>> hero.embed(s, embedding) # doctest: +SKIP | ||
|
henrifroese marked this conversation as resolved.
Outdated
|
||
| 0 [-0.6618074, -0.20467158, -0.05876905, -0.3482... | ||
| 1 [-0.5505255, -0.21915795, -0.0913163, -0.26856... | ||
| dtype: object | ||
|
|
||
| See Also | ||
| -------- | ||
| `Flair Document Embedding https://github.com/flairNLP/flair/blob/master/resources/docs/TUTORIAL_5_DOCUMENT_EMBEDDINGS.md`_ | ||
| """ | ||
|
|
||
| def _embed_and_return_embedding(x): | ||
| # flair embeddings need a 'flair Sentence' object as input. | ||
| x = flair.data.Sentence(x) | ||
| # Calculate the embedding; flair writes it to x.embedding | ||
| flair_embedding.embed(x) | ||
| # Return it as list. | ||
| return x.embedding.detach().tolist() | ||
|
|
||
| if isinstance(flair_embedding, flair.embeddings.DocumentEmbeddings): | ||
| s = s.apply(lambda x: _embed_and_return_embedding(x)) | ||
| else: | ||
| raise ValueError( | ||
| "Unknown embedding type. Texthero only works with" | ||
| " flair DocumentEmbeddings." | ||
| ) | ||
|
|
||
| return s | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.