【问题标题】:convert bipartite graph to adjacency matrix spark scala将二部图转换为邻接矩阵 spark scala
【发布时间】:2016-06-16 21:35:15
【问题描述】:

我正在尝试转换以下格式的边缘列表

data = [('a', 'developer'),
     ('b', 'tester'),
    ('b', 'developer'),
     ('c','developer'),
     ('c', 'architect')]

邻接矩阵的形式为

      developer     tester    architect
 a        1            0          0
 b        1            1          0
 c        1            0          1

我想将矩阵存储为以下格式

 1    0    0
 1    1    0
 1    0    1

我已经用 GraphX 试过了

def pageHash(title:String )  = title.toLowerCase.replace(" ","").hashCode.toLong


val edges: RDD[Edge[String]] = sc.textFile("/user/query.csv").map { line => 
  val row = line.split(",") 
  Edge(pageHash(row(0)), pageHash(row(1)), "1") 
} 
val graph: Graph[Int, String] = Graph.fromEdges(edges, defaultValue = 1)

我能够创建图形,但无法转换为相邻矩阵表示。

【问题讨论】:

    标签: scala apache-spark


    【解决方案1】:

    一种可能的方法是这样的:

    1. RDD 转换为DataFrame

      val rdd = sc.parallelize(Seq(
        ("a", "developer"), ("b", "tester"), ("b", "developer"),
        ("c","developer"), ("c", "architect")))
      
      val df = rdd.toDF("row", "col")
      
    2. 索引列:

      import org.apache.spark.ml.feature.StringIndexer
      
      val indexers = Seq("row", "col").map(x =>
        new StringIndexer().setInputCol(x).setOutputCol(s"${x}_idx").fit(df)
      )
      
    3. 转换数据并创建RDD[MatrixEntry]

      import org.apache.spark.functions.lit
      import org.apache.spark.mllib.linalg.distributed.{MatrixEntry, CoordinateMatrix}
      
      
      val entries = indexers.foldLeft(df)((df, idx) => idx.transform(df))
        .select($"row_idx", $"col_idx", lit(1.0))
        .as[MatrixEntry]  // Spark 1.6. For < 1.5 map manually
        .rdd
      
    4. 创建矩阵

      new CoordinateMatrix(entries)
      

    此矩阵可以进一步转换为任何其他类型的分布式矩阵,包括RowMatrixIndexedRowMatrix

    【讨论】:

    • 我为spark 1.4手动映射,但是邻接矩阵的顺序不同,第一行和第三行互换,任何指针。
    • 它似乎不适用于 spark 1.6.2。错误:org.apache.spark.sql.AnalysisException: cannot resolve 'i' given input columns: [row_idx, col_idx, 1].
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    相关资源
    最近更新 更多