├── __init__.py ├── label_bot ├── __init__.py ├── preprocessing.py ├── paraphrase_detector.py ├── models.py └── utils.py ├── fetch_models.sh ├── token.json ├── .gitignore ├── labels.json ├── Pipfile ├── setup.py ├── notebooks ├── finetune language model.ipynb ├── finetune classifier.ipynb ├── prepare dataset.ipynb ├── label_mapping.ipynb └── train_custom_head.ipynb ├── requirements.txt ├── app.py ├── README.md └── LICENSE /__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /label_bot/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /fetch_models.sh: -------------------------------------------------------------------------------- 1 | wget -c http://cs-people.bu.edu/giorgos/labelbot/models.tar.gz -O - | tar -xz -C label_bot/ -------------------------------------------------------------------------------- /token.json: -------------------------------------------------------------------------------- 1 | { 2 | "FILE DESCRIPTION" : "USE THIS FILE TO SAVE YOUR PERSONAL ACCESS TOKEN. MAKE SURE THAT YOU DON'T SHARE YOUR TOKEN AND THIS FILE WITH ANYONE!", 3 | 4 | "token" : "" 5 | } 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .ipynb_checkpoints 2 | *.gif 3 | wandb/ 4 | label_bot/extra_data/ 5 | token_private.json 6 | *.pkl 7 | label_bot/models/ 8 | *.tar.gz 9 | *.DS_Store 10 | *.png 11 | *.bin 12 | __pycache__ 13 | -------------------------------------------------------------------------------- /labels.json: -------------------------------------------------------------------------------- 1 | { 2 | "FILE DESCRIPTION" : "DEFINE YOUR PREFFERRED TARGET LABELS, AS WELL AS POSSIBLE ALIASES, USING THE FORMAT 'ALIAS : LABEL'. ", 3 | 4 | "bug" : "bug", 5 | "question" : "question", 6 | "enhancement" : "enhancement", 7 | "feature" : "enhancement" 8 | } 9 | -------------------------------------------------------------------------------- /Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | name = "pypi" 3 | url = "https://pypi.org/simple" 4 | verify_ssl = true 5 | 6 | [dev-packages] 7 | 8 | [packages] 9 | rsa = "==3.4" 10 | wrapt = "==1.11.1" 11 | matplotlib = "==3.3.0" 12 | numba = "==0.50.1" 13 | scipy = "==1.5.2" 14 | uuid = "==1.30" 15 | transformers = "==3.0.2" 16 | simpletransformers = "==0.47.2" 17 | pandas = "==1.0.5" 18 | numpy = "==1.18.5" 19 | torch = "==1.6.0" 20 | tensorboardX = "2.1" 21 | click = "*" 22 | pygithub = "*" 23 | 24 | [requires] 25 | python_version = "3.6" 26 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Github-Issues-Classifier 2 | # Copyright(C) 2020 Georgios (Giorgos) Karantonis 3 | # 4 | # This program is free software: you can redistribute it and / or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | from pathlib import Path 18 | from setuptools import setup, find_packages 19 | 20 | 21 | 22 | def get_install_requires(): 23 | with open("requirements.txt", "r") as requirements_file: 24 | res = requirements_file.readlines() 25 | return [req.split(" ", maxsplit=1)[0].replace(";", "") for req in res if req] 26 | 27 | 28 | 29 | setup( 30 | name="git-label", 31 | entry_points={"console_scripts": ["git-label=app:cli"]}, 32 | long_description=Path("README.md").read_text(), 33 | author="Giorgos Karantonis", 34 | author_email="gkaranto@redhat.com, giorgos@bu.edu", 35 | packages=find_packages(), 36 | install_requires=get_install_requires(), 37 | ) 38 | -------------------------------------------------------------------------------- /notebooks/finetune language model.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 1. Prepare the environment" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import logging\n", 17 | "\n", 18 | "import pandas as pd\n", 19 | "\n", 20 | "from Label_Bot.label_bot import utils\n", 21 | "from simpletransformers.language_modeling import LanguageModelingModel" 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": null, 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "logging.basicConfig(level=logging.INFO)\n", 31 | "transformers_logger = logging.getLogger(\"transformers\")\n", 32 | "transformers_logger.setLevel(logging.WARNING)" 33 | ] 34 | }, 35 | { 36 | "cell_type": "markdown", 37 | "metadata": {}, 38 | "source": [ 39 | "
\n", 40 | "\n", 41 | "# 2. Train and Evaluate" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "metadata": {}, 48 | "outputs": [], 49 | "source": [ 50 | "EPOCHS = 1\n", 51 | "LR = 3e-5\n", 52 | "BATCH_SIZE = 4" 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": null, 58 | "metadata": {}, 59 | "outputs": [], 60 | "source": [ 61 | "model_args = {\n", 62 | " 'show_running_loss' : True, \n", 63 | " \n", 64 | " 'train_batch_size' : BATCH_SIZE, \n", 65 | " 'gradient_accumulation_steps' : 16, \n", 66 | " 'learning_rate' : LR, \n", 67 | " 'num_train_epochs' : EPOCHS, \n", 68 | " \n", 69 | " 'dataset_type': 'simple', \n", 70 | " 'sliding_window' : True, \n", 71 | " 'block_size' : 512, \n", 72 | " 'max_seq_length' : 512, \n", 73 | " \n", 74 | " 'save_steps' : 0, \n", 75 | " 'save_model_every_epoch' : True, \n", 76 | " 'overwrite_output_dir' : True, \n", 77 | " \n", 78 | " 'reprocess_input_data' : True, \n", 79 | " 'evaluate_during_training' : True, \n", 80 | " \n", 81 | " 'process_count' : 1, \n", 82 | " 'n_gpu' : 2\n", 83 | "}" 84 | ] 85 | }, 86 | { 87 | "cell_type": "code", 88 | "execution_count": null, 89 | "metadata": {}, 90 | "outputs": [], 91 | "source": [ 92 | "model = utils.load_model(model_args, task='mlm')" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": null, 98 | "metadata": { 99 | "scrolled": true 100 | }, 101 | "outputs": [], 102 | "source": [ 103 | "model.train_model('test.txt', eval_file='val.txt')" 104 | ] 105 | }, 106 | { 107 | "cell_type": "code", 108 | "execution_count": null, 109 | "metadata": {}, 110 | "outputs": [], 111 | "source": [ 112 | "results = model.eval_model('test.txt')" 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "execution_count": null, 118 | "metadata": {}, 119 | "outputs": [], 120 | "source": [ 121 | "results" 122 | ] 123 | }, 124 | { 125 | "cell_type": "code", 126 | "execution_count": null, 127 | "metadata": {}, 128 | "outputs": [], 129 | "source": [] 130 | } 131 | ], 132 | "metadata": { 133 | "kernelspec": { 134 | "display_name": "Python 3", 135 | "language": "python", 136 | "name": "python3" 137 | }, 138 | "language_info": { 139 | "codemirror_mode": { 140 | "name": "ipython", 141 | "version": 3 142 | }, 143 | "file_extension": ".py", 144 | "mimetype": "text/x-python", 145 | "name": "python", 146 | "nbconvert_exporter": "python", 147 | "pygments_lexer": "ipython3", 148 | "version": "3.6.9" 149 | } 150 | }, 151 | "nbformat": 4, 152 | "nbformat_minor": 2 153 | } 154 | -------------------------------------------------------------------------------- /notebooks/finetune classifier.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 1. Prepare the environment" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import numpy as np\n", 17 | "import pandas as pd\n", 18 | "\n", 19 | "from Label_Bot.label_bot import utils" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "## 1.1. Load the data" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": null, 32 | "metadata": {}, 33 | "outputs": [], 34 | "source": [ 35 | "base_url = './'\n", 36 | "file_type = '90k'\n", 37 | "\n", 38 | "train_url = f'{base_url}train_{file_type}.pkl'\n", 39 | "val_url = f'{base_url}val_{file_type}.pkl'\n", 40 | "test_url = f'{base_url}test_{file_type}.pkl'" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": null, 46 | "metadata": {}, 47 | "outputs": [], 48 | "source": [ 49 | "train_df = pd.read_pickle(train_url)\n", 50 | "val_df = pd.read_pickle(val_url)\n", 51 | "test_df = pd.read_pickle(test_url)" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": null, 57 | "metadata": {}, 58 | "outputs": [], 59 | "source": [ 60 | "train_df = train_df.rename(columns={'title':'text'})\n", 61 | "train_df['text'] += ' ' + train_df['body']\n", 62 | "train_df = train_df.drop('body', axis=1)\n", 63 | "\n", 64 | "val_df = val_df.rename(columns={'title':'text'})\n", 65 | "val_df['text'] += ' ' + val_df['body']\n", 66 | "val_df = val_df.drop('body', axis=1)\n", 67 | "\n", 68 | "test_df = test_df.rename(columns={'title':'text'})\n", 69 | "test_df['text'] += ' ' + test_df['body']\n", 70 | "test_df = test_df.drop('body', axis=1)" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": null, 76 | "metadata": {}, 77 | "outputs": [], 78 | "source": [ 79 | "train_df = utils.make_st_compatible(train_df)\n", 80 | "val_df = utils.make_st_compatible(val_df)\n", 81 | "test_df = utils.make_st_compatible(test_df)" 82 | ] 83 | }, 84 | { 85 | "cell_type": "markdown", 86 | "metadata": {}, 87 | "source": [ 88 | "
\n", 89 | "\n", 90 | "# 2. Train and Evaluate" 91 | ] 92 | }, 93 | { 94 | "cell_type": "code", 95 | "execution_count": null, 96 | "metadata": {}, 97 | "outputs": [], 98 | "source": [ 99 | "EPOCHS = 3\n", 100 | "LR = 3e-5\n", 101 | "BATCH_SIZE = 2" 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": null, 107 | "metadata": {}, 108 | "outputs": [], 109 | "source": [ 110 | "model_args = {\n", 111 | " 'show_running_loss' : True, \n", 112 | " \n", 113 | " 'train_batch_size':BATCH_SIZE, \n", 114 | " 'gradient_accumulation_steps':16, \n", 115 | " 'learning_rate': LR, \n", 116 | " 'num_train_epochs': EPOCHS, \n", 117 | " \n", 118 | " 'max_seq_length': 512, \n", 119 | " \n", 120 | " 'save_steps': 0, \n", 121 | " 'save_model_every_epoch' : True, \n", 122 | " 'overwrite_output_dir': True, \n", 123 | " \n", 124 | " 'reprocess_input_data': True, \n", 125 | " 'evaluate_during_training': True, \n", 126 | " \n", 127 | " 'process_count' : 1, \n", 128 | " 'n_gpu': 2\n", 129 | "}" 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "execution_count": null, 135 | "metadata": {}, 136 | "outputs": [], 137 | "source": [ 138 | "model = utils.load_model(model_args, task='mlc')" 139 | ] 140 | }, 141 | { 142 | "cell_type": "code", 143 | "execution_count": null, 144 | "metadata": { 145 | "scrolled": true 146 | }, 147 | "outputs": [], 148 | "source": [ 149 | "model.train_model(train_df, eval_df=val_df, multi_label=True)" 150 | ] 151 | }, 152 | { 153 | "cell_type": "code", 154 | "execution_count": null, 155 | "metadata": {}, 156 | "outputs": [], 157 | "source": [ 158 | "result, model_outputs, wrong_predictions = model.eval_model(test_df)" 159 | ] 160 | }, 161 | { 162 | "cell_type": "code", 163 | "execution_count": null, 164 | "metadata": {}, 165 | "outputs": [], 166 | "source": [ 167 | "result" 168 | ] 169 | }, 170 | { 171 | "cell_type": "code", 172 | "execution_count": null, 173 | "metadata": {}, 174 | "outputs": [], 175 | "source": [] 176 | } 177 | ], 178 | "metadata": { 179 | "kernelspec": { 180 | "display_name": "Python 3", 181 | "language": "python", 182 | "name": "python3" 183 | }, 184 | "language_info": { 185 | "codemirror_mode": { 186 | "name": "ipython", 187 | "version": 3 188 | }, 189 | "file_extension": ".py", 190 | "mimetype": "text/x-python", 191 | "name": "python", 192 | "nbconvert_exporter": "python", 193 | "pygments_lexer": "ipython3", 194 | "version": "3.6.9" 195 | } 196 | }, 197 | "nbformat": 4, 198 | "nbformat_minor": 2 199 | } 200 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | altair==4.1.0; python_version >= '3.6' 2 | appnope==0.1.0; sys_platform == 'darwin' and platform_system == 'Darwin' 3 | argon2-cffi==20.1.0 4 | astor==0.8.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' 5 | attrs==19.3.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' 6 | backcall==0.2.0 7 | base58==2.0.1; python_version >= '3.5' 8 | bleach==3.1.5; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4' 9 | blinker==1.4 10 | boto3==1.14.46 11 | botocore==1.17.46 12 | cachetools==4.1.1; python_version ~= '3.5' 13 | certifi==2020.6.20 14 | cffi==1.14.2 15 | chardet==3.0.4 16 | click==7.1.2 17 | configparser==5.0.0; python_version >= '3.6' 18 | cycler==0.10.0 19 | dataclasses==0.7; python_version < '3.7' 20 | decorator==4.4.2 21 | defusedxml==0.6.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4' 22 | deprecated==1.2.10; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' 23 | docker-pycreds==0.4.0 24 | docutils==0.15.2; python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' 25 | entrypoints==0.3; python_version >= '2.7' 26 | enum-compat==0.0.3 27 | filelock==3.0.12 28 | future==0.18.2; python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' 29 | gitdb==4.0.5; python_version >= '3.4' 30 | gitpython==3.1.7; python_version >= '3.4' 31 | gql==0.2.0 32 | graphql-core==1.1 33 | h5py==2.10.0 34 | idna==2.10; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' 35 | importlib-metadata==1.7.0; python_version < '3.8' 36 | ipykernel==5.3.4; python_version >= '3.4' 37 | ipython-genutils==0.2.0 38 | ipython==7.16.1; python_version >= '3.3' 39 | ipywidgets==7.5.1 40 | jedi==0.17.2; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4' 41 | jinja2==2.11.2; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4' 42 | jmespath==0.10.0; python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' 43 | joblib==0.16.0; python_version >= '3.6' 44 | jsonschema==3.2.0 45 | jupyter-client==6.1.6; python_version >= '3.5' 46 | jupyter-core==4.6.3; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4' 47 | keras==2.4.3 48 | kiwisolver==1.2.0; python_version >= '3.6' 49 | llvmlite==0.33.0; python_version >= '3.6' 50 | markupsafe==1.1.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' 51 | matplotlib==3.3.0 52 | mistune==0.8.4 53 | nbconvert==5.6.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4' 54 | nbformat==5.0.7; python_version >= '3.5' 55 | notebook==6.1.3; python_version >= '3.5' 56 | numba==0.50.1 57 | numpy==1.18.5 58 | nvidia-ml-py3==7.352.0 59 | packaging==20.4; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' 60 | pandas==1.0.5 61 | pandocfilters==1.4.2 62 | parso==0.7.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' 63 | pathtools==0.1.2 64 | pexpect==4.8.0; sys_platform != 'win32' 65 | pickleshare==0.7.5 66 | pillow==7.2.0; python_version >= '3.5' 67 | prometheus-client==0.8.0 68 | promise==2.3 69 | prompt-toolkit==3.0.6; python_full_version >= '3.6.1' 70 | protobuf==3.13.0 71 | psutil==5.7.2; python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' 72 | ptyprocess==0.6.0; os_name != 'nt' 73 | pyarrow==1.0.0; python_version >= '3.5' 74 | pyasn1==0.4.8 75 | pycparser==2.20; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' 76 | pydeck==0.4.1 77 | pygithub==1.53 78 | pygments==2.6.1; python_version >= '3.5' 79 | pyjwt==1.7.1 80 | pyparsing==2.4.7; python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' 81 | pyrsistent==0.16.0 82 | python-dateutil==2.8.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' 83 | pytz==2020.1 84 | pyyaml==5.3.1 85 | pyzmq==19.0.2; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' 86 | regex==2020.7.14 87 | requests==2.24.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4' 88 | rsa==3.4 89 | s3transfer==0.3.3 90 | sacremoses==0.0.43 91 | scikit-learn==0.23.2; python_version >= '3.6' 92 | scipy==1.5.2 93 | send2trash==1.5.0 94 | sentencepiece==0.1.91 95 | sentry-sdk==0.16.5 96 | seqeval==0.0.12 97 | shortuuid==1.0.1; python_version >= '3.5' 98 | simpletransformers==0.47.2 99 | six==1.15.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' 100 | smmap==3.0.4; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' 101 | streamlit==0.65.2; python_version >= '3.6' 102 | subprocess32==3.5.4; python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' and python_version < '4' 103 | tensorboardx==2.1 104 | terminado==0.8.3; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' 105 | testpath==0.4.4 106 | threadpoolctl==2.1.0; python_version >= '3.5' 107 | tokenizers==0.8.1rc1 108 | toml==0.10.1 109 | toolz==0.10.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' 110 | torch==1.6.0 111 | tornado==6.0.4; python_version >= '3.5' 112 | tqdm==4.48.2; python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' 113 | traitlets==4.3.3 114 | transformers==3.0.2 115 | tzlocal==2.1 116 | urllib3==1.25.10; python_version != '3.4' 117 | uuid==1.30 118 | validators==0.18.0; python_version >= '3.4' 119 | wandb==0.9.5; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' 120 | watchdog==0.10.3 121 | wcwidth==0.2.5 122 | webencodings==0.5.1 123 | widgetsnbextension==3.5.1 124 | wrapt==1.11.1 125 | zipp==3.1.0; python_version >= '3.6' 126 | -------------------------------------------------------------------------------- /label_bot/preprocessing.py: -------------------------------------------------------------------------------- 1 | # Github-Issues-Classifier 2 | # Copyright(C) 2020 Georgios (Giorgos) Karantonis 3 | # 4 | # This program is free software: you can redistribute it and / or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | import os 18 | import click 19 | 20 | import numpy as np 21 | import pandas as pd 22 | 23 | import paraphrase_detector 24 | 25 | 26 | 27 | def download_data(memory_limit=None, save=True, base_url='https://storage.googleapis.com/codenet/issue_labels/00000000000'): 28 | ''' 29 | Downloads the raw dataset. 30 | ''' 31 | print('Downloading Dataset...\n') 32 | 33 | df = pd.concat([pd.read_csv(f'{base_url}{i}.csv.gz') for i in range(10)])[:memory_limit] 34 | 35 | if save: 36 | df.to_pickle('data/github_raw.pkl') 37 | 38 | return df 39 | 40 | 41 | def drop_columns(df, *columns): 42 | ''' 43 | Drops specific columns from a dataframe. 44 | ''' 45 | print('Removing Redundant Columns...\n') 46 | 47 | for c in columns: 48 | try: 49 | df = df.drop(c, axis=1) 50 | except KeyError: 51 | print(c) 52 | pass 53 | 54 | return df 55 | 56 | 57 | def clean_labels(labels): 58 | ''' 59 | Cleans the labels columns of the raw dataset. 60 | ''' 61 | print('Cleaning Labels...\n') 62 | 63 | labels_fixed = [] 64 | 65 | for i, label_set in enumerate(labels): 66 | # convert labels from string to list 67 | label_set = label_set.lower().replace('[', '').replace(']', '').replace('"', '').split(', ') 68 | 69 | # keep only unique labels 70 | label_set = set(label_set) 71 | 72 | cur_labels = [] 73 | for label in label_set: 74 | cur_labels.append(label) 75 | 76 | labels_fixed.append(cur_labels) 77 | 78 | return pd.Series(labels_fixed) 79 | 80 | 81 | def get_reference_info(df): 82 | ''' 83 | Gets the repo and the owner of the repo for each issue. 84 | ''' 85 | print('Getting Issue Info...\n') 86 | 87 | reference_df = df['url'].str.extract(r'.*github\.com/(?P.+)/(?P.+)/issues/(?P\d+)') 88 | 89 | df = transform(df, to_add=[reference_df[feature] for feature in reference_df]) 90 | 91 | return df 92 | 93 | 94 | def min_presence(df, feature='labels', p=.001): 95 | ''' 96 | Drops examples that fall into classes that contain very few examples. 97 | ''' 98 | print('Filtering out Redundant Labels...\n') 99 | 100 | thresh = int(p * len(df)) 101 | 102 | features_count = get_unique_values(df, feature) 103 | n_features = features_count.where(features_count.values >= thresh).dropna() 104 | 105 | return n_features.keys().values, n_features.values 106 | 107 | 108 | def vectorize(s, values, prefix=None): 109 | ''' 110 | Gets the multi-hot embeddings for the labels. 111 | ''' 112 | print('Vectorizing Features...\n') 113 | 114 | series_length = len(s) 115 | labels_df = pd.DataFrame(np.zeros((len(s), len(values))), columns=values) 116 | 117 | for i, label_set in enumerate(s): 118 | print(f'{i+1} / {series_length}\r', end='') 119 | 120 | for l in label_set: 121 | labels_df.iloc[i][l] = 1 122 | 123 | if prefix: 124 | labels_df.columns = [f'{prefix}_{v}' for v in values] 125 | 126 | return labels_df 127 | 128 | 129 | def clean_text_data(df, *features): 130 | ''' 131 | Removes the string literal prefix from the bodies and the titles. 132 | ''' 133 | print('Cleaning Text Data...\n') 134 | 135 | for feature in features: 136 | df[feature] = df[feature].str.replace(r'\\r', '').str.lower() 137 | df[feature] = df[feature].str.split().str.join(' ') 138 | 139 | return df 140 | 141 | 142 | def transform(df, **kwargs): 143 | ''' 144 | Adds and removes certain columns from the dataframe. 145 | ''' 146 | print('Transforming DataFrame...\n') 147 | 148 | try: 149 | for feature in kwargs['to_add']: 150 | df.reset_index(drop=True, inplace=True) 151 | feature.reset_index(drop=True, inplace=True) 152 | 153 | df = pd.concat([df, feature], axis=1) 154 | except KeyError: 155 | pass 156 | 157 | try: 158 | df = drop_columns(df, kwargs['to_drop']) 159 | except KeyError: 160 | pass 161 | 162 | return df 163 | 164 | 165 | def preprocess(df, save=True, save_to='data/github.pkl'): 166 | ''' 167 | The main function for the preprocessing of the dataset. 168 | ''' 169 | df['url'] = df['url'].str.replace('"', '') 170 | 171 | df = get_reference_info(df) 172 | 173 | df = drop_columns(df, 'repo', 'num_labels', 'c_bug', 'c_feature', 'c_question', 'class_int') 174 | 175 | # df['labels'] = clean_labels(df['labels'].values) 176 | 177 | df = clean_text_data(df, 'title', 'body') 178 | 179 | df['labels'], LABELS = paraphrase_detector.main(df['labels']) 180 | 181 | labels_vectorized = vectorize(df['labels'], LABELS, prefix='label') 182 | df = transform(df, to_add=[labels_vectorized]) 183 | 184 | if save: 185 | df.to_pickle(save_to) 186 | 187 | return df 188 | 189 | 190 | def fetch_github_data(look_for_downloaded=True, memory_limit=None, base_url='https://storage.googleapis.com/codenet/issue_labels/00000000000'): 191 | ''' 192 | Either loads the raw dataset if its already downloaded or downloads it from scratch. 193 | ''' 194 | if look_for_downloaded: 195 | try: 196 | df = pd.read_pickle('data/github_raw.pkl')[:memory_limit] 197 | except: 198 | df = download_data(memory_limit=memory_limit, base_url=base_url)[:memory_limit] 199 | else: 200 | df = download_data(memory_limit=memory_limit, base_url=base_url)[:memory_limit] 201 | 202 | return df 203 | 204 | 205 | def load_data(fetch=False, memory_limit=None, file='data/github.pkl', base_url='https://storage.googleapis.com/codenet/issue_labels/00000000000'): 206 | ''' 207 | Loads the dataset. 208 | ''' 209 | return fetch_github_data(memory_limit=memory_limit, base_url=base_url) if fetch else pd.read_pickle(file)[:memory_limit] 210 | 211 | 212 | @click.command() 213 | @click.option('--fetch', '-F', default=False, type=bool) 214 | @click.option('--limit', '-L', default=None, type=int) 215 | def cli(fetch, limit): 216 | ''' 217 | A CLI tool for the preprocessing of the dataset. 218 | ''' 219 | if not os.path.exists('data'): 220 | os.mkdir('data') 221 | 222 | df = load_data(fetch=fetch, memory_limit=limit) 223 | df = preprocess(df) 224 | 225 | 226 | 227 | if __name__ == '__main__': 228 | cli() 229 | 230 | 231 | 232 | 233 | 234 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | # Github-Issues-Classifier 2 | # Copyright(C) 2020 Georgios (Giorgos) Karantonis 3 | # 4 | # This program is free software: you can redistribute it and / or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | ''' 18 | A CLI tool for the classifier. 19 | ''' 20 | 21 | import os 22 | os.environ["WANDB_SILENT"] = "true" 23 | 24 | import json 25 | import sys 26 | import click 27 | 28 | import pandas as pd 29 | from github import Github 30 | 31 | from label_bot import models 32 | 33 | 34 | 35 | def init_models(ctx, param, value): 36 | ''' 37 | Initializes the trained model. 38 | ''' 39 | global BOT 40 | 41 | if not value or ctx.resilient_parsing: 42 | BOT = models.Bot(use_head=False) 43 | else: 44 | BOT = models.Bot(use_head=True) 45 | 46 | 47 | def set_token(ctx, param, value): 48 | ''' 49 | Pass the token as a CLI argument. 50 | ''' 51 | global token 52 | 53 | if not value or ctx.resilient_parsing: 54 | token = get_token() 55 | 56 | if not token: 57 | print("Exiting, no token found...") 58 | 59 | return 60 | 61 | token = value 62 | 63 | 64 | def get_token(file="token.json"): 65 | ''' 66 | Finds and the returns the personal access token 67 | from the ./token.json file. 68 | ''' 69 | with open(file) as f: 70 | token = json.load(f)["token"] 71 | 72 | return token 73 | 74 | 75 | def predict(title, body): 76 | ''' 77 | Returns the prediction scores. 78 | 79 | args: 80 | title : the titles of the issues. 81 | body : the bodies of the issues. 82 | ''' 83 | return BOT.predict(title, body)[0] 84 | 85 | 86 | @click.group() 87 | @click.option("--token", "-t", callback=set_token, expose_value=False) 88 | @click.option("--use-head", "-h", is_flag=True, callback=init_models, expose_value=False) 89 | @click.option("--threshold", "-th", default=.5, type=float) 90 | @click.option("--apply-labels", "-l", is_flag=True) 91 | def cli(threshold, apply_labels): 92 | ''' 93 | The CLI tool for the classifier. 94 | 95 | args: 96 | threshold : the decision threshold. 97 | apply_labels : whether or not to set the labels on all the visited issues. 98 | ''' 99 | global THRESHOLD, APPLY_LABELS 100 | 101 | THRESHOLD = threshold 102 | APPLY_LABELS = apply_labels 103 | 104 | pass 105 | 106 | 107 | @cli.command("crawl-org") 108 | @click.option("--organization", "-o") 109 | def run_on_org(organization): 110 | ''' 111 | Runs the classifier on all the issues 112 | opened on all the repos of a certain organization. 113 | 114 | args: 115 | organization : the organization. 116 | ''' 117 | results = pd.DataFrame(columns=["repo", "issue", "bug", "question", "enhancement"]) 118 | 119 | token = get_token() 120 | g = Github(token) 121 | 122 | root = g.get_organization(organization) 123 | 124 | for repo in root.get_repos(): 125 | for issue in repo.get_issues(): 126 | b_score, q_score, e_score = predict(issue.title, issue.body) 127 | 128 | if APPLY_LABELS: 129 | for l, s in zip(("bug", "question", "enhancement"), (b_score, q_score, e_score)): 130 | if s >= THRESHOLD: 131 | issue.set_labels(l) 132 | 133 | results = results.append({"repo" : repo.name, 134 | "issue" : issue.number, 135 | "bug" : b_score, 136 | "question" : q_score, 137 | "enhancement" : e_score 138 | }, ignore_index=True) 139 | 140 | return results 141 | 142 | 143 | @cli.command("crawl-user") 144 | @click.option("--user", "-u") 145 | def run_on_user(user): 146 | ''' 147 | Runs the classifier on all the issues 148 | opened on all the repos of a certain user. 149 | 150 | args: 151 | user : the user. 152 | ''' 153 | results = pd.DataFrame(columns=["repo", "issue", "bug", "question", "enhancement"]) 154 | 155 | token = get_token() 156 | g = Github(token) 157 | 158 | root = g.get_user(user) 159 | 160 | for repo in root.get_repos(): 161 | for issue in repo.get_issues(): 162 | b_score, q_score, e_score = predict(issue.title, issue.body) 163 | 164 | if APPLY_LABELS: 165 | for l, s in zip(("bug", "question", "enhancement"), (b_score, q_score, e_score)): 166 | if s >= THRESHOLD: 167 | issue.set_labels(l) 168 | 169 | results = results.append({"repo" : repo.name, 170 | "issue" : issue.number, 171 | "bug" : b_score, 172 | "question" : q_score, 173 | "enhancement" : e_score 174 | }, ignore_index=True) 175 | 176 | return results 177 | 178 | 179 | @cli.command("crawl-repo") 180 | @click.option("--repo", "-r") 181 | def run_on_repo(repo): 182 | ''' 183 | Runs the classifier on all the issues of a specific repo. 184 | 185 | args: 186 | repo : the repo name. 187 | ''' 188 | results = pd.DataFrame(columns=["repo", "issue", "bug", "question", "enhancement"]) 189 | 190 | token = get_token() 191 | g = Github(token) 192 | 193 | repo = g.get_repo(repo) 194 | 195 | for issue in repo.get_issues(): 196 | b_score, q_score, e_score = predict(issue.title, issue.body) 197 | 198 | if APPLY_LABELS: 199 | for l, s in zip(("bug", "question", "enhancement"), (b_score, q_score, e_score)): 200 | if s >= THRESHOLD: 201 | issue.set_labels(l) 202 | 203 | results = results.append({"repo" : repo.name, 204 | "issue" : issue.number, 205 | "bug" : b_score, 206 | "question" : q_score, 207 | "enhancement" : e_score 208 | }, ignore_index=True) 209 | 210 | return results 211 | 212 | 213 | @cli.command("crawl-issue") 214 | @click.option("--repo", "-r") 215 | @click.option("--issue", "-i") 216 | def run_on_issue(repo, issue): 217 | ''' 218 | Runs the classifier on a specific issue. 219 | 220 | args: 221 | repo : the repo where the issue is opened. 222 | issue : the issue number. 223 | ''' 224 | results = pd.DataFrame(columns=["repo", "issue", "bug", "question", "enhancement"]) 225 | 226 | token = get_token() 227 | g = Github(token) 228 | 229 | repo = g.get_repo(repo) 230 | issue = repo.get_issue(number=issue) 231 | 232 | b_score, q_score, e_score = predict(issue.title, issue.body) 233 | 234 | if APPLY_LABELS: 235 | for l, s in zip(("bug", "question", "enhancement"), (b_score, q_score, e_score)): 236 | if s >= THRESHOLD: 237 | issue.set_labels(l) 238 | 239 | results = results.append({"repo" : repo.name, 240 | "issue" : issue.number, 241 | "bug" : b_score, 242 | "question" : q_score, 243 | "enhancement" : e_score 244 | }, ignore_index=True) 245 | 246 | return results 247 | 248 | 249 | def demo(): 250 | ''' 251 | A simple demo function. 252 | ''' 253 | title = input("Title: ") 254 | body = input("Body: ") 255 | 256 | scores = predict(title, body) 257 | 258 | for kind, score in zip(("Bug", "Question", "Enhancement"), scores): 259 | print(f"{kind}: {score}") 260 | print() 261 | 262 | keep_going = input("Try another one? [y/n] ") 263 | 264 | while keep_going not in ("y", "n"): 265 | print("Type 'y' for YES or 'n' for NO") 266 | keep_going = input("Try another one? [y/n] ") 267 | 268 | if keep_going == "y": 269 | demo() 270 | else: 271 | sys.exit() 272 | 273 | 274 | @cli.command("demo") 275 | def start_demo(): 276 | demo() 277 | 278 | 279 | 280 | if __name__ == "__main__": 281 | cli() 282 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Predicting Issues' Labels with RoBERTa 2 | 3 | Many thanks to Red Hat's AICoE **[Thoth Team](https://github.com/thoth-station)** for giving me the opportunity to create this model while interning there! 4 | **Thoth is a group of *amazing* people who use Artificial Intelligence to create cool tools that make the lives of developers easier.** 5 | 6 | ## Introduction 7 | **This multilabel classifier can predict any combination of *bug*, *question* and *enhancement*, using [RoBERTa](https://arxiv.org/abs/1907.11692), one of the best performing NLP models**. Additionally, the predefined set of labels can be easily extended to almost any set of labels thanks to the incorporated paraphrase detection component; you can simply specify their desired labels and use this component to map them to actual labels in the dataset. Finally, it is completely straightforward to define your own aliases for each one of the predefined labels by mapping the output probabilities to the labels of your choice. 8 | 9 | Utilizing the `app.py` endpoint, that uses the GitHub API, you can run this classifier to your personal or your organization's repos automating your operations. 10 | 11 | **As far as I know this is the best performing implementation on this task.** 🚀 12 | 13 |

