{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "import sys\n", "from transformers import BertTokenizer\n", "from transformers.models.bert.modeling_bert import BertForMaskedLM\n", "import torch\n", "from WHGDataset import WHGDataset\n", "\n", "sys.path.append(\"../\")\n", "from datasets.usgs_os_sample_loader import USGS_MapDataset\n", "from datasets.wikidata_sample_loader import Wikidata_Geocoord_Dataset, Wikidata_Random_Dataset\n", "from models.spatial_bert_model import SpatialBertModel\n", "from models.spatial_bert_model import SpatialBertConfig\n", "from models.spatial_bert_model import SpatialBertForMaskedLM\n", "from utils.find_closest import find_ref_closest_match, sort_ref_closest_match\n", "from utils.common_utils import load_spatial_bert_pretrained_weights, get_spatialbert_embedding, get_bert_embedding, write_to_csv\n", "from utils.baseline_utils import get_baseline_model\n", "\n", "\n", "# load our spabert model\n", "device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n", "tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n", " \n", "config = SpatialBertConfig()\n", "model = SpatialBertModel(config)\n", "\n", "model.to(device)\n", "model.eval()\n", "\n", "# load pretrained weights\n", "pre_trained_model=torch.load('tutorial_datasets/fine-spabert-base-uncased-finetuned-osm-mn.pth')\n", "cnt_layers = 0\n", "model_keys = model.state_dict()\n", "for key in model_keys:\n", " if 'bert.'+ key in pre_trained_model:\n", " model_keys[key] = pre_trained_model[\"bert.\"+key]\n", " cnt_layers += 1\n", " else:\n", " print(\"No weight for\", key)\n", "print(cnt_layers, 'layers loaded')\n", "\n", "model.load_state_dict(model_keys)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# load entity-linking datasets\n", "\n", "sep_between_neighbors = False\n", "wikidata_dict_per_map = {}\n", "wikidata_dict_per_map['wikidata_emb_list'] = []\n", "wikidata_dict_per_map['wikidata_qid_list'] = []\n", "wikidata_dict_per_map['names'] = []\n", "\n", "\n", "whg_dataset = WHGDataset(\n", " data_file_path = 'tutorial_datasets/spabert_whg_wikidata.json',\n", " tokenizer = tokenizer,\n", " max_token_len = 512, \n", " distance_norm_factor = 25, \n", " spatial_dist_fill=100,\n", " sep_between_neighbors = sep_between_neighbors)\n", "\n", "wikidata_dataset = WHGDataset(\n", " data_file_path='tutorial_datasets/spabert_wikidata_sampled.json',\n", " tokenizer=tokenizer,\n", " max_token_len=512,\n", " distance_norm_factor=50000,\n", " spatial_dist_fill=20,\n", " sep_between_neighbors=sep_between_neighbors)\n", "\n", "\n", "matched_wikid_dataset = []\n", "for i in range(len(wikidata_dataset)):\n", " emb = wikidata_dataset[i]\n", " matched_wikid_dataset.append(emb)\n", " max_dist_lng = max(emb['norm_lng_list'])\n", " max_dist_lat = max(emb['norm_lat_list'])\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import sys\n", "sys.path.append('../')\n", "from experiments.entity_matching.data_processing import request_wrapper\n", "import scipy.spatial as sp\n", "import numpy as np\n", "## ENTITY LINKING ##\n", "\n", "\n", "# disambigufy\n", "def disambiguify(model, model_name, usgs_dataset, wikidata_dict_list, candset_mode = 'all_map', if_use_distance = True, select_indices = None): \n", "\n", " if select_indices is None: \n", " select_indices = range(0, len(wikidata_dict_list))\n", "\n", "\n", " assert(candset_mode in ['all_map','per_map'])\n", " wikidata_emb_list = wikidata_dict_list['wikidata_emb_list']\n", " wikidata_qid_list = wikidata_dict_list['wikidata_qid_list'] \n", " ret_list = []\n", " for i in range(len(usgs_dataset)):\n", " if (i % 1000) == 0:\n", " print(\"disambigufy at \" + str((i/len(usgs_dataset))*100)+\"%\")\n", " if model_name == 'spatial_bert-base' or model_name == 'spatial_bert-large':\n", " usgs_emb = get_spatialbert_embedding(usgs_dataset[i], model, use_distance = if_use_distance)\n", " else:\n", " usgs_emb = get_bert_embedding(usgs_dataset[i], model)\n", " sim_matrix = 1 - sp.distance.cdist(np.array(wikidata_emb_list), np.array([usgs_emb]), 'cosine')\n", " closest_match_qid = sort_ref_closest_match(sim_matrix, wikidata_qid_list)\n", " #print(closest_match_qid)\n", " \n", " sorted_sim_matrix = np.sort(sim_matrix, axis = 0)[::-1] # descending order\n", "\n", " ret_dict = dict()\n", " ret_dict['pivot_name'] = usgs_dataset[i]['pivot_name']\n", "\n", " ret_dict['sorted_match_qid'] = [a[0] for a in closest_match_qid]\n", " ret_dict['sorted_sim_matrix'] = [a[0] for a in sorted_sim_matrix]\n", "\n", " ret_list.append(ret_dict)\n", "\n", " return ret_list \n", "\n", "\n", "candset_mode = 'all_map'\n", "for i in range(0, len(matched_wikid_dataset)):\n", " if (i % 1000) == 0:\n", " print(\"processing at: \"+ str(i/len(matched_wikid_dataset)*100) + \"%\")\n", " #print(matched_wikid_dataset[i])\n", " entity = matched_wikid_dataset[i]\n", " wikidata_emb = get_spatialbert_embedding(matched_wikid_dataset[i], model)\n", " wikidata_dict_per_map['wikidata_emb_list'].append(wikidata_emb)\n", " wikidata_dict_per_map['wikidata_qid_list'].append(matched_wikid_dataset[i]['qid'])\n", " wikidata_dict_per_map['names'].append(wikidata_dataset[i]['pivot_name'])\n", "\n", "ret_list = disambiguify(model, 'spatial_bert-base', whg_dataset, wikidata_dict_per_map, candset_mode= candset_mode, if_use_distance = not False, select_indices = None)\n", "write_to_csv('tutorial_datasets/', \"output.csv\", ret_list)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Evaluate entity linking\n", "import os\n", "import pandas as pd\n", "import json\n", "\n", "# define the ground truth directory for evaluation\n", "gt_dir = os.path.abspath(\"tutorial_datasets/spabert_wikidata_sampled.json\")\n", "\n", "\n", "# define the file where we wrote out predictions\n", "prediction_path = os.path.abspath('tutorial_datasets/output.csv.json')\n", "\n", "\n", "# define ground truth dictionary\n", "gt_dict = dict()\n", "\n", "with open(gt_dir) as f:\n", " data = f.readlines()\n", " for line in data:\n", " d = json.loads(line)\n", " gt_dict[d['info']['name']] = d['info']['qid']\n", "\n", "\n", "\n", "rank_list = []\n", "hits_at_1 = 0\n", "hits_at_5 = 0\n", "hits_at_10 = 0\n", "out_dict = {'title':[],'rank':[]}\n", "\n", "with open(prediction_path) as f:\n", " data = f.readlines()\n", " for line in data:\n", " pred_dict = json.loads(line)\n", " pivot_name = pred_dict['pivot_name']\n", " sorted_matched_uri = pred_dict['sorted_match_qid']\n", " sorted_sim_matrix = pred_dict['sorted_sim_matrix']\n", " if pivot_name in gt_dict:\n", " gt_uri = gt_dict[pivot_name]\n", " rank = sorted_matched_uri.index(gt_uri) +1\n", " if rank == 1:\n", " hits_at_1 += 1\n", " if rank <= 5:\n", " hits_at_5 += 1\n", " if rank <= 10:\n", " hits_at_10 +=1\n", " rank_list.append(rank)\n", " out_dict['title'].append(pivot_name)\n", " out_dict['rank'].append(rank)\n", "\n", "hits_at_1 = hits_at_1/len(rank_list)\n", "hits_at_5 = hits_at_5/len(rank_list)\n", "hits_at_10 = hits_at_10/len(rank_list)\n", "\n", "print(hits_at_1)\n", "print(hits_at_5)\n", "print(hits_at_10)\n", "\n", "out_df = pd.DataFrame(out_dict)\n", "out_df\n", " \n", "\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "Mean Reciprocal Rank is a statistical measure for evaluating processes that produce a list of possible responses of a query in order of probability of correctness.\n", "\n", "First we obtain the rank from the ranked list shown above.\n", "\n", "Next we calculate the reciprocal rank for each rank. The reciprocal is the inverse of the rank. So for a rank of 1 the recprocal rank would be 1/1, for a rank of 2 the reciprocal rank would be 1/2.\n", "\n", "The mean reciprocal rank is the average of the reciprocal ranks. \n", "\n", "This measure gives us a general conceptualization of how well our model predicts entities based on their embeddings.\n", "\n", "An in-depth description of Mean Reciprocal Rank can be found here https://en.wikipedia.org/wiki/Mean_reciprocal_rank\n", "\n", "An import thing to keep in mind when caclulating mean reciprocal rank is that it tends to inversely scale with your candidate set size\n", "\n", "Our candidate set is has a length of 4624 " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# calculating the mean reciprocal rank (MRR)\n", "import numpy as np\n", "\n", "reciprocal_list = [1./rank for rank in rank_list]\n", "\n", "MRR = np.mean(reciprocal_list)\n", "\n", "print(MRR)\n" ] } ], "metadata": { "kernelspec": { "display_name": "ucgis23workshop", "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.11.3" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }