Skip to content

Instantly share code, notes, and snippets.

View actsasgeek's full-sized avatar

Stephyn Butcher actsasgeek

View GitHub Profile
@actsasgeek
actsasgeek / nearest_neighbor_spec_v1.scala
Created June 9, 2011 02:29
The spec for NearestNeighbor
class NearestNeighborSpec extends Spec with ShouldMatchers {
describe( "A Nearest Neighbor classifier") {
val library = List(
new Instance( List( 3.0, 3.0), Some( "A")),
new Instance( List( 4.0, 2.0), Some( "A")),
new Instance( List( 2.0, 2.0), Some( "B"))
)
val nearestNeighbor = new NearestNeighbor( library)
it( "can find the 1st closest example in the library to a query") {
val query = new Instance( List( 0.0, 0.0))
@actsasgeek
actsasgeek / nearest_neighbor_v4.scala
Created June 9, 2011 02:11
The NearestNeighbor#classify() method.
class NearestNeighbor( library: List[Instance]) {
def classify( query: Instance): Instance = {
val distanceMeasurements = library.map( example => (query.distanceTo( example), example))
val sortedDistanceMeasurements = distanceMeasurements.sortWith(( e1, e2) => ( e1._1 - e2._1) < 0)
val nearestExample = sortedDistanceMeasurements.head._2
query.assignClassLabel( nearestExample.classLabel)
}
}
@actsasgeek
actsasgeek / nearest_neighbor_v3.scala
Created June 8, 2011 21:29
The distanceTo() method of Instance.
class Instance( val featureValues: List[Double], classLabel: Option[String] = None) {
def assignClassLabel( assignedClassLabel: Option[String]): Instance = {
new Instance( featureValues, assignedClassLabel)
}
def distanceTo( otherInstance: Instance): Double = {
euclideanDistance( featureValues, otherInstance.featureValues)
}
def euclideanDistance( thisVector: List[ Double], thatVector: List[ Double]): Double = {
@actsasgeek
actsasgeek / nearest_neighbor_v2.scala
Created June 8, 2011 19:46
Improved version of the Nearest Neighbor "walking skeleton"
class Instance( featureValues: List[Double], classLabel: Option[String] = None) {
def assignClassLabel( assignedClassLabel: Option[String]): Instance = {
new Instance( featureValues, assignedClassLabel)
}
override def toString(): String = {
"<'"+classLabel.getOrElse( "None")+"' is ["+featureValues.mkString( ", ")+"]>"
}
}
@actsasgeek
actsasgeek / nearest_neighbor_v1.scala
Created June 8, 2011 19:04
"Walking skeleton" of the nearest neighbor algorithm.
class Instance( featureValues: List[Double], var classLabel: String) {
}
class NearestNeighbor( library: List[Instance]) {
def classify( query: Instance) {
query.classLabel = "unknown"
}
}
object NearestNeighbor {