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. Core篇——初探IdentityServer4(OpenID Connect模式)

    Core篇——初探IdentityServer4(OpenID Connect客户端验证) 目录 1.Oauth2协议授权码模式介绍2.IdentityServer4的OpenID Connect客户 ...

  2. ansible usually

    链接地址:https://my.oschina.net/kangvcar/blog/1830155

  3. Sublime Text3 插件记录

    插件官网 其他插件安装之前,先安装 Package Control: 快捷键Ctrl+`或View > Show Console打开控制台. 输入以下 Python 代码,回车. import ...

  4. outlook 2010 搜索不到邮件

    打开outlook 2010 文件, 选项, 加载项, 转到 windows search eamil indexer(打勾) 关闭outlook 控制面板, 索引选项, 高级, 重建索引

  5. Kinect+OpenNI+OpenCV使用

    关于OpenNI,已经可以使用2.0,可以不再使用PrimeSense: 这里的是转载其他人的 OpenCV系列: 原文:http://blog.csdn.net/chenxin_130/articl ...

  6. java学习笔记4——返回值

    这个简单,返回值就是计算结果. 打个比方:个表格中我只要结果,不要经过,这个返回值就是结果.这个过程就是函数. 另外还有一个函数套用一个函数,被套用的函数的结果作为一个返回值给套用的外层函使用.比如: ...

  7. Virtualbox guest in KDE Neon

    在最新版的KDE Neon里面装VirtualBox客户端工具,折腾了好久,时间紧的时候不得已用共享U盘的方法将就. 之前要么装完关机按钮点了没反应,要么重启进桌面后任务栏消失,再就是进去之后复制东西 ...

  8. (转)基于MVC4+EasyUI的Web开发框架经验总结(4)--使用图表控件Highcharts

    http://www.cnblogs.com/wuhuacong/p/3736564.html 在我们做各种应用的时候,我们可能都会使用到图表统计,以前接触过一些不同的图表控件,在无意中发现了图表控件 ...

  9. javase 继承练习

    package xuexi; 父级 public class Fu { int num=0; public void eat() { System.out.println("父亲在吃饭&qu ...

  10. How many integers can you find HDU - 1796_容斥计数

    Code: #include<cstdio> using namespace std; typedef long long ll; const int R=13; ll a[R]; ll ...