1)A网页有链接指向B,C,D,E
2)B网页有链接指向A,D
3)C网页有链接指向A,D
4)D网页有链接指向C
5)E网页有链接指向A,C
易知其Google矩阵如下,利用PageRank算法实现网页排序。
代码如下:
package pageRank;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class PageRank{
PageRank(){
}
//s为初始google矩阵,n为节点数,alpha为系数
float [] pageRankTest(float [][]s, int n, float alpha){
float [] q0 = new float [n]; //定义q0
float [] q1 = new float [n];
float e = 0;
int iterationCount = 0;
//初始化
for(int i=0;i<n;i++){
q0[i] = 1;
}
//中间结果
float [][] alpha_s = new float [n][n];
float belta = (1-alpha)/(float)n;
float [][] google = new float [n][n];
//alpha*s
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
alpha_s[i][j] = alpha * s[i][j];
}
}
//alpha*s+(1-alpha)*u/n 即google矩阵
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
google[i][j] = alpha_s[i][j] + belta;
}
}
System.out.println("A B C D E 按照PageRank算法迭代的过程为:");
//迭代求解q1
do {
for(int i=0;i<n;i++){
q1[i] = 0;
for(int j=0;j<n;j++){
q1[i] = q1[i] + q0[j]*google[i][j];
}
}
//输出中间迭代过程
for(int i=0;i<n;i++){
System.out.print("第"+iterationCount+"次迭代:"+q1[i]+" ");
}
System.out.println();
//判断迭代是否收敛
e=0;
for(int i=0;i<n;i++){
e= e + Math.abs(q0[i]-q1[i]);
}
//将求得的q1重新赋给q0
for(int i=0;i<n;i++){
q0[i] = q1[i];
}
iterationCount++;
} while (e > 0.000001 && iterationCount<=50);
return q1;
}
}
public class TestMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
float [][]googleMatrix = new float [][]{{0, 0.5f, 0.5f, 0, 0.5f},
{0.25f, 0, 0, 0, 0},
{0.25f, 0, 0, 1, 0.5f},
{0.25f, 0.5f, 0.5f, 0, 0},
{0.25f, 0, 0, 0, 0}};
float []qFinal = new float [5];
//调用pageRank算法
PageRank pageRank = new PageRank();
qFinal = pageRank.pageRankTest(googleMatrix, 5, 0.85f);
HashMap<Character, Float> rank = new HashMap<>();
rank.put('A', qFinal[0]);
rank.put('B', qFinal[1]);
rank.put('C', qFinal[2]);
rank.put('D', qFinal[3]);
rank.put('E', qFinal[4]);
System.out.println();
System.out.println("A B C D E 按照rank值排序后为:");
//按照降序对rank值进行排序
List<Map.Entry<Character, Float>> list = new ArrayList<Map.Entry<Character, Float>>(rank.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Character, Float>>() {
public int compare(Map.Entry<Character, Float> o1,
Map.Entry<Character, Float> o2) {
/*
* 扩大float
*/
return (int) (o2.getValue()*100000 - o1.getValue()*100000);
}
});
//遍历输出
for (int i = 0; i < list.size(); i++) {
String id = list.get(i).toString();
System.out.println(" -----"+id);
}
}
}
本文地址:http://www.45fan.com/a/question/100014.html