How to convert from org.apache.spark.mllib.linalg.VectorUDT to ml.linalg.VectorUDT

风格不统一 提交于 2019-12-07 03:13:32

问题


I am using Spark cluster 2.0 and I would like to convert a vector from org.apache.spark.mllib.linalg.VectorUDT to org.apache.spark.ml.linalg.VectorUDT.

# Import LinearRegression class
from pyspark.ml.regression import LinearRegression

# Define LinearRegression algorithm
lr = LinearRegression()

modelA = lr.fit(data, {lr.regParam:0.0})

Error:

u'requirement failed: Column features must be of type org.apache.spark.ml.linalg.VectorUDT@3bfc3ba7 but was actually org.apache.spark.mllib.linalg.VectorUDT@f71b0bce.'

Any thoughts how would I do this conversion between vector types.

Thanks a lot.


回答1:


In PySpark you'll need an or map over RDD. Let's use the first option. First a couple of imports:

from pyspark.ml.linalg import VectorUDT
from pyspark.sql.functions import udf

and a function:

as_ml = udf(lambda v: v.asML() if v is not None else None, VectorUDT())

With example data:

from pyspark.mllib.linalg import Vectors as MLLibVectors

df = sc.parallelize([
    (MLLibVectors.sparse(4, [0, 2], [1, -1]), ),
    (MLLibVectors.dense([1, 2, 3, 4]), )
]).toDF(["features"])

result = df.withColumn("features", as_ml("features"))

The result is

+--------------------+
|            features|
+--------------------+
|(4,[0,2],[1.0,-1.0])|
|   [1.0,2.0,3.0,4.0]|
+--------------------+


来源:https://stackoverflow.com/questions/41127020/how-to-convert-from-org-apache-spark-mllib-linalg-vectorudt-to-ml-linalg-vectoru

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!