├── LICENSE ├── README.md ├── cngram2vec.c ├── compute-accuracy.c ├── distance.c ├── distance_fast.c ├── distance_txt.c ├── kmeans_txt.c ├── makefile ├── weightedWord2vec.c ├── word-analogy.c ├── word2phrase.c ├── word2vec.c └── wordless2vec.c /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 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # wang2vec 2 | Extension of the original word2vec (https://code.google.com/p/word2vec/) using different architectures 3 | 4 | To build the code, simply run: 5 | 6 | make 7 | 8 | The command to build word embeddings is exactly the same as in the original version, except that we removed the argument -cbow and replaced it with the argument -type: 9 | 10 | ./word2vec -train input_file -output embedding_file -type 0 -size 50 -window 5 -negative 10 -nce 0 -hs 0 -sample 1e-4 -threads 1 -binary 1 -iter 5 -cap 0 11 | 12 | The -type argument is a integer that defines the architecture to use. These are the possible parameters: 13 | 0 - cbow 14 | 1 - skipngram 15 | 2 - cwindow (see below) 16 | 3 - structured skipngram(see below) 17 | 4 - collobert's senna context window model (still experimental) 18 | 19 | If you use functionalities we added to the original code for research, please support us by citing our paper (thanks!): 20 | 21 | @InProceedings{Ling:2015:naacl, 22 | author = {Ling, Wang and Dyer, Chris and Black, Alan and Trancoso, Isabel}, 23 | title="Two/Too Simple Adaptations of word2vec for Syntax Problems", 24 | booktitle="Proceedings of the 2015 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies", 25 | year="2015", 26 | publisher="Association for Computational Linguistics", 27 | location="Denver, Colorado", 28 | } 29 | 30 | The main changes we made to the code are: 31 | 32 | ****** Structured Skipngram and CWINDOW ****** 33 | 34 | The two NN architectures cwindow and structured skipngram (aimed for solving syntax problems). 35 | 36 | These are described in our paper: 37 | 38 | -Two/Too Simple Adaptations of word2vec for Syntax Problems 39 | 40 | ****** Noise Contrastive Estimation objective ****** 41 | 42 | Noise contrastive estimation is another approximation for the word softmax objective function, in additon to Hierarchical softmax and negative sampling, which are implemented in the default word2vec toolkit. This can be turned on by setting the -nce argument. Simply set -nce 10, to use 10 negative samples. Also remember to set -negative and -hs to 0. 43 | 44 | ****** Parameter Capping ****** 45 | 46 | By default parameters are updated freely, and are not checked for algebric overflows to maximize efficiency. However, we had some datasets where the CWINDOW architecture overflows, which leads to segfaults, If this happens, even in other architectures, try setting the paramter -cap 1 in order to avoid this problem at the cost of a small degradation in computational speed. 47 | 48 | ****** Class-based Negative Sampling ****** 49 | 50 | A new argument -negative-classes can be added to specify groups of classes. It receives a file in the format: 51 | 52 | N dog 53 | N cat 54 | N worm 55 | V doing 56 | V finding 57 | V dodging 58 | A charming 59 | A satirical 60 | 61 | where each line defines a class and a word belonging to that class. For words belonging to the class, negative sampling is only performed on words on that class. For instance, if the desired output is dog, we would only sample from cat and worm. For words not in the list, sampling is performed over all word types. 62 | 63 | warning: the file must be order so that all words in the same class are grouped, so the following would not work correctly. 64 | 65 | N dog 66 | A charming 67 | N cat 68 | N worm 69 | V doing 70 | V finding 71 | V dodging 72 | A satirical 73 | 74 | ****** Minor Changes ****** 75 | 76 | The distance_txt and kmeans_txt are adaptations of the original distance and kmeans code to take textual (-binary 0) embeddings as input 77 | -------------------------------------------------------------------------------- /compute-accuracy.c: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | 22 | const long long max_size = 2000; // max length of strings 23 | const long long N = 1; // number of closest words 24 | const long long max_w = 50; // max length of vocabulary entries 25 | 26 | int main(int argc, char **argv) 27 | { 28 | FILE *f; 29 | char st1[max_size], st2[max_size], st3[max_size], st4[max_size], bestw[N][max_size], file_name[max_size]; 30 | float dist, len, bestd[N], vec[max_size]; 31 | long long words, size, a, b, c, d, b1, b2, b3, threshold = 0; 32 | float *M; 33 | char *vocab; 34 | int TCN, CCN = 0, TACN = 0, CACN = 0, SECN = 0, SYCN = 0, SEAC = 0, SYAC = 0, QID = 0, TQ = 0, TQS = 0; 35 | if (argc < 2) { 36 | printf("Usage: ./compute-accuracy \nwhere FILE contains word projections, and threshold is used to reduce vocabulary of the model for fast approximate evaluation (0 = off, otherwise typical value is 30000)\n"); 37 | return 0; 38 | } 39 | strcpy(file_name, argv[1]); 40 | if (argc > 2) threshold = atoi(argv[2]); 41 | f = fopen(file_name, "rb"); 42 | if (f == NULL) { 43 | printf("Input file not found\n"); 44 | return -1; 45 | } 46 | fscanf(f, "%lld", &words); 47 | if (threshold) if (words > threshold) words = threshold; 48 | fscanf(f, "%lld", &size); 49 | vocab = (char *)malloc(words * max_w * sizeof(char)); 50 | M = (float *)malloc(words * size * sizeof(float)); 51 | if (M == NULL) { 52 | printf("Cannot allocate memory: %lld MB\n", words * size * sizeof(float) / 1048576); 53 | return -1; 54 | } 55 | for (b = 0; b < words; b++) { 56 | a = 0; 57 | while (1) { 58 | vocab[b * max_w + a] = fgetc(f); 59 | if (feof(f) || (vocab[b * max_w + a] == ' ')) break; 60 | if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++; 61 | } 62 | vocab[b * max_w + a] = 0; 63 | for (a = 0; a < max_w; a++) vocab[b * max_w + a] = toupper(vocab[b * max_w + a]); 64 | for (a = 0; a < size; a++) fread(&M[a + b * size], sizeof(float), 1, f); 65 | len = 0; 66 | for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size]; 67 | len = sqrt(len); 68 | for (a = 0; a < size; a++) M[a + b * size] /= len; 69 | } 70 | fclose(f); 71 | TCN = 0; 72 | while (1) { 73 | for (a = 0; a < N; a++) bestd[a] = 0; 74 | for (a = 0; a < N; a++) bestw[a][0] = 0; 75 | scanf("%s", st1); 76 | for (a = 0; a < strlen(st1); a++) st1[a] = toupper(st1[a]); 77 | if ((!strcmp(st1, ":")) || (!strcmp(st1, "EXIT")) || feof(stdin)) { 78 | if (TCN == 0) TCN = 1; 79 | if (QID != 0) { 80 | printf("ACCURACY TOP1: %.2f %% (%d / %d)\n", CCN / (float)TCN * 100, CCN, TCN); 81 | printf("Total accuracy: %.2f %% Semantic accuracy: %.2f %% Syntactic accuracy: %.2f %% \n", CACN / (float)TACN * 100, SEAC / (float)SECN * 100, SYAC / (float)SYCN * 100); 82 | } 83 | QID++; 84 | scanf("%s", st1); 85 | if (feof(stdin)) break; 86 | printf("%s:\n", st1); 87 | TCN = 0; 88 | CCN = 0; 89 | continue; 90 | } 91 | if (!strcmp(st1, "EXIT")) break; 92 | scanf("%s", st2); 93 | for (a = 0; a < strlen(st2); a++) st2[a] = toupper(st2[a]); 94 | scanf("%s", st3); 95 | for (a = 0; a bestd[a]) { 122 | for (d = N - 1; d > a; d--) { 123 | bestd[d] = bestd[d - 1]; 124 | strcpy(bestw[d], bestw[d - 1]); 125 | } 126 | bestd[a] = dist; 127 | strcpy(bestw[a], &vocab[c * max_w]); 128 | break; 129 | } 130 | } 131 | } 132 | if (!strcmp(st4, bestw[0])) { 133 | CCN++; 134 | CACN++; 135 | if (QID <= 5) SEAC++; else SYAC++; 136 | } 137 | if (QID <= 5) SECN++; else SYCN++; 138 | TCN++; 139 | TACN++; 140 | } 141 | printf("Questions seen / total: %d %d %.2f %% \n", TQS, TQ, TQS/(float)TQ*100); 142 | return 0; 143 | } 144 | -------------------------------------------------------------------------------- /distance.c: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | const long long max_size = 2000; // max length of strings 21 | const long long N = 40; // number of closest words that will be shown 22 | const long long max_w = 50; // max length of vocabulary entries 23 | 24 | #define MAX_STRING 100 25 | void ReadWord(char *word, FILE *fin) { 26 | int a = 0, ch; 27 | while (!feof(fin)) { 28 | ch = fgetc(fin); 29 | if (ch == 13) continue; 30 | if ((ch == ' ') || (ch == '\t') || (ch == '\n')) { 31 | if (a > 0) { 32 | if (ch == '\n') ungetc(ch, fin); 33 | break; 34 | } 35 | if (ch == '\n') { 36 | strcpy(word, (char *)""); 37 | return; 38 | } else continue; 39 | } 40 | word[a] = ch; 41 | a++; 42 | if (a >= MAX_STRING - 1) a--; // Truncate too long words 43 | } 44 | word[a] = 0; 45 | } 46 | 47 | int main(int argc, char **argv) { 48 | FILE *f; 49 | char st1[max_size]; 50 | char *bestw[N]; 51 | char file_name[max_size], st[100][max_size]; 52 | float dist, len, bestd[N], vec[max_size]; 53 | long long words, size, a, b, c, d, cn, bi[100]; 54 | float *M; 55 | char *vocab; 56 | if (argc < 2) { 57 | printf("Usage: ./distance \nwhere FILE contains word projections in the BINARY FORMAT\n"); 58 | return 0; 59 | } 60 | strcpy(file_name, argv[1]); 61 | f = fopen(file_name, "rb"); 62 | if (f == NULL) { 63 | printf("Input file not found\n"); 64 | return -1; 65 | } 66 | fscanf(f, "%lld", &words); 67 | fscanf(f, "%lld", &size); 68 | vocab = (char *)malloc((long long)words * max_w * sizeof(char)); 69 | for (a = 0; a < N; a++) bestw[a] = (char *)malloc(max_size * sizeof(char)); 70 | M = (float *)malloc((long long)words * (long long)size * sizeof(float)); 71 | if (M == NULL) { 72 | printf("Cannot allocate memory: %lld MB %lld %lld\n", (long long)words * size * sizeof(float) / 1048576, words, size); 73 | return -1; 74 | } 75 | for (b = 0; b < words; b++) { 76 | a = 0; 77 | while (1) { 78 | vocab[b * max_w + a] = fgetc(f); 79 | if (feof(f) || (vocab[b * max_w + a] == ' ')) break; 80 | if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++; 81 | } 82 | vocab[b * max_w + a] = 0; 83 | for (a = 0; a < size; a++) fread(&M[a + b * size], sizeof(float), 1, f); 84 | len = 0; 85 | for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size]; 86 | len = sqrt(len); 87 | for (a = 0; a < size; a++) M[a + b * size] /= len; 88 | } 89 | fclose(f); 90 | while (1) { 91 | for (a = 0; a < N; a++) bestd[a] = 0; 92 | for (a = 0; a < N; a++) bestw[a][0] = 0; 93 | printf("Enter word or sentence (EXIT to break): "); 94 | a = 0; 95 | while (1) { 96 | st1[a] = fgetc(stdin); 97 | if ((st1[a] == '\n') || (a >= max_size - 1)) { 98 | st1[a] = 0; 99 | break; 100 | } 101 | a++; 102 | } 103 | if (!strcmp(st1, "EXIT")) break; 104 | cn = 0; 105 | b = 0; 106 | c = 0; 107 | while (1) { 108 | st[cn][b] = st1[c]; 109 | b++; 110 | c++; 111 | st[cn][b] = 0; 112 | if (st1[c] == 0) break; 113 | if (st1[c] == ' ') { 114 | cn++; 115 | b = 0; 116 | c++; 117 | } 118 | } 119 | cn++; 120 | for (a = 0; a < cn; a++) { 121 | for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st[a])) break; 122 | if (b == words) b = -1; 123 | bi[a] = b; 124 | printf("\nWord: %s Position in vocabulary: %lld\n", st[a], bi[a]); 125 | if (b == -1) { 126 | printf("Out of dictionary word!\n"); 127 | break; 128 | } 129 | } 130 | if (b == -1) continue; 131 | printf("\n Word Cosine distance\n------------------------------------------------------------------------\n"); 132 | for (a = 0; a < size; a++) vec[a] = 0; 133 | for (b = 0; b < cn; b++) { 134 | if (bi[b] == -1) continue; 135 | for (a = 0; a < size; a++) vec[a] += M[a + bi[b] * size]; 136 | } 137 | len = 0; 138 | for (a = 0; a < size; a++) len += vec[a] * vec[a]; 139 | len = sqrt(len); 140 | for (a = 0; a < size; a++) vec[a] /= len; 141 | for (a = 0; a < N; a++) bestd[a] = -1; 142 | for (a = 0; a < N; a++) bestw[a][0] = 0; 143 | for (c = 0; c < words; c++) { 144 | a = 0; 145 | for (b = 0; b < cn; b++) if (bi[b] == c) a = 1; 146 | if (a == 1) continue; 147 | dist = 0; 148 | for (a = 0; a < size; a++) dist += vec[a] * M[a + c * size]; 149 | for (a = 0; a < N; a++) { 150 | if (dist > bestd[a]) { 151 | for (d = N - 1; d > a; d--) { 152 | bestd[d] = bestd[d - 1]; 153 | strcpy(bestw[d], bestw[d - 1]); 154 | } 155 | bestd[a] = dist; 156 | strcpy(bestw[a], &vocab[c * max_w]); 157 | break; 158 | } 159 | } 160 | } 161 | for (a = 0; a < N; a++) printf("%50s\t\t%f\n", bestw[a], bestd[a]); 162 | } 163 | return 0; 164 | } 165 | -------------------------------------------------------------------------------- /distance_fast.c: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | const long long max_size = 2000; // max length of strings 22 | const long long N = 10; // number of closest words that will be shown 23 | const long long max_w = 50; // max length of vocabulary entries 24 | 25 | #define MAX_STRING 100 26 | void ReadWord(char *word, FILE *fin) { 27 | int a = 0, ch; 28 | while (!feof(fin)) { 29 | ch = fgetc(fin); 30 | if (ch == 13) continue; 31 | if ((ch == ' ') || (ch == '\t') || (ch == '\n')) { 32 | if (a > 0) { 33 | if (ch == '\n') ungetc(ch, fin); 34 | break; 35 | } 36 | if (ch == '\n') { 37 | strcpy(word, (char *)""); 38 | return; 39 | } else continue; 40 | } 41 | word[a] = ch; 42 | a++; 43 | if (a >= MAX_STRING - 1) a--; // Truncate too long words 44 | } 45 | word[a] = 0; 46 | } 47 | 48 | int main(int argc, char **argv) { 49 | FILE *f; 50 | char st1[max_size]; 51 | char *bestw[N]; 52 | char file_name[max_size], st[100][max_size]; 53 | float dist, len, bestd[N], bestclasses[N], vec[max_size]; 54 | int bestclasses_ids[N]; 55 | long long words, size, a, b, c, d, e, cn, bi[100]; 56 | float *M; 57 | char *vocab; 58 | char word[MAX_STRING]; 59 | clock_t begin; 60 | if (argc < 2) { 61 | printf("Usage: ./kmeans_txt \nwhere FILE contains features\n "); 62 | return 0; 63 | } 64 | strcpy(file_name, argv[1]); 65 | int classes = atoi(argv[2]); 66 | f = fopen(file_name, "rb"); 67 | if (f == NULL) { 68 | printf("Input file not found\n"); 69 | return -1; 70 | } 71 | 72 | printf("reading data\n"); 73 | ReadWord(word, f); 74 | words = atoi(word); 75 | ReadWord(word, f); 76 | size = atoi(word); 77 | vocab = (char *)malloc((long long)words * max_w * sizeof(char)); 78 | for (a = 0; a < N; a++) bestw[a] = (char *)malloc(max_size * sizeof(char)); 79 | M = (float *)malloc((long long)words * (long long)size * sizeof(float)); 80 | if (M == NULL) { 81 | printf("Cannot allocate memory: %lld MB %lld %lld\n", (long long)words * size * sizeof(float) / 1048576, words, size); 82 | return -1; 83 | } 84 | for (b = 0; b < words; b++) { 85 | a = 0; 86 | while (1) { 87 | vocab[b * max_w + a] = fgetc(f); 88 | if (feof(f) || (vocab[b * max_w + a] == ' ')) break; 89 | if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++; 90 | } 91 | vocab[b * max_w + a] = 0; 92 | for (a = 0; a < size; a++) { 93 | ReadWord(word,f); 94 | M[a + b * size] = atof(word); 95 | } 96 | len = 0; 97 | for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size]; 98 | len = sqrt(len); 99 | for (a = 0; a < size; a++) M[a + b * size] /= len; 100 | } 101 | fclose(f); 102 | 103 | //run kmeans 104 | printf("running k-means with %i classes...\n",classes); 105 | int clcn = classes, iter = 10, closeid; 106 | int *centcn = (int *)malloc(classes * sizeof(int)); 107 | int *cl = (int *)calloc(words, sizeof(int)); 108 | float closev, x; 109 | float *cent = (float *)calloc(classes * size, sizeof(float)); 110 | for (a = 0; a < words; a++) cl[a] = a % clcn; 111 | for (a = 0; a < iter; a++) { 112 | for (b = 0; b < clcn * size; b++) cent[b] = 0; 113 | for (b = 0; b < clcn; b++) centcn[b] = 1; 114 | for (c = 0; c < words; c++) { 115 | for (d = 0; d < size; d++) cent[size * cl[c] + d] += M[c * size + d]; 116 | centcn[cl[c]]++; 117 | } 118 | for (b = 0; b < clcn; b++) { 119 | closev = 0; 120 | for (c = 0; c < size; c++) { 121 | cent[size * b + c] /= centcn[b]; 122 | closev += cent[size * b + c] * cent[size * b + c]; 123 | } 124 | closev = sqrt(closev); 125 | for (c = 0; c < size; c++) cent[size * b + c] /= closev; 126 | } 127 | for (c = 0; c < words; c++) { 128 | closev = -10; 129 | closeid = 0; 130 | for (d = 0; d < clcn; d++) { 131 | x = 0; 132 | for (b = 0; b < size; b++) x += cent[size * d + b] * M[c * size + b]; 133 | if (x > closev) { 134 | closev = x; 135 | closeid = d; 136 | } 137 | } 138 | cl[c] = closeid; 139 | } 140 | } 141 | 142 | // build an array of words ordered by class and their offsets (index where each class starts) 143 | int class_words[words]; 144 | int class_offsets[classes]; 145 | for(a = 0; a < classes; a++) class_offsets[a]=0; 146 | for(a = 0; a < words; a++) class_offsets[cl[a]]++; 147 | for(a = 1; a < classes; a++) class_offsets[a] += class_offsets[a-1]; 148 | for(a = 0; a < words; a++) class_words[--class_offsets[cl[a]]] = a; 149 | 150 | //reading from input 151 | while (1) { 152 | for (a = 0; a < N; a++) bestd[a] = 0; 153 | for (a = 0; a < N; a++) bestclasses[a] = 0; 154 | for (a = 0; a < N; a++) bestw[a][0] = 0; 155 | printf("Enter word or sentence (EXIT to break): "); 156 | a = 0; 157 | while (1) { 158 | st1[a] = fgetc(stdin); 159 | if ((st1[a] == '\n') || (a >= max_size - 1)) { 160 | st1[a] = 0; 161 | break; 162 | } 163 | a++; 164 | } 165 | if (!strcmp(st1, "EXIT")) break; 166 | cn = 0; 167 | b = 0; 168 | c = 0; 169 | while (1) { 170 | st[cn][b] = st1[c]; 171 | b++; 172 | c++; 173 | st[cn][b] = 0; 174 | if (st1[c] == 0) break; 175 | if (st1[c] == ' ') { 176 | cn++; 177 | b = 0; 178 | c++; 179 | } 180 | } 181 | cn++; 182 | for (a = 0; a < cn; a++) { 183 | for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st[a])) break; 184 | if (b == words) b = -1; 185 | bi[a] = b; 186 | printf("\nWord: %s Position in vocabulary: %lld\n", st[a], bi[a]); 187 | if (b == -1) { 188 | printf("Out of dictionary word!\n"); 189 | break; 190 | } 191 | } 192 | if (b == -1) continue; 193 | begin = clock(); 194 | 195 | printf("\n Word Cosine distance\n------------------------------------------------------------------------\n"); 196 | 197 | for (a = 0; a < size; a++) vec[a] = 0; 198 | for (b = 0; b < cn; b++) { 199 | if (bi[b] == -1) continue; 200 | for (a = 0; a < size; a++) vec[a] += M[a + bi[b] * size]; 201 | } 202 | 203 | len = 0; 204 | for (a = 0; a < size; a++) len += vec[a] * vec[a]; 205 | len = sqrt(len); 206 | for (a = 0; a < size; a++) vec[a] /= len; 207 | 208 | // find top N centroids 209 | for (a = 0; a < N; a++) bestclasses[a] = -1; 210 | for (a = 0; a < N; a++) bestclasses_ids[a] = -1; 211 | for (c = 0; c < classes; c++){ 212 | dist = 0; 213 | for (a = 0; a < size; a++) dist += vec[a] * cent[a + size * c]; 214 | for (a = 0; a < N; a++) { 215 | if (dist > bestclasses[a]) { 216 | for(d = N - 1; d > a; d--){ 217 | bestclasses[d] = bestclasses[d-1]; 218 | bestclasses_ids[d] = bestclasses_ids[d-1]; 219 | } 220 | bestclasses[a] = dist; 221 | bestclasses_ids[a] = c; 222 | break; 223 | } 224 | } 225 | } 226 | 227 | // find top N words in the centroids 228 | for (a = 0; a < N; a++) bestd[a] = -1; 229 | for (a = 0; a < N; a++) bestw[a][0] = 0; 230 | for (a = 0; a < N; a++){ 231 | c = words; 232 | if(bestclasses_ids[a] < classes-1) c = class_offsets[bestclasses_ids[a]+1]; 233 | b = class_offsets[bestclasses_ids[a]]; 234 | for(; b < c; b++){ 235 | dist = 0; 236 | for (d = 0; d < size; d++) dist += vec[d] * M[d + class_words[b] * size]; 237 | for (d = 0; d < N; d++){ 238 | if(dist > bestd[d]){ 239 | for (e = N -1; e > d; e--){ 240 | bestd[e] = bestd[e-1]; 241 | strcpy(bestw[e], bestw[e-1]); 242 | } 243 | bestd[d] = dist; 244 | strcpy(bestw[d], &vocab[class_words[b] * max_w]); 245 | break; 246 | } 247 | } 248 | } 249 | } 250 | for (a = 0; a < N; a++) printf("%50s\t\t%f\n", bestw[a], bestd[a]); 251 | printf("time spent = %f seconds\n", (double)(clock() - begin) / CLOCKS_PER_SEC); 252 | } 253 | // Save the K-means classes 254 | 255 | free(centcn); 256 | free(cent); 257 | free(cl); 258 | 259 | //start running distance 260 | return 0; 261 | } 262 | -------------------------------------------------------------------------------- /distance_txt.c: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | const long long max_size = 2000; // max length of strings 22 | const long long N = 40; // number of closest words that will be shown 23 | const long long max_w = 50; // max length of vocabulary entries 24 | 25 | #define MAX_STRING 100 26 | void ReadWord(char *word, FILE *fin) { 27 | int a = 0, ch; 28 | while (!feof(fin)) { 29 | ch = fgetc(fin); 30 | if (ch == 13) continue; 31 | if ((ch == ' ') || (ch == '\t') || (ch == '\n')) { 32 | if (a > 0) { 33 | if (ch == '\n') ungetc(ch, fin); 34 | break; 35 | } 36 | if (ch == '\n') { 37 | strcpy(word, (char *)""); 38 | return; 39 | } else continue; 40 | } 41 | word[a] = ch; 42 | a++; 43 | if (a >= MAX_STRING - 1) a--; // Truncate too long words 44 | } 45 | word[a] = 0; 46 | } 47 | 48 | int main(int argc, char **argv) { 49 | FILE *f; 50 | char st1[max_size]; 51 | char *bestw[N]; 52 | char file_name[max_size], st[100][max_size]; 53 | float dist, len, bestd[N], vec[max_size]; 54 | long long words, size, a, b, c, d, cn, bi[100]; 55 | float *M; 56 | char *vocab; 57 | char word[MAX_STRING]; 58 | clock_t begin; 59 | if (argc < 2) { 60 | printf("Usage: ./distance \nwhere FILE contains word projections in the BINARY FORMAT\n"); 61 | return 0; 62 | } 63 | strcpy(file_name, argv[1]); 64 | f = fopen(file_name, "rb"); 65 | if (f == NULL) { 66 | printf("Input file not found\n"); 67 | return -1; 68 | } 69 | ReadWord(word, f); 70 | words = atoi(word); 71 | ReadWord(word, f); 72 | size = atoi(word); 73 | vocab = (char *)malloc((long long)words * max_w * sizeof(char)); 74 | for (a = 0; a < N; a++) bestw[a] = (char *)malloc(max_size * sizeof(char)); 75 | M = (float *)malloc((long long)words * (long long)size * sizeof(float)); 76 | if (M == NULL) { 77 | printf("Cannot allocate memory: %lld MB %lld %lld\n", (long long)words * size * sizeof(float) / 1048576, words, size); 78 | return -1; 79 | } 80 | for (b = 0; b < words; b++) { 81 | a = 0; 82 | while (1) { 83 | vocab[b * max_w + a] = fgetc(f); 84 | if (feof(f) || (vocab[b * max_w + a] == ' ')) break; 85 | if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++; 86 | } 87 | vocab[b * max_w + a] = 0; 88 | for (a = 0; a < size; a++) { 89 | ReadWord(word,f); 90 | M[a + b * size] = atof(word); 91 | } 92 | len = 0; 93 | for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size]; 94 | len = sqrt(len); 95 | for (a = 0; a < size; a++) M[a + b * size] /= len; 96 | } 97 | fclose(f); 98 | while (1) { 99 | for (a = 0; a < N; a++) bestd[a] = 0; 100 | for (a = 0; a < N; a++) bestw[a][0] = 0; 101 | printf("Enter word or sentence (EXIT to break): "); 102 | a = 0; 103 | while (1) { 104 | st1[a] = fgetc(stdin); 105 | if ((st1[a] == '\n') || (a >= max_size - 1)) { 106 | st1[a] = 0; 107 | break; 108 | } 109 | a++; 110 | } 111 | if (!strcmp(st1, "EXIT")) break; 112 | cn = 0; 113 | b = 0; 114 | c = 0; 115 | while (1) { 116 | st[cn][b] = st1[c]; 117 | b++; 118 | c++; 119 | st[cn][b] = 0; 120 | if (st1[c] == 0) break; 121 | if (st1[c] == ' ') { 122 | cn++; 123 | b = 0; 124 | c++; 125 | } 126 | } 127 | cn++; 128 | for (a = 0; a < cn; a++) { 129 | for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st[a])) break; 130 | if (b == words) b = -1; 131 | bi[a] = b; 132 | printf("\nWord: %s Position in vocabulary: %lld\n", st[a], bi[a]); 133 | if (b == -1) { 134 | printf("Out of dictionary word!\n"); 135 | break; 136 | } 137 | } 138 | if (b == -1) continue; 139 | begin = clock(); 140 | 141 | printf("\n Word Cosine distance\n------------------------------------------------------------------------\n"); 142 | for (a = 0; a < size; a++) vec[a] = 0; 143 | for (b = 0; b < cn; b++) { 144 | if (bi[b] == -1) continue; 145 | for (a = 0; a < size; a++) vec[a] += M[a + bi[b] * size]; 146 | } 147 | len = 0; 148 | for (a = 0; a < size; a++) len += vec[a] * vec[a]; 149 | len = sqrt(len); 150 | for (a = 0; a < size; a++) vec[a] /= len; 151 | for (a = 0; a < N; a++) bestd[a] = -1; 152 | for (a = 0; a < N; a++) bestw[a][0] = 0; 153 | for (c = 0; c < words; c++) { 154 | a = 0; 155 | for (b = 0; b < cn; b++) if (bi[b] == c) a = 1; 156 | if (a == 1) continue; 157 | dist = 0; 158 | for (a = 0; a < size; a++) dist += vec[a] * M[a + c * size]; 159 | for (a = 0; a < N; a++) { 160 | if (dist > bestd[a]) { 161 | for (d = N - 1; d > a; d--) { 162 | bestd[d] = bestd[d - 1]; 163 | strcpy(bestw[d], bestw[d - 1]); 164 | } 165 | bestd[a] = dist; 166 | strcpy(bestw[a], &vocab[c * max_w]); 167 | break; 168 | } 169 | } 170 | } 171 | for (a = 0; a < N; a++) printf("%50s\t\t%f\n", bestw[a], bestd[a]); 172 | printf("time spent = %f seconds\n", (double)(clock() - begin) / CLOCKS_PER_SEC); 173 | } 174 | return 0; 175 | } 176 | -------------------------------------------------------------------------------- /kmeans_txt.c: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | const long long max_size = 2000; // max length of strings 21 | const long long N = 40; // number of closest words that will be shown 22 | const long long max_w = 50; // max length of vocabulary entries 23 | 24 | #define MAX_STRING 100 25 | void ReadWord(char *word, FILE *fin) { 26 | int a = 0, ch; 27 | while (!feof(fin)) { 28 | ch = fgetc(fin); 29 | if (ch == 13) continue; 30 | if ((ch == ' ') || (ch == '\t') || (ch == '\n')) { 31 | if (a > 0) { 32 | if (ch == '\n') ungetc(ch, fin); 33 | break; 34 | } 35 | if (ch == '\n') { 36 | strcpy(word, (char *)""); 37 | return; 38 | } else continue; 39 | } 40 | word[a] = ch; 41 | a++; 42 | if (a >= MAX_STRING - 1) a--; // Truncate too long words 43 | } 44 | word[a] = 0; 45 | } 46 | 47 | int main(int argc, char **argv) { 48 | FILE *f; 49 | char file_name[max_size], output_file[max_size]; 50 | float len; 51 | long long words, size, a, b, c, d; 52 | float *M; 53 | char *vocab; 54 | char word[MAX_STRING]; 55 | if (argc < 3) { 56 | printf("Usage: ./kmeans_txt \nwhere FILE contains features\n "); 57 | return 0; 58 | } 59 | strcpy(file_name, argv[1]); 60 | strcpy(output_file, argv[2]); 61 | int classes = atoi(argv[3]); 62 | f = fopen(file_name, "rb"); 63 | if (f == NULL) { 64 | printf("Input file not found\n"); 65 | return -1; 66 | } 67 | 68 | FILE *fo = fopen(output_file, "wb"); 69 | 70 | ReadWord(word, f); 71 | words = atoi(word); 72 | ReadWord(word, f); 73 | size = atoi(word); 74 | vocab = (char *)malloc((long long)words * max_w * sizeof(char)); 75 | M = (float *)malloc((long long)words * (long long)size * sizeof(float)); 76 | if (M == NULL) { 77 | printf("Cannot allocate memory: %lld MB %lld %lld\n", (long long)words * size * sizeof(float) / 1048576, words, size); 78 | return -1; 79 | } 80 | for (b = 0; b < words; b++) { 81 | a = 0; 82 | while (1) { 83 | vocab[b * max_w + a] = fgetc(f); 84 | if (feof(f) || (vocab[b * max_w + a] == ' ')) break; 85 | if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++; 86 | } 87 | vocab[b * max_w + a] = 0; 88 | for (a = 0; a < size; a++) { 89 | ReadWord(word,f); 90 | M[a + b * size] = atof(word); 91 | } 92 | len = 0; 93 | for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size]; 94 | len = sqrt(len); 95 | for (a = 0; a < size; a++) M[a + b * size] /= len; 96 | } 97 | fclose(f); 98 | 99 | //run kmeans 100 | int clcn = classes, iter = 2, closeid; 101 | int *centcn = (int *)malloc(classes * sizeof(int)); 102 | int *cl = (int *)calloc(words, sizeof(int)); 103 | float closev, x; 104 | float *cent = (float *)calloc(classes * size, sizeof(float)); 105 | for (a = 0; a < words; a++) cl[a] = a % clcn; 106 | for (a = 0; a < iter; a++) { 107 | for (b = 0; b < clcn * size; b++) cent[b] = 0; 108 | for (b = 0; b < clcn; b++) centcn[b] = 1; 109 | for (c = 0; c < words; c++) { 110 | for (d = 0; d < size; d++) cent[size * cl[c] + d] += M[c * size + d]; 111 | centcn[cl[c]]++; 112 | } 113 | for (b = 0; b < clcn; b++) { 114 | closev = 0; 115 | for (c = 0; c < size; c++) { 116 | cent[size * b + c] /= centcn[b]; 117 | closev += cent[size * b + c] * cent[size * b + c]; 118 | } 119 | closev = sqrt(closev); 120 | for (c = 0; c < size; c++) cent[size * b + c] /= closev; 121 | } 122 | for (c = 0; c < words; c++) { 123 | closev = -10; 124 | closeid = 0; 125 | for (d = 0; d < clcn; d++) { 126 | x = 0; 127 | for (b = 0; b < size; b++) x += cent[size * d + b] * M[c * size + b]; 128 | if (x > closev) { 129 | closev = x; 130 | closeid = d; 131 | } 132 | } 133 | cl[c] = closeid; 134 | } 135 | } 136 | 137 | // build an array of words ordered by class and their offsets (index where each class starts) 138 | int class_words[words]; 139 | int class_offsets[classes]; 140 | for(a = 0; a < classes; a++) class_offsets[a]=0; 141 | for(a = 0; a < words; a++) class_offsets[cl[a]]++; 142 | for(a = 1; a < classes; a++) class_offsets[a] += class_offsets[a-1]; 143 | for(a = 0; a < words; a++) class_words[--class_offsets[cl[a]]] = a; 144 | 145 | for (a = 0; a < classes; a++){ 146 | c = words; 147 | if(a < classes-1) c = class_offsets[a+1]; 148 | b = class_offsets[a]; 149 | for(; b < c; b++){ 150 | fprintf(fo, "%lld %s\n", a ,&vocab[class_words[b] * max_w]); 151 | } 152 | } 153 | // Save the K-means classes 154 | //for (a = 0; a < words; a++) fprintf(fo, "%s %d\n", &vocab[a * max_w], cl[a]); 155 | free(centcn); 156 | free(cent); 157 | free(cl); 158 | free(M); 159 | free(vocab); 160 | return 0; 161 | } 162 | -------------------------------------------------------------------------------- /makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | #Using -Ofast instead of -O3 might result in faster code, but is supported only by newer GCC versions 3 | CFLAGS = -lm -pthread -O3 -march=native -Wall -funroll-loops -Wno-unused-result -g 4 | 5 | all: word2vec cngram2vec weightedWord2vec wordless2vec word2phrase distance word-analogy compute-accuracy distance_txt distance_fast kmeans_txt 6 | 7 | word2vec : word2vec.c 8 | $(CC) word2vec.c -o word2vec $(CFLAGS) 9 | weightedWord2vec : weightedWord2vec.c 10 | $(CC) weightedWord2vec.c -o weightedWord2vec $(CFLAGS) 11 | cngram2vec : cngram2vec.c 12 | $(CC) cngram2vec.c -o cngram2vec $(CFLAGS) 13 | wordless2vec : wordless2vec.c 14 | $(CC) wordless2vec.c -o wordless2vec $(CFLAGS) 15 | word2phrase : word2phrase.c 16 | $(CC) word2phrase.c -o word2phrase $(CFLAGS) 17 | distance : distance.c 18 | $(CC) distance.c -o distance $(CFLAGS) 19 | distance_txt : distance_txt.c 20 | $(CC) distance_txt.c -o distance_txt $(CFLAGS) 21 | distance_fast : distance_fast.c 22 | $(CC) distance_fast.c -o distance_fast $(CFLAGS) 23 | kmeans_txt : kmeans_txt.c 24 | $(CC) kmeans_txt.c -o kmeans_txt $(CFLAGS) 25 | word-analogy : word-analogy.c 26 | $(CC) word-analogy.c -o word-analogy $(CFLAGS) 27 | compute-accuracy : compute-accuracy.c 28 | $(CC) compute-accuracy.c -o compute-accuracy $(CFLAGS) 29 | clean: 30 | rm -rf word2vec weightedWord2vec cngram2vec word2phrase distance word-analogy compute-accuracy distance_txt kmeans_txt 31 | -------------------------------------------------------------------------------- /weightedWord2vec.c: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | #define MAX_STRING 100 22 | #define EXP_TABLE_SIZE 1000 23 | #define MAX_EXP 6 24 | #define MAX_SENTENCE_LENGTH 1000 25 | #define MAX_CODE_LENGTH 40 26 | 27 | const int vocab_hash_size = 30000000; // Maximum 30 * 0.7 = 21M words in the vocabulary 28 | 29 | typedef float real; // Precision of float numbers 30 | 31 | struct vocab_word { 32 | long long cn; 33 | int *point; 34 | char *word, *code, codelen; 35 | }; 36 | 37 | char train_file[MAX_STRING], output_file[MAX_STRING]; 38 | char save_vocab_file[MAX_STRING], read_vocab_file[MAX_STRING]; 39 | struct vocab_word *vocab; 40 | int binary = 0, type = 1, debug_mode = 2, window = 5, min_count = 5, num_threads = 12, min_reduce = 1; 41 | int *vocab_hash; 42 | long long vocab_max_size = 1000, vocab_size = 0, layer1_size = 100; 43 | long long train_words = 0, word_count_actual = 0, iter = 5, file_size = 0, classes = 0; 44 | real alpha = 0.025, starting_alpha, sample = 1e-3; 45 | real *syn0, *syn1, *syn1neg, *syn1nce, *expTable; 46 | clock_t start; 47 | 48 | real *syn1_window, *syn1neg_window, *syn1nce_window; 49 | int w_offset, window_layer_size; 50 | 51 | int window_hidden_size = 500; 52 | real *syn_window_hidden, *syn_hidden_word, *syn_hidden_word_neg, *syn_hidden_word_nce; 53 | 54 | int hs = 0, negative = 5; 55 | const int table_size = 1e8; 56 | int *table; 57 | 58 | //constrastive negative sampling 59 | char negative_classes_file[MAX_STRING]; 60 | int *word_to_group; 61 | int *group_to_table; //group_size*table_size 62 | int class_number; 63 | 64 | //nce 65 | real* noise_distribution; 66 | int nce = 0; 67 | 68 | //param caps 69 | real CAP_VALUE = 50; 70 | int cap = 0; 71 | 72 | void capParam(real* array, int index){ 73 | if(array[index] > CAP_VALUE) 74 | array[index] = CAP_VALUE; 75 | else if(array[index] < -CAP_VALUE) 76 | array[index] = -CAP_VALUE; 77 | } 78 | 79 | real hardTanh(real x){ 80 | if(x>=1){ 81 | return 1; 82 | } 83 | else if(x<=-1){ 84 | return -1; 85 | } 86 | else{ 87 | return x; 88 | } 89 | } 90 | 91 | real dHardTanh(real x, real g){ 92 | if(x > 1 && g > 0){ 93 | return 0; 94 | } 95 | if(x < -1 && g < 0){ 96 | return 0; 97 | } 98 | return 1; 99 | } 100 | 101 | int isEndOfSentence(char* word){ 102 | return strcmp("", word) == 0; 103 | } 104 | 105 | void InitUnigramTable() { 106 | int a, i; 107 | long long train_words_pow = 0; 108 | real d1, power = 0.75; 109 | table = (int *)malloc(table_size * sizeof(int)); 110 | for (a = 0; a < vocab_size; a++) train_words_pow += pow(vocab[a].cn, power); 111 | i = 0; 112 | d1 = pow(vocab[i].cn, power) / (real)train_words_pow; 113 | for (a = 0; a < table_size; a++) { 114 | table[a] = i; 115 | if (a / (real)table_size > d1) { 116 | i++; 117 | d1 += pow(vocab[i].cn, power) / (real)train_words_pow; 118 | } 119 | if (i >= vocab_size) i = vocab_size - 1; 120 | } 121 | 122 | noise_distribution = (real *)calloc(vocab_size, sizeof(real)); 123 | for (a = 0; a < vocab_size; a++) noise_distribution[a] = pow(vocab[a].cn, power)/(real)train_words_pow; 124 | } 125 | 126 | // Reads a single word from a file, assuming space + tab + EOL to be word boundaries 127 | void ReadWord(char *word, FILE *fin) { 128 | int a = 0, ch; 129 | while (!feof(fin)) { 130 | ch = fgetc(fin); 131 | if (ch == 13) continue; 132 | if ((ch == ' ') || (ch == '\t') || (ch == '\n')) { 133 | if (a > 0) { 134 | if (ch == '\n') ungetc(ch, fin); 135 | break; 136 | } 137 | if (ch == '\n') { 138 | strcpy(word, (char *)""); 139 | return; 140 | } else continue; 141 | } 142 | word[a] = ch; 143 | a++; 144 | if (a >= MAX_STRING - 1) a--; // Truncate too long words 145 | } 146 | word[a] = 0; 147 | } 148 | 149 | // Returns hash value of a word 150 | int GetWordHash(char *word) { 151 | unsigned long long a, hash = 0; 152 | for (a = 0; a < strlen(word); a++) hash = hash * 257 + word[a]; 153 | hash = hash % vocab_hash_size; 154 | return hash; 155 | } 156 | 157 | // Returns position of a word in the vocabulary; if the word is not found, returns -1 158 | int SearchVocab(char *word) { 159 | unsigned int hash = GetWordHash(word); 160 | while (1) { 161 | if (vocab_hash[hash] == -1) return -1; 162 | if (!strcmp(word, vocab[vocab_hash[hash]].word)) return vocab_hash[hash]; 163 | hash = (hash + 1) % vocab_hash_size; 164 | } 165 | return -1; 166 | } 167 | 168 | // Reads a word and returns its index in the vocabulary 169 | int ReadWordIndex(FILE *fin) { 170 | char word[MAX_STRING]; 171 | ReadWord(word, fin); 172 | if (feof(fin)) return -1; 173 | return SearchVocab(word); 174 | } 175 | 176 | // Adds a word to the vocabulary 177 | int AddWordToVocab(char *word) { 178 | unsigned int hash, length = strlen(word) + 1; 179 | if (length > MAX_STRING) length = MAX_STRING; 180 | vocab[vocab_size].word = (char *)calloc(length, sizeof(char)); 181 | strcpy(vocab[vocab_size].word, word); 182 | vocab[vocab_size].cn = 0; 183 | vocab_size++; 184 | // Reallocate memory if needed 185 | if (vocab_size + 2 >= vocab_max_size) { 186 | vocab_max_size += 1000; 187 | vocab = (struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(struct vocab_word)); 188 | } 189 | hash = GetWordHash(word); 190 | while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; 191 | vocab_hash[hash] = vocab_size - 1; 192 | return vocab_size - 1; 193 | } 194 | 195 | // Used later for sorting by word counts 196 | int VocabCompare(const void *a, const void *b) { 197 | return ((struct vocab_word *)b)->cn - ((struct vocab_word *)a)->cn; 198 | } 199 | 200 | // Sorts the vocabulary by frequency using word counts 201 | void SortVocab() { 202 | int a, size; 203 | unsigned int hash; 204 | // Sort the vocabulary and keep at the first position 205 | qsort(&vocab[1], vocab_size - 1, sizeof(struct vocab_word), VocabCompare); 206 | for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; 207 | size = vocab_size; 208 | train_words = 0; 209 | for (a = 0; a < size; a++) { 210 | // Words occuring less than min_count times will be discarded from the vocab 211 | if ((vocab[a].cn < min_count) && (a != 0)) { 212 | vocab_size--; 213 | free(vocab[a].word); 214 | } else { 215 | // Hash will be re-computed, as after the sorting it is not actual 216 | hash=GetWordHash(vocab[a].word); 217 | while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; 218 | vocab_hash[hash] = a; 219 | train_words += vocab[a].cn; 220 | } 221 | } 222 | vocab = (struct vocab_word *)realloc(vocab, (vocab_size + 1) * sizeof(struct vocab_word)); 223 | // Allocate memory for the binary tree construction 224 | for (a = 0; a < vocab_size; a++) { 225 | vocab[a].code = (char *)calloc(MAX_CODE_LENGTH, sizeof(char)); 226 | vocab[a].point = (int *)calloc(MAX_CODE_LENGTH, sizeof(int)); 227 | } 228 | } 229 | 230 | // Reduces the vocabulary by removing infrequent tokens 231 | void ReduceVocab() { 232 | int a, b = 0; 233 | unsigned int hash; 234 | for (a = 0; a < vocab_size; a++) if (vocab[a].cn > min_reduce) { 235 | vocab[b].cn = vocab[a].cn; 236 | vocab[b].word = vocab[a].word; 237 | b++; 238 | } else free(vocab[a].word); 239 | vocab_size = b; 240 | for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; 241 | for (a = 0; a < vocab_size; a++) { 242 | // Hash will be re-computed, as it is not actual 243 | hash = GetWordHash(vocab[a].word); 244 | while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; 245 | vocab_hash[hash] = a; 246 | } 247 | fflush(stdout); 248 | min_reduce++; 249 | } 250 | 251 | // Create binary Huffman tree using the word counts 252 | // Frequent words will have short uniqe binary codes 253 | void CreateBinaryTree() { 254 | long long a, b, i, min1i, min2i, pos1, pos2, point[MAX_CODE_LENGTH]; 255 | char code[MAX_CODE_LENGTH]; 256 | long long *count = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); 257 | long long *binary = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); 258 | long long *parent_node = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); 259 | for (a = 0; a < vocab_size; a++) count[a] = vocab[a].cn; 260 | for (a = vocab_size; a < vocab_size * 2; a++) count[a] = 1e15; 261 | pos1 = vocab_size - 1; 262 | pos2 = vocab_size; 263 | // Following algorithm constructs the Huffman tree by adding one node at a time 264 | for (a = 0; a < vocab_size - 1; a++) { 265 | // First, find two smallest nodes 'min1, min2' 266 | if (pos1 >= 0) { 267 | if (count[pos1] < count[pos2]) { 268 | min1i = pos1; 269 | pos1--; 270 | } else { 271 | min1i = pos2; 272 | pos2++; 273 | } 274 | } else { 275 | min1i = pos2; 276 | pos2++; 277 | } 278 | if (pos1 >= 0) { 279 | if (count[pos1] < count[pos2]) { 280 | min2i = pos1; 281 | pos1--; 282 | } else { 283 | min2i = pos2; 284 | pos2++; 285 | } 286 | } else { 287 | min2i = pos2; 288 | pos2++; 289 | } 290 | count[vocab_size + a] = count[min1i] + count[min2i]; 291 | parent_node[min1i] = vocab_size + a; 292 | parent_node[min2i] = vocab_size + a; 293 | binary[min2i] = 1; 294 | } 295 | // Now assign binary code to each vocabulary word 296 | for (a = 0; a < vocab_size; a++) { 297 | b = a; 298 | i = 0; 299 | while (1) { 300 | code[i] = binary[b]; 301 | point[i] = b; 302 | i++; 303 | b = parent_node[b]; 304 | if (b == vocab_size * 2 - 2) break; 305 | } 306 | vocab[a].codelen = i; 307 | vocab[a].point[0] = vocab_size - 2; 308 | for (b = 0; b < i; b++) { 309 | vocab[a].code[i - b - 1] = code[b]; 310 | vocab[a].point[i - b] = point[b] - vocab_size; 311 | } 312 | } 313 | free(count); 314 | free(binary); 315 | free(parent_node); 316 | } 317 | 318 | void LearnVocabFromTrainFile() { 319 | char word[MAX_STRING]; 320 | FILE *fin; 321 | long long a, i; 322 | for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; 323 | fin = fopen(train_file, "rb"); 324 | if (fin == NULL) { 325 | printf("ERROR: training data file not found!\n"); 326 | exit(1); 327 | } 328 | vocab_size = 0; 329 | AddWordToVocab((char *)""); 330 | int startOfLine = 1; 331 | while (1) { 332 | ReadWord(word, fin); 333 | if (feof(fin)) break; 334 | if (startOfLine) { 335 | ReadWord(word, fin); 336 | startOfLine = 0; 337 | } 338 | if(isEndOfSentence(word)){ 339 | startOfLine = 1; 340 | } 341 | train_words++; 342 | if ((debug_mode > 1) && (train_words % 100000 == 0)) { 343 | printf("%lldK%c", train_words / 1000, 13); 344 | fflush(stdout); 345 | } 346 | i = SearchVocab(word); 347 | if (i == -1) { 348 | a = AddWordToVocab(word); 349 | vocab[a].cn = 1; 350 | } else vocab[i].cn++; 351 | if (vocab_size > vocab_hash_size * 0.7) ReduceVocab(); 352 | } 353 | SortVocab(); 354 | if (debug_mode > 0) { 355 | printf("Vocab size: %lld\n", vocab_size); 356 | printf("Words in train file: %lld\n", train_words); 357 | } 358 | file_size = ftell(fin); 359 | fclose(fin); 360 | } 361 | 362 | void SaveVocab() { 363 | long long i; 364 | FILE *fo = fopen(save_vocab_file, "wb"); 365 | for (i = 0; i < vocab_size; i++) fprintf(fo, "%s %lld\n", vocab[i].word, vocab[i].cn); 366 | fclose(fo); 367 | } 368 | 369 | void ReadVocab() { 370 | long long a, i = 0; 371 | char c; 372 | char word[MAX_STRING]; 373 | FILE *fin = fopen(read_vocab_file, "rb"); 374 | if (fin == NULL) { 375 | printf("Vocabulary file not found\n"); 376 | exit(1); 377 | } 378 | for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; 379 | vocab_size = 0; 380 | while (1) { 381 | ReadWord(word, fin); 382 | if (feof(fin)) break; 383 | a = AddWordToVocab(word); 384 | fscanf(fin, "%lld%c", &vocab[a].cn, &c); 385 | i++; 386 | } 387 | SortVocab(); 388 | if (debug_mode > 0) { 389 | printf("Vocab size: %lld\n", vocab_size); 390 | printf("Words in train file: %lld\n", train_words); 391 | } 392 | fin = fopen(train_file, "rb"); 393 | if (fin == NULL) { 394 | printf("ERROR: training data file not found!\n"); 395 | exit(1); 396 | } 397 | fseek(fin, 0, SEEK_END); 398 | file_size = ftell(fin); 399 | fclose(fin); 400 | } 401 | 402 | void InitClassUnigramTable() { 403 | long long a,c; 404 | printf("loading class unigrams \n"); 405 | FILE *fin = fopen(negative_classes_file, "rb"); 406 | if (fin == NULL) { 407 | printf("ERROR: class file not found!\n"); 408 | exit(1); 409 | } 410 | word_to_group = (int *)malloc(vocab_size * sizeof(int)); 411 | for(a = 0; a < vocab_size; a++) word_to_group[a] = -1; 412 | char class[MAX_STRING]; 413 | char prev_class[MAX_STRING]; 414 | prev_class[0] = 0; 415 | char word[MAX_STRING]; 416 | class_number = -1; 417 | while (1) { 418 | if (feof(fin)) break; 419 | ReadWord(class, fin); 420 | ReadWord(word, fin); 421 | int word_index = SearchVocab(word); 422 | if (word_index != -1){ 423 | if(strcmp(class, prev_class) != 0){ 424 | class_number++; 425 | strcpy(prev_class, class); 426 | } 427 | word_to_group[word_index] = class_number; 428 | } 429 | ReadWord(word, fin); 430 | } 431 | class_number++; 432 | fclose(fin); 433 | 434 | group_to_table = (int *)malloc(table_size * class_number * sizeof(int)); 435 | long long train_words_pow = 0; 436 | real d1, power = 0.75; 437 | 438 | for(c = 0; c < class_number; c++){ 439 | long long offset = c * table_size; 440 | train_words_pow = 0; 441 | for (a = 0; a < vocab_size; a++) if(word_to_group[a] == c) train_words_pow += pow(vocab[a].cn, power); 442 | int i = 0; 443 | while(word_to_group[i]!=c && i < vocab_size) i++; 444 | d1 = pow(vocab[i].cn, power) / (real)train_words_pow; 445 | for (a = 0; a < table_size; a++) { 446 | //printf("index %lld , word %d\n", a, i); 447 | group_to_table[offset + a] = i; 448 | if (a / (real)table_size > d1) { 449 | i++; 450 | while(word_to_group[i]!=c && i < vocab_size) i++; 451 | d1 += pow(vocab[i].cn, power) / (real)train_words_pow; 452 | } 453 | if (i >= vocab_size) while(word_to_group[i]!=c && i >= 0) i--; 454 | } 455 | } 456 | } 457 | 458 | void InitNet() { 459 | long long a, b; 460 | unsigned long long next_random = 1; 461 | window_layer_size = layer1_size*window*2; 462 | a = posix_memalign((void **)&syn0, 128, (long long)vocab_size * layer1_size * sizeof(real)); 463 | if (syn0 == NULL) {printf("Memory allocation failed\n"); exit(1);} 464 | 465 | if (hs) { 466 | a = posix_memalign((void **)&syn1, 128, (long long)vocab_size * layer1_size * sizeof(real)); 467 | if (syn1 == NULL) {printf("Memory allocation failed\n"); exit(1);} 468 | a = posix_memalign((void **)&syn1_window, 128, (long long)vocab_size * window_layer_size * sizeof(real)); 469 | if (syn1_window == NULL) {printf("Memory allocation failed\n"); exit(1);} 470 | a = posix_memalign((void **)&syn_hidden_word, 128, (long long)vocab_size * window_hidden_size * sizeof(real)); 471 | if (syn_hidden_word == NULL) {printf("Memory allocation failed\n"); exit(1);} 472 | 473 | for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) 474 | syn1[a * layer1_size + b] = 0; 475 | for (a = 0; a < vocab_size; a++) for (b = 0; b < window_layer_size; b++) 476 | syn1_window[a * window_layer_size + b] = 0; 477 | for (a = 0; a < vocab_size; a++) for (b = 0; b < window_hidden_size; b++) 478 | syn_hidden_word[a * window_hidden_size + b] = 0; 479 | } 480 | if (negative>0) { 481 | a = posix_memalign((void **)&syn1neg, 128, (long long)vocab_size * layer1_size * sizeof(real)); 482 | if (syn1neg == NULL) {printf("Memory allocation failed\n"); exit(1);} 483 | a = posix_memalign((void **)&syn1neg_window, 128, (long long)vocab_size * window_layer_size * sizeof(real)); 484 | if (syn1neg_window == NULL) {printf("Memory allocation failed\n"); exit(1);} 485 | a = posix_memalign((void **)&syn_hidden_word_neg, 128, (long long)vocab_size * window_hidden_size * sizeof(real)); 486 | if (syn_hidden_word_neg == NULL) {printf("Memory allocation failed\n"); exit(1);} 487 | 488 | for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) 489 | syn1neg[a * layer1_size + b] = 0; 490 | for (a = 0; a < vocab_size; a++) for (b = 0; b < window_layer_size; b++) 491 | syn1neg_window[a * window_layer_size + b] = 0; 492 | for (a = 0; a < vocab_size; a++) for (b = 0; b < window_hidden_size; b++) 493 | syn_hidden_word_neg[a * window_hidden_size + b] = 0; 494 | } 495 | if (nce>0) { 496 | a = posix_memalign((void **)&syn1nce, 128, (long long)vocab_size * layer1_size * sizeof(real)); 497 | if (syn1nce == NULL) {printf("Memory allocation failed\n"); exit(1);} 498 | a = posix_memalign((void **)&syn1nce_window, 128, (long long)vocab_size * window_layer_size * sizeof(real)); 499 | if (syn1nce_window == NULL) {printf("Memory allocation failed\n"); exit(1);} 500 | a = posix_memalign((void **)&syn_hidden_word_nce, 128, (long long)vocab_size * window_hidden_size * sizeof(real)); 501 | if (syn_hidden_word_nce == NULL) {printf("Memory allocation failed\n"); exit(1);} 502 | 503 | for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) 504 | syn1nce[a * layer1_size + b] = 0; 505 | for (a = 0; a < vocab_size; a++) for (b = 0; b < window_layer_size; b++) 506 | syn1nce_window[a * window_layer_size + b] = 0; 507 | for (a = 0; a < vocab_size; a++) for (b = 0; b < window_hidden_size; b++) 508 | syn_hidden_word_nce[a * window_hidden_size + b] = 0; 509 | } 510 | for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) { 511 | next_random = next_random * (unsigned long long)25214903917 + 11; 512 | syn0[a * layer1_size + b] = (((next_random & 0xFFFF) / (real)65536) - 0.5) / layer1_size; 513 | } 514 | 515 | a = posix_memalign((void **)&syn_window_hidden, 128, window_hidden_size * window_layer_size * sizeof(real)); 516 | if (syn_window_hidden == NULL) {printf("Memory allocation failed\n"); exit(1);} 517 | for (a = 0; a < window_hidden_size * window_layer_size; a++){ 518 | next_random = next_random * (unsigned long long)25214903917 + 11; 519 | syn_window_hidden[a] = (((next_random & 0xFFFF) / (real)65536) - 0.5) / (window_hidden_size*window_layer_size); 520 | } 521 | 522 | CreateBinaryTree(); 523 | } 524 | 525 | long long findStartOfLine(char* file, long long start){ 526 | char word[MAX_STRING]; 527 | if(start == 0) return 0; 528 | while(start != 0){ 529 | FILE*fi = fopen(file, "rb"); 530 | fseek(fi, start, SEEK_SET); 531 | ReadWord(word, fi); 532 | if(isEndOfSentence(word)){ 533 | fclose(fi); 534 | return start+1; 535 | } 536 | fclose(fi); 537 | start--; 538 | } 539 | return 0; 540 | } 541 | 542 | void *TrainModelThread(void *id) { 543 | char word_str[MAX_STRING]; 544 | long long a, b, d, cw, word, last_word, sentence_length = 0, sentence_position = 0; 545 | long long word_count = 0, last_word_count = 0, sen[MAX_SENTENCE_LENGTH + 1]; 546 | long long l1, l2, c, target, label, local_iter = iter; 547 | unsigned long long next_random = (long long)id; 548 | real f, g; 549 | clock_t now; 550 | int input_len_1 = layer1_size; 551 | int window_offset = -1; 552 | float currentWeight = 0; 553 | if(type == 2 || type == 4){ 554 | input_len_1=window_layer_size; 555 | } 556 | real *neu1 = (real *)calloc(input_len_1, sizeof(real)); 557 | real *neu1e = (real *)calloc(input_len_1, sizeof(real)); 558 | 559 | int input_len_2 = 0; 560 | if(type == 4){ 561 | input_len_2 = window_hidden_size; 562 | } 563 | real *neu2 = (real *)calloc(input_len_2, sizeof(real)); 564 | real *neu2e = (real *)calloc(input_len_2, sizeof(real)); 565 | 566 | long long start_pos = findStartOfLine(train_file, file_size / (long long)num_threads * (long long)id); 567 | FILE *fi = fopen(train_file, "rb"); 568 | fseek(fi, start_pos, SEEK_SET); 569 | int startOfSentence = 1; 570 | int startEndOfLineIndex = SearchVocab(""); 571 | while (1) { 572 | if (word_count - last_word_count > 10000) { 573 | word_count_actual += word_count - last_word_count; 574 | last_word_count = word_count; 575 | if ((debug_mode > 1)) { 576 | now=clock(); 577 | printf("%cAlpha: %f Weight: %f Progress: %.2f%% Words/thread/sec: %.2fk ", 13, alpha, currentWeight, 578 | word_count_actual / (real)(iter * train_words + 1) * 100, 579 | word_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000)); 580 | fflush(stdout); 581 | } 582 | alpha = starting_alpha * (1 - word_count_actual / (real)(iter * train_words + 1)); 583 | if (alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001; 584 | } 585 | if (sentence_length == 0) { 586 | while (1) { 587 | if(startOfSentence){ 588 | ReadWord(word_str, fi); 589 | currentWeight = atof(word_str); 590 | startOfSentence = 0; 591 | continue; 592 | } 593 | word = ReadWordIndex(fi); 594 | if (word == startEndOfLineIndex){ 595 | startOfSentence = 1; 596 | } 597 | if (feof(fi)) break; 598 | if (word == -1) continue; 599 | word_count++; 600 | if (word == 0) break; 601 | // The subsampling randomly discards frequent words while keeping the ranking same 602 | if (sample > 0) { 603 | real ran = (sqrt(vocab[word].cn / (sample * train_words)) + 1) * (sample * train_words) / vocab[word].cn; 604 | next_random = next_random * (unsigned long long)25214903917 + 11; 605 | if (ran < (next_random & 0xFFFF) / (real)65536) continue; 606 | } 607 | sen[sentence_length] = word; 608 | sentence_length++; 609 | if (sentence_length >= MAX_SENTENCE_LENGTH) break; 610 | } 611 | sentence_position = 0; 612 | } 613 | if (feof(fi) || (word_count > train_words / num_threads)) { 614 | word_count_actual += word_count - last_word_count; 615 | local_iter--; 616 | if (local_iter == 0) break; 617 | word_count = 0; 618 | last_word_count = 0; 619 | sentence_length = 0; 620 | fseek(fi, start_pos, SEEK_SET); 621 | continue; 622 | } 623 | word = sen[sentence_position]; 624 | if (word == -1) continue; 625 | for (c = 0; c < input_len_1; c++) neu1[c] = 0; 626 | for (c = 0; c < input_len_1; c++) neu1e[c] = 0; 627 | for (c = 0; c < input_len_2; c++) neu2[c] = 0; 628 | for (c = 0; c < input_len_2; c++) neu2e[c] = 0; 629 | next_random = next_random * (unsigned long long)25214903917 + 11; 630 | b = next_random % window; 631 | if (type == 0) { //train the cbow architecture 632 | // in -> hidden 633 | cw = 0; 634 | for (a = b; a < window * 2 + 1 - b; a++) if (a != window) { 635 | c = sentence_position - window + a; 636 | if (c < 0) continue; 637 | if (c >= sentence_length) continue; 638 | last_word = sen[c]; 639 | if (last_word == -1) continue; 640 | for (c = 0; c < layer1_size; c++) neu1[c] += syn0[c + last_word * layer1_size]; 641 | cw++; 642 | } 643 | if (cw) { 644 | for (c = 0; c < layer1_size; c++) neu1[c] /= cw; 645 | if (hs) for (d = 0; d < vocab[word].codelen; d++) { 646 | f = 0; 647 | l2 = vocab[word].point[d] * layer1_size; 648 | // Propagate hidden -> output 649 | for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1[c + l2]; 650 | if (f <= -MAX_EXP) continue; 651 | else if (f >= MAX_EXP) continue; 652 | else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; 653 | // 'g' is the gradient multiplied by the learning rate 654 | g = (1 - vocab[word].code[d] - f) * alpha * currentWeight; 655 | // Propagate errors output -> hidden 656 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2]; 657 | // Learn weights hidden -> output 658 | for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * neu1[c]; 659 | if(cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1, c + l2); 660 | } 661 | // NEGATIVE SAMPLING 662 | if (negative > 0) for (d = 0; d < negative + 1; d++) { 663 | if (d == 0) { 664 | target = word; 665 | label = 1; 666 | } else { 667 | next_random = next_random * (unsigned long long)25214903917 + 11; 668 | if(word_to_group != NULL && word_to_group[word] != -1){ 669 | target = word; 670 | while(target == word) { 671 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 672 | next_random = next_random * (unsigned long long)25214903917 + 11; 673 | } 674 | //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); 675 | } 676 | else{ 677 | target = table[(next_random >> 16) % table_size]; 678 | } 679 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 680 | if (target == word) continue; 681 | label = 0; 682 | } 683 | l2 = target * layer1_size; 684 | f = 0; 685 | for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1neg[c + l2]; 686 | if (f > MAX_EXP) g = (label - 1) * alpha * currentWeight; 687 | else if (f < -MAX_EXP) g = (label - 0) * alpha * currentWeight; 688 | else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha * currentWeight; 689 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2]; 690 | for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * neu1[c]; 691 | if (cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1neg, c + l2); 692 | } 693 | // Noise Contrastive Estimation 694 | if (nce > 0) for (d = 0; d < nce + 1; d++) { 695 | if (d == 0) { 696 | target = word; 697 | label = 1; 698 | } else { 699 | next_random = next_random * (unsigned long long)25214903917 + 11; 700 | if(word_to_group != NULL && word_to_group[word] != -1){ 701 | target = word; 702 | while(target == word) { 703 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 704 | next_random = next_random * (unsigned long long)25214903917 + 11; 705 | } 706 | } 707 | else{ 708 | target = table[(next_random >> 16) % table_size]; 709 | } 710 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 711 | if (target == word) continue; 712 | label = 0; 713 | } 714 | l2 = target * layer1_size; 715 | f = 0; 716 | 717 | for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1nce[c + l2]; 718 | if (f > MAX_EXP) g = (label - 1) * alpha * currentWeight; 719 | else if (f < -MAX_EXP) g = (label - 0) * alpha * currentWeight; 720 | else { 721 | f = exp(f); 722 | g = (label - f/(noise_distribution[target]*nce + f)) * alpha * currentWeight; 723 | } 724 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1nce[c + l2]; 725 | for (c = 0; c < layer1_size; c++) syn1nce[c + l2] += g * neu1[c]; 726 | if(cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1nce,c + l2); 727 | } 728 | // hidden -> in 729 | for (a = b; a < window * 2 + 1 - b; a++) if (a != window) { 730 | c = sentence_position - window + a; 731 | if (c < 0) continue; 732 | if (c >= sentence_length) continue; 733 | last_word = sen[c]; 734 | if (last_word == -1) continue; 735 | for (c = 0; c < layer1_size; c++) syn0[c + last_word * layer1_size] += neu1e[c]; 736 | } 737 | } 738 | } else if(type==1) { //train skip-gram 739 | for (a = b; a < window * 2 + 1 - b; a++) if (a != window) { 740 | c = sentence_position - window + a; 741 | if (c < 0) continue; 742 | if (c >= sentence_length) continue; 743 | last_word = sen[c]; 744 | if (last_word == -1) continue; 745 | l1 = last_word * layer1_size; 746 | for (c = 0; c < layer1_size; c++) neu1e[c] = 0; 747 | // HIERARCHICAL SOFTMAX 748 | if (hs) for (d = 0; d < vocab[word].codelen; d++) { 749 | f = 0; 750 | l2 = vocab[word].point[d] * layer1_size; 751 | // Propagate hidden -> output 752 | for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1[c + l2]; 753 | if (f <= -MAX_EXP) continue; 754 | else if (f >= MAX_EXP) continue; 755 | else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; 756 | // 'g' is the gradient multiplied by the learning rate 757 | g = (1 - vocab[word].code[d] - f) * alpha * currentWeight; 758 | // Propagate errors output -> hidden 759 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2]; 760 | // Learn weights hidden -> output 761 | for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * syn0[c + l1]; 762 | if (cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1, c + l2); 763 | } 764 | // NEGATIVE SAMPLING 765 | if (negative > 0) for (d = 0; d < negative + 1; d++) { 766 | if (d == 0) { 767 | target = word; 768 | label = 1; 769 | } else { 770 | next_random = next_random * (unsigned long long)25214903917 + 11; 771 | if(word_to_group != NULL && word_to_group[word] != -1){ 772 | target = word; 773 | while(target == word) { 774 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 775 | next_random = next_random * (unsigned long long)25214903917 + 11; 776 | } 777 | //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); 778 | } 779 | else{ 780 | target = table[(next_random >> 16) % table_size]; 781 | } 782 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 783 | if (target == word) continue; 784 | label = 0; 785 | } 786 | l2 = target * layer1_size; 787 | f = 0; 788 | for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1neg[c + l2]; 789 | if (f > MAX_EXP) g = (label - 1) * alpha * currentWeight; 790 | else if (f < -MAX_EXP) g = (label - 0) * alpha * currentWeight; 791 | else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha * currentWeight; 792 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2]; 793 | for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * syn0[c + l1]; 794 | if (cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1neg, c + l2); 795 | } 796 | //Noise Contrastive Estimation 797 | if (nce > 0) for (d = 0; d < nce + 1; d++) { 798 | if (d == 0) { 799 | target = word; 800 | label = 1; 801 | } else { 802 | next_random = next_random * (unsigned long long)25214903917 + 11; 803 | if(word_to_group != NULL && word_to_group[word] != -1){ 804 | target = word; 805 | while(target == word) { 806 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 807 | next_random = next_random * (unsigned long long)25214903917 + 11; 808 | } 809 | //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); 810 | } 811 | else{ 812 | target = table[(next_random >> 16) % table_size]; 813 | } 814 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 815 | if (target == word) continue; 816 | label = 0; 817 | } 818 | l2 = target * layer1_size; 819 | f = 0; 820 | for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1nce[c + l2]; 821 | if (f > MAX_EXP) g = (label - 1) * alpha * currentWeight; 822 | else if (f < -MAX_EXP) g = (label - 0) * alpha * currentWeight; 823 | else { 824 | f = exp(f); 825 | g = (label - f/(noise_distribution[target]*nce + f)) * alpha * currentWeight; 826 | } 827 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1nce[c + l2]; 828 | for (c = 0; c < layer1_size; c++) syn1nce[c + l2] += g * syn0[c + l1]; 829 | if (cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1nce, c + l2); 830 | } 831 | // Learn weights input -> hidden 832 | for (c = 0; c < layer1_size; c++) syn0[c + l1] += neu1e[c]; 833 | } 834 | } 835 | else if(type == 2){ //train the cwindow architecture 836 | // in -> hidden 837 | cw = 0; 838 | for (a = 0; a < window * 2 + 1; a++) if (a != window) { 839 | c = sentence_position - window + a; 840 | if (c < 0) continue; 841 | if (c >= sentence_length) continue; 842 | last_word = sen[c]; 843 | if (last_word == -1) continue; 844 | window_offset = a*layer1_size; 845 | if (a > window) window_offset-=layer1_size; 846 | for (c = 0; c < layer1_size; c++) neu1[c+window_offset] += syn0[c + last_word * layer1_size]; 847 | cw++; 848 | } 849 | if (cw) { 850 | if (hs) for (d = 0; d < vocab[word].codelen; d++) { 851 | f = 0; 852 | l2 = vocab[word].point[d] * window_layer_size; 853 | // Propagate hidden -> output 854 | for (c = 0; c < window_layer_size; c++) f += neu1[c] * syn1_window[c + l2]; 855 | if (f <= -MAX_EXP) continue; 856 | else if (f >= MAX_EXP) continue; 857 | else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; 858 | // 'g' is the gradient multiplied by the learning rate 859 | g = (1 - vocab[word].code[d] - f) * alpha * currentWeight; 860 | // Propagate errors output -> hidden 861 | for (c = 0; c < window_layer_size; c++) neu1e[c] += g * syn1_window[c + l2]; 862 | // Learn weights hidden -> output 863 | for (c = 0; c < window_layer_size; c++) syn1_window[c + l2] += g * neu1[c]; 864 | if (cap == 1) for (c = 0; c < window_layer_size; c++) capParam(syn1_window, c + l2); 865 | } 866 | // NEGATIVE SAMPLING 867 | if (negative > 0) for (d = 0; d < negative + 1; d++) { 868 | if (d == 0) { 869 | target = word; 870 | label = 1; 871 | } else { 872 | next_random = next_random * (unsigned long long)25214903917 + 11; 873 | if(word_to_group != NULL && word_to_group[word] != -1){ 874 | target = word; 875 | while(target == word) { 876 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 877 | next_random = next_random * (unsigned long long)25214903917 + 11; 878 | } 879 | //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); 880 | } 881 | else{ 882 | target = table[(next_random >> 16) % table_size]; 883 | } 884 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 885 | if (target == word) continue; 886 | label = 0; 887 | } 888 | l2 = target * window_layer_size; 889 | f = 0; 890 | for (c = 0; c < window_layer_size; c++) f += neu1[c] * syn1neg_window[c + l2]; 891 | if (f > MAX_EXP) g = (label - 1) * alpha * currentWeight; 892 | else if (f < -MAX_EXP) g = (label - 0) * alpha * currentWeight; 893 | else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha * currentWeight; 894 | for (c = 0; c < window_layer_size; c++) neu1e[c] += g * syn1neg_window[c + l2]; 895 | for (c = 0; c < window_layer_size; c++) syn1neg_window[c + l2] += g * neu1[c]; 896 | if(cap == 1) for (c = 0; c < window_layer_size; c++) capParam(syn1neg_window, c + l2); 897 | } 898 | // Noise Contrastive Estimation 899 | if (nce > 0) for (d = 0; d < nce + 1; d++) { 900 | if (d == 0) { 901 | target = word; 902 | label = 1; 903 | } else { 904 | next_random = next_random * (unsigned long long)25214903917 + 11; 905 | if(word_to_group != NULL && word_to_group[word] != -1){ 906 | target = word; 907 | while(target == word) { 908 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 909 | next_random = next_random * (unsigned long long)25214903917 + 11; 910 | } 911 | //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); 912 | } 913 | else{ 914 | target = table[(next_random >> 16) % table_size]; 915 | } 916 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 917 | if (target == word) continue; 918 | label = 0; 919 | } 920 | l2 = target * window_layer_size; 921 | f = 0; 922 | for (c = 0; c < window_layer_size; c++) f += neu1[c] * syn1nce_window[c + l2]; 923 | if (f > MAX_EXP) g = (label - 1) * alpha * currentWeight; 924 | else if (f < -MAX_EXP) g = (label - 0) * alpha * currentWeight; 925 | else { 926 | f = exp(f); 927 | g = (label - f/(noise_distribution[target]*nce + f)) * alpha * currentWeight; 928 | } 929 | for (c = 0; c < window_layer_size; c++) neu1e[c] += g * syn1nce_window[c + l2]; 930 | for (c = 0; c < window_layer_size; c++) syn1nce_window[c + l2] += g * neu1[c]; 931 | if(cap == 1) for (c = 0; c < window_layer_size; c++) capParam(syn1nce_window, c + l2); 932 | } 933 | // hidden -> in 934 | for (a = 0; a < window * 2 + 1; a++) if (a != window) { 935 | c = sentence_position - window + a; 936 | if (c < 0) continue; 937 | if (c >= sentence_length) continue; 938 | last_word = sen[c]; 939 | if (last_word == -1) continue; 940 | window_offset = a * layer1_size; 941 | if(a > window) window_offset -= layer1_size; 942 | for (c = 0; c < layer1_size; c++) syn0[c + last_word * layer1_size] += neu1e[c + window_offset]; 943 | } 944 | } 945 | } 946 | else if (type == 3){ //train structured skip-gram 947 | for (a = 0; a < window * 2 + 1; a++) if (a != window) { 948 | c = sentence_position - window + a; 949 | if (c < 0) continue; 950 | if (c >= sentence_length) continue; 951 | last_word = sen[c]; 952 | if (last_word == -1) continue; 953 | l1 = last_word * layer1_size; 954 | window_offset = a * layer1_size; 955 | if(a > window) window_offset -= layer1_size; 956 | for (c = 0; c < layer1_size; c++) neu1e[c] = 0; 957 | // HIERARCHICAL SOFTMAX 958 | if (hs) for (d = 0; d < vocab[word].codelen; d++) { 959 | f = 0; 960 | l2 = vocab[word].point[d] * window_layer_size; 961 | // Propagate hidden -> output 962 | for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1_window[c + l2 + window_offset]; 963 | if (f <= -MAX_EXP) continue; 964 | else if (f >= MAX_EXP) continue; 965 | else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; 966 | // 'g' is the gradient multiplied by the learning rate 967 | g = (1 - vocab[word].code[d] - f) * alpha * currentWeight; 968 | // Propagate errors output -> hidden 969 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1_window[c + l2 + window_offset]; 970 | // Learn weights hidden -> output 971 | for (c = 0; c < layer1_size; c++) syn1[c + l2 + window_offset] += g * syn0[c + l1]; 972 | if(cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1, c + l2 + window_offset); 973 | } 974 | // NEGATIVE SAMPLING 975 | if (negative > 0) for (d = 0; d < negative + 1; d++) { 976 | if (d == 0) { 977 | target = word; 978 | label = 1; 979 | } else { 980 | next_random = next_random * (unsigned long long)25214903917 + 11; 981 | if(word_to_group != NULL && word_to_group[word] != -1){ 982 | target = word; 983 | while(target == word) { 984 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 985 | next_random = next_random * (unsigned long long)25214903917 + 11; 986 | } 987 | //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); 988 | } 989 | else{ 990 | target = table[(next_random >> 16) % table_size]; 991 | } 992 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 993 | if (target == word) continue; 994 | label = 0; 995 | } 996 | l2 = target * window_layer_size; 997 | f = 0; 998 | for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1neg_window[c + l2 + window_offset]; 999 | if (f > MAX_EXP) g = (label - 1) * alpha * currentWeight; 1000 | else if (f < -MAX_EXP) g = (label - 0) * alpha * currentWeight; 1001 | else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha * currentWeight; 1002 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg_window[c + l2 + window_offset]; 1003 | for (c = 0; c < layer1_size; c++) syn1neg_window[c + l2 + window_offset] += g * syn0[c + l1]; 1004 | if(cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1neg_window, c + l2 + window_offset); 1005 | } 1006 | // Noise Constrastive Estimation 1007 | if (nce > 0) for (d = 0; d < nce + 1; d++) { 1008 | if (d == 0) { 1009 | target = word; 1010 | label = 1; 1011 | } else { 1012 | next_random = next_random * (unsigned long long)25214903917 + 11; 1013 | if(word_to_group != NULL && word_to_group[word] != -1){ 1014 | target = word; 1015 | while(target == word) { 1016 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 1017 | next_random = next_random * (unsigned long long)25214903917 + 11; 1018 | } 1019 | //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); 1020 | } 1021 | else{ 1022 | target = table[(next_random >> 16) % table_size]; 1023 | } 1024 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 1025 | if (target == word) continue; 1026 | label = 0; 1027 | } 1028 | l2 = target * window_layer_size; 1029 | f = 0; 1030 | for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1nce_window[c + l2 + window_offset]; 1031 | if (f > MAX_EXP) g = (label - 1) * alpha * currentWeight; 1032 | else if (f < -MAX_EXP) g = (label - 0) * alpha * currentWeight; 1033 | else { 1034 | f = exp(f); 1035 | g = (label - f/(noise_distribution[target]*nce + f)) * alpha * currentWeight; 1036 | } 1037 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1nce_window[c + l2 + window_offset]; 1038 | for (c = 0; c < layer1_size; c++) syn1nce_window[c + l2 + window_offset] += g * syn0[c + l1]; 1039 | if (cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1nce_window, c + l2 + window_offset); 1040 | } 1041 | // Learn weights input -> hidden 1042 | for (c = 0; c < layer1_size; c++) {syn0[c + l1] += neu1e[c]; if(syn0[c + l1] > 50) syn0[c + l1] = 50; if(syn0[c + l1] < -50) syn0[c + l1] = -50;} 1043 | } 1044 | } 1045 | else if(type == 4){ //training senna 1046 | // in -> hidden 1047 | cw = 0; 1048 | for (a = 0; a < window * 2 + 1; a++) if (a != window) { 1049 | c = sentence_position - window + a; 1050 | if (c < 0) continue; 1051 | if (c >= sentence_length) continue; 1052 | last_word = sen[c]; 1053 | if (last_word == -1) continue; 1054 | window_offset = a*layer1_size; 1055 | if (a > window) window_offset-=layer1_size; 1056 | for (c = 0; c < layer1_size; c++) neu1[c+window_offset] += syn0[c + last_word * layer1_size]; 1057 | cw++; 1058 | } 1059 | if (cw) { 1060 | for (a = 0; a < window_hidden_size; a++){ 1061 | c = a*window_layer_size; 1062 | for(b = 0; b < window_layer_size; b++){ 1063 | neu2[a] += syn_window_hidden[c + b] * neu1[b]; 1064 | } 1065 | } 1066 | if (hs) for (d = 0; d < vocab[word].codelen; d++) { 1067 | f = 0; 1068 | l2 = vocab[word].point[d] * window_hidden_size; 1069 | // Propagate hidden -> output 1070 | for (c = 0; c < window_hidden_size; c++) f += hardTanh(neu2[c]) * syn_hidden_word[c + l2]; 1071 | if (f <= -MAX_EXP) continue; 1072 | else if (f >= MAX_EXP) continue; 1073 | else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; 1074 | // 'g' is the gradient multiplied by the learning rate 1075 | g = (1 - vocab[word].code[d] - f) * alpha * currentWeight; 1076 | // Propagate errors output -> hidden 1077 | for (c = 0; c < window_hidden_size; c++) neu2e[c] += dHardTanh(neu2[c],g) * g * syn_hidden_word[c + l2]; 1078 | // Learn weights hidden -> output 1079 | for (c = 0; c < window_hidden_size; c++) syn_hidden_word[c + l2] += dHardTanh(neu2[c],g) * g * neu2[c]; 1080 | } 1081 | // NEGATIVE SAMPLING 1082 | if (negative > 0) for (d = 0; d < negative + 1; d++) { 1083 | if (d == 0) { 1084 | target = word; 1085 | label = 1; 1086 | } else { 1087 | next_random = next_random * (unsigned long long)25214903917 + 11; 1088 | if(word_to_group != NULL && word_to_group[word] != -1){ 1089 | target = word; 1090 | while(target == word) { 1091 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 1092 | next_random = next_random * (unsigned long long)25214903917 + 11; 1093 | } 1094 | //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); 1095 | } 1096 | else{ 1097 | target = table[(next_random >> 16) % table_size]; 1098 | } 1099 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 1100 | if (target == word) continue; 1101 | label = 0; 1102 | } 1103 | l2 = target * window_hidden_size; 1104 | f = 0; 1105 | for (c = 0; c < window_hidden_size; c++) f += hardTanh(neu2[c]) * syn_hidden_word_neg[c + l2]; 1106 | if (f > MAX_EXP) g = (label - 1) * alpha * currentWeight / negative; 1107 | else if (f < -MAX_EXP) g = (label - 0) * alpha * currentWeight / negative; 1108 | else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha * currentWeight / negative; 1109 | for (c = 0; c < window_hidden_size; c++) neu2e[c] += dHardTanh(neu2[c],g) * g * syn_hidden_word_neg[c + l2]; 1110 | for (c = 0; c < window_hidden_size; c++) syn_hidden_word_neg[c + l2] += dHardTanh(neu2[c],g) * g * neu2[c]; 1111 | } 1112 | for (a = 0; a < window_hidden_size; a++) 1113 | for(b = 0; b < window_layer_size; b++) 1114 | neu1e[b] += neu2e[a] * syn_window_hidden[a*window_layer_size + b]; 1115 | for (a = 0; a < window_hidden_size; a++) 1116 | for(b = 0; b < window_layer_size; b++) 1117 | syn_window_hidden[a*window_layer_size + b] += neu2e[a] * neu1[b]; 1118 | // hidden -> in 1119 | for (a = 0; a < window * 2 + 1; a++) if (a != window) { 1120 | c = sentence_position - window + a; 1121 | if (c < 0) continue; 1122 | if (c >= sentence_length) continue; 1123 | last_word = sen[c]; 1124 | if (last_word == -1) continue; 1125 | window_offset = a * layer1_size; 1126 | if(a > window) window_offset -= layer1_size; 1127 | for (c = 0; c < layer1_size; c++) syn0[c + last_word * layer1_size] += neu1e[c + window_offset]; 1128 | } 1129 | } 1130 | } 1131 | else{ 1132 | printf("unknown type %i", type); 1133 | exit(0); 1134 | } 1135 | sentence_position++; 1136 | if (sentence_position >= sentence_length) { 1137 | sentence_length = 0; 1138 | continue; 1139 | } 1140 | } 1141 | fclose(fi); 1142 | free(neu1); 1143 | free(neu1e); 1144 | pthread_exit(NULL); 1145 | } 1146 | 1147 | void TrainModel() { 1148 | long a, b, c, d; 1149 | FILE *fo; 1150 | pthread_t *pt = (pthread_t *)malloc(num_threads * sizeof(pthread_t)); 1151 | printf("Starting training using file %s\n", train_file); 1152 | starting_alpha = alpha; 1153 | if (read_vocab_file[0] != 0) ReadVocab(); else LearnVocabFromTrainFile(); 1154 | if (save_vocab_file[0] != 0) SaveVocab(); 1155 | if (output_file[0] == 0) return; 1156 | InitNet(); 1157 | if (negative > 0 || nce > 0) InitUnigramTable(); 1158 | if (negative_classes_file[0] != 0) InitClassUnigramTable(); 1159 | start = clock(); 1160 | for (a = 0; a < num_threads; a++) pthread_create(&pt[a], NULL, TrainModelThread, (void *)a); 1161 | for (a = 0; a < num_threads; a++) pthread_join(pt[a], NULL); 1162 | fo = fopen(output_file, "wb"); 1163 | if (classes == 0) { 1164 | // Save the word vectors 1165 | fprintf(fo, "%lld %lld\n", vocab_size, layer1_size); 1166 | for (a = 0; a < vocab_size; a++) { 1167 | fprintf(fo, "%s ", vocab[a].word); 1168 | if (binary) for (b = 0; b < layer1_size; b++) fwrite(&syn0[a * layer1_size + b], sizeof(real), 1, fo); 1169 | else for (b = 0; b < layer1_size; b++) fprintf(fo, "%lf ", syn0[a * layer1_size + b]); 1170 | fprintf(fo, "\n"); 1171 | } 1172 | } else { 1173 | // Run K-means on the word vectors 1174 | int clcn = classes, iter = 10, closeid; 1175 | int *centcn = (int *)malloc(classes * sizeof(int)); 1176 | int *cl = (int *)calloc(vocab_size, sizeof(int)); 1177 | real closev, x; 1178 | real *cent = (real *)calloc(classes * layer1_size, sizeof(real)); 1179 | for (a = 0; a < vocab_size; a++) cl[a] = a % clcn; 1180 | for (a = 0; a < iter; a++) { 1181 | for (b = 0; b < clcn * layer1_size; b++) cent[b] = 0; 1182 | for (b = 0; b < clcn; b++) centcn[b] = 1; 1183 | for (c = 0; c < vocab_size; c++) { 1184 | for (d = 0; d < layer1_size; d++) cent[layer1_size * cl[c] + d] += syn0[c * layer1_size + d]; 1185 | centcn[cl[c]]++; 1186 | } 1187 | for (b = 0; b < clcn; b++) { 1188 | closev = 0; 1189 | for (c = 0; c < layer1_size; c++) { 1190 | cent[layer1_size * b + c] /= centcn[b]; 1191 | closev += cent[layer1_size * b + c] * cent[layer1_size * b + c]; 1192 | } 1193 | closev = sqrt(closev); 1194 | for (c = 0; c < layer1_size; c++) cent[layer1_size * b + c] /= closev; 1195 | } 1196 | for (c = 0; c < vocab_size; c++) { 1197 | closev = -10; 1198 | closeid = 0; 1199 | for (d = 0; d < clcn; d++) { 1200 | x = 0; 1201 | for (b = 0; b < layer1_size; b++) x += cent[layer1_size * d + b] * syn0[c * layer1_size + b]; 1202 | if (x > closev) { 1203 | closev = x; 1204 | closeid = d; 1205 | } 1206 | } 1207 | cl[c] = closeid; 1208 | } 1209 | } 1210 | // Save the K-means classes 1211 | for (a = 0; a < vocab_size; a++) fprintf(fo, "%s %d\n", vocab[a].word, cl[a]); 1212 | free(centcn); 1213 | free(cent); 1214 | free(cl); 1215 | } 1216 | fclose(fo); 1217 | } 1218 | 1219 | int ArgPos(char *str, int argc, char **argv) { 1220 | int a; 1221 | for (a = 1; a < argc; a++) if (!strcmp(str, argv[a])) { 1222 | if (a == argc - 1) { 1223 | printf("Argument missing for %s\n", str); 1224 | exit(1); 1225 | } 1226 | return a; 1227 | } 1228 | return -1; 1229 | } 1230 | 1231 | int main(int argc, char **argv) { 1232 | int i; 1233 | if (argc == 1) { 1234 | printf("WORD VECTOR estimation toolkit v 0.1c\n\n"); 1235 | printf("Options:\n"); 1236 | printf("Parameters for training:\n"); 1237 | printf("\t-train \n"); 1238 | printf("\t\tUse text data from to train the model\n"); 1239 | printf("\t-output \n"); 1240 | printf("\t\tUse to save the resulting word vectors / word clusters\n"); 1241 | printf("\t-size \n"); 1242 | printf("\t\tSet size of word vectors; default is 100\n"); 1243 | printf("\t-window \n"); 1244 | printf("\t\tSet max skip length between words; default is 5\n"); 1245 | printf("\t-sample \n"); 1246 | printf("\t\tSet threshold for occurrence of words. Those that appear with higher frequency in the training data\n"); 1247 | printf("\t\twill be randomly down-sampled; default is 1e-3, useful range is (0, 1e-5)\n"); 1248 | printf("\t-hs \n"); 1249 | printf("\t\tUse Hierarchical Softmax; default is 0 (not used)\n"); 1250 | printf("\t-negative \n"); 1251 | printf("\t\tNumber of negative examples; default is 5, common values are 3 - 10 (0 = not used)\n"); 1252 | printf("\t-negative-classes \n"); 1253 | printf("\t\tNegative classes to sample from\n"); 1254 | printf("\t-nce \n"); 1255 | printf("\t\tNumber of negative examples for nce; default is 0, common values are 3 - 10 (0 = not used)\n"); 1256 | printf("\t-threads \n"); 1257 | printf("\t\tUse threads (default 12)\n"); 1258 | printf("\t-iter \n"); 1259 | printf("\t\tRun more training iterations (default 5)\n"); 1260 | printf("\t-min-count \n"); 1261 | printf("\t\tThis will discard words that appear less than times; default is 5\n"); 1262 | printf("\t-alpha \n"); 1263 | printf("\t\tSet the starting learning rate; default is 0.025 for skip-gram and 0.05 for CBOW\n"); 1264 | printf("\t-classes \n"); 1265 | printf("\t\tOutput word classes rather than word vectors; default number of classes is 0 (vectors are written)\n"); 1266 | printf("\t-debug \n"); 1267 | printf("\t\tSet the debug mode (default = 2 = more info during training)\n"); 1268 | printf("\t-binary \n"); 1269 | printf("\t\tSave the resulting vectors in binary moded; default is 0 (off)\n"); 1270 | printf("\t-save-vocab \n"); 1271 | printf("\t\tThe vocabulary will be saved to \n"); 1272 | printf("\t-read-vocab \n"); 1273 | printf("\t\tThe vocabulary will be read from , not constructed from the training data\n"); 1274 | printf("\t-type \n"); 1275 | printf("\t\tType of embeddings (0 for cbow, 1 for skipngram, 2 for cwindow, 3 for structured skipngram, 4 for senna type)\n"); 1276 | printf("\t-cap \n"); 1277 | printf("\t\tlimit the parameter values to the range [-50, 50]; default is 0 (off)\n"); 1278 | printf("\nExamples:\n"); 1279 | printf("./word2vec -train data.txt -output vec.txt -size 200 -window 5 -sample 1e-4 -negative 5 -hs 0 -binary 0 -type 1 -iter 3\n\n"); 1280 | return 0; 1281 | } 1282 | output_file[0] = 0; 1283 | save_vocab_file[0] = 0; 1284 | read_vocab_file[0] = 0; 1285 | negative_classes_file[0] = 0; 1286 | if ((i = ArgPos((char *)"-size", argc, argv)) > 0) layer1_size = atoi(argv[i + 1]); 1287 | if ((i = ArgPos((char *)"-train", argc, argv)) > 0) strcpy(train_file, argv[i + 1]); 1288 | if ((i = ArgPos((char *)"-save-vocab", argc, argv)) > 0) strcpy(save_vocab_file, argv[i + 1]); 1289 | if ((i = ArgPos((char *)"-read-vocab", argc, argv)) > 0) strcpy(read_vocab_file, argv[i + 1]); 1290 | if ((i = ArgPos((char *)"-debug", argc, argv)) > 0) debug_mode = atoi(argv[i + 1]); 1291 | if ((i = ArgPos((char *)"-binary", argc, argv)) > 0) binary = atoi(argv[i + 1]); 1292 | if ((i = ArgPos((char *)"-type", argc, argv)) > 0) type = atoi(argv[i + 1]); 1293 | if ((i = ArgPos((char *)"-output", argc, argv)) > 0) strcpy(output_file, argv[i + 1]); 1294 | if ((i = ArgPos((char *)"-window", argc, argv)) > 0) window = atoi(argv[i + 1]); 1295 | if ((i = ArgPos((char *)"-sample", argc, argv)) > 0) sample = atof(argv[i + 1]); 1296 | if ((i = ArgPos((char *)"-hs", argc, argv)) > 0) hs = atoi(argv[i + 1]); 1297 | if ((i = ArgPos((char *)"-negative", argc, argv)) > 0) negative = atoi(argv[i + 1]); 1298 | if ((i = ArgPos((char *)"-negative-classes", argc, argv)) > 0) strcpy(negative_classes_file, argv[i + 1]); 1299 | if ((i = ArgPos((char *)"-nce", argc, argv)) > 0) nce = atoi(argv[i + 1]); 1300 | if ((i = ArgPos((char *)"-threads", argc, argv)) > 0) num_threads = atoi(argv[i + 1]); 1301 | if ((i = ArgPos((char *)"-iter", argc, argv)) > 0) iter = atoi(argv[i + 1]); 1302 | if ((i = ArgPos((char *)"-min-count", argc, argv)) > 0) min_count = atoi(argv[i + 1]); 1303 | if ((i = ArgPos((char *)"-classes", argc, argv)) > 0) classes = atoi(argv[i + 1]); 1304 | if ((i = ArgPos((char *)"-cap", argc, argv)) > 0) cap = atoi(argv[i + 1]); 1305 | if (type==0 || type==2 || type==4) alpha = 0.05; 1306 | if ((i = ArgPos((char *)"-alpha", argc, argv)) > 0) alpha = atof(argv[i + 1]); 1307 | vocab = (struct vocab_word *)calloc(vocab_max_size, sizeof(struct vocab_word)); 1308 | vocab_hash = (int *)calloc(vocab_hash_size, sizeof(int)); 1309 | expTable = (real *)malloc((EXP_TABLE_SIZE + 1) * sizeof(real)); 1310 | for (i = 0; i < EXP_TABLE_SIZE; i++) { 1311 | expTable[i] = exp((i / (real)EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table 1312 | expTable[i] = expTable[i] / (expTable[i] + 1); // Precompute f(x) = x / (x + 1) 1313 | } 1314 | TrainModel(); 1315 | return 0; 1316 | } 1317 | 1318 | -------------------------------------------------------------------------------- /word-analogy.c: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | const long long max_size = 2000; // max length of strings 21 | const long long N = 40; // number of closest words that will be shown 22 | const long long max_w = 50; // max length of vocabulary entries 23 | 24 | int main(int argc, char **argv) { 25 | FILE *f; 26 | char st1[max_size]; 27 | char bestw[N][max_size]; 28 | char file_name[max_size], st[100][max_size]; 29 | float dist, len, bestd[N], vec[max_size]; 30 | long long words, size, a, b, c, d, cn, bi[100]; 31 | float *M; 32 | char *vocab; 33 | if (argc < 2) { 34 | printf("Usage: ./word-analogy \nwhere FILE contains word projections in the BINARY FORMAT\n"); 35 | return 0; 36 | } 37 | strcpy(file_name, argv[1]); 38 | f = fopen(file_name, "rb"); 39 | if (f == NULL) { 40 | printf("Input file not found\n"); 41 | return -1; 42 | } 43 | fscanf(f, "%lld", &words); 44 | fscanf(f, "%lld", &size); 45 | vocab = (char *)malloc((long long)words * max_w * sizeof(char)); 46 | M = (float *)malloc((long long)words * (long long)size * sizeof(float)); 47 | if (M == NULL) { 48 | printf("Cannot allocate memory: %lld MB %lld %lld\n", (long long)words * size * sizeof(float) / 1048576, words, size); 49 | return -1; 50 | } 51 | for (b = 0; b < words; b++) { 52 | a = 0; 53 | while (1) { 54 | vocab[b * max_w + a] = fgetc(f); 55 | if (feof(f) || (vocab[b * max_w + a] == ' ')) break; 56 | if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++; 57 | } 58 | vocab[b * max_w + a] = 0; 59 | for (a = 0; a < size; a++) fread(&M[a + b * size], sizeof(float), 1, f); 60 | len = 0; 61 | for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size]; 62 | len = sqrt(len); 63 | for (a = 0; a < size; a++) M[a + b * size] /= len; 64 | } 65 | fclose(f); 66 | while (1) { 67 | for (a = 0; a < N; a++) bestd[a] = 0; 68 | for (a = 0; a < N; a++) bestw[a][0] = 0; 69 | printf("Enter three words (EXIT to break): "); 70 | a = 0; 71 | while (1) { 72 | st1[a] = fgetc(stdin); 73 | if ((st1[a] == '\n') || (a >= max_size - 1)) { 74 | st1[a] = 0; 75 | break; 76 | } 77 | a++; 78 | } 79 | if (!strcmp(st1, "EXIT")) break; 80 | cn = 0; 81 | b = 0; 82 | c = 0; 83 | while (1) { 84 | st[cn][b] = st1[c]; 85 | b++; 86 | c++; 87 | st[cn][b] = 0; 88 | if (st1[c] == 0) break; 89 | if (st1[c] == ' ') { 90 | cn++; 91 | b = 0; 92 | c++; 93 | } 94 | } 95 | cn++; 96 | if (cn < 3) { 97 | printf("Only %lld words were entered.. three words are needed at the input to perform the calculation\n", cn); 98 | continue; 99 | } 100 | for (a = 0; a < cn; a++) { 101 | for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st[a])) break; 102 | if (b == words) b = 0; 103 | bi[a] = b; 104 | printf("\nWord: %s Position in vocabulary: %lld\n", st[a], bi[a]); 105 | if (b == 0) { 106 | printf("Out of dictionary word!\n"); 107 | break; 108 | } 109 | } 110 | if (b == 0) continue; 111 | printf("\n Word Distance\n------------------------------------------------------------------------\n"); 112 | for (a = 0; a < size; a++) vec[a] = M[a + bi[1] * size] - M[a + bi[0] * size] + M[a + bi[2] * size]; 113 | len = 0; 114 | for (a = 0; a < size; a++) len += vec[a] * vec[a]; 115 | len = sqrt(len); 116 | for (a = 0; a < size; a++) vec[a] /= len; 117 | for (a = 0; a < N; a++) bestd[a] = 0; 118 | for (a = 0; a < N; a++) bestw[a][0] = 0; 119 | for (c = 0; c < words; c++) { 120 | if (c == bi[0]) continue; 121 | if (c == bi[1]) continue; 122 | if (c == bi[2]) continue; 123 | a = 0; 124 | for (b = 0; b < cn; b++) if (bi[b] == c) a = 1; 125 | if (a == 1) continue; 126 | dist = 0; 127 | for (a = 0; a < size; a++) dist += vec[a] * M[a + c * size]; 128 | for (a = 0; a < N; a++) { 129 | if (dist > bestd[a]) { 130 | for (d = N - 1; d > a; d--) { 131 | bestd[d] = bestd[d - 1]; 132 | strcpy(bestw[d], bestw[d - 1]); 133 | } 134 | bestd[a] = dist; 135 | strcpy(bestw[a], &vocab[c * max_w]); 136 | break; 137 | } 138 | } 139 | } 140 | for (a = 0; a < N; a++) printf("%50s\t\t%f\n", bestw[a], bestd[a]); 141 | } 142 | return 0; 143 | } 144 | -------------------------------------------------------------------------------- /word2phrase.c: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | #define MAX_STRING 60 22 | 23 | const int vocab_hash_size = 500000000; // Maximum 500M entries in the vocabulary 24 | 25 | typedef float real; // Precision of float numbers 26 | 27 | struct vocab_word { 28 | long long cn; 29 | char *word; 30 | }; 31 | 32 | char train_file[MAX_STRING], output_file[MAX_STRING]; 33 | struct vocab_word *vocab; 34 | int debug_mode = 2, min_count = 5, *vocab_hash, min_reduce = 1; 35 | long long vocab_max_size = 10000, vocab_size = 0; 36 | long long train_words = 0; 37 | real threshold = 100; 38 | 39 | unsigned long long next_random = 1; 40 | 41 | // Reads a single word from a file, assuming space + tab + EOL to be word boundaries 42 | void ReadWord(char *word, FILE *fin) { 43 | int a = 0, ch; 44 | while (!feof(fin)) { 45 | ch = fgetc(fin); 46 | if (ch == 13) continue; 47 | if ((ch == ' ') || (ch == '\t') || (ch == '\n')) { 48 | if (a > 0) { 49 | if (ch == '\n') ungetc(ch, fin); 50 | break; 51 | } 52 | if (ch == '\n') { 53 | strcpy(word, (char *)""); 54 | return; 55 | } else continue; 56 | } 57 | word[a] = ch; 58 | a++; 59 | if (a >= MAX_STRING - 1) a--; // Truncate too long words 60 | } 61 | word[a] = 0; 62 | } 63 | 64 | // Returns hash value of a word 65 | int GetWordHash(char *word) { 66 | unsigned long long a, hash = 1; 67 | for (a = 0; a < strlen(word); a++) hash = hash * 257 + word[a]; 68 | hash = hash % vocab_hash_size; 69 | return hash; 70 | } 71 | 72 | // Returns position of a word in the vocabulary; if the word is not found, returns -1 73 | int SearchVocab(char *word) { 74 | unsigned int hash = GetWordHash(word); 75 | while (1) { 76 | if (vocab_hash[hash] == -1) return -1; 77 | if (!strcmp(word, vocab[vocab_hash[hash]].word)) return vocab_hash[hash]; 78 | hash = (hash + 1) % vocab_hash_size; 79 | } 80 | return -1; 81 | } 82 | 83 | // Reads a word and returns its index in the vocabulary 84 | int ReadWordIndex(FILE *fin) { 85 | char word[MAX_STRING]; 86 | ReadWord(word, fin); 87 | if (feof(fin)) return -1; 88 | return SearchVocab(word); 89 | } 90 | 91 | // Adds a word to the vocabulary 92 | int AddWordToVocab(char *word) { 93 | unsigned int hash, length = strlen(word) + 1; 94 | if (length > MAX_STRING) length = MAX_STRING; 95 | vocab[vocab_size].word = (char *)calloc(length, sizeof(char)); 96 | strcpy(vocab[vocab_size].word, word); 97 | vocab[vocab_size].cn = 0; 98 | vocab_size++; 99 | // Reallocate memory if needed 100 | if (vocab_size + 2 >= vocab_max_size) { 101 | vocab_max_size += 10000; 102 | vocab=(struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(struct vocab_word)); 103 | } 104 | hash = GetWordHash(word); 105 | while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; 106 | vocab_hash[hash]=vocab_size - 1; 107 | return vocab_size - 1; 108 | } 109 | 110 | // Used later for sorting by word counts 111 | int VocabCompare(const void *a, const void *b) { 112 | return ((struct vocab_word *)b)->cn - ((struct vocab_word *)a)->cn; 113 | } 114 | 115 | // Sorts the vocabulary by frequency using word counts 116 | void SortVocab() { 117 | int a; 118 | unsigned int hash; 119 | // Sort the vocabulary and keep at the first position 120 | qsort(&vocab[1], vocab_size - 1, sizeof(struct vocab_word), VocabCompare); 121 | for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; 122 | for (a = 0; a < vocab_size; a++) { 123 | // Words occuring less than min_count times will be discarded from the vocab 124 | if (vocab[a].cn < min_count) { 125 | vocab_size--; 126 | free(vocab[vocab_size].word); 127 | } else { 128 | // Hash will be re-computed, as after the sorting it is not actual 129 | hash = GetWordHash(vocab[a].word); 130 | while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; 131 | vocab_hash[hash] = a; 132 | } 133 | } 134 | vocab = (struct vocab_word *)realloc(vocab, vocab_size * sizeof(struct vocab_word)); 135 | } 136 | 137 | // Reduces the vocabulary by removing infrequent tokens 138 | void ReduceVocab() { 139 | int a, b = 0; 140 | unsigned int hash; 141 | for (a = 0; a < vocab_size; a++) if (vocab[a].cn > min_reduce) { 142 | vocab[b].cn = vocab[a].cn; 143 | vocab[b].word = vocab[a].word; 144 | b++; 145 | } else free(vocab[a].word); 146 | vocab_size = b; 147 | for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; 148 | for (a = 0; a < vocab_size; a++) { 149 | // Hash will be re-computed, as it is not actual 150 | hash = GetWordHash(vocab[a].word); 151 | while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; 152 | vocab_hash[hash] = a; 153 | } 154 | fflush(stdout); 155 | min_reduce++; 156 | } 157 | 158 | void LearnVocabFromTrainFile() { 159 | char word[MAX_STRING], last_word[MAX_STRING], bigram_word[MAX_STRING * 2]; 160 | FILE *fin; 161 | long long a, i, start = 1; 162 | for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; 163 | fin = fopen(train_file, "rb"); 164 | if (fin == NULL) { 165 | printf("ERROR: training data file not found!\n"); 166 | exit(1); 167 | } 168 | vocab_size = 0; 169 | AddWordToVocab((char *)""); 170 | while (1) { 171 | ReadWord(word, fin); 172 | if (feof(fin)) break; 173 | if (!strcmp(word, "")) { 174 | start = 1; 175 | continue; 176 | } else start = 0; 177 | train_words++; 178 | if ((debug_mode > 1) && (train_words % 100000 == 0)) { 179 | printf("Words processed: %lldK Vocab size: %lldK %c", train_words / 1000, vocab_size / 1000, 13); 180 | fflush(stdout); 181 | } 182 | i = SearchVocab(word); 183 | if (i == -1) { 184 | a = AddWordToVocab(word); 185 | vocab[a].cn = 1; 186 | } else vocab[i].cn++; 187 | if (start) continue; 188 | sprintf(bigram_word, "%s_%s", last_word, word); 189 | bigram_word[MAX_STRING - 1] = 0; 190 | strcpy(last_word, word); 191 | i = SearchVocab(bigram_word); 192 | if (i == -1) { 193 | a = AddWordToVocab(bigram_word); 194 | vocab[a].cn = 1; 195 | } else vocab[i].cn++; 196 | if (vocab_size > vocab_hash_size * 0.7) ReduceVocab(); 197 | } 198 | SortVocab(); 199 | if (debug_mode > 0) { 200 | printf("\nVocab size (unigrams + bigrams): %lld\n", vocab_size); 201 | printf("Words in train file: %lld\n", train_words); 202 | } 203 | fclose(fin); 204 | } 205 | 206 | void TrainModel() { 207 | long long pa = 0, pb = 0, pab = 0, oov, i, li = -1, cn = 0; 208 | char word[MAX_STRING], last_word[MAX_STRING], bigram_word[MAX_STRING * 2]; 209 | real score; 210 | FILE *fo, *fin; 211 | printf("Starting training using file %s\n", train_file); 212 | LearnVocabFromTrainFile(); 213 | fin = fopen(train_file, "rb"); 214 | fo = fopen(output_file, "wb"); 215 | word[0] = 0; 216 | while (1) { 217 | strcpy(last_word, word); 218 | ReadWord(word, fin); 219 | if (feof(fin)) break; 220 | if (!strcmp(word, "")) { 221 | fprintf(fo, "\n"); 222 | continue; 223 | } 224 | cn++; 225 | if ((debug_mode > 1) && (cn % 100000 == 0)) { 226 | printf("Words written: %lldK%c", cn / 1000, 13); 227 | fflush(stdout); 228 | } 229 | oov = 0; 230 | i = SearchVocab(word); 231 | if (i == -1) oov = 1; else pb = vocab[i].cn; 232 | if (li == -1) oov = 1; 233 | li = i; 234 | sprintf(bigram_word, "%s_%s", last_word, word); 235 | bigram_word[MAX_STRING - 1] = 0; 236 | i = SearchVocab(bigram_word); 237 | if (i == -1) oov = 1; else pab = vocab[i].cn; 238 | if (pa < min_count) oov = 1; 239 | if (pb < min_count) oov = 1; 240 | if (oov) score = 0; else score = (pab - min_count) / (real)pa / (real)pb * (real)train_words; 241 | if (score > threshold) { 242 | fprintf(fo, "_%s", word); 243 | pb = 0; 244 | } else fprintf(fo, " %s", word); 245 | pa = pb; 246 | } 247 | fclose(fo); 248 | fclose(fin); 249 | } 250 | 251 | int ArgPos(char *str, int argc, char **argv) { 252 | int a; 253 | for (a = 1; a < argc; a++) if (!strcmp(str, argv[a])) { 254 | if (a == argc - 1) { 255 | printf("Argument missing for %s\n", str); 256 | exit(1); 257 | } 258 | return a; 259 | } 260 | return -1; 261 | } 262 | 263 | int main(int argc, char **argv) { 264 | int i; 265 | if (argc == 1) { 266 | printf("WORD2PHRASE tool v0.1a\n\n"); 267 | printf("Options:\n"); 268 | printf("Parameters for training:\n"); 269 | printf("\t-train \n"); 270 | printf("\t\tUse text data from to train the model\n"); 271 | printf("\t-output \n"); 272 | printf("\t\tUse to save the resulting word vectors / word clusters / phrases\n"); 273 | printf("\t-min-count \n"); 274 | printf("\t\tThis will discard words that appear less than times; default is 5\n"); 275 | printf("\t-threshold \n"); 276 | printf("\t\t The value represents threshold for forming the phrases (higher means less phrases); default 100\n"); 277 | printf("\t-debug \n"); 278 | printf("\t\tSet the debug mode (default = 2 = more info during training)\n"); 279 | printf("\nExamples:\n"); 280 | printf("./word2phrase -train text.txt -output phrases.txt -threshold 100 -debug 2\n\n"); 281 | return 0; 282 | } 283 | if ((i = ArgPos((char *)"-train", argc, argv)) > 0) strcpy(train_file, argv[i + 1]); 284 | if ((i = ArgPos((char *)"-debug", argc, argv)) > 0) debug_mode = atoi(argv[i + 1]); 285 | if ((i = ArgPos((char *)"-output", argc, argv)) > 0) strcpy(output_file, argv[i + 1]); 286 | if ((i = ArgPos((char *)"-min-count", argc, argv)) > 0) min_count = atoi(argv[i + 1]); 287 | if ((i = ArgPos((char *)"-threshold", argc, argv)) > 0) threshold = atof(argv[i + 1]); 288 | vocab = (struct vocab_word *)calloc(vocab_max_size, sizeof(struct vocab_word)); 289 | vocab_hash = (int *)calloc(vocab_hash_size, sizeof(int)); 290 | TrainModel(); 291 | return 0; 292 | } 293 | -------------------------------------------------------------------------------- /word2vec.c: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | #define MAX_STRING 100 22 | #define EXP_TABLE_SIZE 1000 23 | #define MAX_EXP 6 24 | #define MAX_SENTENCE_LENGTH 1000 25 | #define MAX_CODE_LENGTH 40 26 | 27 | const int vocab_hash_size = 30000000; // Maximum 30 * 0.7 = 21M words in the vocabulary 28 | 29 | typedef float real; // Precision of float numbers 30 | 31 | struct vocab_word { 32 | long long cn; 33 | int *point; 34 | char *word, *code, codelen; 35 | }; 36 | 37 | char train_file[MAX_STRING], output_file[MAX_STRING]; 38 | char save_vocab_file[MAX_STRING], read_vocab_file[MAX_STRING]; 39 | struct vocab_word *vocab; 40 | int binary = 0, type = 1, debug_mode = 2, window = 5, min_count = 5, num_threads = 12, min_reduce = 1; 41 | int *vocab_hash; 42 | long long vocab_max_size = 1000, vocab_size = 0, layer1_size = 100; 43 | long long train_words = 0, word_count_actual = 0, iter = 5, file_size = 0, classes = 0; 44 | real alpha = 0.025, starting_alpha, sample = 1e-3; 45 | real *syn0, *syn1, *syn1neg, *syn1nce, *expTable; 46 | clock_t start; 47 | 48 | real *syn1_window, *syn1neg_window, *syn1nce_window; 49 | int w_offset, window_layer_size; 50 | 51 | int window_hidden_size = 500; 52 | real *syn_window_hidden, *syn_hidden_word, *syn_hidden_word_neg, *syn_hidden_word_nce; 53 | 54 | int hs = 0, negative = 5; 55 | const int table_size = 1e8; 56 | int *table; 57 | 58 | //constrastive negative sampling 59 | char negative_classes_file[MAX_STRING]; 60 | int *word_to_group; 61 | int *group_to_table; //group_size*table_size 62 | int class_number; 63 | 64 | //nce 65 | real* noise_distribution; 66 | int nce = 0; 67 | 68 | //param caps 69 | real CAP_VALUE = 50; 70 | int cap = 0; 71 | 72 | void capParam(real* array, int index){ 73 | if(array[index] > CAP_VALUE) 74 | array[index] = CAP_VALUE; 75 | else if(array[index] < -CAP_VALUE) 76 | array[index] = -CAP_VALUE; 77 | } 78 | 79 | real hardTanh(real x){ 80 | if(x>=1){ 81 | return 1; 82 | } 83 | else if(x<=-1){ 84 | return -1; 85 | } 86 | else{ 87 | return x; 88 | } 89 | } 90 | 91 | real dHardTanh(real x, real g){ 92 | if(x > 1 && g > 0){ 93 | return 0; 94 | } 95 | if(x < -1 && g < 0){ 96 | return 0; 97 | } 98 | return 1; 99 | } 100 | 101 | void InitUnigramTable() { 102 | int a, i; 103 | long long train_words_pow = 0; 104 | real d1, power = 0.75; 105 | table = (int *)malloc(table_size * sizeof(int)); 106 | for (a = 0; a < vocab_size; a++) train_words_pow += pow(vocab[a].cn, power); 107 | i = 0; 108 | d1 = pow(vocab[i].cn, power) / (real)train_words_pow; 109 | for (a = 0; a < table_size; a++) { 110 | table[a] = i; 111 | if (a / (real)table_size > d1) { 112 | i++; 113 | d1 += pow(vocab[i].cn, power) / (real)train_words_pow; 114 | } 115 | if (i >= vocab_size) i = vocab_size - 1; 116 | } 117 | 118 | noise_distribution = (real *)calloc(vocab_size, sizeof(real)); 119 | for (a = 0; a < vocab_size; a++) noise_distribution[a] = pow(vocab[a].cn, power)/(real)train_words_pow; 120 | } 121 | 122 | // Reads a single word from a file, assuming space + tab + EOL to be word boundaries 123 | void ReadWord(char *word, FILE *fin) { 124 | int a = 0, ch; 125 | while (!feof(fin)) { 126 | ch = fgetc(fin); 127 | if (ch == 13) continue; 128 | if ((ch == ' ') || (ch == '\t') || (ch == '\n')) { 129 | if (a > 0) { 130 | if (ch == '\n') ungetc(ch, fin); 131 | break; 132 | } 133 | if (ch == '\n') { 134 | strcpy(word, (char *)""); 135 | return; 136 | } else continue; 137 | } 138 | word[a] = ch; 139 | a++; 140 | if (a >= MAX_STRING - 1) a--; // Truncate too long words 141 | } 142 | word[a] = 0; 143 | } 144 | 145 | // Returns hash value of a word 146 | int GetWordHash(char *word) { 147 | unsigned long long a, hash = 0; 148 | for (a = 0; a < strlen(word); a++) hash = hash * 257 + word[a]; 149 | hash = hash % vocab_hash_size; 150 | return hash; 151 | } 152 | 153 | // Returns position of a word in the vocabulary; if the word is not found, returns -1 154 | int SearchVocab(char *word) { 155 | unsigned int hash = GetWordHash(word); 156 | while (1) { 157 | if (vocab_hash[hash] == -1) return -1; 158 | if (!strcmp(word, vocab[vocab_hash[hash]].word)) return vocab_hash[hash]; 159 | hash = (hash + 1) % vocab_hash_size; 160 | } 161 | return -1; 162 | } 163 | 164 | // Reads a word and returns its index in the vocabulary 165 | int ReadWordIndex(FILE *fin) { 166 | char word[MAX_STRING]; 167 | ReadWord(word, fin); 168 | if (feof(fin)) return -1; 169 | return SearchVocab(word); 170 | } 171 | 172 | // Adds a word to the vocabulary 173 | int AddWordToVocab(char *word) { 174 | unsigned int hash, length = strlen(word) + 1; 175 | if (length > MAX_STRING) length = MAX_STRING; 176 | vocab[vocab_size].word = (char *)calloc(length, sizeof(char)); 177 | strcpy(vocab[vocab_size].word, word); 178 | vocab[vocab_size].cn = 0; 179 | vocab_size++; 180 | // Reallocate memory if needed 181 | if (vocab_size + 2 >= vocab_max_size) { 182 | vocab_max_size += 1000; 183 | vocab = (struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(struct vocab_word)); 184 | } 185 | hash = GetWordHash(word); 186 | while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; 187 | vocab_hash[hash] = vocab_size - 1; 188 | return vocab_size - 1; 189 | } 190 | 191 | // Used later for sorting by word counts 192 | int VocabCompare(const void *a, const void *b) { 193 | return ((struct vocab_word *)b)->cn - ((struct vocab_word *)a)->cn; 194 | } 195 | 196 | // Sorts the vocabulary by frequency using word counts 197 | void SortVocab() { 198 | int a, size; 199 | unsigned int hash; 200 | // Sort the vocabulary and keep at the first position 201 | qsort(&vocab[1], vocab_size - 1, sizeof(struct vocab_word), VocabCompare); 202 | for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; 203 | size = vocab_size; 204 | train_words = 0; 205 | for (a = 0; a < size; a++) { 206 | // Words occuring less than min_count times will be discarded from the vocab 207 | if ((vocab[a].cn < min_count) && (a != 0)) { 208 | vocab_size--; 209 | free(vocab[a].word); 210 | } else { 211 | // Hash will be re-computed, as after the sorting it is not actual 212 | hash=GetWordHash(vocab[a].word); 213 | while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; 214 | vocab_hash[hash] = a; 215 | train_words += vocab[a].cn; 216 | } 217 | } 218 | vocab = (struct vocab_word *)realloc(vocab, (vocab_size + 1) * sizeof(struct vocab_word)); 219 | // Allocate memory for the binary tree construction 220 | for (a = 0; a < vocab_size; a++) { 221 | vocab[a].code = (char *)calloc(MAX_CODE_LENGTH, sizeof(char)); 222 | vocab[a].point = (int *)calloc(MAX_CODE_LENGTH, sizeof(int)); 223 | } 224 | } 225 | 226 | // Reduces the vocabulary by removing infrequent tokens 227 | void ReduceVocab() { 228 | int a, b = 0; 229 | unsigned int hash; 230 | for (a = 0; a < vocab_size; a++) if (vocab[a].cn > min_reduce) { 231 | vocab[b].cn = vocab[a].cn; 232 | vocab[b].word = vocab[a].word; 233 | b++; 234 | } else free(vocab[a].word); 235 | vocab_size = b; 236 | for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; 237 | for (a = 0; a < vocab_size; a++) { 238 | // Hash will be re-computed, as it is not actual 239 | hash = GetWordHash(vocab[a].word); 240 | while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; 241 | vocab_hash[hash] = a; 242 | } 243 | fflush(stdout); 244 | min_reduce++; 245 | } 246 | 247 | // Create binary Huffman tree using the word counts 248 | // Frequent words will have short uniqe binary codes 249 | void CreateBinaryTree() { 250 | long long a, b, i, min1i, min2i, pos1, pos2, point[MAX_CODE_LENGTH]; 251 | char code[MAX_CODE_LENGTH]; 252 | long long *count = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); 253 | long long *binary = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); 254 | long long *parent_node = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); 255 | for (a = 0; a < vocab_size; a++) count[a] = vocab[a].cn; 256 | for (a = vocab_size; a < vocab_size * 2; a++) count[a] = 1e15; 257 | pos1 = vocab_size - 1; 258 | pos2 = vocab_size; 259 | // Following algorithm constructs the Huffman tree by adding one node at a time 260 | for (a = 0; a < vocab_size - 1; a++) { 261 | // First, find two smallest nodes 'min1, min2' 262 | if (pos1 >= 0) { 263 | if (count[pos1] < count[pos2]) { 264 | min1i = pos1; 265 | pos1--; 266 | } else { 267 | min1i = pos2; 268 | pos2++; 269 | } 270 | } else { 271 | min1i = pos2; 272 | pos2++; 273 | } 274 | if (pos1 >= 0) { 275 | if (count[pos1] < count[pos2]) { 276 | min2i = pos1; 277 | pos1--; 278 | } else { 279 | min2i = pos2; 280 | pos2++; 281 | } 282 | } else { 283 | min2i = pos2; 284 | pos2++; 285 | } 286 | count[vocab_size + a] = count[min1i] + count[min2i]; 287 | parent_node[min1i] = vocab_size + a; 288 | parent_node[min2i] = vocab_size + a; 289 | binary[min2i] = 1; 290 | } 291 | // Now assign binary code to each vocabulary word 292 | for (a = 0; a < vocab_size; a++) { 293 | b = a; 294 | i = 0; 295 | while (1) { 296 | code[i] = binary[b]; 297 | point[i] = b; 298 | i++; 299 | b = parent_node[b]; 300 | if (b == vocab_size * 2 - 2) break; 301 | } 302 | vocab[a].codelen = i; 303 | vocab[a].point[0] = vocab_size - 2; 304 | for (b = 0; b < i; b++) { 305 | vocab[a].code[i - b - 1] = code[b]; 306 | vocab[a].point[i - b] = point[b] - vocab_size; 307 | } 308 | } 309 | free(count); 310 | free(binary); 311 | free(parent_node); 312 | } 313 | 314 | void LearnVocabFromTrainFile() { 315 | char word[MAX_STRING]; 316 | FILE *fin; 317 | long long a, i; 318 | for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; 319 | fin = fopen(train_file, "rb"); 320 | if (fin == NULL) { 321 | printf("ERROR: training data file not found!\n"); 322 | exit(1); 323 | } 324 | vocab_size = 0; 325 | AddWordToVocab((char *)""); 326 | while (1) { 327 | ReadWord(word, fin); 328 | if (feof(fin)) break; 329 | train_words++; 330 | if ((debug_mode > 1) && (train_words % 100000 == 0)) { 331 | printf("%lldK%c", train_words / 1000, 13); 332 | fflush(stdout); 333 | } 334 | i = SearchVocab(word); 335 | if (i == -1) { 336 | a = AddWordToVocab(word); 337 | vocab[a].cn = 1; 338 | } else vocab[i].cn++; 339 | if (vocab_size > vocab_hash_size * 0.7) ReduceVocab(); 340 | } 341 | SortVocab(); 342 | if (debug_mode > 0) { 343 | printf("Vocab size: %lld\n", vocab_size); 344 | printf("Words in train file: %lld\n", train_words); 345 | } 346 | file_size = ftell(fin); 347 | fclose(fin); 348 | } 349 | 350 | void SaveVocab() { 351 | long long i; 352 | FILE *fo = fopen(save_vocab_file, "wb"); 353 | for (i = 0; i < vocab_size; i++) fprintf(fo, "%s %lld\n", vocab[i].word, vocab[i].cn); 354 | fclose(fo); 355 | } 356 | 357 | void ReadVocab() { 358 | long long a, i = 0; 359 | char c; 360 | char word[MAX_STRING]; 361 | FILE *fin = fopen(read_vocab_file, "rb"); 362 | if (fin == NULL) { 363 | printf("Vocabulary file not found\n"); 364 | exit(1); 365 | } 366 | for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; 367 | vocab_size = 0; 368 | while (1) { 369 | ReadWord(word, fin); 370 | if (feof(fin)) break; 371 | a = AddWordToVocab(word); 372 | fscanf(fin, "%lld%c", &vocab[a].cn, &c); 373 | i++; 374 | } 375 | SortVocab(); 376 | if (debug_mode > 0) { 377 | printf("Vocab size: %lld\n", vocab_size); 378 | printf("Words in train file: %lld\n", train_words); 379 | } 380 | fin = fopen(train_file, "rb"); 381 | if (fin == NULL) { 382 | printf("ERROR: training data file not found!\n"); 383 | exit(1); 384 | } 385 | fseek(fin, 0, SEEK_END); 386 | file_size = ftell(fin); 387 | fclose(fin); 388 | } 389 | 390 | void InitClassUnigramTable() { 391 | long long a,c; 392 | printf("loading class unigrams \n"); 393 | FILE *fin = fopen(negative_classes_file, "rb"); 394 | if (fin == NULL) { 395 | printf("ERROR: class file not found!\n"); 396 | exit(1); 397 | } 398 | word_to_group = (int *)malloc(vocab_size * sizeof(int)); 399 | for(a = 0; a < vocab_size; a++) word_to_group[a] = -1; 400 | char class[MAX_STRING]; 401 | char prev_class[MAX_STRING]; 402 | prev_class[0] = 0; 403 | char word[MAX_STRING]; 404 | class_number = -1; 405 | while (1) { 406 | if (feof(fin)) break; 407 | ReadWord(class, fin); 408 | ReadWord(word, fin); 409 | int word_index = SearchVocab(word); 410 | if (word_index != -1){ 411 | if(strcmp(class, prev_class) != 0){ 412 | class_number++; 413 | strcpy(prev_class, class); 414 | } 415 | word_to_group[word_index] = class_number; 416 | } 417 | ReadWord(word, fin); 418 | } 419 | class_number++; 420 | fclose(fin); 421 | 422 | group_to_table = (int *)malloc(table_size * class_number * sizeof(int)); 423 | long long train_words_pow = 0; 424 | real d1, power = 0.75; 425 | 426 | for(c = 0; c < class_number; c++){ 427 | long long offset = c * table_size; 428 | train_words_pow = 0; 429 | for (a = 0; a < vocab_size; a++) if(word_to_group[a] == c) train_words_pow += pow(vocab[a].cn, power); 430 | int i = 0; 431 | while(word_to_group[i]!=c && i < vocab_size) i++; 432 | d1 = pow(vocab[i].cn, power) / (real)train_words_pow; 433 | for (a = 0; a < table_size; a++) { 434 | //printf("index %lld , word %d\n", a, i); 435 | group_to_table[offset + a] = i; 436 | if (a / (real)table_size > d1) { 437 | i++; 438 | while(word_to_group[i]!=c && i < vocab_size) i++; 439 | d1 += pow(vocab[i].cn, power) / (real)train_words_pow; 440 | } 441 | if (i >= vocab_size) while(word_to_group[i]!=c && i >= 0) i--; 442 | } 443 | } 444 | } 445 | 446 | void InitNet() { 447 | long long a, b; 448 | unsigned long long next_random = 1; 449 | window_layer_size = layer1_size*window*2; 450 | a = posix_memalign((void **)&syn0, 128, (long long)vocab_size * layer1_size * sizeof(real)); 451 | if (syn0 == NULL) {printf("Memory allocation failed\n"); exit(1);} 452 | 453 | if (hs) { 454 | a = posix_memalign((void **)&syn1, 128, (long long)vocab_size * layer1_size * sizeof(real)); 455 | if (syn1 == NULL) {printf("Memory allocation failed\n"); exit(1);} 456 | a = posix_memalign((void **)&syn1_window, 128, (long long)vocab_size * window_layer_size * sizeof(real)); 457 | if (syn1_window == NULL) {printf("Memory allocation failed\n"); exit(1);} 458 | a = posix_memalign((void **)&syn_hidden_word, 128, (long long)vocab_size * window_hidden_size * sizeof(real)); 459 | if (syn_hidden_word == NULL) {printf("Memory allocation failed\n"); exit(1);} 460 | 461 | for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) 462 | syn1[a * layer1_size + b] = 0; 463 | for (a = 0; a < vocab_size; a++) for (b = 0; b < window_layer_size; b++) 464 | syn1_window[a * window_layer_size + b] = 0; 465 | for (a = 0; a < vocab_size; a++) for (b = 0; b < window_hidden_size; b++) 466 | syn_hidden_word[a * window_hidden_size + b] = 0; 467 | } 468 | if (negative>0) { 469 | a = posix_memalign((void **)&syn1neg, 128, (long long)vocab_size * layer1_size * sizeof(real)); 470 | if (syn1neg == NULL) {printf("Memory allocation failed\n"); exit(1);} 471 | a = posix_memalign((void **)&syn1neg_window, 128, (long long)vocab_size * window_layer_size * sizeof(real)); 472 | if (syn1neg_window == NULL) {printf("Memory allocation failed\n"); exit(1);} 473 | a = posix_memalign((void **)&syn_hidden_word_neg, 128, (long long)vocab_size * window_hidden_size * sizeof(real)); 474 | if (syn_hidden_word_neg == NULL) {printf("Memory allocation failed\n"); exit(1);} 475 | 476 | for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) 477 | syn1neg[a * layer1_size + b] = 0; 478 | for (a = 0; a < vocab_size; a++) for (b = 0; b < window_layer_size; b++) 479 | syn1neg_window[a * window_layer_size + b] = 0; 480 | for (a = 0; a < vocab_size; a++) for (b = 0; b < window_hidden_size; b++) 481 | syn_hidden_word_neg[a * window_hidden_size + b] = 0; 482 | } 483 | if (nce>0) { 484 | a = posix_memalign((void **)&syn1nce, 128, (long long)vocab_size * layer1_size * sizeof(real)); 485 | if (syn1nce == NULL) {printf("Memory allocation failed\n"); exit(1);} 486 | a = posix_memalign((void **)&syn1nce_window, 128, (long long)vocab_size * window_layer_size * sizeof(real)); 487 | if (syn1nce_window == NULL) {printf("Memory allocation failed\n"); exit(1);} 488 | a = posix_memalign((void **)&syn_hidden_word_nce, 128, (long long)vocab_size * window_hidden_size * sizeof(real)); 489 | if (syn_hidden_word_nce == NULL) {printf("Memory allocation failed\n"); exit(1);} 490 | 491 | for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) 492 | syn1nce[a * layer1_size + b] = 0; 493 | for (a = 0; a < vocab_size; a++) for (b = 0; b < window_layer_size; b++) 494 | syn1nce_window[a * window_layer_size + b] = 0; 495 | for (a = 0; a < vocab_size; a++) for (b = 0; b < window_hidden_size; b++) 496 | syn_hidden_word_nce[a * window_hidden_size + b] = 0; 497 | } 498 | for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) { 499 | next_random = next_random * (unsigned long long)25214903917 + 11; 500 | syn0[a * layer1_size + b] = (((next_random & 0xFFFF) / (real)65536) - 0.5) / layer1_size; 501 | } 502 | 503 | a = posix_memalign((void **)&syn_window_hidden, 128, window_hidden_size * window_layer_size * sizeof(real)); 504 | if (syn_window_hidden == NULL) {printf("Memory allocation failed\n"); exit(1);} 505 | for (a = 0; a < window_hidden_size * window_layer_size; a++){ 506 | next_random = next_random * (unsigned long long)25214903917 + 11; 507 | syn_window_hidden[a] = (((next_random & 0xFFFF) / (real)65536) - 0.5) / (window_hidden_size*window_layer_size); 508 | } 509 | 510 | CreateBinaryTree(); 511 | } 512 | 513 | void *TrainModelThread(void *id) { 514 | long long a, b, d, cw, word, last_word, sentence_length = 0, sentence_position = 0; 515 | long long word_count = 0, last_word_count = 0, sen[MAX_SENTENCE_LENGTH + 1]; 516 | long long l1, l2, c, target, label, local_iter = iter; 517 | unsigned long long next_random = (long long)id; 518 | real f, g; 519 | clock_t now; 520 | int input_len_1 = layer1_size; 521 | int window_offset = -1; 522 | if(type == 2 || type == 4){ 523 | input_len_1=window_layer_size; 524 | } 525 | real *neu1 = (real *)calloc(input_len_1, sizeof(real)); 526 | real *neu1e = (real *)calloc(input_len_1, sizeof(real)); 527 | 528 | int input_len_2 = 0; 529 | if(type == 4){ 530 | input_len_2 = window_hidden_size; 531 | } 532 | real *neu2 = (real *)calloc(input_len_2, sizeof(real)); 533 | real *neu2e = (real *)calloc(input_len_2, sizeof(real)); 534 | 535 | FILE *fi = fopen(train_file, "rb"); 536 | fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET); 537 | while (1) { 538 | if (word_count - last_word_count > 10000) { 539 | word_count_actual += word_count - last_word_count; 540 | last_word_count = word_count; 541 | if ((debug_mode > 1)) { 542 | now=clock(); 543 | printf("%cAlpha: %f Progress: %.2f%% Words/thread/sec: %.2fk ", 13, alpha, 544 | word_count_actual / (real)(iter * train_words + 1) * 100, 545 | word_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000)); 546 | fflush(stdout); 547 | } 548 | alpha = starting_alpha * (1 - word_count_actual / (real)(iter * train_words + 1)); 549 | if (alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001; 550 | } 551 | if (sentence_length == 0) { 552 | while (1) { 553 | word = ReadWordIndex(fi); 554 | if (feof(fi)) break; 555 | if (word == -1) continue; 556 | word_count++; 557 | if (word == 0) break; 558 | // The subsampling randomly discards frequent words while keeping the ranking same 559 | if (sample > 0) { 560 | real ran = (sqrt(vocab[word].cn / (sample * train_words)) + 1) * (sample * train_words) / vocab[word].cn; 561 | next_random = next_random * (unsigned long long)25214903917 + 11; 562 | if (ran < (next_random & 0xFFFF) / (real)65536) continue; 563 | } 564 | sen[sentence_length] = word; 565 | sentence_length++; 566 | if (sentence_length >= MAX_SENTENCE_LENGTH) break; 567 | } 568 | sentence_position = 0; 569 | } 570 | if (feof(fi) || (word_count > train_words / num_threads)) { 571 | word_count_actual += word_count - last_word_count; 572 | local_iter--; 573 | if (local_iter == 0) break; 574 | word_count = 0; 575 | last_word_count = 0; 576 | sentence_length = 0; 577 | fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET); 578 | continue; 579 | } 580 | word = sen[sentence_position]; 581 | if (word == -1) continue; 582 | for (c = 0; c < input_len_1; c++) neu1[c] = 0; 583 | for (c = 0; c < input_len_1; c++) neu1e[c] = 0; 584 | for (c = 0; c < input_len_2; c++) neu2[c] = 0; 585 | for (c = 0; c < input_len_2; c++) neu2e[c] = 0; 586 | next_random = next_random * (unsigned long long)25214903917 + 11; 587 | b = next_random % window; 588 | if (type == 0) { //train the cbow architecture 589 | // in -> hidden 590 | cw = 0; 591 | for (a = b; a < window * 2 + 1 - b; a++) if (a != window) { 592 | c = sentence_position - window + a; 593 | if (c < 0) continue; 594 | if (c >= sentence_length) continue; 595 | last_word = sen[c]; 596 | if (last_word == -1) continue; 597 | for (c = 0; c < layer1_size; c++) neu1[c] += syn0[c + last_word * layer1_size]; 598 | cw++; 599 | } 600 | if (cw) { 601 | for (c = 0; c < layer1_size; c++) neu1[c] /= cw; 602 | if (hs) for (d = 0; d < vocab[word].codelen; d++) { 603 | f = 0; 604 | l2 = vocab[word].point[d] * layer1_size; 605 | // Propagate hidden -> output 606 | for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1[c + l2]; 607 | if (f <= -MAX_EXP) continue; 608 | else if (f >= MAX_EXP) continue; 609 | else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; 610 | // 'g' is the gradient multiplied by the learning rate 611 | g = (1 - vocab[word].code[d] - f) * alpha; 612 | // Propagate errors output -> hidden 613 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2]; 614 | // Learn weights hidden -> output 615 | for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * neu1[c]; 616 | if(cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1, c + l2); 617 | } 618 | // NEGATIVE SAMPLING 619 | if (negative > 0) for (d = 0; d < negative + 1; d++) { 620 | if (d == 0) { 621 | target = word; 622 | label = 1; 623 | } else { 624 | next_random = next_random * (unsigned long long)25214903917 + 11; 625 | if(word_to_group != NULL && word_to_group[word] != -1){ 626 | target = word; 627 | while(target == word) { 628 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 629 | next_random = next_random * (unsigned long long)25214903917 + 11; 630 | } 631 | //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); 632 | } 633 | else{ 634 | target = table[(next_random >> 16) % table_size]; 635 | } 636 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 637 | if (target == word) continue; 638 | label = 0; 639 | } 640 | l2 = target * layer1_size; 641 | f = 0; 642 | for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1neg[c + l2]; 643 | if (f > MAX_EXP) g = (label - 1) * alpha; 644 | else if (f < -MAX_EXP) g = (label - 0) * alpha; 645 | else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha; 646 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2]; 647 | for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * neu1[c]; 648 | if (cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1neg, c + l2); 649 | } 650 | // Noise Contrastive Estimation 651 | if (nce > 0) for (d = 0; d < nce + 1; d++) { 652 | if (d == 0) { 653 | target = word; 654 | label = 1; 655 | } else { 656 | next_random = next_random * (unsigned long long)25214903917 + 11; 657 | if(word_to_group != NULL && word_to_group[word] != -1){ 658 | target = word; 659 | while(target == word) { 660 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 661 | next_random = next_random * (unsigned long long)25214903917 + 11; 662 | } 663 | } 664 | else{ 665 | target = table[(next_random >> 16) % table_size]; 666 | } 667 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 668 | if (target == word) continue; 669 | label = 0; 670 | } 671 | l2 = target * layer1_size; 672 | f = 0; 673 | 674 | for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1nce[c + l2]; 675 | if (f > MAX_EXP) g = (label - 1) * alpha; 676 | else if (f < -MAX_EXP) g = (label - 0) * alpha; 677 | else { 678 | f = exp(f); 679 | g = (label - f/(noise_distribution[target]*nce + f)) * alpha; 680 | } 681 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1nce[c + l2]; 682 | for (c = 0; c < layer1_size; c++) syn1nce[c + l2] += g * neu1[c]; 683 | if(cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1nce,c + l2); 684 | } 685 | // hidden -> in 686 | for (a = b; a < window * 2 + 1 - b; a++) if (a != window) { 687 | c = sentence_position - window + a; 688 | if (c < 0) continue; 689 | if (c >= sentence_length) continue; 690 | last_word = sen[c]; 691 | if (last_word == -1) continue; 692 | for (c = 0; c < layer1_size; c++) syn0[c + last_word * layer1_size] += neu1e[c]; 693 | } 694 | } 695 | } else if(type==1) { //train skip-gram 696 | for (a = b; a < window * 2 + 1 - b; a++) if (a != window) { 697 | c = sentence_position - window + a; 698 | if (c < 0) continue; 699 | if (c >= sentence_length) continue; 700 | last_word = sen[c]; 701 | if (last_word == -1) continue; 702 | l1 = last_word * layer1_size; 703 | for (c = 0; c < layer1_size; c++) neu1e[c] = 0; 704 | // HIERARCHICAL SOFTMAX 705 | if (hs) for (d = 0; d < vocab[word].codelen; d++) { 706 | f = 0; 707 | l2 = vocab[word].point[d] * layer1_size; 708 | // Propagate hidden -> output 709 | for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1[c + l2]; 710 | if (f <= -MAX_EXP) continue; 711 | else if (f >= MAX_EXP) continue; 712 | else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; 713 | // 'g' is the gradient multiplied by the learning rate 714 | g = (1 - vocab[word].code[d] - f) * alpha; 715 | // Propagate errors output -> hidden 716 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2]; 717 | // Learn weights hidden -> output 718 | for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * syn0[c + l1]; 719 | if (cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1, c + l2); 720 | } 721 | // NEGATIVE SAMPLING 722 | if (negative > 0) for (d = 0; d < negative + 1; d++) { 723 | if (d == 0) { 724 | target = word; 725 | label = 1; 726 | } else { 727 | next_random = next_random * (unsigned long long)25214903917 + 11; 728 | if(word_to_group != NULL && word_to_group[word] != -1){ 729 | target = word; 730 | while(target == word) { 731 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 732 | next_random = next_random * (unsigned long long)25214903917 + 11; 733 | } 734 | //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); 735 | } 736 | else{ 737 | target = table[(next_random >> 16) % table_size]; 738 | } 739 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 740 | if (target == word) continue; 741 | label = 0; 742 | } 743 | l2 = target * layer1_size; 744 | f = 0; 745 | for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1neg[c + l2]; 746 | if (f > MAX_EXP) g = (label - 1) * alpha; 747 | else if (f < -MAX_EXP) g = (label - 0) * alpha; 748 | else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha; 749 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2]; 750 | for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * syn0[c + l1]; 751 | if (cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1neg, c + l2); 752 | } 753 | //Noise Contrastive Estimation 754 | if (nce > 0) for (d = 0; d < nce + 1; d++) { 755 | if (d == 0) { 756 | target = word; 757 | label = 1; 758 | } else { 759 | next_random = next_random * (unsigned long long)25214903917 + 11; 760 | if(word_to_group != NULL && word_to_group[word] != -1){ 761 | target = word; 762 | while(target == word) { 763 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 764 | next_random = next_random * (unsigned long long)25214903917 + 11; 765 | } 766 | //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); 767 | } 768 | else{ 769 | target = table[(next_random >> 16) % table_size]; 770 | } 771 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 772 | if (target == word) continue; 773 | label = 0; 774 | } 775 | l2 = target * layer1_size; 776 | f = 0; 777 | for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1nce[c + l2]; 778 | if (f > MAX_EXP) g = (label - 1) * alpha; 779 | else if (f < -MAX_EXP) g = (label - 0) * alpha; 780 | else { 781 | f = exp(f); 782 | g = (label - f/(noise_distribution[target]*nce + f)) * alpha; 783 | } 784 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1nce[c + l2]; 785 | for (c = 0; c < layer1_size; c++) syn1nce[c + l2] += g * syn0[c + l1]; 786 | if (cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1nce, c + l2); 787 | } 788 | // Learn weights input -> hidden 789 | for (c = 0; c < layer1_size; c++) syn0[c + l1] += neu1e[c]; 790 | } 791 | } 792 | else if(type == 2){ //train the cwindow architecture 793 | // in -> hidden 794 | cw = 0; 795 | for (a = 0; a < window * 2 + 1; a++) if (a != window) { 796 | c = sentence_position - window + a; 797 | if (c < 0) continue; 798 | if (c >= sentence_length) continue; 799 | last_word = sen[c]; 800 | if (last_word == -1) continue; 801 | window_offset = a*layer1_size; 802 | if (a > window) window_offset-=layer1_size; 803 | for (c = 0; c < layer1_size; c++) neu1[c+window_offset] += syn0[c + last_word * layer1_size]; 804 | cw++; 805 | } 806 | if (cw) { 807 | if (hs) for (d = 0; d < vocab[word].codelen; d++) { 808 | f = 0; 809 | l2 = vocab[word].point[d] * window_layer_size; 810 | // Propagate hidden -> output 811 | for (c = 0; c < window_layer_size; c++) f += neu1[c] * syn1_window[c + l2]; 812 | if (f <= -MAX_EXP) continue; 813 | else if (f >= MAX_EXP) continue; 814 | else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; 815 | // 'g' is the gradient multiplied by the learning rate 816 | g = (1 - vocab[word].code[d] - f) * alpha; 817 | // Propagate errors output -> hidden 818 | for (c = 0; c < window_layer_size; c++) neu1e[c] += g * syn1_window[c + l2]; 819 | // Learn weights hidden -> output 820 | for (c = 0; c < window_layer_size; c++) syn1_window[c + l2] += g * neu1[c]; 821 | if (cap == 1) for (c = 0; c < window_layer_size; c++) capParam(syn1_window, c + l2); 822 | } 823 | // NEGATIVE SAMPLING 824 | if (negative > 0) for (d = 0; d < negative + 1; d++) { 825 | if (d == 0) { 826 | target = word; 827 | label = 1; 828 | } else { 829 | next_random = next_random * (unsigned long long)25214903917 + 11; 830 | if(word_to_group != NULL && word_to_group[word] != -1){ 831 | target = word; 832 | while(target == word) { 833 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 834 | next_random = next_random * (unsigned long long)25214903917 + 11; 835 | } 836 | //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); 837 | } 838 | else{ 839 | target = table[(next_random >> 16) % table_size]; 840 | } 841 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 842 | if (target == word) continue; 843 | label = 0; 844 | } 845 | l2 = target * window_layer_size; 846 | f = 0; 847 | for (c = 0; c < window_layer_size; c++) f += neu1[c] * syn1neg_window[c + l2]; 848 | if (f > MAX_EXP) g = (label - 1) * alpha; 849 | else if (f < -MAX_EXP) g = (label - 0) * alpha; 850 | else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha; 851 | for (c = 0; c < window_layer_size; c++) neu1e[c] += g * syn1neg_window[c + l2]; 852 | for (c = 0; c < window_layer_size; c++) syn1neg_window[c + l2] += g * neu1[c]; 853 | if(cap == 1) for (c = 0; c < window_layer_size; c++) capParam(syn1neg_window, c + l2); 854 | } 855 | // Noise Contrastive Estimation 856 | if (nce > 0) for (d = 0; d < nce + 1; d++) { 857 | if (d == 0) { 858 | target = word; 859 | label = 1; 860 | } else { 861 | next_random = next_random * (unsigned long long)25214903917 + 11; 862 | if(word_to_group != NULL && word_to_group[word] != -1){ 863 | target = word; 864 | while(target == word) { 865 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 866 | next_random = next_random * (unsigned long long)25214903917 + 11; 867 | } 868 | //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); 869 | } 870 | else{ 871 | target = table[(next_random >> 16) % table_size]; 872 | } 873 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 874 | if (target == word) continue; 875 | label = 0; 876 | } 877 | l2 = target * window_layer_size; 878 | f = 0; 879 | for (c = 0; c < window_layer_size; c++) f += neu1[c] * syn1nce_window[c + l2]; 880 | if (f > MAX_EXP) g = (label - 1) * alpha; 881 | else if (f < -MAX_EXP) g = (label - 0) * alpha; 882 | else { 883 | f = exp(f); 884 | g = (label - f/(noise_distribution[target]*nce + f)) * alpha; 885 | } 886 | for (c = 0; c < window_layer_size; c++) neu1e[c] += g * syn1nce_window[c + l2]; 887 | for (c = 0; c < window_layer_size; c++) syn1nce_window[c + l2] += g * neu1[c]; 888 | if(cap == 1) for (c = 0; c < window_layer_size; c++) capParam(syn1nce_window, c + l2); 889 | } 890 | // hidden -> in 891 | for (a = 0; a < window * 2 + 1; a++) if (a != window) { 892 | c = sentence_position - window + a; 893 | if (c < 0) continue; 894 | if (c >= sentence_length) continue; 895 | last_word = sen[c]; 896 | if (last_word == -1) continue; 897 | window_offset = a * layer1_size; 898 | if(a > window) window_offset -= layer1_size; 899 | for (c = 0; c < layer1_size; c++) syn0[c + last_word * layer1_size] += neu1e[c + window_offset]; 900 | } 901 | } 902 | } 903 | else if (type == 3){ //train structured skip-gram 904 | for (a = 0; a < window * 2 + 1; a++) if (a != window) { 905 | c = sentence_position - window + a; 906 | if (c < 0) continue; 907 | if (c >= sentence_length) continue; 908 | last_word = sen[c]; 909 | if (last_word == -1) continue; 910 | l1 = last_word * layer1_size; 911 | window_offset = a * layer1_size; 912 | if(a > window) window_offset -= layer1_size; 913 | for (c = 0; c < layer1_size; c++) neu1e[c] = 0; 914 | // HIERARCHICAL SOFTMAX 915 | if (hs) for (d = 0; d < vocab[word].codelen; d++) { 916 | f = 0; 917 | l2 = vocab[word].point[d] * window_layer_size; 918 | // Propagate hidden -> output 919 | for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1_window[c + l2 + window_offset]; 920 | if (f <= -MAX_EXP) continue; 921 | else if (f >= MAX_EXP) continue; 922 | else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; 923 | // 'g' is the gradient multiplied by the learning rate 924 | g = (1 - vocab[word].code[d] - f) * alpha; 925 | // Propagate errors output -> hidden 926 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1_window[c + l2 + window_offset]; 927 | // Learn weights hidden -> output 928 | for (c = 0; c < layer1_size; c++) syn1_window[c + l2 + window_offset] += g * syn0[c + l1]; 929 | if(cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1, c + l2 + window_offset); 930 | } 931 | // NEGATIVE SAMPLING 932 | if (negative > 0) for (d = 0; d < negative + 1; d++) { 933 | if (d == 0) { 934 | target = word; 935 | label = 1; 936 | } else { 937 | next_random = next_random * (unsigned long long)25214903917 + 11; 938 | if(word_to_group != NULL && word_to_group[word] != -1){ 939 | target = word; 940 | while(target == word) { 941 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 942 | next_random = next_random * (unsigned long long)25214903917 + 11; 943 | } 944 | //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); 945 | } 946 | else{ 947 | target = table[(next_random >> 16) % table_size]; 948 | } 949 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 950 | if (target == word) continue; 951 | label = 0; 952 | } 953 | l2 = target * window_layer_size; 954 | f = 0; 955 | for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1neg_window[c + l2 + window_offset]; 956 | if (f > MAX_EXP) g = (label - 1) * alpha; 957 | else if (f < -MAX_EXP) g = (label - 0) * alpha; 958 | else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha; 959 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg_window[c + l2 + window_offset]; 960 | for (c = 0; c < layer1_size; c++) syn1neg_window[c + l2 + window_offset] += g * syn0[c + l1]; 961 | if(cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1neg_window, c + l2 + window_offset); 962 | } 963 | // Noise Constrastive Estimation 964 | if (nce > 0) for (d = 0; d < nce + 1; d++) { 965 | if (d == 0) { 966 | target = word; 967 | label = 1; 968 | } else { 969 | next_random = next_random * (unsigned long long)25214903917 + 11; 970 | if(word_to_group != NULL && word_to_group[word] != -1){ 971 | target = word; 972 | while(target == word) { 973 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 974 | next_random = next_random * (unsigned long long)25214903917 + 11; 975 | } 976 | //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); 977 | } 978 | else{ 979 | target = table[(next_random >> 16) % table_size]; 980 | } 981 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 982 | if (target == word) continue; 983 | label = 0; 984 | } 985 | l2 = target * window_layer_size; 986 | f = 0; 987 | for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1nce_window[c + l2 + window_offset]; 988 | if (f > MAX_EXP) g = (label - 1) * alpha; 989 | else if (f < -MAX_EXP) g = (label - 0) * alpha; 990 | else { 991 | f = exp(f); 992 | g = (label - f/(noise_distribution[target]*nce + f)) * alpha; 993 | } 994 | for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1nce_window[c + l2 + window_offset]; 995 | for (c = 0; c < layer1_size; c++) syn1nce_window[c + l2 + window_offset] += g * syn0[c + l1]; 996 | if (cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1nce_window, c + l2 + window_offset); 997 | } 998 | // Learn weights input -> hidden 999 | for (c = 0; c < layer1_size; c++) {syn0[c + l1] += neu1e[c]; if(syn0[c + l1] > 50) syn0[c + l1] = 50; if(syn0[c + l1] < -50) syn0[c + l1] = -50;} 1000 | } 1001 | } 1002 | else if(type == 4){ //training senna 1003 | // in -> hidden 1004 | cw = 0; 1005 | for (a = 0; a < window * 2 + 1; a++) if (a != window) { 1006 | c = sentence_position - window + a; 1007 | if (c < 0) continue; 1008 | if (c >= sentence_length) continue; 1009 | last_word = sen[c]; 1010 | if (last_word == -1) continue; 1011 | window_offset = a*layer1_size; 1012 | if (a > window) window_offset-=layer1_size; 1013 | for (c = 0; c < layer1_size; c++) neu1[c+window_offset] += syn0[c + last_word * layer1_size]; 1014 | cw++; 1015 | } 1016 | if (cw) { 1017 | for (a = 0; a < window_hidden_size; a++){ 1018 | c = a*window_layer_size; 1019 | for(b = 0; b < window_layer_size; b++){ 1020 | neu2[a] += syn_window_hidden[c + b] * neu1[b]; 1021 | } 1022 | } 1023 | if (hs) for (d = 0; d < vocab[word].codelen; d++) { 1024 | f = 0; 1025 | l2 = vocab[word].point[d] * window_hidden_size; 1026 | // Propagate hidden -> output 1027 | for (c = 0; c < window_hidden_size; c++) f += hardTanh(neu2[c]) * syn_hidden_word[c + l2]; 1028 | if (f <= -MAX_EXP) continue; 1029 | else if (f >= MAX_EXP) continue; 1030 | else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; 1031 | // 'g' is the gradient multiplied by the learning rate 1032 | g = (1 - vocab[word].code[d] - f) * alpha; 1033 | // Propagate errors output -> hidden 1034 | for (c = 0; c < window_hidden_size; c++) neu2e[c] += dHardTanh(neu2[c],g) * g * syn_hidden_word[c + l2]; 1035 | // Learn weights hidden -> output 1036 | for (c = 0; c < window_hidden_size; c++) syn_hidden_word[c + l2] += dHardTanh(neu2[c],g) * g * neu2[c]; 1037 | } 1038 | // NEGATIVE SAMPLING 1039 | if (negative > 0) for (d = 0; d < negative + 1; d++) { 1040 | if (d == 0) { 1041 | target = word; 1042 | label = 1; 1043 | } else { 1044 | next_random = next_random * (unsigned long long)25214903917 + 11; 1045 | if(word_to_group != NULL && word_to_group[word] != -1){ 1046 | target = word; 1047 | while(target == word) { 1048 | target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; 1049 | next_random = next_random * (unsigned long long)25214903917 + 11; 1050 | } 1051 | //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); 1052 | } 1053 | else{ 1054 | target = table[(next_random >> 16) % table_size]; 1055 | } 1056 | if (target == 0) target = next_random % (vocab_size - 1) + 1; 1057 | if (target == word) continue; 1058 | label = 0; 1059 | } 1060 | l2 = target * window_hidden_size; 1061 | f = 0; 1062 | for (c = 0; c < window_hidden_size; c++) f += hardTanh(neu2[c]) * syn_hidden_word_neg[c + l2]; 1063 | if (f > MAX_EXP) g = (label - 1) * alpha / negative; 1064 | else if (f < -MAX_EXP) g = (label - 0) * alpha / negative; 1065 | else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha / negative; 1066 | for (c = 0; c < window_hidden_size; c++) neu2e[c] += dHardTanh(neu2[c],g) * g * syn_hidden_word_neg[c + l2]; 1067 | for (c = 0; c < window_hidden_size; c++) syn_hidden_word_neg[c + l2] += dHardTanh(neu2[c],g) * g * neu2[c]; 1068 | } 1069 | for (a = 0; a < window_hidden_size; a++) 1070 | for(b = 0; b < window_layer_size; b++) 1071 | neu1e[b] += neu2e[a] * syn_window_hidden[a*window_layer_size + b]; 1072 | for (a = 0; a < window_hidden_size; a++) 1073 | for(b = 0; b < window_layer_size; b++) 1074 | syn_window_hidden[a*window_layer_size + b] += neu2e[a] * neu1[b]; 1075 | // hidden -> in 1076 | for (a = 0; a < window * 2 + 1; a++) if (a != window) { 1077 | c = sentence_position - window + a; 1078 | if (c < 0) continue; 1079 | if (c >= sentence_length) continue; 1080 | last_word = sen[c]; 1081 | if (last_word == -1) continue; 1082 | window_offset = a * layer1_size; 1083 | if(a > window) window_offset -= layer1_size; 1084 | for (c = 0; c < layer1_size; c++) syn0[c + last_word * layer1_size] += neu1e[c + window_offset]; 1085 | } 1086 | } 1087 | } 1088 | else{ 1089 | printf("unknown type %i", type); 1090 | exit(0); 1091 | } 1092 | sentence_position++; 1093 | if (sentence_position >= sentence_length) { 1094 | sentence_length = 0; 1095 | continue; 1096 | } 1097 | } 1098 | fclose(fi); 1099 | free(neu1); 1100 | free(neu1e); 1101 | pthread_exit(NULL); 1102 | } 1103 | 1104 | void TrainModel() { 1105 | long a, b, c, d; 1106 | FILE *fo; 1107 | pthread_t *pt = (pthread_t *)malloc(num_threads * sizeof(pthread_t)); 1108 | printf("Starting training using file %s\n", train_file); 1109 | starting_alpha = alpha; 1110 | if (read_vocab_file[0] != 0) ReadVocab(); else LearnVocabFromTrainFile(); 1111 | if (save_vocab_file[0] != 0) SaveVocab(); 1112 | if (output_file[0] == 0) return; 1113 | InitNet(); 1114 | if (negative > 0 || nce > 0) InitUnigramTable(); 1115 | if (negative_classes_file[0] != 0) InitClassUnigramTable(); 1116 | start = clock(); 1117 | for (a = 0; a < num_threads; a++) pthread_create(&pt[a], NULL, TrainModelThread, (void *)a); 1118 | for (a = 0; a < num_threads; a++) pthread_join(pt[a], NULL); 1119 | fo = fopen(output_file, "wb"); 1120 | if (classes == 0) { 1121 | // Save the word vectors 1122 | fprintf(fo, "%lld %lld\n", vocab_size, layer1_size); 1123 | for (a = 0; a < vocab_size; a++) { 1124 | fprintf(fo, "%s ", vocab[a].word); 1125 | if (binary) for (b = 0; b < layer1_size; b++) fwrite(&syn0[a * layer1_size + b], sizeof(real), 1, fo); 1126 | else for (b = 0; b < layer1_size; b++) fprintf(fo, "%lf ", syn0[a * layer1_size + b]); 1127 | fprintf(fo, "\n"); 1128 | } 1129 | } else { 1130 | // Run K-means on the word vectors 1131 | int clcn = classes, iter = 10, closeid; 1132 | int *centcn = (int *)malloc(classes * sizeof(int)); 1133 | int *cl = (int *)calloc(vocab_size, sizeof(int)); 1134 | real closev, x; 1135 | real *cent = (real *)calloc(classes * layer1_size, sizeof(real)); 1136 | for (a = 0; a < vocab_size; a++) cl[a] = a % clcn; 1137 | for (a = 0; a < iter; a++) { 1138 | for (b = 0; b < clcn * layer1_size; b++) cent[b] = 0; 1139 | for (b = 0; b < clcn; b++) centcn[b] = 1; 1140 | for (c = 0; c < vocab_size; c++) { 1141 | for (d = 0; d < layer1_size; d++) cent[layer1_size * cl[c] + d] += syn0[c * layer1_size + d]; 1142 | centcn[cl[c]]++; 1143 | } 1144 | for (b = 0; b < clcn; b++) { 1145 | closev = 0; 1146 | for (c = 0; c < layer1_size; c++) { 1147 | cent[layer1_size * b + c] /= centcn[b]; 1148 | closev += cent[layer1_size * b + c] * cent[layer1_size * b + c]; 1149 | } 1150 | closev = sqrt(closev); 1151 | for (c = 0; c < layer1_size; c++) cent[layer1_size * b + c] /= closev; 1152 | } 1153 | for (c = 0; c < vocab_size; c++) { 1154 | closev = -10; 1155 | closeid = 0; 1156 | for (d = 0; d < clcn; d++) { 1157 | x = 0; 1158 | for (b = 0; b < layer1_size; b++) x += cent[layer1_size * d + b] * syn0[c * layer1_size + b]; 1159 | if (x > closev) { 1160 | closev = x; 1161 | closeid = d; 1162 | } 1163 | } 1164 | cl[c] = closeid; 1165 | } 1166 | } 1167 | // Save the K-means classes 1168 | for (a = 0; a < vocab_size; a++) fprintf(fo, "%s %d\n", vocab[a].word, cl[a]); 1169 | free(centcn); 1170 | free(cent); 1171 | free(cl); 1172 | } 1173 | fclose(fo); 1174 | } 1175 | 1176 | int ArgPos(char *str, int argc, char **argv) { 1177 | int a; 1178 | for (a = 1; a < argc; a++) if (!strcmp(str, argv[a])) { 1179 | if (a == argc - 1) { 1180 | printf("Argument missing for %s\n", str); 1181 | exit(1); 1182 | } 1183 | return a; 1184 | } 1185 | return -1; 1186 | } 1187 | 1188 | int main(int argc, char **argv) { 1189 | int i; 1190 | if (argc == 1) { 1191 | printf("WORD VECTOR estimation toolkit v 0.1c\n\n"); 1192 | printf("Options:\n"); 1193 | printf("Parameters for training:\n"); 1194 | printf("\t-train \n"); 1195 | printf("\t\tUse text data from to train the model\n"); 1196 | printf("\t-output \n"); 1197 | printf("\t\tUse to save the resulting word vectors / word clusters\n"); 1198 | printf("\t-size \n"); 1199 | printf("\t\tSet size of word vectors; default is 100\n"); 1200 | printf("\t-window \n"); 1201 | printf("\t\tSet max skip length between words; default is 5\n"); 1202 | printf("\t-sample \n"); 1203 | printf("\t\tSet threshold for occurrence of words. Those that appear with higher frequency in the training data\n"); 1204 | printf("\t\twill be randomly down-sampled; default is 1e-3, useful range is (0, 1e-5)\n"); 1205 | printf("\t-hs \n"); 1206 | printf("\t\tUse Hierarchical Softmax; default is 0 (not used)\n"); 1207 | printf("\t-negative \n"); 1208 | printf("\t\tNumber of negative examples; default is 5, common values are 3 - 10 (0 = not used)\n"); 1209 | printf("\t-negative-classes \n"); 1210 | printf("\t\tNegative classes to sample from\n"); 1211 | printf("\t-nce \n"); 1212 | printf("\t\tNumber of negative examples for nce; default is 0, common values are 3 - 10 (0 = not used)\n"); 1213 | printf("\t-threads \n"); 1214 | printf("\t\tUse threads (default 12)\n"); 1215 | printf("\t-iter \n"); 1216 | printf("\t\tRun more training iterations (default 5)\n"); 1217 | printf("\t-min-count \n"); 1218 | printf("\t\tThis will discard words that appear less than times; default is 5\n"); 1219 | printf("\t-alpha \n"); 1220 | printf("\t\tSet the starting learning rate; default is 0.025 for skip-gram and 0.05 for CBOW\n"); 1221 | printf("\t-classes \n"); 1222 | printf("\t\tOutput word classes rather than word vectors; default number of classes is 0 (vectors are written)\n"); 1223 | printf("\t-debug \n"); 1224 | printf("\t\tSet the debug mode (default = 2 = more info during training)\n"); 1225 | printf("\t-binary \n"); 1226 | printf("\t\tSave the resulting vectors in binary moded; default is 0 (off)\n"); 1227 | printf("\t-save-vocab \n"); 1228 | printf("\t\tThe vocabulary will be saved to \n"); 1229 | printf("\t-read-vocab \n"); 1230 | printf("\t\tThe vocabulary will be read from , not constructed from the training data\n"); 1231 | printf("\t-type \n"); 1232 | printf("\t\tType of embeddings (0 for cbow, 1 for skipngram, 2 for cwindow, 3 for structured skipngram, 4 for senna type)\n"); 1233 | printf("\t-cap \n"); 1234 | printf("\t\tlimit the parameter values to the range [-50, 50]; default is 0 (off)\n"); 1235 | printf("\nExamples:\n"); 1236 | printf("./word2vec -train data.txt -output vec.txt -size 200 -window 5 -sample 1e-4 -negative 5 -hs 0 -binary 0 -type 1 -iter 3\n\n"); 1237 | return 0; 1238 | } 1239 | output_file[0] = 0; 1240 | save_vocab_file[0] = 0; 1241 | read_vocab_file[0] = 0; 1242 | negative_classes_file[0] = 0; 1243 | if ((i = ArgPos((char *)"-size", argc, argv)) > 0) layer1_size = atoi(argv[i + 1]); 1244 | if ((i = ArgPos((char *)"-train", argc, argv)) > 0) strcpy(train_file, argv[i + 1]); 1245 | if ((i = ArgPos((char *)"-save-vocab", argc, argv)) > 0) strcpy(save_vocab_file, argv[i + 1]); 1246 | if ((i = ArgPos((char *)"-read-vocab", argc, argv)) > 0) strcpy(read_vocab_file, argv[i + 1]); 1247 | if ((i = ArgPos((char *)"-debug", argc, argv)) > 0) debug_mode = atoi(argv[i + 1]); 1248 | if ((i = ArgPos((char *)"-binary", argc, argv)) > 0) binary = atoi(argv[i + 1]); 1249 | if ((i = ArgPos((char *)"-type", argc, argv)) > 0) type = atoi(argv[i + 1]); 1250 | if ((i = ArgPos((char *)"-output", argc, argv)) > 0) strcpy(output_file, argv[i + 1]); 1251 | if ((i = ArgPos((char *)"-window", argc, argv)) > 0) window = atoi(argv[i + 1]); 1252 | if ((i = ArgPos((char *)"-sample", argc, argv)) > 0) sample = atof(argv[i + 1]); 1253 | if ((i = ArgPos((char *)"-hs", argc, argv)) > 0) hs = atoi(argv[i + 1]); 1254 | if ((i = ArgPos((char *)"-negative", argc, argv)) > 0) negative = atoi(argv[i + 1]); 1255 | if ((i = ArgPos((char *)"-negative-classes", argc, argv)) > 0) strcpy(negative_classes_file, argv[i + 1]); 1256 | if ((i = ArgPos((char *)"-nce", argc, argv)) > 0) nce = atoi(argv[i + 1]); 1257 | if ((i = ArgPos((char *)"-threads", argc, argv)) > 0) num_threads = atoi(argv[i + 1]); 1258 | if ((i = ArgPos((char *)"-iter", argc, argv)) > 0) iter = atoi(argv[i + 1]); 1259 | if ((i = ArgPos((char *)"-min-count", argc, argv)) > 0) min_count = atoi(argv[i + 1]); 1260 | if ((i = ArgPos((char *)"-classes", argc, argv)) > 0) classes = atoi(argv[i + 1]); 1261 | if ((i = ArgPos((char *)"-cap", argc, argv)) > 0) cap = atoi(argv[i + 1]); 1262 | if (type==0 || type==2 || type==4) alpha = 0.05; 1263 | if ((i = ArgPos((char *)"-alpha", argc, argv)) > 0) alpha = atof(argv[i + 1]); 1264 | vocab = (struct vocab_word *)calloc(vocab_max_size, sizeof(struct vocab_word)); 1265 | vocab_hash = (int *)calloc(vocab_hash_size, sizeof(int)); 1266 | expTable = (real *)malloc((EXP_TABLE_SIZE + 1) * sizeof(real)); 1267 | for (i = 0; i < EXP_TABLE_SIZE; i++) { 1268 | expTable[i] = exp((i / (real)EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table 1269 | expTable[i] = expTable[i] / (expTable[i] + 1); // Precompute f(x) = x / (x + 1) 1270 | } 1271 | TrainModel(); 1272 | return 0; 1273 | } 1274 | 1275 | --------------------------------------------------------------------------------