【问题标题】:Load Word2Vec model in Spark在 Spark 中加载 Word2Vec 模型
【发布时间】:2017-10-07 13:56:33
【问题描述】:

是否可以加载预训练(二进制)模型来触发(使用 scala)?我试图加载由谷歌生成的二进制模型之一:

    import org.apache.spark.mllib.feature.{Word2Vec, Word2VecModel}


    val model = Word2VecModel.load(sc, "GoogleNews-vectors-negative300.bin")

但它无法找到元数据目录。我还创建了文件夹并将二进制文件附加到那里,但无法解析。我没有找到这个问题的任何包装。

【问题讨论】:

    标签: scala apache-spark word2vec


    【解决方案1】:

    我编写了一个快速函数,将谷歌新闻预训练模型加载到 spark word2vec 模型中。享受吧。

    def loadBin(file: String) = {
      def readUntil(inputStream: DataInputStream, term: Char, maxLength: Int = 1024 * 8): String = {
        var char: Char = inputStream.readByte().toChar
        val str = new StringBuilder
        while (!char.equals(term)) {
          str.append(char)
          assert(str.size < maxLength)
          char = inputStream.readByte().toChar
        }
        str.toString
      }
      val inputStream: DataInputStream = new DataInputStream(new GZIPInputStream(new FileInputStream(file)))
      try {
        val header = readUntil(inputStream, '\n')
        val (records, dimensions) = header.split(" ") match {
          case Array(records, dimensions) => (records.toInt, dimensions.toInt)
        }
        new Word2VecModel((0 until records).toArray.map(recordIndex => {
          readUntil(inputStream, ' ') -> (0 until dimensions).map(dimensionIndex => {
            java.lang.Float.intBitsToFloat(java.lang.Integer.reverseBytes(inputStream.readInt()))
          }).toArray
        }).toMap)
      } finally {
        inputStream.close()
      }
    }
    

    【讨论】:

    • fasttext 怎么样?我们如何将 fasttext .bin 加载到每个执行程序一次。我尝试这样做,但是模型是按分区加载的,当存在大量 prtition 时,这并不好
    • 听起来你需要使用广播......在驱动程序上加载一次模型,然后通过广播包装器分发它。
    • @Andew Cherneski 你能问我关于同一主题的问题吗stackoverflow.com/questions/54540970/…
    【解决方案2】:

    这是一个未解决的问题: https://issues.apache.org/jira/browse/SPARK-15328

    要么查看特定代码并尝试为自己重新创建一些东西,要么使用 python 或 C 脚本将二进制文件转换为 txt 数据并从那里开始工作。

    Convert word2vec bin file to text

    【讨论】:

    • 将 bin 转换为文本文件后,我应该如何加载模型?
    猜你喜欢
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    • 2019-08-10
    • 2016-08-23
    • 1970-01-01
    • 2017-06-26
    • 2017-08-16
    相关资源
    最近更新 更多