[Java]SimRank
有关SimRank请参看文章http://www.cnblogs.com/youwang/archive/2010/02/06/1665105.html,或者去看相关论文。下面是Java代码实现,用到的是webgraph库。
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cn.edu.dlut.wisdom; import it.unimi.dsi.fastutil.ints.*; import it.unimi.dsi.webgraph.*; /** * * @author You Wang */ public class SimRank { private ImmutableGraph graph; private ImmutableGraph igraph; private double dampening = 0.85; private Int2ObjectArrayMap<Int2DoubleArrayMap> scores; public double getDampening() { return dampening; } public void setDampening(double dampening) { this.dampening = dampening; } public SimRank(ImmutableGraph graph) { this.graph = graph; this.igraph = Transform.transpose(graph); } public SimRank(ImmutableGraph graph, ImmutableGraph igraph) { this.graph = graph; this.igraph = igraph; } public void computeSimRank() { int n = graph.numNodes(); int iter = ((int) Math.abs(Math.log((double) n) / Math.log((double) 10))) + 1; computeSimRank(iter); } public Int2DoubleArrayMap getSimRank(int i) { return scores.get(i); } public Int2ObjectArrayMap getSimRank() { return scores; } public double getSimRank(int i, int j) { return scores.get(i).get(j); } public void computeSimRank(int iter) { // 初始化 int numNodes = graph.numNodes(); this.scores = new Int2ObjectArrayMap<Int2DoubleArrayMap>(numNodes); for (int i = 0; i < numNodes; i++) { Int2DoubleArrayMap aux = new Int2DoubleArrayMap(numNodes); for (int j = 0; j < numNodes; j++) { if (i == j) aux.put(j, 1); else aux.put(j, 0); } scores.put(i, aux); } // 迭代计算 while(iter-- > 0) { for(int i = 0; i < numNodes; i++) { int numInNeighborsi = igraph.outdegree(i); if(numInNeighborsi == 0) continue; int[] inNeighborsi = igraph.successorArray(i); Int2DoubleArrayMap rimap = scores.get(i); for(int j = 0; j < numNodes; j++) { int numInNeighborsj = igraph.outdegree(j); if(numInNeighborsj == 0) continue; int[] inNeighborsj = igraph.successorArray(j); double rab = 0; for(int a : inNeighborsi) { Int2DoubleArrayMap aux = scores.get(a); for(int b : inNeighborsj) { rab += aux.get(b); } } rab *= dampening / (numInNeighborsi * numInNeighborsj); rimap.put(j, rab); } } } } }
![Creative Commons License](http://i.creativecommons.org/l/by/2.5/cn/88x31.png)
本文基于署名 2.5 中国大陆许可协议发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名小橋流水(包含链接)。如您有任何疑问或者授权方面的协商,请给我发邮件。