【问题标题】:Spark mllib LinearRegression weird resultSpark mllib LinearRegression 奇怪的结果
【发布时间】:2016-02-20 08:57:42
【问题描述】:

从我试图做线性回归的一个例子开始。 问题是我得到了错误的结果。作为拦截器,我应该有:2.2.

我尝试添加在另一篇文章中找到的 .optimizer.setStepSize(0.1),但仍然得到一个奇怪的结果。 建议?

这是一组数据

1,2
2,4
3,5
4,4
5,5

代码:

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.regression.LinearRegressionModel
import org.apache.spark.mllib.regression.LinearRegressionWithSGD
import org.apache.spark.mllib.linalg.Vectors

object linearReg {
  def main(args: Array[String]) {
    StreamingExamples.setStreamingLogLevels()
    val sparkConf = new SparkConf().setAppName("linearReg").setMaster("local")
    val sc=new SparkContext(sparkConf)
    // Load and parse the data
    val data = sc.textFile("/home/daniele/dati.data")
    val parsedData = data.map { line =>
      val parts = line.split(',')
      LabeledPoint(parts(0).toDouble, Vectors.dense(Array(1.0)++parts(1).split(' ').map(_.toDouble)))
    }.cache()
    parsedData.collect().foreach(println)
    // Building the model
    val numIterations = 1000
    val model = LinearRegressionWithSGD.train(parsedData, numIterations)
    println("Interceptor:"+model.intercept)
    // Evaluate model on training examples and compute training error
    val valuesAndPreds = parsedData.map { point =>
      val prediction = model.predict(point.features)
      (point.label, prediction)
    }
    valuesAndPreds.collect().foreach(println)
    val MSE = valuesAndPreds.map { case (v, p) => math.pow((v - p), 2) }.mean()
    println("training Mean Squared Error = " + MSE)

    // Save and load model
    model.save(sc, "myModelPath")
    val sameModel = LinearRegressionModel.load(sc, "myModelPath")
  }
}

结果:

weights: [-4.062601003207354E25], intercept: -9.484399253945647E24

更新 - 使用 .train 方法 - 添加了 1.0 作为拦截的附录。 1.0附录数据以这种方式出现

【问题讨论】:

    标签: scala apache-spark machine-learning linear-regression apache-spark-mllib


    【解决方案1】:

    您正在使用run,这意味着您传入的数据被解释为“配置参数”,而不是要回归的特征。

    docs 包含训练然后运行模型的良好示例:

    //note the "train" instead of "run"
    val numIterations = 1000
    val model =  LinearRegressionWithSGD.train(parsedData, numIterations)
    

    结果是更准确的重量:

    scala> model.weights
    res4: org.apache.spark.mllib.linalg.Vector = [0.7674418604651163]
    

    如果要添加截距,只需将 1.0 值作为特征放入密集向量中。修改您的示例代码:

    ...
    LabeledPoint(Parts(0).toDouble, Vectors.dense(Array(1.0) ++ parts(1).split(' ').map(_.toDouble)))
    ...
    

    第一个功能就是你的拦截。

    【讨论】:

    • 已修改以符合您的要求。
    • 它给了我 java.lang.NumberFormatException: empty String
    • 这来自您的解析代码,而不是我针对 1.0 作为您的拦截功能所做的附录...
    • 是的,这是我的问题,抱歉。无论如何,我仍然得到 0 作为拦截。我把我的结果放在主帖上。
    • 模型中将不再有显式截距,您的第一个特征将是 1.0,即截距,而您的原始特征将是第二个。这是人工创建拦截的常见 ML 技巧。
    猜你喜欢
    • 2016-01-19
    • 2016-01-24
    • 2016-11-19
    • 1970-01-01
    • 2016-08-18
    • 2016-11-28
    • 2012-12-16
    • 2012-12-06
    相关资源
    最近更新 更多