public class PageRank {
private static double alpha = 0.85;
/**
* PageRank vector q is defined as q = Gq where
* G = aS + (1-a)*U/n
* S 为转移矩阵
* U 是值都为1的矩阵
* n 是节点数
* a 权重值
* @param args
*/
public static void main(String[] args) {
//转移矩阵S
double[][] S = { { 0, 0.5, 0.5, 0, 0.5 },
{ 0.25, 0, 0, 0, 0 },
{ 0.25, 0, 0, 1, 0.5 },
{ 0.25, 0.5, 0.5, 0, 0 },
{ 0.25, 0, 0, 0, 0 } };
double[][] U = { { 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1 } };
//计算 aS
double[][] aS = multi(alpha, S);
//(1-a)*U/n 的值
double[][] matrix2 = multi((1-alpha)/S[0].length,U);
//G 的值 = aS+(1-a)/n*U 两个矩阵相加
double[][] G = addMatrix(aS,matrix2);
//矩阵内容
matrixToString(G);
//初试时,假设上网者在每一个网页的概率都是相等的,PageRank 向量 vector
double[] pr_cur={1,1,1,1,1};
for(int i = 0; i < 100; i++){
double[] pr_next = multiMatrixVector(G, pr_cur);
System.out.println(pr_next[0]+" "+pr_next[1]+" "+pr_next[2]+" "+pr_next[3]+" "+pr_next[4]);
pr_cur = pr_next;
}
}
// 矩阵与向量相乘
/**
*
* @param multi 矩阵
* @param vector PageRank vector
* @return
*/
public static double[] multiMatrixVector(double[][] multi, double[] vector) {
//
double[] pageRankVector = new double[vector.length];
for (int i = 0; i < vector.length; i++) {
for (int row = 0; row < multi.length; row++) {
double pageRank = 0;
for (int col = 0; col < multi.length; col++) {
pageRank += (multi[row][col] * vector[col]);
}
pageRankVector[row] = pageRank;
}
}
return pageRankVector;
}
/**
* 两矩阵相加
* @param matrix1 矩阵1
* @param matrix2 矩阵2
* @return
*/
public static double[][] addMatrix(double[][] matrix1, double[][] matrix2) {
double[][] result = new double[matrix1.length][matrix1.length];
for (int row = 0; row < matrix1.length; row++) {
for (int col = 0; col < matrix1.length; col++) {
result[row][col] = matrix1[row][col] + matrix2[row][col];
}
}
return result;
}
/**
* // 矩阵乘因子
* @param gene 因子
* @param matrix
* @return
*/
public static double[][] multi(double gene, double[][] matrix) {
double[][] result = new double[matrix.length][matrix.length];
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix.length; col++) {
result[row][col] = matrix[row][col] * gene;
}
}
return result;
}
/**
* 打印矩阵内容
* @param matrix 矩阵
*/
public static void matrixToString(double[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix.length; col++) {
System.out.print(matrix[row][col] + ",");
}
}
}
}