def matrix_multiply(A, B): n1, k1 = shape(A) n2, k2 = shape(B) if k1 != n2: raise ArithmeticError("incompatible shapes!") return make_matrix(n1, k2, partial(matrix_product_entry, A, B))
def matrix_times_matrix(m1: Matrix, m2: Matrix) -> Matrix: nr1, nc1 = shape(m1) nr2, nc2 = shape(m2) assert nc1 == nr2, "must have (# o f columns in m1) == (# of rows in m2)" def entry_fn(i: int, j: int) -> float: """dot product of i-th row of m1 with the j-th column of m2""" return sum(m1[i][k]*m2[k][j] for k in range(nc1)) return make_matrix(nr1,nc2, entry_fn)
while True: result = matrix_times_vector(m, guess) # transform the guess norm = magnitude(result) # compute the norm next_guess = [x/norm for x in result] # rescale if distance(guess, next_guess) < tolerance: # convergence so return (eigenvector, eigenvalue) return next_guess, norm guess = next_guess return 1 if (i,j) in friend_pairs or (j,i) in friend_pairs else 0 n = len(users) adjacency_matrix = make_matrix(n,n, entry_fn) #adjacency_matrix eigenvector_centrality, _ = find_eigenvector(adjacency_matrix) (2, 1), (1, 3), (2, 3), (3, 4), (5, 4), (5, 6), (7, 5), (6, 8), (8, 7), (8, 9)] from collections import Counter endorsement_counts = Counter(target for source, target in endorsements) import tqdm def page_rank(users: List[User], endorsements: List[Tuple[int, int]],
def vector_from_matrix(v_as_matrix): """returns the n x 1 matrix as a list of values""" return [row[0] for row in v_as_matrix] def matrix_operate(A, v): v_as_matrix = vector_as_matrix(v) product = matrix_multiply(A, v_as_matrix) return vector_from_matrix(product) def find_eigenvector(A, tolerance=0.00001): guess = [random.random() for _ in A] while True: result = matrix_operate(A, guess) length = magnitude(result) next_guess = scalar_multiply(1/length, result) if distance(guess, next_guess) < tolerance: return next_guess, length # eigenvector, eigenvalue guess = next_guess def entry_fn(i, j): return 1 if (i, j) in friendships or (j, i) in friendships else 0 friendships = [(0,1), (0,2), (1,2), (1,3), (2,3), (3,4), (4,5), (5,6), (5,7), (6,8), (7,8), (8,9)] n = len(users) adjacency_matrix = make_matrix(n, n, entry_fn) eigenvector_centralities, _ = find_eigenvector(adjacency_matrix)