blob: 77065ab4059d57330ec0c6e48d688ec6dda91ce3 [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 Kupietz7bc85fd2016-02-24 11:42:41 +010014 my $no_nbs=$c->param('n') || 50;
Marc Kupietz247500f2015-10-09 11:29:01 +020015 my $list;
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010016 if(defined($word) && $word !~ /^\s*$/) {
17 $c->inactivity_timeout(300);
18 $c->app->log->debug('Looking for neighbours of '.$word);
19 $list = get_neighbours(encode("iso-8859-1", $word), $no_nbs);
Marc Kupietz247500f2015-10-09 11:29:01 +020020 }
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010021 $c->render(template=>"index", word=>$word, no_nbs=>$no_nbs, list=> $list);
Marc Kupietzdc22b982015-10-09 09:19:34 +020022};
23
24app->start;
25
26exit;
27
28__END__
29
30__C__
31#include <stdio.h>
32#include <string.h>
33#include <math.h>
34#include <malloc.h>
35#include <stdlib.h> //strlen
36
37#define max_size 2000
38#define max_w 50
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010039#define MAX_NEIGHBOURS 1000
Marc Kupietzdc22b982015-10-09 09:19:34 +020040
41//the thread function
42void *connection_handler(void *);
43
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010044char *bestw[MAX_NEIGHBOURS];
Marc Kupietzdc22b982015-10-09 09:19:34 +020045char file_name[max_size], st[100][max_size];
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010046float dist, len, bestd[MAX_NEIGHBOURS], vec[max_size];
Marc Kupietzc4893362016-02-25 08:04:46 +010047long long words, size, a, b, c, d, cn, bi[100], besti[MAX_NEIGHBOURS];
Marc Kupietzdc22b982015-10-09 09:19:34 +020048char ch;
49float *M;
50char *vocab;
51char *stringBuffer;
52
53int init_net(char *file_name) {
54 FILE *f;
55
56 stringBuffer = malloc(64000);
57 f = fopen(file_name, "rb");
58 if (f == NULL) {
59 printf("Input file %s not found\n", file_name);
60 return -1;
61 }
62 fscanf(f, "%lld", &words);
63 fscanf(f, "%lld", &size);
64 vocab = (char *)malloc((long long)words * max_w * sizeof(char));
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010065 for (a = 0; a < MAX_NEIGHBOURS; a++) bestw[a] = (char *)malloc(max_size * sizeof(char));
Marc Kupietzdc22b982015-10-09 09:19:34 +020066 M = (float *)malloc((long long)words * (long long)size * sizeof(float));
67 if (M == NULL) {
68 printf("Cannot allocate memory: %lld MB %lld %lld\n", (long long)words * size * sizeof(float) / 1048576, words, size);
69 return -1;
70 }
71 for (b = 0; b < words; b++) {
72 a = 0;
73 while (1) {
74 vocab[b * max_w + a] = fgetc(f);
75 if (feof(f) || (vocab[b * max_w + a] == ' ')) break;
76 if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++;
77 }
78 vocab[b * max_w + a] = 0;
Marc Kupietz30a43212016-02-25 08:12:00 +010079 fread(&M[b * size], sizeof(float), size, f);
Marc Kupietzdc22b982015-10-09 09:19:34 +020080 len = 0;
81 for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size];
82 len = sqrt(len);
83 for (a = 0; a < size; a++) M[a + b * size] /= len;
84 }
85 fclose(f);
86 return 0;
87}
88
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010089SV *get_neighbours(char *st1, int N) {
90 if(N>MAX_NEIGHBOURS) N=MAX_NEIGHBOURS;
91
Marc Kupietzdc22b982015-10-09 09:19:34 +020092 FILE *out=stdout;
93 *stringBuffer=0;
94
95 for (a = 0; a < N; a++) bestd[a] = 0;
96 for (a = 0; a < N; a++) bestw[a][0] = 0;
97 a = 0;
98 cn = 0;
99 b = 0;
100 c = 0;
101 while (1) {
102 st[cn][b] = st1[c];
103 b++;
104 c++;
105 st[cn][b] = 0;
106 if (st1[c] == 0) break;
107 if (st1[c] == ' ') {
108 cn++;
109 b = 0;
110 c++;
111 }
112 }
113 cn++;
114 for (a = 0; a < cn; a++) {
115 for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st[a])) break;
116 if (b == words) b = -1;
117 bi[a] = b;
Marc Kupietze8da3062016-02-25 08:37:53 +0100118 fprintf(stderr, "Word: \"%s\" Position in vocabulary: %lld\n", st[a], bi[a]);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200119 if (b == -1) {
Marc Kupietze8da3062016-02-25 08:37:53 +0100120 fprintf(stderr, "Out of dictionary word!\n");
Marc Kupietzdc22b982015-10-09 09:19:34 +0200121 break;
122 }
123 }
Marc Kupietz247500f2015-10-09 11:29:01 +0200124 if (b == -1) goto end;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200125 for (a = 0; a < size; a++) vec[a] = 0;
126 for (b = 0; b < cn; b++) {
127 if (bi[b] == -1) continue;
128 for (a = 0; a < size; a++) vec[a] += M[a + bi[b] * size];
129 }
130 len = 0;
131 for (a = 0; a < size; a++) len += vec[a] * vec[a];
132 len = sqrt(len);
133 for (a = 0; a < size; a++) vec[a] /= len;
134 for (a = 0; a < N; a++) bestd[a] = -1;
135 for (a = 0; a < N; a++) bestw[a][0] = 0;
136 for (c = 0; c < words; c++) {
137 a = 0;
Marc Kupietz34020dc2016-02-25 08:44:19 +0100138// do not skip taget word
Marc Kupietze8da3062016-02-25 08:37:53 +0100139// for (b = 0; b < cn; b++) if (bi[b] == c) a = 1;
140// if (a == 1) continue;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200141 dist = 0;
142 for (a = 0; a < size; a++) dist += vec[a] * M[a + c * size];
143 for (a = 0; a < N; a++) {
144 if (dist > bestd[a]) {
145 for (d = N - 1; d > a; d--) {
146 bestd[d] = bestd[d - 1];
Marc Kupietz34020dc2016-02-25 08:44:19 +0100147 besti[d] = besti[d - 1];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200148 }
149 bestd[a] = dist;
Marc Kupietzc4893362016-02-25 08:04:46 +0100150 besti[a] = c;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200151 break;
152 }
153 }
154 }
Marc Kupietz34020dc2016-02-25 08:44:19 +0100155
Marc Kupietz247500f2015-10-09 11:29:01 +0200156 AV* array = newAV();
157 for (a = 0; a < N; a++) {
Marc Kupietz34020dc2016-02-25 08:44:19 +0100158 strcpy(bestw[a], &vocab[besti[a] * max_w]);
Marc Kupietz247500f2015-10-09 11:29:01 +0200159 HV* hash = newHV();
160 hv_store(hash, "word", strlen("word"), newSVpvf(bestw[a], 0), 0);
161 hv_store(hash, "dist", strlen("dist"), newSVnv(bestd[a]), 0);
Marc Kupietzc4893362016-02-25 08:04:46 +0100162 AV *vector = newAV();
163 for (b = 0; b < size; b++) {
164 av_push(vector, newSVnv(M[b + besti[a] * size]));
165 }
166 hv_store(hash, "vector", strlen("vector"), newRV_noinc((SV*)vector), 0);
Marc Kupietz247500f2015-10-09 11:29:01 +0200167 av_push(array, newRV_noinc((SV*)hash));
168 }
169 end:
170 return newRV_noinc((SV*)array);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200171}
172
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100173
Marc Kupietzdc22b982015-10-09 09:19:34 +0200174__DATA__
175
176@@ index.html.ep
177<!DOCTYPE html>
178<html>
Marc Kupietzc4893362016-02-25 08:04:46 +0100179<head>
180 <title>DeReKo-Word-Vector-Distances</title>
181 <script src="http://code.jquery.com/jquery-latest.min.js"></script>
182 <script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
183 <script src="http://klinux10/word2vec/tsne.js"></script>
184<style>
185svg {
186// border: 1px solid #333;
187// margin-right: 5px;
188// margin-bottom: 5px;
189}
190#wrapper {
191 width: 100%;
192// border: 1px solid red;
193 overflow: hidden; /* will contain if #first is longer than #second */
194}
195#first {
196 width: 300px;
197 margin-right: 20px;
198 float:left; /* add this */
199// border: 1px solid green;
200}
201#second {
202 border: 1px solid #333;
203 overflow: hidden; /* if you don't want #second to wrap below #first */
204}
205</style>
206<script>
207
208var opt = {epsilon: 1, perplexity: 8};
209var T = new tsnejs.tSNE(opt); // create a tSNE instance
210
211var Y;
212
213var data;
214
215function updateEmbedding() {
216 var Y = T.getSolution();
217 svg.selectAll('.u')
218 .data(data.words)
219 .attr("transform", function(d, i) { return "translate(" +
220 ((Y[i][0]*20*ss + tx) + 400) + "," +
221 ((Y[i][1]*20*ss + ty) + 400) + ")"; });
222}
223
224var svg;
225function drawEmbedding() {
Marc Kupietza350bce2016-02-25 09:34:25 +0100226 $("#embed").empty();
227 var div = d3.select("#embed");
228
229 // get min and max in each column of Y
230 var Y = T.Y;
231
232 svg = div.append("svg") // svg is global
233 .attr("width", 800)
234 .attr("height", 800);
235
236 var g = svg.selectAll(".b")
237 .data(data.words)
238 .enter().append("g")
239 .attr("class", "u");
240
241 g.append("a")
242 .attr("xlink:href", function(word) {return "/?word="+word;})
243 .append("text")
244 .attr("text-anchor", "top")
245 .attr("font-size", 12)
246 .attr("fill", function(d) {
247 if(d == data.target) {
248 return "red";
249 } else {
250 return "#333"
Marc Kupietzc4893362016-02-25 08:04:46 +0100251 }
Marc Kupietza350bce2016-02-25 09:34:25 +0100252 })
253 .text(function(d) { return d; });
254
255 var zoomListener = d3.behavior.zoom()
256 .scaleExtent([0.1, 10])
257 .center([0,0])
258 .on("zoom", zoomHandler);
259 zoomListener(svg);
260 }
261
262 var tx=0, ty=0;
263 var ss=1;
264 var iter_id=-1;
265
266 function zoomHandler() {
267 tx = d3.event.translate[0];
268 ty = d3.event.translate[1];
269 ss = d3.event.scale;
270 updateEmbedding();
271 }
272
273 var stepnum = 0;
274
275 function stopStep() {
276 clearInterval(iter_id);
277 }
278
279 function step() {
280 var i = T.iter;
281 if(i >= 1000) {
282 stopStep();
283 } else {
284 var cost = T.step(); // do a few steps
285 $("#cost").html("iteration " + i + ", cost: " + cost);
286 updateEmbedding();
287 }
288 }
289
290 function showMap(j) {
291 data=j;
292 T.iter=0;
293 T.initDataRaw(data.vecs); // init embedding
294 drawEmbedding(); // draw initial embedding
295
296 if(iter_id >= 0) {
297 clearInterval(iter_id);
298 }
299 //T.debugGrad();
300 iter_id = setInterval(step, 1);
301 //step();
302 }
303
304 $(window).xxload(function() {
305 $.getJSON( "http://klinux10/word2vec/dings.json", function( j ) {
306 data = j;
307 T.initDataRaw(data.vecs); // init embedding
308 drawEmbedding(); // draw initial embedding
309
310 // T.debugGrad();
311 iter_id = setInterval(step, 1);
312 // step();
313
314 });
315 });
316
Marc Kupietzc4893362016-02-25 08:04:46 +0100317</script>
318</head>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200319<body>
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100320 <p>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 +0200321 <pre>
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100322-cbow 1 -size 300 -window 7 -negative 5 -hs 0 -sample 1e-5 -threads 44 -binary 1 -iter 5
Marc Kupietz247500f2015-10-09 11:29:01 +0200323</pre>
324</p>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200325 <form action="<%=url_for('/')->to_abs%>" method="GET">
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100326 Word: <input type="text" name="word" value="<%= $word %>">
327 Neighbours: <input type="text" name="n" value="<%= $no_nbs %>">
Marc Kupietzdc22b982015-10-09 09:19:34 +0200328 <input type="submit" value="Show neighbours">
329 </form>
330 <br>
Marc Kupietz247500f2015-10-09 11:29:01 +0200331 % if($list) {
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100332 <h3>Nearest neighbours of "<%= $word %>"</h3>
Marc Kupietzc4893362016-02-25 08:04:46 +0100333<div id="wrapper">
334 <table id="first">
Marc Kupietz247500f2015-10-09 11:29:01 +0200335 <tr>
336 <th align="right">Pos.</th><th align="left">Word</th><th align="right">Cosine dist.</th>
337 </tr>
Marc Kupietzc4893362016-02-25 08:04:46 +0100338 % my $i=1; my @words; my @vecs; for my $item (@$list) {
339 % push @vecs, $item->{vector};
340 % push @words, $item->{word};
Marc Kupietz247500f2015-10-09 11:29:01 +0200341 <tr>
342 <td align="right">
343 <%= $i++ %>.
344 </td>
345 <td>
346 <a href="/?word=<%= $item->{word} %>">
347 <%= $item->{word} %>
348 </a>
349 </td>
350 <td align="right">
351 <%= sprintf("%.3f", $item->{dist}) %>
352 </td>
353 </tr>
354 % }
355 </table>
Marc Kupietzc4893362016-02-25 08:04:46 +0100356 <script>
357 % use Mojo::ByteStream 'b';
358$(window).load(function() {
Marc Kupietze8da3062016-02-25 08:37:53 +0100359 showMap(<%= b(Mojo::JSON::to_json({target => $word, words => \@words, vecs => \@vecs})); %>);
Marc Kupietzc4893362016-02-25 08:04:46 +0100360});
361 </script>
Marc Kupietz247500f2015-10-09 11:29:01 +0200362 % }
Marc Kupietzc4893362016-02-25 08:04:46 +0100363<div id="second" style="width:800px; height:800px; font-family: arial;">
364<div id="embed"></div>
365<div id="cost" style="text-align:left; font-family: Impact;"></div>
366 </div>
367 </div>
368 </body>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200369</html>
370