Skip to content

Instantly share code, notes, and snippets.

@ryanlecompte
Last active December 19, 2015 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanlecompte/5942470 to your computer and use it in GitHub Desktop.
Save ryanlecompte/5942470 to your computer and use it in GitHub Desktop.
// Scala implementation of simple linear regression as implemented in Ruby
// in the blog post: http://www.sharethrough.com/2012/09/linear-regression-using-ruby/
import scala.io.Source
class SimpleLinearRegression(xs: Seq[Double], ys: Seq[Double]) {
require(xs.size == ys.size, "xs and ys must be same length")
def mean(values: Seq[Double]): Double = values.sum / values.size
def slope: Double = {
val xmean = mean(xs)
val ymean = mean(ys)
val numerator = xs.zip(ys).foldLeft(0.0) { case (sum, (x, y)) =>
sum + ((x - xmean) * (y - ymean))
}
val denominator = xs.foldLeft(0.0) { (sum, x) =>
sum + math.pow(x - xmean, 2)
}
numerator / denominator
}
def yIntercept: Double = mean(ys) - (slope * mean(xs))
}
object Runner {
def main(args: Array[String]) {
val (xs, ys) = Source.fromFile(args(0)).getLines.toSeq.drop(1).map { line =>
val Array(x, y) = line.split(',').map { _.toDouble }
(x, y)
}.unzip
val linearModel = new SimpleLinearRegression(xs, ys)
println("Model generated with")
println(s"Slope: ${linearModel.slope}")
println(s"Y-Intercept: ${linearModel.yIntercept}")
println("\n")
println("Estimated Linear Model:")
println(s"Y = ${linearModel.yIntercept} + (${linearModel.slope} * X)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment