Last active
August 29, 2015 14:24
-
-
Save tribhuvanesh/8babf71a6d982bfd466d to your computer and use it in GitHub Desktop.
Factorie decode using MPLP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Construct Factor graph and run MAP | |
*/ | |
def decode(unaryPot: DenseMatrix[Double], | |
pairwisePot: DenseMatrix[Double], | |
adj: AdjacencyList): Array[Label] = { | |
val nSuperpixels = unaryPot.cols | |
val nClasses = unaryPot.rows | |
assert(nClasses == NUM_CLASSES) | |
assert(pairwisePot.rows == NUM_CLASSES) | |
object PixelDomain extends DiscreteDomain(nClasses) | |
class Pixel(i: Int) extends DiscreteVariable(i) { | |
def domain = PixelDomain | |
} | |
def getUnaryFactor(yi: Pixel, idx: Int): Factor = { | |
new Factor1(yi) { | |
def score(k: Pixel#Value) = -unaryPot(k.intValue, idx) | |
} | |
} | |
def getPairwiseFactor(yi: Pixel, yj: Pixel): Factor = { | |
new Factor2(yi, yj) { | |
def score(i: Pixel#Value, j: Pixel#Value) = pairwisePot(i.intValue, j.intValue) | |
} | |
} | |
val pixelSeq: IndexedSeq[Pixel] = | |
(0 until nSuperpixels).map(x => new Pixel(12)) | |
val unaryFactors: IndexedSeq[Factor] = | |
(0 until nSuperpixels).map { | |
case idx => | |
getUnaryFactor(pixelSeq(idx), idx) | |
} | |
val pairwiseFactors = | |
(0 until nSuperpixels).flatMap { | |
case thisIdx => | |
val thisFactors = new ArrayBuffer[Factor] | |
adj(thisIdx).foreach { | |
case nextIdx => | |
thisFactors ++= | |
getPairwiseFactor(pixelSeq(thisIdx), pixelSeq(nextIdx)) | |
} | |
thisFactors | |
} | |
val model = new ItemizedModel | |
model ++= unaryFactors | |
model ++= pairwiseFactors | |
val maxIterations = 300 | |
val maximizer = new MaximizeByMPLP(maxIterations) | |
val assgn = maximizer.infer(pixelSeq, model).mapAssignment | |
val mapLabels: Array[Label] = (0 until nSuperpixels).map { | |
idx => | |
assgn(pixelSeq(idx)).intValue | |
}.toArray | |
mapLabels | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment