【问题标题】:Why is linear regression wrong for pyspark?为什么pyspark的线性回归错误?
【发布时间】:2019-07-20 23:19:18
【问题描述】:

我一直得到错误的答案,所以我尝试了一些非常非常基本的东西,但它仍然是错误的。

input file:
1 1:1
2 1:2
3 1:3
4 1:4
from pyspark.ml.regression import LinearRegression

# Load training data
training = spark.read.format("libsvm").load("stupid.txt")

lr = LinearRegression(maxIter=100, regParam=0.3, loss='squaredError')

# Fit the model
lrModel = lr.fit(training)

# Print the coefficients and intercept for linear regression
print("Coefficients: %s" % str(lrModel.coefficients))
print("Intercept: %s" % str(lrModel.intercept))

# Summarize the model over the training set and print out some metrics
trainingSummary = lrModel.summary
print("numIterations: %d" % trainingSummary.totalIterations)
print("objectiveHistory: %s" % str(trainingSummary.objectiveHistory))
trainingSummary.residuals.show()
print("RMSE: %f" % trainingSummary.rootMeanSquaredError)
print("r2: %f" % trainingSummary.r2)

应该得到系数 [1] 并截取 0。 反而得到了

Coefficients: [0.7884394856681294]
Intercept: 0.52890128583

【问题讨论】:

  • 您能否打印训练数据框,以确保它以您期望的方式读取文件?我想知道它是否没有使用正确的列作为标签。
  • 我越看它,似乎它试图为给定的输入 [1,2,3,4] 输出值 1。你的意思是让你的标签列每次都是 1 吗?
  • @BobSwain 和我上面粘贴的完全一样,就是文件“stupid.txt”。请注意,格式是必须的,1:表示列。

标签: pyspark linear-regression


【解决方案1】:

看起来问题出在您使用的 regParam 参数上。如果我将它设置为 0 运行它,这会导致正常的 OLS 发生,我们会得到预期的输出:

代码:

from pyspark.ml.regression import LinearRegression

from pyspark.ml.linalg import Vectors
training = spark.createDataFrame([
    (1.0, Vectors.dense(1.0)),
    (2.0, Vectors.dense(2.0)),
    (3.0, Vectors.dense(3.0)),
    (4.0, Vectors.dense(4.0))], ["label", "features"])

lr = LinearRegression(maxIter=100, regParam=0, loss='squaredError')

# Fit the model
lrModel = lr.fit(training)

# Print the coefficients and intercept for linear regression
print("Coefficients: %s" % str(lrModel.coefficients))
print("Intercept: %s" % str(lrModel.intercept))

# Summarize the model over the training set and print out some metrics
trainingSummary = lrModel.summary
print("numIterations: %d" % trainingSummary.totalIterations)
print("objectiveHistory: %s" % str(trainingSummary.objectiveHistory))
trainingSummary.residuals.show()
print("RMSE: %f" % trainingSummary.rootMeanSquaredError)
print("r2: %f" % trainingSummary.r2)

输出:

Coefficients: [1.0]
Intercept: 0.0
numIterations: 1
objectiveHistory: [0.0]
+---------+
|residuals|
+---------+
|      0.0|
|      0.0|
|      0.0|
|      0.0|
+---------+

RMSE: 0.000000
r2: 1.000000

regParam > 0 似乎被用作 L2 正则化项,并阻止模型执行正常的 OLS 过程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 2021-08-01
    相关资源
    最近更新 更多