Skip to content

Instantly share code, notes, and snippets.

@krishnanraman
Created December 19, 2012 01:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krishnanraman/4333595 to your computer and use it in GitHub Desktop.
Save krishnanraman/4333595 to your computer and use it in GitHub Desktop.
rsq in scala repl
val data = List((1,2),(2,3),(3,4),(4,5),(5,7))
def line(x:Int) = x+1 // guess based on data
def mean(xy:List[(Int,Int)]) = xy.map(a=>a._2).sum/(0.0+xy.size) // average the y's
def sstot(xy:List[(Int,Int)]) = { val mu = mean(data); xy.map(a=>(a._2-mu)*(a._2-mu)).sum } // total sum of squares
def sserr(xy:List[(Int,Int)]) = { xy.map(a=>(a._2-line(a._1))*(a._2-line(a._1))).sum } // sum of squares of residuals
def rsq(xy:List[(Int,Int)]) = 1.0 - sserr(xy)/sstot(xy)
scala> rsq(data)
res5: Double = 0.9324324324324325 // 93% fit, not bad for a guess.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment