π« Better, faster and more customisable matcher
Related issues: #1567, #1711, #1819, #1939, #1945, #1951, #2042
We're currently in the process of rewriting the match loop, fixing long-standing issues and making it easier to extend the Matcher and PhraseMatcher. The community contributions by @GregDubbin and @savkov have already made a big difference β we can't wait to get it all ready and shipped.
This issue discusses some of the planned new features and additions to the match patterns API, including matching by custom extension attributes (Token._.), regular expressions, set membership and rich comparison for numeric values.
New features
Custom extension attributes
spaCy v2.0 introduced custom extension attributes on the Doc, Span and Token. Custom attributes make it easier to attach arbitrary data to the built-in objects, and let users take advantage of spaCy's data structures and the Doc object as the "single source of truth". However, not being able to match on custom attributes was quite limiting (see #1499, #1825).
The new patterns spec will allow an _ space on token patterns, which can map to a dictionary keyed by the attribute names:
Token.set_extension('is_fruit', getter=lambda token: token.text in ('apple', 'banana'))
pattern = [{'LEMMA': 'have'}, {'_': {'is_fruit': True}}]
matcher.add('HAVING_FRUIT', None, pattern)
Both regular attribute extensions (with a default value) and property extensions (with a getter) will be supported and can be combined for more exact matches.
pattern = [{'_': {'is_fruit': True, 'fruit_color': 'red', 'fruit_rating': 5}}]
Rich comparison for numeric values
Token patterns already allow specifying a LENGTH (the token's character length). However, matching tokens of between five and ten characters previously required adding 6 copies of the exact same pattern, introducing unnecessary overhead. Numeric attributes can now also specify a dictionary with the predicate (e.g. '>' or '<=') mapped to the value. For example:
pattern = [{'ENT_TYPE': 'ORG', 'LENGTH': 5}] # exact length
pattern = [{'ENT_TYPE': 'ORG', 'LENGTH': {'>=': 5}}] # length with predicate
The second pattern above will match a token with the entity type ORG that's 5 or more characters long. Combined with custom attributes, this allows very powerful queries combining both linguistic features and numeric data:
# match a token based on custom numeric attributes
pattern = [{'_': {'fruit_rating': {'>': 7}, 'fruit_weight': {'>=': 100, '<': 300}}]
# match a verb with ._.sentiment_score >= 5 and one token on each side
pattern = [{}, {'POS': 'VERB', '_': {'sentiment_score': {'>=': 0.5}}}, {}]
Defining predicates and values as a dictionary instead of a single string like '>=5' allows us to avoid string parsing, and lets spaCy handle custom attributes without requiring the user to specify their types upfront. (While we know the type of the built-in LENGTH attribute, spaCy has no way of knowing whether the value '<3' of a custom attribute should be interpreted as "less than 3", or the heart emoticon.)
Set membership
This is another feature that has been requested before and will now be much easier to implement. Similar to the predicate mapping for numeric values, token attributes can now also be defined as dictionaries. The keys IN or NOT_IN can be used to indicate set membership and non-membership.
pattern = [{'LEMMA': {'IN': ['like', 'love']}},
{'LOWER': {'IN': ['apples', 'bananas']}}]
The above pattern will match a token with the lemma "like" or "love", followed by a token whose lowercase form is either "apples" or "bananas". For example, "loving apples" or "likes bananas". Lists can be used for all non-boolean values, including custom _ attributes:
# verb or conjunction followed by custom is_fruit token
pattern = [{'POS': {'IN': ['VERB', 'CONJ', 'CCONJ']}},
{'_': {'is_fruit': True, 'fruit_color': {'NOT_IN': ['red', 'yellow']}}}]
# set membership of numeric custom attributes
pattern = [{'_': {'is_customer': True, 'customer_year': {'IN': [2018, 2017, 2016]}}}]
# combination of predicates and and non-membership
pattern = [{'_': {'custom_count': {'<=': 100, 'NOT_IN': [12, 66, 79]}}}]
Regular expressions
Using regular expressions within token patterns is already possible via custom binary flags (see #1567). However, this has some inconvenient limitations β including the patterns not being JSON-serializable. If the solution is to add binary flags, spaCy might as well take care of that. The following example is based on the work by @savkov (see #1833):
pattern = [{'ORTH': {'REGEX': '^([Uu](\\.?|nited) ?[Ss](\\.?|tates)'}},
{'LOWER': 'president'}]
'REGEX' as an operator (instead of a top-level property that only matches on the token's text) allows defining rules for any string value, including custom attributes:
# match tokens with fine-grained POS tags starting with 'V'
pattern = [{'TAG': {'REGEX': '^V'}}]
# match custom attribute values with regular expressions
pattern = [{'_': {'country': {'REGEX': '^([Uu](\\.?|nited) ?[Ss](\\.?|tates)'}}}]
New operators
TL;DR: The new patterns spec will allow two ways of defining properties β attribute values for exact matches and dictionaries using operators for more fine-grained matches.
{
PROPERTY: value, # exact match
PROPERTY: {OPERATOR: value, ...} # match with operators
}
The following operators can be used within dictionaries describing attribute values:
| Operator | Value type | Description | Example |
|---|---|---|---|
==, >=, <=, >, < |
int, float | Attribute value is equal, greater or equal, smaller or equal, greater or smaller. | 'LENGTH': {'>': 10} |
IN |
any | Attribute value is member of a list. | 'LEMMA': {'IN': ['like', 'love']} |
NOT_IN |
any | Attribute value is not member of a list. | 'POS': {'NOT_IN': ['NOUN', 'PROPN']} |
REGEX |
unicode | Attribute value matches regular expression. | 'TAG': {'REGEX': '^V'} |
API improvements and bug fixes
See @honnibal's comments in #1945 and the feature/better-faster-matcher branch for more details and implementation examples.
Other fixes
- [x] #1711: Remove hard-coded length limit of 10 on the
PhraseMatcher. - [x] #1939: Fix pickling of
PhraseMatcher. - [x] #1951:
Matcher.pipeshould yield matches instead ofDocobjects. - [ ] #2042: Support deleting rules in
PhraseMatcher. - [x] Accept
"TEXT"as an alternative to"ORTH"(for consistency).
Serialize Phrase Matcher would be great.
Thank you! This will be awesome! I basically need all these new features! Do you have any estimates on when this will be available to try out?
A further improvement on this might be to enable running a matcher after other matchers. i.e to first recognize a pattern, add that patten as an attribute and then run a matcher on that attribute again. Example:
I "walked" to the buss stop. I (tag), " (quote), walked (verb), " (quote), etc...
convert it to:
I (noun), "walked" (verb), to (adv), etc...
And then recognize this pattern:
Noun, Verb, Adv
This might also simplify pattern creation because you can generalize and match simple patterns and re use them in later patterns.
For example i want all "adj + verb" patterns and "verb + adj" be matched and marked as "ACTION". Then use this in another matcher later:
They run fast. He is a fast runner.
Then match something like this: [{"POS": {"IN": ["PRON", "DET"]}, {}, {"MATCH": "ACTION"}]
Where the key "MATCH" is previous matches and ACTION is the previous match id.
Lastly this would also solve issues related to "or" patterns for petterns that depend on two or more tokens. Since you can then combine the new set feature "IN"/"NOT_IN" with previously matched patterns.
This would allow for much more complex types of patterns. I hope you will consider this extension and ill be happy to contribute to developing this. I think all that is needed is to set a hierarchy variable to match patterns, and then run the matchers in each hierarchy level after one another, storing previous matches as attributes.
EDIT I realized after writing this that this can be done using the new logic for custom attributes "_", if Iβm not mistaken. By adding matches to a custom variable on the doc object and then running the second set of matchers after this. However it is a bit much custom logic needed.
@ohenrik isn't this already possible through an _ parameter? Something like the example with a country pattern above:
# match custom attribute values with regular expressions
pattern = [{'_': {'country': {'REGEX': '^([Uu](\\.?|nited) ?[Ss](\\.?|tates)'}}}]
An alternative to the hierarchical matching patterns would be to allow for sub patterns directly in the patterns:
At the moment every rule is for one token. So like this: Pattern = [token_rule, token_rule, token_rule]
But by adding a sub list you could actually create a rule set that can use all the other operators in combination:
Pattern = [ [token_rule, token_rule, token_rule], [token_rule, token_rule, token_rule] ]
Meaning this would be possible: Pattern = ["pattern NOT_IN": [sub_pattern, sub_pattern], token_rule]
@savkov Yes, i realized it will be possible, but a bit much hassle to get it working. I think having nested patterns would solve this better, as i have proposed above. The example might not be that clear though
@ohenrik @savkov @GregDubbin @thomasopsomer
The feature/better-faster-matcher branch now has a module spacy.matcher2 with the reimplemented Matcher. It passes all tests, including ones which had been marked xfail. If you build the branch, you should be able to compare results of new and old by just importing from spacy.matcher2 and spacy.matcher.
Now we need tests with non-trivial grammars. Benchmarks would be particularly useful. I'm hoping the new matcher is faster, but it's hard to guess. If you have a non-trivial grammar handy, could you try it out and see how it looks?
Once we're confident the reimplementation is correct, we can push a v2.0.8 that makes the replacement, to fix #1945 . Then we can implement the fancy new pattern logic for v2.1.0 :tada:
Hm so far the PhraseMatcher seems much slower. Running more tests.
@honnibal I can test it out too, if you still need someone to test it for speed? I donβt have code using the PhraseMatcher though, but most of the other old functionality i can test against the new.
@ohenrik Yes please. I just pushed an update that fixes the speed problems on my PhraseMatcher benchmark, using the data from https://github.com/mpuig/spacy-lookup
Taking the first 1000 documents of IMDB train, and using the 400k patterns in spacy-lookup, we get:
| System | Matches | words per second |
|---|---|---|
| matcher | 24,861 | 2,173,959 |
| matcher2 | 24,861 | 2,001,323 |
| spacy-lookup | 23,693 | 104,664 |
~So, speed is fine (1.7m tokens per second) -- but I'm getting fewer matches, so it seems like something is wrong.~ Edit: Fixed.
Once the doc is tokenized, using the PhraseMatcher is 20x faster than using a string-based algorithm like Aho-Corasick. This does make sense: the inputs are significantly shorter in token-space than in string-space, so we get a big advantage from matching over tokens. If we measure from raw strings, Flashtext comes out faster, especially with the current efficiency problems in the tokenizer.
I think the difference in number of matches between the PhraseMatcher and spacy-lookup comes from handling of overlaps. I think it's nice to be able to return all matches, even if the domain of two patterns overlaps. This is different from how regex engines, but I think it's better semantics for what we want here. If I have patterns for "fresh food" and "food delivery", we do want matches for both if the input text is "fresh food delivery".
I have patterns for "fresh food" and "food delivery", we do want matches for both if the input text is "fresh food delivery".
@honnibal I agree, in most of the use cases i have and foresee i would want to include overlapping matches :) A switch for including overlapping or not would be a bonus though.
Related to the PhraseMatches. Is it possible to add patterns to this? I.e. not just match exact words in sequence, but match token TAG or POS sequences too?
@ohenrik The PhraseMatcher exploits the fact that the TokenC struct holds a pointer to a LexemeC from the vocabulary. This means that every instance of the word "Bill" is pointing to the same LexemeC data. We can then add a flag on that lexeme for the value B-PER, and run the matcher with only a few patterns. Once we have the match candidates, we filter them so that we don't get combinations of start/middle/end sequences that weren't in the actual phrases.
The trick fundamentally relies on the fact that the lexemes are indexed by ORTH. If we try to make the pattern a sequence of, say, LEMMA attributes, we'll run into the problem that the token's lexeme is indexed by the token's ORTH. For the ORTH attribute, we have a set of flags we can look up -- for the LEMMA, we don't.
How about this. We could build a temporary Doc that uses the attribute you're interested in as the ORTH value:
lemmas = Doc(doc.vocab, words=[token.lemma_ for token in doc])
Then we can pass this lemmas instance into the PhraseMatcher. The start and end offsets of the tokens will be correctly aligned to the original Doc, so we can return them directly. Constructing the secondary Doc object should be fairly cheap. We could build this into the PhraseMatcher, so that we can finally support choice of attribute. If a non-ORTH attribute is set, the PhraseMatcher would construct the temporary doc internally.
(I wish I'd thought of this solution earlier --- it would've worked all along!)
@honnibal Nice explanation and solution! :tada: Thank you! :slightly_smiling_face:
The feature/better-faster-matcher branch now has the improved code in matcher.pyx, so it could be merged. The only thing right now is I'm worried that the changed semantics will be a breaking change for some people, especially the inclusion of non-longest matches. I've added a filtering function, and I guess we can have an option that's on by default, that the PhraseMatcher disables.
Now that the Matcher is returning all matches for quantifiers, we can remove the length limit in the PhraseMatcher :tada: . Previously, if we had a pattern like [{ORTH: "a"}, {ORTH: "b", "OP": "+"}, {"ORTH": "c"}], and we had a sequence "abbc", we would only return a match for abbc. This meant we couldn't use quantifiers in the PhraseMatcher, because we would need "abc" as a candidate phrase as well. Now that the matcher returns both candidates, we can make the PhraseMatcher patterns use quantifiers, removing the length limit.
This change currently makes the phrase-matcher a bit less efficient: speed drops from 2m tokens per second to 1.3m. This is still much faster than the tokenizer, and we can recover the missing speed if necessary by having more specific patterns for more lengths.
We could build this into the
PhraseMatcher, so that we can finally support choice of attribute. If a non-ORTH attribute is set, thePhraseMatcherwould construct the temporary doc internally.
Suggested usage / user-facing API for now:
matcher = PhraseMatcher(nlp.vocab, attribute='POS')
matcher.add('PATTERN', None, nlp(u"I like cats")) # kinda useless example, but you get the idea
matches = matcher(nlp(u"You love dogs"))
assert len(matches) == 1
"We could build this into the PhraseMatcher, so that we can finally support choice of attribute." This would make the Rule based Matcher Explorer much more user friendly for non-linguists (i.e. buddhist monks creating spellchecking rules for Tibetan). Type a real sentence, convert it to a pattern, tweak it till you love it.
I hope I could pickle PhraseMatcher soon. Quite inefficient to add millions of rules every time.
So can't we expect PhraseMatcher become 'pickle-able' in the near future? I think the feature is essential to reuse a huge matcher.
@ngawangtrinley actually, is the Rule based Matcher Explorer something that can be run locally, or is it just an online demo? I think even for the non-buddhist Tibetan developers, it would be a time and sanity saver. Would be nice if it could be run on-prem. Maybe should be a separate ticket.
@matanster The UI is mostly just an online demo, but the back-end code is available here: https://github.com/explosion/spacy-services/tree/master/matcher