【问题标题】:Wrong intercept in Spark linear regressionSpark线性回归中的错误截距
【发布时间】:2016-08-31 02:43:51
【问题描述】:

我从 Spark 线性回归开始。我正在尝试将一条线拟合到线性数据集。似乎截距没有正确调整,或者我可能遗漏了一些东西..

使用拦截=假:

linear_model = LinearRegressionWithSGD.train(labeledData, iterations=100, step=0.0001, intercept=False)

这看起来很正常。但是当我使用 intercept=True 时:

linear_model = LinearRegressionWithSGD.train(labeledData, iterations=100, step=0.0001, intercept=True)

我在最后一种情况下得到的模型正是:

(weights=[0.0353471289751], intercept=1.0005127185289888)

我尝试过使用不同的数据集、步长和迭代,但模型总是收敛,截距约为 1

编辑 - 这是我正在使用的代码:

from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.regression import LinearRegressionWithSGD
import numpy as np
import matplotlib.pyplot as plt
from pyspark import SparkContext
sc = SparkContext("local", "regression")

# Generate data
SIZE = 300
SLOPE = 0.1
BASE = -30
NOISE = 10

x = np.arange(SIZE)
delta = np.random.uniform(-NOISE,NOISE, size=(SIZE,))
y = BASE + SLOPE*x + delta
data = zip(range(len(y)), y) # zip with index
dataRDD = sc.parallelize(data)

# Normalize data
# mean = np.mean(data)
# std = np.std(data)
# dataRDD = dataRDD.map(lambda r: (r[0], (float(r[1])-mean)/std))

labeledData = dataRDD.map(lambda r: LabeledPoint(float(r[1]), [float(r[0])]))

# Create linear model
linear_model = LinearRegressionWithSGD.train(labeledData, iterations=1000, step=0.0002, intercept=True, convergenceTol=0.000001)
print linear_model

true_vs_predicted = labeledData.map(lambda p: (p.label, linear_model.predict(p.features))).collect()

# PLOT
fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid()

y_real = [x[0] for x in true_vs_predicted] 
y_pred = [x[1] for x in true_vs_predicted] 

plt.plot(range(len(y_real)), y_real, 'o', markersize=5, c='b')
plt.plot(range(len(y_pred)), y_pred, 'o', markersize=5, c='r')

plt.show()

【问题讨论】:

  • 能否尝试对数据进行归一化,增加迭代次数,降低容差?另外,你用的是什么版本的apache spark?
  • 我使用的是 1.6.0 版本,我安装了新的 1.6.1 版本,没有任何变化。减小容差和增加迭代次数不会改变结果。当我对数据进行归一化时,回归线也从 1 开始。
  • (这会导致斜率为正的训练数据的回归线斜率为负)
  • 你能用机器学习测试这个吗?
  • 你能给我们数据集吗?

标签: apache-spark regression pyspark linear-regression


【解决方案1】:

这是因为迭代次数和步长都较小。结果,试验过程在达到局部最优之前就结束了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 2022-01-09
    • 2019-05-27
    • 2018-06-11
    • 2020-10-28
    • 1970-01-01
    相关资源
    最近更新 更多