Updated:use model broadcast, mappartition+flatmap,see:

from pyspark import SparkContext
import numpy as np
from sklearn import ensemble def batch(xs):
yield list(xs) N = 1000
train_x = np.random.randn(N, 10)
train_y = np.random.binomial(1, 0.5, N) model = ensemble.RandomForestClassifier(10).fit(train_x, train_y) test_x = np.random.randn(N * 100, 10) sc = SparkContext() n_partitions = 10
rdd = sc.parallelize(test_x, n_partitions).zipWithIndex() b_model = sc.broadcast(model) result = rdd.mapPartitions(batch) \
.map(lambda xs: ([x[0] for x in xs], [x[1] for x in xs])) \
.flatMap(lambda x: zip(x[1], b_model.value.predict(x[0]))) print(result.take(100))

see: https://gist.github.com/lucidfrontier45/591be3eb78557d1844ca

----------------------

一开始是因为没法直接在pyspark里使用map 来做model predict,但是scala是可以的!如下:

When we use Scala API a recommended way of getting predictions for RDD[LabeledPoint] using DecisionTreeModel is to simply map over RDD:

val labelAndPreds = testData.map { point =>
val prediction = model.predict(point.features)
(point.label, prediction)
}

Unfortunately similar approach in PySpark doesn't work so well:

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 SPARK-5063.

Instead of that official documentation recommends something like this:

predictions = model.predict(testData.map(lambda x: x.features))
labelsAndPredictions = testData.map(lambda lp: lp.label).zip(predictions)

而这就是万恶的根源,因为zip在某些情况下并不能得到你想要的结果,就是说zip后的顺序是混乱的!!!我就在项目里遇到了!!!

This appears to imply that even the trivial a.map(f).zip(a) is not guaranteed to be equivalent to a.map(x => (f(x),x)). What is the situation when zip() results are reproducible?

见:https://stackoverflow.com/questions/29268210/mind-blown-rdd-zip-method

原因:

zip is generally speaking a tricky operation. It requires both RDDs not only to have the same number of partitions but also the same number of elements per partition.

Excluding some special cases this is guaranteed only if both RDDs have the same ancestor and there are not shuffles and operations potentially changing number of elements (filter, flatMap) between the common ancestor and the current state. Typically it means only map (1-to-1) transformations.

见:https://stackoverflow.com/questions/32084368/can-only-zip-with-rdd-which-has-the-same-number-of-partitions-error

根源是因为我的ancestor rdd做了shuffle和filter的操作!最后在他们的子rdd上使用zip就会出错(数据乱序了)!!!真是太郁闷了,折腾一天这个问题,感谢上帝终于解决了!阿门!

最后我的解决方法是:

1、直接将rdd做union操作,rdd = rdd.union(sc.parallelize([])),然后map,zip就能输出正常结果了!

2、或者是直接将预测的rdd collect到driver机器,使用model predict,是比较丑陋的做法!


 

