Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ixaxaar
Last active March 2, 2017 09:17
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 ixaxaar/ef793e4c3d25f2b5edee5fac4bdd843b to your computer and use it in GitHub Desktop.
Save ixaxaar/ef793e4c3d25f2b5edee5fac4bdd843b to your computer and use it in GitHub Desktop.
Beam over permutations, find the best possible sequence given a perplexity function
def beamPermute[T](
data: List[T],
perplexityFn: List[T] => Double,
startNode: T,
beamSize: Int = 10,
beamWindow: Int = 3
): List[(List[T], Double)] = {
var candidates = List((List(startNode), 0d))
// var leftOver = data.to[ListBuffer]
data.foreach{ _ =>
candidates = candidates.map{
case (c:List[T], p:Double) =>
var now = data.to[ListBuffer]
c.foreach{ x => now -= x }
now.map{ d =>
val x = (c :+ d).takeRight(beamWindow)
((c :+ d), perplexityFn(x))
}
}.toList.flatten
.sortBy{ x => -x._2 }
.take(beamSize)
}
candidates
}
def beamTest:Unit = {
val testData = List("999999999", "22", "55555", "333", "666666", "4444", "7777777", "88888888")
val res = beamPermute[String](
testData,
(x:List[String]) => x.mkString(" ").length.toDouble,
"1",
beamSize=testData.length,
beamWindow=testData.length
)
res
res.map{ r => println(r._1.mkString(" ") +"\t\t->\t"+r._2) }
}
@ixaxaar
Copy link
Author

ixaxaar commented Mar 2, 2017

@ beamTest
1 999999999 88888888 7777777 666666 55555 4444 333 22           ->      51.0
1 88888888 999999999 7777777 666666 55555 4444 333 22           ->      51.0
1 999999999 7777777 88888888 666666 55555 4444 333 22           ->      51.0
1 7777777 999999999 88888888 666666 55555 4444 333 22           ->      51.0
1 88888888 7777777 999999999 666666 55555 4444 333 22           ->      51.0
1 7777777 88888888 999999999 666666 55555 4444 333 22           ->      51.0
1 999999999 88888888 666666 7777777 55555 4444 333 22           ->      51.0
1 88888888 999999999 666666 7777777 55555 4444 333 22           ->      51.0

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