{ "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 Northern Carolina voter registration dataset:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "import blocklib" ] }, { "cell_type": "code", "execution_count": 2, "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": 2, "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, with that we are able to verify the quality of a linkage\n", "between snapshots of this dataset taken at different times. `pc` refers to postcode.\n", "\n", "The next step is to configure how to block the data. There are two privacy preserving blocking methods currently\n", "supported by `blocklib`:\n", "\n", "1. Probabilistic signature (p-sig)\n", "2. LSH based $\\Lambda$-fold redundant (lambda-fold)\n", "\n", "This tutorial will demonstrate using both of these, starting with probabilistic signatures.\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 places records\n", "having the same signatures into the same block. You can find the original paper here:\n", "[Scalable Entity Resolution Using Probabilistic Signatures on Parallel Databases](https://arxiv.org/abs/1712.09691).\n", "\n", "An example blocking configuration using probabilistic signatures:" ] }, { "cell_type": "code", "execution_count": 3, "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\": 20,\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", "}\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The blocking config can be fully validated to ensure all required types are present." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [ { "data": { "text/plain": [ "BlockingSchemaModel(version=1, type=, config=PSigConfig(record_id_column=None, blocking_features=['givenname', 'surname'], filter=PSigFilterRatioConfig(type='ratio', max=0.02, min=0.0), blocking_filter=PSigBlockingBFFilterConfig(type='bloom filter', number_of_hash_functions=20, bloom_filter_length=2048, compress_block_key=False), signatures=[[PSigCharsAtSignatureSpec(type=, feature='givenname', config=PSigCharsAtSignatureConfig(pos=[0])), PSigCharsAtSignatureSpec(type=, feature='surname', config=PSigCharsAtSignatureConfig(pos=[0]))], [PSigMetaphoneSignatureSpec(type=, feature='givenname'), PSigMetaphoneSignatureSpec(type=, feature='surname')]]))" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "blocklib.validation.validate_blocking_schema(blocking_config)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Step 1 - Generate Signatures\n", "\n", "For a record `r`, a signature is a sub-record derived from record `r` with a signature strategy. An example signature\n", "strategy is to concatenate the initials of first and last name, e.g., the signature for record `\"John White\"` is `\"JW\"`.\n", "\n", "`blocklib` provides 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\n", "lists of corresponding record IDs. A record ID could be row index or the actual record identifier if it is available\n", "in the dataset.\n", "\n", "Signature strategies are defined in the `signatureSpecs` section. For example, in the above configuration, we are\n", "going to generate two signatures for each record. The first signature produces initials:\n", "\n", "```json\n", "[\n", " {\"type\": \"characters-at\", \"config\": {\"pos\": [0]}, \"feature\": \"givenname\"},\n", " {\"type\": \"characters-at\", \"config\": {\"pos\": [0]}, \"feature\": \"surname\"}\n", "]\n", "```\n", "\n", "The second signature is generated by a combination of how the two components of a person's name sounds:\n", "\n", "```json\n", "[\n", " {\"type\": \"metaphone\", \"feature\": \"givenname\"},\n", " {\"type\": \"metaphone\", \"feature\": \"surname\"}\n", "]\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", "### Step 2 - Filter Signatures\n", "\n", "Signature strategies can create blocks with many records, and blocks with just one record. To impose limits\n", "on the minimum and maximum block size `blocklib` provides configurable filtering.\n", "\n", "For example, in the above configuration, the filter is configured as:\n", "\n", "```json\n", "{\n", " \"type\": \"ratio\",\n", " \"max\": 0.02,\n", " \"min\": 0.001\n", "}\n", "```\n", "\n", "`blocklib` will filter out all signatures / blocks whose number of records is greater than 2% of number of total\n", "records or is less than 0.1% of number of total records. Note these percentages are based on the data provided\n", "to `blocklib` so only use on roughly symmetric sized record linkage.\n", "\n", "Absolute filtering is also supported to filter by number of records. An example `filter` configuration:\n", "\n", "```json\n", "{\n", " \"type\": \"count\",\n", " \"max\": 100,\n", " \"min\": 5\n", "}\n", "```\n", "\n", "### Step 3 - Anonymization\n", "\n", "Given the aim of privacy preserving record linkage, the signatures themselves (e.g. `\"JW\"`) are not going to be\n", "shared, instead following the `p-sig` paper, the signatures all get encoded into a Bloom Filter. Here we use one\n", "Bloom Filter and map all filtered signatures into that Bloom Filter.\n", "\n", "```\n", "\"blocking-filter\": {\n", " \"type\": \"bloom filter\",\n", " \"number-hash-functions\": 20,\n", " \"bf-len\": 2048,\n", "}\n", "```\n", "\n", "After anonymization, the signature becomes the set of indices of bits 1 in the bloom filter and hence can preserve\n", "the privacy of data for each data provider.\n", "\n", "### Blocking Data\n", "\n", "Now that we have configured how the P-Sig blocking will work, we can carry out our blocking job with `blocklib`.\n", "Note `blocklib` only accept list of tuples or lists as input data, so some pre-processing may be necessary. Example\n", "data input for `blocklib`:\n", "\n", "```python\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", "**Step 1 - Generate Candidate Blocks for Party A - Alice**" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Example PII [761859, 'kate', 'chapman', 'brighton', 4017]\n" ] } ], "source": [ "alice = df_alice.to_dict(orient='split')\n", "print(\"Example PII\", alice['data'][0])" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Statistics for the generated blocks:\n", "\tNumber of Blocks: 5028\n", "\tMinimum Block Size: 1\n", "\tMaximum Block Size: 61\n", "\tAverage Block Size: 1.8341\n", "\tMedian Block Size: 1\n", "\tStandard Deviation of Block Size: 3.8372\n", "\tCoverage: 100.0%\n", "Individual statistics for each strategy:\n", "Strategy: 0\n", "\tNumber of Blocks: 503\n", "\tMinimum Block Size: 1\n", "\tMaximum Block Size: 61\n", "\tAverage Block Size: 9.167\n", "\tMedian Block Size: 6\n", "\tStandard Deviation of Block Size: 9.3427\n", "\tCoverage: 100.0%\n", "Strategy: 1\n", "\tNumber of Blocks: 4534\n", "\tMinimum Block Size: 1\n", "\tMaximum Block Size: 7\n", "\tAverage Block Size: 1.017\n", "\tMedian Block Size: 1\n", "\tStandard Deviation of Block Size: 0.1584\n", "\tCoverage: 100.0%\n" ] } ], "source": [ "from blocklib import generate_candidate_blocks\n", "\n", "block_obj_alice = generate_candidate_blocks(alice['data'], blocking_config, header=alice['columns'])\n", "block_obj_alice.print_summary_statistics()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can print the statistics of the blocks in order to inspect the block distribution and decide if this is a good blocking result. \n", "\n", "`generate_candidate_blocks` returns a `CandidateBlockingResult`, the attribute we are most interested in is `blocks`,\n", "a `dict` that maps signatures to lists of records.\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'(1920, 1031, 142, 401, 1560, 671, 1830, 941, 52, 1211, 1470, 581, 1740, 851, 2010, 1121, 232, 491, 1650, 761)'" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(block_obj_alice.blocks.keys())[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To protect privacy, the signature / blocking key is not the original signature such as `JW`. Instead, it is a list of\n", "mapped indices of bits set to 1 in the Bloom Filter for the original signature. Next we want to do the same thing for\n", "another party - _enter Bob_.\n", "\n", "**Step2 - Generate Candidate Blocks for Party B - Bob**" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "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.8378\n", "\tMedian Block Size: 1\n", "\tStandard Deviation of Block Size: 3.8383\n", "\tCoverage: 100.0%\n", "Individual statistics for each strategy:\n", "Strategy: 0\n", "\tNumber of Blocks: 500\n", "\tMinimum Block Size: 1\n", "\tMaximum Block Size: 59\n", "\tAverage Block Size: 9.222\n", "\tMedian Block Size: 6\n", "\tStandard Deviation of Block Size: 9.3374\n", "\tCoverage: 100.0%\n", "Strategy: 1\n", "\tNumber of Blocks: 4529\n", "\tMinimum Block Size: 1\n", "\tMaximum Block Size: 4\n", "\tAverage Block Size: 1.0181\n", "\tMedian Block Size: 1\n", "\tStandard Deviation of Block Size: 0.1445\n", "\tCoverage: 100.0%\n" ] } ], "source": [ "# NBVAL_IGNORE_OUTPUT\n", "df_bob = pd.read_csv('data/bob.csv')\n", "bob = df_bob.to_dict(orient='split')\n", "block_obj_bob = generate_candidate_blocks(bob['data'], blocking_config, header=bob['columns'])\n", "block_obj_bob.print_summary_statistics()\n" ] }, { "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\n", "in both parties. Instead of directly comparing signatures, the algorithm maps the list of signatures into a\n", "Bloom Filter for each party called the candidate blocking filter, and then creates the combined blocking filter by only\n", "retaining the bits that are present in both candidate filters." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Alice: 2794 out of 5028 blocks are in common\n", "Bob: 2794 out of 5018 blocks are in common\n" ] } ], "source": [ "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\n", "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": 10, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "assessing blocks: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 2794/2794 [00:00<00:00, 223055.41key/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "reduction ratio: 0.996\n", "pair completeness: 1.0\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# NBVAL_IGNORE_OUTPUT\n", "from blocklib.evaluation import assess_blocks_2party\n", "\n", "subdata1 = [x[0] for x in alice['data']]\n", "subdata2 = [x[0] for x in bob['data']]\n", "\n", "rr, pc = assess_blocks_2party([filtered_blocks_alice, filtered_blocks_bob],\n", " [subdata1, subdata2])\n", "print(f'reduction ratio: {round(rr, 3)}')\n", "print(f'pair completeness: {pc}')" ] }, { "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\n", "method uses a list of selected bits selected randomly from Bloom Filter for each record as block keys.\n", "$\\Lambda$ refers the degree of redundancy i.e. we will conduct LSH-based blocking $\\Lambda$ times, each forms a\n", "blocking group. Then those blocking groups are combined into one blocking results. This will make a record\n", "redundant $\\Lambda$ times but will increase the recall.\n", "\n", "Let's see an example config, this time selecting the blocking features using column indices instead of column names:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "BlockingSchemaModel(version=1, type=, config=LambdaConfig(record_id_column=None, blocking_features=[1, 2], Lambda=5, bloom_filter_length=2048, number_of_hash_functions=10, K=40, block_encodings=False, random_state=0))" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "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", "}\n", "\n", "blocklib.validation.validate_blocking_schema(blocking_config)" ] }, { "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": 12, "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.8107\n", "\tMedian Block Size: 1\n", "\tStandard Deviation of Block Size: 20.9703\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.7888\n", "\tMedian Block Size: 1\n", "\tStandard Deviation of Block Size: 20.715\n" ] } ], "source": [ "print('Generating candidate blocks for Alice:')\n", "block_obj_alice = generate_candidate_blocks(alice['data'], blocking_config)\n", "block_obj_alice.print_summary_statistics()\n", "print()\n", "print('Generating candidate blocks for Bob: ')\n", "block_obj_bob = generate_candidate_blocks(bob['data'], blocking_config)\n", "block_obj_bob.print_summary_statistics()" ] }, { "cell_type": "code", "execution_count": 13, "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": [ "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": 14, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "assessing blocks: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 4167/4167 [00:00<00:00, 212918.95key/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "reduction ratio: 0.872\n", "pair completeness: 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(f'reduction ratio: {round(rr, 3)}')\n", "print(f'pair completeness: {pc}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.9.7" } }, "nbformat": 4, "nbformat_minor": 4 }