Created
January 14, 2019 17:24
-
-
Save tarasyarema/e9181f4ac1c924d3cff9922f0e3a8484 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"execution_count": 90, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"import numpy as np\n", | |
"\n", | |
"def pagerank(M, eps = 1.0e-8, d = 0.85):\n", | |
" # Get number of vertices of the graph\n", | |
" N = M.shape[1]\n", | |
" \n", | |
" # Generate random array of dimension N and normalize it\n", | |
" v = np.random.rand(N, 1)\n", | |
" v = v / np.linalg.norm(v, 1)\n", | |
" \n", | |
" # Init score matrix\n", | |
" last_v = np.ones((N, 1))\n", | |
" \n", | |
" # Secured convergence formula\n", | |
" M_hat = ((1 - d) / N) * np.ones(M.shape) + d * M\n", | |
" \n", | |
" # Init step counter\n", | |
" steps = 1\n", | |
" \n", | |
" # Loop while the norm of two steps is greater than eps\n", | |
" while np.linalg.norm(v - last_v, 2) > eps:\n", | |
" last_v = v\n", | |
" v = np.matmul(M_hat, v)\n", | |
" \n", | |
" steps += 1\n", | |
" \n", | |
" print('Steps: {}'.format(steps))\n", | |
" print('Site #{} is the best with score {}'.format(np.argmax(v), np.max(v)))" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 91, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"sites_matrix = np.array(\n", | |
" [[0, 0, 0, 0, 1],\n", | |
" [0.5, 0, 0, 0, 0],\n", | |
" [0.5, 0, 0, 0, 0],\n", | |
" [0, 1, 0.5, 0, 0],\n", | |
" [0, 0, 0.5, 1, 0]]\n", | |
")" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 92, | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"Steps: 77\n", | |
"Site #4 is the best with score 0.2637550314744842\n" | |
] | |
} | |
], | |
"source": [ | |
"pagerank(sites_matrix)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": [] | |
} | |
], | |
"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.6.7" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment