Skip to content

Instantly share code, notes, and snippets.

@jamesthompson
Created May 6, 2013 18:41
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 jamesthompson/5527138 to your computer and use it in GitHub Desktop.
Save jamesthompson/5527138 to your computer and use it in GitHub Desktop.
Linear Regression
implicit class LinearRegression[NA: Numeric, NB: Numeric, M[+_]](pts: (M[NA], M[NB])) {
def getVector[A: Numeric](in: M[A]) : Vector[Double] = {
val n = implicitly[Numeric[A]]
in.asInstanceOf[TraversableLike[A, Traversable[A]]].map(n.toDouble(_)).toVector
}
def lnfit = {
val xpts = getVector(pts._1)
val ypts = getVector(pts._2)
xpts.isEmpty match {
case true => None
case false => {
val length = xpts.length
val xbar = xpts.sum / length
val ybar = ypts.sum / length
val xxbar = xpts.map(d => sqr(d - xbar)).sum
val yybar = ypts.map(d => sqr(d - ybar)).sum
val data = xpts.zip(ypts)
val xybar = data.map(d => (d._1 - xbar) * (d._2 - ybar)).sum
val m = xybar / xxbar
val c = ybar - (m * xbar)
val out = for(d <- data) yield {
val fit = m * d._1 + c
(sqr(fit - d._2), sqr(fit - ybar))
}
val rss = out.map(_._1).sum
val ssr = out.map(_._2).sum
val rsquared = ssr / yybar
val svar = rss / (length - 2).toDouble
val stErrGradient = svar / xxbar
val stErrIntercept = (svar / data.length) + (sqr(xbar) * stErrGradient)
Some(LinearFitResult(m, c, rsquared, math.sqrt(stErrGradient), math.sqrt(stErrIntercept)))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment