背景
当我们使用Scala API a recommended way获得使用DecisionTreeModel的RDD [LabeledPoint]的预测是简单地映射在RDD上:
val labelAndPreds = testData.map { point =>
val prediction = model.predict(point.features)
(point.label, prediction)
}
不幸的是,PySpark中类似的方法不能很好地工作:
labelsAndPredictions = testData.map(
lambda lp: (lp.label, model.predict(lp.features))
labelsAndPredictions.first()
Exception: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transforamtion. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see 07002.
predictions = model.predict(testData.map(lambda x: x.features))
labelsAndPredictions = testData.map(lambda lp: lp.label).zip(predictions)
那么这里发生了什么?这里没有广播变量,Scala API定义预测如下:
/**
* Predict values for a single data point using the model trained.
*
* @param features array representing a single data point
* @return Double prediction from the trained model
*/
def predict(features: Vector): Double = {
topNode.predict(features)
}
/**
* Predict values for the given data set using the model trained.
*
* @param features RDD representing data points to be predicted
* @return RDD of predictions for each of the given data points
*/
def predict(features: RDD[Vector]): RDD[Double] = {
features.map(x => predict(x))
}
所以至少在第一眼看来,从动作或转换调用不是问题,因为预测似乎是本地操作。
说明
callJavaFunc(self._sc, getattr(self._java_model, name), *a)
题
在DecisionTreeModel.predict的情况下,有一个建议的解决方法,所有必需的代码已经是Scala API的一部分,但有什么优雅的方式来处理这样的问题一般?
只有我现在可以想到的解决方案是相当重量级:
>通过扩展Spark类通过隐式转换或添加某种包装器将所有内容推送到JVM
>直接使用Py4j网关