4
votes

Using MLLib LinearRegressionWithSGD for the dummy data set (y, x1, x2) for y = (2*x1) + (3*x2) + 4 is producing wrong intercept and weights. Actual data used is,

x1  x2  y
1   0.1 6.3
2   0.2 8.6
3   0.3 10.9
4   0.6 13.8
5   0.8 16.4
6   1.2 19.6
7   1.6 22.8
8   1.9 25.7
9   2.1 28.3
10  2.4 31.2
11  2.7 34.1

I set the following input parameters and got the below model outputs [numIterations, step, miniBatchFraction, regParam] [intercept, [weights]]

  1. [5,9,0.6,5] = [2.36667135839938E13, weights:[1.708772545209758E14, 3.849548062850367E13] ]
  2. [2,default,default,default] = [-2495.5635231554793, weights:[-19122.41357929275,-4308.224496146531]]
  3. [5,default,default,default] = [2.875191315671051E8, weights: [2.2013802074495964E9,4.9593017130199933E8]]
  4. [20,default,default,default] = [-8.896967235537095E29, weights: [-6.811932001659158E30,-1.5346020624812824E30]]

Need to know,

  1. How do i get the correct intercept and weights [4, [2, 3]] for the above mentioned dummy data.
  2. Will tuning the step size help in convergence? I need to run this in a automated manner for several hundred variables, so not keen to do that.
  3. Should I scale the data? How will it help?

Below is the code used to generate these results.

object SciBenchTest {

  def main(args: Array[String]): Unit = run

  def run: Unit = {

    val sparkConf = new SparkConf().setAppName("SparkBench")
    val sc = new SparkContext(sparkConf)

    // Load and parse the dummy data (y, x1, x2) for y = (2*x1) + (3*x2) + 4
    // i.e. intercept should be 4, weights (2, 3)?
    val data = sc.textFile("data/dummy.csv")

    // LabeledPoint is (label, [features])
    val parsedData = data.map { line =>
      val parts = line.split(',')
      val label = parts(2).toDouble
      val features = Array(parts(0), parts(1)) map (_.toDouble)
      LabeledPoint(label, Vectors.dense(features))
    }
    //parsedData.collect().foreach(x => println(x));

    // Scale the features
    /*val scaler = new StandardScaler(withMean = true, withStd = true)
      .fit(parsedData.map(x => x.features))
    val scaledData = parsedData
      .map(x =>
      LabeledPoint(x.label,
        scaler.transform(Vectors.dense(x.features.toArray))))

    scaledData.collect().foreach(x => println(x));*/

    // Building the model: SGD = stochastic gradient descent
    val numIterations = 20 //5
    val step = 9.0 //9.0 //0.7
    val miniBatchFraction = 0.6 //0.7 //0.65 //0.7
    val regParam = 5.0 //3.0 //10.0
    //val model = LinearRegressionWithSGD.train(parsedData, numIterations, step) //scaledData

    val algorithm = new LinearRegressionWithSGD()       //train(parsedData, numIterations)
    algorithm.setIntercept(true)
    algorithm.optimizer
      //.setMiniBatchFraction(miniBatchFraction)
      .setNumIterations(numIterations)
      //.setStepSize(step)
      //.setGradient(new LeastSquaresGradient())
      //.setUpdater(new SquaredL2Updater()) //L1Updater //SimpleUpdater //SquaredL2Updater
      //.setRegParam(regParam)

    val model = algorithm.run(parsedData)

    println(s">>>> Model intercept: ${model.intercept}, weights: ${model.weights}")

    // Evaluate model on training examples
    val valuesAndPreds = parsedData.map { point =>
      val prediction = model.predict(point.features)
      (point.label, point.features, prediction)
    }
    // Print out features, actual and predicted values...
    valuesAndPreds.take(10).foreach({ case (v, f, p) =>
      println(s"Features: ${f}, Predicted: ${p}, Actual: ${v}")
    })
  }
}
2
Did you set step size? this is SGD-basedSean Owen

2 Answers

3
votes

As described in the documentation https://spark.apache.org/docs/1.0.2/mllib-optimization.html selecting the best step-size for SGD methods can often be delicate.

I would try with lover values, for example

// Build linear regression model
var regression = new LinearRegressionWithSGD().setIntercept(true)
regression.optimizer.setStepSize(0.001)
val model = regression.run(parsedData)
3
votes

Adding the stepsize did not help us much.

We used the following parameters to calculate the intercept/weights and loss and used the same to construct a linear regression model in order to predict our features. Thanks @selvinsource for pointing me in the correct direction.

  val data = sc.textFile("data/dummy.csv")

  // LabeledPoint is (label, [features])
  val parsedData = data.map { line =>
    val parts = line.split(',')
    val label = parts(2).toDouble
    val features = Array(parts(0), parts(1)) map (_.toDouble)
    (label, MLUtils.appendBias(Vectors.dense(features)))
  }.cache()

  val numCorrections = 5 //10//5//3
  val convergenceTol = 1e-4 //1e-4
  val maxNumIterations = 20 //20//100
  val regParam = 0.00001 //0.1//10.0

  val (weightsWithIntercept, loss) = LBFGS.runLBFGS(
    parsedData,
    new LeastSquaresGradient(),//LeastSquaresGradient
    new SquaredL2Updater(), //SquaredL2Updater(),SimpleUpdater(),L1Updater()
    numCorrections,
    convergenceTol,
    maxNumIterations,
    regParam,
    Vectors.dense(0.0, 0.0, 0.0))//initialWeightsWithIntercept)

  loss.foreach(println)

  val model = new LinearRegressionModel(
    Vectors.dense(weightsWithIntercept.toArray.slice(0, weightsWithIntercept.size - 1)),
    weightsWithIntercept(weightsWithIntercept.size - 1))

  println(s">>>> Model intercept: ${model.intercept}, weights: ${model.weights}")

  // Evaluate model on training examples
  val valuesAndPreds = parsedData.collect().map { point =>
    var prediction = model.predict(Vectors.dense(point._2.apply(0), point._2.apply(1)))
    (prediction, point._1)
  }

  // Print out features, actual and predicted values...
  valuesAndPreds.take(10).foreach({ case (v, f) =>
    println(s"Features: ${f}, Predicted: ${v}")//, Actual: ${v}")
  })