Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.95 KB | None | 0 0
  1. object Utils {
  2.   //random
  3.   val r = util.Random
  4.   //read data
  5.   val data = io.Source.fromFile ("data/data.dat").getLines.toList.map
  6.                   {_ split "\t"} map(_.map(_.toInt))
  7.   val ocrData = io.Source.fromFile ("data/ocr.dat").getLines.toList.map
  8.                   {_ split "\t"} map {a => ((a(0).toInt, a(1)(0)), a(2).toDouble) } toMap
  9.   val transData = io.Source.fromFile ("data/trans.dat").getLines.toList.map
  10.                   {_ split "\t"} map {a => ((a(0)(0), a(1)(0)), a(2).toDouble) } toMap
  11. }
  12.  
  13. //variables
  14.   class Variable { var value = -1 }
  15.   class CharVariable(var value: Char = 'z',
  16.                      val possibleValues: Array[Char] = Array('e','t','a','o','i','n','s','h','r','d')) extends Variable {
  17.     def randVal = value = possibleValues(Utils.r.nextInt(possibleValues.length))
  18.   }
  19.  
  20.   class IntVariable(var value: Int = -1, val possibleValues: Array[Int] = 1 to 999 toArray) extends Variable{
  21.     def randVal = value = possibleValues(Utils.r.nextInt(possibleValues.length))
  22.   }
  23.  
  24.   class LetterVariable extends CharVariable
  25.   class ImageVariable extends IntVariable
  26.  
  27. // model stuff
  28.   abstract class Template
  29.   class OCRTemplate extends Template {
  30.     def unroll[t1, t2](v1: t1, v2: t2) = {
  31.         new Factor[t1,t2](v1, v2, {(i: t1, l:t2) => Utils.ocrData((i.value, l.value))})
  32.     }
  33.   }
  34.  
  35.   // a factor scores the two variables it's connected to
  36.   class Factor[T1 <: Variable,T2 <: Variable] (v1: T1, v2: T2, scoreFn: (T1,T2) => Double) {
  37.      def score = scoreFn(v1, v2)
  38.   }
  39.  
  40.   // a Model just holds templates
  41.   class Model {
  42.     var templates: List[Template] = Nil
  43.     def +(t: Template) { templates = t :: templates }
  44.   }
  45.  
  46. //Inference
  47.   class ExhaustiveInferencer(model: Model) {
  48.     var norm = 1.0
  49.  
  50.     def infer(images: List[ImageVariable], words: List[LetterVariable]) {
  51.         val factors = for(t <- model.templates; (i,l) <- images zip words) yield t.unroll(i,l)
  52.         (factors.product) / norm
  53.     }
  54.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement