Volume 6, Number 3, 2019, 17–37 journal homepage: region.ersa.org
DOI: 10.18335/region.v6i3.276

Demonstrating the utility of machine learning innovations in address matching to spatial socio-economic applications*

Sam Comber1
1 University of Liverpool, Liverpool, United Kingdom Received: 16 August 2019/Accepted: 30 December 2019

*This paper is available as computational notebook on the REGION webpage.

Abstract. The last decade has heralded an unprecedented rise in the number, frequency and availability of data sources. Yet they are often incomplete, meaning data fusion is required to enhance their quality and scope. In the context of spatial analysis, address matching is critical to enhancing household socio-economic and demographic characteristics. Matching administrative, commercial, or lifestyle data sources to items such as household surveys has the potential benefits of improving data quality, enabling spatial data visualisation, and the lowering of respondent burden in household surveys. Typically when a practitioner has high quality data, unique identifiers are used to facilitate a direct linkage between household addresses. However, real-world databases are often absent of unique identifiers to enable a one-to-one match. Moreover, irregularities between the text representations of potential matches mean extensive cleaning of the data is often required as a pre-processing step. For this reason, practitioners have traditionally relied on two linkage techniques for facilitating matches between the text representations of addresses that are broadly divided into deterministic or mathematical approaches. Deterministic matching consists of constructing hand-crafted rules that classify address matches and non-matches based on specialist domain knowledge, while mathematical approaches have increasingly adopted machine learning techniques for resolving pairs of addresses to a match. In this notebook we demonstrate methods of the latter by demonstrating the utility of machine learning approaches to the address matching work flow. To achieve this, we construct a predictive model that resolves matches between two small datasets of restaurant addresses in the US. While the problem case may seem trivial, the intention of the notebook is to demonstrate an approach that is reproducible and extensible to larger data challenges. Thus, in the present notebook, we document an end-to-end pipeline that is replicable and instructive towards assisting future address matching problem cases faced by the regional scientist.

1 Introduction

Our overarching objective is to demonstrate how machine learning can be integrated into the address matching work flow. By definition, address matching pertains to the process of resolving pairs of records with a spatial footprint. While geospatial matching links the geometric representations of spatial objects, address matching typically involves linking the text-based representations of address pairs. The utility of address matching, and record linkage in general, lies in the ability to unlock attributes from sources of data that cannot be linked by traditional means. This is often because the datasets lack a common key to resolve a join between the address of a premise. Two example applications of address matching uses include: the linkage of historical censuses across time for exploring economic and geographic mobility across multiple generations (Ruggles et al. 2018), and exploring how early-life hazardous environmental exposure, socio-economic conditions, or natural disasters impact the health and economic outcomes of individuals living in particular residential locations (Cayo & Talbot, 2003; Reynolds et al., 2003; Baldovin et al., 2015).

For demonstrative purposes, we rely on small a set of addresses from the Fodors and Zagat restaurant guides that contain 112 matched addresses for training a predictive model that resolves address pairs to matches and non-matches. In a real-world application, training a machine learning model on a small sample of matched addresses could be used to resolve matches between the remaining addresses of a larger dataset. While we use the example of restaurant addresses, these could easily be replaced by addresses from a far less trivial source and the work flow required to implement the address matching exercise would remain the same. Therefore, it is the intention of this guide to provide insight on how the work flow of a supervised address matching work flow proceeds, and to inspire interested users to scale the supplied code to larger and more interesting problems. To keep this notebook self-contained, we parse the set of addresses from a string meaning we do not require any external datasets to proceed with the matching exercise.

In this section we detail the dependencies required to execute the workflow of this notebook. To begin, we load several pre-built libraries such as io and Ipython.display that provide convenience functions for reading text strings into dataframes and displaying HTML. Next, we load external libraries that facilitate the storage, visualisation, execution and evaluation of our address matching project. For example, pandas and numpy are used for storing the address representations at various stages of the workflow, while matplotlib and seaborn are data visualisation libraries utilised for drawing attractive and informative statistical graphs. jellyfish and recordlinkage provide utility functions for measuring address pair similarities and lowering the computational cost of the matching exercise, respectively. Finally, postal.parser provides the Conditional Random Fields (CRF) segmentation model we use to parse addresses into address fields, and sklearn provides several classifiers and performance metrics we use to evaluate the success of our matching exercise.

In [1]:
# load internal libraries
%matplotlib inline
import os
import uuid
import warnings
from io import StringIO
from IPython.display import HTML

# load external libraries
# data storage libraries
import pandas as pd
import numpy as np

# visualisation libraries
import matplotlib.pyplot as plt
import seaborn as sns

# analysis and evaluation libraries
import jellyfish
import recordlinkage as rl
from postal.parser import parse_address # CRF parser
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_validate, train_test_split
from sklearn.metrics import precision_score, recall_score, f1_score, confusion_matrix

# configure convenience settings
np.random.seed(123)
sns.set_style('whitegrid')
pd.set_option('display.max_colwidth', -1)
warnings.simplefilter(action='ignore', category=FutureWarning)

def hover(hover_color="#add8e6"):
    return dict(selector="tbody tr:hover",
            props=[("background-color", "%s" % hover_color)])

# set table CSS for attractive tables
styles = [
    #table properties
    dict(selector=" ", 
         props=[("margin","0"),
                ("font-family",'"Helvetica", "Arial", sans-serif'),
                ("border-collapse", "collapse"),
                ("border","none"), ("border-style", "hidden")]),
    dict(selector="td", props = [("border-style", "hidden"), 
                                 ("border-collapse", "collapse")]),

    #header color 
    dict(selector="thead", 
         props=[("background-color","#a4dbc8")]),

    #background shading
    dict(selector="tbody tr:nth-child(even)",
         props=[("background-color", "#fff")]),
    dict(selector="tbody tr:nth-child(odd)",
         props=[("background-color", "#eee")]),

    #header cell properties
    dict(selector="th", 
         props=[("text-align", "center"),
               ("border-style", "hidden"), 
               ("border-collapse", "collapse")]),

    hover()
]

To begin our exercise we load entirety of the 112 Zagat and Fodor matched address pairs as a string in the cell block below. For this reason the following cell takes up a lot of space, so feel free to collapse it once it has been executed.

