Last active
August 29, 2015 13:56
-
-
Save naoty/8978134 to your computer and use it in GitHub Desktop.
ページランクのRuby実装
This file contains hidden or 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
| require "matrix" | |
| class Graph | |
| D = 0.85 | |
| EPS = 1 * 10 ** -5 | |
| def initialize(matrix) | |
| @dimension = matrix.row_size | |
| elements = [] | |
| @dimension.times do |i| | |
| elements[i] = [] | |
| row_total = matrix.row(i).inject(&:+) | |
| @dimension.times do |j| | |
| elements[i][j] = row_total.zero? ? 0 : matrix[i, j].to_f / row_total | |
| end | |
| end | |
| @matrix = Matrix.rows(elements).transpose | |
| @vector = Matrix[[].fill(1.0 / @dimension, 0, @dimension)] | |
| end | |
| def pageranks | |
| loop do | |
| elements = [] | |
| @dimension.times do |i| | |
| total = 0 | |
| @dimension.times do |j| | |
| total += @matrix[i, j] * @vector[0, j] | |
| end | |
| elements[i] = D * total + (1.0 - D) / @dimension | |
| end | |
| new_vector = Matrix[elements] | |
| diff = 0 | |
| @dimension.times do |i| | |
| diff += (new_vector[0, i] - @vector[0, i]).abs | |
| end | |
| return new_vector if diff < EPS | |
| @vector = new_vector | |
| end | |
| end | |
| end | |
| matrix = Matrix[[0, 1, 1, 0], | |
| [0, 0, 1, 0], | |
| [0, 1, 0, 0], | |
| [0, 1, 0, 0]] | |
| graph = Graph.new(matrix) | |
| p graph.pageranks |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment