blob: b515c6bdb1650717142d98cf9ef56a8331191250 [file] [log] [blame]
Marc Kupietzdc22b982015-10-09 09:19:34 +02001#!/usr/local/bin/perl
2use Inline C;
3use Mojolicious::Lite;
Marc Kupietzc4893362016-02-25 08:04:46 +01004use Mojo::JSON qw(decode_json encode_json to_json);
Marc Kupietz247500f2015-10-09 11:29:01 +02005use Encode qw(decode encode);
Marc Kupietza5b90152016-03-15 17:39:19 +01006use Getopt::Std;
Marc Kupietz7bc85fd2016-02-24 11:42:41 +01007use Mojo::Server::Daemon;
Marc Kupietzd4227392016-03-01 16:45:12 +01008plugin 'Log::Access';
Marc Kupietzdc22b982015-10-09 09:19:34 +02009
Marc Kupietza5b90152016-03-15 17:39:19 +010010our $opt_i = 0; # latin1-input?
11our $opt_l = undef;
12our $opt_p = 5676;
13
14getopt('il:p:');
15
Marc Kupietz2cb667e2016-03-10 09:44:12 +010016print STDERR $ARGV[1];
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010017# -cbow 1 -size 200 -window 8 -negative 25 -hs 0 -sample 1e-4 -threads 40 -binary 1 -iter 15
Marc Kupietza5b90152016-03-15 17:39:19 +010018if(!$ARGV[0]) {
19 init_net("vectors15.bin", ($opt_i? 1 : 0));
Marc Kupietz2cb667e2016-03-10 09:44:12 +010020} else {
Marc Kupietza5b90152016-03-15 17:39:19 +010021 init_net($ARGV[0], ($opt_i? 1 : 0));
Marc Kupietz2cb667e2016-03-10 09:44:12 +010022}
Marc Kupietzdc22b982015-10-09 09:19:34 +020023
Marc Kupietza5b90152016-03-15 17:39:19 +010024my $daemon = Mojo::Server::Daemon->new(
25 app => app,
26 listen => ['http://'.($opt_l ? $opt_l : '*').":$opt_p"]
27);
28
Marc Kupietzdc22b982015-10-09 09:19:34 +020029get '/' => sub {
30 my $c = shift;
31 my $word=$c->param('word');
Marc Kupietz44bee3c2016-02-25 16:26:29 +010032 my $no_nbs=$c->param('n') || 100;
33 my $no_iterations=$c->param('N') || 2000;
Marc Kupietzd4227392016-03-01 16:45:12 +010034 my $perplexity=$c->param('perplexity') || 20;
Marc Kupietzc4d62f82016-03-01 11:04:24 +010035 my $epsilon=$c->param('epsilon') || 5;
Marc Kupietzd7aea722016-03-02 11:59:12 +010036 my $som=$c->param('som') || 0;
Marc Kupietzd4227392016-03-01 16:45:12 +010037
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010038 my @lists;
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010039 if(defined($word) && $word !~ /^\s*$/) {
40 $c->inactivity_timeout(300);
Marc Kupietz44bee3c2016-02-25 16:26:29 +010041 $word =~ s/\s+/ /g;
42 for my $w (split(' *\| *', $word)) {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010043 $c->app->log->debug('Looking for neighbours of '.$w);
Marc Kupietza5b90152016-03-15 17:39:19 +010044 if($opt_i) {
45 push(@lists, get_neighbours(encode("iso-8859-1", $w), $no_nbs));
46 } else {
47 push(@lists, get_neighbours($w, $no_nbs));
48 }
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010049 }
Marc Kupietz247500f2015-10-09 11:29:01 +020050 }
Marc Kupietz000ad862016-02-26 14:59:12 +010051 $word =~ s/ *\| */ | /g;
Marc Kupietzd7aea722016-03-02 11:59:12 +010052 $c->render(template=>"index", word=>$word, no_nbs=>$no_nbs, no_iterations => $no_iterations, epsilon=> $epsilon, perplexity=> $perplexity, show_som=>$som, lists=> \@lists);
Marc Kupietzdc22b982015-10-09 09:19:34 +020053};
54
Marc Kupietza5b90152016-03-15 17:39:19 +010055$daemon->run; # app->start;
Marc Kupietzdc22b982015-10-09 09:19:34 +020056
57exit;
58
59__END__
60
61__C__
62#include <stdio.h>
63#include <string.h>
64#include <math.h>
65#include <malloc.h>
66#include <stdlib.h> //strlen
Marc Kupietzf0809762016-02-26 10:13:47 +010067#include <sys/mman.h>
Marc Kupietz000ad862016-02-26 14:59:12 +010068#include <pthread.h>
Marc Kupietzdc22b982015-10-09 09:19:34 +020069
70#define max_size 2000
71#define max_w 50
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010072#define MAX_NEIGHBOURS 1000
Marc Kupietz44bee3c2016-02-25 16:26:29 +010073#define MAX_WORDS -1
Marc Kupietz000ad862016-02-26 14:59:12 +010074#define MAX_THREADS 100
Marc Kupietzdc22b982015-10-09 09:19:34 +020075
76//the thread function
77void *connection_handler(void *);
Marc Kupietz000ad862016-02-26 14:59:12 +010078
79typedef struct {
80 long long *index;
81 float *dist;
82 unsigned int length;
83} knn;
84
85
86typedef struct {
87 char *token;
88 int N;
89 unsigned long from;
90 unsigned long upto;
91} knnpars;
92
Marc Kupietzdc22b982015-10-09 09:19:34 +020093float *M;
94char *vocab;
Marc Kupietz82b02672016-02-26 12:32:25 +010095long long words, size;
Marc Kupietz000ad862016-02-26 14:59:12 +010096int num_threads=20;
Marc Kupietza5b90152016-03-15 17:39:19 +010097int latin_enc=0;
Marc Kupietzdc22b982015-10-09 09:19:34 +020098
Marc Kupietza5b90152016-03-15 17:39:19 +010099int init_net(char *file_name, int latin) {
Marc Kupietz67c20282016-02-26 09:42:00 +0100100 FILE *f, *binvecs, *binwords;
Marc Kupietzf0809762016-02-26 10:13:47 +0100101 int binwords_fd, binvecs_fd;
Marc Kupietz82b02672016-02-26 12:32:25 +0100102 long long a, b, c, d, cn;
103 float len;
104
Marc Kupietz67c20282016-02-26 09:42:00 +0100105 char binvecs_fname[256], binwords_fname[256];
106 strcpy(binwords_fname, file_name);
107 strcat(binwords_fname, ".words");
108 strcpy(binvecs_fname, file_name);
109 strcat(binvecs_fname, ".vecs");
Marc Kupietzdc22b982015-10-09 09:19:34 +0200110
Marc Kupietza5b90152016-03-15 17:39:19 +0100111 latin_enc = latin;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200112 f = fopen(file_name, "rb");
113 if (f == NULL) {
114 printf("Input file %s not found\n", file_name);
115 return -1;
116 }
117 fscanf(f, "%lld", &words);
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100118 if(MAX_WORDS > 0 && words > MAX_WORDS) words = MAX_WORDS;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200119 fscanf(f, "%lld", &size);
Marc Kupietz2cb667e2016-03-10 09:44:12 +0100120 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) < 0 || (binwords_fd = open(binwords_fname, O_RDONLY)) < 0) {
121 printf("Converting %s to memory mappable structures\n", file_name);
Marc Kupietzf0809762016-02-26 10:13:47 +0100122 vocab = (char *)malloc((long long)words * max_w * sizeof(char));
123 M = (float *)malloc((long long)words * (long long)size * sizeof(float));
124 if (M == NULL) {
125 printf("Cannot allocate memory: %lld MB %lld %lld\n", (long long)words * size * sizeof(float) / 1048576, words, size);
126 return -1;
127 }
Marc Kupietz67c20282016-02-26 09:42:00 +0100128 for (b = 0; b < words; b++) {
129 a = 0;
130 while (1) {
131 vocab[b * max_w + a] = fgetc(f);
132 if (feof(f) || (vocab[b * max_w + a] == ' ')) break;
133 if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++;
134 }
135 vocab[b * max_w + a] = 0;
136 fread(&M[b * size], sizeof(float), size, f);
137 len = 0;
138 for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size];
139 len = sqrt(len);
140 for (a = 0; a < size; a++) M[a + b * size] /= len;
141 }
142 if( (binvecs = fopen(binvecs_fname, "wb")) != NULL && (binwords = fopen(binwords_fname, "wb")) != NULL) {
143 fwrite(M, sizeof(float), (long long)words * (long long)size, binvecs);
144 fclose(binvecs);
145 fwrite(vocab, sizeof(char), (long long)words * max_w, binwords);
146 fclose(binwords);
147 }
Marc Kupietz2cb667e2016-03-10 09:44:12 +0100148 }
149 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) >= 0 && (binwords_fd = open(binwords_fname, O_RDONLY)) >= 0) {
150 M = mmap(0, sizeof(float) * (long long)words * (long long)size, PROT_READ, MAP_SHARED, binvecs_fd, 0);
151 vocab = mmap(0, sizeof(char) * (long long)words * max_w, PROT_READ, MAP_SHARED, binwords_fd, 0);
152 if (M == MAP_FAILED || vocab == MAP_FAILED) {
153 close(binvecs_fd);
154 close(binwords_fd);
155 fprintf(stderr, "Cannot mmap %s or %s\n", binwords_fname, binvecs_fname);
156 exit(-1);
157 }
158 } else {
159 fprintf(stderr, "Cannot open %s or %s\n", binwords_fname, binvecs_fname);
160 exit(-1);
Marc Kupietz67c20282016-02-26 09:42:00 +0100161 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200162 fclose(f);
163 return 0;
164}
165
Marc Kupietz000ad862016-02-26 14:59:12 +0100166
167void *_get_neighbours(knnpars *pars) {
168 char *st1 = pars->token;
169 int N = pars->N;
170 unsigned long from = pars -> from;
171 unsigned long upto = pars -> upto;
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100172 char file_name[max_size], st[100][max_size], sep[100];
Marc Kupietz000ad862016-02-26 14:59:12 +0100173 float dist, len, *bestd, vec[max_size];
174 long long a, b, c, d, cn, bi[100], *besti;
Marc Kupietz82b02672016-02-26 12:32:25 +0100175 char ch;
Marc Kupietz000ad862016-02-26 14:59:12 +0100176 knn *nbs = NULL;
Marc Kupietz34a3ee92016-02-27 22:43:16 +0100177
Marc Kupietz000ad862016-02-26 14:59:12 +0100178 besti = malloc(N * sizeof(long long));
179 bestd = malloc(N * sizeof(float));
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100180
Marc Kupietz000ad862016-02-26 14:59:12 +0100181 float worstbest=-1;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200182
183 for (a = 0; a < N; a++) bestd[a] = 0;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200184 a = 0;
185 cn = 0;
186 b = 0;
187 c = 0;
188 while (1) {
189 st[cn][b] = st1[c];
190 b++;
191 c++;
192 st[cn][b] = 0;
193 if (st1[c] == 0) break;
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100194 if (st1[c] == ' ' || st1[c] == '-') {
195 sep[cn++] = st1[c];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200196 b = 0;
197 c++;
198 }
199 }
200 cn++;
201 for (a = 0; a < cn; a++) {
Marc Kupietz34a3ee92016-02-27 22:43:16 +0100202 for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st[a])) break;
203 if (b == words) b = -1;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200204 bi[a] = b;
Marc Kupietze8da3062016-02-25 08:37:53 +0100205 fprintf(stderr, "Word: \"%s\" Position in vocabulary: %lld\n", st[a], bi[a]);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200206 if (b == -1) {
Marc Kupietze8da3062016-02-25 08:37:53 +0100207 fprintf(stderr, "Out of dictionary word!\n");
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100208 cn--;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200209 break;
210 }
211 }
Marc Kupietz000ad862016-02-26 14:59:12 +0100212 if (b == -1) {
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100213 N = 0;
214 goto end;
215 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200216 for (a = 0; a < size; a++) vec[a] = 0;
217 for (b = 0; b < cn; b++) {
218 if (bi[b] == -1) continue;
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100219 if(b>0 && sep[b-1] == '-')
220 for (a = 0; a < size; a++) vec[a] -= M[a + bi[b] * size];
221 else
222 for (a = 0; a < size; a++) vec[a] += M[a + bi[b] * size];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200223 }
224 len = 0;
225 for (a = 0; a < size; a++) len += vec[a] * vec[a];
226 len = sqrt(len);
227 for (a = 0; a < size; a++) vec[a] /= len;
228 for (a = 0; a < N; a++) bestd[a] = -1;
Marc Kupietz000ad862016-02-26 14:59:12 +0100229 for (c = from; c < upto; c++) {
Marc Kupietzdc22b982015-10-09 09:19:34 +0200230 a = 0;
Marc Kupietz34020dc2016-02-25 08:44:19 +0100231// do not skip taget word
Marc Kupietze8da3062016-02-25 08:37:53 +0100232// for (b = 0; b < cn; b++) if (bi[b] == c) a = 1;
233// if (a == 1) continue;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200234 dist = 0;
235 for (a = 0; a < size; a++) dist += vec[a] * M[a + c * size];
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100236 if(dist > worstbest) {
237 for (a = 0; a < N; a++) {
238 if (dist > bestd[a]) {
239 for (d = N - 1; d > a; d--) {
240 bestd[d] = bestd[d - 1];
241 besti[d] = besti[d - 1];
242 }
243 bestd[a] = dist;
244 besti[a] = c;
245 break;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200246 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200247 }
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100248 worstbest = bestd[N-1];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200249 }
250 }
Marc Kupietz34020dc2016-02-25 08:44:19 +0100251
Marc Kupietz000ad862016-02-26 14:59:12 +0100252 nbs = malloc(sizeof(knn));
253 nbs->index = besti;
254 nbs->dist = bestd;
255 nbs->length = N;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100256end:
Marc Kupietz000ad862016-02-26 14:59:12 +0100257 pthread_exit(nbs);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200258}
259
Marc Kupietz000ad862016-02-26 14:59:12 +0100260SV *get_neighbours(char *st1, int N) {
261 float bestd[MAX_NEIGHBOURS], vec[max_size];
262 long long besti[MAX_NEIGHBOURS], a, b, c, d, slice;
263 char *bestw[MAX_NEIGHBOURS];
264 knn *nbs[MAX_THREADS];
265 knnpars pars[MAX_THREADS];
266 pthread_t *pt = (pthread_t *)malloc(num_threads * sizeof(pthread_t));
267 AV* array = newAV();
268
269 if(N>MAX_NEIGHBOURS) N=MAX_NEIGHBOURS;
270
271 slice = words / num_threads;
272
273 for(a=0; a < num_threads; a++) {
274 pars[a].token = st1;
275 pars[a].N = N;
276 pars[a].from = a*slice;
277 pars[a].upto = ((a+1)*slice > words? words:(a+1)*slice);
278 pthread_create(&pt[a], NULL, _get_neighbours, (void *) &pars[a]);
279 }
280 for (a = 0; a < num_threads; a++) pthread_join(pt[a], &nbs[a]);
281
282 if(!nbs[0])
283 goto end;
284
285 for(b=0; b < N; b++) {
286 besti[b] = nbs[0]->index[b];
287 bestd[b] = nbs[0]->dist[b];
288 }
289
290 for(a=1; a < num_threads; a++) {
291 for(b=0; b < N; b++) {
292 for(c=0; c < N; c++) {
293 if(nbs[a]->dist[b] > bestd[c]) {
294 for(d=N-1; d>c; d--) {
295 bestd[d] = bestd[d-1];
296 besti[d] = besti[d-1];
297 }
298 besti[c] = nbs[a]->index[b];
299 bestd[c] = nbs[a]->dist[b];
300 break;
301 }
302 }
303 }
304 }
305
306 if(nbs) {
307 for (a = 0; a < N; a++) {
308 bestw[a] = (char *)malloc(max_size * sizeof(char));
309 }
310 for (a = 0; a < N; a++) {
311 strcpy(bestw[a], &vocab[besti[a] * max_w]);
312 HV* hash = newHV();
Marc Kupietza5b90152016-03-15 17:39:19 +0100313 SV* word = newSVpvf(bestw[a], 0);
314 if(latin_enc == 0) SvUTF8_on(word);
315 hv_store(hash, "word", strlen("word"), word , 0);
Marc Kupietz000ad862016-02-26 14:59:12 +0100316 hv_store(hash, "dist", strlen("dist"), newSVnv(bestd[a]), 0);
317 hv_store(hash, "rank", strlen("rank"), newSVuv(besti[a]), 0);
318 AV *vector = newAV();
319 for (b = 0; b < size; b++) {
320 av_push(vector, newSVnv(M[b + besti[a] * size]));
321 }
322 hv_store(hash, "vector", strlen("vector"), newRV_noinc((SV*)vector), 0);
323 av_push(array, newRV_noinc((SV*)hash));
324 }
325 }
326end:
327 return newRV_noinc((SV*)array);
328}
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100329
Marc Kupietzdc22b982015-10-09 09:19:34 +0200330__DATA__
331
332@@ index.html.ep
333<!DOCTYPE html>
334<html>
Marc Kupietzc4893362016-02-25 08:04:46 +0100335<head>
336 <title>DeReKo-Word-Vector-Distances</title>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100337 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
Marc Kupietzc4893362016-02-25 08:04:46 +0100338 <script src="http://code.jquery.com/jquery-latest.min.js"></script>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100339 <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
340 <script>
341 $(function() {
Marc Kupietz5f780672016-02-25 17:15:54 +0100342 $( document ).tooltip({
343 content: function() {
344 return $(this).attr('title');
345 }}
346 )
347 })
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100348 </script>
Marc Kupietzc4893362016-02-25 08:04:46 +0100349 <script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
350 <script src="http://klinux10/word2vec/tsne.js"></script>
Marc Kupietzd7aea722016-03-02 11:59:12 +0100351 <script src="http://klinux10/word2vec/som.js"></script>
Marc Kupietzc5990da2016-02-26 08:47:12 +0100352 <script src="http://klinux10/word2vec/labeler.js"></script>
Marc Kupietzc4893362016-02-25 08:04:46 +0100353<style>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100354body, input {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100355 font-family: Arial, sans-serif;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100356 font-size: 11pt;
357}
358
359.ui-tooltip-content {
360 font-size: 9pt;
361 colour: #222222;
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100362}
Marc Kupietz5f780672016-02-25 17:15:54 +0100363
364svg > .ui-tooltip-content {
Marc Kupietzb1029362016-02-27 21:38:55 +0100365 font-size: 8pt;
Marc Kupietz5f780672016-02-25 17:15:54 +0100366 colour: #222222;
367}
368
Marc Kupietzc4893362016-02-25 08:04:46 +0100369#wrapper {
370 width: 100%;
371// border: 1px solid red;
372 overflow: hidden; /* will contain if #first is longer than #second */
373}
374#first {
Marc Kupietzb1029362016-02-27 21:38:55 +0100375 margin-right: 20px;
376 float: left;
377 // border: 1px solid green;
Marc Kupietzc4893362016-02-25 08:04:46 +0100378}
379#second {
380 border: 1px solid #333;
381 overflow: hidden; /* if you don't want #second to wrap below #first */
382}
Marc Kupietzd7aea722016-03-02 11:59:12 +0100383#som2 svg {
384 border: 1px solid #333;
385}
386
Marc Kupietz4aa62172016-02-25 10:39:27 +0100387#cost {
Marc Kupietzb1029362016-02-27 21:38:55 +0100388 font-size: 8pt;
389 color: #222222;
390 margin-top: 4px;
Marc Kupietzd7aea722016-03-02 11:59:12 +0100391 margin-bottom: 12px;
Marc Kupietz4aa62172016-02-25 10:39:27 +0100392}
Marc Kupietzd7aea722016-03-02 11:59:12 +0100393
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100394#sominfo1, #sominfo {
Marc Kupietzd7aea722016-03-02 11:59:12 +0100395 font-size: 8pt;
396 color: #222222;
397 margin-top: 0px;
398}
399
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100400#somcolor1, #somcolor2, #somcolor3 {
401 display: inline-block;
402 height: 10px;
403 width: 10px;
404}
405
Marc Kupietzd7aea722016-03-02 11:59:12 +0100406#third {
407 border: 1px solid #333;
408}
409
Marc Kupietzc4893362016-02-25 08:04:46 +0100410</style>
411<script>
412
Marc Kupietzc4d62f82016-03-01 11:04:24 +0100413var opt = {epsilon: <%= $epsilon %>, perplexity: <%= $perplexity %>},
Marc Kupietz9fca1732016-02-29 09:07:04 +0100414 mapWidth = 800, // width map
415 mapHeight = 800,
416 jitterRadius = 7;
417
Marc Kupietzc4893362016-02-25 08:04:46 +0100418var T = new tsnejs.tSNE(opt); // create a tSNE instance
419
420var Y;
421
422var data;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100423var labeler;
Marc Kupietzc4893362016-02-25 08:04:46 +0100424
Marc Kupietzc5990da2016-02-26 08:47:12 +0100425
426function applyJitter() {
Marc Kupietzd7aea722016-03-02 11:59:12 +0100427 svg.selectAll('.tsnet')
Marc Kupietzc5990da2016-02-26 08:47:12 +0100428 .data(labels)
429 .transition()
430 .duration(50)
431 .attr("transform", function(d, i) {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100432 T.Y[i][0] = (d.x - mapWidth/2 - tx)/ss/20;
433 T.Y[i][1] = (d.y - mapHeight/2 - ty)/ss/20;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100434 return "translate(" +
435 (d.x) + "," +
436 (d.y) + ")";
437 });
438}
439
Marc Kupietzc4893362016-02-25 08:04:46 +0100440function updateEmbedding() {
441 var Y = T.getSolution();
Marc Kupietzd7aea722016-03-02 11:59:12 +0100442 svg.selectAll('.tsnet')
Marc Kupietz9fca1732016-02-29 09:07:04 +0100443 .data(data.words)
444 .attr("transform", function(d, i) {
445 return "translate(" +
446 ((Y[i][0]*20*ss + tx) + mapWidth/2) + "," +
447 ((Y[i][1]*20*ss + ty) + mapHeight/2) + ")"; });
Marc Kupietzc4893362016-02-25 08:04:46 +0100448}
449
450var svg;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100451var labels = [];
452var anchor_array = [];
453var text;
454
Marc Kupietzc4893362016-02-25 08:04:46 +0100455function drawEmbedding() {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100456 $("#embed").empty();
457 var div = d3.select("#embed");
458
459 // get min and max in each column of Y
460 var Y = T.Y;
461
462 svg = div.append("svg") // svg is global
463 .attr("width", mapWidth)
464 .attr("height", mapHeight);
465
466 var g = svg.selectAll(".b")
467 .data(data.words)
468 .enter().append("g")
Marc Kupietzd7aea722016-03-02 11:59:12 +0100469 .attr("class", "tsnet");
Marc Kupietz9fca1732016-02-29 09:07:04 +0100470
471 g.append("a")
472 .attr("xlink:href", function(word) {return "/?word="+word;})
473 .attr("title", function(d, i) {
Marc Kupietze50c8162016-03-01 10:24:43 +0100474 return "rank: "+i +" "+"freq. rank: "+data.ranks[i].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
Marc Kupietz9fca1732016-02-29 09:07:04 +0100475 })
Marc Kupietza350bce2016-02-25 09:34:25 +0100476 .append("text")
Marc Kupietz9fca1732016-02-29 09:07:04 +0100477 .attr("text-anchor", "top")
478 .attr("font-size", 12)
479 .attr("fill", function(d) {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100480 if(data.target.indexOf(" "+d+" ") >= 0) {
Marc Kupietza350bce2016-02-25 09:34:25 +0100481 return "red";
482 } else {
483 return "#333"
Marc Kupietzc4893362016-02-25 08:04:46 +0100484 }
Marc Kupietz9fca1732016-02-29 09:07:04 +0100485 })
486 .text(function(d) { return d; });
487
488 var zoomListener = d3.behavior.zoom()
489 .scaleExtent([0.1, 10])
490 .center([0,0])
491 .on("zoom", zoomHandler);
492 zoomListener(svg);
493}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100494
Marc Kupietz9fca1732016-02-29 09:07:04 +0100495var tx=0, ty=0;
496var ss=1;
497var iter_id=-1;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100498
Marc Kupietz9fca1732016-02-29 09:07:04 +0100499function zoomHandler() {
500 tx = d3.event.translate[0];
501 ty = d3.event.translate[1];
502 ss = d3.event.scale;
503 updateEmbedding();
504}
505
506var stepnum = 0;
507
508function stopStep() {
509 clearInterval(iter_id);
510 text = svg.selectAll("text");
511
512 // jitter function needs different data and co-ordinate representation
513 labels = d3.range(data.words.length).map(function(i) {
514 var x = (T.Y[i][0]*20*ss + tx) + mapWidth/2;
515 var y = (T.Y[i][1]*20*ss + ty) + mapHeight/2;
516 anchor_array.push({x: x, y: y, r: jitterRadius});
517 return {
518 x: x,
519 y: y,
520 name: data.words[i]
521 };
522 });
523
524 // get the actual label bounding boxes for the jitter function
525 var index = 0;
526 text.each(function() {
527 labels[index].width = this.getBBox().width;
528 labels[index].height = this.getBBox().height;
529 index += 1;
530 });
Marc Kupietzc5990da2016-02-26 08:47:12 +0100531
532
533// setTimeout(updateEmbedding, 1);
534// setTimeout(
Marc Kupietz9fca1732016-02-29 09:07:04 +0100535 labeler = d3.labeler()
536 .label(labels)
537 .anchor(anchor_array)
538 .width(mapWidth)
539 .height(mapHeight)
540 .update(applyJitter);
541 // .start(1000);
Marc Kupietzc5990da2016-02-26 08:47:12 +0100542
Marc Kupietz9fca1732016-02-29 09:07:04 +0100543 iter_id = setInterval(jitterStep, 1);
544}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100545
Marc Kupietz9fca1732016-02-29 09:07:04 +0100546var jitter_i=0;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100547
548function jitterStep() {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100549 if(jitter_i++ > 100) {
550 clearInterval(iter_id);
551 } else {
552 labeler.start2(10);
553 applyJitter();
554 }
Marc Kupietzc5990da2016-02-26 08:47:12 +0100555}
Marc Kupietzb1029362016-02-27 21:38:55 +0100556
557var last_cost=1000;
558
Marc Kupietz9fca1732016-02-29 09:07:04 +0100559function step() {
560 var i = T.iter;
561
562 if(i > <%= $no_iterations %>) {
563 stopStep();
564 } else {
565 var cost = Math.round(T.step() * 100000) / 100000; // do a few steps
566 $("#cost").html("tsne iteration " + i + ", cost: " + cost.toFixed(5));
567 if(i % 250 == 0 && cost >= last_cost) {
568 stopStep();
569 } else {
570 last_cost = cost;
571 updateEmbedding();
572 }
573 }
574}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100575
Marc Kupietz9fca1732016-02-29 09:07:04 +0100576function showMap(j) {
577 data=j;
578 T.iter=0;
579 T.initDataRaw(data.vecs); // init embedding
580 drawEmbedding(); // draw initial embedding
581
582 if(iter_id >= 0) {
583 clearInterval(iter_id);
584 }
585 //T.debugGrad();
586 iter_id = setInterval(step, 1);
Marc Kupietzd7aea722016-03-02 11:59:12 +0100587 if(<%= $show_som %>) {
588 makeSOM(j, <%= $no_iterations %>);
589 }
Marc Kupietz9fca1732016-02-29 09:07:04 +0100590}
Marc Kupietza350bce2016-02-25 09:34:25 +0100591
Marc Kupietzc4893362016-02-25 08:04:46 +0100592</script>
593</head>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200594<body>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100595 <form action="<%=url_for('/')->to_abs%>" method="GET">
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100596 word(s):
597 <input type="text" name="word" size="20" value="<%= $word %>" title="When looking for multiple words use spaces as separators to search around the average vector and | as separator to get the neighbours for each word.">
598 max. neighbours: <input type="text" size="8" name="n" value="<%= $no_nbs %>">
Marc Kupietzd7aea722016-03-02 11:59:12 +0100599 max. iterations: <input type="text" name="N" size="8" value="<%= $no_iterations %>">
600 SOM <input type="checkbox" name="som" value="1" <%= ($show_som ? "checked" : "") %>>
601 <span> </span><input type="submit" value="Show">
Marc Kupietz4aa62172016-02-25 10:39:27 +0100602 </form>
603 <br>
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100604 % if($lists) {
Marc Kupietz4aa62172016-02-25 10:39:27 +0100605 <div id="wrapper">
606 <table id="first">
607 <tr>
Marc Kupietz5f780672016-02-25 17:15:54 +0100608 <th align="right">Pos.</th><th align="left">Word</th><th align="right">Cosine dist.</th><th>Freq. rank</th>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100609 </tr>
Marc Kupietz5f780672016-02-25 17:15:54 +0100610 % my $j=0; my @words; my @vecs; my @ranks; for my $list (@$lists) {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100611 % my $i=1; for my $item (@$list) {
612 % if(!grep{$_ eq $item->{word}} @words) {
613 % push @vecs, $item->{vector};
614 % push @words, $item->{word};
Marc Kupietz5f780672016-02-25 17:15:54 +0100615 % push @ranks, $item->{rank};
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100616 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100617 <tr>
618 <td align="right">
619 <%= $i++ %>.
620 </td>
621 <td>
622 <a href="/?word=<%= $item->{word} %>">
623 <%= $item->{word} %>
624 </a>
625 </td>
626 <td align="right">
627 <%= sprintf("%.3f", $item->{dist}) %>
628 </td>
Marc Kupietz5f780672016-02-25 17:15:54 +0100629 <td align="right">
630 <%= $item->{rank} %>
631 </td>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100632 </tr>
633 % }
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100634 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100635 </table>
636 <script>
637 % use Mojo::ByteStream 'b';
638 $(window).load(function() {
Marc Kupietz5f780672016-02-25 17:15:54 +0100639 showMap(<%= b(Mojo::JSON::to_json({target => " $word ", words => \@words, vecs => \@vecs, ranks => \@ranks})); %>);
Marc Kupietz4aa62172016-02-25 10:39:27 +0100640 });
641 </script>
642 % }
643 <div id="second" style="width:800px; height:800px; font-family: arial;">
644 <div id="embed">
645 </div>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100646 </div>
Marc Kupietzb1029362016-02-27 21:38:55 +0100647 <div id="cost"></div>
Marc Kupietzd7aea722016-03-02 11:59:12 +0100648 % if($show_som) {
649 <div id="som2">
650 </div>
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100651 <div id="sominfo1"><span id="somcolor1"> </span> <span id="somword1"> </span> <span id="somcolor2"> </span> <span id="somword2"> </span> <span id="somcolor3"> </span></div>
Marc Kupietzd7aea722016-03-02 11:59:12 +0100652 <div id="sominfo">SOM iteration <span id="iterations">0</span></div>
653 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100654 </div>
655 <p>
656 Word vector model based on DeReKo-2015-II. Trained with <a href="https://code.google.com/p/word2vec/">word2vec</a> using the following parameters:</p>
Marc Kupietz247500f2015-10-09 11:29:01 +0200657 <pre>
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100658-cbow 1 -size 300 -window 7 -negative 5 -hs 0 -sample 1e-5 -threads 44 -binary 1 -iter 5
Marc Kupietz4aa62172016-02-25 10:39:27 +0100659 </pre>
660 </p>
661</body>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200662</html>
663