项目作者: MaartenGr

项目描述 :
Fuzzy string matching, grouping, and evaluation.
高级语言: Python
项目地址: git://github.com/MaartenGr/PolyFuzz.git
创建时间: 2020-11-21T06:28:09Z
项目社区:https://github.com/MaartenGr/PolyFuzz

开源协议:MIT License

下载


PyPI Downloads
PyPI - Python
PyPI - License
PyPI - PyPi
Build
docs
PolyFuzz performs fuzzy string matching, string grouping, and contains extensive evaluation functions.
PolyFuzz is meant to bring fuzzy string matching techniques together within a single framework.

Currently, methods include a variety of edit distance measures, a character-based n-gram TF-IDF, word embedding
techniques such as FastText and GloVe, and 🤗 transformers embeddings.

Corresponding medium post can be found here.

Installation

You can install PolyFuzz via pip:

  1. pip install polyfuzz

You may want to install more depending on the transformers and language backends that you will be using. The possible installations are:

  1. pip install polyfuzz[sbert]
  2. pip install polyfuzz[flair]
  3. pip install polyfuzz[gensim]
  4. pip install polyfuzz[spacy]
  5. pip install polyfuzz[use]

If you want to speed up the cosine similarity comparison and decrease memory usage when using embedding models,
you can use sparse_dot_topn which is installed via:

  1. pip install polyfuzz[fast]

Installation Issues

You might run into installation issues with sparse_dot_topn. If so, one solution that has worked for many
is by installing it via conda first before installing PolyFuzz:

bash conda install -c conda-forge sparse_dot_topn

