blob: f69b667d0579dfec1a6bc197e1a2fed042ae11b6 [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 Kupietzc4893362016-02-25 08:04:46 +01009init_net("vectors14.bin");
Marc Kupietzdc22b982015-10-09 09:19:34 +020010
11get '/' => sub {
12 my $c = shift;
13 my $word=$c->param('word');
Marc Kupietz4aa62172016-02-25 10:39:27 +010014 my $no_nbs=$c->param('n') || 100;
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010015 my @lists;
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010016 if(defined($word) && $word !~ /^\s*$/) {
17 $c->inactivity_timeout(300);
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010018 for my $w (split('\s+', $word)) {
19 $c->app->log->debug('Looking for neighbours of '.$w);
20 push(@lists, get_neighbours(encode("iso-8859-1", $w), $no_nbs));
21 }
Marc Kupietz247500f2015-10-09 11:29:01 +020022 }
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010023 $c->render(template=>"index", word=>$word, no_nbs=>$no_nbs, lists=> \@lists);
Marc Kupietzdc22b982015-10-09 09:19:34 +020024};
25
26app->start;
27
28exit;
29
30__END__
31
32__C__
33#include <stdio.h>
34#include <string.h>
35#include <math.h>
36#include <malloc.h>
37#include <stdlib.h> //strlen
38
39#define max_size 2000
40#define max_w 50
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010041#define MAX_NEIGHBOURS 1000
Marc Kupietzdc22b982015-10-09 09:19:34 +020042
43//the thread function
44void *connection_handler(void *);
45
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010046char *bestw[MAX_NEIGHBOURS];
Marc Kupietzdc22b982015-10-09 09:19:34 +020047char file_name[max_size], st[100][max_size];
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010048float dist, len, bestd[MAX_NEIGHBOURS], vec[max_size];
Marc Kupietzc4893362016-02-25 08:04:46 +010049long long words, size, a, b, c, d, cn, bi[100], besti[MAX_NEIGHBOURS];
Marc Kupietzdc22b982015-10-09 09:19:34 +020050char ch;
51float *M;
52char *vocab;
53char *stringBuffer;
54
55int init_net(char *file_name) {
56 FILE *f;
57
58 stringBuffer = malloc(64000);
59 f = fopen(file_name, "rb");
60 if (f == NULL) {
61 printf("Input file %s not found\n", file_name);
62 return -1;
63 }
64 fscanf(f, "%lld", &words);
65 fscanf(f, "%lld", &size);
66 vocab = (char *)malloc((long long)words * max_w * sizeof(char));
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010067 for (a = 0; a < MAX_NEIGHBOURS; a++) bestw[a] = (char *)malloc(max_size * sizeof(char));
Marc Kupietzdc22b982015-10-09 09:19:34 +020068 M = (float *)malloc((long long)words * (long long)size * sizeof(float));
69 if (M == NULL) {
70 printf("Cannot allocate memory: %lld MB %lld %lld\n", (long long)words * size * sizeof(float) / 1048576, words, size);
71 return -1;
72 }
73 for (b = 0; b < words; b++) {
74 a = 0;
75 while (1) {
76 vocab[b * max_w + a] = fgetc(f);
77 if (feof(f) || (vocab[b * max_w + a] == ' ')) break;
78 if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++;
79 }
80 vocab[b * max_w + a] = 0;
Marc Kupietz30a43212016-02-25 08:12:00 +010081 fread(&M[b * size], sizeof(float), size, f);
Marc Kupietzdc22b982015-10-09 09:19:34 +020082 len = 0;
83 for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size];
84 len = sqrt(len);
85 for (a = 0; a < size; a++) M[a + b * size] /= len;
86 }
87 fclose(f);
88 return 0;
89}
90
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010091SV *get_neighbours(char *st1, int N) {
92 if(N>MAX_NEIGHBOURS) N=MAX_NEIGHBOURS;
93
Marc Kupietzdc22b982015-10-09 09:19:34 +020094 FILE *out=stdout;
95 *stringBuffer=0;
96
97 for (a = 0; a < N; a++) bestd[a] = 0;
98 for (a = 0; a < N; a++) bestw[a][0] = 0;
99 a = 0;
100 cn = 0;
101 b = 0;
102 c = 0;
103 while (1) {
104 st[cn][b] = st1[c];
105 b++;
106 c++;
107 st[cn][b] = 0;
108 if (st1[c] == 0) break;
109 if (st1[c] == ' ') {
110 cn++;
111 b = 0;
112 c++;
113 }
114 }
115 cn++;
116 for (a = 0; a < cn; a++) {
117 for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st[a])) break;
118 if (b == words) b = -1;
119 bi[a] = b;
Marc Kupietze8da3062016-02-25 08:37:53 +0100120 fprintf(stderr, "Word: \"%s\" Position in vocabulary: %lld\n", st[a], bi[a]);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200121 if (b == -1) {
Marc Kupietze8da3062016-02-25 08:37:53 +0100122 fprintf(stderr, "Out of dictionary word!\n");
Marc Kupietzdc22b982015-10-09 09:19:34 +0200123 break;
124 }
125 }
Marc Kupietz247500f2015-10-09 11:29:01 +0200126 if (b == -1) goto end;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200127 for (a = 0; a < size; a++) vec[a] = 0;
128 for (b = 0; b < cn; b++) {
129 if (bi[b] == -1) continue;
130 for (a = 0; a < size; a++) vec[a] += M[a + bi[b] * size];
131 }
132 len = 0;
133 for (a = 0; a < size; a++) len += vec[a] * vec[a];
134 len = sqrt(len);
135 for (a = 0; a < size; a++) vec[a] /= len;
136 for (a = 0; a < N; a++) bestd[a] = -1;
137 for (a = 0; a < N; a++) bestw[a][0] = 0;
138 for (c = 0; c < words; c++) {
139 a = 0;
Marc Kupietz34020dc2016-02-25 08:44:19 +0100140// do not skip taget word
Marc Kupietze8da3062016-02-25 08:37:53 +0100141// for (b = 0; b < cn; b++) if (bi[b] == c) a = 1;
142// if (a == 1) continue;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200143 dist = 0;
144 for (a = 0; a < size; a++) dist += vec[a] * M[a + c * size];
145 for (a = 0; a < N; a++) {
146 if (dist > bestd[a]) {
147 for (d = N - 1; d > a; d--) {
148 bestd[d] = bestd[d - 1];
Marc Kupietz34020dc2016-02-25 08:44:19 +0100149 besti[d] = besti[d - 1];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200150 }
151 bestd[a] = dist;
Marc Kupietzc4893362016-02-25 08:04:46 +0100152 besti[a] = c;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200153 break;
154 }
155 }
156 }
Marc Kupietz34020dc2016-02-25 08:44:19 +0100157
Marc Kupietz247500f2015-10-09 11:29:01 +0200158 AV* array = newAV();
159 for (a = 0; a < N; a++) {
Marc Kupietz34020dc2016-02-25 08:44:19 +0100160 strcpy(bestw[a], &vocab[besti[a] * max_w]);
Marc Kupietz247500f2015-10-09 11:29:01 +0200161 HV* hash = newHV();
162 hv_store(hash, "word", strlen("word"), newSVpvf(bestw[a], 0), 0);
163 hv_store(hash, "dist", strlen("dist"), newSVnv(bestd[a]), 0);
Marc Kupietzc4893362016-02-25 08:04:46 +0100164 AV *vector = newAV();
165 for (b = 0; b < size; b++) {
166 av_push(vector, newSVnv(M[b + besti[a] * size]));
167 }
168 hv_store(hash, "vector", strlen("vector"), newRV_noinc((SV*)vector), 0);
Marc Kupietz247500f2015-10-09 11:29:01 +0200169 av_push(array, newRV_noinc((SV*)hash));
170 }
171 end:
172 return newRV_noinc((SV*)array);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200173}
174
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100175
Marc Kupietzdc22b982015-10-09 09:19:34 +0200176__DATA__
177
178@@ index.html.ep
179<!DOCTYPE html>
180<html>
Marc Kupietzc4893362016-02-25 08:04:46 +0100181<head>
182 <title>DeReKo-Word-Vector-Distances</title>
183 <script src="http://code.jquery.com/jquery-latest.min.js"></script>
184 <script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
185 <script src="http://klinux10/word2vec/tsne.js"></script>
186<style>
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100187body {
188 font-family: Arial, sans-serif;
189}
Marc Kupietzc4893362016-02-25 08:04:46 +0100190svg {
191// border: 1px solid #333;
Marc Kupietz4aa62172016-02-25 10:39:27 +0100192 margin-right: 10px;
193 margin-bottom:10px;
Marc Kupietzc4893362016-02-25 08:04:46 +0100194}
195#wrapper {
196 width: 100%;
197// border: 1px solid red;
198 overflow: hidden; /* will contain if #first is longer than #second */
199}
200#first {
201 width: 300px;
202 margin-right: 20px;
203 float:left; /* add this */
204// border: 1px solid green;
205}
206#second {
207 border: 1px solid #333;
Marc Kupietz4aa62172016-02-25 10:39:27 +0100208 height: 850px;
Marc Kupietzc4893362016-02-25 08:04:46 +0100209 overflow: hidden; /* if you don't want #second to wrap below #first */
210}
Marc Kupietz4aa62172016-02-25 10:39:27 +0100211#cost {
212 z-index: 1;
213 position: fixed;
214 font-size: 10px;
215 color: #222222;
216 margin-bottom: 10px;
217}
Marc Kupietzc4893362016-02-25 08:04:46 +0100218</style>
219<script>
220
Marc Kupietz4aa62172016-02-25 10:39:27 +0100221var opt = {epsilon: 1, perplexity: 20};
Marc Kupietzc4893362016-02-25 08:04:46 +0100222var T = new tsnejs.tSNE(opt); // create a tSNE instance
223
224var Y;
225
226var data;
227
228function updateEmbedding() {
229 var Y = T.getSolution();
230 svg.selectAll('.u')
231 .data(data.words)
232 .attr("transform", function(d, i) { return "translate(" +
233 ((Y[i][0]*20*ss + tx) + 400) + "," +
234 ((Y[i][1]*20*ss + ty) + 400) + ")"; });
235}
236
237var svg;
238function drawEmbedding() {
Marc Kupietza350bce2016-02-25 09:34:25 +0100239 $("#embed").empty();
240 var div = d3.select("#embed");
241
242 // get min and max in each column of Y
243 var Y = T.Y;
244
245 svg = div.append("svg") // svg is global
246 .attr("width", 800)
247 .attr("height", 800);
248
249 var g = svg.selectAll(".b")
250 .data(data.words)
251 .enter().append("g")
252 .attr("class", "u");
253
254 g.append("a")
255 .attr("xlink:href", function(word) {return "/?word="+word;})
256 .append("text")
257 .attr("text-anchor", "top")
258 .attr("font-size", 12)
259 .attr("fill", function(d) {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100260 if(data.target.indexOf(" "+d+" ") >= 0) {
Marc Kupietza350bce2016-02-25 09:34:25 +0100261 return "red";
262 } else {
263 return "#333"
Marc Kupietzc4893362016-02-25 08:04:46 +0100264 }
Marc Kupietza350bce2016-02-25 09:34:25 +0100265 })
266 .text(function(d) { return d; });
267
268 var zoomListener = d3.behavior.zoom()
269 .scaleExtent([0.1, 10])
270 .center([0,0])
271 .on("zoom", zoomHandler);
272 zoomListener(svg);
273 }
274
275 var tx=0, ty=0;
276 var ss=1;
277 var iter_id=-1;
278
279 function zoomHandler() {
280 tx = d3.event.translate[0];
281 ty = d3.event.translate[1];
282 ss = d3.event.scale;
283 updateEmbedding();
284 }
285
286 var stepnum = 0;
287
288 function stopStep() {
289 clearInterval(iter_id);
290 }
291
292 function step() {
293 var i = T.iter;
Marc Kupietz4aa62172016-02-25 10:39:27 +0100294 if(i > 2000) {
Marc Kupietza350bce2016-02-25 09:34:25 +0100295 stopStep();
296 } else {
Marc Kupietz4aa62172016-02-25 10:39:27 +0100297 var cost = Math.round(T.step() *1000) / 1000; // do a few steps
298 $("#cost").html("iteration " + i + ", cost: " + cost.toFixed(3));
Marc Kupietza350bce2016-02-25 09:34:25 +0100299 updateEmbedding();
300 }
301 }
302
303 function showMap(j) {
304 data=j;
305 T.iter=0;
306 T.initDataRaw(data.vecs); // init embedding
307 drawEmbedding(); // draw initial embedding
308
309 if(iter_id >= 0) {
310 clearInterval(iter_id);
311 }
312 //T.debugGrad();
313 iter_id = setInterval(step, 1);
314 //step();
315 }
316
Marc Kupietzc4893362016-02-25 08:04:46 +0100317</script>
318</head>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200319<body>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100320 <form action="<%=url_for('/')->to_abs%>" method="GET">
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100321 word(s) (space-separated): <input type="text" name="word" value="<%= $word %>">
322 max. neighbours: <input type="text" name="n" value="<%= $no_nbs %>">
323 <input type="submit" value="Show">
Marc Kupietz4aa62172016-02-25 10:39:27 +0100324 </form>
325 <br>
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100326 % if($lists) {
Marc Kupietz4aa62172016-02-25 10:39:27 +0100327 <div id="wrapper">
328 <table id="first">
329 <tr>
330 <th align="right">Pos.</th><th align="left">Word</th><th align="right">Cosine dist.</th>
331 </tr>
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100332 % my $j=0; my @words; my @vecs; for my $list (@$lists) {
333 % my $i=1; for my $item (@$list) {
334 % if(!grep{$_ eq $item->{word}} @words) {
335 % push @vecs, $item->{vector};
336 % push @words, $item->{word};
337 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100338 <tr>
339 <td align="right">
340 <%= $i++ %>.
341 </td>
342 <td>
343 <a href="/?word=<%= $item->{word} %>">
344 <%= $item->{word} %>
345 </a>
346 </td>
347 <td align="right">
348 <%= sprintf("%.3f", $item->{dist}) %>
349 </td>
350 </tr>
351 % }
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100352 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100353 </table>
354 <script>
355 % use Mojo::ByteStream 'b';
356 $(window).load(function() {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100357 showMap(<%= b(Mojo::JSON::to_json({target => " $word ", words => \@words, vecs => \@vecs})); %>);
Marc Kupietz4aa62172016-02-25 10:39:27 +0100358 });
359 </script>
360 % }
361 <div id="second" style="width:800px; height:800px; font-family: arial;">
362 <div id="embed">
363 </div>
364 <div id="cost"></div>
365 </div>
366 </div>
367 <p>
368 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 +0200369 <pre>
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100370-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 +0100371 </pre>
372 </p>
373</body>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200374</html>
375