【问题标题】:How to save IDFmodel with PySpark如何使用 PySpark 保存 IDF 模型
【发布时间】:2015-11-25 14:23:52
【问题描述】:

我使用 PySpark 和 ipython notebook 制作了一个 IDFModel,如下所示:

from pyspark import SparkContext
from pyspark.mllib.feature import HashingTF
from pyspark.mllib.feature import IDF

hashingTF = HashingTF()   #this will be used with hashing later

txtdata_train = sc.wholeTextFiles("/home/ubuntu/folder").sortByKey() #this returns RDD of (filename, string) pairs for each file from the directory

split_data_train = txtdata_train.map(parse) #my parse function puts RDD in form I want

tf_train = hashingTF.transform(split_data_train) #creates term frequency sparse vectors for the training set

tf_train.cache()

idf_train = IDF().fit(tf_train)    #makes IDFmodel, THIS IS WHAT I WANT TO SAVE!!!

tfidf_train = idf_train.transform(tf_train)

这是基于本指南https://spark.apache.org/docs/1.2.0/mllib-feature-extraction.html。我想保存这个模型以便稍后在不同的笔记本中再次加载它。但是,没有信息如何做到这一点,我发现最接近的是:

Save Apache Spark mllib model in python

但是当我尝试答案中的建议时

idf_train.save(sc, "/home/ubuntu/newfolder")

我得到错误代码

AttributeError: 'IDFModel' object has no attribute 'save'

我是否缺少某些东西或者无法解决 IDFModel 对象?谢谢!

【问题讨论】:

  • 我正在使用为 Hadoop 2.4.0 构建的 Spark 1.2.0
  • 看看docsIDFModel 没有 save 方法,而另一个 SO 问题 RandomForestModel 中的模型确实有它...
  • 你是对的,谢谢,这是一个值得的补充
  • 知道如何想出我自己的保存方法吗?
  • 我认为这并不容易......但有可用的资源。 Here 在第 420 行,您有一个可以保存的模型示例。 Here 在第 408 行,这是您要保存的内容。我敢打赌jmodel 要么是java 模型,要么可以转换为java 模型。在我的时区太晚了,不能试一试。

标签: apache-spark pyspark apache-spark-mllib


【解决方案1】:

我在 Scala/Java 中做过类似的事情。它似乎有效,但可能效率不高。这个想法是将一个文件写为一个序列化的对象,然后再读回来。祝你好运! :)

try {
  val fileOut:FileOutputStream  = new FileOutputStream(savePath+"/idf.jserialized");
  val out:ObjectOutputStream  = new ObjectOutputStream(fileOut);
  out.writeObject(idf);
  out.close();
  fileOut.close();
  System.out.println("\nSerialization Successful... Checkout your specified output file..\n");
} catch {
  case foe:FileNotFoundException => foe.printStackTrace()
  case ioe:IOException => ioe.printStackTrace()
}

【讨论】:

  • 你如何加载它?加载时似乎没有序列化。
猜你喜欢
  • 2016-08-05
  • 2017-04-13
  • 2018-02-01
  • 2015-05-25
  • 2017-11-09
  • 2019-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多