java经典算法大全_JAVA 经典算法大全:PageRank算法

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] + ",");

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值