我正在尝试为 jung 测试 Pagerank 算法,但似乎我在做这件事时遇到了问题。 我用这部分代码创建了一个加权和间接图:
private static String getId(int nodeId)
{
return "Node " + nodeId;
}
private static String getId(int nodeId, int neighborId)
{
return "Edge " + nodeId + " -> " + neighborId;
}
public static Graph<String, Integer> createGraphForPageRank(String graphId, double[][] adjacencyMatrix)
{
Graph<String,Integer> g = new UndirectedSparseGraph <String,Integer>();
for (int nodeId = 0; nodeId < adjacencyMatrix.length; nodeId++)
g.addVertex(getId(nodeId));
for (int nodeId = 0; nodeId < adjacencyMatrix.length; nodeId++)
for (int neighborId = 0; neighborId < adjacencyMatrix[nodeId].length; neighborId++)
if (adjacencyMatrix[nodeId][neighborId]>0)
g.addEdge(neighborId,getId(nodeId),getId(neighborId));
return(g);
}
然后,在主类中,我使用这段代码在我的图表上测试 pagerank:
double[][] adjacencyMatrixForPageRank =FileHelper.calculateSimilaritySentences("E:\\my workspace\\TweetsAnalyser2\\outputFiles\\splittedStemmeredFile-1.txt","");
Graph<String,Integer> g2=FileHelper.createGraphForPageRank("MyGraphForPageRank",adjacencyMatrixForPageRank);
PageRank<String,Integer> pagerank= new PageRank<String,Integer>(g2,alpha1);
pagerank.initialize();
pagerank.setTolerance(0.000001);
pagerank.setMaxIterations(200);
pagerank.evaluate();
但是 eclipse 会产生这个错误: 线程“main”中的异常 java.lang.IllegalArgumentException:边 4 已经存在于这个带有端点的图中,不能添加端点 在 edu.uci.ics.jung.graph.AbstractGraph.getValidatedEndpoints(AbstractGraph.java:93) 在 edu.uci.ics.jung.graph.UndirectedSparseGraph.addEdge(UndirectedSparseGraph.java:64) 在 edu.uci.ics.jung.graph.AbstractGraph.addEdge(AbstractGraph.java:60) 在 edu.uci.ics.jung.graph.AbstractGraph.addEdge(AbstractGraph.java:55) 在 com.tweets.helpers.FileHelper.createGraphForPageRank(FileHelper.java:1496) 在 com.tweets.test.Main.main(Main.java:105)
我知道做图有问题,但是不知道怎么解决!!!! 有人可以帮帮我吗。
最佳答案
问题似乎是您定义了一个无向图,并向其中添加了两次相同的节点。一种形式为 (x,y)
,另一种形式为 (y,x)
- 对于相同的 x
值和 y
。
通过仅从 nodeID
而不是从 0 在内部循环中迭代来解决它:
for (int nodeId = 0; nodeId < adjacencyMatrix.length; nodeId++)
for (int neighborId = nodeId; neighborId < adjacencyMatrix[nodeId].length; neighborId++)
^^^
另外:
g.addEdge(neighborId,getId(nodeId),getId(neighborId));
您的边缘 ID 不是唯一的,我认为它应该是唯一的,但我对 API 不够熟悉,无法确定。
关于java - 如何测试 jung 的 PageRank 算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36266667/