Skip to content

Instantly share code, notes, and snippets.

@avibryant
Last active December 10, 2015 23:18
Show Gist options
  • Select an option

  • Save avibryant/4507988 to your computer and use it in GitHub Desktop.

Select an option

Save avibryant/4507988 to your computer and use it in GitHub Desktop.
//See http://en.wikipedia.org/wiki/Locality-sensitive_hashing#Random_projection
class RandomProjection(dimensions : Int, nBuckets : Int, bitsPerBucket : Int) {
val seed = 123456789
lazy val r = new scala.util.Random(seed)
lazy val buckets =
(1 to nBuckets).map{i =>
(1 to bitsPerBucket).map{j =>
(1 to dimensions).map{k =>
val f = r.nextDouble
if(r.nextBoolean)
f
else
f * -1
}
}
}
def apply(s : Seq[Double]) : Seq[Int] = {
buckets.map{bucket =>
bucket.zipWithIndex.map{
case (plane, i) =>
val dotProd = (plane,s).zipped.map{_*_}.sum
if(dotProd > 0)
2 << i
else
0
}.sum
}
}
}
class RandomProjection2(nBuckets : Int, bitsPerBucket : Int)
extends RandomProjection(2, nBuckets, bitsPerBucket) {
def apply(v1 : Double, v2 : Double) : Seq[Int] = apply(List(v1, v2))
}
class RandomProjection3(nBuckets : Int, bitsPerBucket : Int)
extends RandomProjection(3, nBuckets, bitsPerBucket) {
def apply(v1 : Double, v2 : Double, v3 : Double) : Seq[Int] = apply(List(v1, v2, v3))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment