Skip to content

Instantly share code, notes, and snippets.

@benoitdescamps
Created May 11, 2018 21:44
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 benoitdescamps/034fc498c069f2521d175c4232a6df64 to your computer and use it in GitHub Desktop.
Save benoitdescamps/034fc498c069f2521d175c4232a6df64 to your computer and use it in GitHub Desktop.
code snippet for Hyperparameters (part II): Random Search on Spark
class RandomGridBuilder(n: Int) {
private val paramDistr = mutable.Map.empty[Param[_],Any]
def addDistr[T](param: Param[T], distr: Any ): this.type = distr match {
case _ : Rand[_] => {paramDistr.put(param, distr)
this}
case _ : Array[_] => { paramDistr.put(param, distr)
this}
case _ => throw new NotImplementedError("Distribution should be of type breeze.stats.distributions.Rand or an Array")
}
/**
* Similar to GridSearch
* Builds and returns all combinations of parameters specified by the param grid.
*/
def build(): Array[ParamMap] = {
var paramMaps = (1 to n).map( _ => new ParamMap())
paramDistr.foreach{
case (param, distribution) =>
val values = distribution match {
case d :Rand[_] => {
paramMaps.map(_.put(param.asInstanceOf[Param[Any]],d.sample()))
}
case d: Array[_] => {
val r = scala.util.Random
paramMaps.map(_.put(param.asInstanceOf[Param[Any]], d(r.nextInt(d.length))) )
}
}
}
paramMaps.toArray
}
}
@songquanhe-gitstudy
Copy link

songquanhe-gitstudy commented Aug 2, 2019

pretty good!

@stefan005
Copy link

very helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment