Created
May 6, 2013 18:41
-
-
Save jamesthompson/5527138 to your computer and use it in GitHub Desktop.
Linear Regression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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