blob: d10325f3bdd1f2ff90af4fa4c1d7e7f618c880ed [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 Kupietz7bc85fd2016-02-24 11:42:41 +01006use Mojo::Server::Daemon;
Marc Kupietzdc22b982015-10-09 09:19:34 +02007
Marc Kupietz7bc85fd2016-02-24 11:42:41 +01008# -cbow 1 -size 200 -window 8 -negative 25 -hs 0 -sample 1e-4 -threads 40 -binary 1 -iter 15
Marc Kupietz44bee3c2016-02-25 16:26:29 +01009init_net("vectors15.bin");
Marc Kupietzdc22b982015-10-09 09:19:34 +020010
11get '/' => sub {
12 my $c = shift;
13 my $word=$c->param('word');
Marc Kupietz44bee3c2016-02-25 16:26:29 +010014 my $no_nbs=$c->param('n') || 100;
15 my $no_iterations=$c->param('N') || 2000;
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010016 my @lists;
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010017 if(defined($word) && $word !~ /^\s*$/) {
18 $c->inactivity_timeout(300);
Marc Kupietz44bee3c2016-02-25 16:26:29 +010019 $word =~ s/\s+/ /g;
20 for my $w (split(' *\| *', $word)) {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010021 $c->app->log->debug('Looking for neighbours of '.$w);
22 push(@lists, get_neighbours(encode("iso-8859-1", $w), $no_nbs));
23 }
Marc Kupietz247500f2015-10-09 11:29:01 +020024 }
Marc Kupietz44bee3c2016-02-25 16:26:29 +010025 $c->render(template=>"index", word=>$word, no_nbs=>$no_nbs, no_iterations => $no_iterations, lists=> \@lists);
Marc Kupietzdc22b982015-10-09 09:19:34 +020026};
27
28app->start;
29
30exit;
31
32__END__
33
34__C__
35#include <stdio.h>
36#include <string.h>
37#include <math.h>
38#include <malloc.h>
39#include <stdlib.h> //strlen
40
41#define max_size 2000
42#define max_w 50
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010043#define MAX_NEIGHBOURS 1000
Marc Kupietz44bee3c2016-02-25 16:26:29 +010044#define MAX_WORDS -1
Marc Kupietzdc22b982015-10-09 09:19:34 +020045
46//the thread function
47void *connection_handler(void *);
48
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010049char *bestw[MAX_NEIGHBOURS];
Marc Kupietzdc22b982015-10-09 09:19:34 +020050char file_name[max_size], st[100][max_size];
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010051float dist, len, bestd[MAX_NEIGHBOURS], vec[max_size];
Marc Kupietzc4893362016-02-25 08:04:46 +010052long long words, size, a, b, c, d, cn, bi[100], besti[MAX_NEIGHBOURS];
Marc Kupietzdc22b982015-10-09 09:19:34 +020053char ch;
54float *M;
55char *vocab;
56char *stringBuffer;
57
58int init_net(char *file_name) {
59 FILE *f;
60
61 stringBuffer = malloc(64000);
62 f = fopen(file_name, "rb");
63 if (f == NULL) {
64 printf("Input file %s not found\n", file_name);
65 return -1;
66 }
67 fscanf(f, "%lld", &words);
Marc Kupietz44bee3c2016-02-25 16:26:29 +010068 if(MAX_WORDS > 0 && words > MAX_WORDS) words = MAX_WORDS;
Marc Kupietzdc22b982015-10-09 09:19:34 +020069 fscanf(f, "%lld", &size);
70 vocab = (char *)malloc((long long)words * max_w * sizeof(char));
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010071 for (a = 0; a < MAX_NEIGHBOURS; a++) bestw[a] = (char *)malloc(max_size * sizeof(char));
Marc Kupietzdc22b982015-10-09 09:19:34 +020072 M = (float *)malloc((long long)words * (long long)size * sizeof(float));
73 if (M == NULL) {
74 printf("Cannot allocate memory: %lld MB %lld %lld\n", (long long)words * size * sizeof(float) / 1048576, words, size);
75 return -1;
76 }
77 for (b = 0; b < words; b++) {
78 a = 0;
79 while (1) {
80 vocab[b * max_w + a] = fgetc(f);
81 if (feof(f) || (vocab[b * max_w + a] == ' ')) break;
82 if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++;
83 }
84 vocab[b * max_w + a] = 0;
Marc Kupietz30a43212016-02-25 08:12:00 +010085 fread(&M[b * size], sizeof(float), size, f);
Marc Kupietzdc22b982015-10-09 09:19:34 +020086 len = 0;
87 for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size];
88 len = sqrt(len);
89 for (a = 0; a < size; a++) M[a + b * size] /= len;
90 }
91 fclose(f);
92 return 0;
93}
94
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010095SV *get_neighbours(char *st1, int N) {
96 if(N>MAX_NEIGHBOURS) N=MAX_NEIGHBOURS;
97
Marc Kupietzdc22b982015-10-09 09:19:34 +020098 FILE *out=stdout;
99 *stringBuffer=0;
100
101 for (a = 0; a < N; a++) bestd[a] = 0;
102 for (a = 0; a < N; a++) bestw[a][0] = 0;
103 a = 0;
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;
Marc Kupietze8da3062016-02-25 08:37:53 +0100124 fprintf(stderr, "Word: \"%s\" Position in vocabulary: %lld\n", st[a], bi[a]);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200125 if (b == -1) {
Marc Kupietze8da3062016-02-25 08:37:53 +0100126 fprintf(stderr, "Out of dictionary word!\n");
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100127 cn--;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200128 break;
129 }
130 }
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100131 if (b == -1 && cn <= 0) {
132 N = 0;
133 goto end;
134 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200135 for (a = 0; a < size; a++) vec[a] = 0;
136 for (b = 0; b < cn; b++) {
137 if (bi[b] == -1) continue;
138 for (a = 0; a < size; a++) vec[a] += M[a + bi[b] * size];
139 }
140 len = 0;
141 for (a = 0; a < size; a++) len += vec[a] * vec[a];
142 len = sqrt(len);
143 for (a = 0; a < size; a++) vec[a] /= len;
144 for (a = 0; a < N; a++) bestd[a] = -1;
145 for (a = 0; a < N; a++) bestw[a][0] = 0;
146 for (c = 0; c < words; c++) {
147 a = 0;
Marc Kupietz34020dc2016-02-25 08:44:19 +0100148// do not skip taget word
Marc Kupietze8da3062016-02-25 08:37:53 +0100149// for (b = 0; b < cn; b++) if (bi[b] == c) a = 1;
150// if (a == 1) continue;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200151 dist = 0;
152 for (a = 0; a < size; a++) dist += vec[a] * M[a + c * size];
153 for (a = 0; a < N; a++) {
154 if (dist > bestd[a]) {
155 for (d = N - 1; d > a; d--) {
156 bestd[d] = bestd[d - 1];
Marc Kupietz34020dc2016-02-25 08:44:19 +0100157 besti[d] = besti[d - 1];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200158 }
159 bestd[a] = dist;
Marc Kupietzc4893362016-02-25 08:04:46 +0100160 besti[a] = c;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200161 break;
162 }
163 }
164 }
Marc Kupietz34020dc2016-02-25 08:44:19 +0100165
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100166end:
167 a=0;
Marc Kupietz247500f2015-10-09 11:29:01 +0200168 AV* array = newAV();
169 for (a = 0; a < N; a++) {
Marc Kupietz34020dc2016-02-25 08:44:19 +0100170 strcpy(bestw[a], &vocab[besti[a] * max_w]);
Marc Kupietz247500f2015-10-09 11:29:01 +0200171 HV* hash = newHV();
172 hv_store(hash, "word", strlen("word"), newSVpvf(bestw[a], 0), 0);
173 hv_store(hash, "dist", strlen("dist"), newSVnv(bestd[a]), 0);
Marc Kupietz5f780672016-02-25 17:15:54 +0100174 hv_store(hash, "rank", strlen("rank"), newSVuv(besti[a]), 0);
Marc Kupietzc4893362016-02-25 08:04:46 +0100175 AV *vector = newAV();
176 for (b = 0; b < size; b++) {
177 av_push(vector, newSVnv(M[b + besti[a] * size]));
178 }
179 hv_store(hash, "vector", strlen("vector"), newRV_noinc((SV*)vector), 0);
Marc Kupietz247500f2015-10-09 11:29:01 +0200180 av_push(array, newRV_noinc((SV*)hash));
181 }
Marc Kupietz247500f2015-10-09 11:29:01 +0200182 return newRV_noinc((SV*)array);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200183}
184
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100185
Marc Kupietzdc22b982015-10-09 09:19:34 +0200186__DATA__
187
188@@ index.html.ep
189<!DOCTYPE html>
190<html>
Marc Kupietzc4893362016-02-25 08:04:46 +0100191<head>
192 <title>DeReKo-Word-Vector-Distances</title>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100193 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
Marc Kupietzc4893362016-02-25 08:04:46 +0100194 <script src="http://code.jquery.com/jquery-latest.min.js"></script>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100195 <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
196 <script>
197 $(function() {
Marc Kupietz5f780672016-02-25 17:15:54 +0100198 $( document ).tooltip({
199 content: function() {
200 return $(this).attr('title');
201 }}
202 )
203 })
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100204 </script>
Marc Kupietzc4893362016-02-25 08:04:46 +0100205 <script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
206 <script src="http://klinux10/word2vec/tsne.js"></script>
207<style>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100208body, input {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100209 font-family: Arial, sans-serif;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100210 font-size: 11pt;
211}
212
213.ui-tooltip-content {
214 font-size: 9pt;
215 colour: #222222;
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100216}
Marc Kupietz5f780672016-02-25 17:15:54 +0100217
218svg > .ui-tooltip-content {
219 font-size: 7pt;
220 colour: #222222;
221}
222
Marc Kupietzc4893362016-02-25 08:04:46 +0100223svg {
224// border: 1px solid #333;
Marc Kupietz4aa62172016-02-25 10:39:27 +0100225 margin-right: 10px;
226 margin-bottom:10px;
Marc Kupietzc4893362016-02-25 08:04:46 +0100227}
228#wrapper {
229 width: 100%;
230// border: 1px solid red;
231 overflow: hidden; /* will contain if #first is longer than #second */
232}
233#first {
Marc Kupietzc4893362016-02-25 08:04:46 +0100234 margin-right: 20px;
235 float:left; /* add this */
236// border: 1px solid green;
237}
238#second {
239 border: 1px solid #333;
Marc Kupietz4aa62172016-02-25 10:39:27 +0100240 height: 850px;
Marc Kupietzc4893362016-02-25 08:04:46 +0100241 overflow: hidden; /* if you don't want #second to wrap below #first */
242}
Marc Kupietz4aa62172016-02-25 10:39:27 +0100243#cost {
244 z-index: 1;
245 position: fixed;
246 font-size: 10px;
247 color: #222222;
248 margin-bottom: 10px;
249}
Marc Kupietzc4893362016-02-25 08:04:46 +0100250</style>
251<script>
252
Marc Kupietz4aa62172016-02-25 10:39:27 +0100253var opt = {epsilon: 1, perplexity: 20};
Marc Kupietzc4893362016-02-25 08:04:46 +0100254var T = new tsnejs.tSNE(opt); // create a tSNE instance
255
256var Y;
257
258var data;
259
260function updateEmbedding() {
261 var Y = T.getSolution();
262 svg.selectAll('.u')
263 .data(data.words)
264 .attr("transform", function(d, i) { return "translate(" +
265 ((Y[i][0]*20*ss + tx) + 400) + "," +
266 ((Y[i][1]*20*ss + ty) + 400) + ")"; });
267}
268
269var svg;
270function drawEmbedding() {
Marc Kupietza350bce2016-02-25 09:34:25 +0100271 $("#embed").empty();
272 var div = d3.select("#embed");
273
274 // get min and max in each column of Y
275 var Y = T.Y;
276
277 svg = div.append("svg") // svg is global
278 .attr("width", 800)
279 .attr("height", 800);
280
281 var g = svg.selectAll(".b")
282 .data(data.words)
283 .enter().append("g")
284 .attr("class", "u");
285
286 g.append("a")
287 .attr("xlink:href", function(word) {return "/?word="+word;})
Marc Kupietz5f780672016-02-25 17:15:54 +0100288 .attr("title", function(d, i) {
289 return "rank: "+i +" "+"freq. rank: "+data.ranks[i];
290 })
Marc Kupietza350bce2016-02-25 09:34:25 +0100291 .append("text")
292 .attr("text-anchor", "top")
293 .attr("font-size", 12)
294 .attr("fill", function(d) {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100295 if(data.target.indexOf(" "+d+" ") >= 0) {
Marc Kupietza350bce2016-02-25 09:34:25 +0100296 return "red";
297 } else {
298 return "#333"
Marc Kupietzc4893362016-02-25 08:04:46 +0100299 }
Marc Kupietza350bce2016-02-25 09:34:25 +0100300 })
301 .text(function(d) { return d; });
302
303 var zoomListener = d3.behavior.zoom()
304 .scaleExtent([0.1, 10])
305 .center([0,0])
306 .on("zoom", zoomHandler);
307 zoomListener(svg);
308 }
309
310 var tx=0, ty=0;
311 var ss=1;
312 var iter_id=-1;
313
314 function zoomHandler() {
315 tx = d3.event.translate[0];
316 ty = d3.event.translate[1];
317 ss = d3.event.scale;
318 updateEmbedding();
319 }
320
321 var stepnum = 0;
322
323 function stopStep() {
324 clearInterval(iter_id);
325 }
326
327 function step() {
328 var i = T.iter;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100329 if(i > <%= $no_iterations %>) {
Marc Kupietza350bce2016-02-25 09:34:25 +0100330 stopStep();
331 } else {
Marc Kupietz4aa62172016-02-25 10:39:27 +0100332 var cost = Math.round(T.step() *1000) / 1000; // do a few steps
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100333 $("#cost").html("tsne iteration " + i + ", cost: " + cost.toFixed(3));
Marc Kupietza350bce2016-02-25 09:34:25 +0100334 updateEmbedding();
335 }
336 }
337
338 function showMap(j) {
339 data=j;
340 T.iter=0;
341 T.initDataRaw(data.vecs); // init embedding
342 drawEmbedding(); // draw initial embedding
343
344 if(iter_id >= 0) {
345 clearInterval(iter_id);
346 }
347 //T.debugGrad();
348 iter_id = setInterval(step, 1);
349 //step();
350 }
351
Marc Kupietzc4893362016-02-25 08:04:46 +0100352</script>
353</head>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200354<body>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100355 <form action="<%=url_for('/')->to_abs%>" method="GET">
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100356 word(s):
357 <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.">
358 max. neighbours: <input type="text" size="8" name="n" value="<%= $no_nbs %>">
359 iterations: <input type="text" name="N" size="8" value="<%= $no_iterations %>">
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100360 <input type="submit" value="Show">
Marc Kupietz4aa62172016-02-25 10:39:27 +0100361 </form>
362 <br>
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100363 % if($lists) {
Marc Kupietz4aa62172016-02-25 10:39:27 +0100364 <div id="wrapper">
365 <table id="first">
366 <tr>
Marc Kupietz5f780672016-02-25 17:15:54 +0100367 <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 +0100368 </tr>
Marc Kupietz5f780672016-02-25 17:15:54 +0100369 % my $j=0; my @words; my @vecs; my @ranks; for my $list (@$lists) {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100370 % my $i=1; for my $item (@$list) {
371 % if(!grep{$_ eq $item->{word}} @words) {
372 % push @vecs, $item->{vector};
373 % push @words, $item->{word};
Marc Kupietz5f780672016-02-25 17:15:54 +0100374 % push @ranks, $item->{rank};
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100375 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100376 <tr>
377 <td align="right">
378 <%= $i++ %>.
379 </td>
380 <td>
381 <a href="/?word=<%= $item->{word} %>">
382 <%= $item->{word} %>
383 </a>
384 </td>
385 <td align="right">
386 <%= sprintf("%.3f", $item->{dist}) %>
387 </td>
Marc Kupietz5f780672016-02-25 17:15:54 +0100388 <td align="right">
389 <%= $item->{rank} %>
390 </td>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100391 </tr>
392 % }
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100393 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100394 </table>
395 <script>
396 % use Mojo::ByteStream 'b';
397 $(window).load(function() {
Marc Kupietz5f780672016-02-25 17:15:54 +0100398 showMap(<%= b(Mojo::JSON::to_json({target => " $word ", words => \@words, vecs => \@vecs, ranks => \@ranks})); %>);
Marc Kupietz4aa62172016-02-25 10:39:27 +0100399 });
400 </script>
401 % }
402 <div id="second" style="width:800px; height:800px; font-family: arial;">
403 <div id="embed">
404 </div>
405 <div id="cost"></div>
406 </div>
407 </div>
408 <p>
409 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 +0200410 <pre>
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100411-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 +0100412 </pre>
413 </p>
414</body>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200415</html>
416