blob: e62c63ca2f13feae19d621095cd966af3c4d6539 [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 Kupietzc4893362016-02-25 08:04:46 +0100174 AV *vector = newAV();
175 for (b = 0; b < size; b++) {
176 av_push(vector, newSVnv(M[b + besti[a] * size]));
177 }
178 hv_store(hash, "vector", strlen("vector"), newRV_noinc((SV*)vector), 0);
Marc Kupietz247500f2015-10-09 11:29:01 +0200179 av_push(array, newRV_noinc((SV*)hash));
180 }
Marc Kupietz247500f2015-10-09 11:29:01 +0200181 return newRV_noinc((SV*)array);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200182}
183
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100184
Marc Kupietzdc22b982015-10-09 09:19:34 +0200185__DATA__
186
187@@ index.html.ep
188<!DOCTYPE html>
189<html>
Marc Kupietzc4893362016-02-25 08:04:46 +0100190<head>
191 <title>DeReKo-Word-Vector-Distances</title>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100192 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
Marc Kupietzc4893362016-02-25 08:04:46 +0100193 <script src="http://code.jquery.com/jquery-latest.min.js"></script>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100194 <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
195 <script>
196 $(function() {
197 $( document ).tooltip();
198 });
199 </script>
Marc Kupietzc4893362016-02-25 08:04:46 +0100200 <script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
201 <script src="http://klinux10/word2vec/tsne.js"></script>
202<style>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100203body, input {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100204 font-family: Arial, sans-serif;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100205 font-size: 11pt;
206}
207
208.ui-tooltip-content {
209 font-size: 9pt;
210 colour: #222222;
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100211}
Marc Kupietzc4893362016-02-25 08:04:46 +0100212svg {
213// border: 1px solid #333;
Marc Kupietz4aa62172016-02-25 10:39:27 +0100214 margin-right: 10px;
215 margin-bottom:10px;
Marc Kupietzc4893362016-02-25 08:04:46 +0100216}
217#wrapper {
218 width: 100%;
219// border: 1px solid red;
220 overflow: hidden; /* will contain if #first is longer than #second */
221}
222#first {
Marc Kupietzc4893362016-02-25 08:04:46 +0100223 margin-right: 20px;
224 float:left; /* add this */
225// border: 1px solid green;
226}
227#second {
228 border: 1px solid #333;
Marc Kupietz4aa62172016-02-25 10:39:27 +0100229 height: 850px;
Marc Kupietzc4893362016-02-25 08:04:46 +0100230 overflow: hidden; /* if you don't want #second to wrap below #first */
231}
Marc Kupietz4aa62172016-02-25 10:39:27 +0100232#cost {
233 z-index: 1;
234 position: fixed;
235 font-size: 10px;
236 color: #222222;
237 margin-bottom: 10px;
238}
Marc Kupietzc4893362016-02-25 08:04:46 +0100239</style>
240<script>
241
Marc Kupietz4aa62172016-02-25 10:39:27 +0100242var opt = {epsilon: 1, perplexity: 20};
Marc Kupietzc4893362016-02-25 08:04:46 +0100243var T = new tsnejs.tSNE(opt); // create a tSNE instance
244
245var Y;
246
247var data;
248
249function updateEmbedding() {
250 var Y = T.getSolution();
251 svg.selectAll('.u')
252 .data(data.words)
253 .attr("transform", function(d, i) { return "translate(" +
254 ((Y[i][0]*20*ss + tx) + 400) + "," +
255 ((Y[i][1]*20*ss + ty) + 400) + ")"; });
256}
257
258var svg;
259function drawEmbedding() {
Marc Kupietza350bce2016-02-25 09:34:25 +0100260 $("#embed").empty();
261 var div = d3.select("#embed");
262
263 // get min and max in each column of Y
264 var Y = T.Y;
265
266 svg = div.append("svg") // svg is global
267 .attr("width", 800)
268 .attr("height", 800);
269
270 var g = svg.selectAll(".b")
271 .data(data.words)
272 .enter().append("g")
273 .attr("class", "u");
274
275 g.append("a")
276 .attr("xlink:href", function(word) {return "/?word="+word;})
277 .append("text")
278 .attr("text-anchor", "top")
279 .attr("font-size", 12)
280 .attr("fill", function(d) {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100281 if(data.target.indexOf(" "+d+" ") >= 0) {
Marc Kupietza350bce2016-02-25 09:34:25 +0100282 return "red";
283 } else {
284 return "#333"
Marc Kupietzc4893362016-02-25 08:04:46 +0100285 }
Marc Kupietza350bce2016-02-25 09:34:25 +0100286 })
287 .text(function(d) { return d; });
288
289 var zoomListener = d3.behavior.zoom()
290 .scaleExtent([0.1, 10])
291 .center([0,0])
292 .on("zoom", zoomHandler);
293 zoomListener(svg);
294 }
295
296 var tx=0, ty=0;
297 var ss=1;
298 var iter_id=-1;
299
300 function zoomHandler() {
301 tx = d3.event.translate[0];
302 ty = d3.event.translate[1];
303 ss = d3.event.scale;
304 updateEmbedding();
305 }
306
307 var stepnum = 0;
308
309 function stopStep() {
310 clearInterval(iter_id);
311 }
312
313 function step() {
314 var i = T.iter;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100315 if(i > <%= $no_iterations %>) {
Marc Kupietza350bce2016-02-25 09:34:25 +0100316 stopStep();
317 } else {
Marc Kupietz4aa62172016-02-25 10:39:27 +0100318 var cost = Math.round(T.step() *1000) / 1000; // do a few steps
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100319 $("#cost").html("tsne iteration " + i + ", cost: " + cost.toFixed(3));
Marc Kupietza350bce2016-02-25 09:34:25 +0100320 updateEmbedding();
321 }
322 }
323
324 function showMap(j) {
325 data=j;
326 T.iter=0;
327 T.initDataRaw(data.vecs); // init embedding
328 drawEmbedding(); // draw initial embedding
329
330 if(iter_id >= 0) {
331 clearInterval(iter_id);
332 }
333 //T.debugGrad();
334 iter_id = setInterval(step, 1);
335 //step();
336 }
337
Marc Kupietzc4893362016-02-25 08:04:46 +0100338</script>
339</head>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200340<body>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100341 <form action="<%=url_for('/')->to_abs%>" method="GET">
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100342 word(s):
343 <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.">
344 max. neighbours: <input type="text" size="8" name="n" value="<%= $no_nbs %>">
345 iterations: <input type="text" name="N" size="8" value="<%= $no_iterations %>">
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100346 <input type="submit" value="Show">
Marc Kupietz4aa62172016-02-25 10:39:27 +0100347 </form>
348 <br>
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100349 % if($lists) {
Marc Kupietz4aa62172016-02-25 10:39:27 +0100350 <div id="wrapper">
351 <table id="first">
352 <tr>
353 <th align="right">Pos.</th><th align="left">Word</th><th align="right">Cosine dist.</th>
354 </tr>
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100355 % my $j=0; my @words; my @vecs; for my $list (@$lists) {
356 % my $i=1; for my $item (@$list) {
357 % if(!grep{$_ eq $item->{word}} @words) {
358 % push @vecs, $item->{vector};
359 % push @words, $item->{word};
360 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100361 <tr>
362 <td align="right">
363 <%= $i++ %>.
364 </td>
365 <td>
366 <a href="/?word=<%= $item->{word} %>">
367 <%= $item->{word} %>
368 </a>
369 </td>
370 <td align="right">
371 <%= sprintf("%.3f", $item->{dist}) %>
372 </td>
373 </tr>
374 % }
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100375 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100376 </table>
377 <script>
378 % use Mojo::ByteStream 'b';
379 $(window).load(function() {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100380 showMap(<%= b(Mojo::JSON::to_json({target => " $word ", words => \@words, vecs => \@vecs})); %>);
Marc Kupietz4aa62172016-02-25 10:39:27 +0100381 });
382 </script>
383 % }
384 <div id="second" style="width:800px; height:800px; font-family: arial;">
385 <div id="embed">
386 </div>
387 <div id="cost"></div>
388 </div>
389 </div>
390 <p>
391 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 +0200392 <pre>
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100393-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 +0100394 </pre>
395 </p>
396</body>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200397</html>
398