{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Blocking API\n", "\n", "Blocking is a technique that makes record linkage scalable. It is achieved by partitioning datasets into groups, called blocks and only comparing records in corresponding blocks. This can reduce the number of comparisons that need to be conducted to find which pairs of records should be linked.\n", "\n", "There are two main metrics to evaluate a blocking technique - reduction ratio and pair completeness. \n", "\n", "**Reduction Ratio**\n", "\n", "Reduction ratio measures the proportion of number of comparisons reduced by using blocking technique. If we have two data providers each has $N$ number of records, then \n", "\n", "$$\\text{reduction ratio}= 1 - \\frac{\\text{number of comparisons after blocking}}{N^2}$$\n", "\n", "**Pair Completeness**\n", "\n", "Pair completeness measure how many true matches are maintained after blocking. It is evalauted as\n", "\n", "$$\\text{pair completeness}= 1 - \\frac{\\text{number of true matches after blocking}}{\\text{number of all true matches}}$$\n", "\n", "Different blocking techniques have different methods to partition datasets in order to reduce as much number of comparisons as possible while maintain high pair completeness.\n", "\n", "In this tutorial, we demonstrate how to use blocking in privacy preserving record linkage. \n", "\n", "Load example Nothern Carolina voter registration dataset:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
recidgivennamesurnamesuburbpc
0761859katechapmanbrighton4017
11384455lianhursecarisbrook3464
21933333matthewrussobardon4065
31564695lorrainezammitminchinbury2770
45971993ingorichardsonwoolsthorpe3276
\n", "
" ], "text/plain": [ " recid givenname surname suburb pc\n", "0 761859 kate chapman brighton 4017\n", "1 1384455 lian hurse carisbrook 3464\n", "2 1933333 matthew russo bardon 4065\n", "3 1564695 lorraine zammit minchinbury 2770\n", "4 5971993 ingo richardson woolsthorpe 3276" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# NBVAL_IGNORE_OUTPUT\n", "import pandas as pd\n", "\n", "df_alice = pd.read_csv('data/alice.csv')\n", "df_alice.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this dataset, `recid` is the voter registration number. So we are able to verify the quality of a linkage between snapshots of this dataset taken at different times. `pc` refers to postcode.\n", "\n", "Next step is to config a blocking job. Before we do that, let's look at the blocking methods we are currently supporting:\n", "\n", "1. Probabilistic signature (p-sig)\n", "2. LSH based $\\Lambda$-fold redundant (lambda-fold)\n", "\n", "Let's firstly look at P-sig\n", "\n", "### Blocking Methods - Probabilistic signature (p-sig)\n", "\n", "The high level idea behind this blocking method is that it uses signatures as the blocking key and place only records having same signatures into the same block. You can find the original paper here: [Scalable Entity Resolution Using Probabilistic Signatures on Parallel Databases](https://arxiv.org/abs/1712.09691).\n", "\n", "Detailed steps and explanations are in the following.\n", "\n", "Let's see an example of configuration for `p-sig`" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "blocking_config = {\n", " \"type\": \"p-sig\",\n", " \"version\": 1,\n", " \"config\": {\n", " \"blocking-features\": [1, 2],\n", "# \"record-id-col\": 0,\n", " \"filter\": {\n", " \"type\": \"ratio\",\n", " \"max\": 0.02,\n", " \"min\": 0.00,\n", " },\n", " \"blocking-filter\": {\n", " \"type\": \"bloom filter\",\n", " \"number-hash-functions\": 4,\n", " \"bf-len\": 2048,\n", " },\n", " \"signatureSpecs\": [\n", " [\n", " {\"type\": \"characters-at\", \"config\": {\"pos\": [0]}, \"feature\": 1},\n", " {\"type\": \"characters-at\", \"config\": {\"pos\": [0]}, \"feature\": 2},\n", " ],\n", " [\n", " {\"type\": \"metaphone\", \"feature\": 1},\n", " {\"type\": \"metaphone\", \"feature\": 2},\n", " ]\n", " ]\n", " }\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Step1 - Generate Signature**\n", "\n", "For a record `r`, a signature is a sub-record derived from record `r` with a signature strategy. An example signature strategy is to concatenate the initials of first and last name, e.g., the signature for record `\"John White\"` is `\"JW\"`.\n", "\n", "We provide the following signature strategies:\n", "\n", "* feature-value: the signature is generated by returning the selected feature\n", "* characters-at: the signature is generated by selecting a single character or a sequence of characters from selected feature\n", "* metaphone: the signature is generated by phonetic encoding the selected feature using metaphone\n", "\n", "The output of this step is a reversed index where keys are generated signatures / blocking key and the values are list of corresponding record IDs. A record ID could be row index or the actual record identifier if it is available in the dataset.\n", "\n", "Signature strategies are defined in the `signatureSpecs` section. For example, in the above configuration, we are going to generate two signatures for each record. The first signature is a combination of 3 different signature strategies\n", "\n", "```\n", " {\"type\": \"characters-at\", \"config\": {\"pos\": [0]}, \"feature\": 1},\n", " {\"type\": \"characters-at\", \"config\": {\"pos\": [0]}, \"feature\": 2},\n", " {\"type\": \"feature-value\", \"feature_idx\": 4}\n", "\n", "```\n", "It combines the initials of first and last name and postcode.\n", "\n", "The second signature is generated by a combination of 2 signature strategies:\n", "```\n", " {\"type\": \"metaphone\", \"feature\": 1},\n", " {\"type\": \"metaphone\", \"feature\": 2},\n", "```\n", "That is phonetic encoding of first name and last name.\n", "\n", "*One signature corresponds to one block. I will use signature and block interchangeably but they mean the same thing.*\n", "\n", "**Step2 - Filter Too Frequent Signatures**\n", "\n", "A signature is assumed to identify a record as uniquely as possible. Therefore, we need to filter out some too frequent signatures since they can uniquely identify the record. On the otherside, we want to be resilient to frequency attack, so we need to filter out too rare signature that only contains very few records. The configuration of filtering is in the `filter` part. For example, in the above configuration, the filter section is configured as:\n", "```\n", " \"filter\": {\n", " \"type\": \"ratio\",\n", " \"max\": 0.02,\n", " \"min\": 0.001,\n", " }\n", "```\n", "Then we will filter out all signatures / blocks whose number of records is greater than 2% of number of total records or is less than 0.1% of number of total records. \n", "\n", "Note that we also support absoulte filtering configuration i.e. filter by number of counts. For example:\n", "\n", "```\n", " \"filter\": {\n", " \"type\": \"count\",\n", " \"max\": 100,\n", " \"min\": 5,\n", " }\n", "```\n", "\n", "**Step3 - Anonymization**\n", "\n", "Given we want to do privacy preserving record linkage, the signatures need to be hashed to avoid leaking of PII information. The most frequent used data structure of such encoding is Bloom Filter. Here we use one Bloom Filter and map all filtered signatures into that Bloom Filter. The configuration of Bloom Filter is in `block-filter` section:\n", "\n", "```\n", " \"blocking-filter\": {\n", " \"type\": \"bloom filter\",\n", " \"number-hash-functions\": 20,\n", " \"bf-len\": 2048,\n", " }\n", "\n", "```\n", "\n", "After anonymization, the signature becomes the set of indices of bits 1 in the bloom filter and hence can preseve the privacy of data for each data provider.\n", "\n", "### Carry out Blocking Job\n", "\n", "Okay, once you have a good understanding of the P-Sig blocking, we can carry out our blocking job with `blocklib`. First, we need to process the data since `blocklib` only accept list of tuples or lists as input data. An example data input for blocklib is\n", "\n", "```\n", "[\n", " [761859, 'kate', 'chapman', 'brighton', 4017],\n", " [1384455, 'lian', 'hurse', 'carisbrook', 3464],\n", " [1933333, 'matthew', 'russo', 'bardon', 4065],\n", " [1564695, 'lorraine', 'zammit', 'minchinbury', 2770],\n", " [5971993, 'ingo', 'richardson', 'woolsthorpe', 3276]\n", "]\n", "```\n", "\n", "**Step1 - Generate Candidate Blocks for Party A - Alice**" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Example PII [761859, 'kate', 'chapman', 'brighton', 4017]\n" ] } ], "source": [ "# NBVAL_IGNORE_OUTPUT\n", "data_alice = df_alice.to_dict(orient='split')['data']\n", "print(\"Example PII\", data_alice[0])" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "P-Sig: 100.0% records are covered in blocks\n", "Statistics for the generated blocks:\n", "\tNumber of Blocks: 5029\n", "\tMinimum Block Size: 1\n", "\tMaximum Block Size: 61\n", "\tAverage Block Size: 1.8337641678266057\n", "\tMedian Block Size: 1\n", "\tStandard Deviation of Block Size: 3.8368431973204213\n" ] } ], "source": [ "# NBVAL_IGNORE_OUTPUT\n", "from blocklib import generate_candidate_blocks\n", "\n", "block_obj_alice = generate_candidate_blocks(data_alice, blocking_config)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The statistics of blocks are printed for you to inspect the block distribution and decide if this is a good blocking result. Here both average and median block sizes are 1 which is resilient to frequency attack. \n", "\n", "You can get the blocking instance and blocks/reversed indice in the `block_obj_alice`. Let's look at the first block in the reversed indcies:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] }, { "data": { "text/plain": [ "'(1560, 401, 491, 1470)'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# NBVAL_IGNORE_OUTPUT\n", "print(block_obj_alice.state)\n", "list(block_obj_alice.blocks.keys())[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To protect the privacy of data, the signature / blocking key is not the original signature such as `JW`. Instead, it is a list of mapped indices of bits 1 in Bloom Filter of `JW`. Next we want to do the same thing for another party - Bob.\n", "\n", "**Step2 - Generate Candidate Blocks for Party B - Bob**" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "P-Sig: 100.0% records are covered in blocks\n", "Statistics for the generated blocks:\n", "\tNumber of Blocks: 5018\n", "\tMinimum Block Size: 1\n", "\tMaximum Block Size: 59\n", "\tAverage Block Size: 1.8377839776803508\n", "\tMedian Block Size: 1\n", "\tStandard Deviation of Block Size: 3.838423809405143\n", "\n", "(1098, 707, 316, 1973)\n", "[1, 25, 765, 1078, 1166, 1203, 1273, 1531, 1621, 1625, 1755, 1965, 2027, 2824, 3106, 3125, 3414, 3501, 3610, 4033, 4139, 4472, 4579]\n" ] } ], "source": [ "# NBVAL_IGNORE_OUTPUT\n", "df_bob = pd.read_csv('data/bob.csv')\n", "data_bob = df_bob.to_dict(orient='split')['data']\n", "block_obj_bob = generate_candidate_blocks(data_bob, blocking_config)\n", "print(block_obj_bob.state)\n", "print(list(block_obj_bob.blocks.keys())[0])\n", "print(list(block_obj_bob.blocks.values())[1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Generate Final Blocks\n", "\n", "Now we have candidate blocks from both parties, we can generate final blocks by only including signatures that appear in both parties. Instead of directly comparing signature, the algorithm will firstly map the list of signatures into a Bloom Filter for for each party called the candidate blocking filter, and then creates the combined blocking filter by only retaining the bits that are present in all candidate filters." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Alice: 2793 out of 5029 blocks are in common\n", "Bob: 2793 out of 5018 blocks are in common\n" ] } ], "source": [ "# NBVAL_IGNORE_OUTPUT\n", "from blocklib import generate_blocks\n", "\n", "filtered_blocks_alice, filtered_blocks_bob = generate_blocks([block_obj_alice, block_obj_bob], K=2)\n", "print('Alice: {} out of {} blocks are in common'.format(len(filtered_blocks_alice), len(block_obj_alice.blocks)))\n", "print('Bob: {} out of {} blocks are in common'.format(len(filtered_blocks_bob), len(block_obj_bob.blocks)))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Assess Blocking\n", "\n", "We can assess the blocking result when we have ground truth. There are two main metrics to assess blocking result as we mentioned in the beginning of this tutorial. Here is a recap:\n", "\n", "* reduction ratio: relative reduction in the number of record pairs to be compared.\n", "* pair completeness: the percentage of true matches after blocking\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "assessing blocks: 100%|██████████| 2793/2793 [00:00<00:00, 97204.45key/s]\n" ] } ], "source": [ "# NBVAL_IGNORE_OUTPUT\n", "from blocklib.evaluation import assess_blocks_2party\n", "\n", "\n", "subdata1 = [x[0] for x in data_alice]\n", "subdata2 = [x[0] for x in data_bob]\n", "\n", "rr, pc = assess_blocks_2party([filtered_blocks_alice, filtered_blocks_bob],\n", " [subdata1, subdata2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Feature Name are also Supported!\n", "\n", "When there are many columns in the data, it is a bit inconvenient to use feature index. Luckily, blocklib also supports feature name in the blocking schema:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "blocking_config = {\n", " \"type\": \"p-sig\",\n", " \"version\": 1,\n", " \"config\": {\n", " \"blocking-features\": ['givenname', 'surname'],\n", " \"filter\": {\n", " \"type\": \"ratio\",\n", " \"max\": 0.02,\n", " \"min\": 0.00,\n", " },\n", " \"blocking-filter\": {\n", " \"type\": \"bloom filter\",\n", " \"number-hash-functions\": 4,\n", " \"bf-len\": 2048,\n", " },\n", " \"signatureSpecs\": [\n", " [\n", " {\"type\": \"characters-at\", \"config\": {\"pos\": [0]}, \"feature\": 'givenname'},\n", " {\"type\": \"characters-at\", \"config\": {\"pos\": [0]}, \"feature\": 'surname'},\n", " ],\n", " [\n", " {\"type\": \"metaphone\", \"feature\": 'givenname'},\n", " {\"type\": \"metaphone\", \"feature\": 'surname'},\n", " ]\n", " ]\n", " }\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When generating candidate blocks, a header is required to pass through:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "P-Sig: 100.0% records are covered in blocks\n", "Statistics for the generated blocks:\n", "\tNumber of Blocks: 5029\n", "\tMinimum Block Size: 1\n", "\tMaximum Block Size: 61\n", "\tAverage Block Size: 1.8337641678266057\n", "\tMedian Block Size: 1\n", "\tStandard Deviation of Block Size: 3.8368431973204213\n" ] } ], "source": [ "data_alice = df_alice.to_dict(orient='split')['data']\n", "header = list(df_alice.columns)\n", "\n", "block_obj_alice = generate_candidate_blocks(data_alice, blocking_config, header=header)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Blocking Methods - LSH Based $\\Lambda$-fold Redundant\n", "\n", "Now we look the other blocking method that we support - LSH Based $\\Lambda$-fold Redundant blocking.This blocking method uses the a list of selected bits selected randomly from Bloom Filter for each record as block keys. $\\Lambda$ refers the degree of redundancy i.e. we will conduct LSH-based blocking $\\Lambda$ times, each forms a blocking group. Then those blocking groups are combined into one blocking results. This will make a record redundant $\\Lambda$ times but will increase the recall.\n", "\n", "Let's see an example config of it:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "blocking_config = {\n", " \"type\": \"lambda-fold\",\n", " \"version\": 1,\n", " \"config\": {\n", " \"blocking-features\": [1, 2],\n", " \"Lambda\": 5,\n", " \"bf-len\": 2048,\n", " \"num-hash-funcs\": 10,\n", " \"K\": 40,\n", " \"random_state\": 0,\n", " \"input-clks\": False\n", " }\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "Now let's explain the meaning of each argument:\n", "\n", "* blocking-features: a list of feature indice that we are going to use to generate blocks\n", "* Lambda: this number denotes the degree of redundancy - $H^i$, $i=1,2,...,\\Lambda$ where each $H^i$ represents one independent blocking group\n", "* bf-len: length of Bloom Filter for each record\n", "* num-hash-funcs: number of hash functions used to map record to Bloom Filter\n", "* K: number of bits we selected from Bloom Filter for each record\n", "* random_state: control random seed\n", "\n", "Then we can carry out the blocking job and assess the result just like above steps\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Generating candidate blocks for Alice:\n", "Statistics for the generated blocks:\n", "\tNumber of Blocks: 6050\n", "\tMinimum Block Size: 1\n", "\tMaximum Block Size: 873\n", "\tAverage Block Size: 3.8107438016528925\n", "\tMedian Block Size: 1\n", "\tStandard Deviation of Block Size: 20.970313750521722\n", "\n", "Generating candidate blocks for Bob: \n", "Statistics for the generated blocks:\n", "\tNumber of Blocks: 6085\n", "\tMinimum Block Size: 1\n", "\tMaximum Block Size: 862\n", "\tAverage Block Size: 3.788824979457683\n", "\tMedian Block Size: 1\n", "\tStandard Deviation of Block Size: 20.71496408472215\n" ] } ], "source": [ "# NBVAL_IGNORE_OUTPUT\n", "print('Generating candidate blocks for Alice:')\n", "block_obj_alice = generate_candidate_blocks(data_alice, blocking_config)\n", "print()\n", "print('Generating candidate blocks for Bob: ')\n", "block_obj_bob = generate_candidate_blocks(data_bob, blocking_config)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Alice: 4167 out of 6050 blocks are in common\n", "Bob: 4167 out of 6085 blocks are in common\n" ] } ], "source": [ "# NBVAL_IGNORE_OUTPUT\n", "filtered_blocks_alice, filtered_blocks_bob = generate_blocks([block_obj_alice, block_obj_bob], K=2)\n", "print('Alice: {} out of {} blocks are in common'.format(len(filtered_blocks_alice), len(block_obj_alice.blocks)))\n", "print('Bob: {} out of {} blocks are in common'.format(len(filtered_blocks_bob), len(block_obj_bob.blocks)))\n" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "assessing blocks: 100%|██████████| 4167/4167 [00:00<00:00, 7690.70key/s] " ] }, { "name": "stdout", "output_type": "stream", "text": [ "RR=0.8823915973988634\n", "PC=1.0\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# NBVAL_IGNORE_OUTPUT\n", "rr, pc = assess_blocks_2party([filtered_blocks_alice, filtered_blocks_bob],\n", " [subdata1, subdata2])\n", "print('RR={}'.format(rr))\n", "print('PC={}'.format(pc))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.4" }, "pycharm": { "stem_cell": { "cell_type": "raw", "metadata": { "collapsed": false }, "source": [] } } }, "nbformat": 4, "nbformat_minor": 4 }