gpt4 book ai didi

scala - Spark mllib LinearRegression 奇怪的结果

转载 作者:行者123 更新时间:2023-11-30 08:44:11 24 4
gpt4 key购买 nike

从一个示例开始,我尝试进行线性回归。问题是我得到了错误的结果。作为拦截器我应该有: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 附录中数据以这种方式出现

最佳答案

您正在使用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)))
...

第一个特征是你的拦截。

关于scala - Spark mllib LinearRegression 奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33783187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com