我用python中的tensorflow训练了一个DNN分类器模型。现在我想把它加载到pyspark中,并使用这个模型来预测每个RDD记录的性别。首先按照训练模型构建张量流图,然后加载训练模型并尝试预测RDD的每一行:
"""
code to generate the tensorflow graph omitted
"""
with tf.Session(graph=graph) as sess:
# load the trained model
saver.restore(sess, "./nonClass_gender")
# lib is the RDD, each Row has the form of Row(key = ..., values = ..., indcies =..., shape = ...)
predictions_1 = lib.map(lambda e: Row(key = e["key"],
prob = y_proba.eval(feed_dict={values: e["values"],
indices: e["indices"], shape: [1,2318]})))
predictions_1.take(5)
注意,在RDD中,每一行的形式都是row(key=…,values=…,indices=…,shape=…)。值、指数和形状与此答案中的值、指数和密集形状相等: Use coo_matrix in TensorFlow。它们用于生成sparsetenservalue。不同的是,在我的代码中,每行将生成一个sparsetenservalue。在
那么我有以下错误:
^{pr2}$在上面的代码中,如果我将prob = y_proba.eval(feed_dict={values: e["values"], indices: e["indices"], shape: [1,2318]})))
更改为一个python定义的函数,比如proba = test(e["values"],e["indices"], [1,2318])
,它就可以工作了。另外,如果我在python中使用y_proba.eval
(而不是在RDD映射中),它也可以工作。在
感谢@user8371915,从他的回答和这个相关主题得到启发:Transform map to mapPartition using pyspark,我可以完成任务。解决方案的关键是在mapPartitions使用的函数内部而不是函数外部构建tensoflow图。以下是有效的代码:
SparkFiles
)。在重写器
与
mapPartitions
一起使用相关问题 更多 >
编程相关推荐