Feature engineering

This notebook will teach you how to extract feature values using revscoring's built-in feature library as well as to build your own features.

Set up the feature extractor

This line constructs a "feature extractor" that uses Wikipedia's API. We'll need to use it later, so we'll construct it first.


In [29]:
import sys
sys.path.append("/usr/local/lib/python3.4/dist-packages/")
sys.path.append("/usr/local/lib/python3.4/dist-packages/revscoring/")
sys.path.append("/usr/local/lib/python3.4/dist-packages/more_itertools/")
sys.path.append("/usr/local/lib/python3.4/dist-packages/deltas/")

In [30]:
!sudo pip3 install dependencies deltas


Requirement already satisfied (use --upgrade to upgrade): dependencies in /usr/local/lib/python3.4/dist-packages
Requirement already satisfied (use --upgrade to upgrade): deltas in /usr/local/lib/python3.4/dist-packages
Cleaning up...

In [33]:
from revscoring.extractors import api
import mwapi

extractor = api.Extractor(mwapi.Session("https://en.wikipedia.org",
                                        user_agent="Revscoring feature demo ahalfaker@wikimedia.org"))


---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-33-6e18ecb37322> in <module>()
----> 1 from revscoring.extractors import api
      2 import mwapi
      3 
      4 extractor = api.Extractor(mwapi.Session("https://en.wikipedia.org",
      5                                         user_agent="Revscoring feature demo ahalfaker@wikimedia.org"))

/usr/local/lib/python3.4/dist-packages/revscoring/extractors/api/__init__.py in <module>()
----> 1 from .extractor import Extractor
      2 
      3 __all__ = [Extractor]

/usr/local/lib/python3.4/dist-packages/revscoring/extractors/api/extractor.py in <module>()
      4 import mwapi
      5 
----> 6 from . import datasources
      7 from .. import Extractor as BaseExtractor
      8 from ...datasources import Datasource, revision_oriented

/usr/local/lib/python3.4/dist-packages/revscoring/__init__.py in <module>()
    116 from .features import Feature
    117 from .scorer_models import ScorerModel
--> 118 from .score_processor import ScoreProcessor
    119 
    120 __version__ = "1.2.9"  # Change in setup.py

/usr/local/lib/python3.4/dist-packages/revscoring/score_processor.py in <module>()
      5 from more_itertools import chunked
      6 
----> 7 from . import dependencies
      8 from .datasources import Datasource
      9 

ImportError: cannot import name 'dependencies'

Extract features

The following line demonstrates a simple feature extraction. We'll extract two features: wikitext.revision.chars, the number of characters added; and wikitext.revision.diff.chars_added, the number of characters in the entire revision. Note that we wrap the call in a list() because it returns a generator.

from revscoring.features import wikitext list(extractor.extract(123456789, [wikitext.revision.chars, wikitext.revision.diff.chars_added]))

Defining a custom feature

The next block defines a new feature and sets the dependencies to be the two features we just extracted. This feature represents the proportion of characters in the current version of the page that the current edit is responsible for adding.


In [3]:
from revscoring import Feature

chars_added_ratio_explicit = Feature(
    "chars_added_ratio_explicit", 
    lambda a,c: a/max(c, 1), # Prevents divide by zero
    depends_on=[wikitext.revision.diff.chars_added, 
                wikitext.revision.chars],
    returns=float)

list(extractor.extract(123456789, [chars_added_ratio_explicit]))


Out[3]:
[0.0002550369803621525]

There's easier ways that we can do this though. revscoring.Feature overloads simple mathematical operators to allow you to do math with features and get a feature returned. revscoring.features.modifiers contains a set of basic functions that do the same. This code roughly corresponds to what's going on above.


In [4]:
from revscoring.features import modifiers

chars_added_ratio_implicit = (wikitext.revision.diff.chars_added /
                              modifiers.max(wikitext.revision.chars, 1))

list(extractor.extract(123456789, [chars_added_ratio_implicit]))


Out[4]:
[0.0002550369803621525]

While the implicit pattern is quicker and easier than the explicit pattern, it's name can not be customized.


In [5]:
chars_added_ratio_explicit, chars_added_ratio_implicit


