This repository has been archived by the owner on Feb 19, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 82
/
SignatureLexicon.scala
49 lines (38 loc) · 1.58 KB
/
SignatureLexicon.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package epic.lexicon
import breeze.linalg._
import breeze.util.Index
import epic.features.EnglishWordClassGenerator
import breeze.util.SerializableLogging
/**
* A lexicon that backs off to a signature when it decides which tags to allow.
*/
@SerialVersionUID(1L)
class SignatureLexicon[L, W](val labelIndex: Index[L], allowed: Map[W, Set[Int]], signature: W => W) extends Lexicon[L, W] with Serializable with SerializableLogging {
override def morePermissive: Lexicon[L, W] = {
new SignatureLexicon(labelIndex, Map.empty[W, Set[Int]].withDefaultValue(allTags), signature)
}
val allTags = allowed.values.reduce(_ ++ _)
def anchor(w: IndexedSeq[W]):Anchoring = new Anchoring {
def words: IndexedSeq[W] = w
val sigs = w.map(x => allowed.get(x).orElse(allowed.get(signature(x))).getOrElse{
logger.warn(s"unknown word signature ${signature(x)} for word $x ")
allTags
})
def allowedTags(pos: Int): Set[Int] = sigs(pos)
def length: Int = words.length
}
}
object SignatureLexicon {
def fromCounts[L, W](labelIndex: Index[L],
counts: Counter2[L, W, Double],
signatureThreshold: Double = 5,
sig: W=>W = EnglishWordClassGenerator) = {
val totalCounts = sum(counts(::, *))
val map = collection.mutable.Map[W, Set[Int]]().withDefaultValue(Set.empty)
for( (w, total) <- totalCounts.iterator) {
val dest = if (total >= signatureThreshold) w else sig(w)
map(dest) ++= counts(::, w).keysIterator.map(labelIndex)
}
new SignatureLexicon(labelIndex, map.toMap, sig)
}
}