{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "e30bf074", "metadata": { "ExecuteTime": { "end_time": "2023-06-14T17:16:17.863326Z", "start_time": "2023-06-14T17:16:17.806871Z" } }, "outputs": [], "source": [ "import json\n", "import jellyfish\n", "import nltk\n", "import statistics\n", "from collections import Counter\n", "from tqdm import tqdm" ] }, { "cell_type": "markdown", "id": "711902a2", "metadata": {}, "source": [ "# Load KWX" ] }, { "cell_type": "code", "execution_count": null, "id": "2bba73c8", "metadata": { "ExecuteTime": { "end_time": "2023-06-14T17:12:46.170356Z", "start_time": "2023-06-14T17:12:44.665181Z" } }, "outputs": [], "source": [ "kwx = json.load(open('./data.json','r'))\n", "train_size = 16000" ] }, { "cell_type": "markdown", "id": "ed39b665", "metadata": {}, "source": [ "# Metrics" ] }, { "cell_type": "code", "execution_count": null, "id": "b7df88f3", "metadata": { "ExecuteTime": { "end_time": "2023-06-14T17:19:12.956834Z", "start_time": "2023-06-14T17:19:12.949734Z" } }, "outputs": [], "source": [ "def compare_two_words(w1,w2):\n", " return jellyfish.jaro_distance(w1, w2)\n", "\n", "def is_related_in_list(word,ys):\n", " for y in ys:\n", " if compare_two_words(word.lower(),y.lower()) >= 0.9:\n", " return True\n", " return False \n", "\n", "def kws_precision(ys,ys_true):\n", " if len(ys) >= 1:\n", " count = 0 \n", " for y in ys:\n", " if is_related_in_list(y,ys_true):\n", " count += 1\n", " return count/len(ys)\n", " else:\n", " return 0\n", "\n", "def kws_recall(ys,ys_true):\n", " if not ys_true:\n", " return 0\n", " if len(ys) >= 1:\n", " count = 0 \n", " for y in ys:\n", " if is_related_in_list(y,ys_true):\n", " count += 1\n", " if count > len(ys_true):\n", " return 1\n", " return count/len(ys_true)\n", " else:\n", " return 0 \n", " \n", "def evaluate_kws(ys,ys_true):\n", " res = {}\n", " res['precision'] = kws_precision(ys,ys_true)\n", " res['recall'] = kws_recall(ys,ys_true)\n", " if res['precision'] or res['recall']:\n", " res['f1'] = (2*res['precision']*res['recall'])/(res['precision']+res['recall'])\n", " else:\n", " res['f1'] = 0\n", " return res \n", "\n", "\n", "def macro_pr(yt_pairs):\n", " f1 = []\n", " p = []\n", " r = []\n", " for pair in yt_pairs:\n", " evaluate = evaluate_kws(pair[0],pair[1])\n", " f1.append(evaluate['f1'])\n", " p.append(evaluate['precision'])\n", " r.append(evaluate['recall'])\n", " return {'f1':statistics.mean(f1),\n", " 'precision':statistics.mean(p),\n", " 'recall':statistics.mean(r)}\n", "\n", "def evaluate_extractor(docs_with_kws, extractor, top=None):\n", " yt_pairs = []\n", " for i in tqdm(list(docs_with_kws.keys())[train_size:]):\n", " pair = []\n", " pair.append(extractor(docs_with_kws[i]['abstract'],top))\n", " ys_true = docs_with_kws[i]['keywords']\n", " if 'keywords_extra' in docs_with_kws[i]:\n", " ys_true += docs_with_kws[i]['keywords_extra']\n", " pair.append(ys_true)\n", " yt_pairs.append(pair)\n", " print(len(yt_pairs))\n", " print(macro_pr(yt_pairs))" ] }, { "cell_type": "markdown", "id": "949cd440", "metadata": {}, "source": [ "# Keyword Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "30cd3512", "metadata": { "ExecuteTime": { "end_time": "2023-06-14T17:12:51.826420Z", "start_time": "2023-06-14T17:12:51.821688Z" } }, "outputs": [], "source": [ "kw_start = [\n", " 'NN',\n", " 'NNP',\n", " 'JJ',\n", " 'NNS',\n", " 'VBG',\n", " 'RB',\n", " 'VBN'\n", "]\n", "\n", "kw_end = [\n", " 'NN',\n", " 'NNP',\n", " 'NNS',\n", " 'VBG',\n", " 'JJ'\n", "]\n", "\n", "kw_split = [\n", " '.',\n", " ','\n", "]\n", "def keywords_selector(text):\n", " tokens = nltk.word_tokenize(text)\n", " tags = nltk.pos_tag(tokens)\n", " res = set()\n", " for i in range(len(tags)):\n", " if tags[i][1] in kw_start:\n", " end = i+4 if i+4 <= len(tags) - 1 else len(tags) - 1\n", " cut = tags[i:end]\n", " for j in range(len(cut)):\n", " if cut[j][0] in kw_split:\n", " cut = cut[:j]\n", " break \n", " for k in range(len(cut)):\n", " if cut[k][1] in kw_end:\n", " res.add(' '.join([m[0] for m in cut][:k+1]))\n", " return res \n", " " ] }, { "cell_type": "code", "execution_count": null, "id": "00bf7e61", "metadata": { "ExecuteTime": { "end_time": "2023-06-14T17:14:54.344161Z", "start_time": "2023-06-14T17:13:30.555540Z" } }, "outputs": [], "source": [ "# scoreboard to record all combinations.\n", "history_score = {}\n", "# global dictionary to record all links between present and absent keywords\n", "global_kwx_index = {}\n", "for i in tqdm(list(kwx.keys())[:train_size]):\n", " ys = kwx[i]['keywords']\n", " candidates = keywords_selector(kwx[i]['abstract'])\n", " for c in candidates:\n", " if not c in history_score:\n", " history_score[c] = 0\n", " if is_related_in_list(c,ys):\n", " history_score[c] += 100\n", " else:\n", " history_score[c] -= 1\n", " for y in ys:\n", " if y in global_kwx_index:\n", " global_kwx_index[y].update(ys)\n", " else:\n", " global_kwx_index[y] = Counter(ys)\n", "print(len(history_score))" ] }, { "cell_type": "code", "execution_count": null, "id": "cf0bc909", "metadata": { "ExecuteTime": { "end_time": "2023-06-14T17:20:03.965152Z", "start_time": "2023-06-14T17:20:03.960665Z" } }, "outputs": [], "source": [ "def kwx_kws(text,top=None):\n", " res = []\n", " score = []\n", " candidates = keywords_selector(text)\n", " for c in candidates:\n", " if c not in history_score:\n", " res.append(c)\n", " score.append(1)\n", " elif history_score[c]>0:\n", " res.append(c)\n", " score.append(history_score[c])\n", " if c in global_kwx_index:\n", " for r in global_kwx_index[c]:\n", " if r not in candidates:\n", " res.append(r)\n", " score.append(global_kwx_index[c][r])\n", " if not res:\n", " res = ['None']\n", " sorted_res = [x for _, x in sorted(zip(score, res))][::-1]\n", " if top and len(sorted_res)>top:\n", " return sorted_res[:top]\n", " else:\n", " return sorted_res" ] }, { "cell_type": "code", "execution_count": null, "id": "86f377c6", "metadata": { "ExecuteTime": { "end_time": "2023-06-14T17:17:18.438467Z", "start_time": "2023-06-14T17:16:21.507730Z" } }, "outputs": [], "source": [ "evaluate_extractor(kwx, kwx_kws)" ] }, { "cell_type": "code", "execution_count": null, "id": "cdfec2e8", "metadata": { "ExecuteTime": { "end_time": "2023-06-14T17:20:24.682626Z", "start_time": "2023-06-14T17:20:06.517802Z" } }, "outputs": [], "source": [ "evaluate_extractor(kwx, kwx_kws, 10)" ] } ], "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.12" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 5 }