Spaces:
Running
Running
File size: 10,588 Bytes
46e0dd0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 |
{
"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
}
|