Basic EM workflow 2 (Restaurants data set)

Introduction

This IPython notebook explains a basic workflow two tables using py_entitymatching. Our goal is to come up with a workflow to match restaurants from Fodors and Zagat sites. Specifically, we want to achieve precision and recall above 96%. The datasets contain information about the restaurants.

First, we need to import py_entitymatching package and other libraries as follows:


In [1]:
import sys
sys.path.append('/Users/pradap/Documents/Research/Python-Package/anhaid/py_entitymatching/')

import py_entitymatching as em
import pandas as pd
import os

In [2]:
# Display the versions
print('python version: ' + sys.version )
print('pandas version: ' + pd.__version__ )
print('magellan version: ' + em.__version__ )


python version: 3.5.2 | packaged by conda-forge | (default, Sep  8 2016, 14:36:38) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.54)]
pandas version: 0.19.2
magellan version: 0.1.0

Matching two tables typically consists of the following three steps:

1. Reading the input tables

2. Blocking the input tables to get a candidate set

3. Matching the tuple pairs in the candidate set

Read input tables

We begin by loading the input tables. For the purpose of this guide, we use the datasets that are included with the package.


In [3]:
# Get the paths
path_A = em.get_install_path() + os.sep + 'datasets' + os.sep + 'end-to-end' + os.sep + 'restaurants/fodors.csv'
path_B = em.get_install_path() + os.sep + 'datasets' + os.sep + 'end-to-end' + os.sep + 'restaurants/zagats.csv'

In [4]:
# Load csv files as dataframes and set the key attribute in the dataframe
A = em.read_csv_metadata(path_A, key='id')
B = em.read_csv_metadata(path_B, key='id')


Metadata file is not present in the given path; proceeding to read the csv file.
Metadata file is not present in the given path; proceeding to read the csv file.

In [5]:
print('Number of tuples in A: ' + str(len(A)))
print('Number of tuples in B: ' + str(len(B)))
print('Number of tuples in A X B (i.e the cartesian product): ' + str(len(A)*len(B)))


Number of tuples in A: 533
Number of tuples in B: 331
Number of tuples in A X B (i.e the cartesian product): 176423

In [6]:
A.head(2)


Out[6]:
id name addr city phone type
0 534 arnie mortons of chicago 435 s. la cienega blv. los angeles 310/246-1501 american
1 535 arts delicatessen 12224 ventura blvd. studio city 818/762-1221 american

In [7]:
B.head(2)


Out[7]:
id name addr city phone type
0 1 apple pan the 10801 w. pico blvd. west la 310-475-3585 american
1 2 asahi ramen 2027 sawtelle blvd. west la 310-479-2231 noodle shops

In [25]:
# Display the keys of the input tables
em.get_key(A), em.get_key(B)


Out[25]:
('id', 'id')

In [8]:
# If the tables are large we can downsample the tables like this
A1, B1 = em.down_sample(A, B, 200, 1, show_progress=False)
len(A1), len(B1)

# But for the purposes of this notebook, we will use the entire table A and B


Out[8]:
(150, 200)

Block Tables To Get Candidate Set

Before we do the matching, we would like to remove the obviously non-matching tuple pairs from the input tables. This would reduce the number of tuple pairs considered for matching. py_entitymatching provides four different blockers: (1) attribute equivalence, (2) overlap, (3) rule-based, and (4) black-box. The user can mix and match these blockers to form a blocking sequence applied to input tables.

For the matching problem at hand, we know that two restaurants with no overlap between the names will not match. So we decide the apply blocking over names:


In [9]:
# Blocking plan

# A, B -- Overlap blocker [name] --------------------|---> candidate set

In [10]:
# Create overlap blocker
ob = em.OverlapBlocker()

# Block tables using 'name' attribute 
C = ob.block_tables(A, B, 'name', 'name', 
                    l_output_attrs=['name', 'addr', 'city', 'phone'], 
                    r_output_attrs=['name', 'addr', 'city', 'phone'],
                    overlap_size=1, show_progress=False
                    )
len(C)


Out[10]:
2600

Match tuple pairs in candidate set

In this step, we would want to match the tuple pairs in the candidate set. Specifically, we use learning-based method for matching purposes. This typically involves the following four steps:

  1. Sampling and labeling the candidate set
  2. Splitting the labeled data into development and evaluation set
  3. Selecting the best learning based matcher using the development set
  4. Evaluating the selected matcher using the evaluation set

Sampling and labeling the candidate set

First, we randomly sample 450 tuple pairs for labeling purposes.


In [11]:
# Sample  candidate set
S = em.sample_table(C, 450)

Next, we label the sampled candidate set. Specify we would enter 1 for a match and 0 for a non-match.


In [12]:
# Label S
G = em.label_table(S, 'gold')

For the purposes of this guide, we will load in a pre-labeled dataset (of 450 tuple pairs) included in this package.


In [13]:
# Load the pre-labeled data
path_G = em.get_install_path() + os.sep + 'datasets' + os.sep + 'end-to-end' + os.sep + 'restaurants/lbl_restnt_wf1.csv'
G = em.read_csv_metadata(path_G, 
                         key='_id',
                         ltable=A, rtable=B, 
                         fk_ltable='ltable_id', fk_rtable='rtable_id')
len(G)


Out[13]:
450

Splitting the labeled data into development and evaluation set

In this step, we split the labeled data into two sets: development (I) and evaluation (J). Specifically, the development set is used to come up with the best learning-based matcher and the evaluation set used to evaluate the selected matcher on unseen data.


In [14]:
# Split S into development set (I) and evaluation set (J)
IJ = em.split_train_test(G, train_proportion=0.7, random_state=0)
I = IJ['train']
J = IJ['test']

Selecting the best learning-based matcher

Selecting the best learning-based matcher typically involves the following steps:

  1. Creating a set of learning-based matchers
  2. Creating features
  3. Converting the development set into feature vectors
  4. Selecting the best learning-based matcher using k-fold cross validation

Creating a set of learning-based matchers


In [15]:
# Create a set of ML-matchers
dt = em.DTMatcher(name='DecisionTree', random_state=0)
svm = em.SVMMatcher(name='SVM', random_state=0)
rf = em.RFMatcher(name='RF', random_state=0)
lg = em.LogRegMatcher(name='LogReg', random_state=0)
ln = em.LinRegMatcher(name='LinReg')
nb = em.NBMatcher(name='NaiveBayes')

Creating features

Next, we need to create a set of features for the development set. py_entitymatching provides a way to automatically generate features based on the attributes in the input tables. For the purposes of this guide, we use the automatically generated features.


In [16]:
# Generate features
feature_table = em.get_features_for_matching(A, B)

Converting the development set to feature vectors


In [17]:
# Convert the I into a set of feature vectors using F
H = em.extract_feature_vecs(I, 
                            feature_table=feature_table, 
                            attrs_after='gold',
                            show_progress=False)

In [18]:
# Display first few rows
H.head(3)


Out[18]:
_id ltable_id rtable_id id_id_exm id_id_anm id_id_lev_dist id_id_lev_sim name_name_jac_qgm_3_qgm_3 name_name_cos_dlm_dc0_dlm_dc0 name_name_jac_dlm_dc0_dlm_dc0 ... city_city_sw type_type_jac_qgm_3_qgm_3 type_type_cos_dlm_dc0_dlm_dc0 type_type_jac_dlm_dc0_dlm_dc0 type_type_mel type_type_lev_dist type_type_lev_sim type_type_nmw type_type_sw gold
221 1790 563 248 0 0.440497 3 0.0 1.000000 1.000000 1.000000 ... 8.0 0.235294 0.0 0.0 0.883333 7.0 0.416667 -2.0 4.0 1
439 794 544 116 0 0.213235 3 0.0 0.258065 0.500000 0.333333 ... 1.0 0.000000 0.0 0.0 0.466667 4.0 0.200000 0.0 1.0 0
191 2315 589 305 0 0.517827 3 0.0 0.172414 0.353553 0.200000 ... 1.0 0.000000 0.0 0.0 0.451923 24.0 0.000000 -11.0 2.0 0

3 rows × 40 columns

Selecting the best matcher using cross-validation

Now, we select the best matcher using k-fold cross-validation. For the purposes of this guide, we use five fold cross validation and use 'precision' and 'recall' metric to select the best matcher.


In [19]:
# Select the best ML matcher using CV
result = em.select_matcher([dt, rf, svm, ln, lg, nb], table=H, 
        exclude_attrs=['_id', 'ltable_id', 'rtable_id', 'gold'],
        k=5,
        target_attr='gold', metric='precision', random_state=0)
result['cv_stats']


Out[19]:
Name Matcher Num folds Fold 1 Fold 2 Fold 3 Fold 4 Fold 5 Mean score
0 DecisionTree <py_entitymatching.matcher.dtmatcher.DTMatcher object at 0x110aef5f8> 5 1.000000 1.0000 0.941176 1.0 0.941176 0.976471
1 RF <py_entitymatching.matcher.rfmatcher.RFMatcher object at 0x110aef668> 5 1.000000 0.9375 1.000000 1.0 0.941176 0.975735
2 SVM <py_entitymatching.matcher.svmmatcher.SVMMatcher object at 0x110aef5c0> 5 1.000000 1.0000 1.000000 1.0 1.000000 1.000000
3 LinReg <py_entitymatching.matcher.linregmatcher.LinRegMatcher object at 0x110aef780> 5 0.833333 1.0000 1.000000 1.0 0.888889 0.944444
4 LogReg <py_entitymatching.matcher.logregmatcher.LogRegMatcher object at 0x110aef6d8> 5 0.928571 1.0000 1.000000 1.0 0.944444 0.974603
5 NaiveBayes <py_entitymatching.matcher.nbmatcher.NBMatcher object at 0x110aef828> 5 0.937500 0.9375 1.000000 1.0 0.894737 0.953947

In [20]:
result = em.select_matcher([dt, rf, svm, ln, lg, nb], table=H, 
        exclude_attrs=['_id', 'ltable_id', 'rtable_id', 'gold'],
        k=5,
        target_attr='gold', metric='recall', random_state=0)
result['cv_stats']


Out[20]:
Name Matcher Num folds Fold 1 Fold 2 Fold 3 Fold 4 Fold 5 Mean score
0 DecisionTree <py_entitymatching.matcher.dtmatcher.DTMatcher object at 0x110aef5f8> 5 0.8125 1.000000 1.0 0.928571 0.941176 0.936450
1 RF <py_entitymatching.matcher.rfmatcher.RFMatcher object at 0x110aef668> 5 0.8750 1.000000 1.0 1.000000 0.941176 0.963235
2 SVM <py_entitymatching.matcher.svmmatcher.SVMMatcher object at 0x110aef5c0> 5 0.1250 0.400000 0.5 0.285714 0.176471 0.297437
3 LinReg <py_entitymatching.matcher.linregmatcher.LinRegMatcher object at 0x110aef780> 5 0.9375 0.866667 1.0 0.785714 0.941176 0.906211
4 LogReg <py_entitymatching.matcher.logregmatcher.LogRegMatcher object at 0x110aef6d8> 5 0.8125 1.000000 1.0 0.928571 1.000000 0.948214
5 NaiveBayes <py_entitymatching.matcher.nbmatcher.NBMatcher object at 0x110aef828> 5 0.9375 1.000000 1.0 0.928571 1.000000 0.973214

We observe that the best matcher (RF) is getting us the best precision and recall. So, we select this matcher and now we can proceed on to evaluating the best matcher on the unseen data (the evaluation set).

Evaluating the matching output

Evaluating the matching outputs for the evaluation set typically involves the following four steps:

  1. Converting the evaluation set to feature vectors
  2. Training matcher using the feature vectors extracted from the development set
  3. Predicting the evaluation set using the trained matcher
  4. Evaluating the predicted matches

Converting the evaluation set to feature vectors

As before, we convert to the feature vectors (using the feature table and the evaluation set)


In [21]:
# Convert J into a set of feature vectors using feature table
L = em.extract_feature_vecs(J, feature_table=feature_table,
                            attrs_after='gold', show_progress=False)

Training the selected matcher

Now, we train the matcher using all of the feature vectors from the development set. For the purposes of this guide we use random forest as the selected matcher.


In [22]:
# Train using feature vectors from I 
dt.fit(table=H, 
       exclude_attrs=['_id', 'ltable_id', 'rtable_id', 'gold'], 
       target_attr='gold')

Predicting the matches

Next, we predict the matches for the evaluation set (using the feature vectors extracted from it).


In [23]:
# Predict on L 
predictions = dt.predict(table=L, exclude_attrs=['_id', 'ltable_id', 'rtable_id', 'gold'], 
              append=True, target_attr='predicted', inplace=False)

Evaluating the predictions

Finally, we evaluate the accuracy of predicted outputs


In [24]:
# Evaluate the predictions
eval_result = em.eval_matches(predictions, 'gold', 'predicted')
em.print_eval_summary(eval_result)


Precision : 97.14% (34/35)
Recall : 100.0% (34/34)
F1 : 98.55%
False positives : 1 (out of 35 positive predictions)
False negatives : 0 (out of 100 negative predictions)