我刚开始使用 ML 和 Apache Spark,所以我一直在尝试基于 Spark 示例的线性回归。除了示例中的样本外,我似乎无法为任何数据生成合适的模型,并且无论输入数据如何,截距始终为 0.0。
我已经准备了一个基于函数的简单训练数据集:
y = (2*x1) + (3*x2) + 4
即,我希望截距为 4,权重为 (2, 3)。
如果我对原始数据运行 LinearRegressionWithSGD.train(...),则模型为:
Model intercept: 0.0, weights: [NaN,NaN]
并且预测都是 NaN:
Features: [1.0,1.0], Predicted: NaN, Actual: 9.0
Features: [1.0,2.0], Predicted: NaN, Actual: 12.0
ETC
如果我先缩放数据,我会得到:
Model intercept: 0.0, weights: [17.407863391511754,2.463212481736855]
Features: [1.0,1.0], Predicted: 19.871075873248607, Actual: 9.0
Features: [1.0,2.0], Predicted: 22.334288354985464, Actual: 12.0
Features: [1.0,3.0], Predicted: 24.797500836722318, Actual: 15.0
ETC
要么我做错了什么,要么我不明白这个模型的输出应该是什么,所以有人可以建议我在这里可能出错的地方吗?
我的代码如下:
// 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/dummydata.txt")
// LabeledPoint is (label, [features])
val parsedData = data.map { line =>
val parts = line.split(',')
val label = parts(0).toDouble
val features = Array(parts(1), parts(2)) map (_.toDouble)
LabeledPoint(label, Vectors.dense(features))
}
// 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))))
// Building the model: SGD = stochastic gradient descent
val numIterations = 1000
val step = 0.2
val model = LinearRegressionWithSGD.train(scaledData, numIterations, step)
println(s">>>> Model intercept: ${model.intercept}, weights: ${model.weights}")`
// Evaluate model on training examples
val valuesAndPreds = scaledData.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}")})