In [2]:
f = """###################################################################################################
#   There are 112 matches between the tuples.  The Zagat tuple is listed first, 
#   and then its Fodors pair.
###################################################################################################
Arnie Morton's of Chicago 435 S. La Cienega Blvd. Los Angeles 90048 310-246-1501 Steakhouses
Arnie Morton's of Chicago 435 S. La Cienega Blvd. Los Angeles 90048 310/246-1501 American
########################
Art's Deli 12224 Ventura Blvd. Studio City 91604 818-762-1221 Delis
Art's Delicatessen 12224 Ventura Blvd. Studio City 91604 818/762-1221 American
########################
Bel-Air Hotel 701 Stone Canyon Rd. Bel Air 90077 310-472-1211 Californian
Hotel Bel-Air 701 Stone Canyon Rd. Bel Air 90077 310/472-1211 Californian
########################
Cafe Bizou 14016 Ventura Blvd. Sherman Oaks 91423 818-788-3536 French Bistro
Cafe Bizou 14016 Ventura Blvd. Sherman Oaks 91423 818/788-3536 French
########################
Campanile 624 S. La Brea Ave. Los Angeles 90036 213-938-1447 Californian
Campanile 624 S. La Brea Ave. Los Angeles 90036 213/938-1447 American
########################
Chinois on Main 2709 Main St. Santa Monica 90405 310-392-9025 Pacific New Wave
Chinois on Main 2709 Main St. Santa Monica 90405 310/392-9025 French
########################
Citrus 6703 Melrose Ave. Los Angeles 90038 213-857-0034 Californian
Citrus 6703 Melrose Ave. Los Angeles 90038 213/857-0034 Californian
########################
Fenix at the Argyle 8358 Sunset Blvd. W. Hollywood 90069 213-848-6677 French (New)
Fenix 8358 Sunset Blvd. West Hollywood 90069 213/848-6677 American
########################
Granita 23725 W. Malibu Rd. Malibu 90265 310-456-0488 Californian
Granita 23725 W. Malibu Rd. Malibu 90265 310/456-0488 Californian
########################
Grill  The 9560 Dayton Way Beverly Hills 90210 310-276-0615 American (Traditional)
Grill on the Alley 9560 Dayton Way Los Angeles 90210 310/276-0615 American
########################
Katsu 1972 Hillhurst Ave. Los Feliz 90027 213-665-1891 Japanese
Restaurant Katsu 1972 N. Hillhurst Ave. Los Angeles 90027 213/665-1891 Asian
########################
L'Orangerie 903 N. La Cienega Blvd. W. Hollywood 90069 310-652-9770 French (Classic)
L'Orangerie 903 N. La Cienega Blvd. Los Angeles 90069 310/652-9770 French
########################
Le Chardonnay (Los Angeles) 8284 Melrose Ave. Los Angeles 90046 213-655-8880 French Bistro
Le Chardonnay 8284 Melrose Ave. Los Angeles 90046 213/655-8880 French
########################
Locanda Veneta 8638 W. Third St. Los Angeles 90048 310-274-1893 Italian
Locanda Veneta 3rd St. Los Angeles 90048 310/274-1893 Italian
########################
Matsuhisa 129 N. La Cienega Blvd. Beverly Hills 90069 310-659-9639 Seafood
Matsuhisa 129 N. La Cienega Blvd. Beverly Hills 90069 310/659-9639 Asian
########################
Palm  The (Los Angeles) 9001 Santa Monica Blvd. W. Hollywood 90069 310-550-8811 Steakhouses
The Palm 9001 Santa Monica Blvd. Los Angeles 90069 310/550-8811 American
########################
Patina 5955 Melrose Ave. Los Angeles 90038 213-467-1108 Californian
Patina 5955 Melrose Ave. Los Angeles 90038 213/467-1108 Californian
########################
Philippe The Original 1001 N. Alameda St. Chinatown 90012 213-628-3781 Cafeterias
Philippe's The Original 1001 N. Alameda St. Los Angeles 90012 213/628-3781 American
########################
Pinot Bistro 12969 Ventura Blvd. Studio City 91604 818-990-0500 French Bistro
Pinot Bistro 12969 Ventura Blvd. Los Angeles 91604 818/990-0500 French
########################
Rex Il Ristorante 617 S. Olive St. Los Angeles 90014 213-627-2300 Nuova Cucina Italian
Rex Il Ristorante 617 S. Olive St. Los Angeles 90014 213/627-2300 Italian
########################
Spago (Los Angeles) 8795 Sunset Blvd. W. Hollywood 90069 310-652-4025 Californian
Spago 1114 Horn Ave. Los Angeles 90069 310/652-4025 Californian
########################
Valentino 3115 Pico Blvd. Santa Monica 90405 310-829-4313 Italian
Valentino 3115 Pico Blvd. Santa Monica 90405 310/829-4313 Italian
########################
Yujean Kang's 67 N. Raymond Ave. Pasadena 91103 818-585-0855 Chinese
Yujean Kang's Gourmet Chinese Cuisine 67 N. Raymond Ave. Los Angeles 91103 818/585-0855 Asian
########################
21 Club 21 W. 52nd St. New York City 10019 212-582-7200 American (New)
21 Club 21 W. 52nd St. New York 10019 212/582-7200 American
########################
Aquavit 13 W. 54th St. New York City 10019 212-307-7311 Scandinavian
Aquavit 13 W. 54th St. New York 10019 212/307-7311 Continental
########################
Aureole 34 E. 61st St. New York City 10065 212-319-1660 American (New)
Aureole 34 E. 61st St. New York 10065 212/319-1660 American
########################
BCafe Lalo 201 W. 83rd St. New York City 10024 212-496-6031 Coffeehouses
Café Lalo 201 W. 83rd St. New York 10024 212/496-6031 Coffee Bar
########################
Cafe des Artistes 1 W. 67th St. New York City 10023 212-877-3500 French (Classic)
Café des Artistes 1 W. 67th St. New York 10023 212/877-3500 Continental
########################
Carmine's 2450 Broadway New York City 10024 212-362-2200 Italian
Carmine's 2450 Broadway  between 90th and 91st Sts. New York 10024 212/362-2200 Italian
########################
Carnegie Deli 854 Seventh Ave. New York City 10019 212-757-2245 Delis
Carnegie Deli 854 7th Ave.  between 54th and 55th Sts. New York 10019 212/757-2245 Delicatessen
########################
Chanterelle 2 Harrison St. New York City 10013 212-966-6960 French (New)
Chanterelle 2 Harrison St.  near Hudson St. New York 10013 212/966-6960 American
########################
CDaniel 20 E. 76th St. New York City 10021 212-288-0033 French (New)
Daniel 20 E. 76th St. New York 10021 212/288-0033 French
########################
Dawat 210 E. 58th St. New York City 10022 212-355-7555 Indian
Dawat 210 E. 58th St. New York 10022 212/355-7555 Asian
########################
Felidia 243 E. 58th St. New York City 10022 212-758-1479 Italian
Felidia 243 E. 58th St. New York 10022 212/758-1479 Italian
########################
Four Seasons 99 E. 52nd St. New York City 10022 212-754-9494 American (New)
Four Seasons Grill Room 99 E. 52nd St. New York 10022 212/754-9494 American
########################
Gotham Bar & Grill 12 E. 12th St. New York City 10003 212-620-4020 American (New)
Gotham Bar & Grill 12 E. 12th St. New York 10003 212/620-4020 American
########################
Gramercy Tavern 42 E. 20th St. New York City 10003 212-477-0777 American (New)
Gramercy Tavern 42 E. 20th St.  between Park Ave. S and Broadway New York 10003 212/477-0777 American
########################
Island Spice 402 W. 44th St. New York City 10036 212-765-1737 Caribbean
Island Spice 402 W. 44th St. New York 10036 212/765-1737  tel Caribbean
########################
Jo Jo 160 E. 64th St. New York City 10065 212-223-5656 French Bistro
Jo Jo 160 E. 64th St. New York 10065 212/223-5656 American
########################
La Caravelle 33 W. 55th St. New York City 10019 212-586-4252 French (Classic)
La Caravelle 33 W. 55th St. New York 10019 212/586-4252 French
########################
La Cote Basque 60 W. 55th St. New York City 10019 212-688-6525 French (Classic)
La Cote Basque 60 W. 55th St.  between 5th and 6th Ave. New York 10019 212/688-6525 French
########################
Le Bernardin 155 W. 51st St. New York City 10019 212-489-1515 Seafood
Le Bernardin 155 W. 51st St. New York 10019 212/489-1515 French
########################
Les Celebrites 155 W. 58th St. New York City 10019 212-484-5113 French (Classic)
Les Célébrités 160 Central Park S New York 10019 212/484-5113 French
########################
Lespinasse (New York City) 2 E. 55th St. New York City 10022 212-339-6719 Asian
Lespinasse 2 E. 55th St. New York 10022 212/339-6719 American
########################
Lutece 249 E. 50th St. New York City 10022 212-752-2225 French (Classic)
Lutèce 249 E. 50th St. New York 10022 212/752-2225 French
########################
Manhattan Ocean Club 57 W. 58th St. New York City 10019 212-371-7777 Seafood
Manhattan Ocean Club 57 W. 58th St. New York 10019 212/371-7777 Seafood
########################
March 405 E. 58th St. New York City 10022 212-754-6272 American (New)
March 405 E. 58th St. New York 10022 212/754-6272 American
########################
Mesa Grill 102 Fifth Ave. New York City 10011 212-807-7400 Southwestern
Mesa Grill 102 5th Ave.  between 15th and 16th Sts. New York 10011 212/807-7400 American
########################
Mi Cocina 57 Jane St. New York City 10014 212-627-8273 Mexican
Mi Cocina 57 Jane St.  off Hudson St. New York 10014 212/627-8273 Mexican
########################
Montrachet 239 W. Broadway New York City 10013 212-219-2777 French Bistro
Montrachet 239 W. Broadway  between Walker and White Sts. New York 10013 212/219-2777 French
########################
Oceana 55 E. 54th St. New York City 10022 212-759-5941 Seafood
Oceana 55 E. 54th St. New York 10022 212/759-5941 Seafood
########################
Park Avenue Cafe (New York City) 100 E. 63rd St. New York City 10065 212-644-1900 American (New)
Park Avenue Cafe 100 E. 63rd St. New York 10065 212/644-1900 American
########################
Petrossian 182 W. 58th St. New York City 10019 212-245-2214 Russian
Petrossian 182 W. 58th St. New York 10019 212/245-2214 French
########################
Picholine 35 W. 64th St. New York City 10023 212-724-8585 Mediterranean
Picholine 35 W. 64th St. New York 10023 212/724-8585 Mediterranean
########################
Pisces 95 Ave. A New York City 10009 212-260-6660 Seafood
Pisces 95 Ave. A at 6th St. New York 10009 212/260-6660 Seafood
########################
Rainbow Room 30 Rockefeller Plaza New York City 10112 212-632-5000 American (New)
Rainbow Room 30 Rockefeller Plaza New York 10112 212/632-5000 or 212/632-5100 American
########################
River Cafe 1 Water St. Brooklyn 11201 718-522-5200 American (New)
River Café 1 Water St. at the East River Brooklyn 11201 718/522-5200 American
########################
San Domenico 240 Central Park S. New York City 10019 212-265-5959 Italian
San Domenico 240 Central Park S New York 10019 212/265-5959 Italian
########################
Second Avenue Deli 156 Second Ave. New York City 10003 212-677-0606 Delis
Second Avenue Deli 156 2nd Ave. at 10th St. New York 10003 212/677-0606 Delicatessen
########################
Seryna 11 E. 53rd St. New York City 10022 212-980-9393 Japanese
Seryna 11 E. 53rd St. New York 10022 212/980-9393 Asian
########################
Shun Lee Palace 155 E. 55th St. New York City 10022 212-371-8844 Chinese
Shun Lee West 43 W. 65th St. New York 10022 212/371-8844 Asian
########################
Sign of the Dove 1110 Third Ave. New York City 10065 212-861-8080 American (New)
Sign of the Dove 1110 3rd Ave. at 65th St. New York 10065 212/861-8080 American
########################
Smith & Wollensky 797 Third Ave. New York City 10022 212-753-1530 Steakhouses
Smith & Wollensky 201 E. 49th St. New York 10022 212/753-1530 American
########################
Tavern on the Green Central Park West New York City 10023 212-873-3200 American (New)
Tavern on the Green In Central Park at 67th St. New York 10023 212/873-3200 American
########################
Uncle Nick's 747 Ninth Ave. New York City 10019 212-245-7992 Greek
Uncle Nick's 747 9th Ave.  between 50th and 51st Sts. New York 10019 212/315-1726 Mediterranean
########################
Union Square Cafe 16th St. New York City 10003 212-243-4020 American (New)
Union Square Cafe 21 E. 16th St. New York 10003 212/243-4020 American
########################
Virgil's Real BBQ 152 W. 44th St. New York City 10036 212-921-9494 BBQ
Virgil's 152 W. 44th St. New York 10036 212/921-9494 American
########################
Chin's 3200 Las Vegas Blvd. S. Las Vegas 89109 702-733-8899 Chinese
Chin's 3200 Las Vegas Blvd. S Las Vegas 89109 702/733-8899 Asian
########################
Coyote Cafe (Las Vegas) 3799 Las Vegas Blvd. S. Las Vegas 89109 702-891-7349 Southwestern
Coyote Café 3799 Las Vegas Blvd. S Las Vegas 89109 702/891-7349 Southwestern
########################
Le Montrachet Bistro Paradise Rd. Las Vegas 89109 702-732-5651 French Bistro
Le Montrachet 3000 W. Paradise Rd. Las Vegas 89109 702/732-5111 Continental
########################
Palace Court 3570 Las Vegas Blvd. S. Las Vegas 89109 702-731-7110 French (New)
Palace Court 3570 Las Vegas Blvd. S Las Vegas 89109 702/731-7547 Continental
########################
Second Street Grill 200 E. Fremont St. Las Vegas 89101 702-385-6277 Pacific Rim
Second Street Grille 200 E. Fremont St. Las Vegas 89101 702/385-3232 Seafood
########################
Steak House  The 2880 Las Vegas Blvd. S. Las Vegas 89109 702-734-0410 Steakhouses
Steak House 2880 Las Vegas Blvd. S Las Vegas 89109 702/734-0410 Steak Houses
########################
Tillerman  The 2245 E. Flamingo Rd. Las Vegas 89119 702-731-4036 Steakhouses
Tillerman 2245 E. Flamingo Rd. Las Vegas 89119 702/731-4036 Seafood
########################
Abruzzi 2355 Peachtree Rd. NE Atlanta 30305 404-261-8186 Italian
Abruzzi 2355 Peachtree Rd.  Peachtree Battle Shopping Center Atlanta 30305 404/261-8186 Italian
########################
Bacchanalia 3125 Piedmont Rd. Atlanta 30305 404-365-0410 Californian
Bacchanalia 3125 Piedmont Rd.  near Peachtree Rd. Atlanta 30305 404/365-0410 International
########################
Bone's Restaurant Piedmont Rd. NE Atlanta 30305 404-237-2663 Steakhouses
Bone's 3130 Piedmont Road Atlanta 30305 404/237-2663 American
########################
Brasserie Le Coze 3393 Peachtree Rd. Atlanta 30326 404-266-1440 French Bistro
Brasserie Le Coze 3393 Peachtree Rd.  Lenox Square Mall  near Neiman Marcus Atlanta 30326 404/266-1440 French
########################
Buckhead Diner 3073 Piedmont Rd. Atlanta 30305 404-262-3336 American (New)
Buckhead Diner 3073 Piedmont Road Atlanta 30305 404/262-3336 American
########################
Ciboulette Restaurant 1529 Piedmont Ave. Atlanta 30324 404-874-7600 French (New)
Ciboulette 1529 Piedmont Ave. Atlanta 30324 404/874-7600 French
########################
Delectables 1 Margaret Mitchell Sq. Atlanta 30303 404-681-2909 Cafeterias
Delectables 1 Margaret Mitchell Sq. Atlanta 30303 404/681-2909 American
########################
Georgia Grille 2290 Peachtree Rd. Atlanta 30309 404-352-3517 Southwestern
Georgia Grille 2290 Peachtree Rd.  Peachtree Square Shopping Center Atlanta 30309 404/352-3517 American
########################
GHedgerose Heights Inn  The 490 E. Paces Ferry Rd. NE Atlanta 30305 404-233-7673 Continental
Hedgerose Heights Inn 490 E. Paces Ferry Rd. Atlanta 30305 404/233-7673 International
########################
Heera of India 595 Piedmont Ave. Atlanta 30324 404-876-4408 Indian
Heera of India 595a Piedmont Ave.  Rio Shopping Mall Atlanta 30324 404/876-4408 Asian
########################
Indigo Coastal Grill 1397 N. Highland Ave. Atlanta 30306 404-876-0676 Eclectic
Indigo Coastal Grill 1397 N. Highland Ave. Atlanta 30306 404/876-0676 Caribbean
########################
La Grotta 2637 Peachtree Rd. NE Atlanta 30305 404-231-1368 Italian
La Grotta 2637 Peachtree Rd.  Peachtree House Condominium Atlanta 30305 404/231-1368 Italian
########################
Mary Mac's Tea Room 224 Ponce de Leon Ave. Atlanta 30308 404-876-1800 Southern/Soul
Mary Mac's Tea Room 224 Ponce de Leon Ave. Atlanta 30308 404/876-1800 Southern
########################
Nikolai's Roof 255 Courtland St. Atlanta 404-221-6362 30303 Continental
Nikolai's Roof 255 Courtland St.  at Harris St. Atlanta 30303 404/221-6362 Continental
########################
Pano's & Paul's 1232 W. Paces Ferry Rd. Atlanta 30327 404-261-3662 American (New)
Pano's and Paul's 1232 W. Paces Ferry Rd. Atlanta 30327 404/261-3662 International
########################
Ritz-Carlton Cafe (Buckhead) 3434 Peachtree Rd. NE Atlanta 30326 404-237-2700 American (New)
Cafeacute;  Ritz-Carlton  Buckhead 3434 Peachtree Rd. Atlanta Georgia 30326 404/237-2700  ext 6108 International
########################
Ritz-Carlton Dining Room (Buckhead) 3434 Peachtree Rd. NE Atlanta 30326 404-237-2700 American (New)
Dining Room  Ritz-Carlton  Buckhead 3434 Peachtree Rd. Atlanta 30326 404/237-2700 International
########################
Ritz-Carlton Restaurant 181 Peachtree St. Atlanta 30303 404-659-0400 French (Classic)
Restaurant  Ritz-Carlton  Atlanta 181 Peachtree St. Atlanta 30303 404/659-0400 Continental
########################
Toulouse 293-B Peachtree Rd. Atlanta 30309 404-351-9533 French (New)
Toulouse B Peachtree Rd. Atlanta 30309 404/351-9533 French
########################
Veni Vidi Vici 41 14th St. Atlanta 30309 404-875-8424 Italian
Veni Vidi Vici 41 14th St. Atlanta 30309 404/875-8424 Italian
########################
Alain Rondelli 126 Clement St. San Francisco 94118 415-387-0408 French (New)
Alain Rondelli 126 Clement St. San Francisco 94118 415/387-0408 French
########################
Aqua 252 California St. San Francisco 94111 415-956-9662 American (New)
Aqua 252 California St. San Francisco 94111 415/956-9662 Seafood
########################
Boulevard 1 Mission St. San Francisco 94105 415-543-6084 American (New)
Boulevard 1 Mission St. San Francisco 94105 415/543-6084 American
########################
Cafe Claude 7 Claude Ln. San Francisco 94108 415-392-3505 French Bistro
Café Claude 7 Claude La. San Francisco 94108 415/392-3505 French
########################
Campton Place 340 Stockton St. San Francisco 94108 415-955-5555 American (New)
Campton Place 340 Stockton St. San Francisco 94108 415/955-5555 American
########################
Chez Michel 804 North Point St. San Francisco 94109 415-775-7036 Californian
Chez Michel 804 Northpoint San Francisco 94109 415/775-7036 French
########################
Fleur de Lys 777 Sutter St. San Francisco 94109 415-673-7779 French (New)
Fleur de Lys 777 Sutter St. San Francisco 94109 415/673-7779 French
########################
Fringale 570 Fourth St. San Francisco 94107 415-543-0573 French Bistro
Fringale 570 4th St. San Francisco 94107 415/543-0573 French
########################
Hawthorne Lane 22 Hawthorne St. San Francisco 94105 415-777-9779 Californian
Hawthorne Lane 22 Hawthorne St. San Francisco 94105 415/777-9779 American
########################
Khan Toke Thai House 5937 Geary Blvd. San Francisco 94121 415-668-6654 Thai
Khan Toke Thai House 5937 Geary Blvd. San Francisco 94121 415/668-6654 Asian
########################
La Folie 2316 Polk St. San Francisco 94109 415-776-5577 French (New)
La Folie 2316 Polk St. San Francisco 94109 415/776-5577 French
########################
LuLu Restaurant-Bis-Cafe 816 Folsom St. San Francisco 94107 415-495-5775 Mediterranean
LuLu 816 Folsom St. San Francisco 94107 415/495-5775 Mediterranean
########################
Masa's 648 Bush St. San Francisco 94108 415-989-7154 French (New)
Masa's 648 Bush St. San Francisco 94108 415/989-7154 French
########################
Mifune 1737 Post St. San Francisco 94115 415-922-0337 Japanese
Mifune Japan Center  Kintetsu Building  1737 Post St. San Francisco 94115 415/922-0337 Asian
########################
PlumpJack Cafe 3127 Fillmore St. San Francisco 94102 415-563-4755 American (New)
PlumpJack Café 3201 Fillmore St. San Francisco 94102 415/563-4755 Mediterranean
########################
Postrio 545 Post St. San Francisco 94102 415-776-7825 Californian
Postrio 545 Post St. San Francisco 94102 415/776-7825 American
########################
Ritz-Carlton Dining Room (San Francisco) 600 Stockton St. San Francisco 94108 415-296-7465 French (New)
Ritz-Carlton Restaurant and Dining Room 600 Stockton St. San Francisco 94108 415/296-7465 American
########################
Rose Pistola 532 Columbus Ave. San Francisco 94133 415-399-0499 Italian
Rose Pistola 532 Columbus Ave. San Francisco 94133 415/399-0499 Italian
########################
"""

