那是因为您试图混合来自两个不同库的功能:LinearRegressionWithSGD 来自 pyspark.mllib(即旧的 RDD-based API),而 LinearRegression 和 ParamGridBuilder 都来自 pyspark.ml(新的,dataframe-based API)。
确实,在您引用的documentation 中的代码 sn-p 前几行(顺便说一句,将来最好也提供一个链接),您会找到以下行:
from pyspark.ml.regression import LinearRegression
而对于LinearRegressionWithSGD,你使用了something like:
from pyspark.mllib.regression import LabeledPoint, LinearRegressionWithSGD, LinearRegressionModel
这两个库不兼容:pyspark.mllib 将LabeledPoint 的RDD 作为输入,这与pyspark.ml 中使用的数据帧不兼容;由于ParamGridBuilder 是后者的一部分,它只能用于数据帧,不能用于pyspark.mllib 中包含的算法(请查看上面提供的文档链接)。
此外,请记住 LinearRegressionWithSGD 在 Spark 2 中是 deprecated:
注意:在 2.0.0 中已弃用。使用 ml.classification.LogisticRegression 或 LogisticRegressionWithLBFGS。
更新:感谢@rvisio 在下方的评论,我们现在知道,虽然undocumented,实际上可以在@987654346 中使用solver='sgd' 代替LinearRegression @;这是一个简短的例子adapted from the docs:
spark.version
# u'2.2.0'
from pyspark.ml.linalg import Vectors
from pyspark.ml.regression import LinearRegression
df = spark.createDataFrame([
(1.0, 2.0, Vectors.dense(1.0)),
(0.0, 2.0, Vectors.sparse(1, [], []))], ["label", "weight", "features"])
lr = LinearRegression(maxIter=5, regParam=0.0, solver="sgd", weightCol="weight") # solver='sgd'
model = lr.fit(df) # works OK
lr.getSolver()
# 'sgd'