pagerank ----scala 实现

import scala.collection.mutable

class RelationBean {

  //起始节点
  private var _fromNode: String = "null"

  def fromNode: String = _fromNode

  def fromNode_=(value: String): Unit = {
    _fromNode = value
  }

  //指向节点
  private var _toNode: String = "null"

  def toNode: String = _toNode

  def toNode_=(value: String): Unit = {
    _toNode = value
  }

  //属性
  private var _info: Set[String] = new mutable.HashSet[String].toSet

  def info: Set[String] = _info

  def info_=(value: Set[String]): Unit = {
    _info = value
  }

  def canEqual(other: Any): Boolean = other.isInstanceOf[RelationBean]

  override def equals(other: Any): Boolean = other match {
    case that: RelationBean =>
      (that canEqual this) && (_fromNode == that._fromNode && _toNode == that._toNode)
    case _ => false
  }


  override def toString: String = "{fromNode:" + fromNode + ",toNode:" + toNode + ",info:" + info.toString() + "}"
}

object RelationBean {
  def apply: RelationBean = new RelationBean()

}


import RelationBean

import scala.collection.mutable

object PageRank {

  //计算出度和入度
  private def degree(relationset: Set[RelationBean]): (Map[String, Set[String]], Map[String, Set[String]]) = {

    val indegree = new mutable.HashMap[String, Set[String]]()
    val outdegree = new mutable.HashMap[String, Set[String]]()

    relationset.foreach(rela => {
      outdegree.put(rela.fromNode, outdegree.getOrElse(rela.fromNode, new mutable.HashSet[String]()).+(rela.toNode).toSet)
      indegree.put(rela.toNode, indegree.getOrElse(rela.toNode, new mutable.HashSet[String]()).+(rela.fromNode).toSet)
    })
    (indegree.toMap, outdegree.toMap)
  }

  //计算权重
  private def weight(indegree: Map[String, Set[String]], outdegree: Map[String, Set[String]]): Map[String, Double] = {

    var oldweight = new mutable.HashMap[String, Double]()
    val newweight = new mutable.HashMap[String, Double]()

    var f = 0
    while (f < 3) {
      indegree.foreach(a => {
        var w = 0.0
        a._2.foreach(b => {
          w += (oldweight.getOrElse(b, 1.0) / outdegree(b).size)
        })
        newweight.put(a._1, w)
      })

      oldweight.clear()
      oldweight = newweight.clone()
      f += 1
    }
    newweight.toMap

  }

  def run(relationset: Set[RelationBean]): Map[String, Double] = {
    val (in, out) = this.degree(relationset)
    weight(in, out)
  }

}

自用,待优化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值