我已经从互联网上下载了标签传播算法的源代码。来源如下:
def run[VD, ED: ClassTag](graph: Graph[VD, ED], maxSteps: Int): Graph[VertexId, ED] = {
val lpaGraph = graph.mapVertices { case (vid,_) => vid}
def sendMessage(e: EdgeTriplet[VertexId, ED]): Iterator[(VertexId, Map[VertexId, Long])] = {
Iterator((e.srcId, Map(e.dstAttr -> 1L)), (e.dstId, Map(e.srcAttr -> 1L)))
}
def mergeMessage(count1: Map[VertexId, Long], count2: Map[VertexId, Long])
: Map[VertexId, Long] = {
// Mimics the optimization of breakOut, not present in Scala 2.13, while working in 2.12
val map = mutable.Map[VertexId, Long]()
(count1.keySet ++ count2.keySet).foreach { i =>
val count1Val = count1.getOrElse(i, 0L)
val count2Val = count2.getOrElse(i, 0L)
map.put(i, count1Val + count2Val)
}
map
}
def vertexProgram(vid: VertexId, attr: Long, message: Map[VertexId, Long]): VertexId = {
if (message.isEmpty) attr else message.maxBy(_._2)._1
}
val initialMessage = Map[VertexId, Long]()
Pregel(lpaGraph, initialMessage, maxIterations = maxSteps)(
vprog = vertexProgram,
sendMsg = sendMessage,
mergeMsg = mergeMessage)
}
代码获取图形作为输入,并对图形进行一些操作。函数内的第一行是val lpaGraph = graph.mapVertices { case (vid,_) => vid}
,将节点的ID用作其初始标签(属性)。我想做的是从不等于节点ID的标签开始,而是等于节点标签的当前状态的标签开始算法。因为在执行LPA之前,我已经对图形进行了一些操作,并且某些节点具有标签。首先,我在原始图上用以下代码完成了mapvertices
:
case class nodes_properties(label: VertexId, isCoreNode: Boolean = false)
var work_graph = graph.mapVertices { case (node:Long, property) => nodes_properties(node.toInt, false) }
然后,在完成我的操作后,我已经更改了节点的属性以使其准备好执行上述run
方法。
val xx = work_graph.mapVertices { case (node) => (node._2.label) }
结果是某些东西看起来像这样:
(1,3)
(2,3)
(3,3)
(4,9)
(5,2)
....
然后我执行run
方法。我刚刚从以下方法更改了运行方法的第一行:
val lpaGraph = graph.mapVertices { case (vid,_) => vid}
to
val lpaGraph = graph.mapVertices {case (vid) =>(vid._2)}
但是我收到类型不匹配错误:
代码有什么问题?我认为一切都很好。谁能找到错在哪里?
据我从您的问题中了解,您的标签属性将是Long或Int或任何其他不同于VD的类型。尝试测试一下:
val lpaGraph= graph.mapVertices { case (vid) =>(vid._2).asInstanceOf[(VertexId)]}
通过使用asInstanceOf
,您可以将值的类型从所有要变为VertexId
的位置更改为>]