14 | 15 | 16 | 17 |

18 | 19 | 20 | ## Performance 21 | The original dataset is highly imbalanced which means that a classifier may look good just by learning to predict well the most probable label(s). Such an example is the, otherwise great, [Issue Label Bot](https://github.com/machine-learning-apps/Issue-Label-Bot) which *performs multiclass classification* and achieves a high overall accuracy due to the fact that it has a good accuracy on the two classes that dominate the dataset. If we assumed a uniform distribution of the labels (and also that the performance of the classifier wouldn't change) the overall accuracy would drop ~10%! 22 | 23 | My implementation manages to completely overcome this issue and **achieves equally high scores for all the distinct labels while extending the capabilities of the classifier to multilabel predictions**! More specifically, the average per label **accuracy is approximately 15% higher**, while the multilabel exact match accuracy is approximately 5% higher than the multiclass accuracy of the Issue Label Bot, **using only about 9% of the dataset** and without tweaking the decision threshold! 24 | 25 | You can have a look at the [`notebooks/stats.ipynb`](https://github.com/GiorgosKarantonis/Github-Issues-Classifier/blob/master/notebooks/stats.ipynb) notebook for a detailed performance report on various different metrics. 26 | 27 | 28 | ## The Dataset 29 | The original dataset consists of more than 3 million examples of GitHub issues and each one is described by its url, its repo, its title, its body and the assigned labels. Although the size of the dataset can be a big advantage to deep learning architectures there are two severe disadvantages. The first is that some labels, for example `bug` and its derivatives, dominate the dataset which can lead to unreliable classifiers. The second is the inconsistency of the labels, which means that labels that have the same meaning appear under different names in the dataset. You can check the [`notebooks/prepare_dataset.ipynb`](https://github.com/GiorgosKarantonis/Github-Issues-Classifier/blob/master/notebooks/prepare%20dataset.ipynb) and the [`notebooks/label_mapping.ipynb`](https://github.com/GiorgosKarantonis/Github-Issues-Classifier/blob/master/notebooks/label_mapping.ipynb) notebooks to get an idea how I deal with these issues and how the paraphrase detection component is incorporated to the classifier. 30 | 31 | Training, validation and testing, use a **uniform** sample of the original dataset containing a total of 90k examples for each one of the classes plus all the examples that correspond to combinations of classes. This is just a small fraction of the full dataset, but thanks to the nature of fine-tuning it's enough to achieve great performance. 32 | 33 | If you want to create your own version or see in detail how I created mine have a look at the [`notebooks/prepare_dataset.ipynb`](https://github.com/GiorgosKarantonis/Github-Issues-Classifier/blob/master/notebooks/prepare%20dataset.ipynb) notebook. 34 | 35 | 36 | ## The Model(s) 37 | **There are two models that can be used for predictions**; one is the RoBERTa base model fine-tuned on the issues' dataset for multilabel classification and the other one is the same with a, small, additional head. 38 | 39 | The second model passes to the network the title and the body of the issue separately and their respective scores, along with the score of their combination, are fed to the additional head. The idea behind this approach is that it allows to not only polarize the output scores but to also weight differently the titles and the bodies; for example the title of a specific issue may be a great indicator of its label while the body may be noisy and disorienting so if they are weighted the same useful information may be lost. Additionally, the way I have trained it provides an additional solution to the imbalance issue. 40 | 41 | Another advantage of this module can be seen when working with smaller datasets. For example, when using 20k examples per class and just by setting the threshold for each class at *0.5*, the model with the additional head manages to achieve slightly better per class accuracy, better per class recall, about 8% higher exact match accuracy and more uniform scores across the classes, compared to the model without the extra head. 42 | 43 | The outputs of both models are the independent probabilities of each class so that you can define the thresholds yourself depending on the metric that you want to optimize. Refer to the [`notebooks/stats.ipynb`](https://github.com/GiorgosKarantonis/Github-Issues-Classifier/blob/master/notebooks/stats.ipynb) for a more detailed report of the various scores. 44 | 45 | Finally, **my implementation also allows you to create and train your own heads just by defining a list of PyTorch layers**; see the [`notebooks/train_custom_head.ipynb`](https://github.com/GiorgosKarantonis/Github-Issues-Classifier/blob/master/notebooks/train_custom_head.ipynb) for more details and a more thorough explanation of the way this head is trained and when you should activate it. 46 | 47 | 48 | ## Using the classifier 49 | If you want to use my pre-trained models for predictions, make sure to download them using the `fetch_models.sh` script, but obviously you can fine-tune the models on your own datasets as well even if you have a small train set; I was able to achieve good performance even with a total of 5,000 examples. 50 | 51 | Also, you can manage all the dependencies using the provided Pipfile. 52 | 53 | In order to make predictions simply do: 54 | 55 | ```python 56 | bot = models.Bot() # the additional head is deactivated by default; if you want to use it just pass use_head=True 57 | scores = bot.predict(title=some_title, body=some_body) # the inputs can be a single string, a list of strings, a pd.Series object or a pd.DataFrame object 58 | ``` 59 | Additionally, you can use the `app.py` endpoint to use the classifier's command line interface which also allows you to also deploy the classifier to your or your organization's repos. 60 | 61 | You may also have a look at the [`notebooks/predict.ipynb`](https://github.com/GiorgosKarantonis/Github-Issues-Classifier/blob/master/notebooks/predict.ipynb) file for a few examples on real issues. 62 | 63 | 64 | ## Potential Improvements 65 | If you are interested in improving the performance of the classifier, I would recommend considering the following: 66 | 67 | * **Train on more data.** I ran into RAM issues with the tokenizers but if you have more than 8Gb of RAM or you find a workaround I believe you can significantly boost the performance just by using more data. 68 | 69 | * **Use the RoBERTa large.** Instead of the base version. 70 | 71 | * **Noise reduction in the bodies using summarization.** I experimented with this using [BART](https://arxiv.org/abs/1910.13461), but I ran into several bugs. If you plan on working on the summarization, I would advice you to use [T5](https://arxiv.org/abs/1910.10683)'s [tensorflow version](https://huggingface.co/transformers/model_doc/t5.html#tft5forconditionalgeneration). 72 | 73 | * **Fine-tune a language model first.** It's unfair to think of GitHub issues as regular text due to the fact that they are usually a hybrid between real text, code and logs etc. So fine-tuning a language model on this dataset and then fine-tuning this language model on classification could yield good results. In the `demos/prepare_dataset.ipynb` file you can find a sampling method that ensures that the examples used in the language model will be different than the ones used in the classification task. 74 | 75 | * **Use the paraphrase detection component to get better clusters than mine.** Despite all the workarounds used, you can further improve the performance by providing a cleaner and more consistent dataset. 76 | 77 | Also, if you are interested in improving the performance feel free to contact me! 🙂 78 | -------------------------------------------------------------------------------- /label_bot/paraphrase_detector.py: -------------------------------------------------------------------------------- 1 | # Github-Issues-Classifier 2 | # Copyright(C) 2020 Georgios (Giorgos) Karantonis 3 | # 4 | # This program is free software: you can redistribute it and / or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | ''' 18 | The paraphrase detection component. 19 | ''' 20 | 21 | import os 22 | os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' 23 | os.environ['WANDB_SILENT'] = 'true' 24 | 25 | import json 26 | import click 27 | import logging 28 | 29 | import numpy as np 30 | import pandas as pd 31 | 32 | import tensorflow as tf 33 | from transformers import BertTokenizer, TFBertForSequenceClassification 34 | 35 | from utils import get_n_chunks 36 | 37 | 38 | logging.getLogger('transformers').setLevel(logging.ERROR) 39 | 40 | 41 | 42 | def clean_labels(labels): 43 | ''' 44 | Cleans the labels observed in the dataset. 45 | 46 | args : 47 | labels : a pd.Series object of the observed labels. 48 | 49 | returns : 50 | labels_fixed : the cleaned labels cast as a pd.Series object. 51 | ''' 52 | print('Cleaning Labels...\n') 53 | 54 | labels_fixed = [] 55 | 56 | for i, label_set in enumerate(labels): 57 | # convert labels from string to list 58 | label_set = label_set.lower().replace('[', '').replace(']', '').replace('"', '').split(', ') 59 | 60 | # keep only unique labels 61 | label_set = set(label_set) 62 | 63 | cur_labels = [] 64 | for label in label_set: 65 | cur_labels.append(label) 66 | 67 | labels_fixed.append(cur_labels) 68 | 69 | return pd.Series(labels_fixed) 70 | 71 | 72 | def get_target_labels(): 73 | ''' 74 | Gets the target labels and their aliases. 75 | 76 | returns : 77 | aliases : all the aliases of the target labels 78 | that will be used during the clustering. 79 | target_labels : the unique target labels. 80 | label_mapping : the rules of how to map the labels. 81 | ''' 82 | with open(os.path.join('..', 'labels.json')) as f: 83 | label_mapping = json.load(f) 84 | 85 | aliases = set([k for k in label_mapping.keys()]) 86 | target_labels = set([v for v in label_mapping.values()]) 87 | 88 | return aliases, target_labels, label_mapping 89 | 90 | 91 | def disambiguate_labels(labels_dict, disambiguate='keep_most_probable'): 92 | ''' 93 | Deals with conflicts in the label mapping. 94 | 95 | args : 96 | labels_dict : a dictionary containing the observed labels 97 | and all their possible substitutions. 98 | disambiguate : how to deal with conficts; 99 | either keep only the most probable label, 100 | or drop all of the possible labels. 101 | ''' 102 | print('Disambiguating Labels...\n') 103 | 104 | assert disambiguate in ['keep_most_probable', 'drop_all'] 105 | 106 | cleaned_dict = {} 107 | 108 | for key in labels_dict: 109 | if len(labels_dict[key]) > 1: 110 | if disambiguate == 'drop_all': 111 | cleaned_dict[key] = None 112 | else: 113 | max_likelihood = 0 114 | best_match = None 115 | 116 | for label, likelihood in labels_dict[key]: 117 | if likelihood > max_likelihood: 118 | max_likelihood = likelihood 119 | best_match = label 120 | 121 | cleaned_dict[key] = best_match 122 | else: 123 | label, likelihood = labels_dict[key][0] 124 | cleaned_dict[key] = label 125 | 126 | return cleaned_dict 127 | 128 | 129 | def map_labels(label_series, mapping): 130 | ''' 131 | Replaces the observed labels with their corresponding target ones. 132 | 133 | args : 134 | label_series : the pd.Series object containing the observed labels 135 | mapping : the mapping rule obtained my the get_mapping() function. 136 | 137 | returns : 138 | mapped_labels : a modified list of labels, such that the observed ones 139 | are mapped to their corresponding targets or to nothing, 140 | cast as a pd.Series object. 141 | ''' 142 | print('Mappping Labels...\n') 143 | 144 | mapped_labels = [] 145 | 146 | for i, label_list in enumerate(label_series): 147 | temp_labels = [] 148 | 149 | for l in label_list: 150 | try: 151 | temp_labels.append(mapping[l]) 152 | except: 153 | pass 154 | 155 | if temp_labels: 156 | mapped_labels.append(temp_labels) 157 | else: 158 | mapped_labels.append(['undefined']) 159 | 160 | return pd.Series(mapped_labels) 161 | 162 | 163 | def get_mapping(paraphrase_candidates, paraphrase_likelihood, threshold=.5): 164 | ''' 165 | Finds the mapping of labels observed in the dataset to target labels. 166 | 167 | args : 168 | paraphrase_candidates : combinations of target and observed labels. 169 | paraphrase_likelihood : the probability, for each combination, 170 | of being a paraphrase. 171 | threshold : the minimum probability to consider a combination paraphrase. 172 | 173 | returns : 174 | label_mapping : a dictionary containing observed labels and their 175 | corresponding target label. 176 | ''' 177 | label_mapping = {} 178 | 179 | for pair, pair_likelihood in zip(paraphrase_candidates, paraphrase_likelihood): 180 | if pair_likelihood > threshold: 181 | target_l, real_l = pair[0], pair[1] 182 | 183 | try: 184 | label_mapping[real_l].append((LABELS[target_l], pair_likelihood)) 185 | except: 186 | label_mapping[real_l] = [] 187 | label_mapping[real_l].append((LABELS[target_l], pair_likelihood)) 188 | 189 | return label_mapping 190 | 191 | 192 | def make_combinations(targets, observed): 193 | ''' 194 | Creates combinations of target labels and observed ones. 195 | 196 | args : 197 | targets : the target labels. 198 | observed : the unique labels observed in the dataset. 199 | 200 | returns : 201 | combinations : the combinations of target and observed labels. 202 | ''' 203 | print('Creating Label Combinations...\n') 204 | 205 | combinations = [] 206 | 207 | for t in targets: 208 | for o in observed: 209 | combinations.append([t, o]) 210 | 211 | return combinations 212 | 213 | 214 | def check_paraphrase(inputs, low_memory=True, chunk_size=1000): 215 | ''' 216 | Finds the likelihood of a combination of strings to be a paraphrase. 217 | 218 | args : 219 | inputs : a combination of strings. 220 | low_memory : if you want to split the inputs 221 | to batches in order to avoid OOM issues. 222 | chunk_size : the batch size in case low_memory is set to True. 223 | 224 | returns : 225 | paraphrase_likelihood : the probability, for each combination, 226 | of being a paraphrase. 227 | 228 | ''' 229 | print('Checking for Paraphrase...\n') 230 | 231 | tokenizer = BertTokenizer.from_pretrained('bert-base-cased-finetuned-mrpc', output_loading_info=False) 232 | model = TFBertForSequenceClassification.from_pretrained('bert-base-cased-finetuned-mrpc', output_loading_info=False) 233 | 234 | if low_memory: 235 | n_chunks = get_n_chunks(inputs, chunk_size) 236 | 237 | paraphrase_likelihood = np.array([]) 238 | 239 | for i in range(n_chunks): 240 | from time import time 241 | start = time() 242 | 243 | print(f'Chunk: {i+1}/{n_chunks}\r', end='') 244 | 245 | try: 246 | cur_inputs = inputs[i*chunk_size:(i+1)*chunk_size] 247 | except IndexError: 248 | cur_inputs = inputs[i*chunk_size:] 249 | 250 | cur_inputs = tokenizer(cur_inputs, 251 | padding=True, 252 | truncation=True, 253 | return_tensors='tf') 254 | 255 | logits = model(cur_inputs)[0] 256 | outputs = tf.nn.softmax(logits, axis=1).numpy() 257 | 258 | paraphrase_likelihood = np.append(paraphrase_likelihood, outputs[:, 1]) 259 | 260 | return paraphrase_likelihood 261 | 262 | 263 | print(f'Time elapsed for chunk {i}: {time() - start}sec') 264 | else: 265 | cur_inputs = tokenizer(cur_inputs, 266 | padding=True, 267 | truncation=True, 268 | return_tensors='tf') 269 | 270 | logits = model(cur_inputs)[0] 271 | outputs = tf.nn.softmax(logits, axis=1).numpy() 272 | 273 | paraphrase_likelihood = outputs[:, 1] 274 | 275 | return paraphrase_likelihood 276 | 277 | 278 | def main(label_series): 279 | ''' 280 | The main function that handles the alignment of the labels. 281 | 282 | args : 283 | label_series : a pd.Series object containing all the labels 284 | as they are observed in the dataset. 285 | 286 | returns : 287 | label_series : a pd.Series object containing the mapped labels. 288 | target_labels : a set containing all the unique target labels. 289 | ''' 290 | global LABELS 291 | aliases, target_labels, LABELS = get_target_labels() 292 | 293 | label_series = clean_labels(label_series) 294 | unique_labels = label_series.explode().value_counts().keys().values 295 | 296 | paraphrase_candidates = make_combinations(aliases, unique_labels) 297 | paraphrase_likelihood = check_paraphrase(paraphrase_candidates) 298 | 299 | label_mapping = get_mapping(paraphrase_candidates, paraphrase_likelihood) 300 | label_mapping = disambiguate_labels(label_mapping) 301 | label_series = map_labels(label_series, label_mapping) 302 | 303 | if 'undefined' not in target_labels: 304 | target_labels.add('undefined') 305 | 306 | return label_series, target_labels 307 | 308 | 309 | @click.command() 310 | @click.option('--limit', '-L', default=None, type=int) 311 | @click.option('--file', '-F', default='data/github_raw.pkl', type=str) 312 | def cli(limit, file): 313 | ''' 314 | A CLI tool for the paraphrase detection component. 315 | ''' 316 | label_series = pd.read_pickle(file)['labels'][:limit] 317 | label_series, LABELS = main(label_series) 318 | 319 | 320 | 321 | if __name__ == '__main__': 322 | cli() -------------------------------------------------------------------------------- /label_bot/models.py: -------------------------------------------------------------------------------- 1 | # Github-Issues-Classifier 2 | # Copyright(C) 2020 Georgios (Giorgos) Karantonis 3 | # 4 | # This program is free software: you can redistribute it and / or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | ''' 18 | Contains the models used for the classification. 19 | ''' 20 | 21 | import os 22 | import json 23 | 24 | import numpy as np 25 | import pandas as pd 26 | 27 | import torch 28 | import torch.nn as nn 29 | import torch.optim as optim 30 | 31 | from simpletransformers.classification import MultiLabelClassificationModel 32 | 33 | 34 | _HERE_DIR = os.path.dirname(os.path.abspath(__file__)) 35 | 36 | 37 | 38 | class ScoresHead(nn.Module): 39 | ''' 40 | An extra head applied to the top of the fine-tuned model 41 | to tweak the final scores. 42 | ''' 43 | def __init__(self, custom_head=None): 44 | ''' 45 | Initializes the head. 46 | 47 | args: 48 | custom_head : a list of PyTorch layers 49 | ''' 50 | super().__init__() 51 | self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 52 | 53 | self.loss = nn.BCELoss() 54 | self.optimizer = optim.Adam 55 | 56 | head = custom_head if custom_head else self.default_head() 57 | self.model = nn.Sequential(*head).to(self.device) 58 | 59 | 60 | def default_head(self): 61 | ''' 62 | The default head to be used 63 | in case no other is provided by the user. 64 | ''' 65 | return [ 66 | nn.Linear(9, 100), 67 | nn.LeakyReLU(.2), 68 | nn.BatchNorm1d(100), 69 | nn.Linear(100, 3) 70 | ] 71 | 72 | 73 | def forward(self, titles, bodies, combined, train=True): 74 | ''' 75 | The forward pass of the model. 76 | 77 | args: 78 | titles : the output scores of the fine-tuned model 79 | when only the titles of issues are fed to it. 80 | bodies : the output scores of the fine-tuned model 81 | when only the bodies of issues are fed to it. 82 | combined : the output scores of the fine-tuned model 83 | when the combination of titles and bodies is fed to it. 84 | ''' 85 | if train: 86 | self.model = self.model.train() 87 | else: 88 | self.model = self.model.eval() 89 | 90 | x = torch.cat((titles, bodies, combined), dim=1).to(self.device) 91 | x = self.model(x) 92 | x = torch.sigmoid(x) 93 | 94 | return x 95 | 96 | 97 | def fit(self, 98 | titles, 99 | bodies, 100 | combined, 101 | labels, 102 | validation=True, 103 | val_titles=None, 104 | val_bodies=None, 105 | val_combined=None, 106 | val_labels=None, 107 | epochs=35, 108 | lr=5e-3, 109 | verbose=True): 110 | ''' 111 | The training function. 112 | 113 | args : 114 | titles : the titles of the issues. 115 | bodies : the bodies of the issues. 116 | combined : the combination of title and body for each issue. 117 | labels : the ground truth labels. 118 | validation : if a validation set is used. 119 | val_titles : the titles of the validation set. 120 | val_bodies : the bodies of the validation set. 121 | val_combined : the combination of titles and bodies 122 | for each issue of the validation set. 123 | val_labels : the ground truth labels for the validation set. 124 | epochs : the number of epochs. 125 | lr : the learning rate. 126 | verbose : whether of not to print the loss and the accuracy 127 | after every epoch. 128 | 129 | returns : 130 | outputs : the output scores. 131 | losses : the training (and validation) losses. 132 | ''' 133 | losses = { 134 | 'train' : [], 135 | 'val' : [] 136 | } 137 | 138 | optimizer = self.optimizer(self.model.parameters(), lr=lr) 139 | 140 | labels = np.array(labels) 141 | 142 | for epoch in range(epochs): 143 | indices = np.arange(titles.shape[0]) 144 | np.random.shuffle(indices) 145 | 146 | titles = titles[indices] 147 | bodies = bodies[indices] 148 | combined = combined[indices] 149 | labels = labels[indices] 150 | 151 | titles_tensor = torch.from_numpy(titles).to(self.device) 152 | bodies_tensor = torch.from_numpy(bodies).to(self.device) 153 | combined_tensor = torch.from_numpy(combined).to(self.device) 154 | 155 | labels = torch.FloatTensor(list(map(list, labels))).to(self.device) 156 | 157 | optimizer.zero_grad() 158 | outputs = self.forward(titles_tensor, bodies_tensor, combined_tensor) 159 | 160 | loss = self.loss(outputs, labels) 161 | 162 | loss.backward() 163 | optimizer.step() 164 | 165 | losses['train'].append(loss.item()) 166 | if validation: 167 | val_loss = self.evaluate(val_titles, val_bodies, val_combined, val_labels) 168 | losses['val'].append(val_loss) 169 | 170 | if verbose: 171 | print(f'Epoch: {epoch+1}') 172 | print(f'Training loss: {loss.item()}') 173 | if validation: 174 | print(f'Validation loss: {val_loss}') 175 | print('Validation Accuracy: ', accuracy(np.where(outputs.detach().cpu().numpy() > .5, 1, 0), 176 | labels.detach().cpu().numpy())) 177 | print() 178 | 179 | return outputs.detach().cpu().numpy(), losses 180 | 181 | 182 | def evaluate(self, titles, bodies, combined, labels): 183 | ''' 184 | Evaluates the performance of the head. 185 | 186 | args : 187 | titles : the titles of the issues. 188 | bodies : the bodies of the issues. 189 | combined : the combinations of title and body for each issue. 190 | labels : the ground truth labels. 191 | 192 | returns : 193 | predictions : the prediction scores. 194 | ''' 195 | losses = [] 196 | 197 | titles_tensor = torch.from_numpy(titles).to(self.device) 198 | bodies_tensor = torch.from_numpy(bodies).to(self.device) 199 | combined_tensor = torch.from_numpy(combined).to(self.device) 200 | 201 | labels = torch.FloatTensor(list(map(list, labels))).to(self.device) 202 | 203 | outputs = self.forward(titles_tensor, bodies_tensor, combined_tensor, train=False) 204 | 205 | loss = self.loss(outputs, labels) 206 | 207 | return loss.detach().cpu().item() 208 | 209 | 210 | def predict(self, titles, bodies, combined): 211 | ''' 212 | Makes predictions on given issues. 213 | 214 | args : 215 | titles : the titles of the issues. 216 | bodies : the bodies of the issues. 217 | combined : the combinations of title and body for each issue. 218 | 219 | returns : 220 | predictions : the prediction scores. 221 | ''' 222 | titles_tensor = torch.from_numpy(titles).to(self.device) 223 | bodies_tensor = torch.from_numpy(bodies).to(self.device) 224 | combined_tensor = torch.from_numpy(combined).to(self.device) 225 | 226 | predictions = self.forward(titles_tensor, bodies_tensor, combined_tensor, train=False) 227 | 228 | return predictions.detach().cpu().numpy() 229 | 230 | 231 | 232 | class Bot: 233 | ''' 234 | The final classifier! 235 | ''' 236 | def __init__(self, 237 | use_head=True, 238 | model_name='roberta', 239 | model_path=os.path.join(_HERE_DIR, 'models', 'classification', 'roberta-base')): 240 | ''' 241 | Initializes the classifier. 242 | 243 | args : 244 | use_head : whether or not to activate the extra head. 245 | model_name : the name of the fine-tuned model. 246 | model_path : the path where the model is saved to. 247 | ''' 248 | super().__init__() 249 | self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 250 | 251 | 252 | self.use_head = use_head 253 | self.model_path = model_path 254 | 255 | self.classifier = self.load_pretrained_model(model_name, model_path) 256 | 257 | 258 | def load_pretrained_model(self, name='roberta', from_path='roberta-base'): 259 | ''' 260 | Loads and returns the fine-tuned model. 261 | 262 | args : 263 | name : the name of the fine-tuned model. 264 | from_path : the path where the model is saved to. 265 | ''' 266 | if from_path.endswith('/'): 267 | from_path = from_path[:-1] 268 | 269 | with open(f'{from_path}/model_args.json') as f: 270 | model_args = json.load(f) 271 | 272 | return MultiLabelClassificationModel(name, 273 | from_path, 274 | num_labels=3, 275 | args=model_args, 276 | use_cuda=self.device==torch.device('cuda')) 277 | 278 | 279 | def predict(self, title, body): 280 | ''' 281 | The prediction function. 282 | 283 | args : 284 | title : the title of one or more issues. 285 | body : the body of one or more issues. 286 | 287 | returns : 288 | scores : the prediction scores. 289 | ''' 290 | if isinstance(title, str): 291 | title = pd.DataFrame([title]) 292 | if isinstance(body, str): 293 | body = pd.DataFrame([body]) 294 | 295 | if not isinstance(title, pd.DataFrame): 296 | title = pd.DataFrame(title) 297 | if not isinstance(body, pd.DataFrame): 298 | body = pd.DataFrame(body) 299 | 300 | title.columns = ['text'] 301 | body.columns = ['text'] 302 | 303 | if self.use_head: 304 | _, titles_scores = self.classifier.predict(title['text']) 305 | _, bodies_scores = self.classifier.predict(body['text']) 306 | _, scores = self.classifier.predict(title['text'] + ' ' + body['text']) 307 | 308 | head = ScoresHead() 309 | if self.device == 'cuda': 310 | head.load_state_dict(torch.load(os.path.join(self.model_path, 'scores_head.pt'))) 311 | else: 312 | head.load_state_dict(torch.load(os.path.join(self.model_path, 'scores_head.pt'), map_location=torch.device('cpu'))) 313 | 314 | scores = head.predict(titles_scores, bodies_scores, scores) 315 | else: 316 | df = pd.DataFrame(title['text'] + ' ' + body['text']) 317 | df.columns = ['text'] 318 | 319 | _, scores = self.classifier.predict(df['text']) 320 | 321 | 322 | return scores -------------------------------------------------------------------------------- /label_bot/utils.py: -------------------------------------------------------------------------------- 1 | # Github-Issues-Classifier 2 | # Copyright(C) 2020 Georgios (Giorgos) Karantonis 3 | # 4 | # This program is free software: you can redistribute it and / or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | ''' 18 | A set of utility functions. 19 | ''' 20 | 21 | import os 22 | os.environ['WANDB_SILENT'] = 'true' 23 | 24 | import json 25 | import numpy as np 26 | import pandas as pd 27 | 28 | from sklearn.metrics import roc_curve, accuracy_score, roc_auc_score, precision_recall_fscore_support 29 | from sklearn.metrics import label_ranking_average_precision_score as lrap 30 | from sklearn.preprocessing import MultiLabelBinarizer 31 | 32 | from matplotlib import pyplot as plt 33 | 34 | from simpletransformers.classification import MultiLabelClassificationModel 35 | 36 | 37 | 38 | def get_model_stats(y_true, model_outputs, b_thres=.5, q_thres=.5, e_thres=.5, plot_roc=True): 39 | ''' 40 | Gets the performance statistics of a model based on its outputs and the ground truth. 41 | ''' 42 | b_scores, q_scores, e_scores = model_outputs[:, 0], model_outputs[:, 1], model_outputs[:, 2] 43 | b_true, q_true, e_true = y_true[:, 0], y_true[:, 1], y_true[:, 2] 44 | 45 | b_roc_auc = roc_auc_score(b_true, b_scores) 46 | q_roc_auc = roc_auc_score(q_true, q_scores) 47 | e_roc_auc = roc_auc_score(e_true, e_scores) 48 | 49 | b_fpr, b_tpr, _ = roc_curve(b_true, b_scores) 50 | q_fpr, q_tpr, _ = roc_curve(q_true, q_scores) 51 | e_fpr, e_tpr, _ = roc_curve(e_true, e_scores) 52 | 53 | if plot_roc: 54 | plt.figure() 55 | plt.title('ROC Curves \nfor Bugs, Questions and Enhancements') 56 | plt.xlabel('False Positive Rate') 57 | plt.ylabel('True Positive Rate') 58 | plt.plot(b_fpr, b_tpr, color='orange', label=f'Bug{" "*24}, AUC: {b_roc_auc:.3f}') 59 | plt.plot(q_fpr, q_tpr, color='blue', label=f'Question{" "*16}, AUC: {q_roc_auc:.3f}') 60 | plt.plot(e_fpr, e_tpr, color='green', label=f'Enhancement{" "*8}, AUC: {e_roc_auc:.3f}') 61 | plt.plot([0, 1], [0, 1], color='red', linestyle='--', label=f'Random Guess{" "*6}, AUC: 0.5') 62 | plt.legend(loc="lower right") 63 | plt.show() 64 | 65 | b_preds = np.where(b_scores >= b_thres, 1, 0) 66 | q_preds = np.where(q_scores >= q_thres, 1, 0) 67 | e_preds = np.where(e_scores >= e_thres, 1, 0) 68 | 69 | b_accuracy = accuracy_score(b_true, b_preds) 70 | q_accuracy = accuracy_score(q_true, q_preds) 71 | e_accuracy = accuracy_score(e_true, e_preds) 72 | 73 | b_precision, b_recall, b_f1, _ = precision_recall_fscore_support(b_true, b_preds, average='binary') 74 | q_precision, q_recall, q_f1, _ = precision_recall_fscore_support(q_true, q_preds, average='binary') 75 | e_precision, e_recall, e_f1, _ = precision_recall_fscore_support(e_true, e_preds, average='binary') 76 | 77 | y_pred = np.concatenate((b_preds.reshape(-1, 1), q_preds.reshape(-1, 1), e_preds.reshape(-1, 1)), axis=1) 78 | 79 | exact_matches = 0 80 | for true, pred in zip(y_true, y_pred): 81 | if (true == pred).all(): 82 | exact_matches += 1 83 | 84 | exact_accuracy = exact_matches/len(y_true) 85 | 86 | metrics_df = pd.DataFrame([[b_accuracy, b_roc_auc, b_precision, b_recall, b_f1], 87 | [q_accuracy, q_roc_auc, q_precision, q_recall, q_f1], 88 | [e_accuracy, e_roc_auc, e_precision, e_recall, e_f1]], 89 | columns=['Accuracy', 'ROC-AUC', 'Precision', 'Recall', 'F1'], 90 | index=['Bug', 'Question', 'Enhancement']) 91 | 92 | lrap_score = lrap(y_true, model_outputs) 93 | 94 | return metrics_df, exact_accuracy, lrap_score 95 | 96 | 97 | def load_model(args, task='mlc', name='roberta', from_path='roberta-base'): 98 | ''' 99 | Loads a pre-trained PyTorch model. 100 | ''' 101 | if task == 'mlm': 102 | return LanguageModelingModel(name, 103 | from_path, 104 | args=args) 105 | elif task == 'mlc': 106 | return MultiLabelClassificationModel(name, 107 | from_path, 108 | num_labels=3, 109 | args=args) 110 | else: 111 | raise NotImplementedError("Choose 'mlm' for Masked Language Modeling or 'mlc' for Multilabel Classification!") 112 | 113 | 114 | def load_models_meta(): 115 | ''' 116 | Loads the metadata of a trained PyTorch model. 117 | ''' 118 | with open('models.json') as json_file: 119 | models_meta = json.load(json_file) 120 | 121 | return models_meta 122 | 123 | 124 | def get_n_chunks(df, chunk_size): 125 | ''' 126 | Returns the number of batches that a dataset can be split to given the batch size. 127 | ''' 128 | df_size = len(df) 129 | 130 | return int(df_size / chunk_size) if df_size % chunk_size == 0 else int(df_size / chunk_size) + 1 131 | 132 | 133 | def get_unique_values(df, feature): 134 | ''' 135 | Returns only the unique values of a specific feature of a dataframe. 136 | ''' 137 | return df.explode(feature)[feature].value_counts() 138 | 139 | 140 | def df_to_txt(df, return_text=False, save=True, path='./', name='text', extension='txt'): 141 | ''' 142 | Converts the title and body features of a dataframe to a text file. 143 | ''' 144 | text = '' 145 | 146 | for i in range(len(df)): 147 | title = df.iloc[i].title 148 | body = df.iloc[i].body 149 | 150 | text += f'{title}\n{body}\n\n' 151 | 152 | if save: 153 | if not path.endswith('/'): 154 | path = f'{path}/' 155 | 156 | with open(f'{path}{name}.{extension}', 'w') as f: 157 | f.write(text) 158 | 159 | if return_text: 160 | return text 161 | 162 | 163 | def split_to_classes(df, 164 | to_keep=['title', 'body', 'label_bug', 'label_question', 'label_enhancement'], 165 | save=False, 166 | path='./'): 167 | ''' 168 | Split the dataset to several smaller ones, 169 | where each one of them contains only a specific class 170 | or all the examples that fall into a combination of classes. 171 | ''' 172 | if to_keep: 173 | df = df[to_keep] 174 | 175 | bugs_df = df.query('label_bug == 1 and \ 176 | label_question == 0 and \ 177 | label_enhancement == 0') 178 | 179 | questions_df = df.query('label_bug == 0 and \ 180 | label_question == 1 and \ 181 | label_enhancement == 0') 182 | 183 | enhancements_df = df.query('label_bug == 0 and \ 184 | label_question == 0 and \ 185 | label_enhancement == 1') 186 | 187 | combinations_df = df.query('(label_bug == 1 and label_question == 1 and label_enhancement == 0) or \ 188 | (label_bug == 1 and label_question == 0 and label_enhancement == 1) or \ 189 | (label_bug == 0 and label_question == 1 and label_enhancement == 1) or \ 190 | (label_bug == 1 and label_question == 1 and label_enhancement == 1)') 191 | 192 | if save: 193 | if not path.endswith('/'): 194 | path = f'{path}/' 195 | 196 | bugs_df.to_pickle(f'{path}bugs.pkl') 197 | questions_df.to_pickle(f'{path}questions.pkl') 198 | enhancements_df.to_pickle(f'{path}enhancements.pkl') 199 | combinations_df.to_pickle(f'{path}combinations.pkl') 200 | 201 | return bugs_df, questions_df, enhancements_df, combinations_df 202 | 203 | 204 | def get_labels_stats(df): 205 | ''' 206 | Gets statistics for each one of the labels. 207 | ''' 208 | total = len(df) 209 | 210 | # all the examples that are labelled 211 | # only as bugs 212 | b = len(df.query('label_bug == 1 and \ 213 | label_question == 0 and \ 214 | label_enhancement == 0')) 215 | 216 | # all the examples that are labelled 217 | # only as questions 218 | q = len(df.query('label_bug == 0 and \ 219 | label_question == 1 and \ 220 | label_enhancement == 0')) 221 | 222 | # all the examples that are labelled 223 | # only as enhancement 224 | e = len(df.query('label_bug == 0 and \ 225 | label_question == 0 and \ 226 | label_enhancement == 1')) 227 | 228 | # all the examples that are labelled 229 | # only as both bug and question 230 | b_q = len(df.query('label_bug == 1 and \ 231 | label_question == 1 and \ 232 | label_enhancement == 0')) 233 | 234 | # all the examples that are labelled 235 | # only as both bug and enhancement 236 | b_e = len(df.query('label_bug == 1 and \ 237 | label_question == 0 and \ 238 | label_enhancement == 1')) 239 | 240 | # all the examples that are labelled 241 | # only as both question and enhancement 242 | q_e = len(df.query('label_bug == 0 and \ 243 | label_question == 1 and \ 244 | label_enhancement == 1')) 245 | 246 | # all the examples that are labelled 247 | # as bug, question and enhancement 248 | b_q_e = len(df.query('label_bug == 1 and \ 249 | label_question == 1 and \ 250 | label_enhancement == 1')) 251 | 252 | return pd.DataFrame([['Bug', b/total, b], 253 | ['Question', q/total, q], 254 | ['Enhancement', e/total, e], 255 | ['Bug, Question', b_q/total, b_q], 256 | ['Bug, Enhancement', b_e/total, b_e], 257 | ['Question, Enhancement', q_e/total, q_e], 258 | ['Bug, Question, Enhancement', b_q_e/total, b_q_e], 259 | ['Total', total/total, total]], 260 | columns=['Labels Present', 'Fraction', 'Examples']) 261 | 262 | 263 | def sample_df(df, 264 | n=None, 265 | frac=None, 266 | to_keep=['title', 'body', 'label_bug', 'label_question', 'label_enhancement']): 267 | ''' 268 | Performs sampling over the dataset. 269 | 270 | args : 271 | df : the dataset. 272 | n : the absolute number of examples that are going to be kept. 273 | fract : the fraction of examples that it going to be kept; 274 | it has to be mutually exclusive with the n argument. 275 | to_keep : the columns to keep in the datasets. 276 | ''' 277 | assert n != frac 278 | bugs_df, questions_df, enhancements_df, combinations_df = split_to_classes(df, to_keep) 279 | 280 | if n: 281 | bugs_df = bugs_df.sample(n=n) 282 | questions_df = questions_df.sample(n=n) 283 | enhancements_df = enhancements_df.sample(n=n) 284 | else: 285 | bugs_df = bugs_df.sample(frac=frac) 286 | questions_df = questions_df.sample(frac=frac) 287 | enhancements_df = enhancements_df.sample(frac=frac) 288 | 289 | # shuffle the dataframes 290 | bugs_df = bugs_df.sample(frac=1) 291 | questions_df = questions_df.sample(frac=1) 292 | enhancements_df = enhancements_df.sample(frac=1) 293 | combinations_df = combinations_df.sample(frac=1) 294 | 295 | return bugs_df, questions_df, enhancements_df, combinations_df 296 | 297 | 298 | def split_train_test(df, 299 | validation=False, 300 | train_frac=.7, 301 | val_frac=.1, 302 | shuffle=True, 303 | save=True, 304 | path='./', 305 | name='', 306 | to_keep=None): 307 | ''' 308 | Splits the dataset to train, test and validation sets. 309 | ''' 310 | if shuffle: 311 | df = df.sample(frac=1) 312 | 313 | if to_keep: 314 | df = df[to_keep] 315 | 316 | train_split = int(train_frac * (len(df))) 317 | 318 | train_df = df.iloc[:train_split] 319 | test_df = df.iloc[train_split:] 320 | 321 | if validation: 322 | val_split = int(val_frac * (len(train_df))) 323 | 324 | val_df = train_df.iloc[:val_split] 325 | train_df = train_df.iloc[val_split:] 326 | 327 | if save: 328 | if not path.endswith('/'): 329 | path = f'{path}/' 330 | 331 | train_df.to_pickle(f'{path}{name}train.pkl') 332 | test_df.to_pickle(f'{path}{name}test.pkl') 333 | 334 | if validation: 335 | val_df.to_pickle(f'{path}{name}val.pkl') 336 | 337 | if validation: 338 | return train_df, val_df, test_df 339 | else: 340 | return train_df, test_df 341 | 342 | 343 | def make_st_compatible(df): 344 | ''' 345 | Converts the labels column to a format 346 | compatible to the simple transformers library. 347 | ''' 348 | df['labels'] = list(zip(df.label_bug.tolist(), 349 | df.label_question.tolist(), 350 | df.label_enhancement.tolist())) 351 | 352 | for c in df.columns: 353 | if c.startswith('label_'): 354 | df = df.drop(c, axis=1) 355 | 356 | return df 357 | 358 | 359 | 360 | 361 | -------------------------------------------------------------------------------- /notebooks/prepare dataset.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 1. Prepare the environment" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import pandas as pd\n", 17 | "from Label_Bot.label_bot import utils" 18 | ] 19 | }, 20 | { 21 | "cell_type": "markdown", 22 | "metadata": {}, 23 | "source": [ 24 | "## 1.1. Load the full dataset\n", 25 | "More versions of the dataset can be found in **http://cs-people.bu.edu/giorgos/labelbot**. " 26 | ] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": 2, 31 | "metadata": {}, 32 | "outputs": [], 33 | "source": [ 34 | "base_url = 'http://cs-people.bu.edu/giorgos/labelbot/'\n", 35 | "\n", 36 | "url = base_url + 'github.pkl'" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": 3, 42 | "metadata": {}, 43 | "outputs": [], 44 | "source": [ 45 | "df = pd.read_pickle(url)" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": 4, 51 | "metadata": {}, 52 | "outputs": [ 53 | { 54 | "data": { 55 | "text/html": [ 56 | "
\n", 57 | "\n", 70 | "\n", 71 | " \n", 72 | " \n", 73 | " \n", 74 | " \n", 75 | " \n", 76 | " \n", 77 | " \n", 78 | " \n", 79 | " \n", 80 | " \n", 81 | " \n", 82 | " \n", 83 | " \n", 84 | " \n", 85 | " \n", 86 | " \n", 87 | " \n", 88 | " \n", 89 | " \n", 90 | " \n", 91 | " \n", 92 | " \n", 93 | " \n", 94 | " \n", 95 | " \n", 96 | " \n", 97 | " \n", 98 | " \n", 99 | " \n", 100 | " \n", 101 | " \n", 102 | " \n", 103 | " \n", 104 | " \n", 105 | " \n", 106 | " \n", 107 | " \n", 108 | " \n", 109 | " \n", 110 | " \n", 111 | " \n", 112 | " \n", 113 | " \n", 114 | " \n", 115 | " \n", 116 | " \n", 117 | " \n", 118 | " \n", 119 | " \n", 120 | " \n", 121 | " \n", 122 | " \n", 123 | " \n", 124 | " \n", 125 | " \n", 126 | " \n", 127 | " \n", 128 | " \n", 129 | "
Labels PresentFractionExamples
0Bug0.4394701395227
1Question0.085425271206
2Enhancement0.4444261410962
3Bug, Question0.0004601459
4Bug, Enhancement0.0016765322
5Question, Enhancement0.0004301365
6Bug, Question, Enhancement0.0000025
7Total1.0000003174798
\n", 130 | "
" 131 | ], 132 | "text/plain": [ 133 | " Labels Present Fraction Examples\n", 134 | "0 Bug 0.439470 1395227\n", 135 | "1 Question 0.085425 271206\n", 136 | "2 Enhancement 0.444426 1410962\n", 137 | "3 Bug, Question 0.000460 1459\n", 138 | "4 Bug, Enhancement 0.001676 5322\n", 139 | "5 Question, Enhancement 0.000430 1365\n", 140 | "6 Bug, Question, Enhancement 0.000002 5\n", 141 | "7 Total 1.000000 3174798" 142 | ] 143 | }, 144 | "execution_count": 4, 145 | "metadata": {}, 146 | "output_type": "execute_result" 147 | } 148 | ], 149 | "source": [ 150 | "utils.get_labels_stats(df)" 151 | ] 152 | }, 153 | { 154 | "cell_type": "markdown", 155 | "metadata": {}, 156 | "source": [ 157 | "
\n", 158 | "\n", 159 | "# 2. Prepare the dataset for Masked Language Modeling\n", 160 | "\n", 161 | "**You should skip this section if you're not interested in Language Modeling!**" 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": null, 167 | "metadata": {}, 168 | "outputs": [], 169 | "source": [ 170 | "df, _ = utils.split_train_test(df, \n", 171 | " train_frac=.125, \n", 172 | " save=False)" 173 | ] 174 | }, 175 | { 176 | "cell_type": "code", 177 | "execution_count": null, 178 | "metadata": {}, 179 | "outputs": [], 180 | "source": [ 181 | "df, mlm_df = utils.split_train_test(df, \n", 182 | " save=False)" 183 | ] 184 | }, 185 | { 186 | "cell_type": "code", 187 | "execution_count": null, 188 | "metadata": {}, 189 | "outputs": [], 190 | "source": [ 191 | "mlm_df_train, mlm_df_val, mlm_df_test = utils.split_train_test(mlm_df, \n", 192 | " save=False, \n", 193 | " validation=True, \n", 194 | " to_keep=['title', 'body'])" 195 | ] 196 | }, 197 | { 198 | "cell_type": "code", 199 | "execution_count": null, 200 | "metadata": {}, 201 | "outputs": [], 202 | "source": [ 203 | "utils.df_to_txt(mlm_df_train, name='train')\n", 204 | "utils.df_to_txt(mlm_df_val, name='val')\n", 205 | "utils.df_to_txt(mlm_df_test, name='test')\n", 206 | "\n", 207 | "del mlm_df, mlm_df_train, mlm_df_val, mlm_df_test" 208 | ] 209 | }, 210 | { 211 | "cell_type": "markdown", 212 | "metadata": {}, 213 | "source": [ 214 | "
\n", 215 | "\n", 216 | "# 3. Prepare the dataset for classification" 217 | ] 218 | }, 219 | { 220 | "cell_type": "markdown", 221 | "metadata": {}, 222 | "source": [ 223 | "## 3.1. Sample the dataset\n", 224 | "We randomly keep only 90,000 examples from each class. Because the dataframe that corresponds to combinations of classes is too small, we keep all of its examples. If you plan to fine-tune the model on your own, you can use a bigger dataset as well; I used this size due to RAM issues. \n", 225 | "\n", 226 | "Keep in mind that for the classification dataset, we use only datapoints that haven't been seen by our language model, meaning that we don't sample from the 400k datapoints of the language modeling dataset. " 227 | ] 228 | }, 229 | { 230 | "cell_type": "code", 231 | "execution_count": 5, 232 | "metadata": {}, 233 | "outputs": [], 234 | "source": [ 235 | "sample_size = int(9e+4)\n", 236 | "name = f'{int(sample_size / 1000)}k'" 237 | ] 238 | }, 239 | { 240 | "cell_type": "code", 241 | "execution_count": 6, 242 | "metadata": {}, 243 | "outputs": [], 244 | "source": [ 245 | "bugs_df, questions_df, enhancements_df, combinations_df = utils.sample_df(df, \n", 246 | " n=sample_size, \n", 247 | " to_keep=['title', \n", 248 | " 'body', \n", 249 | " 'label_bug', \n", 250 | " 'label_question', \n", 251 | " 'label_enhancement'])" 252 | ] 253 | }, 254 | { 255 | "cell_type": "markdown", 256 | "metadata": {}, 257 | "source": [ 258 | "## 3.2. Split to train, test and validation sets. \n", 259 | "By default the split is done 70/30." 260 | ] 261 | }, 262 | { 263 | "cell_type": "code", 264 | "execution_count": 7, 265 | "metadata": {}, 266 | "outputs": [], 267 | "source": [ 268 | "to_keep=['title', 'body', 'label_bug', 'label_question', 'label_enhancement']" 269 | ] 270 | }, 271 | { 272 | "cell_type": "code", 273 | "execution_count": 8, 274 | "metadata": {}, 275 | "outputs": [], 276 | "source": [ 277 | "bugs_train, bugs_val, bugs_test = utils.split_train_test(bugs_df, \n", 278 | " save=False, \n", 279 | " validation=True, \n", 280 | " to_keep=to_keep)\n", 281 | "\n", 282 | "questions_train, questions_val, questions_test = utils.split_train_test(questions_df, \n", 283 | " save=False, \n", 284 | " validation=True, \n", 285 | " to_keep=to_keep)\n", 286 | "\n", 287 | "enhancements_train, enhancements_val, enhancements_test = utils.split_train_test(enhancements_df, \n", 288 | " save=False, \n", 289 | " validation=True, \n", 290 | " to_keep=to_keep)\n", 291 | "\n", 292 | "combinations_train, combinations_val, combinations_test = utils.split_train_test(combinations_df, \n", 293 | " save=False, \n", 294 | " validation=True, \n", 295 | " to_keep=to_keep)" 296 | ] 297 | }, 298 | { 299 | "cell_type": "code", 300 | "execution_count": 9, 301 | "metadata": {}, 302 | "outputs": [], 303 | "source": [ 304 | "train_df = pd.concat((bugs_train, \n", 305 | " questions_train, \n", 306 | " enhancements_train, \n", 307 | " combinations_train), axis=0, ignore_index=True)\n", 308 | "\n", 309 | "val_df = pd.concat((bugs_val, \n", 310 | " questions_val, \n", 311 | " enhancements_val, \n", 312 | " combinations_val), axis=0, ignore_index=True)\n", 313 | "\n", 314 | "test_df = pd.concat((bugs_test, \n", 315 | " questions_test, \n", 316 | " enhancements_test, \n", 317 | " combinations_test), axis=0, ignore_index=True)" 318 | ] 319 | }, 320 | { 321 | "cell_type": "markdown", 322 | "metadata": {}, 323 | "source": [ 324 | "## 3.3. Shuffle Dataframes" 325 | ] 326 | }, 327 | { 328 | "cell_type": "code", 329 | "execution_count": 10, 330 | "metadata": {}, 331 | "outputs": [], 332 | "source": [ 333 | "train_df = train_df.sample(frac=1)\n", 334 | "val_df = val_df.sample(frac=1)\n", 335 | "test_df = test_df.sample(frac=1)" 336 | ] 337 | }, 338 | { 339 | "cell_type": "markdown", 340 | "metadata": {}, 341 | "source": [ 342 | "## 3.4. Check the distribution of classes in train and test set" 343 | ] 344 | }, 345 | { 346 | "cell_type": "code", 347 | "execution_count": 11, 348 | "metadata": {}, 349 | "outputs": [ 350 | { 351 | "data": { 352 | "text/html": [ 353 | "
\n", 354 | "\n", 367 | "\n", 368 | " \n", 369 | " \n", 370 | " \n", 371 | " \n", 372 | " \n", 373 | " \n", 374 | " \n", 375 | " \n", 376 | " \n", 377 | " \n", 378 | " \n", 379 | " \n", 380 | " \n", 381 | " \n", 382 | " \n", 383 | " \n", 384 | " \n", 385 | " \n", 386 | " \n", 387 | " \n", 388 | " \n", 389 | " \n", 390 | " \n", 391 | " \n", 392 | " \n", 393 | " \n", 394 | " \n", 395 | " \n", 396 | " \n", 397 | " \n", 398 | " \n", 399 | " \n", 400 | " \n", 401 | " \n", 402 | " \n", 403 | " \n", 404 | " \n", 405 | " \n", 406 | " \n", 407 | " \n", 408 | " \n", 409 | " \n", 410 | " \n", 411 | " \n", 412 | " \n", 413 | " \n", 414 | " \n", 415 | " \n", 416 | " \n", 417 | " \n", 418 | " \n", 419 | " \n", 420 | " \n", 421 | " \n", 422 | " \n", 423 | " \n", 424 | " \n", 425 | " \n", 426 | " \n", 427 | " \n", 428 | " \n", 429 | " \n", 430 | " \n", 431 | " \n", 432 | " \n", 433 | " \n", 434 | " \n", 435 | " \n", 436 | " \n", 437 | " \n", 438 | " \n", 439 | " \n", 440 | " \n", 441 | " \n", 442 | " \n", 443 | " \n", 444 | " \n", 445 | " \n", 446 | " \n", 447 | " \n", 448 | " \n", 449 | " \n", 450 | " \n", 451 | " \n", 452 | " \n", 453 | " \n", 454 | " \n", 455 | " \n", 456 | " \n", 457 | " \n", 458 | " \n", 459 | " \n", 460 | " \n", 461 | " \n", 462 | " \n", 463 | " \n", 464 | " \n", 465 | " \n", 466 | " \n", 467 | " \n", 468 | " \n", 469 | " \n", 470 | " \n", 471 | " \n", 472 | " \n", 473 | " \n", 474 | " \n", 475 | " \n", 476 | " \n", 477 | " \n", 478 | " \n", 479 | " \n", 480 | " \n", 481 | " \n", 482 | " \n", 483 | " \n", 484 | " \n", 485 | " \n", 486 | " \n", 487 | " \n", 488 | " \n", 489 | " \n", 490 | " \n", 491 | " \n", 492 | " \n", 493 | " \n", 494 | " \n", 495 | " \n", 496 | " \n", 497 | " \n", 498 | " \n", 499 | " \n", 500 | " \n", 501 | " \n", 502 | " \n", 503 | " \n", 504 | " \n", 505 | " \n", 506 | " \n", 507 | " \n", 508 | " \n", 509 | " \n", 510 | " \n", 511 | " \n", 512 | " \n", 513 | " \n", 514 | "
Original DatasetTrainValTest
Labels PresentFractionExamplesLabels PresentFractionExamplesLabels PresentFractionExamplesLabels PresentFractionExamples
0Bug0.4394701395227Bug0.32356556700Bug0.3235736299Bug0.32356327001
1Question0.085425271206Question0.32356556700Question0.3235736299Question0.32356327001
2Enhancement0.4444261410962Enhancement0.32356556700Enhancement0.3235736299Enhancement0.32356327001
3Bug, Question0.0004601459Bug, Question0.005227916Bug, Question0.005496107Bug, Question0.005225436
4Bug, Enhancement0.0016765322Bug, Enhancement0.0192143367Bug, Enhancement0.018801366Bug, Enhancement0.0190421589
5Question, Enhancement0.0004301365Question, Enhancement0.004845849Question, Enhancement0.00498397Question, Enhancement0.005021419
6Bug, Question, Enhancement0.0000025Bug, Question, Enhancement0.0000173Bug, Question, Enhancement0.0000000Bug, Question, Enhancement0.0000242
7Total1.0000003174798Total1.000000175235Total1.00000019467Total1.00000083449
\n", 515 | "
" 516 | ], 517 | "text/plain": [ 518 | " Original Dataset Train \\\n", 519 | " Labels Present Fraction Examples Labels Present \n", 520 | "0 Bug 0.439470 1395227 Bug \n", 521 | "1 Question 0.085425 271206 Question \n", 522 | "2 Enhancement 0.444426 1410962 Enhancement \n", 523 | "3 Bug, Question 0.000460 1459 Bug, Question \n", 524 | "4 Bug, Enhancement 0.001676 5322 Bug, Enhancement \n", 525 | "5 Question, Enhancement 0.000430 1365 Question, Enhancement \n", 526 | "6 Bug, Question, Enhancement 0.000002 5 Bug, Question, Enhancement \n", 527 | "7 Total 1.000000 3174798 Total \n", 528 | "\n", 529 | " Val \\\n", 530 | " Fraction Examples Labels Present Fraction Examples \n", 531 | "0 0.323565 56700 Bug 0.323573 6299 \n", 532 | "1 0.323565 56700 Question 0.323573 6299 \n", 533 | "2 0.323565 56700 Enhancement 0.323573 6299 \n", 534 | "3 0.005227 916 Bug, Question 0.005496 107 \n", 535 | "4 0.019214 3367 Bug, Enhancement 0.018801 366 \n", 536 | "5 0.004845 849 Question, Enhancement 0.004983 97 \n", 537 | "6 0.000017 3 Bug, Question, Enhancement 0.000000 0 \n", 538 | "7 1.000000 175235 Total 1.000000 19467 \n", 539 | "\n", 540 | " Test \n", 541 | " Labels Present Fraction Examples \n", 542 | "0 Bug 0.323563 27001 \n", 543 | "1 Question 0.323563 27001 \n", 544 | "2 Enhancement 0.323563 27001 \n", 545 | "3 Bug, Question 0.005225 436 \n", 546 | "4 Bug, Enhancement 0.019042 1589 \n", 547 | "5 Question, Enhancement 0.005021 419 \n", 548 | "6 Bug, Question, Enhancement 0.000024 2 \n", 549 | "7 Total 1.000000 83449 " 550 | ] 551 | }, 552 | "execution_count": 11, 553 | "metadata": {}, 554 | "output_type": "execute_result" 555 | } 556 | ], 557 | "source": [ 558 | "df_stats = utils.get_labels_stats(df)\n", 559 | "train_stats = utils.get_labels_stats(train_df)\n", 560 | "val_stats = utils.get_labels_stats(val_df)\n", 561 | "test_stats = utils.get_labels_stats(test_df)\n", 562 | "\n", 563 | "pd.DataFrame(pd.concat([df_stats, \n", 564 | " train_stats, \n", 565 | " val_stats, \n", 566 | " test_stats], \n", 567 | " axis=1, \n", 568 | " keys=['Original Dataset', 'Train', 'Val', 'Test']))" 569 | ] 570 | }, 571 | { 572 | "cell_type": "markdown", 573 | "metadata": {}, 574 | "source": [ 575 | "## 3.5. Save the train and test set" 576 | ] 577 | }, 578 | { 579 | "cell_type": "code", 580 | "execution_count": 12, 581 | "metadata": {}, 582 | "outputs": [], 583 | "source": [ 584 | "train_df.to_pickle(f'train_{name}.pkl')\n", 585 | "val_df.to_pickle(f'val_{name}.pkl')\n", 586 | "test_df.to_pickle(f'test_{name}.pkl')" 587 | ] 588 | }, 589 | { 590 | "cell_type": "code", 591 | "execution_count": null, 592 | "metadata": {}, 593 | "outputs": [], 594 | "source": [] 595 | } 596 | ], 597 | "metadata": { 598 | "kernelspec": { 599 | "display_name": "Python 3", 600 | "language": "python", 601 | "name": "python3" 602 | }, 603 | "language_info": { 604 | "codemirror_mode": { 605 | "name": "ipython", 606 | "version": 3 607 | }, 608 | "file_extension": ".py", 609 | "mimetype": "text/x-python", 610 | "name": "python", 611 | "nbconvert_exporter": "python", 612 | "pygments_lexer": "ipython3", 613 | "version": "3.6.9" 614 | } 615 | }, 616 | "nbformat": 4, 617 | "nbformat_minor": 2 618 | } 619 | -------------------------------------------------------------------------------- /notebooks/label_mapping.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "demo_label_mapping.ipynb", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "accelerator": "GPU" 15 | }, 16 | "cells": [ 17 | { 18 | "cell_type": "markdown", 19 | "metadata": { 20 | "id": "0FcSAmw4-4ZL", 21 | "colab_type": "text" 22 | }, 23 | "source": [ 24 | "# **1. Prepare the environment**" 25 | ] 26 | }, 27 | { 28 | "cell_type": "markdown", 29 | "metadata": { 30 | "id": "VPyBsXRM---j", 31 | "colab_type": "text" 32 | }, 33 | "source": [ 34 | "## **Fetch the \"Label-Bot\" repo and modify it so that it can be used in colab**" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "metadata": { 40 | "id": "iC0yuU3Y-08P", 41 | "colab_type": "code", 42 | "colab": {} 43 | }, 44 | "source": [ 45 | "!git clone https://github.com/GiorgosKarantonis/Label-Bot\n", 46 | "\n", 47 | "!mv Label-Bot Label_Bot\n", 48 | "!touch Label_Bot/__init__.py" 49 | ], 50 | "execution_count": null, 51 | "outputs": [] 52 | }, 53 | { 54 | "cell_type": "markdown", 55 | "metadata": { 56 | "id": "Na6mbeCB_IFQ", 57 | "colab_type": "text" 58 | }, 59 | "source": [ 60 | "\n", 61 | "## **Mount google drive in order to be able to access the preprocessed dataset**" 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "metadata": { 67 | "id": "T79eu96__HyE", 68 | "colab_type": "code", 69 | "colab": {} 70 | }, 71 | "source": [ 72 | "from google.colab import drive\n", 73 | "drive.mount('/content/drive')" 74 | ], 75 | "execution_count": null, 76 | "outputs": [] 77 | }, 78 | { 79 | "cell_type": "markdown", 80 | "metadata": { 81 | "id": "aqUbxDn-_M5L", 82 | "colab_type": "text" 83 | }, 84 | "source": [ 85 | "# **2. Prepare the Label Bot**" 86 | ] 87 | }, 88 | { 89 | "cell_type": "markdown", 90 | "metadata": { 91 | "id": "VjtqD7qr_dnU", 92 | "colab_type": "text" 93 | }, 94 | "source": [ 95 | "## **Import all the required libraries**" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "metadata": { 101 | "id": "D80d9iCv_OH6", 102 | "colab_type": "code", 103 | "colab": {} 104 | }, 105 | "source": [ 106 | "import time\n", 107 | "\n", 108 | "import numpy as np\n", 109 | "import pandas as pd\n", 110 | "\n", 111 | "import tensorflow as tf\n", 112 | "\n", 113 | "try:\n", 114 | " from transformers import BertTokenizer, TFBertForSequenceClassification\n", 115 | "except:\n", 116 | " !pip install transformers==3.0.0\n", 117 | " from transformers import BertTokenizer, TFBertForSequenceClassification\n", 118 | "\n", 119 | "import Label_Bot.preprocessing as pp" 120 | ], 121 | "execution_count": 1, 122 | "outputs": [] 123 | }, 124 | { 125 | "cell_type": "markdown", 126 | "metadata": { 127 | "id": "8Eed7WSKCOjr", 128 | "colab_type": "text" 129 | }, 130 | "source": [ 131 | "## **Define the hyperparameters**" 132 | ] 133 | }, 134 | { 135 | "cell_type": "code", 136 | "metadata": { 137 | "id": "OLq6v5Q5_lw8", 138 | "colab_type": "code", 139 | "colab": {} 140 | }, 141 | "source": [ 142 | "MEMORY_LIMIT = 100\n", 143 | "\n", 144 | "LABELS = [\n", 145 | " 'bug', \n", 146 | " 'question', \n", 147 | " 'enhancement'\n", 148 | "]" 149 | ], 150 | "execution_count": 2, 151 | "outputs": [] 152 | }, 153 | { 154 | "cell_type": "markdown", 155 | "metadata": { 156 | "id": "O-YFRhPtCRre", 157 | "colab_type": "text" 158 | }, 159 | "source": [ 160 | "## **Load the dataset**" 161 | ] 162 | }, 163 | { 164 | "cell_type": "code", 165 | "metadata": { 166 | "id": "x9MZcrC4B6L3", 167 | "colab_type": "code", 168 | "colab": {} 169 | }, 170 | "source": [ 171 | "df = pp.load_data(memory_limit=MEMORY_LIMIT, file='./drive/My Drive/Label Bot/data/github_no_merging.pkl')\n", 172 | "\n", 173 | "for c in df.columns:\n", 174 | " if c.startswith('label_'):\n", 175 | " df = df.drop(c, axis=1)" 176 | ], 177 | "execution_count": 3, 178 | "outputs": [] 179 | }, 180 | { 181 | "cell_type": "code", 182 | "metadata": { 183 | "id": "Ms2RlI3fCJkf", 184 | "colab_type": "code", 185 | "colab": { 186 | "base_uri": "https://localhost:8080/", 187 | "height": 343 188 | }, 189 | "outputId": "eafb1937-0110-428a-d1b7-640486d3b166" 190 | }, 191 | "source": [ 192 | "df.head()" 193 | ], 194 | "execution_count": 6, 195 | "outputs": [ 196 | { 197 | "output_type": "execute_result", 198 | "data": { 199 | "text/html": [ 200 | "
\n", 201 | "\n", 214 | "\n", 215 | " \n", 216 | " \n", 217 | " \n", 218 | " \n", 219 | " \n", 220 | " \n", 221 | " \n", 222 | " \n", 223 | " \n", 224 | " \n", 225 | " \n", 226 | " \n", 227 | " \n", 228 | " \n", 229 | " \n", 230 | " \n", 231 | " \n", 232 | " \n", 233 | " \n", 234 | " \n", 235 | " \n", 236 | " \n", 237 | " \n", 238 | " \n", 239 | " \n", 240 | " \n", 241 | " \n", 242 | " \n", 243 | " \n", 244 | " \n", 245 | " \n", 246 | " \n", 247 | " \n", 248 | " \n", 249 | " \n", 250 | " \n", 251 | " \n", 252 | " \n", 253 | " \n", 254 | " \n", 255 | " \n", 256 | " \n", 257 | " \n", 258 | " \n", 259 | " \n", 260 | " \n", 261 | " \n", 262 | " \n", 263 | " \n", 264 | " \n", 265 | " \n", 266 | " \n", 267 | " \n", 268 | " \n", 269 | " \n", 270 | " \n", 271 | " \n", 272 | " \n", 273 | " \n", 274 | " \n", 275 | " \n", 276 | " \n", 277 | " \n", 278 | " \n", 279 | " \n", 280 | " \n", 281 | " \n", 282 | " \n", 283 | " \n", 284 | " \n", 285 | "
urlrepotitlebodylabelsuserrepo_nameissue_number
0https://github.com/F5Networks/f5-openstack-lba...F5Networks/f5-openstack-lbaasv2-drivertest_l7policies_and_rules.py:testl7basicupdate...title: test_l7policies_and_rules.py:testl7basi...[s3, p3, test-bug]F5Networksf5-openstack-lbaasv2-driver835
1https://github.com/aspnet/Mvc/issues/6339aspnet/Mvctesting all controllers dependency injectioni'm writing integration tests for my applicati...[question]aspnetMvc6339
2https://github.com/ionic-team/ionic-cli/issues...ionic-team/ionic-clitesting ionic4 - serve shows two displays\\r description: \\r ionic serve shows two di...[bug]ionic-teamionic-cli3044
3https://github.com/thefarwind/chip-8/issues/21thefarwind/chip-8tests are all brokenwhen switching chip8 such that the audio, disp...[bug, tests]thefarwindchip-821
4https://github.com/n-sokolov/CoffeeShop/issues/1n-sokolov/CoffeeShoptests for paging_ context _: paging mechanism must be tested...[enhancement]n-sokolovCoffeeShop1
\n", 286 | "
" 287 | ], 288 | "text/plain": [ 289 | " url ... issue_number\n", 290 | "0 https://github.com/F5Networks/f5-openstack-lba... ... 835\n", 291 | "1 https://github.com/aspnet/Mvc/issues/6339 ... 6339\n", 292 | "2 https://github.com/ionic-team/ionic-cli/issues... ... 3044\n", 293 | "3 https://github.com/thefarwind/chip-8/issues/21 ... 21\n", 294 | "4 https://github.com/n-sokolov/CoffeeShop/issues/1 ... 1\n", 295 | "\n", 296 | "[5 rows x 8 columns]" 297 | ] 298 | }, 299 | "metadata": { 300 | "tags": [] 301 | }, 302 | "execution_count": 6 303 | } 304 | ] 305 | }, 306 | { 307 | "cell_type": "markdown", 308 | "metadata": { 309 | "id": "lKOEN4vICarN", 310 | "colab_type": "text" 311 | }, 312 | "source": [ 313 | "# **3. Disambiguate the Labels**" 314 | ] 315 | }, 316 | { 317 | "cell_type": "code", 318 | "metadata": { 319 | "id": "zXx1SzVOBcnc", 320 | "colab_type": "code", 321 | "colab": {} 322 | }, 323 | "source": [ 324 | "unique_labels = pp.get_unique_values(df, 'labels').keys().values\n", 325 | "\n", 326 | "paraphrase_candidates = pp.make_combinations(LABELS, unique_labels)\n", 327 | "paraphrase_likelihood = pp.check_paraphrase(paraphrase_candidates)\n", 328 | "\n", 329 | "label_mapping = {}\n", 330 | "for i, pair in enumerate(paraphrase_candidates):\n", 331 | " if paraphrase_likelihood[i] > .5:\n", 332 | " target_l, real_l = pair[0], pair[1]\n", 333 | " try:\n", 334 | " label_mapping[real_l].append((target_l, paraphrase_likelihood[i]))\n", 335 | " except:\n", 336 | " label_mapping[real_l] = []\n", 337 | " label_mapping[real_l].append((target_l, paraphrase_likelihood[i]))" 338 | ], 339 | "execution_count": null, 340 | "outputs": [] 341 | }, 342 | { 343 | "cell_type": "code", 344 | "metadata": { 345 | "id": "swbMpNt3Bdq2", 346 | "colab_type": "code", 347 | "colab": { 348 | "base_uri": "https://localhost:8080/", 349 | "height": 238 350 | }, 351 | "outputId": "af3ea60b-c46b-4cc4-ddc8-944a08b89a7c" 352 | }, 353 | "source": [ 354 | "pd.Series(label_mapping)" 355 | ], 356 | "execution_count": 8, 357 | "outputs": [ 358 | { 359 | "output_type": "execute_result", 360 | "data": { 361 | "text/plain": [ 362 | "bug [(bug, 0.9162983894348145)]\n", 363 | "kind/bug [(bug, 0.8486595153808594)]\n", 364 | "extension-bug [(bug, 0.6228393912315369)]\n", 365 | "type-bug [(bug, 0.7991788387298584)]\n", 366 | "type: bug [(bug, 0.8241775035858154)]\n", 367 | "minor bug [(bug, 0.5306734442710876)]\n", 368 | "bug report [(bug, 0.6632622480392456)]\n", 369 | "type:visual bug [(bug, 0.7715801000595093)]\n", 370 | "question [(question, 0.9274781942367554)]\n", 371 | "enhancement [(enhancement, 0.9370462894439697)]\n", 372 | "kind/enhancement [(enhancement, 0.9053848385810852)]\n", 373 | "doc-enhancement [(enhancement, 0.8313373923301697)]\n", 374 | "dtype: object" 375 | ] 376 | }, 377 | "metadata": { 378 | "tags": [] 379 | }, 380 | "execution_count": 8 381 | } 382 | ] 383 | }, 384 | { 385 | "cell_type": "code", 386 | "metadata": { 387 | "id": "XMNQeBzcBkhd", 388 | "colab_type": "code", 389 | "colab": {} 390 | }, 391 | "source": [ 392 | "label_mapping = pp.disambiguate_labels(label_mapping)" 393 | ], 394 | "execution_count": null, 395 | "outputs": [] 396 | }, 397 | { 398 | "cell_type": "code", 399 | "metadata": { 400 | "id": "hQENayAwBrag", 401 | "colab_type": "code", 402 | "colab": { 403 | "base_uri": "https://localhost:8080/", 404 | "height": 238 405 | }, 406 | "outputId": "c5e43d8e-3577-436f-9dec-9260ee625006" 407 | }, 408 | "source": [ 409 | "pd.Series(label_mapping)" 410 | ], 411 | "execution_count": 10, 412 | "outputs": [ 413 | { 414 | "output_type": "execute_result", 415 | "data": { 416 | "text/plain": [ 417 | "bug bug\n", 418 | "kind/bug bug\n", 419 | "extension-bug bug\n", 420 | "type-bug bug\n", 421 | "type: bug bug\n", 422 | "minor bug bug\n", 423 | "bug report bug\n", 424 | "type:visual bug bug\n", 425 | "question question\n", 426 | "enhancement enhancement\n", 427 | "kind/enhancement enhancement\n", 428 | "doc-enhancement enhancement\n", 429 | "dtype: object" 430 | ] 431 | }, 432 | "metadata": { 433 | "tags": [] 434 | }, 435 | "execution_count": 10 436 | } 437 | ] 438 | }, 439 | { 440 | "cell_type": "code", 441 | "metadata": { 442 | "id": "om-mulXgFAsF", 443 | "colab_type": "code", 444 | "colab": { 445 | "base_uri": "https://localhost:8080/", 446 | "height": 221 447 | }, 448 | "outputId": "07c641ad-f064-47d0-82a1-5e739f322e6a" 449 | }, 450 | "source": [ 451 | "df['labels']" 452 | ], 453 | "execution_count": 11, 454 | "outputs": [ 455 | { 456 | "output_type": "execute_result", 457 | "data": { 458 | "text/plain": [ 459 | "0 [s3, p3, test-bug]\n", 460 | "1 [question]\n", 461 | "2 [bug]\n", 462 | "3 [bug, tests]\n", 463 | "4 [enhancement]\n", 464 | " ... \n", 465 | "95 [extension-bug, status: stale]\n", 466 | "96 [bug, done]\n", 467 | "97 [enhancement]\n", 468 | "98 [bug, pdf previewer]\n", 469 | "99 [bug]\n", 470 | "Name: labels, Length: 100, dtype: object" 471 | ] 472 | }, 473 | "metadata": { 474 | "tags": [] 475 | }, 476 | "execution_count": 11 477 | } 478 | ] 479 | }, 480 | { 481 | "cell_type": "code", 482 | "metadata": { 483 | "id": "Zl5ahOL0BsiM", 484 | "colab_type": "code", 485 | "colab": {} 486 | }, 487 | "source": [ 488 | "df['labels'] = pp.map_labels(df['labels'], label_mapping)" 489 | ], 490 | "execution_count": null, 491 | "outputs": [] 492 | }, 493 | { 494 | "cell_type": "code", 495 | "metadata": { 496 | "id": "CtrgoyBPBv5s", 497 | "colab_type": "code", 498 | "colab": { 499 | "base_uri": "https://localhost:8080/", 500 | "height": 221 501 | }, 502 | "outputId": "611b2964-1e9e-4bf5-8682-6d34576cda47" 503 | }, 504 | "source": [ 505 | "df['labels']" 506 | ], 507 | "execution_count": 13, 508 | "outputs": [ 509 | { 510 | "output_type": "execute_result", 511 | "data": { 512 | "text/plain": [ 513 | "0 [undefined]\n", 514 | "1 [question]\n", 515 | "2 [bug]\n", 516 | "3 [bug]\n", 517 | "4 [enhancement]\n", 518 | " ... \n", 519 | "95 [bug]\n", 520 | "96 [bug]\n", 521 | "97 [enhancement]\n", 522 | "98 [bug]\n", 523 | "99 [bug]\n", 524 | "Name: labels, Length: 100, dtype: object" 525 | ] 526 | }, 527 | "metadata": { 528 | "tags": [] 529 | }, 530 | "execution_count": 13 531 | } 532 | ] 533 | }, 534 | { 535 | "cell_type": "markdown", 536 | "metadata": { 537 | "id": "Nc3gJTnzLb8F", 538 | "colab_type": "text" 539 | }, 540 | "source": [ 541 | "# **4. Finish and vectorize the Labels**" 542 | ] 543 | }, 544 | { 545 | "cell_type": "code", 546 | "metadata": { 547 | "id": "AVkHw0tXBxif", 548 | "colab_type": "code", 549 | "colab": {} 550 | }, 551 | "source": [ 552 | "if 'undefined' not in LABELS:\n", 553 | " LABELS.append('undefined')\n", 554 | "\n", 555 | "labels_vectorized = pp.vectorize(df['labels'], LABELS, prefix='label')\n", 556 | "df = pp.transform(df, to_add=[labels_vectorized])" 557 | ], 558 | "execution_count": null, 559 | "outputs": [] 560 | }, 561 | { 562 | "cell_type": "code", 563 | "metadata": { 564 | "id": "7iejp9rNB07M", 565 | "colab_type": "code", 566 | "colab": { 567 | "base_uri": "https://localhost:8080/", 568 | "height": 419 569 | }, 570 | "outputId": "5e96f59d-61ad-4b92-bb17-4c43d7b09333" 571 | }, 572 | "source": [ 573 | "labels_vectorized" 574 | ], 575 | "execution_count": 15, 576 | "outputs": [ 577 | { 578 | "output_type": "execute_result", 579 | "data": { 580 | "text/html": [ 581 | "
\n", 582 | "\n", 595 | "\n", 596 | " \n", 597 | " \n", 598 | " \n", 599 | " \n", 600 | " \n", 601 | " \n", 602 | " \n", 603 | " \n", 604 | " \n", 605 | " \n", 606 | " \n", 607 | " \n", 608 | " \n", 609 | " \n", 610 | " \n", 611 | " \n", 612 | " \n", 613 | " \n", 614 | " \n", 615 | " \n", 616 | " \n", 617 | " \n", 618 | " \n", 619 | " \n", 620 | " \n", 621 | " \n", 622 | " \n", 623 | " \n", 624 | " \n", 625 | " \n", 626 | " \n", 627 | " \n", 628 | " \n", 629 | " \n", 630 | " \n", 631 | " \n", 632 | " \n", 633 | " \n", 634 | " \n", 635 | " \n", 636 | " \n", 637 | " \n", 638 | " \n", 639 | " \n", 640 | " \n", 641 | " \n", 642 | " \n", 643 | " \n", 644 | " \n", 645 | " \n", 646 | " \n", 647 | " \n", 648 | " \n", 649 | " \n", 650 | " \n", 651 | " \n", 652 | " \n", 653 | " \n", 654 | " \n", 655 | " \n", 656 | " \n", 657 | " \n", 658 | " \n", 659 | " \n", 660 | " \n", 661 | " \n", 662 | " \n", 663 | " \n", 664 | " \n", 665 | " \n", 666 | " \n", 667 | " \n", 668 | " \n", 669 | " \n", 670 | " \n", 671 | " \n", 672 | " \n", 673 | " \n", 674 | " \n", 675 | " \n", 676 | " \n", 677 | " \n", 678 | " \n", 679 | " \n", 680 | " \n", 681 | " \n", 682 | " \n", 683 | " \n", 684 | "
label_buglabel_questionlabel_enhancementlabel_undefined
00.00.00.01.0
10.01.00.00.0
21.00.00.00.0
31.00.00.00.0
40.00.01.00.0
...............
951.00.00.00.0
961.00.00.00.0
970.00.01.00.0
981.00.00.00.0
991.00.00.00.0
\n", 685 | "

100 rows × 4 columns

\n", 686 | "
" 687 | ], 688 | "text/plain": [ 689 | " label_bug label_question label_enhancement label_undefined\n", 690 | "0 0.0 0.0 0.0 1.0\n", 691 | "1 0.0 1.0 0.0 0.0\n", 692 | "2 1.0 0.0 0.0 0.0\n", 693 | "3 1.0 0.0 0.0 0.0\n", 694 | "4 0.0 0.0 1.0 0.0\n", 695 | ".. ... ... ... ...\n", 696 | "95 1.0 0.0 0.0 0.0\n", 697 | "96 1.0 0.0 0.0 0.0\n", 698 | "97 0.0 0.0 1.0 0.0\n", 699 | "98 1.0 0.0 0.0 0.0\n", 700 | "99 1.0 0.0 0.0 0.0\n", 701 | "\n", 702 | "[100 rows x 4 columns]" 703 | ] 704 | }, 705 | "metadata": { 706 | "tags": [] 707 | }, 708 | "execution_count": 15 709 | } 710 | ] 711 | } 712 | ] 713 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /notebooks/train_custom_head.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 1. Prepare the environment" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import os\n", 17 | "import json\n", 18 | "\n", 19 | "import numpy as np\n", 20 | "import pandas as pd\n", 21 | "\n", 22 | "import torch\n", 23 | "import torch.nn as nn\n", 24 | "import torch.optim as optim\n", 25 | "\n", 26 | "from matplotlib import pyplot as plt\n", 27 | "from Label_Bot.label_bot import utils\n", 28 | "\n", 29 | "from sklearn.metrics import accuracy_score as accuracy\n", 30 | "\n", 31 | "from simpletransformers.classification import MultiLabelClassificationModel" 32 | ] 33 | }, 34 | { 35 | "cell_type": "markdown", 36 | "metadata": {}, 37 | "source": [ 38 | "## 1.1. Load the fine-tuned model" 39 | ] 40 | }, 41 | { 42 | "cell_type": "code", 43 | "execution_count": 2, 44 | "metadata": {}, 45 | "outputs": [], 46 | "source": [ 47 | "model_path = 'models/classification/roberta-base'\n", 48 | "\n", 49 | "with open(f'{model_path}/model_args.json') as f:\n", 50 | " model_args = json.load(f)\n", 51 | "\n", 52 | "model = utils.load_model(model_args, task='mlc', from_path=model_path)" 53 | ] 54 | }, 55 | { 56 | "cell_type": "markdown", 57 | "metadata": {}, 58 | "source": [ 59 | "## 1.2. Prepare the datasets\n", 60 | "\n", 61 | "The original model is fine-tuned in a big dataset, which is great but has a serious drawback; the lack of enough training examples that have more than one labels. If we retain here the original distribution, this issue is not going to be addressed, so instead we use all the examples that have multiple labels and for each of the rest of the classes we keep as many examples we keep only as many as the number of examples that have multiple labels. \n", 62 | "\n", 63 | "Although this partially solves the problem, there are a couple of things we need to consider: \n", 64 | "
    \n", 65 | "
  • \n", 66 | " Some combinations are still underrepresented and since the number of examples of these combinations is quite small, if we want to fully solve this issue we have to augment the original dataset either physically or synthetically, with more examples that fall in more than one categories. \n", 67 | "
  • \n", 68 | "
    \n", 69 | "
  • \n", 70 | " Ideally, instead of the raw scores we would feed the logits of the fine-tuned model to the head, but due to the fact that these logits aren't returned if we want to get them we have to clone and tweak the code of the used library. \n", 71 | "
  • \n", 72 | "
    \n", 73 | "
  • \n", 74 | " Using the additional head can have an extra benefit. If we had used fewer examples during the fine-tuning, the head could boost the results significantly. For example, when I used 20k examples from each class during the fine-tuning phase (instead of 90k), the additional of the head significantly increased the score of almost all of the metrics that are used for evaluation in the stats.ipynb file. \n", 75 | "
  • \n", 76 | "
" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": 12, 82 | "metadata": {}, 83 | "outputs": [], 84 | "source": [ 85 | "bugs_train, questions_train, enhancements_train, comb_train = utils.sample_df(pd.read_pickle('train_90k.pkl'), \n", 86 | " n=5000, \n", 87 | " to_keep=['title', \n", 88 | " 'body', \n", 89 | " 'label_bug', \n", 90 | " 'label_question', \n", 91 | " 'label_enhancement'])\n", 92 | "\n", 93 | "bugs_val, questions_val, enhancements_val, comb_val = utils.sample_df(pd.read_pickle('val_90k.pkl'), \n", 94 | " n=550, \n", 95 | " to_keep=['title', \n", 96 | " 'body', \n", 97 | " 'label_bug', \n", 98 | " 'label_question', \n", 99 | " 'label_enhancement'])" 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": 13, 105 | "metadata": {}, 106 | "outputs": [], 107 | "source": [ 108 | "train_df = pd.concat((bugs_train, \n", 109 | " questions_train, \n", 110 | " enhancements_train, \n", 111 | " comb_train), axis=0, ignore_index=True)\n", 112 | "\n", 113 | "val_df = pd.concat((bugs_val, \n", 114 | " questions_val, \n", 115 | " enhancements_val, \n", 116 | " comb_val), axis=0, ignore_index=True)" 117 | ] 118 | }, 119 | { 120 | "cell_type": "markdown", 121 | "metadata": {}, 122 | "source": [ 123 | "### 1.2.1. Calculate the scores and save them for future use" 124 | ] 125 | }, 126 | { 127 | "cell_type": "code", 128 | "execution_count": null, 129 | "metadata": {}, 130 | "outputs": [], 131 | "source": [ 132 | "scores = model.predict(val_df.title)[1]\n", 133 | "np.save(f'val_scores_titles', scores)\n", 134 | "\n", 135 | "scores = model.predict(val_df.body)[1]\n", 136 | "np.save(f'val_scores_bodies', scores)\n", 137 | "\n", 138 | "scores = model.predict(val_df.title + ' ' + val_df.body)[1]\n", 139 | "np.save(f'val_scores_combined', scores)\n", 140 | "\n", 141 | "np.save(f'val_scores_labels', utils.make_st_compatible(val_df).labels)\n", 142 | "\n", 143 | "\n", 144 | "scores = model.predict(train_df.title)[1]\n", 145 | "np.save(f'train_scores_titles', scores)\n", 146 | "\n", 147 | "scores = model.predict(train_df.body)[1]\n", 148 | "np.save(f'train_scores_bodies', scores)\n", 149 | "\n", 150 | "scores = model.predict(train_df.title + ' ' + train_df.body)[1]\n", 151 | "np.save(f'train_scores_combined', scores)\n", 152 | "\n", 153 | "np.save(f'train_scores_labels', utils.make_st_compatible(train_df).labels)" 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "execution_count": 15, 159 | "metadata": {}, 160 | "outputs": [], 161 | "source": [ 162 | "train_scores_titles = np.load('train_scores_titles.npy')\n", 163 | "train_scores_bodies = np.load('train_scores_bodies.npy')\n", 164 | "train_scores_combined = np.load('train_scores_combined.npy')\n", 165 | "\n", 166 | "train_labels = np.load('train_scores_labels.npy', allow_pickle=True)\n", 167 | "train_labels = list(map(list, train_labels))\n", 168 | "\n", 169 | "\n", 170 | "val_scores_titles = np.load('val_scores_titles.npy')\n", 171 | "val_scores_bodies = np.load('val_scores_bodies.npy')\n", 172 | "val_scores_combined = np.load('val_scores_combined.npy')\n", 173 | "\n", 174 | "val_labels = np.load('val_scores_labels.npy', allow_pickle=True)\n", 175 | "val_labels = list(map(list, val_labels))" 176 | ] 177 | }, 178 | { 179 | "cell_type": "markdown", 180 | "metadata": {}, 181 | "source": [ 182 | "
\n", 183 | "\n", 184 | "# 2. Train the head on top of the fine-tuned model" 185 | ] 186 | }, 187 | { 188 | "cell_type": "markdown", 189 | "metadata": {}, 190 | "source": [ 191 | "## 2.1. Define the Additional Head\n", 192 | "\n", 193 | "You can also try using your own custom head by defining a list of PyTorch layers and passing using it when you initialize the head object. For example: \n", 194 | "\n", 195 | "```Python\n", 196 | "my_head = [\n", 197 | " nn.Linear(9, 20), \n", 198 | " nn.ReLU(), \n", 199 | " nn.Linear(20, 3)\n", 200 | "]\n", 201 | "head = ScoresHead(my_head)\n", 202 | "```\n", 203 | "\n", 204 | "**Note that after the last layer there is no activation.** This is because we're doing multilabel classification, so a sigmoid is by default in the forward function. \n", 205 | "\n", 206 | "Additionally, if you want to make a more complex model you can simply replace the forward function. " 207 | ] 208 | }, 209 | { 210 | "cell_type": "code", 211 | "execution_count": 16, 212 | "metadata": {}, 213 | "outputs": [], 214 | "source": [ 215 | "class ScoresHead(nn.Module):\n", 216 | " def __init__(self, custom_head=None):\n", 217 | " super().__init__()\n", 218 | " self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", 219 | " \n", 220 | " self.loss = nn.BCELoss()\n", 221 | " self.optimizer = optim.Adam\n", 222 | " \n", 223 | " head = custom_head if custom_head else self.default_head()\n", 224 | " self.model = nn.Sequential(*head).to(self.device)\n", 225 | " \n", 226 | " \n", 227 | " def default_head(self):\n", 228 | " return [\n", 229 | " nn.Linear(9, 100), \n", 230 | " nn.LeakyReLU(.2), \n", 231 | " nn.BatchNorm1d(100), \n", 232 | " nn.Linear(100, 3)\n", 233 | " ]\n", 234 | " \n", 235 | " \n", 236 | " def forward(self, titles, bodies, combined, train=True):\n", 237 | " if train: \n", 238 | " self.model = self.model.train()\n", 239 | " else:\n", 240 | " self.model = self.model.eval()\n", 241 | "\n", 242 | " x = torch.cat((titles, bodies, combined), dim=1).to(self.device)\n", 243 | " x = self.model(x)\n", 244 | " x = torch.sigmoid(x)\n", 245 | " \n", 246 | " return x\n", 247 | " \n", 248 | " \n", 249 | " def fit(self, \n", 250 | " titles, \n", 251 | " bodies, \n", 252 | " combined, \n", 253 | " labels, \n", 254 | " validation=True, \n", 255 | " val_titles=None, \n", 256 | " val_bodies=None, \n", 257 | " val_combined=None, \n", 258 | " val_labels=None, \n", 259 | " epochs=35, \n", 260 | " lr=5e-3, \n", 261 | " verbose=True):\n", 262 | " \n", 263 | " losses = {\n", 264 | " 'train' : [], \n", 265 | " 'val' : []\n", 266 | " }\n", 267 | " \n", 268 | " optimizer = self.optimizer(self.model.parameters(), lr=lr)\n", 269 | " \n", 270 | " labels = np.array(labels)\n", 271 | " \n", 272 | " for epoch in range(epochs):\n", 273 | " indices = np.arange(titles.shape[0])\n", 274 | " np.random.shuffle(indices)\n", 275 | "\n", 276 | " titles = titles[indices]\n", 277 | " bodies = bodies[indices]\n", 278 | " combined = combined[indices]\n", 279 | " labels = labels[indices]\n", 280 | " \n", 281 | " titles_tensor = torch.from_numpy(titles).to(self.device)\n", 282 | " bodies_tensor = torch.from_numpy(bodies).to(self.device)\n", 283 | " combined_tensor = torch.from_numpy(combined).to(self.device)\n", 284 | " \n", 285 | " labels = torch.FloatTensor(list(map(list, labels))).to(self.device)\n", 286 | " \n", 287 | " optimizer.zero_grad()\n", 288 | " outputs = self.forward(titles_tensor, bodies_tensor, combined_tensor)\n", 289 | " \n", 290 | " loss = self.loss(outputs, labels)\n", 291 | " \n", 292 | " loss.backward()\n", 293 | " optimizer.step()\n", 294 | " \n", 295 | " losses['train'].append(loss.item())\n", 296 | " if validation:\n", 297 | " val_loss = self.evaluate(val_titles, val_bodies, val_combined, val_labels)\n", 298 | " losses['val'].append(val_loss)\n", 299 | " \n", 300 | " if verbose:\n", 301 | " print(f'Epoch: {epoch+1}')\n", 302 | " print(f'Training loss: {loss.item()}')\n", 303 | " if validation:\n", 304 | " print(f'Validation loss: {val_loss}')\n", 305 | " print('Validation Accuracy: ', accuracy(np.where(outputs.detach().cpu().numpy() > .5, 1, 0), \n", 306 | " labels.detach().cpu().numpy()))\n", 307 | " print()\n", 308 | " \n", 309 | " return outputs.detach().cpu().numpy(), losses\n", 310 | " \n", 311 | " \n", 312 | " def evaluate(self, titles, bodies, combined, labels):\n", 313 | " losses = []\n", 314 | " \n", 315 | " titles_tensor = torch.from_numpy(titles).to(self.device)\n", 316 | " bodies_tensor = torch.from_numpy(bodies).to(self.device)\n", 317 | " combined_tensor = torch.from_numpy(combined).to(self.device)\n", 318 | " \n", 319 | " labels = torch.FloatTensor(list(map(list, labels))).to(self.device)\n", 320 | " \n", 321 | " outputs = self.forward(titles_tensor, bodies_tensor, combined_tensor, train=False)\n", 322 | " \n", 323 | " loss = self.loss(outputs, labels)\n", 324 | " \n", 325 | " return loss.detach().cpu().item()\n", 326 | " \n", 327 | " \n", 328 | " def predict(self, titles, bodies, combined):\n", 329 | " titles_tensor = torch.from_numpy(titles).to(self.device)\n", 330 | " bodies_tensor = torch.from_numpy(bodies).to(self.device)\n", 331 | " combined_tensor = torch.from_numpy(combined).to(self.device)\n", 332 | " \n", 333 | " predictions = self.forward(titles_tensor, bodies_tensor, combined_tensor, train=False)\n", 334 | " \n", 335 | " return predictions.detach().cpu().numpy()" 336 | ] 337 | }, 338 | { 339 | "cell_type": "markdown", 340 | "metadata": {}, 341 | "source": [ 342 | "## 2.2. Define the hyperparameters and start the training" 343 | ] 344 | }, 345 | { 346 | "cell_type": "code", 347 | "execution_count": null, 348 | "metadata": { 349 | "scrolled": true 350 | }, 351 | "outputs": [], 352 | "source": [ 353 | "EPOCHS = 35\n", 354 | "\n", 355 | "head = ScoresHead()\n", 356 | "model_outputs, losses = head.fit(train_scores_titles, \n", 357 | " train_scores_bodies, \n", 358 | " train_scores_combined, \n", 359 | " train_labels, \n", 360 | " val_titles=val_scores_titles, \n", 361 | " val_bodies=val_scores_bodies, \n", 362 | " val_combined=val_scores_combined, \n", 363 | " val_labels=val_labels, \n", 364 | " verbose=True, \n", 365 | " epochs=EPOCHS)" 366 | ] 367 | }, 368 | { 369 | "cell_type": "markdown", 370 | "metadata": {}, 371 | "source": [ 372 | "## 2.3. Visualize the training results" 373 | ] 374 | }, 375 | { 376 | "cell_type": "code", 377 | "execution_count": 18, 378 | "metadata": {}, 379 | "outputs": [ 380 | { 381 | "data": { 382 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYgAAAEWCAYAAAB8LwAVAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy86wFpkAAAACXBIWXMAAAsTAAALEwEAmpwYAAA9xUlEQVR4nO3dd3hUZfrw8e+dQhISSkJCgCRAghQhJIEEEOmWFcUFEVCKCuu6lvcHqGt3i4rrrrtrW3ZRxN4RRBFFZNFVQZESehPppNB7CaQ97x/nZBzCJCQkM2dC7s91nWvm9HtGmTtPOc8jxhiUUkqp0gKcDkAppZR/0gShlFLKI00QSimlPNIEoZRSyiNNEEoppTzSBKG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Gtp+KOO6juOFxS/w8YaPnQhBKVVFY8aM4c4776Rbt248+OCDLFmyhO7du9OpUycuvfRSNm7cCMC3337LtddeC1jJ5dZbb6Vv374kJSUxceLECt9v+/btXHbZZaSkpHD55Zezc+dOAKZPn05ycjKpqan07m1Np75u3Tq6du1KWloaKSkpbNq0qZo/vXd4s5trHNYk5iWyOXv6wTYAIvIDEAg8bowpmV4yVEQygULgaWPMTC/Gyj+v/CeLshdx66e3khqbSquoVt68nVIXjmX3wKGV1XvNyDRIf6HSp2VnZ7Nw4UICAwM5evQoCxYsICgoiK+++opHH32UGTNmnHXOTz/9xDfffMOxY8do27Ytd911V4WeFRg3bhyjR49m9OjRvP7664wfP56ZM2cyYcIE5s6dS1xcHIcPHwZg8uTJ3H333YwaNYr8/HyKiooq/dmc4HQjdRDQGugLjABeEZGG9r4WxpgMYCTwgoic9YstIreLSKaIZO7bt69KgYQEhfDh0A8REW746AZOFeoDQErVNMOGDSMwMBCAI0eOMGzYMJKTk7n33ntZt26dx3MGDBhASEgI0dHRNG7cmD179lToXj/++CMjR44E4Oabb+b7778HoEePHowZM4ZXXnnFlQi6d+/OX//6V/7+97+zY8cOwsLCqvpRfcKbJYgcIMFtPd7e5i4bWGyMKQC2icjPWAljqTEmB8AYs1VEvgU6AVvcTzbGTAGmAGRkZFR55qPEyETeHPQm1314HffNvY9JAyZV9ZJKXfjO4y99bwkPD3e9/9Of/kS/fv345JNP2L59O3379vV4TkhIiOt9YGAghYWFVYph8uTJLF68mNmzZ5Oens6yZcsYOXIk3bp1Y/bs2VxzzTW8/PLLXHbZZVW6jy94swSxFGgtIokiUgcYDpTujTQTq/SAiERjVTltFZFIEQlx294DWI8PDGo3iPu638eLmS/y4doPfXFLpZQXHDlyhLi4OADefPPNar/+pZdeytSpUwF477336NWrFwBbtmyhW7duTJgwgZiYGLKysti6dStJSUmMHz+eQYMGsXr16mqPxxu8liCMMYXAWGAusAGYZoxZJyITRGSgfdhc4ICIrAe+AR4wxhwALgYyRWSV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sxh0KBBTJ06lRtuuAER4amnniIqKoqioiIuv/xyVq9eTUpKisfrLFu2jKlTp7Jy5UoKCwvp3Lkz6enpAFx//fX87ne/A+CPf/wjr732GuPGjWPgwIFce+21DB069IxrnTp1ijFjxvD111/Tpk0bbrnlFl566SXuueceAKKjo1m+fDkvvvgizzzzDK+++uo5v4fc3Fweeughli1bRmRkJL/61a+YOXMmCQkJ5OTksHbtWgBXddnTTz/Ntm3bCAkJ8ViFVllagoAzE0QF3d3tboZcPISHvnqI73d+76XAlFJlca9mcq9emjZtGp07d6ZTp06sW7fujOqg0hYsWMDgwYOpW7cu9evXZ+DAga59a9eupVevXnTs2JH33nuvzOHCS2zcuJHExETatGkDwOjRo5k/f75r//XXXw9Aeno627dvr9BnXLp0KX379iUmJoagoCBGjRrF/PnzSUpKYuvWrYwbN44vv/yS+vXrA9Z4UaNGjeLdd98tc0a9ytASBEBoYwise86eTO5EhNcGvsaqPau48aMbWXHHChqHNz73iUpdYMr7S9+bBg0axL333svy5cs5efIk6enpbNu2jWeeeYalS5cSGRnJmDFjOHXq/OZ2GTNmDDNnziQ1NZU333yTb7/9tkrxlgwrXh1DikdGRrJq1Srmzp3L5MmTmTZtGq+//jqzZ89m/vz5fPbZZzz11FOsWbOmSolCSxAAIhXuyeSuQWgDpg+bzoGTBxj18SiKimvGLFFKXQgiIiLo168ft956q6v0cPToUcLDw2nQoAF79uxhzpw55V6jd+/ezJw5k7y8PI4dO8Znn33m2nfs2DGaNm1KQUEB7733nmt7vXr1OHbs2FnXatu2Ldu3b2fz5s0AvPPOO/Tp06dKn7Fr165899137N+/n6KiIj744AP69OnD/v37KS4uZsiQIfzlL39h+fLlFBcXk5WVRb9+/fj73//OkSNHOH68ag/2agmiRERSpRMEWHWlk66ZxG2f3caT85/k8b6PV39sSimPRowYweDBg11VTampqXTq1Il27dqRkJBAjx49yj2/c+fO3HjjjaSmptK4cWO6dOni2vfkk0/SrVs3YmJi6NatmyspDB8+nN/97ndMnDjR1TgNEBoay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H3Ab+ztdwNTROS3WCWFu7AmylHKb2gbhFLVwG6DyDDG7Hc6FqWqi1YxKaWU8khLEEoppTzSEoRSSimPNEEopZTySBOEUkopjzRBKKWU8kgThFJKKY/+P5JuZHQPIhUJAAAAAElFTkSuQmCC\n", 383 | "text/plain": [ 384 | "
" 385 | ] 386 | }, 387 | "metadata": { 388 | "needs_background": "light" 389 | }, 390 | "output_type": "display_data" 391 | } 392 | ], 393 | "source": [ 394 | "plt.figure()\n", 395 | "plt.title('Training Performance')\n", 396 | "plt.xlabel('Epoch')\n", 397 | "plt.ylabel('Loss')\n", 398 | "plt.plot([i for i in range(EPOCHS)], losses['train'], color='orange', label='Train Loss')\n", 399 | "plt.plot([i for i in range(EPOCHS)], losses['val'], color='green', label='Validation Loss')\n", 400 | "plt.legend(loc=\"upper right\")\n", 401 | "plt.show()" 402 | ] 403 | }, 404 | { 405 | "cell_type": "markdown", 406 | "metadata": {}, 407 | "source": [ 408 | "## 2.4. Save the trained head\n", 409 | "\n", 410 | "The head is save in the same directory as the fine-tuned model. " 411 | ] 412 | }, 413 | { 414 | "cell_type": "code", 415 | "execution_count": 19, 416 | "metadata": {}, 417 | "outputs": [], 418 | "source": [ 419 | "torch.save(head.state_dict(), os.path.join(model_path, 'scores_head.pt'))" 420 | ] 421 | }, 422 | { 423 | "cell_type": "code", 424 | "execution_count": null, 425 | "metadata": {}, 426 | "outputs": [], 427 | "source": [] 428 | } 429 | ], 430 | "metadata": { 431 | "kernelspec": { 432 | "display_name": "Python 3", 433 | "language": "python", 434 | "name": "python3" 435 | }, 436 | "language_info": { 437 | "codemirror_mode": { 438 | "name": "ipython", 439 | "version": 3 440 | }, 441 | "file_extension": ".py", 442 | "mimetype": "text/x-python", 443 | "name": "python", 444 | "nbconvert_exporter": "python", 445 | "pygments_lexer": "ipython3", 446 | "version": "3.6.9" 447 | } 448 | }, 449 | "nbformat": 4, 450 | "nbformat_minor": 2 451 | } 452 | --------------------------------------------------------------------------------