Address matching is principally a data quality challenge. Similar to other areas of data analysis, when the quality of input data to the match classification is low, the output generated will typically be of low accuracy (Christen, 2012). Problematically, most address databases we encounter in the real world are inconsistent, are missing of several values, and lack standardisation. Thus, a first step in the address matching work flow is to increase the quality of input data. In this way we increase the accuracy, completeness and consistency of our address records, which increases the ease in which they can be linked by the techniques we apply later on. Typically this stage begins by parsing the text representations of addresses into rows of a dataframe.

In [3]:
# load matched addresses, remove comment lines and reshape into two columns
data = pd.read_csv(StringIO(f), comment='#', 
                  header=None, 
                  names=['address']).values.reshape(-1, 2)

matched_address = pd.DataFrame(data, columns=['addr_zagat', 'addr_fodor'])
In [4]:
print('{} matched addresses loaded.'.format(matched_address.shape[0]))
matched_address.head(10).style.set_table_styles(styles)
112 matched addresses loaded.
Out[4]:
addr_zagat addr_fodor
0 Arnie Morton's of Chicago 435 S. La Cienega Blvd. Los Angeles 90048 310-246-1501 Steakhouses Arnie Morton's of Chicago 435 S. La Cienega Blvd. Los Angeles 90048 310/246-1501 American
1 Art's Deli 12224 Ventura Blvd. Studio City 91604 818-762-1221 Delis Art's Delicatessen 12224 Ventura Blvd. Studio City 91604 818/762-1221 American
2 Bel-Air Hotel 701 Stone Canyon Rd. Bel Air 90077 310-472-1211 Californian Hotel Bel-Air 701 Stone Canyon Rd. Bel Air 90077 310/472-1211 Californian
3 Cafe Bizou 14016 Ventura Blvd. Sherman Oaks 91423 818-788-3536 French Bistro Cafe Bizou 14016 Ventura Blvd. Sherman Oaks 91423 818/788-3536 French
4 Campanile 624 S. La Brea Ave. Los Angeles 90036 213-938-1447 Californian Campanile 624 S. La Brea Ave. Los Angeles 90036 213/938-1447 American
5 Chinois on Main 2709 Main St. Santa Monica 90405 310-392-9025 Pacific New Wave Chinois on Main 2709 Main St. Santa Monica 90405 310/392-9025 French
6 Citrus 6703 Melrose Ave. Los Angeles 90038 213-857-0034 Californian Citrus 6703 Melrose Ave. Los Angeles 90038 213/857-0034 Californian
7 Fenix at the Argyle 8358 Sunset Blvd. W. Hollywood 90069 213-848-6677 French (New) Fenix 8358 Sunset Blvd. West Hollywood 90069 213/848-6677 American
8 Granita 23725 W. Malibu Rd. Malibu 90265 310-456-0488 Californian Granita 23725 W. Malibu Rd. Malibu 90265 310/456-0488 Californian
9 Grill The 9560 Dayton Way Beverly Hills 90210 310-276-0615 American (Traditional) Grill on the Alley 9560 Dayton Way Los Angeles 90210 310/276-0615 American

A series of data cleaning exercises will then modify the data in ways that support the application of the linkage techniques. This might involve writing data cleaning scripts that convert all letters to lowercase characters, delete leading and trailing whitespaces, remove unwanted characters and tokens such as punctuation, or using hard-coded look-up tables to find and replace particular tokens. All together coding these steps contributes towards a standard form between the two address databases the user is attempting to match. This is important because standards between the two sources of address data under consideration will typically differ due to different naming conventions.

In the following cell blocks, we execute these steps by standardising our addresses. More specifically, we remove non-address components, convert all text to lower case and remove punctuation and non-alphanumeric characters.

In [5]:
# our rows contain non-address components such as phone number and 
# restaurant type so lets parse these using regular expressions into new columns
zagat_pattern = r"(?P<address>.*?)(?P<phone_number>\b\d{3}\-\d{3}\-\d{4}\b)(?P<category>.*$)"
fodor_pattern = r"(?P<address>.*?)(?P<phone_number>\b\d{3}\/\d{3}\-\d{4}\b)(?P<category>.*$)"

matched_address[["addr_zagat", "phone_number_zagat", "category_zagat"]] = matched_address["addr_zagat"].str.extract(zagat_pattern)
matched_address[["addr_fodor", "phone_number_fodor", "category_fodor"]] = matched_address["addr_fodor"].str.extract(fodor_pattern)
In [6]:
# standardise dataframe by converting all strings to lower case
matched_address = matched_address.applymap(lambda row : row.lower() if type(row) == str else row)

# remove punctuation and non-alphanumeric characters
matched_address['addr_zagat'] = matched_address['addr_zagat'].str.replace('[^\w\s]','')
matched_address['addr_fodor'] = matched_address['addr_fodor'].str.replace('[^\w\s]','')

After removing unwanted characters and tokens, our next step is to segment the entire address string into tagged attribute values. Addresses rarely come neatly formatted into sensible fields that identify each component, and so segmentation is a vital and often overlooked stage of the work flow. For example, an address might come in an unsegmented format such as "19 Water St. New York 11201". Our objective is then to segment (or label) this address into the appropriate columns for street number, street name, city and postcode. When we segment both sets of addresses from the datasets we intend to link, we build well-defined output fields that are suitable for matching.