pyspark MLlib踩坑之model predict+rdd map zip,zip使用尤其注意啊啊啊!的更多相关文章

  1. Spark踩坑记——从RDD看集群调度

    [TOC] 前言 在Spark的使用中,性能的调优配置过程中,查阅了很多资料,之前自己总结过两篇小博文Spark踩坑记--初试和Spark踩坑记--数据库(Hbase+Mysql),第一篇概况的归纳了 ...

  2. Django model重写save方法及update踩坑记录

    一个非常实用的小方法 试想一下,Django中如果我们想对保存进数据库的数据做校验,有哪些实现的方法? 我们可以在view中去处理,每当view接收请求,就对提交的数据做校验,校验不通过直接返回错误, ...

  3. pyspark.mllib.feature module

    Feature Extraction Feature Extraction converts vague features in the raw data into concrete numbers ...

  4. tensorflow踩坑合集2. TF Serving & gRPC 踩坑

    这一章我们借着之前的NER的模型聊聊tensorflow serving,以及gRPC调用要注意的点.以下代码为了方便理解做了简化,完整代码详见Github-ChineseNER ,里面提供了训练好的 ...

  5. Spark踩坑记——Spark Streaming+Kafka

    [TOC] 前言 在WeTest舆情项目中,需要对每天千万级的游戏评论信息进行词频统计,在生产者一端,我们将数据按照每天的拉取时间存入了Kafka当中,而在消费者一端,我们利用了spark strea ...

  6. Spark踩坑记——数据库(Hbase+Mysql)

    [TOC] 前言 在使用Spark Streaming的过程中对于计算产生结果的进行持久化时,我们往往需要操作数据库,去统计或者改变一些值.最近一个实时消费者处理任务,在使用spark streami ...

  7. Spark踩坑记——共享变量

    [TOC] 前言 Spark踩坑记--初试 Spark踩坑记--数据库(Hbase+Mysql) Spark踩坑记--Spark Streaming+kafka应用及调优 在前面总结的几篇spark踩 ...

  8. [转]Spark 踩坑记:数据库(Hbase+Mysql)

    https://cloud.tencent.com/developer/article/1004820 Spark 踩坑记:数据库(Hbase+Mysql) 前言 在使用Spark Streaming ...

  9. ABP框架入门踩坑-配置数据库表前缀

    配置数据库表前缀 ABP踩坑记录-目录 本篇其实和ABP关系并不大,主要是EF Core的一些应用-.-. 起因 支持数据库表前缀应该是很多应用中比较常见的功能,而在ABP中并没直接提供这一功能,所以 ...

随机推荐

  1. JAVA比较两张图相似度

    代码: package com.uiwho.com; import javax.imageio.*; import java.awt.image.*; import java.awt.*;//Colo ...

  2. 开发手机APP过程,不同使用场景APP搜索框的样式及区别

    搜索框是 app 内最常见的控件之一,可以帮助用户快速又精准找到期望的内容与功能.不同的使用场景下,根据页面中搜索的重要程度,搜索框也有着不同的样式. 下面就常州开发APP公司和大家聊聊常见的四种样式 ...

  3. 微信小程序开发之animation动画实现

    1. 创建动画实例 wx.createAnimation(OBJECT) 创建一个动画实例animation.调用实例的方法来描述动画.最后通过动画实例的export方法导出动画数据传递给组件的ani ...

  4. String[]转化暴露“思维误区”

    那天写code,用到这个,强转,将页面传来的值转换为数组,结果是,当页面传来的只有一个值时,它是无法转换为数组的,只能获得1个string,只有length>1时才会转化为数组的形式,报的错误是 ...

  5. Spring AOP理解

    Spring的核心思想的IOC和AOP.最近学习AOP,对切面的学习有了进一步的认识. Spring用代理类包裹切面,把他们织入到Spring管理的bean中.也就是说代理类伪装成目标类,它会截取对目 ...

  6. 【PYTHON】编码是个细致活

    python逆向获取DNS时用到一个函数socket.gethostbyaddr,传入本地主机地址后报错如下: UnicodeDecodeError: 'utf-8' codec can't deco ...

  7. C++调用Matlab 注意事项

    前言:脑残的使用了C++调用Matlab,没想到Matlab的使用者的智商还真TMD不一般, 竟然有这样的 plot(x_Abnorm_index,Vec2(Abnorm_index),'sb','l ...

  8. Auto Layout压缩阻力及内容吸附讲解

    Auto Layout压缩阻力及内容吸附讲解 本文为投稿文章,作者:梁炜V 在Auto Layout的使用中,有两个很重要的布局概念:Content Compression Resistance 和  ...

  9. 历年真题 未完成(Noip 2008 - Noip 2017)

    Noip 2008 :全部 Noip 2009 :全部 Noip 2010 :AK Noip 2011 :AK Noip 2012 : Vigenère 密码,国王游戏,开车旅行 Noip 2013 ...

  10. 路飞学城Python-Day59(第五模块记录)

    HTML部分 <!DOCTYPE html> <html lang="en"> <head> <!--head标签的主要作用:文档的头部主 ...