File size: 28,188 Bytes
a3ab6c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# DeepWalk"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As a part of this blog series and continuing with the tradition of extracting useful graph features by considering the topology of the network graph using machine learning, this blog deals with Deep Walk. This is a simple unsupervised online learning approach, very similar to language modelling used in NLP, where the goal is to generate word embeddings. In this case, generalizing the same concept, it simply tries to learn latent representations of nodes/vertices of a given graph. These graph embeddings which capture neighborhood similarity and community membership can then be used for learning downstream tasks on the graph. \n",
    "\n",
    "\n",
    "![Input Graph to Embdeddings](img/karate_to_embedding.jpg)\n",
    "\n",
    "\n",
    "## Motivation\n",
    "\n",
    "Assume a setting, given a graph G where you wish to convert the nodes into embedding vectors and the only information about a node are the indices of the nodes to which it is connected (adjacency matrix). Since there is no initial feature matrix corresponding to the data, we will construct a feature matrix which will have all the randomly selected nodes. There can be multiple methods to select these but here we will be assuming that they are normally sampled (though it won't make much of a difference even if they are taken from some other distribution).\n",
    "\n",
    "\n",
    "## Random Walks\n",
    "\n",
    "Random walk rooted at vertex $v_i$ as $W_{v_i}$. It is a stochastic process with random variables ${W^1}_{v_i}$, ${W^2}_{v_i}$, $. . .$, ${W^k}_{v_i}$ such that ${W^{k+1}}{v_i}$ is a vertex chosen at random from the\n",
    "neighbors of vertex $v_k$. Random Walk distances are good features for many problems. We'll be discussing how these short random walks are analogous to the sentences in the language modelling setting and how we can carry the concept of context windows to graphs as well.\n",
    "\n",
    "\n",
    "## What is Power Law?\n",
    "\n",
    "A scale-free network is a network whose degree distribution follows a power law, at least asymptotically. That is, the fraction $P(k)$ of nodes in the network having $k$ connections to other nodes goes for large values of $k$ as\n",
    "$P(k) \\sim k^{-\\gamma}$ where $k=2,3$ etc.\n",
    "\n",
    "![Power Law Graph](./Power_Law_Graph.gif)\n",
    "\n",
    "The network of global banking activity with nodes representing the absolute size of assets booked in the respective jurisdiction and the edges between them the exchange of financial assets, with data taken from the IMF is a scale free network and follows Power Law. We can then see clearly how a very few core nodes dominate this network, there are approximately 200 countries in the world but these 19 largest jurisdictions in terms of capital together are responsible for over 90% of the assets.\n",
    "\n",
    "<img src=\"img/Power_Law_Example.jpg\" alt=\"Input Graph to Embdeddings\" width=\"600\"/>\n",
    "\n",
    "These highly centralized networks are more formally called scale free or power law networks, that describe a power or exponential relationship between the degree of connectivity a node has and the frequency of its occurrence. [More](https://www.youtube.com/watch?v=qmCrtuS9vtU) about centralized networks and power law.\n",
    "\n",
    "### Why is it important here?\n",
    "\n",
    "Social networks, including collaboration networks, computer networks, financial networks and Protein-protein interaction networks are some examples of networks claimed to be scale-free.\n",
    "\n",
    "According to the authors, \"If the degree distribution of a connected graph follows a power law (i.e. scale-free), we observe that the frequency which vertices appear in the short random walks will also follow a power-law distribution. Word frequency in natural language follows a similar distribution, and techniques from language modeling account for this distributional behavior.\"\n",
    "\n",
    "![NLP vs Graph Random Walks Power Law D](img/NLP_vs_Graph.jpg)\n",
    "*$(a)$ comes from a series of short random walks on a scale-free graph, and $(b)$ comes from the text of 100,000 articles from the English Wikipedia.*\n",
    "\n",
    "\n",
    "## Intuition with SkipGram\n",
    "\n",
    "Think about the below unrelated problem for now:-\n",
    "\n",
    "Given, some english sentences (could be any other language, doesn't matter) you need to find a vector corresponding to each word appearing at least once in the sentence such that the words having similar meaning appear close to each other in their vector space, and the opposite must hold for words which are dissimilar.\n",
    "\n",
    "Suppose the sentences are\n",
    "1. Hi, I am Bert.\n",
    "2. Hello, this is Bert.\n",
    "\n",
    "From the above sentences you can see that 1 and 2 are related to each other, so even if someone does'nt know the language, one can make out that the words 'Hi' and 'Hello' have roughly the same meaning. We will be using a technique similar to what a human uses while trying to find out related words. Yes! We'll be guessing the meaning based on the words which are common between the sentences. Mathematically, learning a representation in word-2-vec means learning a mapping function from the word co-occurences, and that is exactly what we are heading for.\n",
    "\n",
    "#### But, How?\n",
    "\n",
    "First lets git rid of the punctuations and assign a random vector to each word. Now since these vectors are assigned randomly, it implies the current representation is useless. We'll use our good old friend, *probability*, to convert these into meaningful representations. The idea is to maximize the probability of the appearence of a word, given the words that appear around it. Let's assume the probability is given by $P(x|y)$ where $y$ is the set of words that appear in the same sentence in which $x$ occurs. Remember we are only taking one sentence at a time, so first we'll maximize the probability of 'Hi' given {'I', 'am', 'Bert'} , then we'll maximize the probability of 'I' given {'Hi', 'am', 'Bert'}. We will do it for each word in the first sentence, and then for the second sentence. Repeat this procedure for all the sentences over and over again until the feature vectors have converged. \n",
    "\n",
    "One question that may arise now is, 'How do these feature vectors relate with the probability?'. The answer is that in the probability function we'll utilize the word vectors assinged to them. But, aren't those vectors random? Ahh, they are at the start, but we promise you by the end of the blog they would have converged to the values which really gives some meaning to those seamingly random numbers.\n",
    "\n",
    "#### So, What exactly the probability function helps us with?\n",
    "\n",
    "What does it mean to find the probability of a vector given other vectors? This actually is a simple question with a pretty simple answer, take it as a fill in the blank problem that you may have dealt with in the primary school,\n",
    "\n",
    "Roses ____ red.\n",
    "\n",
    "What is the most likely guess? Most people will fill it with an 'are'. (Unless, you are pretending to be oversmart in an attempt to prove how cool you are). You were able to fill that, because, you've seen some examples of the word 'are' previously in life which help you with the context. The probability function is also trying to do the same, it is finding out the word which is most likely to occur given the words that are surrounding it.\n",
    "\n",
    "\n",
    "#### But but this still doesn't explain how it's gonna do that.\n",
    "\n",
    "In case you guessed 'Neural Network', you are correct. In this blog we'll be using neural nets (feeling sleepy now, so let's wrap this up)\n",
    "\n",
    "It is not necesary to use neural nets to estimate the probability funciton but it works and looks cool :P, frankly, the authors used it, so we'll follow them.\n",
    "\n",
    "The input layer will have |V| neurons, where |V| is the number of words that are interesting to us. We will be using only one hidden layer for simplicity. It can have as many neurons as you want, but it is suggested to keep a number that is less than the number of words in the vocabulary. The output layer will also have the |V| neurons.\n",
    "\n",
    "Now let's move on to the interpretation of input and output layers (don't care about the hidden layer).\n",
    "Lets suppose the words in the vocabulary are $V_1$, $V_2$, $...$ $V_i$, $....$ $V_n$. Assume that out of these V4,V7, V9 appears along with the word whose probability we are tying to maximise. so the input layers will have the 4th, 7th, and the 9th neuron with value 1 and all other will have the value 0. The hidden layer will then have some function of these values. The hidden layer have no non linear acitvation. The |V| neuron in the output layer will have a score, the higher it is ,the higher the chances of that word appearning along with the surrounding words. Apply Sigmoid, boom! we got the probabilities. \n",
    "\n",
    "So a simple neural network will help us solve the fill in the blank problem.\n",
    "\n",
    "\n",
    "## Deep Walk = SkipGram Analogy + Random Walks\n",
    "\n",
    "These random walks can be thought of as short sentences and phrases in a special language; the direct analog is to estimate the likelihood of observing vertex $v_i$ given all the previous vertices visited so far in the random walk, i.e. Our goal is to learn a latent representation, not only a probability distribution of node co-occurrences, and so we introduce a mapping function $ Φ: v ∈ V→R^{|V|×d} $. This mapping $Φ$ represents the latent social representation associated with each vertex $v$ in the graph. (In practice, we represent $Φ$ by a $|V|×d$ matrix of free parameters, which will serve later on as our $X_E$).\n",
    "\n",
    "The problem then, is to estimate the likelihood: $ Pr ({v}_{i} | Φ(v1), Φ(v2), · · · , Φ(vi−1))) $\n",
    "\n",
    "In simple words *DeepWalk* algorithm uses the notion of Random Walks to get the surrounding nodes(words) and ultimately calulate the probability given the context nodes. In simple words we use random walk to start at a node, finds out all the nodes which have and edge connecting with this start node and randomly select one out of them, then consider this new node as the start node and repeat the procedue after n iterations you will have traversed n nodes (some of them might repeat, but it does not matter as is the case of words in a sentence which may repeat as well). We will take n nodes as the surrounding nodes for the original node and will try to maximize probability with respect to those using the probability function estimate. \n",
    "\n",
    "*So, that is for you Ladies and Gentlemen , the <b>'DeepWalk'</b> model.*\n",
    "\n",
    "Mathematically the Deep Walk algorithm is defined as follows,\n",
    "\n",
    "![Deep Walk Algorithm](img/DeepWalk_Algo.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## PyTorch Implementation of DeepWalk"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we will use using the following graph as an example to implement Deep Walk on,\n",
    "![Example Graph](./graph.png)\n",
    "\n",
    "As you can see there are two connected components, so we can expect than when we create the vectors for each node, the vectors of [1 , 2, 3, 7] should be close and similarly that of [4, 5, 6] should be close. Also if  any two vectors are from different group then their vectors should also be far away."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we will we representing the graph using the adjacency list representation. Make sure that you are able to understand that the given graph and this adjacency list are equivalent."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "adj_list = [[1,2,3], [0,2,3], [0, 1, 3], [0, 1, 2], [5, 6], [4,6], [4, 5], [1, 3]]\n",
    "size_vertex = len(adj_list)  # number of vertices"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import random"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Hyperparameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "w=3            # window size\n",
    "d=2            # embedding size\n",
    "y=200          # walks per vertex\n",
    "t=6            # walk length \n",
    "lr=0.025       # learning rate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "v=[0,1,2,3,4,5,6,7] #labels of available vertices"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Random Walk"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def RandomWalk(node,t):\n",
    "    walk = [node]        # Walk starts from this node\n",
    "    \n",
    "    for i in range(t-1):\n",
    "        node = adj_list[node][random.randint(0,len(adj_list[node])-1)]\n",
    "        walk.append(node)\n",
    "\n",
    "    return walk"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Skipgram\n",
    "\n",
    "The skipgram model is closely related to the CBOW model that we just covered. In the CBOW model we have to maximise the probability of the word given its surrounding word using a neural network. And when the probability is maximised, the weights learnt from the input to hidden layer are the word vectors of the given words. In the skipgram word we will be using a using single word to maximise the probability of the surrounding words. This can be done by using a neural network that looks like the mirror image of the network that we used for the CBOW. And in the end the weights of the input to hidden layer will be the corresponding word vectors.\n",
    "\n",
    "Now let's analyze the complexity.\n",
    "There are |V| words in the vocabulary so for each iteration we will be modifying a total of |V| vectors. This is very complex, usually the vocabulary size is in million and since we usually need millions of iteration before convergence, this can take a long long time to run.\n",
    "\n",
    "We will soon be discussing some methods like Hierarchical Softmax or negative sampling to reduce this complexity. But, first we'll code for a simple skipgram model. The class defines the model, whereas the function 'skip_gram' takes care of the training loop."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Model(torch.nn.Module):\n",
    "    def __init__(self):\n",
    "        super(Model, self).__init__()\n",
    "        self.phi  = nn.Parameter(torch.rand((size_vertex, d), requires_grad=True))    \n",
    "        self.phi2 = nn.Parameter(torch.rand((d, size_vertex), requires_grad=True))\n",
    "        \n",
    "        \n",
    "    def forward(self, one_hot):\n",
    "        hidden = torch.matmul(one_hot, self.phi)\n",
    "        out    = torch.matmul(hidden, self.phi2)\n",
    "        return out"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = Model()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "def skip_gram(wvi,  w):\n",
    "    for j in range(len(wvi)):\n",
    "        for k in range(max(0,j-w) , min(j+w, len(wvi))):\n",
    "            \n",
    "            #generate one hot vector\n",
    "            one_hot          = torch.zeros(size_vertex)\n",
    "            one_hot[wvi[j]]  = 1\n",
    "            \n",
    "            out              = model(one_hot)\n",
    "            loss             = torch.log(torch.sum(torch.exp(out))) - out[wvi[k]]\n",
    "            loss.backward()\n",
    "            \n",
    "            for param in model.parameters():\n",
    "                param.data.sub_(lr*param.grad)\n",
    "                param.grad.data.zero_()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(y):\n",
    "    random.shuffle(v)\n",
    "    for vi in v:\n",
    "        wvi=RandomWalk(vi,t)\n",
    "        skip_gram(wvi, w)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "i'th row of the model.phi corresponds to vector of the i'th node. As you can see the vectors of [0, 1, 2,3 , 7] are very close, whereas their vector are much different from the vectors corresponding to [4, 5, 6]."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Parameter containing:\n",
      "tensor([[ 1.2371,  0.3519],\n",
      "        [ 1.0416, -0.1595],\n",
      "        [ 1.4024, -0.2323],\n",
      "        [ 1.2611, -0.5249],\n",
      "        [-1.1221,  0.8553],\n",
      "        [-0.9691,  1.1747],\n",
      "        [-1.3842,  0.4503],\n",
      "        [ 0.2370, -1.2395]], requires_grad=True)\n"
     ]
    }
   ],
   "source": [
    "print(model.phi)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we will be discussing a variant of the above using Hierarchical softmax."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Hierarchical Softmax"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As we have seen in the skip-gram model that the probability of any outcome depends on the total outcomes of our model. If you haven't noticed this yet, let us explain you how!\n",
    "\n",
    "When we calculate the probability of an outcome using softmax, this probability depends on the number of model parameters via the normalisation constant(denominator term) in the softmax.\n",
    "\n",
    "$\\text{Softmax}(x_{i}) = \\frac{\\exp(x_i)}{\\sum_j \\exp(x_j)}$\n",
    "\n",
    "And the number of such parameters are linear in the total number of outcomes. It means if we are dealing with a very large graphical structure, it can be computationally very expensive and taking a lot of time.\n",
    "\n",
    "### Can we somehow overcome this challenge?\n",
    "Obviously, Yes! (because we're asking at this stage). \n",
    "\n",
    "\\*Drum roll please\\*\n",
    "\n",
    "<b>Enter \"Hierarchical Softmax(hs)\"</b>.\n",
    "\n",
    "Basically, hs is an alternative approximation to the softmax in which the probability of any one outcome depends on a number of model parameters that is only logarithmic in the total number of outcomes.\n",
    "\n",
    "Hierarchical softmax uses a binary tree to represent all the words(nodes) in the vocabulary. Each leaf of the tree is a node of our graph, and there is a unique path from root to the leaf. Each intermediate node of tree explicitly represents the relative probabilities of its child nodes. So these nodes are associated to different vectors which our model is going to learn."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The idea behind decomposing the output layer into binary tree is to reduce the time complexity to obtain \n",
    "probability distribution from $O(V)$ to $O(log(V))$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let us understand the process with an example.\n",
    "\n",
    "![binary tree](img/tree.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this example, leaf nodes represent the original nodes of our graph. The highlighted nodes and edges make a path from root to an example leaf node $w_2$.\n",
    "\n",
    "Here, length of the path $L(w_{2}) = 4$.\n",
    "\n",
    "$n(w, j)$ means the $j^{th}$ node on the path from root to a leaf node $w$."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, view this tree as a decision process, or a random walk, that begins at the root of the tree and descents towards the leaf nodes at each step. It turns out that the probability of each outcome in the original distribution uniquely determines the transition probabilities of this random walk. If you want to go from root node to $w_2$(say), first you have to take a left turn, again left turn and then right turn. \n",
    "\n",
    "Let's denote the probability of going left at an intermediate node $n$ as $p(n,left)$ and probability of going right as $p(n,right)$. So we can define the probabilty of going to $w_2$ as follows.\n",
    "\n",
    "<b> $P(w2|wi) = p(n(w_{2}, 1), left) . p(n(w_{2}, 2),left) . p(n(w_{2}, 3), right)$ </b>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Above process implies that the cost for computing the loss function and its gradient will be proportional to the number of nodes $(V)$ in the intermediate path between root node and the output node, which on average is no greater than $log(V)$. That's nice! Isn't it? In the case where we deal with a large number of outcomes, there will be a huge difference in the computational cost of 'vanilla' softmax and hierarchical softmax.\n",
    "\n",
    "Implementation remains similar to the vanilla, except that we will only need to change the Model class by HierarchicalModel class, which is defined below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "def func_L(w):\n",
    "    \"\"\"\n",
    "    Parameters\n",
    "    ----------\n",
    "    w: Leaf node.\n",
    "    \n",
    "    Returns\n",
    "    -------\n",
    "    count: The length of path from the root node to the given vertex.\n",
    "    \"\"\"\n",
    "    count=1\n",
    "    while(w!=1):\n",
    "        count+=1\n",
    "        w//=2\n",
    "\n",
    "    return count"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# func_n returns the nth node in the path from the root node to the given vertex\n",
    "def func_n(w, j):\n",
    "    li=[w]\n",
    "    while(w!=1):\n",
    "        w = w//2\n",
    "        li.append(w)\n",
    "\n",
    "    li.reverse()\n",
    "    \n",
    "    return li[j]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "def sigmoid(x):\n",
    "    out = 1/(1+torch.exp(-x))\n",
    "    return out"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "class HierarchicalModel(torch.nn.Module):\n",
    "    \n",
    "    def __init__(self):\n",
    "        super(HierarchicalModel, self).__init__()\n",
    "        self.phi         = nn.Parameter(torch.rand((size_vertex, d), requires_grad=True))   \n",
    "        self.prob_tensor = nn.Parameter(torch.rand((2*size_vertex, d), requires_grad=True))\n",
    "    \n",
    "    def forward(self, wi, wo):\n",
    "        one_hot     = torch.zeros(size_vertex)\n",
    "        one_hot[wi] = 1\n",
    "        w = size_vertex + wo\n",
    "        h = torch.matmul(one_hot,self.phi)\n",
    "        p = torch.tensor([1.0])\n",
    "        for j in range(1, func_L(w)-1):\n",
    "            mult = -1\n",
    "            if(func_n(w, j+1)==2*func_n(w, j)): # Left child\n",
    "                mult = 1\n",
    "        \n",
    "            p = p*sigmoid(mult*torch.matmul(self.prob_tensor[func_n(w,j)], h))\n",
    "        \n",
    "        return p"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The input to hidden weight vector no longer represents the vector corresponding to each vector , so directly trying to read it will not provide any valuable insight, a better option is to predict the probability of different vectors against each other to figure out the likelihood of coexistance of the nodes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "hierarchicalModel = HierarchicalModel()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "def HierarchicalSkipGram(wvi,  w):\n",
    "   \n",
    "    for j in range(len(wvi)):\n",
    "        for k in range(max(0,j-w) , min(j+w, len(wvi))):\n",
    "            #generate one hot vector\n",
    "       \n",
    "            prob = hierarchicalModel(wvi[j], wvi[k])\n",
    "            loss = - torch.log(prob)\n",
    "            loss.backward()\n",
    "            for param in hierarchicalModel.parameters():\n",
    "                param.data.sub_(lr*param.grad)\n",
    "                param.grad.data.zero_()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(y):\n",
    "    random.shuffle(v)\n",
    "    for vi in v:\n",
    "        wvi = RandomWalk(vi,t)\n",
    "        HierarchicalSkipGram(wvi, w)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "24.0 28.0 23.0 22.0 14.0 8.0 5.0 70.0 \n",
      "24.0 31.0 23.0 21.0 8.0 3.0 1.0 86.0 \n",
      "22.0 25.0 25.0 26.0 15.0 11.0 2.0 69.0 \n",
      "19.0 23.0 26.0 31.0 10.0 7.0 0.0 81.0 \n",
      "36.0 33.0 18.0 12.0 39.0 29.0 31.0 0.0 \n",
      "31.0 28.0 22.0 18.0 34.0 34.0 30.0 0.0 \n",
      "33.0 30.0 20.0 15.0 35.0 28.0 35.0 0.0 \n",
      "20.0 26.0 25.0 27.0 6.0 3.0 0.0 90.0 \n"
     ]
    }
   ],
   "source": [
    "for i in range(8):\n",
    "    for j in range(8):\n",
    "        print((hierarchicalModel(i,j).item()*100)//1, end=' ')\n",
    "    print(end = '\\n')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3>References</h3>\n",
    "\n",
    "- [DeepWalk: Online Learning of Social Representations](http://www.perozzi.net/publications/14_kdd_deepwalk.pdf)\n",
    "\n",
    "- [An Illustrated Explanation of Using SkipGram To Encode The Structure of A Graph (DeepWalk)](https://medium.com/@_init_/an-illustrated-explanation-of-using-skipgram-to-encode-the-structure-of-a-graph-deepwalk-6220e304d71b?source=---------13------------------)\n",
    "\n",
    "- [Word Embedding](https://medium.com/data-science-group-iitr/word-embedding-2d05d270b285)\n",
    "\n",
    "- [Centralized & Scale Free Networks](https://www.youtube.com/watch?v=qmCrtuS9vtU)\n",
    "\n",
    "\n",
    "- Beautiful explanations by Chris McCormick:\n",
    "    - [Hieararchical Softmax](https://youtu.be/pzyIWCelt_E)\n",
    "    - [word2vec](http://mccormickml.com/2019/03/12/the-inner-workings-of-word2vec/)\n",
    "    - [Negative Sampling](http://mccormickml.com/2017/01/11/word2vec-tutorial-part-2-negative-sampling/)\n",
    "    - [skip-gram](http://mccormickml.com/2016/04/19/word2vec-tutorial-the-skip-gram-model/)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}