In our case we use a statistical segmentation tool called Libpostal which is a Conditional Random Fields (CRFs) model trained on OpenStreetMap addresses. Before using the Python bindings, users are required to install the Libpostal C library first (see https://github.com/openvenues/pypostal#installation for installation instructions). CRFs are popular methods in natural language processing (NLP) for predicting sequence of labels across sequences of text inputs. Unlike discrete classifiers, CRFs model the probability of a transition between labels on "neighbouring" elements, meaning they take into account past and future address field states into the labelling of addresses into address fields. This mitigates a limitation of segmentation models such as hidden markov models (HMMs) called the label bias problem: "transitions leaving a given state to compete only against each other, rather than against all transitions in the model" (Lafferty et al., 2001). Take, for example, the business address for "1st for Toys, 244 Ponce de Leon Ave. Atlanta 30308". A naive segmentation model would incorrectly parse "1st" as a property number, whereas it actually completes the business name "1st for Toys", leading to an erroneous sequence of label predictions. When a CRFs has parsed "1st" and reaches the second token, "for", the model scores an $l\times l$ matrix where $l$ is the maximal number of labels (or address fields) that can be assigned by the CRFs. In $L$, $l_{ij}$ reflects the probability of the current word being labelled as $i$ and the previous word labelled $j$ (Diesner & Carley, 2008). In a CRFs model, when the parser reaches the actual property number, "244", high scoring in the matrix indicates the current label should be a property number, and the previous label revised to a business name. For a more detailed account, see Comber and Arribas-Bel (2019).

To segment each address, we apply the parse_address function row-wise for both the Zagat and Fodors addresses. This generates a list of tuples (see below code block for an example of the first two addresses from the Zagat dataset) that we convert into dictionaries before finally reading these into a pandas dataframe.

In [7]:
[[('arnie mortons of chicago', 'house'),
  ('435', 'house_number'),
  ('s la cienega blvd', 'road'),
  ('los angeles', 'city'),
  ('90048', 'postcode')],
 [('arts deli', 'house'),
  ('12224', 'house_number'),
  ('ventura blvd', 'road'),
  ('studio city', 'city'),
  ('91604', 'postcode')]]
Out[7]:
[[('arnie mortons of chicago', 'house'),
  ('435', 'house_number'),
  ('s la cienega blvd', 'road'),
  ('los angeles', 'city'),
  ('90048', 'postcode')],
 [('arts deli', 'house'),
  ('12224', 'house_number'),
  ('ventura blvd', 'road'),
  ('studio city', 'city'),
  ('91604', 'postcode')]]
In [8]:
# parse address string using libpostal CRF segmentation tool
addr_zagat_parse = [parse_address(addr, country='us') for addr in matched_address.addr_zagat]
addr_fodor_parse = [parse_address(addr, country='us') for addr in matched_address.addr_fodor]

# convert to pandas dataframe
addr_zagat_parse = pd.DataFrame.from_records([{k: v for v, k in row} for row in addr_zagat_parse]).add_suffix('_zagat')
addr_fodor_parse = pd.DataFrame.from_records([{k: v for v, k in row} for row in addr_fodor_parse]).add_suffix('_fodor')

# vertical join of CRF-parsed addresses between both dataframes
matched_address = matched_address.join(addr_zagat_parse).join(addr_fodor_parse)

Given we know the match status of our training data, we can safely join the records back together once we have successfully segmented them. Moreover, as we know the match status in advance, we can assign unique IDs that we will use later to create a binary variable for indicating whether an address pair is matched or non-matched.

In [9]:
# create unique ID for matched addresses, these will be used later to create a match status
uids = [str(uuid.uuid4()) for i in matched_address.iterrows()]

# the following two lines will assign the same uid to both columns, thus facilitating a match
addr_zagat_parse['uid'], addr_fodor_parse['uid'] = uids, uids
match_ids = pd.DataFrame({'zagat_id' : addr_fodor_parse['uid'], 'fodor_id' : addr_fodor_parse['uid']})
In [10]:
# join match ids to main dataframe
matched_address = matched_address.join(match_ids)

# preview of our parsed dataframe with uids assigned
matched_address.head().style.set_table_styles(styles)
Out[10]:
addr_zagat addr_fodor phone_number_zagat category_zagat phone_number_fodor category_fodor city_zagat city_district_zagat house_zagat house_number_zagat postcode_zagat road_zagat suburb_zagat city_fodor city_district_fodor house_fodor house_number_fodor postcode_fodor road_fodor state_fodor suburb_fodor zagat_id fodor_id
0 arnie mortons of chicago 435 s la cienega blvd los angeles 90048 arnie mortons of chicago 435 s la cienega blvd los angeles 90048 310-246-1501 steakhouses 310/246-1501 american los angeles nan arnie mortons of chicago 435 90048 s la cienega blvd nan los angeles nan arnie mortons of chicago 435 90048 s la cienega blvd nan nan 99bbcd03-ce45-40b5-907f-47f5ae16ae29 99bbcd03-ce45-40b5-907f-47f5ae16ae29
1 arts deli 12224 ventura blvd studio city 91604 arts delicatessen 12224 ventura blvd studio city 91604 818-762-1221 delis 818/762-1221 american studio city nan arts deli 12224 91604 ventura blvd nan studio city nan arts delicatessen 12224 91604 ventura blvd nan nan 1b1e1ee1-c880-4722-abaa-4ec44c7d94a6 1b1e1ee1-c880-4722-abaa-4ec44c7d94a6
2 belair hotel 701 stone canyon rd bel air 90077 hotel belair 701 stone canyon rd bel air 90077 310-472-1211 californian 310/472-1211 californian nan nan belair hotel 701 90077 stone canyon rd bel air nan nan nan hotel belair 701 90077 stone canyon rd bel air nan nan f2548f68-2326-4706-bdc1-dbfc265ecbf3 f2548f68-2326-4706-bdc1-dbfc265ecbf3
3 cafe bizou 14016 ventura blvd sherman oaks 91423 cafe bizou 14016 ventura blvd sherman oaks 91423 818-788-3536 french bistro 818/788-3536 french sherman oaks nan cafe bizou 14016 91423 ventura blvd nan sherman oaks nan cafe bizou 14016 91423 ventura blvd nan nan 936687e2-1161-4ecd-98c3-b5ac620d8776 936687e2-1161-4ecd-98c3-b5ac620d8776
4 campanile 624 s la brea ave los angeles 90036 campanile 624 s la brea ave los angeles 90036 213-938-1447 californian 213/938-1447 american los angeles nan campanile 624 90036 s la brea ave nan los angeles nan campanile 624 90036 s la brea ave nan nan 20a05006-d08e-4245-b014-ab2d0f552662 20a05006-d08e-4245-b014-ab2d0f552662

Once our addresses have met a particular standard of quality and are segmented into the desired address fields, the next step requires us to create candidate pairs of addresses that potentially resolve to the same address. In record linkage, this step is typically called indexing or blocking, and is required to reduce the number of address pairs that are compared. In doing so we remove pairs that are unlikely to resolve to true matches. To demonstrate the utility of blocking and why it is so important to address matching, we first create a full index which creates all possible combinations of address pairs. More concretely, a full index generates the Cartesian product between both sets of addresses. Conditional on the size of both dataframes, full blocking is highly computationally inefficient, and in our case we create $112\times 112 = 12544$ candidate links; this has a complexity of $O(n^2)$. We demonstrate the full index method to motivate the desire for practitioners to implement more sophisticated blocking techniques.

Below, we instantiate an Index class before specifying the desired full index method for generating pairs of records. We then create the Cartesian join between the Zagat and Fodor addresses which creates a MultiIndex that links every Zagat address with every Fodor address.

In [11]:
indexer = rl.Index()
indexer.full()

# create cartesian join between zagat and fodor restaurant addresses
candidate_links = indexer.index(matched_address.city_zagat, matched_address.city_fodor)
WARNING:recordlinkage:indexing - performance warning - A full index can result in large number of record pairs.
In [12]:
# this creates a two-level multiindex, so we name addresses from the zagat and fodor databases, respectively.
candidate_links.names = ['zagat', 'fodor']

print('{} candidate links created using full indexing.'.format(len(candidate_links)))
12544 candidate links created using full indexing.

In practice, a full index creates a dataframe with 12,544 rows and thus creates candidate address pairs between every possible combination of address from both the Zagat and Fodor datasets. Once we generate this dataframe of potential matches, we create a match status column and assign a 1 to actual matched addresses and 0 to non-matches based on the unique IDs created earlier.

In [13]:
# lets create a function we can reuse later on
def return_candidate_links_with_match_status(candidate_links):
    
    # we return a vector of label values for both the zagat and fodor restaurant IDs from the multiindex
    zagat_ids = candidate_links.get_level_values('zagat')
    fodor_ids = candidate_links.get_level_values('fodor')

    # now we create a new dataframe as long as the number of candidate links
    zagat = matched_address.loc[zagat_ids][['city_zagat', 'house_zagat',\
                                            'house_number_zagat', 'road_zagat', 'suburb_zagat', 'zagat_id']]
    fodor = matched_address.loc[fodor_ids][['city_fodor','house_fodor', 'house_number_fodor',\
                                            'road_fodor', 'suburb_fodor', 'fodor_id']]

    # vertically concateate addresses from both databases
    candidate_link_df = pd.concat([zagat.reset_index(drop=True), fodor.reset_index(drop=True)], axis=1)

    # next we create a match status column that we will use to train a machine learning model
    candidate_link_df['match_status'] = np.nan

    # assign 1 for matched, 0 non-matched
    candidate_link_df.loc[candidate_link_df['zagat_id'] == candidate_link_df['fodor_id'], 'match_status'] = 1.
    candidate_link_df.loc[ ~(candidate_link_df['zagat_id'] == candidate_link_df['fodor_id']), 'match_status'] = 0.
    
    return candidate_link_df

candidate_link_df = return_candidate_links_with_match_status(candidate_links)

To resolve addresses into matches and non-matches we generate comparison vectors between each candidate address pair. Each element of this comparison vector is a similarity metric used to assess the closeness of two address fields. In our case, we use Jaro-Winkler similarity because it has been observed to perform best on attributes containing named values (e.g., property names, street names, or city names) (Christen, 2012; Yancey, 2005). The Jaro similarity of two given address components $a_1$ and $a_2$ is given by

$$ jaro\_sim =\left\{ \begin{array}{ll} 0 \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ if \ \ m = 0\\ \frac{1}{3} (\frac{m}{|a_1|} + \frac{m}{|a_2|} + \frac{m-t}{m}) \ \ otherwise \end{array} \right. \ $$

where $|a_i|$ is the length of the address component string $a_i$, $m$ is the number of matching characters, and $t$ is the number of transpositions required to match the two address components. We will create a function that makes use of the jellyfish implementation of Jaro-winkler similarity. Several other string similarity metrics are available and are optimised for particular use cases and data types. See Chapter 5 of Concepts and Techniques for Record Linkage, Entity Resolution, and Duplicate Detection by Peter Christen for an excellent overview.

In [13]:
def jarowinkler_similarity(s1, s2):
    
    conc = pd.concat([s1, s2], axis=1, ignore_index=True)
    
    def jaro_winkler_apply(x):
        
        try:
            return jellyfish.jaro_winkler(x[0], x[1])
        # raise error if fields are empty
        except Exception as err:
            if pd.isnull(x[0]) or pd.isnull(x[1]):
                return np.nan
            else:
                raise err
                
    # apply row-wise to concatenated columns
    return conc.apply(jaro_winkler_apply, axis=1)

Before applying Jaro-Winkler similarity we need to choose columns that were segmented in both the Zagat and Fodor datasets.

In [14]:
# lets take a look at the columns we have available
candidate_link_df.columns
Out[14]:
Index(['city_zagat', 'house_zagat', 'house_number_zagat', 'road_zagat',
       'suburb_zagat', 'zagat_id', 'city_fodor', 'house_fodor',
       'house_number_fodor', 'road_fodor', 'suburb_fodor', 'fodor_id',
       'match_status'],
      dtype='object')

As we can only match columns that were parsed in both address datasets, this means we lose two columns, city_district_zagat and state_fodor, that were parsed by the CRF segmentation model. Once we observe which address fields are common to both datasets, we create so-called comparison vectors from candidate address pairs of the Zagat and Fodor datasets. Each element of the comparison vector represents the string similarity between address fields contained in both databases. For example, city_jaro describes the string similarity between the columns city_zagat and city_fodor. Looking at the first two rows of our comparison vectors dataframe, a city_jaro value of 1.00 implies an exact match whereas a value of 0.4040 implies a number of modifications are required to match the two city names, and so these are less likely to correspond to a match.

In [15]:
# create a function for building comparison vectors we can reuse later
def return_comparison_vectors(candidate_link_df):
    
    # compute jaro-winkler string similarity between columns of zagat and fodor databases
    candidate_link_df['city_jaro'] = jarowinkler_similarity(candidate_link_df.city_zagat, candidate_link_df.city_fodor)
    candidate_link_df['house_jaro'] = jarowinkler_similarity(candidate_link_df.house_zagat, candidate_link_df.house_fodor)
    candidate_link_df['house_number_jaro'] = jarowinkler_similarity(candidate_link_df.house_number_zagat, candidate_link_df.house_number_fodor)
    candidate_link_df['road_jaro'] = jarowinkler_similarity(candidate_link_df.road_zagat, candidate_link_df.road_fodor)
    candidate_link_df['suburb_jaro'] = jarowinkler_similarity(candidate_link_df.suburb_zagat, candidate_link_df.suburb_fodor)

    # now we build a dataframe that contains the jaro-winkler similarity between the address components and the matching status
    comparison_vectors = candidate_link_df[['city_jaro', 'house_jaro', 'house_number_jaro',\
                                            'road_jaro', 'suburb_jaro', 'match_status']]
    
    # set NaN values that occur with empty field comparisons to 0
    comparison_vectors = comparison_vectors.fillna(0.)
    
    return comparison_vectors

comparison_vectors = return_comparison_vectors(candidate_link_df)

# lets preview this dataframe to build some intution as to how it looks
comparison_vectors.head().style.set_table_styles(styles)
Out[15]:
city_jaro house_jaro house_number_jaro road_jaro suburb_jaro match_status
0 1 1 1 1 0 1
1 0.40404 0.568301 0 0.629085 0 0
2 0 0.482143 0 0.674077 0 0
3 0.626263 0.502778 0.511111 0.629085 0 0
4 1 0.45463 0 0.831493 0 0

Once we obtain comparison vectors for each candidate address pair, we frame our approach as a binary classification problem by resolving the vectors into matches and non-matches. As the Zagat and Fodors dataframe has labels that describe our address pairs as matched, we use supervised classification to train a statistical model, a random forest, to classify address pairs with an unknown match status into matches and non-matches. As a reminder, a random forest is generated using a multitude of decision trees during training which then outputs the mode of the match status decision for the individual trees.

In practice, we initialize a random forest object and split our comparison_vectors dataframe into features containing our Jaro-Winkler string similarity features, $X$, and a vector used to predict match status of the addresses, $y$.

In [ ]:
# create a random forest classifier that uses 100 trees and number of cores equal to those available on machine
rf = RandomForestClassifier(n_estimators = 100, 
                             # Due to small number of features (5) we do not limit depth of trees
                            max_depth = None, 
                            # max number of features to evaluate split is sqrt(n_features)
                            max_features = 'auto', 
                            n_jobs = os.cpu_count())

# define metrics we use to assess the model
scoring = ['precision', 'recall', 'f1']
folds = 10

# extract the jaro-winkler string similarity and match label
X = comparison_vectors.iloc[:, 0:5]
y = comparison_vectors['match_status']

To evaluate the performance of our built classification model, we use 10-fold cross-validation meaning the performance measures are averaged across the test sets used within the 10 folds. We use three metrics that are commonly used to evaluate machine learning models. Recall measures the proportion of address pairs that should have been classified, or recalled, as matched (Christen, 2012). The precision (or, equivalently, the positive predictive value) calculates the proportion of the matched address pairs that are classified correctly as true matches (Christen, 2012). Finally, the F1 score reflects the harmonic mean between precision and recall. Our cross-validation exercise is executed in the following cell.

In [16]:
# 10-fold cross-validation procedure
scores = cross_validate(estimator = rf,
                X = X,
                y = y,
                cv = folds, 
                scoring = scoring,
                return_train_score = False)
In [17]:
print('Mean precision score is {} over {} folds.'.format( np.round(np.mean(scores['test_precision']), 4), folds))
print('Mean recall score is {} over {} folds.'.format( np.round(np.mean(scores['test_recall']), 4), folds))
print('Mean F1 score is {} over {} folds.'.format( np.round(np.mean(scores['test_f1']), 4), folds))
Mean precision score is 0.9546 over 10 folds.
Mean recall score is 0.928 over 10 folds.
Mean F1 score is 0.9383 over 10 folds.

Overall, the high precision value implies that 95% of true positives are successfully disambiguated from false positives. Moreover, our recall value implies that 93% of all potential matches were successfully returned, with the remaining 7% of correct matches incorrectly labelled as false negatives. Given the high values in both of these metrics, the accompanying F1 score is equally high.

While a Cartesian product could be useful in a linkage exercise where we have a very small number of matched addresses, in production environments more sophisticated techniques are generally required to create candidate address links. This is particularly the case when we have a large number of addresses. Thus, blocking is typically introduced to partition the set of all possible address comparisons to within mutually exclusive blocks. If we let $b$ equal the number of blocks, we reduce the complexity of the comparison exercise to $O(\frac{n^2}{b})$, which is far more computationally tractable than the full index method used above.

When deciding which column to use as a blocking key we generally need pay attention to two main considerations. Firstly, we pay attention to attribute data quality. Typically when identifying a blocking key, we choose a key that has a low number of missing values. This is because choosing a key with many missing values forces a large number of addresses into a block where the key is an empty value, which may lead to many misclassified address matches. And secondly we pay attention to the frequency distribution of attribute values. We optimise towards a uniform distribution of values, as typically skewed distributions that result in some values occurring very frequently mean that these values will dominate the candidate pairs of address generated.

These considerations are addressed in the following two code blocks.

In [20]:
print("Missing postcodes for Zagat addresses: {}. \nMissing postcodes for Fodor addresses: {}."
      .format(matched_address.postcode_zagat.isnull().sum(), matched_address.postcode_fodor.isnull().sum()))
Missing postcodes for Zagat addresses: 1. 
Missing postcodes for Fodor addresses: 0.
In [21]:
# check distribution of postcode blocks
pc_dist = matched_address.groupby('postcode_fodor').size().to_frame().rename(columns={0:'n_addresses'})

f, ax = plt.subplots(1, figsize=(10,6))
sns.kdeplot(pc_dist.n_addresses.values, color='g', shade=True, legend=False)
ax.set_xlabel('Number of addresses in postcode block ($\mu = {}$, $\sigma = {}$).'
              .format(np.mean(pc_dist.n_addresses), np.round(np.std(pc_dist.n_addresses), 2)), size=15)
plt.show()

Figure 1: Figure generated by code 21

The postcode attribute looks like a sensible choice of blocking key because it contains just one missing value and there are very low numbers of candidate address comparisons within each block. As you can see in the output below, when we use a more sophisticated indexing technique we generate a far lower number of candidate address comparisons. In fact, we create only 1014 candidate address links despite adding synthetic non-matches (discussed below). Overall, our introduction of blocking substantially lowers the computational requirement of the linkage task.

To make this exercise more realistic, let's also create 112 synthetic non-matches so we have 224 addresses in total. This will also be important for training our machine learning technique to learn the representations of non-matched addresses in addition to matches. In this case we use the FEBRL data set generator script generate.py to create an artificially generated dataset (see http://users.cecs.anu.edu.au/~Peter.Christen/Febrl/febrl-0.3/febrldoc-0.3/node70.html). The script uses Python 2.7, so we read the output as JSON so the user does not have to rely on an external input. We do this in keeping with a self-contained notebook but describe the steps required to reproduce the non-matches below.

The synthetic non-matches are essentially random permutations of the matched addresses. These are constructed on the basis of frequency tables for each address field that count the occurrence of particular values. For example, the first row of a frequency table for a house number would look like: $<\text{house_number_attribute_value}>$,$<\text{frequency_of_occurence}>$.

In [19]:
# first we need columns from the zagat and fodor databases to create random addresses
zagat_cols = ['city_zagat', 'house_number_zagat', 'house_zagat', 'suburb_zagat', 'road_zagat', 'postcode_zagat']
fodor_cols = ['city_fodor', 'house_number_fodor', 'house_fodor', 'suburb_fodor', 'road_fodor','postcode_fodor']

# create a directory for address component frequencies
if not os.path.exists('freqs'):
    os.makedirs('freqs')

# create distributions of address components for both datasets that will be used to create fake addresses
for cols in [zagat_cols, fodor_cols]:
    for col in cols:
        freq = matched_address[col].value_counts().reset_index()
        freq.to_csv('freqs/{}_freq.csv'.format(col), index=False, header=False)

generate.py takes six parameters that are used to create non-matched addresses. The first argument demarcates the number of original records to be generated; the second specifies the number of duplicate records from the original to be generated; and the third, fourth and fifth arguments define the maximal number of duplicate records that will be created based on one original record, the maximum number of modifications introduced to the address field, and the maximum number of modifications introduced to the address, respectively. The final parameter is used to enter which probability distribution will be to create duplicate records - i.e. uniform, poisson, or zipf. In our case we are only interested in building synthetic non-matches (and not duplicates), so we set the number of original records to be built as 112, the number of duplicates generated as 0, and leave the number of modifications introduced by the recommended default settings.

In addition, for each address field, users are asked to define a dictionary inside generate.py that outlines the probability for particular modifications. This includes setting the probability of modifications such as misspellings, insertions, deletions, substitutions and transpositions of word and characters. An example dictionary for the house number address field is given below where we set the file path to the word frequency CSV generated above:

In [114]:
house_number_dict = {'name':'house_number',
                     'type':'freq',
               'char_range':'digit',
              # 'freq_file':'freqs/house_number_fodor_freq.csv',
               'freq_file':'freqs/house_number_zagat_freq.csv',
              'select_prob':0.20,
                 'ins_prob':0.10,
                 'del_prob':0.16,
                 'sub_prob':0.54,
               'trans_prob':0.00,
            'val_swap_prob':0.00,
            'wrd_swap_prob':0.00,
             'spc_ins_prob':0.00,
             'spc_del_prob':0.00,
                'miss_prob':0.00,
             'new_val_prob':0.20}

Damerau (1964) finds the proportions of typographical errors are typically spread as substitutions (59%), deletions (16%), transpositions (2%), insertions (10%) and multiple errors (13%). For this reason we broadly align our dictionary probabilities with these findings. After defining sensible probabilities for modifications, we execute the following scripts on a terminal which will create a file, zagat_synthetic_addresses.csv and fodor_synthetic_addresses.csv consisting of synthetic addresses from the Zagat and Fodor datasets, respectively.

For simplicity we generate our non-matches using all the data at once. However, in a real-world application, we might wish to create non-matches within each postcode block one at a time. This would create more realistic synthetic non-matches. This is because non-matched addresses would be constructed from the frequency tables of each postcode block, meaning each non-match would share more commonality to actual matched addresses. In practice, this would improve the predictive power of our classification model to disambiguate between candidate address pairs that have very subtle differences yet are still matched or non-matched.

In [112]:
# ! python2 generate.py zagat_synthetic_addresses.csv 112 0 4 2 2 poisson
Create 112 original and 0 duplicate records
  Distribution of number of duplicates (maximal 4 duplicates):
  [(1, 0.0), (2, 0.375), (3, 0.75), (4, 0.9375)]

Step 1: Load and process frequency tables and misspellings dictionaries

Step 2: Create original records


Step 2: Create duplicate records


Step 3: Write output file
End.
In [43]:
# ! python2 generate.py fodor_synthetic_addresses.csv 112 0 4 2 2 poisson
Create 112 original and 0 duplicate records
  Distribution of number of duplicates (maximal 4 duplicates):
  [(1, 0.0), (2, 0.375), (3, 0.75), (4, 0.9375)]

Step 1: Load and process frequency tables and misspellings dictionaries

Step 2: Create original records


Step 2: Create duplicate records


Step 3: Write output file
End.

We then read these synthetic non-matches into a dataframe.

In [116]:
# read parsed synthetic addresses
synthetic_zagat_address = pd.read_csv('zagat_synthetic_addresses.csv').add_suffix('_zagat').drop(columns=['rec_id_zagat'])
synthetic_fodor_address = pd.read_csv('fodor_synthetic_addresses.csv').add_suffix('_fodor').drop(columns=['rec_id_fodor'])

# set uids for synthetic addresses
synthetic_zagat_address['zagat_id'] = [str(uuid.uuid4()) for i in synthetic_zagat_address.iterrows()] 
synthetic_fodor_address['fodor_id'] = [str(uuid.uuid4()) for i in synthetic_fodor_address.iterrows()]

# join synthetic zagat and fodor addresses vertically
synthetic_non_matches = synthetic_zagat_address.join(synthetic_fodor_address)

# remove whitespace from column names and attributes
synthetic_non_matches = synthetic_non_matches.rename(columns = lambda x : x.strip())
synthetic_non_matches = synthetic_non_matches.applymap(lambda x : x.strip() if type(x) == str else x)

Now we have generated synthetic non-matches, we need to join these back to our dataframe of matched addresses. As the above steps require external scripts we provide the JSON required to reconstruct the synthetic dataframe below to keep the notebook self-contained. This can be read by executing the cell below which uses the pd.read_json function. As before, given this cell takes up a lot of real estate, feel free to collapse it after you have executed the code.

In [35]:
synthetic_non_matches = pd.read_json('{"house_zagat":{"0":"katsu","1":"fenix at the argyle","2":"dawat","3":"mary macs tea room","4":"buckhead diner","5":"alain rondelli","6":"spago","7":"rainbow room 30 rockefeller plaza","8":"tavern on the green","9":"plumpjack cafe","10":"palm","11":"les celebrites","12":"","13":"les celebrites","14":"arnie mortons of chicago","15":"rainbow room 30 rockefeller plaza","16":"spago","17":"chez michel","18":"","19":"carnegie deli","20":"bcafe lalo","21":"","22":"chez michel","23":"mi cocina","24":"tavern on the green","25":"union square cafe","26":"carnegie deli","27":"cdaniel","28":"khan toke thai house","29":"le chardonnay","30":"belair hotel","31":"manhattan ocean club","32":"locanda veneta","33":"gotham bar grill","34":"la caravelle","35":"arnie mortons of chicago","36":"ritzcarlton dining room","37":"ritzcarlton restaurant","38":"lespinasse","39":"campton place","40":"lorangerie","41":"cafe bizou","42":"mesa grill","43":"lulu restaurantbiscafe","44":"locanda veneta","45":"le chardonnay","46":"la caravelle","47":"union square cafe","48":"heera of india","49":"carnegie deli","50":"mifune","51":"union square cafe","52":"ritzcarlton dining room","53":"palace court","54":"coyote cafe las vegas","55":"island spice","56":"buckhead diner","57":"veni vidi vici","58":"mary macs tea room","59":"les celebrites","60":"sign of the dove","61":"mary macs tea room","62":"","63":"bones restaurant","64":"locanda veneta","65":"grill the","66":"coyote cafe las vegas","67":"four seasons","68":"nikolais roof","69":"cafe claude","70":"mary macs tea room","71":"ritzcarlton restaurant","72":"fleur de lys","73":"ritzcarlton cafe buckhead","74":"","75":"","76":"park avenue cafe","77":"second street grill","78":"uncle nicks","79":"arnie mortons of chicago","80":"bones restaurant","81":"ritzcarlton restaurant","82":"veni vidi vici","83":"","84":"locanda veneta","85":"yujean kangs","86":"mary macs tea room","87":"lulu restaurantbiscafe","88":"bones restaurant","89":"katsu","90":"","91":"ritzcarlton dining room","92":"carnegie deli","93":"dawat","94":"valentino","95":"georgia grille","96":"","97":"mesa grill","98":"rex il ristorante","99":"","100":"yujean kangs","101":"delectables","102":"katsu","103":"ritzcarlton dining room","104":"chez michel","105":"","106":"mi cocina","107":"lespinasse","108":"belair hotel","109":"bones restaurant","110":"ghedgerose heights inn","111":""},"house_number_zagat":{"0":"3799","1":"33","2":"340","3":"648","4":"701","5":"67","6":"3125","7":"2880","8":"100","9":"20","10":"33","11":"3200","12":"160","13":"255","14":"60","15":"1001","16":"293b","17":"8795","18":"1737","19":"1","20":"34","21":"2637","22":"5955","23":"545","24":"12224","25":"126","26":"155","27":"2316","28":"249","29":"595","30":"9001","31":"11","32":"2637","33":"816","34":"55","35":"1","36":"1737","37":"1","38":"595","39":"405","40":"5937","41":"797","42":"600","43":"1397","44":"1232","45":"903","46":"57","47":"701","48":"156","49":"3434","50":"545","51":"1397","52":"701","53":"33","54":"155","55":"155","56":"435","57":"255","58":"129","59":"293b","60":"435","61":"5937","62":"240","63":"57","64":"3130","65":"340","66":"8358","67":"2880","68":"1232","69":"100","70":"252","71":"1001","72":"2709","73":"804","74":"240","75":"804","76":"624","77":"9560","78":"42","79":"1","80":"624","81":"747","82":"1","83":"201","84":"1529","85":"3200","86":"129","87":"1972","88":"3570","89":"12","90":"2290","91":"3570","92":"3125","93":"57","94":"156","95":"2290","96":"3000","97":"2355","98":"20","99":"33","100":"20","101":"1737","102":"13","103":"8795","104":"126","105":"67","106":"129","107":"8795","108":"2355","109":"12","110":"156","111":"67"},"road_zagat":{"0":"","1":"pico blvd santa monica","2":"e 12th st","3":"","4":"second ave","5":"piedmont ave","6":"n highland ave","7":"w 58th st","8":"piedmont rd","9":"","10":"ponce de leon ave","11":"sunset blvd","12":"n la cienega blvd","13":"","14":"harrison st","15":"post st","16":"peachtree rd","17":"ninth ave","18":"main st","19":"","20":"","21":"las vegas blvd s las vegas","22":"","23":"","24":"e 53rd st","25":"","26":"dayton way","27":"jane st","28":"","29":"","30":"w 67th st","31":"","32":"e 55th st","33":"santa monica blvd","34":"","35":"central park s","36":"las vegas blvd s las vegas","37":"geary blvd","38":"e 61st st","39":"","40":"e 58th st","41":"harrison st","42":"","43":"","44":"","45":"","46":"ventura blvd","47":"","48":"s la cienega blvd","49":"","50":"","51":"","52":"ventura blvd","53":"w 58th st","54":"","55":"","56":"","57":"","58":"","59":"ventura blvd","60":"","61":"seventh ave","62":"","63":"peachtree rd ne","64":"ventura blvd","65":"e 63rd st","66":"","67":"margaret mitchell sq","68":"w 64th st","69":"","70":"third ave","71":"w paces ferry rd","72":"peachtree rd","73":"w 83rd st","74":"w 44th st","75":"peachtree rd","76":"","77":"","78":"","79":"","80":"","81":"","82":"w 51st st","83":"w broadway","84":"hillhurst ave","85":"","86":"dayton way","87":"w 51st st","88":"","89":"","90":"","91":"main st","92":"","93":"peachtree rd ne","94":"","95":"e 58th st","96":"","97":"e 55th st","98":"","99":"melrose ave","100":"s la cienega blvd","101":"stockton st","102":"e 50th st","103":"n alameda st","104":"e 54th st","105":"las vegas blvd s las vegas","106":"","107":"e 55th st","108":"","109":"","110":"e 12th st","111":"fillmore st"},"suburb_zagat":{"0":"los feliz","1":"","2":"","3":"","4":"","5":"","6":"","7":"","8":"los feliz","9":"","10":"","11":"","12":"","13":"","14":"","15":"","16":"","17":"","18":"","19":"","20":"","21":"","22":"","23":"","24":"chinatown","25":"","26":"","27":"","28":"","29":"","30":"","31":"","32":"","33":"","34":"","35":"","36":"","37":"","38":"","39":"","40":"","41":"","42":"","43":"","44":"","45":"los feliz","46":"","47":"","48":"","49":"","50":"","51":"","52":"chinatown","53":"chinatown","54":"chinatown","55":"","56":"","57":"los feliz","58":"","59":"","60":"","61":"","62":"","63":"","64":"","65":"","66":"","67":"","68":"","69":"","70":"","71":"","72":"","73":"","74":"","75":"","76":"","77":"","78":"","79":"","80":"","81":"","82":"","83":"","84":"","85":"","86":"","87":"los feliz","88":"","89":"","90":"","91":"","92":"","93":"","94":"","95":"","96":"","97":"","98":"los feliz","99":"","100":"","101":"","102":"","103":"","104":"","105":"","106":"","107":"","108":"","109":"los feliz","110":"","111":""},"city_zagat":{"0":"new york city","1":"atlanta","2":"new york city","3":"","4":"los angeles","5":"atlanta","6":"new york city","7":"pasadena","8":"las vegas","9":"atlanta","10":"atlanta","11":"atlanta","12":"atlanta","13":"","14":"w hollywood","15":"new york city","16":"san francisco","17":"atlanta","18":"new york city","19":"atlanta","20":"new york city","21":"san francisco","22":"atlanta","23":"atlanta","24":"new york city","25":"new york city","26":"atlanta","27":"san francisco","28":"new york city","29":"new york city","30":"","31":"atlanta","32":"san francisco","33":"las vegas","34":"las vegas","35":"atlanta","36":"atlanta","37":"atlanta","38":"new york city","39":"san francisco","40":"atlanta","41":"atlanta","42":"atlanta","43":"new york city","44":"malibu","45":"","46":"san francisco","47":"new york city","48":"atlanta","49":"w hollywood","50":"new york city","51":"new york city","52":"new york city","53":"w hollywood","54":"new york city","55":"atlanta","56":"new york city","57":"santa monica","58":"","59":"san francisco","60":"san francisco","61":"new york city","62":"los angeles","63":"","64":"studio city","65":"san francisco","66":"atlanta","67":"new york city","68":"","69":"san francisco","70":"san francisco","71":"new york city","72":"new york city","73":"new york city","74":"atlanta","75":"san francisco","76":"san francisco","77":"new york city","78":"new york city","79":"new york city","80":"","81":"new york city","82":"w hollywood","83":"w hollywood","84":"new york city","85":"new york city","86":"atlanta","87":"new york city","88":"","89":"las vegas","90":"new york city","91":"new york city","92":"","93":"new york city","94":"new york city","95":"new york city","96":"atlanta","97":"new york city","98":"new york city","99":"san francisco","100":"beverly hills","101":"new york city","102":"san francisco","103":"atlanta","104":"las vegas","105":"atlanta","106":"atlanta","107":"los angeles","108":"new york city","109":"new york city","110":"new york city","111":"new york city"},"postcode_zagat":{"0":89109,"1":10065,"2":10013,"3":30326,"4":30309,"5":10003,"6":30309,"7":90046,"8":90036,"9":30326,"10":30324,"11":89109,"12":10065,"13":30305,"14":10022,"15":10003,"16":10065,"17":89109,"18":10009,"19":10019,"20":10003,"21":94121,"22":30306,"23":30303,"24":30305,"25":10065,"26":10019,"27":10013,"28":10022,"29":94105,"30":10065,"31":10022,"32":10023,"33":10022,"34":91103,"35":10019,"36":10112,"37":30324,"38":30305,"39":30309,"40":10022,"41":30327,"42":30309,"43":94107,"44":94133,"45":10024,"46":10019,"47":10019,"48":90046,"49":30305,"50":89109,"51":30324,"52":10014,"53":30305,"54":10023,"55":10024,"56":10019,"57":94108,"58":30305,"59":90048,"60":30305,"61":94121,"62":10022,"63":94105,"64":94133,"65":10022,"66":10019,"67":30324,"68":10019,"69":30308,"70":10019,"71":90027,"72":10023,"73":90069,"74":94109,"75":10023,"76":10112,"77":10019,"78":30327,"79":94121,"80":10112,"81":10023,"82":90048,"83":10022,"84":10022,"85":10003,"86":30303,"87":90048,"88":11201,"89":10019,"90":10022,"91":10065,"92":94115,"93":90405,"94":10065,"95":10024,"96":10019,"97":10022,"98":94133,"99":94102,"100":30305,"101":10022,"102":10036,"103":94133,"104":30327,"105":10013,"106":10009,"107":10019,"108":90069,"109":90077,"110":10036,"111":94102},"zagat_id":{"0":"61acbbe3-c8ad-4ca8-8a2b-796e4e0a695c","1":"91a409a8-cd5b-4934-97f3-aeb5b7718ad2","2":"826630cc-301a-488b-ab53-169b7f74ee94","3":"83f7db98-c162-4f95-b13d-dd6fd369721d","4":"e560da16-f2a3-49e4-a1e4-8fddfb35d787","5":"0999c8b9-57f0-440e-b17e-40cb800a50e7","6":"82846de1-d9af-404e-9d18-e4dcf781eb68","7":"aebb25cb-539f-4684-b044-52eb98b2f329","8":"c7d97782-c12e-410b-bc50-f6e4d492a0dc","9":"a5eacdca-060a-49cd-932a-280e5f64db6f","10":"f9215436-d51e-4012-8111-e92cc7c31436","11":"7bcc5019-7c9a-48d5-bbd4-cdbdbecd98c2","12":"3aa65c71-07d7-4613-aef4-965b2a9855e3","13":"17452044-9a0a-4106-b9d0-ca471d0de69d","14":"5730f578-af2e-4dfc-8898-3fcb36a160f8","15":"a6a64fe0-8403-4494-965b-56113b549bb8","16":"617cd442-a085-4a61-a57d-e52d8ab51429","17":"c61da49f-164c-47ee-ab18-aa8b382d70cd","18":"54fb182b-b4b3-40a3-b0da-576b89b7c3b3","19":"28a62631-8be3-4161-98c0-4447ff2411cd","20":"1af4147b-ea95-40b2-8513-871d17f9c2f9","21":"fc3406ef-6ceb-4507-a4ed-4ba849950845","22":"ecf68609-9490-4736-ace0-8182ed99ba32","23":"5978e7cb-1dad-4ed1-b001-5e9f077e0136","24":"83c6a3b7-a502-44b5-88ae-1621ec305698","25":"5824b239-3d0e-42b1-a2ba-5a063b654b8e","26":"29dcf5bc-6e51-4f9d-84b6-14c338c7919e","27":"f7e52b40-7c09-4fd0-9e9b-12f9f638bfbd","28":"84a5b284-f286-4d91-936b-79cf5ff73434","29":"446b9dc0-a555-4568-a68a-9eb919dfc70f","30":"505bb164-4f0e-4d08-980d-b85992714553","31":"5711eda5-656a-4d97-8138-10ff1795f7e4","32":"793c0ade-dc0d-4058-a7da-6bd1f03eb769","33":"eab8910a-4362-45ab-86a0-d8483297cf2e","34":"fd9af25b-532a-44be-8019-b878b17ddee2","35":"b491d594-fb3a-48b2-8819-a0eb4f42bcd1","36":"c6b34c28-6664-425c-9791-4d25e64817e0","37":"0bdb021c-8ff2-4563-9d55-46a6f3fc392e","38":"531c66f0-22b9-4b3c-bca9-db9c290214f0","39":"5d855218-7b2d-47d8-a988-f05d23bc643f","40":"e1090d3e-930b-4ea1-9952-27c88053b3d7","41":"810905c3-22b1-481e-9cef-f1c0e4030f51","42":"4d64e508-0a80-47b8-8eab-d1008d088379","43":"43304557-365f-457c-8e18-8143e3ffc58a","44":"1ed3bb69-afe8-49fa-a535-c2072eeb089c","45":"abc4b185-5cfa-4a34-be09-5fff0d7ac3dd","46":"eba8fd4a-4b6e-461c-87ac-0c6906b82707","47":"e9025f7b-54d9-4e41-b8d6-c0f3d568be19","48":"12728e39-09a3-46e0-9b05-4715a3fad395","49":"bcb27e90-0de5-49a8-8758-1b1981a9d6fd","50":"ab1fe081-a6ce-4067-96ad-5f37ebbd5849","51":"9684d34e-172d-4ab4-9536-f94ee70a4c48","52":"943b21f0-f605-4308-8eb9-4df581b25344","53":"3805db19-a390-41fc-80ab-5a158139a465","54":"1d2a42b1-0f16-4648-a21c-9a6156a76d05","55":"9f572b61-2328-439e-be88-8dc6398a0990","56":"e61a1d26-5402-4f91-9f14-a2a8a2bbaf18","57":"022d5c33-0fdc-4488-aaa1-157d37322f87","58":"417d4887-1153-4c02-8644-e20164acbef8","59":"dd704dd1-5531-411b-9da6-55b3e70cb0bd","60":"7b3c699c-d715-4e2f-aba5-395a71aed144","61":"948722b7-2618-4209-ae91-ffd2b28585ff","62":"41193f69-baa7-4e31-add4-890f937951f7","63":"b4596a5b-ed79-4fbc-a518-5d664224025f","64":"456de68f-da8c-4bbc-8758-e65c1ea9ab0d","65":"d4b74c0b-ee69-4670-9269-c6adf6aee3d6","66":"ca628600-ce25-44e9-94cb-06816e17eb68","67":"217a6eb2-8ca7-4035-9454-db6e81344e5e","68":"fbb20a0e-b41b-4ad7-a824-bb4c654cff6f","69":"9023e333-6f6d-4e41-9d62-be93215446c2","70":"d6cc01b9-ee9c-4d1c-a807-6fb917fe2ceb","71":"0697fed2-6232-498d-ab2e-2e7580331464","72":"4826f084-7fbd-472d-a449-5afd1a6dbb21","73":"bcaa29de-5b9a-4186-a63f-81c0fe88f60a","74":"1ec2aa3a-9e8e-426b-b8b8-92bd7bbe2e47","75":"39b5e475-32fd-4154-b334-9576ddd08f8f","76":"2b48cc35-cef2-4776-8613-dc5c85909aba","77":"7a04a30f-b264-40e3-a63f-08455a0db545","78":"0ce1f790-0f5f-4efc-afdd-cf662e31e21a","79":"4742d085-bcef-4ce3-a40e-6c8a50c83ac8","80":"b6f58564-73fb-4152-bacc-19bb4970d4ed","81":"35fcaa05-6c37-4bb2-aee0-649384ef53c6","82":"3458e2ac-7064-4fb6-8431-60b711e6dc18","83":"8c76c443-0cdc-4fa0-a2fc-227fc9c803cc","84":"fcc0964d-ff3e-4418-a4d0-e09b7ef9aef6","85":"3a68d483-ad32-4aa8-92da-98d9114dc7bb","86":"c45fc451-e2cd-4be3-89e4-4bc9279135a9","87":"14bb1ff2-2639-4818-a5e1-5185c5818be2","88":"e56ccafd-d1dd-4eac-84e3-695665616b51","89":"1b1d01b2-9fe4-4468-9699-d6c10acb953b","90":"1a945940-bbce-4bf1-b69d-835790f649f1","91":"43b7cb7c-a148-401a-971d-3c463a189a35","92":"62f2bd3a-dd2b-4431-82b7-ded03a74b9b5","93":"0b5e5c10-43ad-4c19-80fe-cd5665d5e80b","94":"8bdcbca9-28c9-4ade-977e-1c79c6e75906","95":"07c9df7a-4318-4b40-93c8-39ed3ff7b86f","96":"abdb0d2a-908e-4dc9-847f-a2d5cd41bdb7","97":"687d1eb2-875c-476d-8ef3-8b33ee0c4a89","98":"2b3d8ce5-7dab-4452-859e-22a21366e23d","99":"afc4200e-2f8a-4adb-bd27-773b4ab3e5e1","100":"3f76e5bf-4298-420b-946f-abafe3c494b5","101":"080b9f68-2070-426d-aa35-864b89307e7d","102":"207deff4-5125-4c03-8391-5f7c55e7020d","103":"21866b2c-342a-4660-8cf8-6775083f46c5","104":"451724da-61a5-48ef-b735-b810555d7b06","105":"e5b70e23-2eea-4277-a013-400c2a7c5757","106":"a337e12a-67e9-411a-827a-e70ac7e4cb6c","107":"5b3c0883-397a-4c31-ae74-2d13476d0b85","108":"2c73780e-f714-41fa-b1cd-517f774d219a","109":"73e3a64e-ff04-4266-99b0-2cdfd6a2973b","110":"4e01bb13-661c-4c10-aa9e-bf2afd3798cb","111":"b1b549ec-14f0-46a3-bdd3-dabcff1dcc08"},"house_fodor":{"0":"cafeacute ritzcarlton","1":"the palm","2":"patina","3":"indigo coastal grill","4":"mary macs tea room","5":"yujean kangs gourmet chinese cuisine","6":"the palm","7":"pinot bistro","8":"veni vidi vici","9":"mi cocina","10":"brasserie le coze","11":"gramercy tavern","12":"locanda veneta","13":"philippes the original","14":"yujean kangs gourmet chinese cuisine","15":"lorangerie","16":"","17":"la caravelle","18":"georgia grille","19":"arnie mortons of chicago","20":"","21":"locanda veneta","22":"sign of the dove","23":"","24":"second street grille","25":"","26":"heera of india","27":"locanda veneta","28":"chinois on main","29":"chinois on main","30":"the palm","31":"nikolais roof","32":"coyote cafeacute","33":"khan toke thai house","34":"petrossian","35":"valentino","36":"delectables","37":"","38":"cafeacute claude","39":"chez michel","40":"carnegie deli","41":"brasserie le coze","42":"chinois on main","43":"nikolais roof","44":"arnie mortons of chicago","45":"les ceacuteleacutebriteacutes","46":"grill on the alley","47":"dining room ritzcarlton","48":"","49":"mi cocina","50":"la grotta","51":"chez michel","52":"restaurant ritzcarlton atlanta","53":"the palm","54":"mesa grill","55":"georgia grille","56":"manhattan ocean club","57":"restaurant katsu","58":"second avenue deli","59":"restaurant ritzcarlton atlanta","60":"manhattan ocean club","61":"second street grille","62":"campton place","63":"aqua","64":"palace court","65":"locanda veneta","66":"grill on the alley","67":"","68":"cafeacute ritzcarlton","69":"nikolais roof","70":"","71":"ciboulette","72":"veni vidi vici","73":"chinois on main","74":"","75":"park avenue cafe","76":"fleur de lys","77":"panos and pauls","78":"bacchanalia","79":"gramercy tavern","80":"manhattan ocean club","81":"fleur de lys","82":"carnegie deli","83":"","84":"second avenue deli","85":"cafe bizou","86":"seryna","87":"","88":"","89":"the palm","90":"la caravelle","91":"","92":"la cote basque","93":"nikolais roof","94":"cafeacute claude","95":"ciboulette","96":"manhattan ocean club","97":"second avenue deli","98":"dining room ritzcarlton","99":"brasserie le coze","100":"grill on the alley","101":"bones","102":"mifune japan center kintetsu building","103":"gramercy tavern","104":"ciboulette","105":"nikolais roof","106":"rex il ristorante","107":"delectables","108":"cafeacute des artistes","109":"restaurant ritzcarlton atlanta","110":"steak house","111":"coyote cafeacute"},"house_number_fodor":{"0":1232,"1":3130,"2":1001,"3":243,"4":6703,"5":42,"6":224,"7":9001,"8":2290,"9":1232,"10":2450,"11":2245,"12":3130,"13":545,"14":95,"15":95,"16":545,"17":3200,"18":3200,"19":255,"20":3130,"21":2709,"22":35,"23":210,"24":99,"25":6703,"26":1232,"27":402,"28":12224,"29":67,"30":100,"31":3799,"32":160,"33":160,"34":3125,"35":1529,"36":156,"37":9560,"38":532,"39":9560,"40":3434,"41":239,"42":570,"43":182,"44":1232,"45":3570,"46":210,"47":2637,"48":249,"49":2880,"50":402,"51":2,"52":2637,"53":648,"54":243,"55":3200,"56":55,"57":9560,"58":5955,"59":129,"60":57,"61":100,"62":210,"63":11,"64":255,"65":160,"66":57,"67":2,"68":99,"69":1,"70":181,"71":200,"72":243,"73":490,"74":152,"75":99,"76":402,"77":12224,"78":3000,"79":3393,"80":57,"81":1114,"82":35,"83":100,"84":570,"85":33,"86":2880,"87":1114,"88":854,"89":181,"90":224,"91":3125,"92":804,"93":600,"94":2880,"95":816,"96":1232,"97":2709,"98":8284,"99":35,"100":55,"101":201,"102":200,"103":3201,"104":210,"105":11,"106":1001,"107":3200,"108":181,"109":57,"110":5955,"111":3799},"road_fodor":{"0":"","1":"w 55th st between 5th and 6th ave","2":"","3":"w 54th st","4":"e 12th st","5":"e 52nd st","6":"e paces ferry rd","7":"central park s","8":"","9":"3rd st","10":"horn ave","11":"e fremont st","12":"","13":"e 54th st","14":"n la cienega blvd","15":"peachtree rd","16":"","17":"","18":"","19":"melrose ave","20":"","21":"sutter st","22":"w 58th st","23":"stone canyon rd bel air","24":"","25":"","26":"w 54th st","27":"2nd ave at 10th st","28":"s la cienega blvd","29":"","30":"","31":"clement st","32":"","33":"","34":"","35":"w 58th st","36":"ave a at 6th st","37":"e paces ferry rd","38":"e 50th st","39":"w 58th st","40":"n highland ave","41":"","42":"las vegas blvd s las vegas","43":"","44":"e flamingo rd","45":"","46":"horn ave","47":"","48":"","49":"","50":"water st at the east river","51":"folsom st","52":"","53":"","54":"harrison st near hudson st","55":"peachtree rd","56":"n highland ave","57":"post st","58":"","59":"claude la","60":"peachtree rd","61":"santa monica blvd","62":"club 21 w 52nd st","63":"s olive st","64":"","65":"","66":"shun lee west 43 w 65th st","67":"peachtree rd","68":"las vegas blvd s las vegas","69":"e 16th st","70":"s la cienega blvd","71":"","72":"","73":"","74":"e 58th st","75":"peachtree st","76":"ventura blvd","77":"stockton st","78":"","79":"margaret mitchell sq","80":"","81":"n raymond ave","82":"e 61st st","83":"melrose ave","84":"peachtree rd","85":"","86":"peachtree rd","87":"w 44th st","88":"hawthorne lane 22 hawthorne st","89":"w 55th st","90":"","91":"","92":"2nd ave at 10th st","93":"","94":"n highland ave","95":"folsom st","96":"","97":"sunset blvd","98":"","99":"","100":"ventura blvd","101":"","102":"margaret mitchell sq","103":"","104":"clement st","105":"ventura blvd","106":"","107":"","108":"","109":"","110":"n la cienega blvd","111":""},"suburb_fodor":{"0":"","1":"","2":"","3":"","4":"","5":"","6":"","7":"","8":"","9":"","10":"","11":"","12":"","13":"","14":"","15":"","16":"","17":"peachtree square shopping center","18":"","19":"","20":"northpoint","21":"","22":"","23":"","24":"","25":"","26":"","27":"","28":"","29":"","30":"","31":"","32":"","33":"","34":"","35":"","36":"","37":"","38":"","39":"","40":"","41":"","42":"peachtree square shopping center","43":"","44":"","45":"northpoint","46":"","47":"","48":"","49":"","50":"","51":"","52":"northpoint","53":"","54":"","55":"","56":"","57":"","58":"","59":"","60":"","61":"","62":"","63":"","64":"northpoint","65":"peachtree square shopping center","66":"","67":"","68":"","69":"","70":"peachtree square shopping center","71":"","72":"","73":"","74":"","75":"","76":"","77":"","78":"","79":"","80":"","81":"","82":"","83":"","84":"","85":"","86":"","87":"","88":"northpoint","89":"","90":"","91":"","92":"","93":"","94":"","95":"","96":"","97":"","98":"peachtree square shopping center","99":"","100":"","101":"","102":"peachtree square shopping center","103":"","104":"","105":"","106":"","107":"","108":"","109":"","110":"","111":""},"city_fodor":{"0":"los angeles","1":"los angeles","2":"san francisco","3":"los angeles","4":"san francisco","5":"san francisco","6":"los angeles","7":"san francisco","8":"new york","9":"los angeles","10":"atlanta","11":"los angeles","12":"beverly hills","13":"los angeles","14":"sherman oaks","15":"new york","16":"new york","17":"los angeles","18":"new york","19":"new","20":"las vegas","21":"san francisco","22":"los angeles","23":"atlanta","24":"atlanta","25":"los angeles","26":"new york","27":"atlanta","28":"new york","29":"los angeles","30":"","31":"beverly hills","32":"new york","33":"","34":"san francisco","35":"new york","36":"atlanta","37":"los angeles","38":"","39":"","40":"los angeles","41":"new york","42":"new york","43":"malibu","44":"","45":"new","46":"","47":"new york","48":"","49":"las vegas","50":"san francisco","51":"atlanta","52":"atlanta","53":"san francisco","54":"new york","55":"new","56":"new york","57":"san francisco","58":"","59":"","60":"atlanta","61":"san francisco","62":"atlanta","63":"atlanta","64":"new york","65":"san francisco","66":"new york","67":"","68":"new york","69":"atlanta","70":"los angeles","71":"","72":"new york","73":"new york","74":"los angeles","75":"los angeles","76":"new york","77":"new york","78":"new york","79":"los angeles","80":"","81":"sherman oaks","82":"new york","83":"atlanta","84":"los angeles","85":"new york","86":"los angeles","87":"las vegas","88":"atlanta","89":"los angeles","90":"new york","91":"new york","92":"san francisco","93":"los angeles","94":"atlanta","95":"san francisco","96":"los angeles","97":"los angeles","98":"new york","99":"new york","100":"new york","101":"atlanta","102":"new york","103":"new york","104":"new","105":"","106":"atlanta","107":"las vegas","108":"los angeles","109":"new york","110":"los angeles","111":"atlanta"},"postcode_fodor":{"0":94108,"1":90069,"2":10003,"3":94121,"4":30305,"5":10022,"6":30305,"7":94108,"8":90069,"9":90038,"10":10019,"11":89109,"12":10003,"13":10021,"14":30303,"15":94107,"16":90027,"17":30305,"18":10009,"19":10003,"20":10024,"21":94102,"22":10022,"23":10014,"24":89101,"25":94108,"26":10019,"27":10022,"28":30305,"29":30308,"30":90048,"31":10022,"32":10013,"33":10024,"34":10019,"35":90069,"36":94102,"37":94109,"38":89109,"39":90038,"40":10013,"41":10019,"42":91423,"43":90405,"44":94118,"45":94108,"46":89109,"47":10003,"48":30326,"49":91423,"50":90012,"51":10022,"52":10019,"53":30309,"54":10022,"55":10014,"56":30327,"57":10022,"58":10019,"59":10019,"60":30326,"61":30309,"62":30305,"63":10036,"64":30305,"65":90069,"66":10022,"67":30305,"68":30305,"69":10019,"70":30326,"71":91103,"72":10023,"73":91423,"74":30309,"75":94109,"76":10003,"77":90405,"78":10019,"79":10023,"80":10024,"81":89109,"82":10022,"83":94107,"84":89119,"85":94109,"86":30324,"87":10112,"88":10019,"89":94121,"90":10003,"91":90210,"92":30326,"93":94105,"94":10003,"95":90046,"96":30326,"97":89109,"98":10013,"99":10023,"100":30305,"101":30305,"102":10022,"103":30305,"104":89109,"105":10022,"106":30309,"107":10022,"108":90036,"109":10022,"110":91423,"111":89109},"fodor_id":{"0":"fa5a52eb-f5b4-4978-915f-6e51237539b7","1":"2ae631ee-6ee5-4954-b68c-2ac8feb7ff74","2":"5a15f32e-506a-459e-8aa2-669f60eb9c2d","3":"1bd58d83-bef5-4ccb-a3db-53e486f465a2","4":"057fc904-9726-4f49-9738-3fc34111b54f","5":"478c61be-84d7-4841-81ba-f172aa0d656b","6":"6ff33b99-69a5-4ee0-ba19-0c2e2e46e6e7","7":"ce8cc353-8e77-43ad-be9b-4e6160d157a1","8":"c4935d11-7463-4931-98b3-eaf3a8f76e55","9":"b3fe9fb7-a786-4140-bff7-5499ab7f9eb4","10":"ceedc8c3-ea83-4b2f-877f-be97c389e965","11":"4102d1de-bcf0-4425-bfda-48112568f45b","12":"e5070b1b-8c9a-40ee-acf1-161b79d89327","13":"e5785c5b-ed42-40ce-94eb-6d98a62cbc2a","14":"1b988961-3d05-49bc-bedd-2bdd579d87cd","15":"b2f0d718-f556-4f88-b2a6-170502568840","16":"07e18e49-c899-4ec1-9de2-88c27fa334c1","17":"990ea007-d112-4436-aafb-51e1f2efb645","18":"66a4f30c-f865-4025-a0d7-15477a9e2d1e","19":"f47586ce-3153-4469-82f7-174c914a50a5","20":"379f5d4d-d536-4d23-858d-1f8897fdd67d","21":"d509773b-fb01-4fcb-a149-0afa5412550e","22":"031cef25-33dc-4d70-8e64-21f89dccace7","23":"9aa488a3-1f09-4103-8efb-3f53d29093f6","24":"6f2c2ee0-e5e4-49cd-a2fc-94c0e34bcf88","25":"3ba623c3-adaf-4714-a591-a1528ce6f2b6","26":"a32a22ea-d19d-476f-b619-2f01e770db02","27":"71496ea1-ee77-43bc-a301-7041f8075e9c","28":"4f6d462f-eed0-4722-89d4-e45a509abd8c","29":"9ed644d6-effe-433a-8edf-9d43efb620b1","30":"25affbea-186b-454e-a2b9-e0d5dba907c0","31":"db2abeeb-a011-45ab-af3b-a49221b023c4","32":"6205d265-9d2e-4e2f-86ce-a8eda1df2aba","33":"4d76dea9-c442-4da4-a855-ff11bf48a085","34":"840173f2-cb39-4e4b-bf5a-c92975b16bf0","35":"324c388c-86b9-4996-b184-b1b99e73f86d","36":"6fba3842-d1d6-4da8-8b35-f2ba11c8bed1","37":"9700ec5c-cc20-4c64-8f7a-b39ce31301b3","38":"9298f379-abb2-46f3-b019-72f981bdd1a9","39":"73ae10e7-09bb-491b-b1b5-11b7e6cdb301","40":"23168827-eee8-4c96-8e17-f241045cb836","41":"15a11250-889b-4c00-a3c8-5eb71a0043ef","42":"d7f7436a-feea-412e-9001-a24bcd3735d7","43":"480152f0-9e97-4c65-b494-1c0ea9f6e436","44":"3944414c-58f5-465e-9326-b4960cc2ad31","45":"62ea2093-67a4-49a8-8fb4-07f843819ed9","46":"64b87c84-b163-48e2-87b1-0c9ebf63a2f9","47":"d80dc0ae-352a-4615-ab2f-cf50306cd2ec","48":"2800fe95-44c4-4a5d-839d-038d3c396970","49":"c8f3fbce-4bf4-4381-99be-4c2a2cf88b2e","50":"068aaf3f-4990-495f-b689-f6a9d9dabf52","51":"31db35e6-829e-41ac-93f6-64e309640bb9","52":"5ad33fa5-76e5-4dd3-87fa-3a6468143611","53":"d51023a9-21ad-49d5-8b3b-b2c753d5b075","54":"3f0114c7-d615-4ccd-b7d2-2ed695601472","55":"9ea4dbac-f9f6-4a4c-905c-838a498cef83","56":"123a8c92-d188-4086-9ff3-0ca6563d68e7","57":"20ab8746-043d-4dec-a0aa-7de4c2de6160","58":"36fb798b-a337-4c32-a85d-dd9b0d816d5b","59":"43983d27-ea44-4d1c-9568-a6de81b8ca04","60":"9512d12f-3f5a-4be2-8ef4-280857ae87bd","61":"92cf6345-4dce-4742-a872-bf69a10451ee","62":"df5c3ba9-1d82-4db1-af71-d45cfbc18734","63":"88fa63b4-cbd9-49a1-bd0a-e12760045ba2","64":"e1a01bec-35a2-4df1-9f96-fcc06e681b87","65":"1ea8b69f-1472-4119-b479-2ad031f52397","66":"05e71227-785e-46a8-a46e-d72ed4e33ec6","67":"09c70b38-b6fa-4c54-8489-35815e597724","68":"549f99be-c479-46e3-9bc2-552d2a4a9e19","69":"06e43841-fbf5-4b91-833e-d01186d7c14b","70":"8cc04b51-a218-4310-bf3b-4bdc08e50aaa","71":"cc03c16c-379d-4fcf-a010-62e8fef0c2a9","72":"c70480d0-b1da-443e-9620-e9f908ce255b","73":"0c23eeda-e0c0-4484-ba71-9ecf14c5c308","74":"62bbcb30-4d4a-488b-8f09-45fa4aa94f38","75":"4c22a1a4-8360-45f5-aa4f-5e876b46f02f","76":"db17ae8e-bbcf-4f4e-b9ab-5d6c5bdb6921","77":"88eb5dd9-9d20-4d57-af50-f25017c24668","78":"3aa90986-6390-4b92-9a14-80af30565644","79":"16978197-17ab-4a36-83f4-9769811d221d","80":"e98f22e0-c0a1-4315-85d2-7c3c6bd3d5dd","81":"4b9a0739-a05e-4ceb-9041-0730bbc60ef6","82":"c5ea78fd-d08f-4360-a607-ccc4c5e1b4d8","83":"64e4ceeb-ce6e-4e3b-aa8d-248ed9c89ebd","84":"e4fab091-635e-4570-a5f7-a62c850c3c2e","85":"0534eafa-3508-4225-a441-63f32a8beeba","86":"e6a5a025-f6f4-49bc-9ab8-39171f56965d","87":"f9bf9c2b-4d24-4068-9718-738fd6a54ca6","88":"a668060d-5c8d-4f15-9291-1987840aca1c","89":"bbb4b95c-6361-4b06-8742-3e3c3f39266b","90":"f2c98f9d-380b-4853-9ad0-1895e0eb7527","91":"8556a638-0fe7-4667-87ae-170fe1457f2e","92":"282af179-9188-4627-90e5-deea76ca3336","93":"2992be83-31f7-40d4-bef1-38febdd3b8b8","94":"70959b67-2ba9-4130-8b57-d4984f2498ac","95":"94fe2a46-30d2-4419-822e-0a5734a7c520","96":"c8145a3e-d956-4a89-adec-94186a0f1d4d","97":"76eedd1c-8507-41f2-a8dc-3fb2e5c24b10","98":"02608814-a04c-4082-8d8b-f3625246309d","99":"8a452297-a3a1-4345-90b8-7c6a466f9c6a","100":"9105252b-0e61-49c1-af3e-7eb79e11ec9e","101":"bef13b9c-3eaf-4104-af87-daed77deacbf","102":"1a77106f-b06c-40d0-948b-97cb78748067","103":"2e4c0849-48eb-4dd0-8a73-63389dfe8448","104":"88a92eb4-5e58-4ef4-9513-cb18d308a1f2","105":"fd0a0b85-31bf-4925-841e-495a90186b1f","106":"abeb42ce-5afd-4576-b7ff-73a9af59eb0c","107":"b02c56fb-722f-4914-bf75-727eb753caab","108":"7bba539e-2609-4fd5-bead-dbb8b4f8b291","109":"adf52b74-241f-4eb7-8bb5-a28c17bdcd5e","110":"9c9e52d0-2346-47f2-9a30-2cc8cb24e27a","111":"00cc49d2-ec95-4496-bd86-708779ad3850"}}')

In the cell below we join our matched addresses with our synthetic non-matches, creating a dataframe of 224 address pairs.

In [36]:
# align columns of matched_address dataframe for horizontal join
matched_address = matched_address[['house_zagat', 'house_number_zagat', 'road_zagat', 'suburb_zagat', 'city_zagat', 'postcode_zagat','zagat_id', 'house_fodor', 'house_number_fodor', 'road_fodor', 'suburb_fodor', 'city_fodor', 'postcode_fodor', 'fodor_id']]

# horizontal join between matched addresses and synthetic non-matches
matches_with_non_matches = pd.concat([matched_address, synthetic_non_matches], ignore_index=True)

print('{} address pairs created consisting of {} matches and {} synthetic non-matches.'.format(matches_with_non_matches.shape[0],
                                                                                               matched_address.shape[0],
                                                                                               synthetic_non_matches.shape[0]))
224 address pairs created consisting of 112 matches and 112 synthetic non-matches.

With our matches and synthetic non-matches assembled into a dataframe with 224 address pairs, we can proceed to block on postcode values to create mutually exclusive address partitions. Thus, for every unique postcode value, a dataframe (or block) will be created in which candidate address pairs will be matched and non-matched based on attributes of their comparison vectors.

The following code block creates a MultiIndex that links together the IDs of addresses that are within the same postcode block.

In [37]:
indexer = rl.Index()

# block on postcode attribute
indexer.block(left_on='postcode_zagat', right_on='postcode_fodor')
candidate_links = indexer.index(matches_with_non_matches, matches_with_non_matches)

# this creates a two-level multiindex, so we name addresses from the zagat and fodor databases, respectively.
candidate_links.names = ['zagat', 'fodor']

print('{} candidate links created using the postcode attribute as a blocking key.'.format(len(candidate_links)))
1014 candidate links created using the postcode attribute as a blocking key.

We follow the same work flow as before and create comparison vectors for every 1014 candidate address links.

In [38]:
candidate_link_df = return_candidate_links_with_match_status(candidate_links)

comparison_vectors = return_comparison_vectors(candidate_link_df)

Following this, we train our random forest on the comparison vectors and match status labels. We use a 75/25 split for our train and test data.

In [39]:
X = comparison_vectors.iloc[:, 0:5]
y = comparison_vectors.match_status

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)

# create a random forest classifier that uses 100 trees and number of cores equal to those available on machine
rf = RandomForestClassifier(n_estimators = 100, 
                             # Due to small number of features (5) we do not limit depth of trees
                            max_depth = None, 
                            # max number of features to evaluate split is sqrt(n_features)
                            max_features = 'auto', 
                            n_jobs = os.cpu_count())

# predict match status of unseen address pairs
y_pred = rf.fit(X_train, y_train).predict(X_test)

Having fit our random forest on the training data we can now assess the model under the number of metrics we introduced earlier. We can also produce a confusion matrix which shows true negatives in the top-left quadrant, false positives in the top-right, false negatives in the bottom-left and true positives in the bottom-right. At first glance, the findings from the evaluation metrics below may seem counter-intuitive, especially as the results of the classification exercise using the full index performed better. However, it is pertinent to remind ourselves that we trained our classification model on matched address only, which reflected an idealised but unrealistic scenario. In the results below we introduced synthetic non-matches which reflected a scenario that a user is more likely to encounter in a real-world address matching exercise.

In the following code block we generate evaluation metrics and a confusion matrix for evaluating match performance.

In [40]:
print('Precision score: {}.'.format(np.round(precision_score(y_test, y_pred), 4)))
print('Recall score: {}.'.format(np.round(recall_score(y_test, y_pred), 4)))
print('F1 score: {}.'.format(np.round(f1_score(y_test, y_pred), 4)))

f,ax = plt.subplots(1, figsize=(10,6))
f.set_tight_layout(False)

fontsize=12
sns.heatmap(confusion_matrix(y_test, y_pred), 
            ax=ax, 
            annot=True, 
            annot_kws={'fontsize': 16}, 
            cmap='Greens', 
            fmt='g')
ax.set_yticklabels(['Match', 'Non-match'], fontsize=fontsize)
ax.set_xticklabels(['Non-match', 'Match'], fontsize=fontsize);
ax.set_ylabel('True label', fontsize=fontsize)
ax.set_xlabel('Predicted label', fontsize=fontsize)
ax.xaxis.labelpad = 18
ax.yaxis.labelpad = 18
plt.show();
Precision score: 0.8519.
Recall score: 0.8846.
F1 score: 0.8679.

Figure 2: Figure generated by code 40

Overall, our precision value implied 85% of true positives were correctly separated from false positives, and our recall value indicated that 88% of all true address matches were successfully retrieved, with the remaining 12% incorrectly classified as non-matches. With our model now fitted and tested, we could extend its use to predict the match status of unseen address pairs. As an example application, if we had a small sample of matched addresses that belonged to a larger set of unmatched addresses, we could use our trained predictive model to match the remaining addresses in the dataset. This would work so long as the textual representations of addresses used in the prediction stage follow a similar structure to those addresses used to train the classification model.

Before we conclude, a benefit of using ensemble methods such as random forest classifiers is that we can return an indication of how useful and valuable each feature was in the construction of each decision tree. In a practical application, extracting a measure of feature importance might be a useful step in pruning redundant features from the comparison vectors. This might be a useful step in lowering computation times as we decrease the number of address field comparisons required to evaluate candidate address pairs.

Thus, in the following code block we rank feature importance of particular address fields to the match classification.

In [41]:
# extract feature importances from random forest classifier
feature_importance_to_match = rf.feature_importances_

# calculate standard deviation of feature importances across trees
std = np.std([tree.feature_importances_ for tree in rf.estimators_], axis=0)
indices = np.argsort(feature_importance_to_match)[::-1]

# plot importances alongside feature labels
plt.figure(figsize=(10,6))
plt.title("Feature importances of address attributes to match", size=15)
plt.bar(range(X_train.shape[1]), feature_importance_to_match[indices],
       color="#3CB371", yerr=std[indices], align="center")
feature_labs = X_train.columns[np.argsort(feature_importance_to_match)[::-1]].values
plt.xticks(range(X_train.shape[1]), feature_labs, size=12)
plt.xlim([-1, X_train.shape[1]])
plt.show()

Figure 3: Figure generated by code 41

In our case, and as one might expect, the restaurant's house number, house_number_jaro is the most important feature used for resolving candidate pairs of addresses into a match while the suburb, suburb_jaro, is the least important feature and so could possibly be removed as an address field from the comparison step.

Address matching is a data enrichment process that is increasingly required in wide-ranging, real-world applications. For example, matching between census, commercial or lifestyle records has the potential benefit of improving data quality, enabling spatial data visualisation and joining data that would otherwise remain isolated in data silos. In absence of unique identifiers for directly linking data, practitioners have typically relied on statistical linkage methods for matching addresses. Linking address datasets in this way has the potential to unlock attributes that one would be unable to access in circumstances where no primary keys exist to join the two datasets. Thus, in this notebook, we documented the steps required to execute the work flow for an address matching exercise that utilised new and recent innovations in machine learning. While the dataset we used was low volume, the intention of the notebook was to demonstrate an approach that is reproducible within a self-contained environment, and which might be adapted by the interested user to larger data challenges. Training a predictive model to link restaurant addresses may seem a trivial problem to solve, but these addresses could easily be replaced by more meaningful address records in areas such as public health and socio-economic mobility studies. Therefore, the core contribution of this notebook sought to equip the regional scientist with skills necessary to extend the address matching work flow to their own (and far more interesting) use cases.

Bibliography

Baldovin, T., Zangrando, D., Casale, P., Ferrarese, F., Bertoncello, C., Buja, A., Marcolongo, A. and Baldo, V. (2015) Geocoding health data with geographic information systems: A pilot study in northeast Italy for developing a standardized data‐acquiring format. Journal of Preventive Medicine & Hygiene, 56, 88–94.

Cayo, R. and Talbot, T. O. (2003) Positional error in automated geocoding of residential addresses. International Journal of Health Geographics, 2, 1–10.

Christen, P. (2012) Data matching: Concepts and techniques for record linkage, entity resolution, and duplicate detection. New York, NY: Springer.

Comber, S. and Arribas‐Bel, D. (2019) Machine learning innovations in address matching: A practical comparison of word2vec and CRFs. Transactions in GIS.23, 334–348.

Damerau, F. (1964). A technique for computer detection and correction of spelling errors. Commun. ACM, 7, 171-176.

Diesner, J., and Carley, M. (2008). Conditional random fields for entity extraction and ontological text coding. Computational and Mathematical Organization Theory, 14, 248–262

Lafferty, J., McCallum, A., and Pereira, F. (2001). Conditional random fields: Probabilistic models for segmenting and labelling sequence data. In C. E. Brodley and A. P. Danyluk (Eds.), Proceedings of the 18th International Conference on Machine Learning (pp. 282–289). San Francisco, CA: Morgan Kaufmann

Reynolds, P., Behren, J. V., Gunier, R., Goldberg, D., Hertz, A., and Smith, D. (2003) Childhood cancer incidence rates and hazardous air pollutants in California: An exploratory analysis. Environmental Health Perspectives, 111, 663–668.

Ruggles, S., Fitch, C. and Roberts, E. (2018) Historical Census Record Linkage. Annual Review of Sociology, 44 (1), 19-37.

Yancey, W. (2005) Evaluating string comparator performance for record linkage (Research Report Series, Statistics #2005‐05). Washington, DC: U.S. Bureau of the Census.

© 2019 by the authors. Licensee: REGION - The Journal of ERSA, European Regional Science Association, Louvain-la-Neuve, Belgium. This article is distributed under the terms and conditions of the Creative Commons Attribution, Non-Commercial (CC BY NC) license (http://creativecommons.org/licenses/by-nc/4.0/)