├── .gitignore ├── LICENSE ├── README.md ├── subtask1 ├── README.md ├── answer_selection │ ├── __init__.py │ ├── data_helpers.py │ ├── eval.py │ ├── metrics.py │ ├── model.py │ └── train.py ├── data │ └── embeddings │ │ └── char_vocab.txt ├── requirements.txt └── scripts │ └── convert_dstc8_data.py └── subtask4 ├── README.md ├── disentangle.model ├── disentangle.py ├── glove-ubuntu.txt ├── reserved_words.py ├── task-4-evaluation.py ├── tokenise.py └── vocab.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Dialog System Technology Challenges 8 (DSTC 8) - Track 2 2 | ## NOESIS II: Predicting Responses, Identifying Success, and Managing Complexity in Task-Oriented Dialogue 3 | 4 | ### Introduction ### 5 | Building on the success of [DSTC 7 Track 1](https://ibm.github.io/dstc-noesis/public/index.html) (NOESIS: Noetic End-to-End Response Selection Challenge), we propose an extension of the task, incorporating new elements that are vital for the creation of a deployed task-oriented dialogue system. Specifically, we add three new dimensions to the challenge: 6 | 1. Conversations with more than 2 participants 7 | 2. Predicting whether a dialogue has solved the problem yet, 8 | 3. Handling multiple simultaneous conversations. 9 | Each of these adds an exciting new dimension and brings the task closer to the creation of systems able to handle the complexity of real-world conversation. 10 | 11 | This challenge is offered with two goal oriented dialog datasets, used in 4 subtasks. A participant may participate in one, several, or all the subtasks. A full description of the track is available [here](https://drive.google.com/file/d/1rCCRsuZ7rq2KGEnT-pBCF6WS47yEsIJA/view). 12 | 13 | **Please visit this webpage often to remain updated about baseline results and more material.** 14 | 15 | ### Ubuntu dataset ### 16 | A new set of disentangled Ubuntu IRC dialogs will be provided in this challenge. The dataset consists of multi party conversations extracted from the Ubuntu IRC channel. A typical dialog starts with a question that was asked by participant_1, and then other partipants responds with either an answer or follow-up questions that then lead to a back-and-forth conversation. In this challenge, the context of each dialog contains more than 3 turns which occurred between the participants and the next turn in the conversation should be selected from the given set of candidate utterances. Relevant external information of the form of Linux manual pages and Ubuntu discussion forums is also provided. 17 | 18 | If you use the Ubuntu data, please also cite the paper in which we describe its creation: 19 | ``` 20 | @InProceedings{acl19disentangle, 21 | author = {Jonathan K. Kummerfeld and Sai R. Gouravajhala and Joseph Peper and Vignesh Athreya and Chulaka Gunasekara and Jatin Ganhotra and Siva Sankalp Patel and Lazaros Polymenakos and Walter S. Lasecki}, 22 | title = {A Large-Scale Corpus for Conversation Disentanglement}, 23 | booktitle = {Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)}, 24 | month = {July}, 25 | year = {2019}, 26 | } 27 | ``` 28 | 29 | ### Advising dataset ### 30 | This dataset contains two party dialogs that simulate a discussion between a student and an academic advisor. The purpose of the dialogs is to guide the student to pick courses that fit not only their curriculum, but also personal preferences about time, difficulty, areas of interest, etc. These conversations were collected by having students at the University of Michigan act as the two roles using provided personas. Structured information in the form of a database of course information will be provided, as well as the personas (though at test time only information available to the advisor will be provided, i.e. not the explicit student preferences). The data also includes paraphrases of the sentences and of the target responses. 31 | 32 | Note: the Advising data is considerably smaller than the Ubuntu data, but more focused in topic. 33 | 34 | ### Sub-tasks ### 35 | We are considered several subtasks that have similar structure, but vary in the output space and available context. In the table below, [x] indicates that the subtask is evaluated on the marked dataset. 36 | 37 | |Subtask number| Description | Ubuntu | Advising | 38 | |--------------| ------------ | ------------ | ------------ | 39 | |1|Given the disentangled conversation, select the next utterance from a candidate pool of 100 which might not contain the correct next utterance | [x] | [x] | 40 | |2|Given a section of the IRC channel, select the next utterance from a candidate pool of 100 which might not contain the correct next utterance | [x] | | 41 | |3|Given a conversation, predict where in the conversation the problem is solved (if at all).||[x] | 42 | |4|Given a section of the IRC channel, identify a set of conversations contained within that section| [x] || 43 | 44 | 45 | ### Data ### 46 | The datasets are available from the following links. 47 | 48 | - Training and dev data - [http://ibm.biz/dstc8_track2_data](http://ibm.biz/dstc8_track2_data) 49 | - Test data - [http://ibm.biz/dstc8_track2_test_data](http://ibm.biz/dstc8_track2_test_data) 50 | - Ground truth of the test data - [http://ibm.biz/dstc8_test_ground_truth](http://ibm.biz/dstc8_test_ground_truth) 51 | 52 | In addition to the training and validation dialog datasets, and extra dataset which includes paraphrases for utterances in advising dataset is also provided. 53 | 54 | The candidate sets that are provided for some dialogs in **subtask 1 and 2** does not include the correct next utterance. 55 | The contestants are expected to train their models in a way that during testing they can identify such cases. 56 | 57 | Additional external information which will be important for dialog modeling will be provided. For Ubuntu dataset, this external information comes in the form of Linux manual pages and Ubuntu discussion forums and for Advising dataset, extra information about courses will be given. 58 | The contestants can use the provided knowledge sources as is, or transform them to appropriate representations (e.g. knowledge graphs, continuous embeddings, etc.) that can be integrated with end-to-end dialog systems to improve accuracy. 59 | 60 | ### Data format #### 61 | 62 | #### Subtask 1, 2 and 3 #### 63 | Each dialog contains in training, validation and test datasets follows the JSON format which is similar to the below example. 64 | ``` 65 | { 66 | "data-split": "train", 67 | "example-id": 0, 68 | "messages-so-far": [ 69 | { 70 | "date": "2007-02-13", 71 | "speaker": "participant_0", 72 | "time": "07:31", 73 | "utterance": "hi guys, i need some urgent help. i \"rm -rf'd\" a direcotry. any way i can recover it?" 74 | }, 75 | { 76 | "date": "2007-02-13", 77 | "speaker": "participant_1", 78 | "time": "07:31", 79 | "utterance": "participant_0 : in short, no." 80 | }, 81 | { 82 | "date": "2007-02-13", 83 | "speaker": "participant_0", 84 | "time": "07:31", 85 | "utterance": "participant_1 , are you sure?" 86 | }, 87 | ... 88 | ], 89 | "options-for-correct-answers": [ 90 | { 91 | "candidate-id": "3d06877cb2f0c1861b248860fa60ce07", 92 | "speaker": "participant_1", 93 | "utterance": "\"Are you sure?\" is something rm -rf never asks.." 94 | } 95 | ], 96 | "options-for-next": [ 97 | { 98 | "candidate-id": "ace962b708d559fc462b7fdd9b6fc093", 99 | "speaker": "participant_1", 100 | "utterance": "(and if hardware is detected correctly, of course)" 101 | }, 102 | { 103 | "candidate-id": "349efca9c3d5986a87d95fb90c1b7c04", 104 | "speaker": "participant_2", 105 | "utterance": "how do i do a simulated reboot" 106 | }, 107 | ... 108 | ], 109 | "scenario": 1 110 | } 111 | ``` 112 | The field `messages-so-far` contains the context of the dialog and `options-for-next` contains the candidates to select the next utterance from. The correct next utterance is given in the field `options-for-correct-answers`. The field `scenario` refers to the subtask. 113 | 114 | For each dialog in advising dataset, we provide a profile that contains information used during the creation of the dialog. It has the following fields: 115 | 116 | - Aggregated - contains student preferences, with each field matching up with a field in the course information file. 117 | - Courses - contains two lists, first is a list of courses this student has taken (“Prior”) and second is a list of suggestions that the advisor had access to (“Suggested”). 118 | - Term - specifies the simulated year and semester for the conversation 119 | - Standing - specifies how far through their degree the student is. 120 | 121 | For subtask 3, the information regarding the success of a conversation is given in the field similar to the following where the `label` indicates whether the conversation is a success or not and `position` indicates the utterance where the conversation is accepted. 122 | ``` 123 | "success-labels": [ 124 | { 125 | "label": "Accept", 126 | "position": 8 127 | } 128 | ] 129 | ``` 130 | 131 | The label can be 'Accept', 'Reject', or 'No Decision Yet'. 132 | There can be multiple labels, to cover cases where the student accepts/rejects multiple advisor suggestions. 133 | If the value is 'No Decision Yet' then the position will be -1. 134 | 'No Decision Yet' appears in the task-1.advising.train.json file, and the dev and test files, but not in the task-1.advising.train.complete.json file (which contains complete conversations rather than partial ones). 135 | 136 | #### Subtask 4 #### 137 | This data is not in the same format as the other subtasks. There are train and dev folders containing a set of files like this: 138 | 139 | - DATE.raw.txt 140 | - DATE.tok.txt 141 | - DATE.ascii.txt 142 | - DATE.annotation.txt 143 | 144 | The `.raw.txt` file is a sample from the IRC log from that day. The `.ascii.txt` file is a version of the raw file that we have converted to ascii. The `.tok.txt` file has the same data agian, but with automatic tokenisation and replacement of rare words with a placeholder symbol. The `.annotation.txt` file contains a series of lines, each describing a link between two messages. For example: `1002 1003 -`. This indicates that message `1002` in the logs should be linked to message `1003`. 145 | 146 | Note: 147 | - Messages are counted starting at 0 and each one is a single line in the logs. 148 | - System messages (e.g. “=== blah has joined #ubuntu”) are counted and annotated. 149 | - A message can be linked to multiple messages both before it and after it. Each link is given separately. 150 | - There are no links where both values are less than 1000. In other words, the annotations specify what each message is a response to, starting from message 1,000. 151 | 152 | ### Baselines ### 153 | Baselines for subtask 1 and 4 are available [here](https://github.com/dstc8-track2/NOESIS-II/tree/baseline). 154 | 155 | ### Evaluation ### 156 | 157 | For subtask 1 and 2, we will expect you to return a set of 100 candidates and a probability distribution over those 100 choices. As competition metrics we will compute range of scores, including recall@k, MRR(mean reciprocal rank). The 158 | final metric will be the average of MRR and recall@10. 159 | 160 | For subtask 3, the participants are expected to return the success or a failiure of the conversation and utterance in which the success is indicated. The participants will be evaluated by the accuracy of identifying success and failure. 161 | 162 | The participants of the subtask 4 will be evaluated based on Precision, recall, and F- 163 | score over complete threads and several clustering metrics (Variation of Information, Adjusted Rand Index, and Adjusted Mutual Information). 164 | 165 | 166 | ### Submission ### 167 | 168 | Your submissions should be emailed to `chulaka.gunasekara@ibm.com`, with the subject line `DSTC8_Track2_Submission`. The results should be submitted from an email address that is registered for Track 2. 169 | 170 | You need to submit a single zipped directory containing the result files for each of the subtasks that you need to be evaluated on. The files should be named `_subtask_.json` for subtasks 1-3 and `Ubuntu_subtask_4.txt` for subtask 4. 171 | 172 | For subtasks 1-3, the `` should be replaced by either `Ubuntu` or `Advising`, and the `` should be replaced by the subtask number(1-3). For example, the results file for subtask 1 on Ubuntu dataset should be named as `Ubuntu_subtask_1.json` 173 | 174 | Each results file for subtask 1 and 2 should follow the following json format. 175 | ``` 176 | [ 177 | { 178 | "example-id": xxxxxxx, 179 | "candidate-ranking":[ 180 | { 181 | "candidate-id": aaaaaa, 182 | "confidence": b.bbb 183 | }, 184 | { 185 | "candidate-id": cccccc, 186 | "confidence": d.ddd 187 | }, 188 | ... 189 | ] 190 | }, 191 | ... 192 | ] 193 | ``` 194 | The value for the field `example-id` should contain the corresponding example-id of the test dataset. The candidate ranking field should ONLY include 100 candidates in the order of confidence. 195 | 196 | When the correct candidate is not available in the candidate set, return `"candidate-id": "NONE"` with the confidence score as an item in the candidate-ranking list. 197 | 198 | The results file for subtask 3 should follow the following format. 199 | ``` 200 | [ 201 | { 202 | "example-id": xxxxxxx, 203 | "success-labels": [ 204 | { 205 | "label": "label", 206 | "position": N 207 | } 208 | ] 209 | }, 210 | ... 211 | ] 212 | ``` 213 | The value for the field `example-id` should contain the corresponding `example-id` of the test dataset. The `label` can be 'Accept', 'Reject', or 'No Decision Yet'. The `position` should be and integer which points to the utterance where the conversation is accepted or rejected. The If the value is 'No Decision Yet' then the position should be -1. 214 | 215 | 216 | The results for subtask 4 should be a submitted by a single file `(Ubuntu_subtask_4.txt)` in the following format: 217 | 218 | ``` 219 | DATE: A B C... 220 | DATE: Q W E R T Y... 221 | ... 222 | ``` 223 | 224 | Where each line describes one cluster for that date (where the date comes from the test input filename). For example, you could have: 225 | 226 | ``` 227 | 2005-07-06 1000 1001 1002 1003 228 | 2005-07-06 1004 1006 229 | 2005-07-06 1005 230 | 2005-07-06 1007 1008 231 | ... 232 | 2014-06-18 1000 1002 233 | 2014-06-18 1001 1003 1004 234 | ... 235 | ``` 236 | 237 | Note, we will ignore all numbers below 1000 and if any numbers 1000 or above are missing we will assume each of those lines forms its own conversation. 238 | 239 | 240 | 241 | ### Timeline ### 242 | 243 | - Development Phase: Jun 17 - Sep 22, 2019 (14 weeks) 244 | - Test data out on: Sep 23, 2019 245 | - Evaluation Phase: Sep 23 - Oct 13, 2019 (2 weeks) 246 | - Submission deadline: Oct 13, 2019 at 11:59pm UTC-10 (midnight Hawaii) 247 | - Announcement of the results: Oct 20, 2019 248 | - Paper Submission: TBA 249 | - DSTC8 Workshop: TBA 250 | 251 | ### Organizers ### 252 | 253 | [Chulaka Gunasekara](https://researcher.watson.ibm.com/researcher/view.php?person=ibm-chulaka.gunasekara), [Luis Lastras](https://researcher.watson.ibm.com/researcher/view.php?person=us-lastrasl) – IBM Research AI
254 | [Jonathan K. Kummerfeld](http://www.jkk.name), [Walter Lasecki](https://web.eecs.umich.edu/~wlasecki/) – University of Michigan 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | -------------------------------------------------------------------------------- /subtask1/README.md: -------------------------------------------------------------------------------- 1 | ## Response Selection for Conversation Systems in Tensorflow (DSTC 8) 2 | 3 | #### Overview 4 | 5 | This code implements a simple dual encoder baseline for the subtask 1 of DSTC-8 [Sentence Selection track](https://github.com/dstc8-track2/NOESIS-II). 6 | 7 | This code uses parts of the [work](https://github.com/jdongca2003/next_utterance_selection) from Jianxiong Dong 8 | 9 | #### Setup 10 | 11 | This code uses Python 3.6 and Tensorflow-GPU 1.6. Clone the repository and install all required packages. It is recommended to use the [Anaconda package manager](https://www.anaconda.com/download/#macos). After installing Anaconda - 12 | 13 | ``` 14 | conda create --name dstc8 python=3.6 15 | source activate dstc7 16 | pip install -r requirements.txt 17 | ``` 18 | 19 | #### Get the data 20 | 21 | Make sure you register for the track 2 of DSTC8 to download the data and copy it inside the `data` directory. 22 | 23 | #### Prepare the data 24 | 25 | Before training, the data needs to converted into a suitable format. The script `convert_dstc8_data.py` can be used to convert data for both advising and ubuntu datasets. 26 | 27 | ``` 28 | python scripts/convert_dstc8_data.py --train_in data/Task_1/ubuntu/task-1.ubuntu.train.json 29 | --train_out data/Task_1/ubuntu/task-1.ubuntu.train.txt 30 | --dev_in data/Task_1/ubuntu/task-1.ubuntu.dev.json 31 | --dev_out data/Task_1/ubuntu/task-1.ubuntu.dev.txt 32 | --answers_file data/Task_1/ubuntu/ubuntu_task_1_candidates.txt 33 | --save_vocab_path data/Task_1/ubuntu/ubuntu_task_1_vocab.txt 34 | ``` 35 | 36 | #### Training 37 | 38 | And then train the model 39 | 40 | ``` 41 | python answer_selection/train.py --answer_file data/Task_1/ubuntu/ubuntu_task_1_candidates.txt 42 | --train_file data/Task_1/ubuntu/task-1.ubuntu.train.txt 43 | --embedded_vector_file data/embeddings/glove.6B.100d.txt 44 | --vocab_file data/Task_1/ubuntu/ubuntu_task_1_vocab.txt 45 | --valid_file data/Task_1/ubuntu/task-1.ubuntu.dev.txt 46 | --max_sequence_length 180 47 | --embedding_dim 100 48 | --l2_reg_lambda 0 49 | --dropout_keep_prob 1.0 50 | --batch_size 64 51 | --rnn_size 200 52 | --evaluate_every 2 53 | --char_vocab_file data/embeddings/char_vocab.txt 54 | --max_word_length 18 55 | ``` 56 | 57 | Similar command works for subtask 1 of Advising data as well. 58 | 59 | Glove embeddings can be downloaded from [here](https://nlp.stanford.edu/projects/glove/). Embeddings used for the baseline run can be found [here](https://github.com/jdongca2003/next_utterance_selection#Dataset) 60 | 61 | #### Model 62 | 63 | This baseline model extends the dual-encoder model used [here](http://www.wildml.com/2016/07/deep-learning-for-chatbots-2-retrieval-based-model-tensorflow). 64 | 65 | 66 | #### Dual Encoder Baselines (Recall) 67 | 68 | Baselines are reported on validation set. 69 | 70 | | Dataset | 1 in 100 R@1 | 1 in 100 R@2 | 1 in 100 R@5 | 1 in 100 R@10 | MRR | 71 | | :---------------: | :-------------: | :-----------: |:----------: | :---------: | :---------: | 72 | | Ubuntu - Subtask 1 | 21.16% | 29.03% | 42.11% | 56.53% | 0.3249 | 73 | | Advising - Subtask 1 | 22.18% | 33.60% | 49.31% | 62.20% | 0.3551 | 74 | -------------------------------------------------------------------------------- /subtask1/answer_selection/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 IBM Corp. Intellectual Property. All rights reserved. 2 | # Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | # This file has been modified by IBM Corp. to add support for DSTC8 Track 2 17 | # 18 | # ============================================================================== 19 | -------------------------------------------------------------------------------- /subtask1/answer_selection/data_helpers.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 IBM Corp. Intellectual Property. All rights reserved. 2 | # Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | # This file has been modified by IBM Corp. to add support for DSTC8 Track 2 17 | # 18 | # ============================================================================== 19 | 20 | import numpy as np 21 | import random 22 | 23 | def loadCharVocab(fname): 24 | charVocab={} 25 | with open(fname, 'rt') as f: 26 | for line in f: 27 | fields = line.strip().split('\t') 28 | char_id = int(fields[0]) 29 | ch = fields[1] 30 | charVocab[ch] = char_id 31 | return charVocab 32 | 33 | def loadVocab(fname): 34 | vocab={} 35 | with open(fname, 'rt') as f: 36 | for line in f: 37 | line = line.strip() 38 | fields = line.split('\t') 39 | term_id = int(fields[0]) 40 | if fields[1] in vocab: 41 | print("FOUND DUPLICATE") 42 | print(fields[1]) 43 | print(vocab[fields[1]]) 44 | print(term_id) 45 | vocab[fields[1]] = term_id 46 | print("Vocab length: {}".format(len(vocab))) 47 | return vocab 48 | 49 | def toVec(tokens, vocab, maxlen): 50 | n = len(tokens) 51 | length = 0 52 | vec=[] 53 | for i in range(n): 54 | length += 1 55 | if tokens[i] in vocab: 56 | vec.append(vocab[tokens[i]]) 57 | else: 58 | vec.append(vocab[""]) 59 | 60 | return length, np.array(vec) 61 | 62 | def loadAnswers(fname, vocab, maxlen): 63 | answers={} 64 | with open(fname, 'rt') as f: 65 | for line in f: 66 | line = line.strip() 67 | fields = line.split('\t') 68 | if len(fields) != 2: 69 | print("WRONG LINE: {}".format(line)) 70 | a_text = '' 71 | else: 72 | a_text = fields[1] 73 | a_text = a_text.replace('?', ' ').replace('.', ' ').replace(',', ' ').replace('*', ' ').replace('=', ' ') 74 | tokens = a_text.split(' ') 75 | len1, vec = toVec(tokens[:maxlen], vocab, maxlen) 76 | answers[fields[0]] = (len1, vec, tokens[:maxlen]) 77 | return answers 78 | 79 | 80 | def loadDataset(fname, vocab, maxlen, answers, do_label_smoothing=False): 81 | dataset=[] 82 | with open(fname, 'rt') as f: 83 | for line in f: 84 | line = line.strip() 85 | fields = line.split('\t') 86 | q_id = fields[0] 87 | question_text = fields[1] 88 | question_text = question_text.replace('?', ' ').replace('.', ' ').replace(',', ' ').replace('*', ' ').replace('=', ' ') 89 | q_tokens = question_text.split(' ') 90 | q_len, q_vec = toVec(q_tokens[:maxlen], vocab, maxlen) 91 | num_neg_ids = 0 92 | if fields[3] != "NA": 93 | neg_ids = [id for id in fields[3].split('|')] 94 | num_neg_ids = len(neg_ids) 95 | for aid in neg_ids: 96 | a_len, a_vec, a_tokens = answers[aid] 97 | if do_label_smoothing: 98 | epsilon = 0.1 99 | neg_score = ((1 - epsilon) * 0) + (epsilon / num_neg_ids) 100 | dataset.append((q_id, q_len, q_vec, aid, a_len, a_vec, neg_score, q_tokens[:maxlen], a_tokens)) 101 | else: 102 | dataset.append((q_id, q_len, q_vec, aid, a_len, a_vec, 0, q_tokens[:maxlen], a_tokens)) 103 | 104 | if fields[2] != "NA": 105 | pos_ids = [id for id in fields[2].split('|')] 106 | #num_pos_ids = len(pos_ids) 107 | #assert num_pos_ids == 1, "For Ubuntu, only 1 positive answer given" 108 | for aid in pos_ids: 109 | a_len, a_vec, a_tokens = answers[aid] 110 | if do_label_smoothing: 111 | epsilon = 0.1 112 | if num_neg_ids != 0: 113 | pos_score = ((1 - epsilon) * 1) + (epsilon / num_neg_ids) 114 | else: 115 | pos_score = 0.901 116 | dataset.append((q_id, q_len, q_vec, aid, a_len, a_vec, pos_score, q_tokens[:maxlen], a_tokens)) 117 | else: 118 | dataset.append((q_id, q_len, q_vec, aid, a_len, a_vec, 1.0, q_tokens[:maxlen], a_tokens)) 119 | return dataset 120 | 121 | def word_count(q_vec, a_vec, q_len, a_len, idf): 122 | q_set = set([q_vec[i] for i in range(q_len) if q_vec[i] > 100]) 123 | a_set = set([a_vec[i] for i in range(a_len) if a_vec[i] > 100]) 124 | new_q_len = float(max(len(q_set), 1)) 125 | count1 = 0.0 126 | count2 = 0.0 127 | for id1 in q_set: 128 | if id1 in a_set: 129 | count1 += 1.0 130 | if id1 in idf: 131 | count2 += idf[id1] 132 | return count1/new_q_len, count2/new_q_len 133 | 134 | def common_words(q_vec, a_vec, q_len, a_len): 135 | q_set = set([q_vec[i] for i in range(q_len) if q_vec[i] > 100]) 136 | a_set = set([a_vec[i] for i in range(a_len) if a_vec[i] > 100]) 137 | return q_set.intersection(a_set) 138 | 139 | def tfidf_feature(id_list, common_id_set, idf): 140 | word_freq={} 141 | for t in id_list: 142 | if t in common_id_set: 143 | if t in word_freq: 144 | word_freq[t] += 1 145 | else: 146 | word_freq[t] = 1 147 | tfidf_feature={} 148 | for t in common_id_set: 149 | if t in idf: 150 | tfidf_feature[t] = word_freq[t] * idf[t] 151 | else: 152 | tfidf_feature[t] = word_freq[t] 153 | return tfidf_feature 154 | 155 | def word_feature(id_list, tfidf): 156 | len1 = len(id_list) 157 | features = np.zeros((len1, 2), dtype='float32') 158 | for idx, t in enumerate(id_list): 159 | if t in tfidf: 160 | features[idx, 0] = 1 161 | features[idx, 1] = tfidf[t] 162 | return features 163 | 164 | def normalize_vec(vec, maxlen): 165 | if len(vec) == maxlen: 166 | return vec 167 | 168 | new_vec = np.zeros(maxlen, dtype='int32') 169 | for i in range(len(vec)): 170 | new_vec[i] = vec[i] 171 | return new_vec 172 | 173 | 174 | def charVec(tokens, charVocab, maxlen, maxWordLength): 175 | n = len(tokens) 176 | if n > maxlen: 177 | n = maxlen 178 | 179 | chars = np.zeros((maxlen, maxWordLength), dtype=np.int32) 180 | word_lengths = np.ones(maxlen, dtype=np.int32) 181 | for i in range(n): 182 | token = tokens[i][:maxWordLength] 183 | word_lengths[i] = len(token) 184 | row = chars[i] 185 | for idx, ch in enumerate(token): 186 | if ch in charVocab: 187 | row[idx] = charVocab[ch] 188 | 189 | return chars, word_lengths 190 | 191 | 192 | def batch_iter(data, batch_size, num_epochs, target_loss_weights, maxlen, charVocab, max_word_length, shuffle=True): 193 | """ 194 | Generates a batch iterator for a dataset. 195 | """ 196 | data_size = len(data) 197 | num_batches_per_epoch = int(len(data)/batch_size) + 1 198 | for epoch in range(num_epochs): 199 | # Shuffle the fixtures at each epoch 200 | if shuffle: 201 | random.shuffle(data) 202 | for batch_num in range(num_batches_per_epoch): 203 | start_index = batch_num * batch_size 204 | end_index = min((batch_num + 1) * batch_size, data_size) 205 | x_question = [] 206 | x_answer = [] 207 | x_question_len = [] 208 | x_answer_len = [] 209 | targets = [] 210 | target_weights=[] 211 | id_pairs =[] 212 | 213 | x_question_char=[] 214 | x_question_char_len=[] 215 | x_answer_char=[] 216 | x_answer_char_len=[] 217 | 218 | for rowIdx in range(start_index, end_index): 219 | q_id, q_len, q_vec, aid, a_len, a_vec, label, q_tokens, a_tokens = data[rowIdx] 220 | if label > 0: 221 | target_weights.append(target_loss_weights[1]) 222 | else: 223 | target_weights.append(target_loss_weights[0]) 224 | 225 | common_ids = common_words(q_vec, a_vec, q_len, a_len) 226 | new_q_vec = normalize_vec(q_vec, maxlen) 227 | new_a_vec = normalize_vec(a_vec, maxlen) 228 | 229 | x_question.append(new_q_vec) 230 | x_question_len.append(q_len) 231 | x_answer.append(new_a_vec) 232 | x_answer_len.append(a_len) 233 | targets.append(label) 234 | id_pairs.append((q_id, aid, int(label))) 235 | 236 | qCharVec, qCharLen = charVec(q_tokens, charVocab, maxlen, max_word_length) 237 | aCharVec, aCharLen = charVec(a_tokens, charVocab, maxlen, max_word_length) 238 | 239 | x_question_char.append(qCharVec) 240 | x_question_char_len.append(qCharLen) 241 | x_answer_char.append(aCharVec) 242 | x_answer_char_len.append(aCharLen) 243 | 244 | yield np.array(x_question), np.array(x_answer), np.array(x_question_len), np.array(x_answer_len), np.array(targets), np.array(target_weights), id_pairs, np.array(x_question_char), np.array(x_question_char_len), np.array(x_answer_char), np.array(x_answer_char_len) 245 | 246 | -------------------------------------------------------------------------------- /subtask1/answer_selection/eval.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 IBM Corp. Intellectual Property. All rights reserved. 2 | # Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | # This file has been modified by IBM Corp. to add support for DSTC8 Track 2 17 | # 18 | # ============================================================================== 19 | 20 | import tensorflow as tf 21 | import os, sys 22 | 23 | from answer_selection import data_helpers 24 | from collections import defaultdict 25 | import operator 26 | from answer_selection import metrics 27 | 28 | # Data Parameters 29 | tf.flags.DEFINE_integer("batch_size", 128, "Batch Size (default: 64)") 30 | tf.flags.DEFINE_string("checkpoint_dir", "", "Checkpoint directory from training run") 31 | tf.flags.DEFINE_integer("max_sequence_length", 200, "max sequence length") 32 | 33 | # Misc Parameters 34 | tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement") 35 | tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices") 36 | 37 | tf.flags.DEFINE_string("answer_file", "", "tokenized answers") 38 | tf.flags.DEFINE_string("test_file", "", "test file containing (question, positive and negative answer ids)") 39 | tf.flags.DEFINE_string("vocab_file", "", "vocabulary file (map word to integer)") 40 | tf.flags.DEFINE_string("output_file", "", "prediction output file") 41 | 42 | tf.flags.DEFINE_string("char_vocab_file", "", "vocabulary file (map char to integer)") 43 | tf.flags.DEFINE_integer("max_word_length", 18, "max word length") 44 | 45 | 46 | FLAGS = tf.flags.FLAGS 47 | FLAGS(sys.argv) 48 | print("\nParameters:") 49 | for attr, value in sorted(FLAGS.flag_values_dict().items()): 50 | print("{}={}".format(attr.upper(), value)) 51 | print("") 52 | 53 | vocab = data_helpers.loadVocab(FLAGS.vocab_file) 54 | print(len(vocab)) 55 | 56 | charVocab = data_helpers.loadCharVocab(FLAGS.char_vocab_file) 57 | 58 | 59 | SEQ_LEN = FLAGS.max_sequence_length 60 | answer_data = data_helpers.loadAnswers(FLAGS.answer_file, vocab, SEQ_LEN) 61 | test_dataset = data_helpers.loadDataset(FLAGS.test_file, vocab, SEQ_LEN, answer_data) 62 | 63 | 64 | target_loss_weight=[1.0,1.0] 65 | 66 | print("\nEvaluating...\n") 67 | 68 | # Evaluation 69 | # ================================================== 70 | checkpoint_file = tf.train.latest_checkpoint(os.path.normpath(FLAGS.checkpoint_dir)) 71 | print(FLAGS.checkpoint_dir) 72 | print(checkpoint_file) 73 | 74 | graph = tf.Graph() 75 | with graph.as_default(): 76 | session_conf = tf.ConfigProto( 77 | allow_soft_placement=FLAGS.allow_soft_placement, 78 | log_device_placement=FLAGS.log_device_placement) 79 | sess = tf.Session(config=session_conf) 80 | with sess.as_default(): 81 | # Load the saved meta graph and restore variables 82 | saver = tf.train.import_meta_graph("{}.meta".format(checkpoint_file)) 83 | saver.restore(sess, checkpoint_file) 84 | 85 | # Get the placeholders from the graph by name 86 | question_x = graph.get_operation_by_name("question").outputs[0] 87 | answer_x = graph.get_operation_by_name("answer").outputs[0] 88 | 89 | question_len = graph.get_operation_by_name("question_len").outputs[0] 90 | answer_len = graph.get_operation_by_name("answer_len").outputs[0] 91 | 92 | dropout_keep_prob = graph.get_operation_by_name("dropout_keep_prob").outputs[0] 93 | 94 | q_char_feature = graph.get_operation_by_name("question_char").outputs[0] 95 | q_char_len = graph.get_operation_by_name("question_char_len").outputs[0] 96 | 97 | a_char_feature = graph.get_operation_by_name("answer_char").outputs[0] 98 | a_char_len = graph.get_operation_by_name("answer_char_len").outputs[0] 99 | 100 | # Tensors we want to evaluate 101 | prob = graph.get_operation_by_name("prediction/prob").outputs[0] 102 | 103 | results = defaultdict(list) 104 | num_test = 0 105 | test_batches = data_helpers.batch_iter(test_dataset, FLAGS.batch_size, 1, target_loss_weight, SEQ_LEN, charVocab, FLAGS.max_word_length, shuffle=False) 106 | for test_batch in test_batches: 107 | batch_question, batch_answer, batch_question_len, batch_answer_len, batch_target, batch_target_weight, batch_id_pairs, x_q_char, x_q_len, x_a_char, x_a_len = test_batch 108 | feed_dict = { 109 | question_x: batch_question, 110 | answer_x: batch_answer, 111 | question_len: batch_question_len, 112 | answer_len: batch_answer_len, 113 | dropout_keep_prob: 1.0, 114 | q_char_feature: x_q_char, 115 | q_char_len: x_q_len, 116 | a_char_feature: x_a_char, 117 | a_char_len: x_a_len 118 | } 119 | predicted_prob = sess.run(prob, feed_dict) 120 | num_test += len(predicted_prob) 121 | print('num_test_sample={}'.format(num_test)) 122 | for i, prob_score in enumerate(predicted_prob): 123 | qid, aid, label = batch_id_pairs[i] 124 | results[qid].append((aid, label, prob_score)) 125 | 126 | accu, precision, recall, f1, loss = metrics.classification_metrics(results) 127 | print('Accuracy: {}, Precision: {} Recall: {} F1: {} Loss: {}'.format(accu, precision, recall, f1, loss)) 128 | 129 | mrr = metrics.mean_reciprocal_rank(results) 130 | top_1_precision = metrics.top_k_precision(results, k=1) 131 | top_2_precision = metrics.top_k_precision(results, k=2) 132 | top_5_precision = metrics.top_k_precision(results, k=5) 133 | top_10_precision = metrics.top_k_precision(results, k=10) 134 | total_valid_query = metrics.get_num_valid_query(results) 135 | print('MRR (mean reciprocal rank): {}\tTop-1 recall: {}\tNum_query: {}'.format(mrr, top_1_precision, total_valid_query)) 136 | print('Top-2 recall: {}'.format(top_2_precision)) 137 | print('Top-5 recall: {}'.format(top_5_precision)) 138 | print('Top-10 recall: {}'.format(top_10_precision)) 139 | 140 | 141 | out_path = FLAGS.output_file 142 | print("Saving evaluation to {}".format(out_path)) 143 | with open(out_path, 'w') as f: 144 | f.write("query_id\tdocument_id\tscore\trank\trelevance\n") 145 | for qid, v in results.items(): 146 | v.sort(key=operator.itemgetter(2), reverse=True) 147 | for i, rec in enumerate(v): 148 | aid, label, prob_score = rec 149 | rank = i+1 150 | f.write('{}\t{}\t{}\t{}\t{}\n'.format(qid, aid, prob_score, rank, label)) 151 | -------------------------------------------------------------------------------- /subtask1/answer_selection/metrics.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 IBM Corp. Intellectual Property. All rights reserved. 2 | # Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | # This file has been modified by IBM Corp. to add support for DSTC8 Track 2 17 | # 18 | # ============================================================================== 19 | 20 | 21 | import operator 22 | import math 23 | 24 | def is_valid_query(v): 25 | num_pos = 0 26 | num_neg = 0 27 | for aid, label, score in v: 28 | if label > 0: 29 | num_pos += 1 30 | else: 31 | num_neg += 1 32 | if num_pos > 0 and num_neg > 0: 33 | return True 34 | else: 35 | return False 36 | 37 | def get_num_valid_query(results): 38 | num_query = 0 39 | for k, v in results.items(): 40 | if not is_valid_query(v): 41 | continue 42 | num_query += 1 43 | return num_query 44 | 45 | def top_k_precision(results, k=1): 46 | num_query = 0 47 | top_1_correct = 0.0 48 | for key, v in results.items(): 49 | if not is_valid_query(v): 50 | continue 51 | num_query += 1 52 | sorted_v = sorted(v, key=operator.itemgetter(2), reverse=True) 53 | if k == 1: 54 | aid, label, score = sorted_v[0] 55 | if label > 0: 56 | top_1_correct += 1 57 | elif k == 2: 58 | aid1, label1, score1 = sorted_v[0] 59 | aid2, label2, score2 = sorted_v[1] 60 | if label1 > 0 or label2 > 0: 61 | top_1_correct += 1 62 | elif k == 5: 63 | for vv in sorted_v[0:5]: 64 | label = vv[1] 65 | if label > 0: 66 | top_1_correct += 1 67 | break 68 | elif k == 10: 69 | for vv in sorted_v[0:10]: 70 | label = vv[1] 71 | if label > 0: 72 | top_1_correct += 1 73 | break 74 | elif k == 20: 75 | for vv in sorted_v[0:20]: 76 | label = vv[1] 77 | if label > 0: 78 | top_1_correct += 1 79 | break 80 | elif k == 50: 81 | for vv in sorted_v[0:50]: 82 | label = vv[1] 83 | if label > 0: 84 | top_1_correct += 1 85 | break 86 | elif k == 100: 87 | for vv in sorted_v[0:100]: 88 | label = vv[1] 89 | if label > 0: 90 | top_1_correct += 1 91 | break 92 | else: 93 | raise BaseException 94 | 95 | if num_query > 0: 96 | return top_1_correct/num_query 97 | else: 98 | return 0.0 99 | 100 | def mean_reciprocal_rank(results): 101 | num_query = 0 102 | mrr = 0.0 103 | for k, v in results.items(): 104 | if not is_valid_query(v): 105 | continue 106 | 107 | num_query += 1 108 | sorted_v = sorted(v, key=operator.itemgetter(2), reverse=True) 109 | for i, rec in enumerate(sorted_v): 110 | aid, label, score = rec 111 | if label > 0: 112 | mrr += 1.0/(i+1) 113 | break 114 | 115 | if num_query == 0: 116 | return 0.0 117 | else: 118 | mrr = mrr/num_query 119 | return mrr 120 | 121 | 122 | def classification_metrics(results): 123 | total_num = 0 124 | total_correct = 0 125 | true_positive = 0 126 | positive_correct = 0 127 | predicted_positive = 0 128 | 129 | loss = 0.0; 130 | for k, v in results.items(): 131 | for rec in v: 132 | total_num += 1 133 | aid, label, score = rec 134 | 135 | 136 | if score > 0.5: 137 | predicted_positive += 1 138 | 139 | if label > 0: 140 | true_positive += 1 141 | loss += -math.log(score+1e-12) 142 | else: 143 | loss += -math.log(1.0 - score + 1e-12); 144 | 145 | if score > 0.5 and label > 0: 146 | total_correct += 1 147 | positive_correct += 1 148 | 149 | if score < 0.5 and label < 0.5: 150 | total_correct += 1 151 | 152 | accuracy = float(total_correct)/total_num 153 | precision = float(positive_correct)/(predicted_positive+1e-12) 154 | recall = float(positive_correct)/true_positive 155 | F1 = 2.0 * precision * recall/(1e-12+precision + recall) 156 | return accuracy, precision, recall, F1, loss/total_num; 157 | -------------------------------------------------------------------------------- /subtask1/answer_selection/model.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 IBM Corp. Intellectual Property. All rights reserved. 2 | # Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | # This file has been modified by IBM Corp. to add support for DSTC8 Track 2 17 | # 18 | # ============================================================================== 19 | 20 | import tensorflow as tf 21 | import numpy as np 22 | 23 | FLAGS = tf.flags.FLAGS 24 | 25 | 26 | def get_embeddings(vocab): 27 | initializer = load_word_embeddings(vocab, FLAGS.embedding_dim) 28 | return tf.constant(initializer, name="word_embedding") 29 | 30 | 31 | def get_char_embedding(charVocab): 32 | char_size = len(charVocab) 33 | embeddings = np.zeros((char_size, char_size), dtype='float32') 34 | for i in range(1, char_size): 35 | embeddings[i, i] = 1.0 36 | 37 | return tf.constant(embeddings, name="word_char_embedding") 38 | 39 | 40 | def load_embed_vectors(fname, dim): 41 | vectors = {} 42 | for line in open(fname, 'rt', encoding='utf-8'): 43 | items = line.strip().split(' ') 44 | if len(items[0]) <= 0: 45 | continue 46 | vec = [float(items[i]) for i in range(1, dim + 1)] 47 | vectors[items[0]] = vec 48 | 49 | return vectors 50 | 51 | 52 | def load_word_embeddings(vocab, dim): 53 | vectors = load_embed_vectors(FLAGS.embedded_vector_file, dim) 54 | vocab_size = len(vocab) 55 | embeddings = np.zeros((vocab_size + 1, dim), dtype='float32') 56 | for word, code in vocab.items(): 57 | if word in vectors: 58 | embeddings[code] = vectors[word] 59 | else: 60 | embeddings[code] = np.random.uniform(-0.25, 0.25, dim) 61 | 62 | return embeddings 63 | 64 | 65 | def lstm_layer(inputs, input_seq_len, rnn_size, dropout_keep_prob, scope, scope_reuse=False): 66 | with tf.variable_scope(scope, reuse=scope_reuse) as vs: 67 | fw_cell = tf.contrib.rnn.LSTMCell(rnn_size, forget_bias=1.0, state_is_tuple=True, reuse=scope_reuse) 68 | fw_cell = tf.contrib.rnn.DropoutWrapper(fw_cell, output_keep_prob=dropout_keep_prob) 69 | bw_cell = tf.contrib.rnn.LSTMCell(rnn_size, forget_bias=1.0, state_is_tuple=True, reuse=scope_reuse) 70 | bw_cell = tf.contrib.rnn.DropoutWrapper(bw_cell, output_keep_prob=dropout_keep_prob) 71 | rnn_outputs, rnn_states = tf.nn.bidirectional_dynamic_rnn(cell_fw=fw_cell, cell_bw=bw_cell, 72 | inputs=inputs, 73 | sequence_length=input_seq_len, 74 | dtype=tf.float32) 75 | return rnn_outputs, rnn_states 76 | 77 | 78 | class DualEncoder(object): 79 | def __init__( 80 | self, sequence_length, vocab_size, embedding_size, vocab, rnn_size, maxWordLength, charVocab, 81 | l2_reg_lambda=0.0): 82 | # question 83 | self.question = tf.placeholder(tf.int32, [None, sequence_length], name="question") 84 | # answer 85 | self.answer = tf.placeholder(tf.int32, [None, sequence_length], name="answer") 86 | 87 | self.target = tf.placeholder(tf.float32, [None], name="target") 88 | 89 | self.target_loss_weight = tf.placeholder(tf.float32, [None], name="target_weight") 90 | 91 | self.question_len = tf.placeholder(tf.int32, [None], name="question_len") 92 | self.answer_len = tf.placeholder(tf.int32, [None], name="answer_len") 93 | 94 | self.dropout_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob") 95 | 96 | self.q_charVec = tf.placeholder(tf.int32, [None, sequence_length, maxWordLength], name="question_char") 97 | self.q_charLen = tf.placeholder(tf.int32, [None, sequence_length], name="question_char_len") 98 | 99 | self.a_charVec = tf.placeholder(tf.int32, [None, sequence_length, maxWordLength], name="answer_char") 100 | self.a_charLen = tf.placeholder(tf.int32, [None, sequence_length], name="answer_char_len") 101 | 102 | # Embedding layer 103 | with tf.device('/cpu:0'), tf.name_scope("embedding"): 104 | W = get_embeddings(vocab) 105 | question_embedded = tf.nn.embedding_lookup(W, self.question) 106 | answer_embedded = tf.nn.embedding_lookup(W, self.answer) 107 | 108 | with tf.device('/cpu:0'), tf.name_scope('char_embedding'): 109 | char_W = get_char_embedding(charVocab) 110 | # [batch_size, q_len, maxWordLength, char_dim] 111 | question_char_embedded = tf.nn.embedding_lookup(char_W, self.q_charVec) 112 | 113 | # [batch_size, a_len, maxWordLength, char_dim] 114 | answer_char_embedded = tf.nn.embedding_lookup(char_W, self.a_charVec) 115 | 116 | charRNN_size = 40 117 | charRNN_name = "char_RNN" 118 | char_dim = question_char_embedded.get_shape()[3].value 119 | question_char_embedded = tf.reshape(question_char_embedded, [-1, maxWordLength, char_dim]) 120 | question_char_len = tf.reshape(self.q_charLen, [-1]) 121 | answer_char_embedded = tf.reshape(answer_char_embedded, [-1, maxWordLength, char_dim]) 122 | answer_char_len = tf.reshape(self.a_charLen, [-1]) 123 | 124 | char_rnn_output1, char_rnn_states1 = lstm_layer(question_char_embedded, question_char_len, charRNN_size, 125 | self.dropout_keep_prob, charRNN_name, scope_reuse=False) 126 | char_rnn_output2, char_rnn_states2 = lstm_layer(answer_char_embedded, answer_char_len, charRNN_size, 127 | self.dropout_keep_prob, charRNN_name, scope_reuse=True) 128 | 129 | question_char_state = tf.concat(axis=1, values=[char_rnn_states1[0].h, char_rnn_states1[1].h]) 130 | char_embed_dim = 2 * charRNN_size 131 | question_char_state = tf.reshape(question_char_state, [-1, sequence_length, char_embed_dim]) 132 | 133 | answer_char_state = tf.concat(axis=1, values=[char_rnn_states2[0].h, char_rnn_states2[1].h]) 134 | answer_char_state = tf.reshape(answer_char_state, [-1, sequence_length, char_embed_dim]) 135 | 136 | question_embedded = tf.concat(axis=2, values=[question_embedded, question_char_state]) 137 | answer_embedded = tf.concat(axis=2, values=[answer_embedded, answer_char_state]) 138 | 139 | # Build the Context Encoder RNN 140 | with tf.variable_scope("context-rnn") as vs: 141 | # We use an LSTM Cell 142 | cell_context = tf.nn.rnn_cell.LSTMCell( 143 | rnn_size, 144 | forget_bias=2.0, 145 | use_peepholes=True, 146 | state_is_tuple=True) 147 | 148 | # Run context through the RNN 149 | context_encoded_outputs, context_encoded_states = tf.nn.dynamic_rnn(cell_context, question_embedded, 150 | self.question_len, dtype=tf.float32) 151 | 152 | # Build the Utterance Encoder RNN 153 | with tf.variable_scope("utterance-rnn") as vs: 154 | # We use an LSTM Cell 155 | cell_utterance = tf.nn.rnn_cell.LSTMCell( 156 | rnn_size, 157 | forget_bias=2.0, 158 | use_peepholes=True, 159 | state_is_tuple=True) 160 | 161 | # Run the utterance through the RNN 162 | utterance_encoded_outputs, utterance_encoded_states = tf.nn.dynamic_rnn(cell_utterance, answer_embedded, 163 | self.answer_len, dtype=tf.float32) 164 | 165 | with tf.variable_scope("prediction") as vs: 166 | M = tf.get_variable("M", 167 | shape=[rnn_size, rnn_size], 168 | initializer=tf.truncated_normal_initializer()) 169 | 170 | # "Predict" a response: c * M 171 | generated_response = tf.matmul(context_encoded_states.h, M) 172 | generated_response = tf.expand_dims(generated_response, 2) 173 | encoding_utterance = tf.expand_dims(utterance_encoded_states.h, 2) 174 | 175 | # Dot product between generated response and actual response 176 | # (c * M) * r 177 | logits = tf.matmul(generated_response, encoding_utterance, True) 178 | logits = tf.squeeze(logits, [2]) 179 | logits = tf.squeeze(logits, [1]) 180 | 181 | # Apply sigmoid to convert logits to probabilities 182 | self.probs = tf.sigmoid(logits, name="prob") 183 | 184 | # Calculate the binary cross-entropy loss 185 | losses = tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=tf.to_float(self.target)) 186 | 187 | # Mean loss across the batch of examples 188 | self.mean_loss = tf.reduce_mean(losses, name="mean_loss") 189 | 190 | with tf.name_scope("accuracy"): 191 | correct_prediction = tf.equal(tf.sign(self.probs - 0.5), tf.sign(self.target - 0.5)) 192 | self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"), name="accuracy") 193 | -------------------------------------------------------------------------------- /subtask1/answer_selection/train.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 IBM Corp. Intellectual Property. All rights reserved. 2 | # Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | # This file has been modified by IBM Corp. to add support for DSTC8 Track 2 17 | # 18 | # ============================================================================== 19 | 20 | import tensorflow as tf 21 | 22 | import sys, os 23 | import time 24 | import datetime 25 | from answer_selection import data_helpers 26 | from answer_selection.model import DualEncoder 27 | 28 | from collections import defaultdict 29 | from answer_selection import metrics 30 | 31 | # Model Hyperparameters 32 | tf.flags.DEFINE_integer("embedding_dim", 100, "Dimensionality of character embedding (default: 128)") 33 | tf.flags.DEFINE_float("dropout_keep_prob", 1.0, "Dropout keep probability (default: 0.5)") 34 | tf.flags.DEFINE_float("l2_reg_lambda", 0.000005, "L2 regularizaion lambda (default: 0.0)") 35 | 36 | tf.flags.DEFINE_string("answers_file", "", "tokenized answers") 37 | tf.flags.DEFINE_string("train_file", "", "train file containing (question, positive and negative answer ids)") 38 | tf.flags.DEFINE_string("embedded_vector_file", "", "pre-trained embedded word vector") 39 | tf.flags.DEFINE_string("vocab_file", "", "vocabulary file (map word to integer)") 40 | tf.flags.DEFINE_string("valid_file", "", "validation file containg (question, positive and negative response ids") 41 | tf.flags.DEFINE_integer("max_sequence_length", 200, "max sequence length") 42 | tf.flags.DEFINE_integer("rnn_size", 200, "number of RNN units") 43 | tf.flags.DEFINE_string("char_vocab_file", "", "vocabulary file (map char to integer)") 44 | tf.flags.DEFINE_integer("max_word_length", 18, "max word length") 45 | 46 | # Training parameters 47 | 48 | tf.flags.DEFINE_integer("batch_size", 1024, "Batch Size (default: 64)") 49 | 50 | tf.flags.DEFINE_integer("num_epochs", 5000000, "Number of training epochs (default: 200)") 51 | tf.flags.DEFINE_integer("evaluate_every", 1000, "Evaluate model on dev set after this many steps (default: 100)") 52 | tf.flags.DEFINE_integer("checkpoint_every", 1000, "Save model after this many steps (default: 100)") 53 | tf.flags.DEFINE_string("checkpoint_dir", "", "Checkpoint directory from training run") 54 | tf.flags.DEFINE_boolean("load_checkpoint", False, "Load from checkpoint") 55 | 56 | # Misc Parameters 57 | tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement") 58 | tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices") 59 | 60 | FLAGS = tf.flags.FLAGS 61 | FLAGS(sys.argv) 62 | print("\nParameters:") 63 | for attr, value in sorted(FLAGS.flag_values_dict().items()): 64 | print("{}={}".format(attr.upper(), value)) 65 | print("") 66 | 67 | 68 | def train(): 69 | graph = tf.Graph() 70 | with graph.as_default(): 71 | with tf.device("/gpu:0"): 72 | session_conf = tf.ConfigProto( 73 | allow_soft_placement=FLAGS.allow_soft_placement, 74 | log_device_placement=FLAGS.log_device_placement) 75 | sess = tf.Session(config=session_conf) 76 | with sess.as_default(): 77 | model = DualEncoder( 78 | sequence_length=FLAGS.max_sequence_length, 79 | vocab_size=len(vocab), 80 | embedding_size=FLAGS.embedding_dim, 81 | vocab=vocab, 82 | rnn_size=FLAGS.rnn_size, 83 | maxWordLength=FLAGS.max_word_length, 84 | charVocab=charVocab, 85 | l2_reg_lambda=FLAGS.l2_reg_lambda) 86 | # Define Training procedure 87 | global_step = tf.Variable(0, name="global_step", trainable=False) 88 | starter_learning_rate = 0.001 89 | target_loss_weight = [1.0, 1.0] 90 | learning_rate = tf.train.exponential_decay(starter_learning_rate, global_step, 91 | 5000, 0.96, staircase=True) 92 | optimizer = tf.train.AdamOptimizer(learning_rate) 93 | grads_and_vars = optimizer.compute_gradients(model.mean_loss) 94 | train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) 95 | # Output directory for models and summaries 96 | timestamp = str(int(time.time())) 97 | out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs", timestamp)) 98 | print("Writing to {}\n".format(out_dir)) 99 | 100 | # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it 101 | checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints")) 102 | checkpoint_prefix = os.path.join(checkpoint_dir, "model") 103 | if not os.path.exists(checkpoint_dir): 104 | os.makedirs(checkpoint_dir) 105 | saver = tf.train.Saver(tf.global_variables()) 106 | 107 | # Initialize all variables 108 | sess.run(tf.global_variables_initializer()) 109 | 110 | best_mrr = 0.0 111 | batches = data_helpers.batch_iter(train_dataset, FLAGS.batch_size, FLAGS.num_epochs, target_loss_weight, 112 | FLAGS.max_sequence_length, charVocab, FLAGS.max_word_length, shuffle=True) 113 | for batch in batches: 114 | x_question, x_answer, x_question_len, x_answer_len, x_target, x_target_weight, id_pairs, x_q_char, x_q_len, x_a_char, x_a_len = batch 115 | feed_dict = { 116 | model.question: x_question, 117 | model.answer: x_answer, 118 | model.question_len: x_question_len, 119 | model.answer_len: x_answer_len, 120 | model.target: x_target, 121 | model.target_loss_weight: x_target_weight, 122 | model.dropout_keep_prob: FLAGS.dropout_keep_prob, 123 | model.q_charVec: x_q_char, 124 | model.q_charLen: x_q_len, 125 | model.a_charVec: x_a_char, 126 | model.a_charLen: x_a_len 127 | } 128 | train_step(sess, train_op, global_step, model, feed_dict) 129 | current_step = tf.train.global_step(sess, global_step) 130 | if current_step > 10 and current_step % FLAGS.evaluate_every == 0: 131 | print("\nEvaluation:") 132 | valid_mrr = dev_step(sess, model, target_loss_weight) 133 | if valid_mrr > best_mrr: 134 | best_mrr = valid_mrr 135 | path = saver.save(sess, checkpoint_prefix, global_step=current_step) 136 | print("Saved model checkpoint to {}\n".format(path)) 137 | 138 | 139 | def train_step(sess, train_op, global_step, model, feed_dict): 140 | """ 141 | A single training step 142 | """ 143 | _, step, loss, accuracy, predicted_prob = sess.run( 144 | [train_op, global_step, model.mean_loss, model.accuracy, model.probs], 145 | feed_dict) 146 | 147 | time_str = datetime.datetime.now().isoformat() 148 | print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy)) 149 | 150 | 151 | def dev_step(sess, model, target_loss_weight): 152 | results = defaultdict(list) 153 | num_test = 0 154 | num_correct = 0.0 155 | test_batches = data_helpers.batch_iter(valid_dataset, FLAGS.batch_size, 1, target_loss_weight, FLAGS.max_sequence_length, charVocab, FLAGS.max_word_length, shuffle=True) 156 | for test_batch in test_batches: 157 | x_question, x_answer, x_question_len, x_answer_len, x_target, x_target_weight, id_pairs, x_q_char, x_q_len, x_a_char, x_a_len = test_batch 158 | feed_dict = { 159 | model.question: x_question, 160 | model.answer: x_answer, 161 | model.question_len: x_question_len, 162 | model.answer_len: x_answer_len, 163 | model.target: x_target, 164 | model.target_loss_weight: x_target_weight, 165 | model.dropout_keep_prob: 1.0, 166 | model.q_charVec: x_q_char, 167 | model.q_charLen: x_q_len, 168 | model.a_charVec: x_a_char, 169 | model.a_charLen: x_a_len 170 | } 171 | batch_accuracy, predicted_prob = sess.run([model.accuracy, model.probs], feed_dict) 172 | num_test += len(predicted_prob) 173 | if num_test % 1000 == 0: 174 | print(num_test) 175 | 176 | num_correct += len(predicted_prob) * batch_accuracy 177 | for i, prob_score in enumerate(predicted_prob): 178 | question_id, answer_id, label = id_pairs[i] 179 | results[question_id].append((answer_id, label, prob_score)) 180 | 181 | #calculate top-1 precision 182 | print('num_test_samples: {} test_accuracy: {}'.format(num_test, num_correct/num_test)) 183 | accu, precision, recall, f1, loss = metrics.classification_metrics(results) 184 | print('Accuracy: {}, Precision: {} Recall: {} F1: {} Loss: {}'.format(accu, precision, recall, f1, loss)) 185 | 186 | mrr = metrics.mean_reciprocal_rank(results) 187 | top_1_precision = metrics.top_k_precision(results, k=1) 188 | top_2_precision = metrics.top_k_precision(results, k=2) 189 | top_5_precision = metrics.top_k_precision(results, k=5) 190 | top_10_precision = metrics.top_k_precision(results, k=10) 191 | total_valid_query = metrics.get_num_valid_query(results) 192 | 193 | print('MRR (mean reciprocal rank): {}\tTop-1 precision: {}\tNum_query: {}\n'.format(mrr, top_1_precision, total_valid_query)) 194 | print('Top-2 precision: {}'.format(top_2_precision)) 195 | print('Top-5 precision: {}'.format(top_5_precision)) 196 | print('Top-10 precision: {}'.format(top_10_precision)) 197 | 198 | return mrr 199 | 200 | 201 | if __name__=="__main__": 202 | # Load fixtures 203 | print("Loading data...") 204 | 205 | vocab = data_helpers.loadVocab(FLAGS.vocab_file) 206 | charVocab = data_helpers.loadCharVocab(FLAGS.char_vocab_file) 207 | 208 | answer_data = data_helpers.loadAnswers(FLAGS.answers_file, vocab, FLAGS.max_sequence_length) 209 | train_dataset = data_helpers.loadDataset(FLAGS.train_file, vocab, FLAGS.max_sequence_length, answer_data, 210 | do_label_smoothing=True) 211 | print('train_pairs: {}'.format(len(train_dataset))) 212 | valid_dataset = data_helpers.loadDataset(FLAGS.valid_file, vocab, FLAGS.max_sequence_length, answer_data, 213 | do_label_smoothing=False) 214 | print('dev_pairs: {}'.format(len(valid_dataset))) 215 | 216 | train() -------------------------------------------------------------------------------- /subtask1/data/embeddings/char_vocab.txt: -------------------------------------------------------------------------------- 1 | 0 U 2 | 1 ! 3 | 2 " 4 | 3 # 5 | 4 $ 6 | 5 % 7 | 6 & 8 | 7 ' 9 | 8 ( 10 | 9 ) 11 | 10 * 12 | 11 + 13 | 12 , 14 | 13 - 15 | 14 . 16 | 15 / 17 | 16 0 18 | 17 1 19 | 18 2 20 | 19 3 21 | 20 4 22 | 21 5 23 | 22 6 24 | 23 7 25 | 24 8 26 | 25 9 27 | 26 : 28 | 27 ; 29 | 28 < 30 | 29 = 31 | 30 > 32 | 31 ? 33 | 32 @ 34 | 33 [ 35 | 34 \ 36 | 35 ] 37 | 36 ^ 38 | 37 _ 39 | 38 ` 40 | 39 a 41 | 40 b 42 | 41 c 43 | 42 d 44 | 43 e 45 | 44 f 46 | 45 g 47 | 46 h 48 | 47 i 49 | 48 j 50 | 49 k 51 | 50 l 52 | 51 m 53 | 52 n 54 | 53 o 55 | 54 p 56 | 55 q 57 | 56 r 58 | 57 s 59 | 58 t 60 | 59 u 61 | 60 v 62 | 61 w 63 | 62 x 64 | 63 y 65 | 64 z 66 | 65 { 67 | 66 | 68 | 67 } 69 | 68 ~ 70 | -------------------------------------------------------------------------------- /subtask1/requirements.txt: -------------------------------------------------------------------------------- 1 | tensorflow-gpu==1.6.0 -------------------------------------------------------------------------------- /subtask1/scripts/convert_dstc8_data.py: -------------------------------------------------------------------------------- 1 | import os 2 | import ijson 3 | import random 4 | import tensorflow as tf 5 | 6 | tf.flags.DEFINE_integer("min_word_frequency", 1, "Minimum frequency of words in the vocabulary") 7 | tf.flags.DEFINE_integer("max_sentence_len", 180, "Maximum Sentence Length") 8 | tf.flags.DEFINE_integer("random_seed", 42, "Seed for sampling negative training examples") 9 | 10 | tf.flags.DEFINE_string("train_in", "data/Task_1/ubuntu/task-1.ubuntu.train.json", "Path to input data file") 11 | tf.flags.DEFINE_string("train_out", "data/Task_1/ubuntu/task-1.ubuntu.train.txt", "Path to output train file") 12 | 13 | tf.flags.DEFINE_string("dev_in", "data/Task_1/ubuntu/task-1.ubuntu.dev.json", "Path to dev data file") 14 | tf.flags.DEFINE_string("dev_out", "data/Task_1/ubuntu/task-1.ubuntu.dev.txt", "Path to output dev file") 15 | 16 | tf.flags.DEFINE_string("answers_file", "data/Task_1/ubuntu/ubuntu_task_1_candidates.txt", "Path to write answers file") 17 | tf.flags.DEFINE_string("save_vocab_path", 'data/Task_1/ubuntu/ubuntu_task_1_vocab.txt', "Path to save vocabulary txt file") 18 | 19 | ## Once we have the test_set, we need to add test_file here too! 20 | # tf.flags.DEFINE_string("test_in", "data/Task_1/ubuntu/..", "Path to test data file") 21 | # tf.flags.DEFINE_string("test_out", "data/Task_1/ubuntu/..", "Path to output test file") 22 | # tf.flags.DEFINE_string("test_answers_file", "data/Task_1/ubuntu/..", "Path to write test answers file") 23 | 24 | FLAGS = tf.flags.FLAGS 25 | 26 | def tokenizer_fn(iterator): 27 | return (x.replace('?', ' ').replace('.', ' ').replace(',', ' ').replace('*', ' ').replace('=', ' ').split(" ") for x in iterator) 28 | 29 | def process_dialog(dialog, train=False, positive=True, all_negative=False, seed=42): 30 | row = [] 31 | 32 | context = get_context(dialog) 33 | row.append(context) 34 | 35 | # Get correct answer and target id 36 | if len(dialog['options-for-correct-answers']) == 0: 37 | correct_answer = {} 38 | correct_answer['utterance'] = "None" 39 | target_id = "NONE" 40 | else: 41 | correct_answer = dialog['options-for-correct-answers'][0] 42 | target_id = correct_answer['candidate-id'] 43 | 44 | # Create a list of all negative answers 45 | negative_answers = [] 46 | for i, utterance in enumerate(dialog['options-for-next']): 47 | if utterance['candidate-id'] != target_id: 48 | negative_answers.append(utterance) 49 | 50 | if len(negative_answers) < 100: 51 | none = {'utterance': "None", 52 | 'candidate-id': "NONE"} 53 | negative_answers.append(none) 54 | 55 | # If this is a training sample (train=True) and positive=True return the correct response 56 | if train and positive: 57 | row.append(correct_answer['utterance'] + " __eou__ ") 58 | return row 59 | # If this is a training sample and positive=False return a randomly sampled from list of negative answers 60 | elif train and not positive and not all_negative: 61 | random.seed(seed) 62 | negative_answer = random.choice(negative_answers) 63 | row.append(negative_answer['utterance'] + " __eou__ ") 64 | return row 65 | # If all_negative = True, return all negative options 66 | elif train and all_negative: 67 | rows = [] 68 | for option in negative_answers: 69 | row = [] 70 | row.append(context) 71 | row.append(option['utterance'] + " __eou__") 72 | rows.append(row) 73 | return rows 74 | 75 | return row 76 | 77 | def get_dialogs(filename): 78 | rows = [] 79 | with open(filename, 'rb') as f: 80 | json_data = ijson.items(f, 'item') 81 | for entry in json_data: 82 | rows.append(process_dialog(entry, train=True, positive=True)) 83 | rows.extend(process_dialog(entry, train=True, positive=False, all_negative=True)) 84 | return rows 85 | 86 | def create_utterance_iter(input_iter): 87 | for row in input_iter: 88 | all_utterances = [] 89 | context = row[0] 90 | next_utterances = row[1:] 91 | all_utterances.append(context) 92 | all_utterances.extend(next_utterances) 93 | for utterance in all_utterances: 94 | yield utterance 95 | 96 | def create_vocab(input_iter, min_frequency): 97 | vocab_processor = tf.contrib.learn.preprocessing.VocabularyProcessor( 98 | FLAGS.max_sentence_len, 99 | min_frequency=min_frequency, 100 | tokenizer_fn=tokenizer_fn) 101 | vocab_processor.fit(input_iter) 102 | return vocab_processor 103 | 104 | def write_vocabulary(vocab_processor, outfile): 105 | vocab_size = len(vocab_processor.vocabulary_) 106 | count = 0 107 | with open(outfile, "w") as vocabfile: 108 | for id in range(vocab_size): 109 | word = vocab_processor.vocabulary_._reverse_mapping[id] 110 | if word == '': 111 | continue 112 | vocabfile.write(str(count) + "\t" + word.replace("\n", "") + "\n") 113 | count += 1 114 | vocabfile.write(str(count) + "\t" + "UNKNOWN" + "\n") 115 | print("Saved vocabulary to {}".format(outfile)) 116 | 117 | # TODO - Once we have the test_set, we need to add test_file here too! 118 | def create_answers_file(train_file, dev_file, answers_file): 119 | answers = set() 120 | with open(train_file, 'rb') as f: 121 | json_data = ijson.items(f, 'item') 122 | for entry in json_data: 123 | if len(entry['options-for-correct-answers']) == 0: 124 | correct_answer = {} 125 | correct_answer['utterance'] = "None" 126 | else: 127 | correct_answer = entry['options-for-correct-answers'][0] 128 | answer = correct_answer['utterance'] + " __eou__ " 129 | answers.add(answer.strip()) 130 | 131 | for i, utterance in enumerate(entry['options-for-next']): 132 | answer = utterance['utterance'] + " __eou__ " 133 | answers.add(answer.strip()) 134 | 135 | with open(dev_file, 'rb') as f: 136 | json_data = ijson.items(f, 'item') 137 | for entry in json_data: 138 | if len(entry['options-for-correct-answers']) == 0: 139 | correct_answer = {} 140 | correct_answer['utterance'] = "None" 141 | else: 142 | correct_answer = entry['options-for-correct-answers'][0] 143 | answer = correct_answer['utterance'] + " __eou__ " 144 | answers.add(answer.strip()) 145 | 146 | for i, utterance in enumerate(entry['options-for-next']): 147 | answer = utterance['utterance'] + " __eou__ " 148 | answers.add(answer.strip()) 149 | 150 | answers = list(answers) 151 | with open(answers_file, "w") as vocabfile: 152 | for id in range(len(answers)): 153 | answer = answers[id] 154 | vocabfile.write(str(id+1) + "\t" + answer.replace("\n", "") + "\n") 155 | print("Saved answers to {}".format(answers_file)) 156 | 157 | answers_return_dict = {} 158 | for i in range(len(answers)): 159 | answers_return_dict[answers[i]] = i 160 | 161 | return answers_return_dict 162 | 163 | 164 | def create_test_answers_file(test_file, test_answers_file): 165 | answers = {} 166 | 167 | with open(test_file, 'rb') as f: 168 | json_data = ijson.items(f, 'item') 169 | for entry in json_data: 170 | for i, utterance in enumerate(entry['options-for-next']): 171 | answer = utterance['utterance'] + " __eou__ " 172 | answer_id = utterance['candidate-id'] 173 | answers[answer_id] = answer 174 | 175 | answers["NONE"] = "None __eou__ " 176 | with open(test_answers_file, "w") as vocabfile: 177 | for answer_id, answer in answers.items(): 178 | vocabfile.write(str(answer_id) + "\t" + answer.replace("\n", "") + "\n") 179 | print("Saved test answers to {}".format(test_answers_file)) 180 | 181 | return answers 182 | 183 | 184 | def get_context(dialog): 185 | utterances = dialog['messages-so-far'] 186 | 187 | # Create the context 188 | context = "" 189 | speaker = None 190 | for msg in utterances: 191 | if speaker is None: 192 | context += msg['utterance'] + " __eou__ " 193 | speaker = msg['speaker'] 194 | elif speaker != msg['speaker']: 195 | context += "__eot__ " + msg['utterance'] + " __eou__ " 196 | speaker = msg['speaker'] 197 | else: 198 | context += msg['utterance'] + " __eou__ " 199 | 200 | context += "__eot__" 201 | return context 202 | 203 | def create_train_file(train_file, train_file_out, answers): 204 | train_file_op = open(train_file_out, "w") 205 | positive_samples_count = 0 206 | negative_samples_count = 0 207 | 208 | train_data_handle = open(train_file, 'rb') 209 | json_data = ijson.items(train_data_handle, 'item') 210 | for index, entry in enumerate(json_data): 211 | row = str(index+1) + "\t" 212 | context = get_context(entry) 213 | row += context + "\t" 214 | 215 | if len(entry['options-for-correct-answers']) == 0: 216 | correct_answer = {} 217 | correct_answer['utterance'] = "None" 218 | target_id = "NONE" 219 | else: 220 | correct_answer = entry['options-for-correct-answers'][0] 221 | target_id = correct_answer['candidate-id'] 222 | answer = correct_answer['utterance'] + " __eou__ " 223 | answer = answer.strip() 224 | correct_answer_row = row + str(answers[answer] + 1) + "\t" + "NA" 225 | positive_samples_count += 1 226 | train_file_op.write(correct_answer_row.replace("\n", "") + "\n") 227 | 228 | negative_answers = [] 229 | for i, utterance in enumerate(entry['options-for-next']): 230 | if utterance['candidate-id'] == target_id: 231 | continue 232 | answer = utterance['utterance'] + " __eou__ " 233 | answer = answer.strip() 234 | negative_answers.append(str(answers[answer] + 1)) 235 | negative_samples_count += 1 236 | 237 | if len(negative_answers) < 100: 238 | answer = "None __eou__" 239 | negative_answers.append(str(answers[answer] + 1)) 240 | negative_samples_count += 1 241 | 242 | negative_answers = "|".join(negative_answers) 243 | negative_answer_row = row + "NA" + "\t" + negative_answers + "\t" 244 | train_file_op.write(negative_answer_row.replace("\n", "") + "\n") 245 | 246 | print("Saved training data to {}".format(train_file_out)) 247 | print("Train - Positive samples count - {}".format(positive_samples_count)) 248 | print("Train - Negative samples count - {}".format(negative_samples_count)) 249 | train_file_op.close() 250 | 251 | def create_dev_file(dev_file, dev_file_out, answers): 252 | dev_file_op = open(dev_file_out, "w") 253 | positive_samples_count = 0 254 | negative_samples_count = 0 255 | 256 | dev_data_handle = open(dev_file, 'rb') 257 | json_data = ijson.items(dev_data_handle, 'item') 258 | for index, entry in enumerate(json_data): 259 | row = str(index+1) + "\t" 260 | context = get_context(entry) 261 | row += context + "\t" 262 | 263 | if len(entry['options-for-correct-answers']) == 0: 264 | correct_answer = {} 265 | correct_answer['utterance'] = "None" 266 | target_id = "NONE" 267 | else: 268 | correct_answer = entry['options-for-correct-answers'][0] 269 | target_id = correct_answer['candidate-id'] 270 | answer = correct_answer['utterance'] + " __eou__ " 271 | answer = answer.strip() 272 | row += str(answers[answer] + 1) + "\t" 273 | positive_samples_count += 1 274 | 275 | negative_answers = [] 276 | for i, utterance in enumerate(entry['options-for-next']): 277 | if utterance['candidate-id'] == target_id: 278 | continue 279 | answer = utterance['utterance'] + " __eou__ " 280 | answer = answer.strip() 281 | negative_answers.append(str(answers[answer] + 1)) 282 | negative_samples_count += 1 283 | 284 | if len(negative_answers) < 100: 285 | answer = "None __eou__" 286 | negative_answers.append(str(answers[answer] + 1)) 287 | negative_samples_count += 1 288 | 289 | negative_answers = "|".join(negative_answers) 290 | row += negative_answers + "\t" 291 | dev_file_op.write(row.replace("\n", "") + "\n") 292 | 293 | print("Saved dev data to {}".format(dev_file_out)) 294 | print("Dev - Positive samples count - {}".format(positive_samples_count)) 295 | print("Dev - Negative samples count - {}".format(negative_samples_count)) 296 | dev_file_op.close() 297 | 298 | 299 | def create_test_file(test_file, test_file_out): 300 | test_file_op = open(test_file_out, "w") 301 | candidates_count = 0 302 | 303 | test_data_handle = open(test_file, 'rb') 304 | json_data = ijson.items(test_data_handle, 'item') 305 | for index, entry in enumerate(json_data): 306 | entry_id = entry["example-id"] 307 | row = str(entry_id) + "\t" 308 | context = get_context(entry) 309 | row += context + "\t" 310 | 311 | candidates = [] 312 | for i, utterance in enumerate(entry['options-for-next']): 313 | answer_id = utterance['candidate-id'] 314 | candidates.append(answer_id) 315 | candidates_count += 1 316 | 317 | candidates.append("NONE") 318 | 319 | candidates = "|".join(candidates) 320 | row += "NA" + "\t" + candidates + "\t" 321 | test_file_op.write(row.replace("\n", "") + "\n") 322 | 323 | print("Saved test data to {}".format(test_file_out)) 324 | print("Test - candidates count - {}".format(candidates_count)) 325 | test_file_op.close() 326 | 327 | 328 | if __name__ == "__main__": 329 | train_file = os.path.join(FLAGS.train_in) 330 | dev_file = os.path.join(FLAGS.dev_in) 331 | #test_file = os.path.join(FLAGS.test_in) 332 | 333 | answers_file = os.path.join(FLAGS.answers_file) 334 | #test_answers_file = os.path.join(FLAGS.test_answers_file) 335 | 336 | train_file_out = os.path.join(FLAGS.train_out) 337 | dev_file_out = os.path.join(FLAGS.dev_out) 338 | #test_file_out = os.path.join(FLAGS.test_out) 339 | 340 | print("Creating vocabulary...") 341 | dialogs = get_dialogs(train_file) 342 | input_iter = iter(dialogs) 343 | input_iter = create_utterance_iter(input_iter) 344 | vocab = create_vocab(input_iter, min_frequency=FLAGS.min_word_frequency) 345 | print("Total vocabulary size: {}".format(len(vocab.vocabulary_))) 346 | 347 | # Create vocabulary txt file 348 | vocab_file = os.path.join(FLAGS.save_vocab_path) 349 | write_vocabulary(vocab, vocab_file) 350 | 351 | # Create answers txt file 352 | answers = create_answers_file(train_file, dev_file, answers_file) 353 | 354 | ## Once we have the test_set, we need to add test_file here too! 355 | #answers_test = create_test_answers_file(test_file, test_answers_file) 356 | 357 | # Create train txt file 358 | create_train_file(train_file, train_file_out, answers) 359 | # Create dev txt file 360 | create_dev_file(dev_file, dev_file_out, answers) 361 | 362 | ## Once we have the test_set, we need to add test_file here too! 363 | # Create test txt file 364 | #create_test_file(test_file, test_file_out) 365 | -------------------------------------------------------------------------------- /subtask4/README.md: -------------------------------------------------------------------------------- 1 | # Disentanglement Baseline and Evaluation 2 | 3 | This folder contains the code needed to run and evaluate the baseline disentanglement model. The files are: 4 | 5 | - `README.md`, this file 6 | - `task-4-evaluation.py`, the evaluation program 7 | - `disentangle.py`, the baseline 8 | - `reserved_words.py`, a set of words used by the baseline (kept in a separate file for convenience) 9 | - `disentangle.model`, a trained model for the baseline 10 | - `glove-ubuntu.txt`, a set of word vectors trained on all of the Ubuntu data (after applying our tokenisation method) 11 | - `tokenise.py`, a tool to tokenise the text ~as we have in the provided files 12 | 13 | ## Baseline 14 | 15 | The baseline is a feedforward neural network with 2 layers, 512 dimensional hidden vectors, and softsign non-linearities. It uses the DyNet library: 16 | 17 | dynet.readthedocs.io 18 | 19 | This can usually be installed with: 20 | 21 | `pip3 install dynet` 22 | 23 | This will train a model with the same parameters as we have used here: 24 | 25 | ``` 26 | python3 disentangle.py example-train --train ../task-4/train/*annotation.txt --dev ../task-4/dev/*annotation.txt --hidden 512 --drop 0 --layers 2 --nonlin softsign --word-vectors glove-ubuntu.txt --epochs 20 --dynet-autobatch --learning-rate 0.018804 --learning-decay-rate 0.103 --seed 10 --clip 3.740 --weight-decay 1e-07 --momentum 0.96 --opt sgd > example-train.out 2>example-train.err 27 | ``` 28 | 29 | This will run the trained model on the development set: 30 | 31 | ``` 32 | python3 disentangle.py example-run --model disentangle.model --test ../task-4/dev/*annotation* --hidden 512 --drop 0 --layers 2 --nonlin softsign --test-start 1000 --test-end 2000 --word-vectors glove-ubuntu.txt > example-run.out 2>example-run.err 33 | ``` 34 | 35 | For a full list of arguments run: 36 | 37 | ``` 38 | python3 disentangle.py --help 39 | ``` 40 | 41 | ## Evaluation 42 | 43 | To evaluate the output of a system use: 44 | 45 | ``` 46 | python3 task-4-evaluation.py --gold ../task-4/dev/*anno* --auto example-run.out 47 | ``` 48 | 49 | For the provided model, that should give: 50 | 51 | ``` 52 | 92.15 1 - Scaled VI 53 | 74.19 Adjusted rand index 54 | 40.53 Matched clusters precision 55 | 41.26 Matched clusters recall 56 | 40.89 Matched clusters f-score 57 | ``` 58 | 59 | The format for output files is: 60 | 61 | ``` 62 | anything.../filename:line_number line_number - 63 | ``` 64 | 65 | For example: 66 | 67 | ``` 68 | ../task-4/dev/2004-11-15.annotation.txt:1000 1000 - 69 | ../task-4/dev/2004-11-15.annotation.txt:1001 1001 - 70 | ../task-4/dev/2004-11-15.annotation.txt:1002 1002 - 71 | ../task-4/dev/2004-11-15.annotation.txt:1003 1002 - 72 | ../task-4/dev/2004-11-15.annotation.txt:1004 1003 - 73 | ../task-4/dev/2004-11-15.annotation.txt:1005 1003 - 74 | ``` 75 | 76 | ## Tokenise 77 | 78 | Run to convert text to tokens with unk symbols. NOTE: we have done this for you on all the provided files in task 4. This is mainly here in case you wish to use the same process on task 1 or task 2. 79 | 80 | ``` 81 | ./tokenise.py --vocab vocab.txt --output-suffix .tok ASCII_FILENAME 82 | ``` 83 | 84 | -------------------------------------------------------------------------------- /subtask4/disentangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | import random 5 | import sys 6 | import string 7 | import time 8 | 9 | import numpy as np 10 | 11 | def header(args, out=sys.stdout): 12 | head_text = "# "+ time.ctime(time.time()) 13 | head_text += "\n# "+ ' '.join(args) 14 | for outfile in out: 15 | print(head_text, file=outfile) 16 | 17 | 18 | FEATURES = 77 19 | ###FEATURES = 34 20 | 21 | parser = argparse.ArgumentParser(description='Disentangler.') 22 | parser.add_argument('prefix') 23 | parser.add_argument('--train', nargs="+") 24 | parser.add_argument('--dev', nargs="+") 25 | parser.add_argument('--test', nargs="+") 26 | parser.add_argument('--model') 27 | parser.add_argument('--DEPRECATED-pytorch', action='store_true') 28 | parser.add_argument('--epochs', default=20, type=int) 29 | parser.add_argument('--word-vectors') 30 | parser.add_argument('--max-dist', default=101, type=int) 31 | parser.add_argument('--dynet-autobatch', action='store_true') 32 | parser.add_argument('--random-sample') 33 | parser.add_argument('--test-start', type=int) 34 | parser.add_argument('--test-end', type=int) 35 | parser.add_argument('--report-freq', default=5000, type=int) 36 | 37 | parser.add_argument('--seed', default=0, type=int) 38 | parser.add_argument('--weight-decay', default=1e-8, type=float) 39 | parser.add_argument('--hidden', default=1024, type=int)#64) 40 | parser.add_argument('--learning-rate', default=0.1, type=float) 41 | parser.add_argument('--learning-decay-rate', default=0.0, type=float) 42 | parser.add_argument('--momentum', default=0.1, type=float) 43 | parser.add_argument('--drop', default=0.0, type=float) 44 | parser.add_argument('--layers', default=2, type=int) 45 | parser.add_argument('--clip', default=1.0, type=float) 46 | parser.add_argument('--nonlin', choices=["tanh", "cube", "logistic", "relu", "elu", "selu", "softsign", "swish", "linear"], default='tanh') 47 | parser.add_argument('--opt', choices=['sgd', 'mom'], default='sgd') 48 | args = parser.parse_args() 49 | 50 | WEIGHT_DECAY = args.weight_decay 51 | HIDDEN = args.hidden 52 | LEARNING_RATE = args.learning_rate 53 | LEARNING_DECAY_RATE = args.learning_decay_rate 54 | MOMENTUM = args.momentum 55 | EPOCHS = args.epochs 56 | DROP = args.drop 57 | MAX_DIST = args.max_dist 58 | 59 | log_file = open(args.prefix +".log", 'w') 60 | header(sys.argv, [log_file, sys.stdout]) 61 | 62 | PYTORCH = args.DEPRECATED_pytorch 63 | if PYTORCH: 64 | import torch 65 | torch.manual_seed(args.seed) 66 | else: 67 | import dynet_config 68 | batching = 1 if args.dynet_autobatch else 0 69 | dynet_config.set(mem=512, autobatch=batching, weight_decay=WEIGHT_DECAY, random_seed=args.seed) 70 | # dynet_config.set_gpu() for when we want to run with GPUs 71 | import dynet as dy 72 | 73 | from reserved_words import reserved 74 | 75 | 76 | 77 | ############################################################################### 78 | 79 | def update_user(users, user): 80 | if user in reserved: 81 | return 82 | all_digit = True 83 | for char in user: 84 | if char not in string.digits: 85 | all_digit = False 86 | if all_digit: 87 | return 88 | users.add(user.lower()) 89 | 90 | def update_users(line, users): 91 | if len(line) < 2: 92 | return 93 | user = line[1] 94 | if user in ["Topic", "Signoff", "Signon", "Total", "#ubuntu" 95 | "Window", "Server:", "Screen:", "Geometry", "CO,", 96 | "Current", "Query", "Prompt:", "Second", "Split", 97 | "Logging", "Logfile", "Notification", "Hold", "Window", 98 | "Lastlog", "Notify", 'netjoined:']: 99 | # Ignore as these are channel commands 100 | pass 101 | else: 102 | if line[0].endswith("==="): 103 | parts = ' '.join(line).split("is now known as") 104 | if len(parts) == 2 and line[-1] == parts[-1].strip(): 105 | user = line[-1] 106 | elif line[0][-1] == ']': 107 | if user[0] == '<': 108 | user = user[1:] 109 | if user[-1] == '>': 110 | user = user[:-1] 111 | 112 | user = user.lower() 113 | update_user(users, user) 114 | # This is for cases like a user named |blah| who is 115 | # refered to as simply blah 116 | core = [char for char in user] 117 | while len(core) > 0 and core[0] in string.punctuation: 118 | core.pop(0) 119 | while len(core) > 0 and core[-1] in string.punctuation: 120 | core.pop() 121 | core = ''.join(core) 122 | update_user(users, core) 123 | 124 | # Names two letters or less that occur more than 500 times in the data 125 | common_short_names = {"ng", "_2", "x_", "rq", "\\9", "ww", "nn", "bc", "te", 126 | "io", "v7", "dm", "m0", "d1", "mr", "x3", "nm", "nu", "jc", "wy", "pa", "mn", 127 | "a_", "xz", "qr", "s1", "jo", "sw", "em", "jn", "cj", "j_"} 128 | 129 | def get_targets(line, users): 130 | targets = set() 131 | for token in line[2:]: 132 | token = token.lower() 133 | user = None 134 | if token in users and len(token) > 2: 135 | user = token 136 | else: 137 | core = [char for char in token] 138 | while len(core) > 0 and core[-1] in string.punctuation: 139 | core.pop() 140 | nword = ''.join(core) 141 | if nword in users and (len(core) > 2 or nword in common_short_names): 142 | user = nword 143 | break 144 | if user is None: 145 | while len(core) > 0 and core[0] in string.punctuation: 146 | core.pop(0) 147 | nword = ''.join(core) 148 | if nword in users and (len(core) > 2 or nword in common_short_names): 149 | user = nword 150 | break 151 | if user is not None: 152 | targets.add(user) 153 | return targets 154 | 155 | def lines_to_info(text_ascii): 156 | users = set() 157 | for line in text_ascii: 158 | update_users(line, users) 159 | 160 | chour = 12 161 | cmin = 0 162 | info = [] 163 | target_info = {} 164 | nexts = {} 165 | for line_no, line in enumerate(text_ascii): 166 | if line[0].startswith("["): 167 | user = line[1][1:-1] 168 | nexts.setdefault(user, []).append(line_no) 169 | 170 | prev = {} 171 | for line_no, line in enumerate(text_ascii): 172 | user = line[1] 173 | system = True 174 | if line[0].startswith("["): 175 | chour = int(line[0][1:3]) 176 | cmin = int(line[0][4:6]) 177 | user = user[1:-1] 178 | system = False 179 | is_bot = (user == 'ubottu' or user == 'ubotu') 180 | targets = get_targets(line, users) 181 | for target in targets: 182 | target_info.setdefault((user, target), []).append(line_no) 183 | last_from_user = prev.get(user, None) 184 | if not system: 185 | prev[user] = line_no 186 | next_from_user = None 187 | if user in nexts: 188 | while len(nexts[user]) > 0 and nexts[user][0] <= line_no: 189 | nexts[user].pop(0) 190 | if len(nexts[user]) > 0: 191 | next_from_user = nexts[user][0] 192 | 193 | info.append((user, targets, chour, cmin, system, is_bot, last_from_user, line, next_from_user)) 194 | 195 | return info, target_info 196 | 197 | def get_time_diff(info, a, b): 198 | if a is None or b is None: 199 | return -1 200 | if a > b: 201 | t = a 202 | a = b 203 | b = t 204 | ahour = info[a][2] 205 | amin = info[a][3] 206 | bhour = info[b][2] 207 | bmin = info[b][3] 208 | if ahour == bhour: 209 | return bmin - amin 210 | if bhour < ahour: 211 | bhour += 24 212 | return (60 - amin) + bmin + 60*(bhour - ahour - 1) 213 | 214 | cache = {} 215 | def get_features(name, query_no, link_no, text_ascii, text_tok, info, target_info, do_cache): 216 | global cache 217 | if (name, query_no, link_no) in cache: 218 | return cache[name, query_no, link_no] 219 | 220 | features = [] 221 | 222 | quser, qtargets, qhour, qmin, qsystem, qis_bot, qlast_from_user, qline, qnext_from_user = info[query_no] 223 | luser, ltargets, lhour, lmin, lsystem, lis_bot, llast_from_user, lline, lnext_from_user = info[link_no] 224 | 225 | # General information about this sample of data 226 | # Year 227 | for i in range(2004, 2018): 228 | features.append(str(i) in name) 229 | # Number of messages per minute 230 | start = None 231 | end = None 232 | for i in range(len(text_ascii)): 233 | if start is None and text_ascii[i][0].startswith("["): 234 | start = i 235 | if end is None and i > 0 and text_ascii[-i][0].startswith("["): 236 | end = len(text_ascii) - i - 1 237 | if start is not None and end is not None: 238 | break 239 | diff = get_time_diff(info, start, end) 240 | msg_per_min = len(text_ascii) / max(1, diff) 241 | cutoffs = [-1, 1, 3, 10, 10000] 242 | for start, end in zip(cutoffs, cutoffs[1:]): 243 | features.append(start <= msg_per_min < end) 244 | 245 | # Query 246 | # - Normal message or system message 247 | features.append(qsystem) 248 | # - Hour of day 249 | features.append(qhour / 24) 250 | # - Is it targeted 251 | features.append(len(qtargets) > 0) 252 | # - Is there a previous message from this user? 253 | features.append(qlast_from_user is not None) 254 | # - Did the previous message from this user have a target? 255 | if qlast_from_user is None: 256 | features.append(False) 257 | else: 258 | features.append(len(info[qlast_from_user][1]) > 0) 259 | # - How long ago was the previous message from this user in messages? 260 | dist = -1 if qlast_from_user is None else query_no - qlast_from_user 261 | cutoffs = [-1, 0, 1, 5, 20, 1000] 262 | for start, end in zip(cutoffs, cutoffs[1:]): 263 | features.append(start <= dist < end) 264 | # - How long ago was the previous message from this user in minutes? 265 | time = get_time_diff(info, query_no, qlast_from_user) 266 | cutoffs = [-1, 0, 2, 10, 10000] 267 | for start, end in zip(cutoffs, cutoffs[1:]): 268 | features.append(start <= time < end) 269 | # - Are they a bot? 270 | features.append(qis_bot) 271 | 272 | ###- Often a person asks a question as the first thing they do after entering the channel. Could be a useful feature. Encode as how long ago they entered, or if this is their first message since entering. 273 | 274 | # Link 275 | # - Normal message or system message 276 | features.append(lsystem) 277 | # - Hour of day 278 | features.append(lhour / 24) 279 | # - Is it targeted 280 | features.append(link_no != query_no and len(ltargets) > 0) 281 | # - Is there a previous message from this user? 282 | features.append(link_no != query_no and llast_from_user is not None) 283 | # - Did the previous message from this user have a target? 284 | if link_no == query_no or llast_from_user is None: 285 | features.append(False) 286 | else: 287 | features.append(len(info[llast_from_user][1]) > 0) 288 | # - How long ago was the previous message from this user in messages? 289 | dist = -1 if llast_from_user is None else link_no - llast_from_user 290 | cutoffs = [-1, 0, 1, 5, 20, 1000] 291 | for start, end in zip(cutoffs, cutoffs[1:]): 292 | features.append(link_no != query_no and start <= dist < end) 293 | # - How long ago was the previous message from this user in minutes? 294 | time = get_time_diff(info, link_no, llast_from_user) 295 | cutoffs = [-1, 0, 2, 10, 10000] 296 | for start, end in zip(cutoffs, cutoffs[1:]): 297 | features.append(start <= time < end) 298 | # - Are they a bot? 299 | features.append(lis_bot) 300 | # - Is the message after from the same user? 301 | features.append(link_no != query_no and link_no + 1 < len(info) and luser == info[link_no + 1][0]) 302 | # - Is the message before from the same user? 303 | features.append(link_no != query_no and link_no - 1 > 0 and luser == info[link_no - 1][0]) 304 | 305 | # Both 306 | # - Is this a self-link? 307 | features.append(link_no == query_no) 308 | # - How far apart in messages are the two? 309 | dist = query_no - link_no 310 | features.append(min(100, dist) / 100) 311 | features.append(dist > 1) 312 | # - How far apart in time are the two? 313 | time = get_time_diff(info, link_no, query_no) 314 | features.append(min(100, time) / 100) 315 | cutoffs = [-1, 0, 1, 5, 60, 10000] 316 | for start, end in zip(cutoffs, cutoffs[1:]): 317 | features.append(start <= time < end) 318 | # - Does the link target the query user? 319 | features.append(quser.lower() in ltargets) 320 | # - Does the query target the link user? 321 | features.append(luser.lower() in qtargets) 322 | # - none in between from src? 323 | features.append(link_no != query_no and (qlast_from_user is None or qlast_from_user < link_no)) 324 | # - none in between from target? 325 | features.append(link_no != query_no and (lnext_from_user is None or lnext_from_user > query_no)) 326 | # - previously src addressed target? 327 | # - future src addressed target? 328 | # - src addressed target in between? 329 | if link_no != query_no and (quser, luser) in target_info: 330 | features.append(min(target_info[quser, luser]) < link_no) 331 | features.append(max(target_info[quser, luser]) > query_no) 332 | between = False 333 | for num in target_info[quser, luser]: 334 | if query_no > num > link_no: 335 | between = True 336 | features.append(between) 337 | else: 338 | features.append(False) 339 | features.append(False) 340 | features.append(False) 341 | # - previously target addressed src? 342 | # - future target addressed src? 343 | # - target addressed src in between? 344 | if link_no != query_no and (luser, quser) in target_info: 345 | features.append(min(target_info[luser, quser]) < link_no) 346 | features.append(max(target_info[luser, quser]) > query_no) 347 | between = False 348 | for num in target_info[luser, quser]: 349 | if query_no > num > link_no: 350 | between = True 351 | features.append(between) 352 | else: 353 | features.append(False) 354 | features.append(False) 355 | features.append(False) 356 | # - are they the same speaker? 357 | features.append(luser == quser) 358 | # - do they have the same target? 359 | features.append(link_no != query_no and len(ltargets.intersection(qtargets)) > 0) 360 | # - Do they have words in common? 361 | ltokens = set(text_ascii[link_no]) 362 | qtokens = set(text_ascii[query_no]) 363 | common = len(ltokens.intersection(qtokens)) 364 | if link_no != query_no and len(ltokens) > 0 and len(qtokens) > 0: 365 | features.append(common / len(ltokens)) 366 | features.append(common / len(qtokens)) 367 | else: 368 | features.append(False) 369 | features.append(False) 370 | features.append(link_no != query_no and common == 0) 371 | features.append(link_no != query_no and common == 1) 372 | features.append(link_no != query_no and common > 1) 373 | features.append(link_no != query_no and common > 5) 374 | 375 | # Convert to 0/1 376 | final_features = [] 377 | for feature in features: 378 | if feature == True: 379 | final_features.append(1.0) 380 | elif feature == False: 381 | final_features.append(0.0) 382 | else: 383 | final_features.append(feature) 384 | ### print(query_no, link_no, ' '.join([str(int(v)) for v in final_features])) 385 | 386 | if do_cache: 387 | cache[name, query_no, link_no] = final_features 388 | return final_features 389 | 390 | 391 | def read_data(filenames, is_test=False): 392 | instances = [] 393 | for filename in filenames: 394 | name = filename 395 | for ending in [".annotation.txt", ".ascii.txt", ".raw.txt", ".tok.txt"]: 396 | if filename.endswith(ending): 397 | name = filename[:-len(ending)] 398 | text_ascii = [l.strip().split() for l in open(name +".ascii.txt")] 399 | text_tok = [] 400 | for l in open(name +".tok.txt"): 401 | l = l.strip().split() 402 | if len(l) > 0 and l[-1] == "": 403 | l = l[:-1] 404 | if len(l) == 0 or l[0] != '': 405 | l.insert(0, "") 406 | text_tok.append(l) 407 | info, target_info = lines_to_info(text_ascii) 408 | 409 | links = {} 410 | if is_test: 411 | for i in range(args.test_start, min(args.test_end, len(text_ascii))): 412 | links[i] = [] 413 | else: 414 | for line in open(name +".annotation.txt"): 415 | nums = [int(v) for v in line.strip().split() if v != '-'] 416 | links.setdefault(max(nums), []).append(min(nums)) 417 | for link, nums in links.items(): 418 | instances.append((name +".annotation.txt", link, nums, text_ascii, text_tok, info, target_info)) 419 | return instances 420 | 421 | def simplify_token(token): 422 | chars = [] 423 | for char in token: 424 | #### Reduce sparsity by replacing all digits with 0. 425 | if char.isdigit(): 426 | chars.append("0") 427 | else: 428 | chars.append(char) 429 | return ''.join(chars) 430 | 431 | 432 | if PYTORCH: 433 | class PyTorchModel(torch.nn.Module): 434 | def __init__(self): 435 | super().__init__() 436 | 437 | self.hidden1 = torch.nn.Linear(FEATURES, HIDDEN) 438 | self.nonlin1 = torch.nn.Tanh() 439 | self.hidden2 = torch.nn.Linear(HIDDEN, HIDDEN) 440 | self.nonlin2 = torch.nn.Tanh() 441 | 442 | self.loss_function = torch.nn.CrossEntropyLoss(reduction='sum') 443 | 444 | def forward(self, query, options, gold, lengths, query_no): 445 | answer = max(gold) 446 | 447 | # Concatenate the other features 448 | features = torch.tensor([v[1] for v in options]) 449 | 450 | h1 = self.nonlin1(self.hidden1(features)) 451 | h2 = self.nonlin2(self.hidden2(h1)) 452 | scores = torch.sum(h2, 1) 453 | output_scores = torch.unsqueeze(torch.unsqueeze(scores, 0), 2) 454 | 455 | # Get loss and prediction 456 | true_out = torch.tensor([[answer]]) 457 | loss = self.loss_function(output_scores, true_out) 458 | predicted_link = torch.argmax(output_scores, 1) 459 | return loss, predicted_link 460 | 461 | class DyNetModel(): 462 | def __init__(self): 463 | super().__init__() 464 | 465 | self.model = dy.ParameterCollection() 466 | 467 | input_size = FEATURES 468 | 469 | # Create word embeddings and initialise 470 | self.id_to_token = [] 471 | self.token_to_id = {} 472 | pretrained = [] 473 | if args.word_vectors: 474 | for line in open(args.word_vectors): 475 | parts = line.strip().split() 476 | word = parts[0].lower() 477 | vector = [float(v) for v in parts[1:]] 478 | self.token_to_id[word] = len(self.id_to_token) 479 | self.id_to_token.append(word) 480 | pretrained.append(vector) 481 | NWORDS = len(self.id_to_token) 482 | DIM_WORDS = len(pretrained[0]) 483 | self.pEmbedding = self.model.add_lookup_parameters((NWORDS, DIM_WORDS)) 484 | self.pEmbedding.init_from_array(np.array(pretrained)) 485 | input_size += 4 * DIM_WORDS 486 | 487 | self.hidden = [] 488 | self.bias = [] 489 | self.hidden.append(self.model.add_parameters((HIDDEN, input_size))) 490 | self.bias.append(self.model.add_parameters((HIDDEN,))) 491 | for i in range(args.layers - 1): 492 | self.hidden.append(self.model.add_parameters((HIDDEN, HIDDEN))) 493 | self.bias.append(self.model.add_parameters((HIDDEN,))) 494 | self.final_sum = self.model.add_parameters((HIDDEN, 1)) 495 | 496 | def __call__(self, query, options, gold, lengths, query_no): 497 | if len(options) == 1: 498 | return None, 0 499 | 500 | final = [] 501 | if args.word_vectors: 502 | qvecs = [dy.lookup(self.pEmbedding, w) for w in query] 503 | qvec_max = dy.emax(qvecs) 504 | qvec_mean = dy.average(qvecs) 505 | for otext, features in options: 506 | inputs = dy.inputTensor(features) 507 | if args.word_vectors: 508 | ovecs = [dy.lookup(self.pEmbedding, w) for w in otext] 509 | ovec_max = dy.emax(ovecs) 510 | ovec_mean = dy.average(ovecs) 511 | inputs = dy.concatenate([inputs, qvec_max, qvec_mean, ovec_max, ovec_mean]) 512 | if args.drop > 0: 513 | inputs = dy.dropout(inputs, args.drop) 514 | h = inputs 515 | for pH, pB in zip(self.hidden, self.bias): 516 | h = dy.affine_transform([pB, pH, h]) 517 | if args.nonlin == "linear": 518 | pass 519 | elif args.nonlin == "tanh": 520 | h = dy.tanh(h) 521 | elif args.nonlin == "cube": 522 | h = dy.cube(h) 523 | elif args.nonlin == "logistic": 524 | h = dy.logistic(h) 525 | elif args.nonlin == "relu": 526 | h = dy.rectify(h) 527 | elif args.nonlin == "elu": 528 | h = dy.elu(h) 529 | elif args.nonlin == "selu": 530 | h = dy.selu(h) 531 | elif args.nonlin == "softsign": 532 | h = dy.softsign(h) 533 | elif args.nonlin == "swish": 534 | h = dy.cmult(h, dy.logistic(h)) 535 | final.append(dy.sum_dim(h, [0])) 536 | 537 | final = dy.concatenate(final) 538 | nll = -dy.log_softmax(final) 539 | dense_gold = [] 540 | for i in range(len(options)): 541 | dense_gold.append(1.0 / len(gold) if i in gold else 0.0) 542 | answer = dy.inputTensor(dense_gold) 543 | loss = dy.transpose(answer) * nll 544 | predicted_link = np.argmax(final.npvalue()) 545 | 546 | return loss, predicted_link 547 | 548 | def get_ids(self, words): 549 | ans = [] 550 | backup = self.token_to_id.get('', 0) 551 | for word in words: 552 | ans.append(self.token_to_id.get(word, backup)) 553 | return ans 554 | 555 | def do_instance(instance, train, model, optimizer, do_cache=True): 556 | name, query, gold, text_ascii, text_tok, info, target_info = instance 557 | 558 | # Skip cases if we can't represent them 559 | gold = [v for v in gold if v > query - MAX_DIST] 560 | if len(gold) == 0 and train: 561 | return 0, False, query 562 | 563 | # Get features 564 | options = [] 565 | query_ascii = text_ascii[query] 566 | query_tok = model.get_ids(text_tok[query]) 567 | for i in range(query, max(-1, query - MAX_DIST), -1): 568 | option_ascii = text_ascii[i] 569 | option_tok = model.get_ids(text_tok[i]) 570 | features = get_features(name, query, i, text_ascii, text_tok, info, target_info, do_cache) 571 | options.append((option_tok, features)) 572 | gold = [query - v for v in gold] 573 | lengths = [len(sent) for sent in options] 574 | 575 | # Run computation 576 | example_loss, output = model(query_tok, options, gold, lengths, query) 577 | loss = 0.0 578 | if train and example_loss is not None: 579 | if PYTORCH: 580 | example_loss.backward() 581 | # TODO: Gradient clipping 582 | optimizer.step() 583 | model.zero_grad() 584 | loss = example_loss.item() 585 | else: 586 | example_loss.backward() 587 | optimizer.update() 588 | loss = example_loss.scalar_value() 589 | predicted = output 590 | if PYTORCH: 591 | predicted = output.item() 592 | matched = (predicted in gold) 593 | 594 | return loss, matched, predicted 595 | 596 | ############################################################################### 597 | 598 | train = [] 599 | if args.train: 600 | train = read_data(args.train) 601 | dev = [] 602 | if args.dev: 603 | dev = read_data(args.dev) 604 | test = dev 605 | if args.test: 606 | test = read_data(args.test, True) 607 | if args.random_sample and args.train: 608 | random.seed(args.seed) 609 | random.shuffle(train) 610 | train = train[:int(args.random_sample)] 611 | 612 | # Model and optimizer creation 613 | model = None 614 | optimizer = None 615 | scheduler = None 616 | if PYTORCH: 617 | model = PyTorchModel() 618 | optimizer = torch.optim.SGD(model.parameters(), lr=LEARNING_RATE, 619 | weight_decay=WEIGHT_DECAY) 620 | rescale_lr = lambda epoch: 1 / (1 + LEARNING_DECAY_RATE * epoch) 621 | scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, 622 | lr_lambda=rescale_lr) 623 | else: 624 | model = DyNetModel() 625 | optimizer = None 626 | if args.opt == 'sgd': 627 | optimizer = dy.SimpleSGDTrainer(model.model, learning_rate=LEARNING_RATE) 628 | elif args.opt == 'mom': 629 | optimizer = dy.MomentumSGDTrainer(model.model, learning_rate=LEARNING_RATE, mom=MOMENTUM) 630 | elif args.opt == 'csgd': 631 | pass 632 | ### optimizer = dy.CyclicalSGDTrainer(model.model, learning_rate=LEARNING_RATE, mom=MOMENTUM) lrmin, lrmax, step, gamma (decay) 633 | optimizer.set_clip_threshold(args.clip) 634 | 635 | prev_best = None 636 | if args.train: 637 | step = 0 638 | for epoch in range(EPOCHS): 639 | random.shuffle(train) 640 | 641 | # Update learning rate 642 | if PYTORCH: 643 | scheduler.step() 644 | else: 645 | optimizer.learning_rate = LEARNING_RATE / (1+ LEARNING_DECAY_RATE * epoch) 646 | 647 | # Loop over batches 648 | loss = 0 649 | match = 0 650 | total = 0 651 | loss_steps = 0 652 | for instance in train: 653 | step += 1 654 | 655 | if PYTORCH: 656 | model.train() 657 | model.zero_grad() 658 | else: 659 | dy.renew_cg() 660 | ex_loss, matched, _ = do_instance(instance, True, model, optimizer) 661 | loss += ex_loss 662 | loss_steps += 1 663 | if matched: 664 | match += 1 665 | total += len(instance[2]) 666 | 667 | # Partial results 668 | if step % args.report_freq == 0: 669 | # Dev pass 670 | if PYTORCH: 671 | model.eval() 672 | dev_match = 0 673 | dev_total = 0 674 | for dinstance in dev: 675 | if not PYTORCH: 676 | dy.renew_cg() 677 | _, matched, _ = do_instance(dinstance, False, model, optimizer) 678 | if matched: 679 | dev_match += 1 680 | dev_total += len(dinstance[2]) 681 | 682 | tacc = match / total 683 | dacc = dev_match / dev_total 684 | print("{} tl {:.3f} ta {:.3f} da {:.3f} from {} {}".format(epoch, loss / loss_steps, tacc, dacc, dev_match, dev_total), file=log_file) 685 | log_file.flush() 686 | 687 | if prev_best is None or prev_best[0] < dacc: 688 | prev_best = (dacc, epoch) 689 | if PYTORCH: 690 | torch.save(model.state_dict(), args.prefix +".pt.model") 691 | else: 692 | model.model.save(args.prefix + ".dy.model") 693 | 694 | if prev_best is not None and epoch - prev_best[1] > 5: 695 | break 696 | 697 | # Load model 698 | if prev_best is not None or args.model: 699 | location = args.model 700 | if PYTORCH: 701 | if location is None: 702 | location = args.prefix +'.pt.model' 703 | model.load_state_dict(torch.load(location)) 704 | else: 705 | if location is None: 706 | location = args.prefix +".dy.model" 707 | model.model.populate(location) 708 | 709 | # Evaluation pass. 710 | for instance in test: 711 | if not PYTORCH: 712 | dy.renew_cg() 713 | _, _, prediction = do_instance(instance, False, model, optimizer, False) 714 | print("{}:{} {} -".format(instance[0], instance[1], instance[1] - prediction)) 715 | 716 | log_file.close() 717 | 718 | -------------------------------------------------------------------------------- /subtask4/reserved_words.py: -------------------------------------------------------------------------------- 1 | 2 | # These are: 3 | # - Names of Ubuntu versions 4 | # - Words that occur 100x as often in a message as they do as a user name 5 | reserved = { 6 | 'ubuntu', 'help', 'linux' 7 | "topic", "signoff", "signon", "total", "#ubuntu", "window", "server:", 8 | "screen:", "geometry", "co,", "current", "query", "prompt:", "second", "split", 9 | "logging", "logfile", "notification", "hold", "window", "lastlog", "notify", 10 | 'netjoined:', 11 | "artful", "aardvark", "bionic", "beaver", "breezy", "badger", "cosmic", 12 | "cuttlefish", "dapper", "drake", "disco", "dingo", "edgy", "eft", "feisty", 13 | "fawn", "gutsy", "gibbon", "hardy", "heron", "hoary", "hedgehog", "intrepid", 14 | "ibex", "jaunty", "jackalope", "karmic", "koala", "lucid", "lynx", "maverick", 15 | "meerkat", "natty", "narwhal", "oneiric", "ocelot", "precise", "pangolin", 16 | "quantal", "quetzal", "raring", "ringtail", "saucy", "salamander", "trusty", 17 | "tahr", "utopic", "unicorn", "vivid", "vervet", "warty", "warthog", "wily", 18 | "werewolf", "xenial", "xerus", "yakkety", "yak", "zesty", "zapus", 19 | "`", "^^", "^_^", "^", "||", "|", "_", "[", "[[", "]]", "{", "\\", "\\\\", "^5", "a", 20 | "aaah", "aaahhh", "aao", "aargh", "abandoned", "abit", "able", "abot", "about", 21 | "above", "absolute", "accent", "accept", "acceptance", "acces", "access", 22 | "accident", "account", "accused", "acpi", "acronym", "across", "act", "action", 23 | "active", "activex", "acts", "adapter", "adb", "add", "addict", "adding", 24 | "additional", "addon", "adds", "adduser", "adept", "administer", 25 | "administration", "administrators", "adn", "adobe", "adsl", "advanced", 26 | "adventure", "advertise", "advertising", "advise", "af", "afk", "african", 27 | "after", "again", "against", "aggravating", "aggressive", "ago", "agp", 28 | "agree", "ah", "aha", "ahead", "ahh", "ahhh", "ahhhh", "ahs", "ai", "air", 29 | "airflow", "airsnort", "ait", "aix", "album", "alert", "algorithm", "alguien", 30 | "algun", "alias", "aliases", "all", "alla", "allegro", "alli", "alliance", 31 | "allow", "allright", "almost", "alo", "alone", "along", "alors", "already", 32 | "alsa", "alsaconf", "alse", "also", "alt", "alter", "alternate", "alternative", 33 | "always", "am", "amarok", "amazed", "amazing", "amazon", "amd", "amd64", 34 | "among", "ampache", "an", "analog", "analysis", "analyzer", "and", "angles", 35 | "animals", "anime", "anjuta", "anotehr", "another", "ansible", "antenna", 36 | "anthy", "any", "anybody", "anyone", "anything", "anyway", "anywhere", "aol", 37 | "apache", "apache2", "apci", "apis", "apm", "apology", "app", "appears", 38 | "apple", "applet", "application", "applied", "apply", "appreciated", 39 | "appropriate", "apps", "apr", "april", "aprox", "apt", "apt-get", "aptitude", 40 | "archaic", "architecture", "archive", "archiver", "archives", "archlinux", 41 | "are", "area", "arena", "arg", "argh", "arise", "arista", "ark", "arm", "arms", 42 | "array", "arrgh", "artist", "arts", "as", "asap", "ascii", "aside", "ask", 43 | "asking", "asla", "ass", "assertion", "assist", "assistance", "association", 44 | "at", "ath0", "athlonxp", "ati", "atm", "atsc", "attack", "attackers", 45 | "attempt", "attractive", "audacity", "audigy", "audio", "audition", "aug", 46 | "aus", "auth", "author", "authority", "authorized", "auto", "automated", 47 | "automatic", "automatix", "autostart", "aux", "av", "avail", "available", 48 | "avant", "avconv", "aw", "aware", "away", "awe", "awesome", "awry", "awww", 49 | "awwww", "aye", "ayone", "ayuda", "azalia", "b4", "back", "backdoor", 50 | "backintime", "backlight", "backport", "backspace", "backup", "bad", "bahasa", 51 | "bakc", "balloon", "ban", "band", "banned", "banning", "banshee", "bar", 52 | "barrel", "bars", "base", "basement", "bash", "bashing", "bashrc", "basic", 53 | "bastard", "battery", "bay", "bbl", "bcm4318", "bcm43xx", "bcm43xx-fwcutter", 54 | "bcz", "be", "beagle", "beautiful", "beauty", "becase", "because", "bed", 55 | "been", "beep", "beers", "beg", "begin", "begs", "being", "bell", "bells", 56 | "bench", "berly", "bery", "beryl", "best", "bet", "beta", "better", "beyond", 57 | "bg", "bi", "bias", "bible", "bie", "big", "biger", "bigger", "biggy", "bin", 58 | "binary", "bios", "bit", "bitch", "bitches", "bitchx", "bitlbee", "bitrate", 59 | "bitten", "bittorrent", "bizarre", "bizzare", "bla", "black", "blacklist", 60 | "bleeding", "blew", "blinking", "block", "blocks", "blow", "blue", "bluefish", 61 | "blueman", "bluetooth", "bluez", "blu-ray", "bmp", "bnc", "boat", "bochs", 62 | "body", "bonding", "bonsoir", "book", "books", "boost", "boot", "booted", 63 | "bootloader", "bootmgr", "boots", "boottime", "bootup", "border", "bose", 64 | "both", "botnet", "bots", "botsnack", "bound", "bout", "box", "boxes", "boys", 65 | "brackets", "brake", "branch", "branches", "brand", "brasero", "brave", 66 | "brazil", "brb", "break", "breaks", "breezy", "bricks", "bridge", "brightness", 67 | "brightside", "brilliant", "british", "broad", "broadband", "broke", "brother", 68 | "brown", "browser", "browsing", "bsd", "btnx", "btrfs", "btw", "budget", 69 | "buffer", "bug", "bugfixes", "bugger", "buggy", "bugs", "bugzilla", "build", 70 | "bulk", "burn", "burned", "burning", "busca", "busted", "busy", "busybox", 71 | "but", "button", "buttons", "buzz", "by", "bzip", "c", "c2", "ca", "cable", 72 | "cache", "cacher", "caldera", "calendar", "california", "call", "called", 73 | "caller", "came", "camera", "campus", "cams", "can", "canada", "cancel", 74 | "canonical", "cant", "capital", "capitals", "caps", "capslock", "car", "card", 75 | "cards", "care", "carry", "cases", "`cat", "cat5", "catalyst", "ccleaner", 76 | "cd", "cd1", "cd-r", "cds", "ce", "celeron", "cellphone", "center", "centos", 77 | "century", "certain", "certificate", "cfdisk", "challenged", "chance", 78 | "chanell", "change", "changing", "charge", "charged", "charm", "chars", 79 | "charset", "chat", "chatter", "cheat", "check", "checker", "checks", "cheers", 80 | "chess", "chicago", "child", "chime", "china", "chinese", "chips", "chipset", 81 | "chm", "chmod", "choice", "choices", "choppy", "chops", "chose", "chosen", 82 | "chown", "chowned", "christ", "christmas", "chrome", "chromium", "chunk", 83 | "chunks", "ci", "ciao", "cigarettes", "circuits", "claim", "class", "clean", 84 | "cleaner", "clear", "cli", "click", "client", "clients", "clock", "clocking", 85 | "clone", "clonezilla", "close", "closed", "closer", "clue", "clueless", 86 | "clutter", "cmd", "cms", "cnt", "cobol", "coc", "code", "coded", "coders", 87 | "coding", "color", "column", "com", "comand", "combine", "comcast", "come", 88 | "comfort", "comics", "coming", "command", "command-line", "commandline", 89 | "common", "community", "como", "comp", "compile", "compiler", "compiz", 90 | "complete", "compliant", "comply", "component", "composite", "compressed", 91 | "computer", "computers", "concentrate", "concepts", "concerned", "concrete", 92 | "conf", "confident", "config", "conflict", "confuse", "confusion", "conky", 93 | "connect", "connected", "connecting", "connection", "connections", "connector", 94 | "console", "construct", "contact", "contents", "contract", "control", 95 | "controller", "controls", "controversial", "convert", "converted", "converter", 96 | "convinced", "coo", "cookies", "copies", "copy", "core2", "core2duo", "corner", 97 | "correct", "corrupted", "cost", "couch", "coucou", "coul", "counter", 98 | "country", "couple", "cousin", "cousins", "cover", "cpanel", "cpp", "cpu", 99 | "cpufreqd", "crappy", "crash", "crashed", "crazy", "create", "creating", 100 | "creation", "creative", "creator", "crippled", "critical", "cron", "cronjob", 101 | "crontab", "cross", "crossover", "crt", "crud", "cry", "ctcp", "ctrl", 102 | "ctrl-alt-del", "cuda", "culprit", "cup", "cure", "curious", "current", 103 | "curses", "cursor", "curve", "cuss", "custom", "customize", "cuz", "cvs", "cz", 104 | "czech", "czy", "daemons", "daily", "damn", "damnit", "dances", "dancing", 105 | "dang", "danger", "dangerous", "danko", "dapper", "darn", "dashboard", "data", 106 | "dates", "day", "daytime", "db", "dban", "dbus", "dcc", "dd", "de", "dead", 107 | "deal", "deb", "debain", "debian", "debians", "debs", "debug", "dec", "decade", 108 | "decent", "decode", "decoded", "decrypt", "decryption", "dedicated", "deeper", 109 | "def", "defalt", "default", "defect", "defense", "deff", "define", "defined", 110 | "defult", "deg", "degree", "delay", "delet", "delete", "deleted", "deluge", 111 | "demonoid", "demuxer", "denied", "dependencies", "depth", "design", "designer", 112 | "desktop", "destination", "destroy", "detached", "detail", "detected", 113 | "detection", "determin", "deutsch", "deutsche", "dev", "devede", "develop", 114 | "device", "devote", "devs", "df", "dhcp", "diag", "diagnostic", "dial", 115 | "dial-up", "dictionary", "did", "died", "dif", "diff", "different", 116 | "difficult", "dig", "dilemma", "dillo", "dinner", "dir", "dire", "directory", 117 | "directx", "disabled", "disappear", "disappeared", "disc", "disconnect", 118 | "disconnected", "discrete", "diskette", "disks", "display", "diss", "dist", 119 | "distinct", "distorted", "distracted", "distribution", "distro", "distupgrade", 120 | "disturb", "dit", "ditch", "dl", "dlink", "dmesg", "dns", "do", "doable", 121 | "doc", "dock", "docker", "docky", "dod", "doe", "does", "doki", "domain", 122 | "domu", "done", "dongle", "donno", "dont", "dos", "dose", "dots", "double", 123 | "doubleclick", "doubt", "dove", "down", "downgrade", "downloader", 124 | "downloading", "downtime", "doze", "dozen", "dpi", "dram", "draw", "drawn", 125 | "dreamweaver", "dress", "dri", "drinks", "drive", "driver", "drm", "drop", 126 | "dropbox", "dropped", "drops", "drug", "drums", "dsp", "du", "dual", 127 | "dualboot", "dudes", "due", "duh", "dumb", "dummies", "dump", "dun", "dunno", 128 | "duo", "duplex", "duplicated", "duplicity", "duron", "dvb", "dvd", "dvd-rw", 129 | "dvdrw", "dvds", "dvr", "dynamic", "e", "e2fsck", "each", "ear", "early", 130 | "earth", "ease", "east", "easter", "easy", "eat", "ebay", "edit", "edited", 131 | "editor", "ee", "eed", "eeebuntu", "een", "effect", "effective", "effort", 132 | "efi", "eg", "eh", "ehat", "eheh", "eide", "electronic", "elegant", "elements", 133 | "elevate", "elevated", "elitist", "ello", "else", "emacs", "email", "embedded", 134 | "embeded", "emerald", "emergency", "emmm", "empathy", "empty", "emulator", 135 | "emulators", "en", "encode", "encoder", "encoding", "encrypted", "encryption", 136 | "end", "enemy", "engine", "engineering", "english", "enjoy", "enlightened", 137 | "enter", "entra", "entrance", "enuf", "enumerate", "enumeration", "env", 138 | "envy", "enyone", "eol", "epiphany", "equipment", "equipped", "er", "erase", 139 | "erh", "erlang", "erorr", "err", "errno", "erro", "erroneous", "error", "es", 140 | "esd", "est", "este", "estimate", "et", "eta", "etc", "etch", "eth", "eth0", 141 | "eth2", "ethernet", "etho", "european", "even", "evening", "ever", "everybody", 142 | "everyday", "evidence", "evolution", "evolved", "ew", "ex", "exact", "exceed", 143 | "excellent", "except", "excessive", "exe", "exec", "execute", "exfat", "exist", 144 | "existed", "existence", "exit", "expect", "expecting", "experiment", "expert", 145 | "explicit", "explicitly", "explode", "explorer", "export", "express", 146 | "expression", "ext", "ext3", "ext4", "extended", "extra", "eye", "eyecandy", 147 | "eyes", "f1", "f10", "f2", "f3", "f7", "facebook", "faced", "fact", "factoid", 148 | "fail", "fair", "fait", "fake", "fala", "fallow", "falls", "familiar", "fan", 149 | "fancy", "fantasy", "faptastic", "far", "fashion", "faster", "fastest", 150 | "fat32", "fatal", "fatrat", "fault", "faulty", "favor", "favorite", 151 | "favorites", "favourite", "fawn", "fb", "fd0", "fdd", "fdi", "feat", "feb", 152 | "fedora", "fee", "feed", "feel", "feeling", "feisty", "fellas", "fellow", 153 | "fetch", "few", "ff", "ff2", "fglrx", "fi", "fiddle", "field", "fighting", 154 | "file", "files", "fileserver", "filesystem", "fill", "filling", "filter", 155 | "filtered", "final", "finally", "find", "fine", "fing", "fingers", "fins", 156 | "firebug", "firefox", "firefox3", "firestarter", "firewall", "firewalls", 157 | "firewire", "firmware", "first", "firstly", "fishing", "fits", "fix", "fixed", 158 | "flag", "flaky", "flamed", "flash", "flashed", "flashget", "flashplugin", 159 | "flavor", "flavors", "flawed", "flickering", "flock", "flood", "floodbot", 160 | "flooding", "floola", "floor", "floppy", "floss", "fluff", "flux", "fluxbox", 161 | "fly", "fml", "fn", "focus", "folder", "folk", "folks", "follow", "font", 162 | "fonts", "foobar2000", "fools", "foomatic", "football", "footprint", "fopen", 163 | "for", "force", "forensic", "forget", "forgotten", "fork", "form", "format", 164 | "formatted", "forme", "former", "formula", "forth", "fortress", "fortune", 165 | "forum", "forward", "foss", "found", "founder", "fr", "francais", "free", 166 | "freebsd", "freely", "freenode", "freevo", "freeware", "freezes", "freezing", 167 | "french", "fresh", "freshly", "friend", "friendly", "friends", "friggin", 168 | "frist", "fro", "from", "froze", "fs", "fsck", "fsf", "fspot", "ftp", "ftw", 169 | "fucker", "fuhrer", "full", "fullscreen", "fully", "function", "funny", "fuss", 170 | "future", "fvwm", "g3", "g5", "gaah", "gadmin", "gah", "gals", "game", "games", 171 | "gaming", "garbage", "gates", "gateway", "gather", "gave", "gay", "gb", "gcc", 172 | "gconf", "gconftool", "gd", "gdisk", "gear", "geeks", "geese", "gem", 173 | "general", "generate", "gentoo", "get", "getty", "gf", "gftp", "gfx", "ghz", 174 | "gib", "gibbon", "gift", "gig", "gigabit", "gimp", "girlfriend", "gist", "git", 175 | "give", "gksudo", "glad", "glibc", "gmp", "gmt", "gnash", "gnewsense", "gnite", 176 | "gnome", "gnomes", "gnome-shell", "gnome-terminal", "gnone", "gns3", "gnu", 177 | "gnutella", "go", "goddamnit", "gods", "goes", "goin", "going", "golly", 178 | "gone", "gonna", "good", "goodbye", "goodness", "goodnight", "google", 179 | "googled", "google-fu", "googles", "googling", "goole", "goood", "goot", "got", 180 | "goto", "gotten", "government", "gpart", "gparted", "gpg", "gpt", "gpu", "gq", 181 | "grabbed", "gracias", "grade", "grain", "grammer", "grand", "grants", "graph", 182 | "graphic", "graphical", "graphics", "graphix", "grasp", "grats", "gratz", 183 | "grazie", "great", "grep", "greyed", "grid", "grief", "ground", "groundhog", 184 | "growisofs", "grr", "grub", "grub2", "grubs", "gsm", "gstreamer", "gta", "gtg", 185 | "gtk", "gues", "guess", "guessing", "gui", "guid", "guide", "guilty", "guis", 186 | "gusty", "guts", "gutsy", "guy", "guys", "guyz", "gvim", "gw", "gxmame", "gym", 187 | "gz", "ha", "haa", "hacked", "hackers", "hacking", "hacks", "had", "hadoop", 188 | "haha", "hahaha", "hahahah", "hahahaha", "hahahahah", "half", "halflife", 189 | "halfway", "halloween", "haloo", "hand", "handle", "hands", "handy", "hang", 190 | "hanks", "happier", "happily", "hard", "harddrive", "harder", "hardly", 191 | "hardware", "hardy", "has", "hate", "hav", "have", "haves", "hd", "hda", 192 | "hda1", "hdb", "hdd", "hdtv", "he", "head", "header", "headless", "headphone", 193 | "heads", "healthy", "hear", "heart", "heartbleed", "heat", "heavy", "heck", 194 | "hee", "hefty", "heh", "hehe", "heheh", "heil", "held", "hell", "hella", 195 | "helllo", "hello", "heloo", "help", "hence", "here", "heres", "heron", 196 | "herring", "het", "heu", "heve", "hex", "hey", "heya", "heyyy", "hi", "hidden", 197 | "hides", "hie", "hier", "high", "high-end", "hii", "hilfe", "him", "himself", 198 | "hint", "his", "history", "hit", "hits", "hl2", "hm", "hmm", "hmmm", "hmmmmm", 199 | "ho", "hoary", "hoe", "hokay", "holder", "homepage", "homeserver", "homework", 200 | "honest", "honesty", "hoops", "hooray", "hope", "horny", "horrid", "hosed", 201 | "host", "hosting", "hostname", "hotspot", "hours", "how", "howso", "howto", 202 | "howtos", "hr", "hrhr", "hrm", "hrs", "hsf", "hsync", "htop", "http", "huawei", 203 | "hug", "huge", "huh", "hum", "hung", "hw", "hwe", "hwy", "hy", "hypervisor", 204 | "_i_", "i", "i3", "i386", "i7", "ia64", "ibook", "ican", "iceweasel", "ici", 205 | "icon", "icons", "icq", "ics", "id", "id3", "ide", "idea", "ideas", "ident", 206 | "idiocy", "idk", "idle", "idling", "idont", "ie", "ieee", "if", "iface", 207 | "ifconfig", "iffy", "ifup", "ignorance", "ignorant", "ignore", "igp", "ihr", 208 | "iii", "iin", "ill", "illiterate", "illustrator", "i`m", "im", "image", 209 | "imagine", "img", "immediately", "immune", "imo", "impatient", 210 | "implementation", "import", "improve", "improved", "in", "inbox", "inch", 211 | "incident", "incomplete", "inconvenience", "indeed", "india", "indicates", 212 | "individual", "indonesia", "inet", "inet6", "inetd", "infection", "infer", 213 | "info", "inform", "infos", "ing", "in-game", "init", "initial", "initialize", 214 | "initram", "injection", "inline", "insecure", "insert", "inserts", "inside", 215 | "inspiron", "install", "installer", "installing", "instant", "instantly", 216 | "insurance", "integrated", "intel", "intent", "interactive", "interested", 217 | "interface", "interim", "internal", "internet", "internets", "interval", 218 | "intrepid", "intro", "introduce", "invalid", "invert", "ioctl", "ios", "iot", 219 | "ip", "ipad", "iphone", "ipod", "ips", "iptraf", "ir", "irc", "irs", "irssi", 220 | "is", "isdn", "isee", "island", "isnt", "iso", "isp", "issue", "ist", 221 | "istanbul", "it", "italiano", "itanium", "item", "ith", "itouch", "its", "itt", 222 | "itunes", "iu", "iv", "ive", "iw", "iwl3945", "jackalope", "jaunty", "java", 223 | "javascript", "jdk", "jeez", "jetzt", "jfs", "job", "jobs", "join", "joins", 224 | "joke", "joomla", "jou", "journal", "joystick", "jre", "jump", "jumps", "junk", 225 | "jus", "just", "justs", "k", "k6", "k7", "kaffeine", "kanji", "karmic", 226 | "kazam", "kb", "kde", "kde4", "kdm", "keep", "keine", "kernal", "kernel", 227 | "kewl", "key", "keyboard", "keygen", "keyring", "keys", "keystroke", "keyword", 228 | "khz", "kick", "kicks", "kil", "kile", "kill", "killed", "killing", "kinda", 229 | "kindly", "kino", "kiso", "kit", "kk", "kms", "knew", "knock", "know", "knows", 230 | "knw", "koala", "kodi", "konquerer", "kontact", "kopete", "krusader", "ksirc", 231 | "kthx", "kto", "kubuntu", "kvm", "l2", "la", "label", "lack", "lacking", 232 | "ladies", "lagged", "lame", "lamp", "lan", "landlord", "landscape", "laptop", 233 | "large", "laserjet", "last", "late", "latency", "later", "laugh", "laughing", 234 | "launch", "launched", "launchpad", "law", "lay", "layer", "ldd", "le", "lead", 235 | "leading", "leak", "lean", "lear", "learn", "learning", "leave", "leaves", 236 | "left", "leg", "legacy", "legal", "lesbian", "less", "let", "letter", "level", 237 | "lfe", "lib", "libc", "libet", "library", "libre", "license", "lid", "lie", 238 | "life", "light", "lightning", "lights", "like", "liked", "likes", "limb", 239 | "limewire", "limited", "line", "linear", "lines", "link", "linked", "links", 240 | "links2", "linksys", "linux-", "linux", "linux-firmware", "linuxmce", "list", 241 | "listen", "listening", "little", "live", "liveboot", "live-cd", "livecd", 242 | "liveusb", "living", "lo", "load", "loaded", "loader", "loading", "lobby", 243 | "local", "locales", "localhost", "locate", "locked", "lockup", "log", 244 | "logging", "logical", "logically", "logins", "logo", "lol", "long", "longer", 245 | "longterm", "look", "looking", "looks", "lookup", "loop", "loop0", "loopback", 246 | "looping", "loose", "los", "lose", "losing", "loss", "lossless", "lossy", 247 | "lost", "lot", "love", "lovely", "loving", "low", "lowest", "lpr", "ls", 248 | "lsblk", "lsof", "lspci", "lts", "ltsp", "lubuntu", "lucid", "luck", "lug", 249 | "luks", "lvm", "lxde", "lyx", "m", "m68k", "maas", "mabe", "mac", "macbookpro", 250 | "machine", "machines", "macintosh", "macos", "macosx", "made", "mageia", 251 | "mail", "mailserver", "main", "major", "majority", "make", "makefile", "makin", 252 | "male", "malicious", "malone", "mam", "man", "manager", "mandatory", 253 | "mandriva", "manger", "mangled", "manipulate", "many", "mapping", "marked", 254 | "marketing", "massive", "mastering", "matchbox", "mate", "matter", "mature", 255 | "maximum", "may", "maybe", "mb", "mbox", "mbr", "mce", "md5", "md5sum", 256 | "mdadm", "me", "mean", "means", "mechanical", "media", "medicine", "medium", 257 | "member", "men", "mention", "mentor", "menu", "mepis", "merci", "merge", 258 | "merry", "mess", "metacity", "method", "me-tv", "mf1", "mga", "mhm", "mi", 259 | "mic", "mice", "microsd", "microsoft", "midi", "might", "mikrotik", "mileage", 260 | "min", "mind", "mine", "minecraft", "mines", "minimal", "minor", "mins", 261 | "minute", "mirc", "mirror", "mirrored", "mirrors", "miserable", "misplaced", 262 | "miss", "missed", "missing", "mistake", "mix", "mixer", "mixing", "mkay", 263 | "mkdir", "mkv", "mldonkey", "mlr", "mmap", "mmh", "mmkay", "mobility", 264 | "moblin", "mobo", "modding", "mode", "model", "modem", "modern", "modify", 265 | "modinfo", "modprobe", "modular", "mol", "moment", "monde", "monitor", 266 | "monitoring", "month", "moral", "more", "morning", "most", "mostly", "mother", 267 | "motu", "mount", "mousepad", "mout", "move", "mozilla", "mp2", "mp3", "mpeg", 268 | "mprime", "mpv", "mroe", "msdos", "msg", "msn", "mtp", "muck", "muh", "multi", 269 | "multimedia", "munin", "music", "must", "muted", "mutt", "mv", "my", "mybe", 270 | "mysql", "myuser", "\\n", "n", "na", "nah", "nahh", "name", "namely", "nar", 271 | "narwhal", "nasty", "nat", "native", "natty", "navigator", "nay", "nbr", "nc", 272 | "ncq", "ndiswrapper", "near", "nearby", "neat", "need", "neighbor", "neither", 273 | "nerdy", "nervous", "nessus", "net", "netbios", "netbook", "netcat", "nethack", 274 | "netmask", "netstat", "network", "networked", "networking", "networks", 275 | "never", "new", "newbs", "newer", "newline", "news", "nexenta", "next", 276 | "nexuiz", "nfs", "nfsv4", "nginx", "ni", "nice", "nicely", "nick", "nicks", 277 | "nickspam", "nicotine", "nid", "nie", "nipple", "nmap", "no", "noapic", 278 | "nobody", "nome", "non", "none", "nonsense", "noobs", "no-one", "nop", "nope", 279 | "nor", "norm", "normal", "normally", "not", "note", "notes", "nothing", 280 | "nouveau", "novell", "now", "np", "ns", "ntfs", "ntfs-3g", "ntp", "nuisance", 281 | "number", "numbers", "nun", "nup", "nvidia", "nvm", "nx", "o", "obex", 282 | "observing", "obv", "oct", "od", "odd", "odds", "oes", "of", "ofc", "ofcourse", 283 | "off", "offense", "offensive", "offer", "offsets", "offtopic", "often", "ogl", 284 | "ogle", "oh", "oi", "oic", "ok", "okay", "oki", "okies", "okk", "okkk", "oky", 285 | "okz", "ola", "old", "omg", "on", "onboard", "once", "one", "ones", "online", 286 | "only", "onto", "oof", "ook", "ooo", "oops", "op", "open", "openarena", 287 | "openbox", "opend", "opened", "openerp", "opengl", "openoffice", "open-source", 288 | "opensource", "opensuse", "openttd", "openvpn", "opinion", "ops", "option", 289 | "or", "orange", "oranges", "order", "original", "originals", "oss", "osx", 290 | "ot", "other", "others", "ouch", "oui", "out", "output", "outside", "ovaries", 291 | "over", "overkill", "overloaded", "overlook", "override", "owa", "own", 292 | "owned", "p2p", "p3", "p4", "pack", "package", "packets", "padding", "pae", 293 | "pain", "painful", "paint", "pakage", "palm", "paman", "panasonic", "panic", 294 | "para", "paragraph", "parallel", "parent", "parents", "park", "part", 295 | "partition", "partitioner", "partner", "party", "pas", "pass", "passed", 296 | "passwd", "password", "past", "paste", "pata", "patch", "patches", "patient", 297 | "pattern", "patterns", "pavilion", "pay", "pc", "pcbsd", "pci", "pcm", "pcs", 298 | "pctv", "pdf", "pearl", "peek", "peer", "pending", "pentium", "people", 299 | "peoples", "per", "perfect", "performances", "perl", "permanent", 300 | "persistence", "personal", "pesky", "peu", "pff", "pgp", "phd", "phew", 301 | "philosophy", "phone", "phones", "photo", "photos", "php", "phpmyadmin", 302 | "physical", "phyton", "pianobar", "pic", "picard", "pick", "pico", "pics", 303 | "picture", "pictures", "pid", "pidgin", "pidof", "piece", "ping", "pingus", 304 | "pink", "pint", "pipe", "pipes", "pity", "places", "plagued", "plain", 305 | "plaintext", "plan", "play", "playback", "player", "playing", "please", 306 | "plenty", "plex", "pls", "plug", "plugin", "plugins", "plugs", "plymouth", 307 | "plz", "pm", "pocket", "pocketpc", "poff", "point", "pointer", "pointless", 308 | "poke", "poking", "police", "polite", "poll", "pooched", "pool", "poor", "pop", 309 | "pop3", "popup", "por", "porno", "port", "portable", "portage", "ports", 310 | "portugues", "positive", "possible", "post", "postgres", "postgresql", "pour", 311 | "pov", "power", "powered", "powerpc", "ppc", "ppl", "ppp0", "pppoe", "pptp", 312 | "pra", "practical", "practice", "pre", "preferred", "prefixed", "preload", 313 | "premiere", "preseed", "press", "pretty", "prety", "price", "primary", "print", 314 | "printer", "prints", "prior", "priv", "privacy", "private", "privileged", 315 | "prize", "prob", "probably", "probe", "problem", "problems", "proc", "proceed", 316 | "process", "processor", "procs", "programer", "programming", "progress", 317 | "progs", "prohibit", "project", "projects", "prolog", "prompt", "proper", 318 | "props", "protect", "protection", "protocols", "prove", "proven", "provider", 319 | "proxy", "prt", "pry", "ps", "ps2", "ps3", "psd", "psk", "psu", "ptp", 320 | "public", "puel", "pulse", "pulseaudio", "pun", "purge", "purpose", "puta", 321 | "putty", "puzzled", "pv", "pvt", "pwd", "pxe", "pxeboot", "q3", "qdisc", 322 | "qemu", "qn", "qt", "quad", "quadro", "quake2", "quakenet", "qualcuno", 323 | "quality", "quanta", "quantal", "que", "quel", "query", "question", 324 | "questionable", "questioning", "questions", "questo", "quick", "quickly", 325 | "quicksilver", "quit", "quotes", "r1", "r40", "r9", "raep", "ragazzi", "raid", 326 | "raid0", "rails", "ramdisk", "ran", "random", "randomly", "rape", "rar", 327 | "rare", "ratio", "rc", "re", "reach", "read", "reader", "reading", "readme", 328 | "ready", "real", "realistic", "reality", "realize", "really", "realm", 329 | "realplayer", "realtek", "realtime", "rear", "reason", "reasonable", "reasons", 330 | "reboot", "reburn", "recall", "received", "recent", "reconnect", "record", 331 | "recover", "recovery", "recreate", "recycle", "redhat", "redo", "reduce", 332 | "refresh", "refund", "regard", "regenerate", "regenerating", "regexp", 333 | "register", "regression", "regular", "reinstall", "reiserfs", "relate", 334 | "relation", "relax", "relay", "release", "relevant", "reload", "reloaded", 335 | "reloading", "rely", "remaster", "remastersys", "remember", "remembers", 336 | "remix", "remote", "removed", "rename", "repair", "replaced", "replay", "repo", 337 | "repro", "reproducing", "request", "required", "rerun", "rescue", "research", 338 | "reservation", "reserved", "reset", "resolution", "resolve", "respectful", 339 | "responce", "respond", "rest", "restart", "restricted", "results", "retards", 340 | "return", "returning", "reverse", "revision", "rf", "rfc", "ribbon", "rid", 341 | "ridiculous", "right", "ringtail", "ripoff", "ripping", "risk", "rite", "rl", 342 | "rm", "rmdir", "road", "roaming", "rocks", "rolling", "roms", "room", "root", 343 | "roulette", "routed", "router", "routing", "row", "rows", "rpi", "rpm", 344 | "rsync", "rtf", "rtt", "ru", "rude", "ruin", "rule", "run", "runaway", 345 | "runescape", "runlevel", "runs", "rushed", "rv8", "rvm", "rwx", "s3", "safe", 346 | "safety", "said", "salut", "samba", "same", "samples", "sand", "sandbox", 347 | "sandisk", "sans", "sansa", "sarcasm", "sasl", "sat", "sata", "saturday", 348 | "saucy", "save", "saveas", "savvy", "saw", "sawfish", "say", "scaled", "scan", 349 | "scandisk", "scheduler", "science", "scite", "scp", "scrambled", "scratch", 350 | "screen", "screencast", "screening", "screensaver", "screenshot", "screw", 351 | "screwed", "screwing", "script", "scripts", "scroll", "scrollbar", "scrolls", 352 | "scsi", "sda3", "sda9", "sdc", "sdcard", "se", "seagate", "seahorse", 353 | "seamonkey", "search", "searched", "searching", "seattle", "sec", "second", 354 | "secondary", "secondlife", "security", "sed", "see", "seed", "seeking", 355 | "segfaults", "select", "selection", "selective", "selinux", "selling", "sem", 356 | "semicolon", "send", "sense", "sensible", "sent", "sentence", "senza", 357 | "separate", "serial", "series", "serious", "seriously", "serpentine", "serve", 358 | "server", "servers", "servlet", "session", "set", "seti", "setting", "setup", 359 | "sever", "sex", "sfs", "sftp", "sh", "sha1", "shame", "sharing", "she", 360 | "shell", "shells", "shellshock", "shift", "shipit", "shite", "sho", "shoes", 361 | "shoot", "shoots", "shop", "short", "shortcut", "shortcuts", "shorter", 362 | "shoutcast", "shouting", "shown", "shred", "shrink", "shrugs", "shuffle", 363 | "shure", "shut", "shutdown", "shuttleworth", "si", "sick", "side", "sidebar", 364 | "siema", "siemens", "sigh", "sign", "signal", "silence", "silently", "silly", 365 | "sim", "similar", "simple", "simplicity", "simply", "simulate", "sing", 366 | "single", "sips", "sir", "sis", "sistem", "sit0", "site", "situation", 367 | "skills", "skin", "skype", "slang", "slaps", "slave", "sleep", "sleeping", 368 | "sleeve", "slightly", "slow", "slower", "slowest", "slowing", "slowness", 369 | "sm56", "small", "smarter", "smb", "sme", "smooth", "smp", "smth", "smtp", 370 | "snaps", "snapshot", "snes", "snippets", "snmp", "so", "sobre", "socat", 371 | "social", "socks", "soem", "soft", "software", "solar", "solution", "solving", 372 | "som", "some", "some1", "somebody", "somehow", "someon", "someone", 373 | "someplace", "somethin", "something", "somewhat", "somewhere", "somone", 374 | "song", "songbird", "soo", "soon", "sooner", "soooo", "sorry", "sort", "sorta", 375 | "sory", "soulseek", "sound", "soundblaster", "soundtrack", "source", 376 | "sourcecode", "sourced", "sow", "sp2", "sp3", "space", "spam", "spanish", 377 | "spe", "speak", "speaker", "speakers", "specs", "speed", "speeding", 378 | "speedtouch", "spelling", "spin", "spinning", "spit", "splash", "split", 379 | "splitter", "spoke", "spoofing", "spot", "spread", "sprint", "spurious", 380 | "spyware", "sql", "squares", "squeeze", "srt", "ssb", "ssd", "ssh", "sshd", 381 | "ssh-server", "ssl", "sta", "stack", "stacks", "stand", "standalone", 382 | "standard", "standby", "starcraft", "start", "startkeylogger", "startx", 383 | "stat", "state", "stated", "states", "static", "status", "stay", "stderr", 384 | "stdout", "steady", "steam", "steep", "step", "steps", "stfu", "sthg", 385 | "stickers", "sticks", "still", "stopped", "storage", "store", "strace", 386 | "strain", "stream", "streamer", "street", "strength", "stress", "string", 387 | "stripped", "stroke", "strong", "stronger", "stty", "stubborn", "stuck", 388 | "study", "studying", "stuff", "stuffs", "stupid", "stupidity", "su", "subject", 389 | "subnet", "subset", "substance", "subversion", "succeed", "sucker", "sucks", 390 | "sucky", "suddenly", "sudo", "sudoers", "suffer", "suffering", "suffice", 391 | "sugar", "sum", "sunday", "sup", "super-user", "supply", "suppor", "support", 392 | "supybot", "sure", "surely", "surfing", "surprise", "survives", "suse", 393 | "suspend", "sux", "svn", "swap", "swapon", "swedish", "sweeet", "sweet", "swf", 394 | "swiftweasel", "switch", "switched", "switcher", "switches", "sym", "symbolic", 395 | "symlinks", "synaptic", "synatic", "sync", "synoptic", "sys", "syscall", 396 | "sysctl", "syslogd", "system", "system76", "systemd", "systems", "systray", 397 | "sysv", "t", "t400", "t42", "t61", "ta", "tab", "tab-complete", "tablet", 398 | "taboo", "tabs", "tails", "take", "taken", "taking", "talk", "talkin", "tanks", 399 | "tap", "tape", "target", "tasks", "tcp", "tea", "teach", "teachers", "team", 400 | "teams", "teamspeak", "technical", "techs", "tedious", "tee", "teh", "tel", 401 | "television", "tell", "telling", "telnet", "temperature", "temporary", "tend", 402 | "terminal", "terminate", "terminology", "terror", "terse", "tes", "tested", 403 | "testing", "text", "tf2", "th", "tha", "thank", "thanks", "thankyou", "that", 404 | "thats", "the", "theater", "them", "theme", "then", "theora", "there", 405 | "therefore", "these", "they", "thier", "thik", "thing", "things", "think", 406 | "thinking", "third", "this", "thng", "tho", "thos", "thought", "thoughts", 407 | "thousands", "threads", "three", "threw", "throttled", "ths", "tht", 408 | "thumbdrive", "thumbs", "thunar", "thunderbird", "thunk", "thus", "thx", "ti", 409 | "tia", "ticking", "tie", "tiff", "tightvnc", "till", "time", "timeout", 410 | "timers", "timestamp", "tip", "tips", "tired", "tis", "tit", "tivo", "tks", 411 | "tlp", "tls", "tnx", "to", "toasted", "today", "together", "toilet", 412 | "tomorrow", "tonight", "too", "took", "tool", "tools", "top", "topic", "tor", 413 | "torrent", "toss", "total", "totem", "touch", "touched", "touchpad", "tough", 414 | "tous", "tp", "tracert", "track", "tracker", "trackpoint", "tracks", "trafic", 415 | "training", "transgaming", "transient", "transition", "translated", 416 | "transparent", "trap", "trash", "travelmate", "tray", "trayer", "treat", 417 | "tremulous", "trial", "trick", "tricky", "tried", "trigger", "triple", 418 | "trivial", "trolling", "trolls", "trouble", "troubleshooter", "tru", "true", 419 | "truly", "truncate", "trunk", "trusted", "trusty", "try", "trying", "tsc", 420 | "ttf", "ttfn", "tthe", "tty", "tty1", "tue", "tune", "tuner", "tunes", 421 | "tunnel", "turds", "tut", "tuto", "tutorial", "tutorials", "tutti", "tuxracer", 422 | "tv", "tweaks", "twenty", "twin", "twitter", "twm", "two", "txt", "tym", 423 | "type", "u", "uac", "uae", "ubnutu", "ubunto", "ubuntu-cn", "ubuntu-dev", 424 | "ubuntu-es", "ubuntu-fr", "ubuntuguide", "ubuntu-server", "ubunutu", "ubutto", 425 | "ues", "ufw", "ug", "ugh", "ughh", "ugly", "uh", "uhh", "uh-oh", "uhu", "uid", 426 | "uk", "ulimit", "um", "uma", "umm", "ummm", "una", "unable", "unallocated", 427 | "uname", "unbanned", "unbelievable", "unbound", "unbuntu", "unclean", "und", 428 | "undefined", "under", "undo", "undone", "une", "unetbootin", "unfriendly", 429 | "unhappy", "uni", "unicorn", "unified", "unit", "univ", "universe", "unix", 430 | "unix-like", "unless", "unlike", "unlimited", "unlock", "unmanaged", "unplug", 431 | "unplugged", "unregged", "unto", "untouched", "untrusted", "unused", "up", 432 | "update", "updated", "updater", "updates", "upgrade", "upgrading", "uploaded", 433 | "upon", "upside", "upstairs", "upstart", "uptime", "ur", "urban", "urgh", 434 | "url", "urs", "us", "usa", "usb", "use", "user", "userb", "userid", "userland", 435 | "users", "using", "usre", "ut", "ut2004", "utf-8", "util", "utils", "utopic", 436 | "utorrent", "uxa", "v4l", "v8", "v9", "vagina", "vagrant", "vai", "vain", 437 | "value", "values", "valve", "various", "vary", "vault", "vbox", "venezuela", 438 | "vent", "ventrilo", "verbosity", "versatile", "version", "vertical", "very", 439 | "vga", "vi", "via", "victory", "vid", "viet", "view", "vim", "virgin", 440 | "virtual", "virtualbox", "virtualized", "virtualmachine", "visit", "vista", 441 | "visual", "visually", "vlc", "vmlinuz", "vms", "vmstat", "vmware", "vnc", 442 | "voip", "volume", "volunteer", "vorbis", "vpc", "vpn", "vps", "vram", "vs", 443 | "vsftpd", "vt", "vulnerable", "w7", "w8", "wa", "wack", "wah", "waht", "wait", 444 | "waiting", "walking", "wall", "wan", "wana", "wanna", "wanted", "warcraft", 445 | "warning", "wary", "was", "washed", "wast", "waste", "watch", "watchdog", 446 | "wav", "way", "wayland", "ways", "wbar", "we", "wear", "weather", "web", 447 | "webadmin", "webhosting", "webmin", "webserver", "website", "wed", "weechat", 448 | "weird", "welcom", "welcome", "well", "welll", "wep", "wer", "were", "werk", 449 | "wget", "whacky", "what", "whatever", "whatis", "whee", "when", "where", 450 | "wherever", "which", "while", "whim", "whit", "white", "whitespace", "who", 451 | "whoa", "whole", "whomever", "whoops", "whore", "whose", "wht", "why", "wid", 452 | "widescreen", "width", "wie", "wife", "wi-fi", "wifi", "wiki", "wikipedia", 453 | "wildcards", "will", "willl", "win", "win2k", "win7", "winblows", "winbox", 454 | "window", "windows", "windows7", "windoze", "wine", "winehq", "wink", "wins", 455 | "winxp", "wipe", "wire", "wired", "wireless", "wiser", "wish", "wit", "witch", 456 | "with", "without", "wl", "wlan", "wlan0", "wm", "wmware", "wo", "wobbly", 457 | "wol", "woman", "wonder", "wondered", "wonderful", "wondering", "wont", "woof", 458 | "woohoo", "woohooo", "woooo", "woops", "word", "work", "workbench", "worker", 459 | "workgroup", "working", "works", "world", "worried", "worry", "wors", "worth", 460 | "worx", "wow", "wrapper", "wrecked", "write", "writer", "writing", "written", 461 | "wrong", "wtc", "wtf", "wubi", "wusb54g", "wxp", "x", "x11", "x64", "x86", 462 | "x86_64", "xampp", "xandros", "xargs", "x-chat", "xchat", "xconfig", "xd", 463 | "xdmcp", "xe1", "xenial", "xeyes", "xf86", "xfburn", "xfce", "xfire", "xfs", 464 | "xfx", "xgl", "xine", "xls", "xmacro", "xml", "xmms", "xmonad", "xmpp", "xorg", 465 | "xp", "xps", "xsane", "xscreen", "xt", "xterm", "xubuntu", "xv", "xvf", "ya", 466 | "yakuake", "yawn", "yay", "yea", "yeah", "yeap", "yeh", "yell", "yelp", "yep", 467 | "yer", "yes", "yess", "yessir", "yesterday", "yet", "yields", "yikes", "you", 468 | "your", "yours", "yourself", "yourusername", "youtube", "youve", "yoy", "yp", 469 | "yrs", "yummy", "yup", "yus", "yw", "zeros", "zesty", "zips", "znc", "zomg", 470 | "zone", 471 | } 472 | -------------------------------------------------------------------------------- /subtask4/task-4-evaluation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # For the definition of the metric, see https://en.wikipedia.org/wiki/Variation_of_information 4 | 5 | from __future__ import print_function 6 | 7 | import argparse 8 | import math 9 | import sys 10 | 11 | def find(x, parents): 12 | while parents[x] != x: 13 | parent = parents[x] 14 | parents[x] = parents[parent] 15 | x = parent 16 | return x 17 | 18 | def union(x, y, parents, sizes): 19 | # Get the representative for their sets 20 | x_root = find(x, parents) 21 | y_root = find(y, parents) 22 | 23 | # If equal, no change needed 24 | if x_root == y_root: 25 | return 26 | 27 | # Otherwise, merge them 28 | if sizes[x_root] > sizes[y_root]: 29 | parents[y_root] = x_root 30 | sizes[x_root] += sizes[y_root] 31 | else: 32 | parents[x_root] = y_root 33 | sizes[y_root] += sizes[x_root] 34 | 35 | def union_find(nodes, edges): 36 | # Make sets 37 | parents = {n:n for n in nodes} 38 | sizes = {n:1 for n in nodes} 39 | 40 | for edge in edges: 41 | union(edge[0], edge[1], parents, sizes) 42 | 43 | clusters = {} 44 | for n in parents: 45 | clusters.setdefault(find(n, parents), set()).add(n) 46 | cluster_list = list(clusters.values()) 47 | return cluster_list 48 | 49 | def read_data(filenames): 50 | clusters = {} 51 | graphs = {} 52 | all_points = set() 53 | for filename in filenames: 54 | nodes = {} 55 | edges = {} 56 | for line in open(filename): 57 | if line.startswith("#") or line.startswith("%") or line.startswith("/"): 58 | continue 59 | cfile = filename 60 | if ':' in line: 61 | cfile, line = line.split(':') 62 | cfile = cfile.split('/')[-1] 63 | parts = [int(v) for v in line.strip().split() if v != '-'] 64 | assert len(parts) == 2 65 | source = max(parts) 66 | nodes.setdefault(cfile, set()).add(source) 67 | parts.remove(source) 68 | for num in parts: 69 | edges.setdefault(cfile, []).append((source, num)) 70 | nodes.setdefault(cfile, set()).add(num) 71 | graphs.setdefault(cfile, {}).setdefault(source, set()).add(num) 72 | 73 | for cfile in nodes: 74 | for cluster in union_find(nodes[cfile], edges[cfile]): 75 | vals = {v for v in cluster if v >= 1000} 76 | clusters.setdefault(cfile, []).append(vals) 77 | for val in vals: 78 | all_points.add("{}:{}".format(cfile, val)) 79 | return clusters, all_points, graphs 80 | 81 | def clusters_to_contingency(gold, auto): 82 | # A table, in the form of: 83 | # https://en.wikipedia.org/wiki/Rand_index#The_contingency_table 84 | table = {} 85 | for filename in auto: 86 | for i, acluster in enumerate(auto[filename]): 87 | aname = "auto.{}.{}".format(filename, i) 88 | current = {} 89 | table[aname] = current 90 | for j, gcluster in enumerate(gold[filename]): 91 | gname = "gold.{}.{}".format(filename, j) 92 | count = len(acluster.intersection(gcluster)) 93 | if count > 0: 94 | current[gname] = count 95 | counts_a = {} 96 | for filename in auto: 97 | for i, acluster in enumerate(auto[filename]): 98 | aname = "auto.{}.{}".format(filename, i) 99 | counts_a[aname] = len(acluster) 100 | counts_g = {} 101 | for filename in gold: 102 | for i, gcluster in enumerate(gold[filename]): 103 | gname = "gold.{}.{}".format(filename, i) 104 | counts_g[gname] = len(gcluster) 105 | return table, counts_a, counts_g 106 | 107 | def variation_of_information(contingency, row_sums, col_sums): 108 | total = 0.0 109 | for row in row_sums: 110 | total += row_sums[row] 111 | 112 | H_UV = 0.0 113 | I_UV = 0.0 114 | for row in contingency: 115 | for col in contingency[row]: 116 | num = contingency[row][col] 117 | H_UV -= (num / total) * math.log(num / total, 2) 118 | I_UV += (num / total) * math.log(num * total / (row_sums[row] * col_sums[col]), 2) 119 | 120 | H_U = 0.0 121 | for row in row_sums: 122 | num = row_sums[row] 123 | H_U -= (num / total) * math.log(num / total, 2) 124 | H_V = 0.0 125 | for col in col_sums: 126 | num = col_sums[col] 127 | H_V -= (num / total) * math.log(num / total, 2) 128 | 129 | max_score = math.log(total, 2) 130 | VI = H_UV - I_UV 131 | 132 | scaled_VI = VI / max_score 133 | print("{:5.2f} 1 - Scaled VI".format(100 - 100 * scaled_VI)) 134 | 135 | def adjusted_rand_index(contingency, row_sums, col_sums): 136 | # See https://en.wikipedia.org/wiki/Rand_index 137 | rand_index = 0.0 138 | total = 0.0 139 | for row in contingency: 140 | for col in contingency[row]: 141 | n = contingency[row][col] 142 | rand_index += n * (n-1) / 2.0 143 | total += n 144 | 145 | sum_row_choose2 = 0.0 146 | for row in row_sums: 147 | n = row_sums[row] 148 | sum_row_choose2 += n * (n-1) / 2.0 149 | sum_col_choose2 = 0.0 150 | for col in col_sums: 151 | n = col_sums[col] 152 | sum_col_choose2 += n * (n-1) / 2.0 153 | random_index = sum_row_choose2 * sum_col_choose2 * 2.0 / (total * (total - 1)) 154 | 155 | max_index = 0.5 * (sum_row_choose2 + sum_col_choose2) 156 | 157 | adjusted_rand_index = (rand_index - random_index) / (max_index - random_index) 158 | 159 | print('{:5.2f} Adjusted rand index'.format(100 * adjusted_rand_index)) 160 | 161 | def exact_match(gold, auto): 162 | # P/R/F over complete clusters 163 | total_gold = 0 164 | total_matched = 0 165 | for filename in gold: 166 | for cluster in gold[filename]: 167 | if len(cluster) == 1: 168 | continue 169 | total_gold += 1 170 | matched = False 171 | for ocluster in auto[filename]: 172 | if len(ocluster.symmetric_difference(cluster)) == 0: 173 | matched = True 174 | break 175 | if matched: 176 | total_matched += 1 177 | total_auto = 0 178 | for filename in auto: 179 | for cluster in auto[filename]: 180 | if len(cluster) == 1: 181 | continue 182 | total_auto += 1 183 | p, r, f = 0.0, 0.0, 0.0 184 | if total_auto > 0: 185 | p = 100 * total_matched / total_auto 186 | if total_gold > 0: 187 | r = 100 * total_matched / total_gold 188 | if total_matched > 0: 189 | f = 2 * p * r / (p + r) 190 | print("{:5.2f} Matched clusters precision".format(p)) 191 | print("{:5.2f} Matched clusters recall".format(r)) 192 | print("{:5.2f} Matched clusters f-score".format(f)) 193 | 194 | if __name__ == '__main__': 195 | parser = argparse.ArgumentParser(description='Calculate cluster / thread / conversation metrics.') 196 | parser.add_argument('--gold', help='File(s) containing the gold clusters, one per line. If a line contains a ":" the start is considered a filename', required=True, nargs="+") 197 | parser.add_argument('--auto', help='File(s) containing the system clusters, one per line. If a line contains a ":" the start is considered a filename', required=True, nargs="+") 198 | parser.add_argument('--metric', nargs="+", choices=['vi', 'rand', 'ex', 'all'], default=['all']) 199 | args = parser.parse_args() 200 | 201 | gold, gpoints, gedges = read_data(args.gold) 202 | auto, apoints, aedges = read_data(args.auto) 203 | issue = False 204 | for filename in auto: 205 | if filename not in gold: 206 | print("Gold is missing file {}".format(filename), file=sys.stderr) 207 | issue = True 208 | for filename in gold: 209 | if filename not in auto: 210 | print("Auto is missing file {}".format(filename), file=sys.stderr) 211 | issue = True 212 | if issue: 213 | sys.exit(0) 214 | if len(apoints.symmetric_difference(gpoints)) != 0: 215 | print(apoints.difference(gpoints)) 216 | print(gpoints.difference(apoints)) 217 | raise Exception("Set of lines does not match: {}".format(apoints.symmetric_difference(gpoints))) 218 | 219 | contingency, row_sums, col_sums = None, None, None 220 | if 'vi' in args.metric or 'rand' in args.metric or 'all' in args.metric: 221 | contingency, row_sums, col_sums = clusters_to_contingency(gold, auto) 222 | 223 | if 'vi' in args.metric or 'all' in args.metric: 224 | variation_of_information(contingency, row_sums, col_sums) 225 | if 'rand' in args.metric or 'all' in args.metric: 226 | adjusted_rand_index(contingency, row_sums, col_sums) 227 | if 'ex' in args.metric or 'all' in args.metric: 228 | exact_match(gold, auto) 229 | 230 | -------------------------------------------------------------------------------- /subtask4/tokenise.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from __future__ import print_function 4 | 5 | import argparse 6 | import logging 7 | import re 8 | import sys 9 | import string 10 | 11 | from reserved_words import reserved 12 | 13 | def make_unk(word): 14 | has_digit = any(c in string.digits for c in word) 15 | has_letter = any(c in string.ascii_letters for c in word) 16 | marks = set() 17 | for c in word: 18 | if c in string.punctuation: 19 | marks.add(c) 20 | marks = list(marks) 21 | marks.sort() 22 | marks = ''.join(marks) 23 | 24 | ans = " 0: 41 | parts.append(label + v) 42 | 43 | # Push all but the start back on todo 44 | if len(parts) > 1: 45 | for part in parts[:0:-1]: 46 | if len(part) > 0: 47 | todo.insert(0, part) 48 | 49 | return parts[0] 50 | 51 | # Names two letters or less that occur more than 500 times in the data 52 | common_short_names = {"ng", "_2", "x_", "rq", "\\9", "ww", "nn", "bc", "te", 53 | "io", "v7", "dm", "m0", "d1", "mr", "x3", "nm", "nu", "jc", "wy", "pa", "mn", 54 | "a_", "xz", "qr", "s1", "jo", "sw", "em", "jn", "cj", "j_"} 55 | 56 | def tokenise(line, args, vocab, users, line_no): 57 | tokens = [] 58 | 59 | parts = line.strip().split() 60 | # Handle timestamp and username 61 | if re.match(".*\[[0-9][0-9][:][0-9][0-9]\]$", parts[0]) is None: 62 | timestamp = parts.pop(0) 63 | else: 64 | timestamp = parts.pop(0) 65 | user = parts.pop(0) 66 | while user[-1] != '>' and len(parts) > 0: 67 | user +=" "+ parts.pop(0) 68 | 69 | # Handle message 70 | while len(parts) > 0: 71 | current = parts.pop(0) 72 | current = current.lower() 73 | 74 | # Handle username mentions 75 | user = None 76 | if current in users and len(current) > 2: 77 | user = current 78 | else: 79 | core = [char for char in current] 80 | while len(core) > 0 and core[-1] in string.punctuation: 81 | core.pop() 82 | nword = ''.join(core) 83 | if nword in users and (len(core) > 2 or nword in common_short_names): 84 | user = nword 85 | break 86 | if user is None: 87 | while len(core) > 0 and core[0] in string.punctuation: 88 | core.pop(0) 89 | nword = ''.join(core) 90 | if nword in users and (len(core) > 2 or nword in common_short_names): 91 | user = nword 92 | break 93 | if user is not None: 94 | cmin, cmax = users[user] 95 | if cmin - 1000 <= line_no <= cmax + 1000: 96 | subparts = current.split(user) 97 | if len(subparts[0]) > 0: 98 | tokens.append(subparts[0]) 99 | tokens.append("") 100 | if len(subparts[-1]) > 0: 101 | tokens.append(subparts[-1]) 102 | current = '' 103 | continue 104 | 105 | # - email (...@...) or prompt (...@...:...) make word shape (...@...) and split on ':' 106 | if "@" in current and (not current.startswith("@")) and (not current.endswith('@')): 107 | if len(current.split("@")) == 2: 108 | tokens.append("ADDRESS_" + current.split("@")[0]) 109 | tokens.append("ADDRESS_@" + current.split("@")[1]) 110 | current = '' 111 | continue 112 | 113 | # - Permissions (only rwxd-), split into groups of three characters 114 | if len(current) == 10 and re.fullmatch("[-rwxd]+", current) is not None: 115 | tokens.append('PERMISSIONS_'+ current[:1]) 116 | tokens.append('PERMISSIONS_'+ current[1:4]) 117 | tokens.append('PERMISSIONS_'+ current[4:7]) 118 | tokens.append('PERMISSIONS_'+ current[7:]) 119 | current = '' 120 | continue 121 | 122 | # - URLs (start with http, sftp, telnet) split on '/' and add it (http://) (...) (/.../) (/.../) ... 123 | if re.match("^((http)|(sftp)|(telnet)).*\/", current) is not None: 124 | chunks = [c for c in current.split("/") if len(c) != 0] 125 | tokens.append("URL/"+ chunks[0] +"/") 126 | if len(chunks) > 1: 127 | tokens.append("URL/"+ chunks[1] +"/") 128 | if len(chunks) > 2: 129 | tokens.append("URL/"+ '/'.join(chunks[2:]) +"/") 130 | current = '' 131 | continue 132 | if current.startswith("www."): 133 | current = "URL/"+ current 134 | 135 | # - ...[:;*,.?!)] and group repeats (... or ... or !?!!??!?!) 136 | current = apply_re("""([":;?!.,)}\]]+$)""", tokens, parts, current) 137 | 138 | # - Directories (start with / or ~) split into pieces (/.../) (/.../) 139 | if re.match("^[~/]", current) is not None: 140 | chunks = current.split("/") 141 | for chunk in chunks: 142 | if len(chunk) > 0: 143 | tokens.append("DIR/"+ chunk +"/") 144 | current = '' 145 | continue 146 | 147 | # - [!({[]... 148 | current = apply_re("""(^["!({[]+)""", tokens, parts, current) 149 | 150 | # - ...'s ...n't ...'ll ...'m ...'ve (and in all cases allow ' or ") 151 | current = apply_re("""(['"]s)$""", tokens, parts, current) 152 | current = apply_re("""(n['"]t)$""", tokens, parts, current) 153 | current = apply_re("""(['"]ll)$""", tokens, parts, current) 154 | current = apply_re("""(['"]m)$""", tokens, parts, current) 155 | current = apply_re("""(['"]ve)$""", tokens, parts, current) 156 | 157 | # - mid-word ellipses (e.g. know...But) 158 | current = apply_re("""([.][.]+)""", tokens, parts, current) 159 | 160 | # - Instructions like "System->Admin->Shared" split on "[-]?>" 161 | current = apply_re("""([-]?[>])""", tokens, parts, current) 162 | 163 | # - "s/.../..." to "substitution / ... / ... /" 164 | if re.match("s/.*/", current) is not None: 165 | for chunk in current.split("/"): 166 | if len(chunk) > 0: 167 | tokens.append("SUB/"+ chunk +"/") 168 | current = '' 169 | continue 170 | 171 | # - Numbers (do not convert all numbers to 0, as 32 != 64) 172 | # versions, etc, so not worth collapsing 173 | 174 | if len(current) > 0: 175 | tokens.append(current) 176 | 177 | # Add unks 178 | if len(vocab) > 0: 179 | for i, token in enumerate(tokens): 180 | if token.lower() not in users and token not in vocab: 181 | tokens[i] = make_unk(token) 182 | 183 | tokens.insert(0, "") 184 | tokens.append("") 185 | 186 | return tokens 187 | 188 | def update_user(users, user, line_no): 189 | if user in reserved: 190 | return 191 | all_digit = True 192 | for char in user: 193 | if char not in string.digits: 194 | all_digit = False 195 | if all_digit: 196 | return 197 | 198 | if user not in users: 199 | users[user] = (line_no, line_no) 200 | else: 201 | cmin, cmax = users[user] 202 | users[user] = (min(cmin, line_no), max(cmax, line_no)) 203 | 204 | def update_users(line, users, line_no): 205 | if len(line.split()) < 2: 206 | return 207 | user = line.split()[1] 208 | if user in ["Topic", "Signoff", "Signon", "Total", "#ubuntu", 209 | "Window", "Server:", "Screen:", "Geometry", "CO,", 210 | "Current", "Query", "Prompt:", "Second", "Split", 211 | "Logging", "Logfile", "Notification", "Hold", "Window", 212 | "Lastlog", "Notify", 'netjoined:']: 213 | # Ignore as these are channel commands 214 | pass 215 | else: 216 | if line.split()[0].endswith("==="): 217 | parts = line.split("is now known as") 218 | if len(parts) == 2 and line.split()[-1] == parts[-1].strip(): 219 | user = line.split()[-1] 220 | elif line.split()[0][-1] == ']': 221 | if user[0] == '<': 222 | user = user[1:] 223 | if user[-1] == '>': 224 | user = user[:-1] 225 | 226 | user = user.lower() 227 | update_user(users, user, line_no) 228 | # This is for cases like a user named |blah| who is 229 | # refered to as simply blah 230 | core = [char for char in user] 231 | while len(core) > 0 and core[0] in string.punctuation: 232 | core.pop(0) 233 | while len(core) > 0 and core[-1] in string.punctuation: 234 | core.pop() 235 | core = ''.join(core) 236 | update_user(users, core, line_no) 237 | 238 | if __name__ == '__main__': 239 | parser = argparse.ArgumentParser(description='Tokenise content from IRC logs.') 240 | parser.add_argument('raw_data', help='File(s) containing the ascii logs.', nargs="+") 241 | parser.add_argument('--vocab', help='Use a vocab file to limit what is generated.', required=True) 242 | parser.add_argument('--output-suffix', help='Save to files with the suffix added.', required=True) 243 | args = parser.parse_args() 244 | 245 | vocab = set() 246 | for line in open(args.vocab): 247 | vocab.add(line.strip().split()[-1]) 248 | for input_filename in args.raw_data: 249 | out = open(input_filename + args.output_suffix, 'w') 250 | 251 | users = {} 252 | line_no = 0 253 | for line in open(input_filename): 254 | line_no += 1 255 | update_users(line.strip(), users, line_no) 256 | 257 | line_no = 0 258 | for line in open(input_filename): 259 | line_no += 1 260 | line = line.strip() 261 | tokens = tokenise(line, args, vocab, users, line_no) 262 | print(' '.join(tokens), file=out) 263 | 264 | out.close() 265 | 266 | --------------------------------------------------------------------------------