def adjacency2laplacian(adj: csc_matrix, degree: csc_matrix = None, mode: int = 0) -> csc_matrix: """ This function create a graph laplacian matrix from the adjacency matrix. Parameters ---------- A (sparse matrix): Adjacency matrix. D (Degree matrix): Optional, diagonal matrix containing the sum over the adjacency row. mode (int): 0 Returns the standard graph Laplacian, L = D - A. 1 Returns the random walk normalized graph Laplacian, L = I - D^-1 * A. 2 Returns the symmetric normalized graph Laplacian, L = I - D^-0.5 * A D^-0.5. Returns ------- L (sparse matrix): graph Laplacian """ degree = adjacency2degree(adj) if degree is None else degree if mode == 0: # standard graph Laplacian return degree - adj elif mode == 1: # random walk graph Laplacian return eye(degree.shape[0], format='csc') - degree.power(-1) * adj elif mode == 2: # symmetric normalized graph Laplacian return eye( degree.shape[0], format='csc') - degree.power(-0.5) * adj * degree.power(-0.5) else: raise NotImplementedError
def matrix_similarity(urm: sp.csc_matrix, shrink: int): item_weights = np.sqrt( np.sum(urm.power(2), axis=0) ).A numerator = urm.T.dot(urm) denominator = item_weights.T.dot(item_weights) + shrink + 1e-6 weights = numerator / denominator np.fill_diagonal(item_similarity, 0.0) return weights
def adjacency2transition(adj: csc_matrix, degree: csc_matrix = None) -> csc_matrix: """ Compute the transition matrix associated with the adjacency matrix A""" degree = adjacency2degree(adj) if degree is None else degree return adj * degree.power(-1)