Out[5]:
(<chars_added_ratio_explicit>,
 <(wikitext.revision.diff.chars_added / max(wikitext.revision.chars, 1))>)

Extracting datasources

There's a also a set of revscoring.Datasource's that are part of the dependency injection system. These "datasources" represent the data needed for feature generation. We can extract them just like revscoring.Feature's.


In [6]:
list(extractor.extract(662953550, [wikitext.revision.diff.datasources.segments_added,
                                   wikitext.revision.diff.datasources.segments_removed]))


Out[6]:
[['Ideology and policies',
  'Political scientists [[Robert Ford]] and [[Matthew Goodwin]] characterised UKIP as "a radical right party".{{sfn|Ford|Goodwin|2014|p=13}}\n\n',
  '{{fact}}',
  '{{fact}}',
  '{{fact}}',
  '{{fact}}',
  '{{fact}}',
  '{{fact}}',
  '{{fact}}',
  '{{fact}}',
  '{{fact}}',
  '{{fact}}'],
 ['Policies']]

OK. Let's define a new feature for counting the number of templates added. I'll make use of mwparserfromhell to do this. See the docs.


In [7]:
import mwparserfromhell as mwp

templates_added = Feature("templates_added", 
                          lambda add_segments: sum(len(mwp.parse(s).filter_templates()) > 0 for s in add_segments),
                          depends_on=[wikitext.revision.diff.datasources.segments_added],
                          returns=int)
list(extractor.extract(662953550, [templates_added]))


Out[7]:
[11]

Debugging

There's some facilities in place to help you make sense of issues when they arise. The most important is the draw function.


In [8]:
from revscoring.dependencies import draw
print(draw(templates_added))


 - <templates_added>
	 - <wikitext.revision.diff.segments_added>
		 - <wikitext.revision.diff.operations>
			 - <tokenized(<revision.parent.text>)>
				 - <revision.parent.text>
			 - <tokenized(<revision.text>)>
				 - <revision.text>

In the tree structure above, you can see how our new feature depends on wikitext.revision.diff.segments_added which depends on wikitext.revision.diff.operations which depends (as you might imagine) on the current and parent revision. Some features can get quite complicated.


In [9]:
print(draw(wikitext.revision.diff.number_prop_delta_sum))


 - <wikitext.revision.diff.number_prop_delta_sum>
	 - <values(<wikitext.revision.diff.number_prop_delta>)>
		 - <wikitext.revision.diff.number_prop_delta>
			 - <wikitext.revision.parent.number_frequency>
				 - <wikitext.revision.parent.numbers>
					 - <tokenized(<revision.parent.text>)>
						 - <revision.parent.text>
			 - <wikitext.revision.diff.number_delta>
				 - <wikitext.revision.parent.number_frequency>
					 - <wikitext.revision.parent.numbers>
						 - <tokenized(<revision.parent.text>)>
							 - <revision.parent.text>
				 - <wikitext.revision.number_frequency>
					 - <wikitext.revision.numbers>
						 - <tokenized(<revision.text>)>
							 - <revision.text>

The dependency injection system will only solve a unique dependency once for a given tree. So, even though <revision.parent.text> appears twice above, it will only be extracted once and then cached. This allows for multiple features to share large sections of their dependency trees -- and therefor minimize resource usage.

Errors during extraction

A revscoring.Extractor should be expected to throw an exception if it cannot find a missing resource during extraction. These messages are intented to clearly convey what went wrong.


In [10]:
try:
    list(extractor.extract(2, [wikitext.revision.diff.words_added]))
except Exception as e:
    print(e)


RevisionNotFound: Could not find revision ({revision}:2)

In [11]:
try:
    list(extractor.extract(262721924, [wikitext.revision.diff.words_added]))
except Exception as e:
    print(e)


TextDeleted: Text deleted (<revision.text>)

In [12]:
from revscoring.features import revision_oriented
try:
    list(extractor.extract(172665816, [revision_oriented.revision.comment_matches("foo")]))
except Exception as e:
    print(e)


CommentDeleted: Comment deleted (<revision.comment>)

In [13]:
from revscoring.features import temporal
try:
    list(extractor.extract(591839757, [revision_oriented.revision.user.text_matches("foo")]))
except Exception as e:
    print(e)


UserDeleted: User deleted ({revision.user})