{ "cells": [ { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "# Entity Service Permutation Output\n", "\n", "This tutorial demonstrates the workflow for private record linkage using the entity service. Two parties _Alice_ and _Bob_ have a dataset of personally identifiable information (PII) of several entities. They want to learn the linkage of corresponding entities between their respective datasets with the help of the entity service and an independent party, the _Analyst_.\n", "\n", "The chosen output type is `permuatations`, which consists of two permutations and one mask.\n", "\n", "\n", "### Who learns what?\n", "\n", "After the linkage has been carried out Alice and Bob will be able to retrieve a `permutation` - a reordering of their respective data sets such that shared entities line up.\n", "\n", "The Analyst - who creates the linkage project - learns the `mask`. The mask is a binary vector that indicates which rows in the permuted data sets are aligned. Note this reveals how many entities are shared.\n", "\n", "\n", "### Steps\n", "These steps are usually run by different companies - but for illustration all is carried out in this one file. The participants providing data are _Alice_ and *Bob*, and the *Analyst* acting the integration authority.\n", "\n", "* [Check connection to Entity Service](#Check-Connection)\n", "* [Data preparation](#Data-preparation)\n", " * Write CSV files with PII\n", " * [Create a Linkage Schema](#Schema-Preparation)\n", "* [Create Linkage Project](#Create-Linkage-Project)\n", "* [Generate CLKs from PII](#Hash-and-Upload)\n", "* [Upload the PII](#Hash-and-Upload)\n", "* [Create a run](#Create-a-run)\n", "* [Retrieve and analyse results](#Results)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "## Check Connection\n", "\n", "> If you're connecting to a custom entity service, change the address here. Or set the environment variable `SERVER` before launching the Jupyter notebook." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Testing anonlink-entity-service hosted at https://anonlink.easd.data61.xyz\n" ] } ], "source": [ "import os\n", "url = os.getenv(\"SERVER\", \"https://anonlink.easd.data61.xyz\")\n", "print(f'Testing anonlink-entity-service hosted at {url}')" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\"project_count\": 846, \"rate\": 593838, \"status\": \"ok\"}\r\n" ] } ], "source": [ "!anonlink status --server \"{url}\"" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "## Data preparation\n", "\n", "Following the [anonlink-client command line tutorial](https://anonlink-client.readthedocs.io/en/latest/tutorial/tutorial_cli.html) we will use a dataset from the `recordlinkage` library. We will just write both datasets out to temporary CSV files." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [], "source": [ "from tempfile import NamedTemporaryFile\n", "from recordlinkage.datasets import load_febrl4" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "pycharm": { "is_executing": false } }, "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", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
given_namesurnamestreet_numberaddress_1address_2suburbpostcodestatedate_of_birthsoc_sec_id
rec_id
rec-1070-orgmichaelaneumann8stanley streetmiamiwinston hills4223nsw191511115304218
rec-1016-orgcourtneypainter12pinkerton circuitbega flatsrichlands4560vic191612144066625
rec-4405-orgcharlesgreen38salkauskas crescentkeladapto4566nsw194809304365168
\n", "
" ], "text/plain": [ " given_name surname street_number address_1 \\\n", "rec_id \n", "rec-1070-org michaela neumann 8 stanley street \n", "rec-1016-org courtney painter 12 pinkerton circuit \n", "rec-4405-org charles green 38 salkauskas crescent \n", "\n", " address_2 suburb postcode state date_of_birth \\\n", "rec_id \n", "rec-1070-org miami winston hills 4223 nsw 19151111 \n", "rec-1016-org bega flats richlands 4560 vic 19161214 \n", "rec-4405-org kela dapto 4566 nsw 19480930 \n", "\n", " soc_sec_id \n", "rec_id \n", "rec-1070-org 5304218 \n", "rec-1016-org 4066625 \n", "rec-4405-org 4365168 " ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dfA, dfB = load_febrl4()\n", "\n", "a_csv = NamedTemporaryFile('w')\n", "a_clks = NamedTemporaryFile('w', suffix='.json')\n", "dfA.to_csv(a_csv)\n", "a_csv.seek(0)\n", "\n", "b_csv = NamedTemporaryFile('w')\n", "b_clks = NamedTemporaryFile('w', suffix='.json')\n", "dfB.to_csv(b_csv)\n", "b_csv.seek(0)\n", "\n", "dfA.head(3)\n" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "## Schema Preparation\n", "The linkage schema must be agreed on by the two parties. A hashing schema instructs clkhash how to treat each column for generating CLKs. A detailed description of the hashing schema can be found in the [clkhash schema docs](http://clkhash.readthedocs.io/en/latest/schema.html). We will ignore the columns ‘rec_id’ and ‘soc_sec_id’ for CLK generation." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [], "source": [ "schema = NamedTemporaryFile('wt')" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting /tmp/tmplm0udc70\n" ] } ], "source": [ "%%writefile {schema.name}\n", "{\n", " \"version\": 3,\n", " \"clkConfig\": {\n", " \"l\": 1024,\n", " \"xor_folds\": 0,\n", " \"kdf\": {\n", " \"type\": \"HKDF\",\n", " \"hash\": \"SHA256\",\n", " \"info\": \"c2NoZW1hX2V4YW1wbGU=\",\n", " \"salt\": \"SCbL2zHNnmsckfzchsNkZY9XoHk96P/G5nUBrM7ybymlEFsMV6PAeDZCNp3rfNUPCtLDMOGQHG4pCQpfhiHCyA==\",\n", " \"keySize\": 64\n", " }\n", " },\n", " \"features\": [\n", " {\n", " \"identifier\": \"rec_id\",\n", " \"ignored\": true\n", " },\n", " {\n", " \"identifier\": \"given_name\",\n", " \"format\": {\n", " \"type\": \"string\",\n", " \"encoding\": \"utf-8\"\n", " },\n", " \"hashing\": {\n", " \"strategy\": {\n", " \"bitsPerToken\": 30\n", " },\n", " \"hash\": {\n", " \"type\": \"doubleHash\"\n", " },\n", " \"comparison\": {\n", " \"type\": \"ngram\",\n", " \"n\": 2,\n", " \"positional\": false\n", " }\n", " }\n", " },\n", " {\n", " \"identifier\": \"surname\",\n", " \"format\": {\n", " \"type\": \"string\",\n", " \"encoding\": \"utf-8\"\n", " },\n", " \"hashing\": {\n", " \"strategy\": {\n", " \"bitsPerToken\": 30\n", " },\n", " \"hash\": {\n", " \"type\": \"doubleHash\"\n", " },\n", " \"comparison\": {\n", " \"type\": \"ngram\",\n", " \"n\": 2,\n", " \"positional\": false\n", " }\n", " }\n", " },\n", " {\n", " \"identifier\": \"street_number\",\n", " \"format\": {\n", " \"type\": \"integer\"\n", " },\n", " \"hashing\": {\n", " \"missingValue\": {\n", " \"sentinel\": \"\"\n", " },\n", " \"strategy\": {\n", " \"bitsPerToken\": 15\n", " },\n", " \"hash\": {\n", " \"type\": \"doubleHash\"\n", " },\n", " \"comparison\": {\n", " \"type\": \"ngram\",\n", " \"n\": 1,\n", " \"positional\": true\n", " }\n", " }\n", " },\n", " {\n", " \"identifier\": \"address_1\",\n", " \"format\": {\n", " \"type\": \"string\",\n", " \"encoding\": \"utf-8\"\n", " },\n", " \"hashing\": {\n", " \"strategy\": {\n", " \"bitsPerToken\": 15\n", " },\n", " \"hash\": {\n", " \"type\": \"doubleHash\"\n", " },\n", " \"comparison\": {\n", " \"type\": \"ngram\",\n", " \"n\": 2,\n", " \"positional\": false\n", " }\n", " }\n", " },\n", " {\n", " \"identifier\": \"address_2\",\n", " \"format\": {\n", " \"type\": \"string\",\n", " \"encoding\": \"utf-8\"\n", " },\n", " \"hashing\": {\n", " \"strategy\": {\n", " \"bitsPerToken\": 15\n", " },\n", " \"hash\": {\n", " \"type\": \"doubleHash\"\n", " },\n", " \"comparison\": {\n", " \"type\": \"ngram\",\n", " \"n\": 2,\n", " \"positional\": false\n", " }\n", " }\n", " },\n", " {\n", " \"identifier\": \"suburb\",\n", " \"format\": {\n", " \"type\": \"string\",\n", " \"encoding\": \"utf-8\"\n", " },\n", " \"hashing\": {\n", " \"strategy\": {\n", " \"bitsPerToken\": 15\n", " },\n", " \"hash\": {\n", " \"type\": \"doubleHash\"\n", " },\n", " \"comparison\": {\n", " \"type\": \"ngram\",\n", " \"n\": 2,\n", " \"positional\": false\n", " }\n", " }\n", " },\n", " {\n", " \"identifier\": \"postcode\",\n", " \"format\": {\n", " \"type\": \"integer\",\n", " \"minimum\": 100,\n", " \"maximum\": 9999\n", " },\n", " \"hashing\": {\n", " \"strategy\": {\n", " \"bitsPerToken\": 15\n", " },\n", " \"hash\": {\n", " \"type\": \"doubleHash\"\n", " },\n", " \"comparison\": {\n", " \"type\": \"ngram\",\n", " \"n\": 1,\n", " \"positional\": true\n", " }\n", " }\n", " },\n", " {\n", " \"identifier\": \"state\",\n", " \"format\": {\n", " \"type\": \"string\",\n", " \"encoding\": \"utf-8\",\n", " \"maxLength\": 3\n", " },\n", " \"hashing\": {\n", " \"strategy\": {\n", " \"bitsPerToken\": 30\n", " },\n", " \"hash\": {\n", " \"type\": \"doubleHash\"\n", " },\n", " \"comparison\": {\n", " \"type\": \"ngram\",\n", " \"n\": 2,\n", " \"positional\": false\n", " }\n", " }\n", " },\n", " {\n", " \"identifier\": \"date_of_birth\",\n", " \"format\": {\n", " \"type\": \"integer\"\n", " },\n", " \"hashing\": {\n", " \"missingValue\": {\n", " \"sentinel\": \"\"\n", " },\n", " \"strategy\": {\n", " \"bitsPerToken\": 30\n", " },\n", " \"hash\": {\n", " \"type\": \"doubleHash\"\n", " },\n", " \"comparison\": {\n", " \"type\": \"ngram\",\n", " \"n\": 1,\n", " \"positional\": true\n", " }\n", " }\n", " },\n", " {\n", " \"identifier\": \"soc_sec_id\",\n", " \"ignored\": true\n", " }\n", " ]\n", "}" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "## Create Linkage Project\n", "\n", "The analyst carrying out the linkage starts by creating a linkage project of the desired output type with the Entity Service.\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Credentials will be saved in /tmp/tmp_d0pcu7x\n", "\u001b[31mProject created\u001b[0m\n" ] }, { "data": { "text/plain": [ "{'project_id': 'd9ffdb48df4cc0acb4f0ab29f56be0873dff50f95ba15ada',\n", " 'result_token': '030796ecdf1fdf600f6751ca2bd2aee98c360aafcea56934',\n", " 'update_tokens': ['4b138f6464315179e08e3d08e403b1da0be27ab3e478ece4',\n", " '61c9e2ddd1a053c99af4f5c09e224a43723a4dfd9dceafd7']}" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "creds = NamedTemporaryFile('wt')\n", "print(\"Credentials will be saved in\", creds.name)\n", "\n", "!anonlink create-project \\\n", " --schema \"{schema.name}\" \\\n", " --output \"{creds.name}\" \\\n", " --type \"permutations\" \\\n", " --server \"{url}\"\n", "\n", "creds.seek(0)\n", "\n", "import json\n", "with open(creds.name, 'r') as f:\n", " credentials = json.load(f)\n", "\n", "project_id = credentials['project_id']\n", "credentials" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "**Note:** the analyst will need to pass on the `project_id` (the id of the linkage project) and one of the two `update_tokens` to each data provider.\n", "\n", "## Hash and Upload\n", "\n", "At the moment both data providers have *raw* personally identiy information. We first have to generate CLKs from the raw entity information. We need:\n", "- *anonlink-client* provides a command line encoding tool.\n", "- the linkage schema from above\n", "- and a secret which is only known to Alice and Bob. (here: `my_secret`)\n", "\n", "Full command line documentation can be fournd [here](https://anonlink-client.readthedocs.io/en/latest/cli.html), see [clkhash documentation](https://clkhash.readthedocs.io/) for further details on the encoding itself." ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\u001b[31mCLK data written to /tmp/tmpgso1v_7b.json\u001b[0m\n", "\u001b[31mCLK data written to /tmp/tmpamtsmico.json\u001b[0m\n" ] } ], "source": [ "!anonlink hash \"{a_csv.name}\" my_secret \"{schema.name}\" \"{a_clks.name}\"\n", "!anonlink hash \"{b_csv.name}\" my_secret \"{schema.name}\" \"{b_clks.name}\"" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "Now the two clients can upload their data providing the appropriate *upload tokens* and the *project_id*. As with all commands in `anonlink` we can output help:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Usage: anonlink upload [OPTIONS] CLK_JSON\r\n", "\r\n", " Upload CLK data to entity matching server.\r\n", "\r\n", " Given a json file containing hashed clk data as CLK_JSON, upload to the\r\n", " entity resolution service.\r\n", "\r\n", " Use \"-\" to read from stdin.\r\n", "\r\n", "Options:\r\n", " --project TEXT Project identifier\r\n", " --apikey TEXT Authentication API key for the server.\r\n", " -o, --output FILENAME\r\n", " --blocks FILENAME Generated blocks JSON file\r\n", " --server TEXT Server address including protocol. Default\r\n", " https://anonlink.easd.data61.xyz.\r\n", "\r\n", " --retry-multiplier INTEGER If receives a 503 from\r\n", " server, minimum waiting time before\r\n", " retrying. Default 100.\r\n", "\r\n", " --retry-exponential-max INTEGER\r\n", " If receives a 503 from\r\n", " server, maximum time interval between\r\n", " retries. Default 10000.\r\n", "\r\n", " --retry-max-time INTEGER If receives a 503 from\r\n", " server, retry only within this period.\r\n", " Default 20000.\r\n", "\r\n", " -v, --verbose Script is more talkative\r\n", " --help Show this message and exit.\r\n" ] } ], "source": [ "!anonlink upload --help" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "### Alice uploads her data" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [], "source": [ "with NamedTemporaryFile('wt') as f:\n", " !anonlink upload \\\n", " --project=\"{project_id}\" \\\n", " --apikey=\"{credentials['update_tokens'][0]}\" \\\n", " --server \"{url}\" \\\n", " --output \"{f.name}\" \\\n", " \"{a_clks.name}\"\n", " res = json.load(open(f.name))\n", " alice_receipt_token = res['receipt_token']" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "Every upload gets a receipt token. This token is required to access the results." ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "### Bob uploads his data" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [], "source": [ "with NamedTemporaryFile('wt') as f:\n", " !anonlink upload \\\n", " --project=\"{project_id}\" \\\n", " --apikey=\"{credentials['update_tokens'][1]}\" \\\n", " --server \"{url}\" \\\n", " --output \"{f.name}\" \\\n", " \"{b_clks.name}\"\n", " \n", " bob_receipt_token = json.load(open(f.name))['receipt_token']" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "## Create a run\n", "\n", "Now the project has been created and the CLK data has been uploaded we can carry out some privacy preserving record linkage. Try with a few different threshold values:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [], "source": [ "with NamedTemporaryFile('wt') as f:\n", " !anonlink create \\\n", " --project=\"{project_id}\" \\\n", " --apikey=\"{credentials['result_token']}\" \\\n", " --server \"{url}\" \\\n", " --threshold 0.85 \\\n", " --output \"{f.name}\"\n", " \n", " run_id = json.load(open(f.name))['run_id']" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "## Results\n", "\n", "Now after some delay (depending on the size) we can fetch the mask.\n", "Results can be fetched with the `anonlink` command line tool:\n", "\n", " !anonlink results --server \"{url}\" \\\n", " --project=\"{credentials['project_id']}\" \\\n", " --apikey=\"{credentials['result_token']}\" --output results.txt\n", " \n", "However for this tutorial we are going to wait for the run to complete using the `anonlinkclient.rest_client` then pull the raw results using the `requests` library:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [], "source": [ "import requests\n", "from anonlinkclient.rest_client import RestClient\n", "from anonlinkclient.rest_client import format_run_status\n", "\n", "from IPython.display import clear_output" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "State: completed\n", "Stage (3/3): compute output\n" ] } ], "source": [ "rest_client = RestClient(url)\n", "for update in rest_client.watch_run_status(project_id, run_id, credentials['result_token'], timeout=300):\n", " clear_output(wait=True)\n", " print(format_run_status(update))" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [], "source": [ "results = requests.get('{}/api/v1/projects/{}/runs/{}/result'.format(url, project_id, run_id), headers={'Authorization': credentials['result_token']}).json()" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [], "source": [ "mask = results['mask']" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "This mask is a boolean array that specifies where rows of permuted data line up." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n" ] } ], "source": [ "print(mask[:10])" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "The number of 1s in the mask will tell us how many matches were found." ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "data": { "text/plain": [ "4851" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum([1 for m in mask if m == 1])" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "We also use `requests` to fetch the permutations for each data provider:" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [], "source": [ "alice_res = requests.get('{}/api/v1/projects/{}/runs/{}/result'.format(url, project_id, run_id), headers={'Authorization': alice_receipt_token}).json()\n", "bob_res = requests.get('{}/api/v1/projects/{}/runs/{}/result'.format(url, project_id, run_id), headers={'Authorization': bob_receipt_token}).json()" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "Now Alice and Bob both have a new permutation - a new ordering for their data." ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "data": { "text/plain": [ "[1525, 1775, 4695, 1669, 1816, 2778, 1025, 2069, 4358, 4217]" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alice_permutation = alice_res['permutation']\n", "alice_permutation[:10]" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "This permutation says the first row of Alice's data should be moved to position 308." ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "data": { "text/plain": [ "[2882, 3332, 3654, 300, 1949, 765, 4356, 1049, 2325, 4964]" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bob_permutation = bob_res['permutation']\n", "bob_permutation[:10]" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [], "source": [ "def reorder(items, order):\n", " \"\"\"\n", " Assume order is a list of new index\n", " \"\"\"\n", " neworder = items.copy()\n", " for item, newpos in zip(items, order):\n", " neworder[newpos] = item\n", " \n", " return neworder" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [], "source": [ "with open(a_csv.name, 'r') as f:\n", " alice_raw = f.readlines()[1:]\n", " alice_reordered = reorder(alice_raw, alice_permutation)\n", "\n", "with open(b_csv.name, 'r') as f:\n", " bob_raw = f.readlines()[1:]\n", " bob_reordered = reorder(bob_raw, bob_permutation)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "Now that the two data sets have been permuted, the mask reveals where the rows line up, and where they don't." ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "data": { "text/plain": [ "['rec-1977-org,aidan,morrison,2,broadsmith street,,cloverdale,2787,act,19140202,8821751\\n',\n", " 'rec-51-org,ella,blunden,37,freda gibson circuit,croyde,paddington,2770,sa,19401209,3593307\\n',\n", " 'rec-1151-org,courtney,gilbertson,35,maccallum circuit,barley hill,granville,2646,qld,19910105,5257049\\n',\n", " 'rec-2037-org,freya,mason,10,barnett close,dianella masonic village (cnr cornwell s,clifton springs,7301,wa,19241109,1571902\\n',\n", " 'rec-903-org,brianna,barisic,1502,haddon street,parish talowahl,launching place,3220,vic,19750703,5367822\\n',\n", " 'rec-2883-org,jackson,clarke,1,cargelligo street,summerset,bellevue hill,3835,qld,19571105,7943648\\n',\n", " 'rec-2856-org,chloe,setlhong,4,nunki place,yacklin,cronulla,6164,act,19950628,2829638\\n',\n", " 'rec-4831-org,caleb,thorpe,4,river street,,granville,2641,nsw,19590118,7916934\\n',\n", " 'rec-317-org,amber,nicolakopoulos,38,atkinson street,mount patrick,edgewater,2905,sa,19910707,9220881\\n',\n", " 'rec-2685-org,joel,lodge,200,steinwedel street,kmart p plaza,toowoomba,4012,wa,19710830,2655513\\n']" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alice_reordered[:10]" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "data": { "text/plain": [ "['rec-1977-dup-0,aidan,morrison,2,broadsmit hstreet,,clovedale,2787,act,19140202,8821751\\n',\n", " 'rec-51-dup-0,adam,,37,freda gibson circuit,cryode,paddington,2770,sa,19401209,3593307\\n',\n", " 'rec-1151-dup-0,courtney,dabinet,240,feathertopstreet,barley hill,tardun,2646,qld,19910105,5257049\\n',\n", " 'rec-2037-dup-0,beth,maso,10,barnett close,dianella masonic vlilage (cnr cornwell s,clifton springs,7320,wa,19241109,1571902\\n',\n", " 'rec-903-dup-0,barisic,brianna,1502,haddon street,parish talowahl,launching place,3220,vic,19750703,5367822\\n',\n", " 'rec-2883-dup-0,jackon,clareke,1,cargelligo street,summerset,bellevueh ill,3835,qdl,19571105,7943648\\n',\n", " 'rec-2856-dup-0,chloe,setlhong,4,nunki place,yacklin,cronulla,6614,act,19950628,2829638\\n',\n", " 'rec-4831-dup-0,cleb,thorpe,4,river street,,granville,2641,nsw,19590118,7916134\\n',\n", " 'rec-317-dup-0,amber,nicolakopoulos,38,atkinson street,mount patrick,edgewter,2905,sa,19910707,9220881\\n',\n", " 'rec-2685-dup-0,joe,lodgw,200,steinwedel street,kmart p plaza,toowoomba,4016,wa,19710830,2655513\\n']" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bob_reordered[:10]" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "## Accuracy\n", "\n", "To compute how well the matching went we will use the first index as our reference.\n", "\n", "For example in `rec-1396-org` is the original record which has a match in `rec-1396-dup-0`. To satisfy ourselves we can preview the first few supposed matches:" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Aidan Morrison (rec-1977-org) =? Aidan Morrison (rec-1977-dup-0)\n", "Ella Blunden (rec-51-org) =? Adam (rec-51-dup-0)\n", "Courtney Gilbertson (rec-1151-org) =? Courtney Dabinet (rec-1151-dup-0)\n", "Freya Mason (rec-2037-org) =? Beth Maso (rec-2037-dup-0)\n", "Brianna Barisic (rec-903-org) =? Barisic Brianna (rec-903-dup-0)\n", "Jackson Clarke (rec-2883-org) =? Jackon Clareke (rec-2883-dup-0)\n", "Chloe Setlhong (rec-2856-org) =? Chloe Setlhong (rec-2856-dup-0)\n", "Caleb Thorpe (rec-4831-org) =? Cleb Thorpe (rec-4831-dup-0)\n", "Amber Nicolakopoulos (rec-317-org) =? Amber Nicolakopoulos (rec-317-dup-0)\n", "Joel Lodge (rec-2685-org) =? Joe Lodgw (rec-2685-dup-0)\n" ] } ], "source": [ "for i, m in enumerate(mask[:10]):\n", " if m:\n", " entity_a = alice_reordered[i].split(',')\n", " entity_b = bob_reordered[i].split(',')\n", " name_a = ' '.join(entity_a[1:3]).title()\n", " name_b = ' '.join(entity_b[1:3]).title()\n", " \n", " print(\"{} ({})\".format(name_a, entity_a[0]), '=?', \"{} ({})\".format(name_b, entity_b[0]))" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "### Metrics\n", "If you know the ground truth — the correct mapping between the two datasets — you can compute performance metrics of the linkage.\n", "\n", "**Precision**: The percentage of actual matches out of all found matches. (`tp/(tp+fp)`)\n", "\n", "**Recall**: How many of the actual matches have we found? (`tp/(tp+fn)`)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found 4851 correct matches out of 5000. Incorrectly linked 0 matches.\n", "Precision: 100.0%\n", "Recall: 97.0%\n" ] } ], "source": [ "tp = 0\n", "fp = 0\n", "\n", "for i, m in enumerate(mask):\n", " if m:\n", " entity_a = alice_reordered[i].split(',')\n", " entity_b = bob_reordered[i].split(',')\n", " if entity_a[0].split('-')[1] == entity_b[0].split('-')[1]:\n", " tp += 1\n", " else:\n", " fp += 1\n", " #print('False positive:',' '.join(entity_a[1:3]).title(), '?', ' '.join(entity_b[1:3]).title(), entity_a[-1] == entity_b[-1])\n", "\n", "print(\"Found {} correct matches out of 5000. Incorrectly linked {} matches.\".format(tp, fp))\n", "precision = tp/(tp+fp)\n", "recall = tp/5000\n", "\n", "print(\"Precision: {:.1f}%\".format(100*precision))\n", "print(\"Recall: {:.1f}%\".format(100*recall))" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\u001b[31mProject deleted\u001b[0m\r\n" ] } ], "source": [ "# Deleting the project\n", "!anonlink delete-project \\\n", " --project=\"{credentials['project_id']}\" \\\n", " --apikey=\"{credentials['result_token']}\" \\\n", " --server=\"{url}\"" ] } ], "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.8.0" }, "pycharm": { "stem_cell": { "cell_type": "raw", "metadata": { "collapsed": false }, "source": [] } } }, "nbformat": 4, "nbformat_minor": 4 }