如何将 Hive table 转换为 MLlib LabeledPoint?
How to convert a Hive table into a MLlib LabeledPoint?
我已经使用 Impala 构建了一个包含目标和数百个特征的 table。
我想使用 Spark MLlib 来训练模型。
我了解到,为了通过 Spark 运行 分布式监督模型,数据需要采用多种格式之一。 LabeledPoint 对我来说似乎是最直观的。
使用 PySpark 将 Hive table 转换为标记点的最有效方法是什么?
这个问题的最佳解决方案可能是使用 ml 库及其模型,因为它们直接作用于数据帧。
但是,ml api 尚未达到与 mllib 相同的功能,可能缺少您需要的东西。因此,我们通过在配置单元上下文检索到的数据帧上调用映射来解决工作流中的这个问题。
from pyspark import SparkContext, HiveContext
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.classification import LogisticRegressionWithLBFGS
table_name = "MyTable"
target_col = "MyTargetCol"
sc = SparkContext()
hc = HiveContext(sc)
# get the table from the hive context
df = hc.table(table_name)
# reorder columns so that we know the index of the target column
df = df.select(target_col, *[col for col in dataframe.columns if col != target_col])
# map through the data to produce an rdd of labeled points
rdd_of_labeled_points = df.map(lambda row: LabeledPoint(row[0], row[1:]))
# use the rdd as input to a model
model = LogisticRegressionWithLBFGS.train(rdd_of_labeled_points)
请记住,任何时候使用 python 进行映射时,都需要将数据从 JVM 编组到 Python VM,因此性能会受到影响。我们发现使用地图对我们数据的性能影响可以忽略不计,但您的里程可能会有所不同。
我已经使用 Impala 构建了一个包含目标和数百个特征的 table。 我想使用 Spark MLlib 来训练模型。 我了解到,为了通过 Spark 运行 分布式监督模型,数据需要采用多种格式之一。 LabeledPoint 对我来说似乎是最直观的。 使用 PySpark 将 Hive table 转换为标记点的最有效方法是什么?
这个问题的最佳解决方案可能是使用 ml 库及其模型,因为它们直接作用于数据帧。
但是,ml api 尚未达到与 mllib 相同的功能,可能缺少您需要的东西。因此,我们通过在配置单元上下文检索到的数据帧上调用映射来解决工作流中的这个问题。
from pyspark import SparkContext, HiveContext
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.classification import LogisticRegressionWithLBFGS
table_name = "MyTable"
target_col = "MyTargetCol"
sc = SparkContext()
hc = HiveContext(sc)
# get the table from the hive context
df = hc.table(table_name)
# reorder columns so that we know the index of the target column
df = df.select(target_col, *[col for col in dataframe.columns if col != target_col])
# map through the data to produce an rdd of labeled points
rdd_of_labeled_points = df.map(lambda row: LabeledPoint(row[0], row[1:]))
# use the rdd as input to a model
model = LogisticRegressionWithLBFGS.train(rdd_of_labeled_points)
请记住,任何时候使用 python 进行映射时,都需要将数据从 JVM 编组到 Python VM,因此性能会受到影响。我们发现使用地图对我们数据的性能影响可以忽略不计,但您的里程可能会有所不同。