If that does not work, I would advise you to look through their
issues](https://github.com/ing-bank/sparse_dot_topn/issues) page or continue to use PolyFuzz without sparse_dot_topn.

Getting Started

For an in-depth overview of the possibilities of PolyFuzz
you can check the full documentation here or you can follow along
with the notebook here.

Quick Start

The main goal of PolyFuzz is to allow the user to perform different methods for matching strings.
We start by defining two lists, one to map from and one to map to. We are going to be using TF-IDF to create
n-grams on a character level in order to compare similarity between strings. Then, we calculate the similarity
between strings by calculating the cosine similarity between vector representations.

We only have to instantiate PolyFuzz with TF-IDF and match the lists:

  1. from polyfuzz import PolyFuzz
  2. from_list = ["apple", "apples", "appl", "recal", "house", "similarity"]
  3. to_list = ["apple", "apples", "mouse"]
  4. model = PolyFuzz("TF-IDF")
  5. model.match(from_list, to_list)

The resulting matches can be accessed through model.get_matches():

  1. >>> model.get_matches()
  2. From To Similarity
  3. 0 apple apple 1.000000
  4. 1 apples apples 1.000000
  5. 2 appl apple 0.783751
  6. 3 recal None 0.000000
  7. 4 house mouse 0.587927
  8. 5 similarity None 0.000000

NOTE 1: If you want to compare distances within a single list, you can simply pass that list as such: model.match(from_list)

NOTE 2: When instantiating PolyFuzz we also could have used “EditDistance” or “Embeddings” to quickly
access Levenshtein and FastText (English) respectively.

Production

The .match function allows you to quickly extract similar strings. However, after selecting the right models to be used, you may want to use PolyFuzz
in production to match incoming strings. To do so, we can make use of the familiar fit, transform, and fit_transform functions.

Let’s say that we have a list of words that we know to be correct called train_words. We want to any incoming word to mapped to one of the words in train_words.
In other words, we fit on train_words and we use transform on any incoming words:

  1. from sklearn.datasets import fetch_20newsgroups
  2. from sklearn.feature_extraction.text import CountVectorizer
  3. from polyfuzz import PolyFuzz
  4. train_words = ["apple", "apples", "appl", "recal", "house", "similarity"]
  5. unseen_words = ["apple", "apples", "mouse"]
  6. # Fit
  7. model = PolyFuzz("TF-IDF")
  8. model.fit(train_words)
  9. # Transform
  10. results = model.transform(unseen_words)

In the above example, we are using fit on train_words to calculate the TF-IDF representation of those words which are saved to be used again in transform.
This speeds up transform quite a bit since all TF-IDF representations are stored when applying fit.

Then, we apply save and load the model as follows to be used in production:

  1. # Save the model
  2. model.save("my_model")
  3. # Load the model
  4. loaded_model = PolyFuzz.load("my_model")

Group Matches

We can group the matches To as there might be significant overlap in strings in our to_list.
To do this, we calculate the similarity within strings in to_list and use single linkage to then
group the strings with a high similarity.

When we extract the new matches, we can see an additional column Group in which all the To matches were grouped to:

  1. >>> model.group(link_min_similarity=0.75)
  2. >>> model.get_matches()
  3. From To Similarity Group
  4. 0 apple apple 1.000000 apples
  5. 1 apples apples 1.000000 apples
  6. 2 appl apple 0.783751 apples
  7. 3 recal None 0.000000 None
  8. 4 house mouse 0.587927 mouse
  9. 5 similarity None 0.000000 None

As can be seen above, we grouped apple and apples together to apple such that when a string is mapped to apple it
will fall in the cluster of [apples, apple] and will be mapped to the first instance in the cluster which is apples.

Precision-Recall Curve

Next, we would like to see how well our model is doing on our data. We express our results as
precision and recall where precision is defined as the minimum similarity score before a match is correct and
recall the percentage of matches found at a certain minimum similarity score.

Creating the visualizations is as simple as:

  1. model.visualize_precision_recall()

Models

Currently, the following models are implemented in PolyFuzz:

  • TF-IDF
  • EditDistance (you can use any distance measure, see documentation)
  • FastText and GloVe
  • 🤗 Transformers

With Flair, we can use all 🤗 Transformers models.
We simply have to instantiate any Flair WordEmbedding method and pass it through PolyFuzzy.

All models listed above can be found in polyfuzz.models and can be used to create and compare different models:

  1. from polyfuzz.models import EditDistance, TFIDF, Embeddings
  2. from flair.embeddings import TransformerWordEmbeddings
  3. embeddings = TransformerWordEmbeddings('bert-base-multilingual-cased')
  4. bert = Embeddings(embeddings, min_similarity=0, model_id="BERT")
  5. tfidf = TFIDF(min_similarity=0)
  6. edit = EditDistance()
  7. string_models = [bert, tfidf, edit]
  8. model = PolyFuzz(string_models)
  9. model.match(from_list, to_list)

To access the results, we again can call get_matches but since we have multiple models we get back a dictionary
of dataframes back.

In order to access the results of a specific model, call get_matches with the correct id:

  1. >>> model.get_matches("BERT")
  2. From To Similarity
  3. 0 apple apple 1.000000
  4. 1 apples apples 1.000000
  5. 2 appl apple 0.928045
  6. 3 recal apples 0.825268
  7. 4 house mouse 0.887524
  8. 5 similarity mouse 0.791548

Finally, visualize the results to compare the models:

  1. model.visualize_precision_recall(kde=True)

Custom Grouper

We can even use one of the polyfuzz.models to be used as the grouper in case you would like to use
something else than the standard TF-IDF model:

  1. model = PolyFuzz("TF-IDF")
  2. model.match(from_list, to_list)
  3. edit_grouper = EditDistance(n_jobs=1)
  4. model.group(edit_grouper)

Custom Models

Although the options above are a great solution for comparing different models, what if you have developed your own?
If you follow the structure of PolyFuzz’s BaseMatcher
you can quickly implement any model you would like.

Below, we are implementing the ratio similarity measure from RapidFuzz.

  1. import numpy as np
  2. import pandas as pd
  3. from rapidfuzz import fuzz
  4. from polyfuzz.models import BaseMatcher
  5. class MyModel(BaseMatcher):
  6. def match(self, from_list, to_list, **kwargs):
  7. # Calculate distances
  8. matches = [[fuzz.ratio(from_string, to_string) / 100 for to_string in to_list]
  9. for from_string in from_list]
  10. # Get best matches
  11. mappings = [to_list[index] for index in np.argmax(matches, axis=1)]
  12. scores = np.max(matches, axis=1)
  13. # Prepare dataframe
  14. matches = pd.DataFrame({'From': from_list,'To': mappings, 'Similarity': scores})
  15. return matches

Then, we can simply create an instance of MyModel and pass it through PolyFuzz:

  1. custom_model = MyModel()
  2. model = PolyFuzz(custom_model)

Citation

To cite PolyFuzz in your work, please use the following bibtex reference:

  1. @misc{grootendorst2020polyfuzz,
  2. author = {Maarten Grootendorst},
  3. title = {PolyFuzz: Fuzzy string matching, grouping, and evaluation.},
  4. year = 2020,
  5. publisher = {Zenodo},
  6. version = {v0.2.2},
  7. doi = {10.5281/zenodo.4461050},
  8. url = {https://doi.org/10.5281/zenodo.4461050}
  9. }

References

Below, you can find several resources that were used for or inspired by when developing PolyFuzz:

Edit distance algorithms:
These algorithms focus primarily on edit distance measures and can be used in polyfuzz.models.EditDistance:

Other interesting repos: