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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
|
package com.wcohen.ss.abbvGapsHmm;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Dana Movshovitz-Attias
*/
public class AlignmentPredictionModel {
public static final String SEPARATOR = "#_#";
public static String _trainingDataDir;
public static String _trueLabelsFile;
public static String _trainingCorpusFile;
private AbbvGapsHMM _abbvHmm = null;
public AlignmentPredictionModel() throws IOException{
_abbvHmm = new AbbvGapsHMM();
setTrainingDataDir("train/");
}
public void setTrainingDataDir(String trainDir) {
_trainingDataDir = trainDir;
_trueLabelsFile = _trainingDataDir+"abbvAlign_pairs.txt";
_trainingCorpusFile = _trainingDataDir+"abbvAlign_corpus.txt";
}
public void setTfIdfData(String dataFile) throws IOException{
_abbvHmm.setTfIdfData(dataFile);
}
public void setModelParamsFile(String paramFilename){
_abbvHmm.setParamFile(paramFilename);
}
public void setModelParamsFile(){
setModelParamsFile("hmmModelParams.txt");
}
public static ArrayList<Map<String, String>> loadLabels(String labelsFile) {
if(labelsFile == null)
return null;
ArrayList<Map<String, String>> labels = null;
try{
BufferedReader fi = new BufferedReader(new FileReader(labelsFile));
labels = new ArrayList<Map<String, String>>();
String docLine;
while( (docLine = fi.readLine()) != null){
Map<String, String> docAcronymMap = new HashMap<String, String>();
String acronyms[] = docLine.split(SEPARATOR);
for (int i = 0; i < acronyms.length; i++) {
String singleAcronym = acronyms[i];
if(singleAcronym.isEmpty())
continue;
String parts[] = singleAcronym.split("\t");
if(parts.length != 2){
System.out.println("BAD FORMAT in "+labelsFile+": "+singleAcronym);
}
else{
docAcronymMap.put(parts[0].trim(), parts[1].trim());
}
}
labels.add(docAcronymMap);
}
fi.close();
}
catch(Exception e){
e.printStackTrace();
System.exit(1);
}
return labels;
}
public static List<String> loadTrainingCorpus(String corpusFile){
List<String> trainingCorpus = null;
try{
trainingCorpus = new ArrayList<String>();
BufferedReader fi = new BufferedReader(new FileReader(corpusFile));
String line;
while( (line = fi.readLine()) != null){
trainingCorpus.add(line);
}
fi.close();
}catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
return trainingCorpus;
}
// Trains on full corpus
public boolean trainOnAll(){
List<Map<String, String>> trueLabels = loadLabels(_trueLabelsFile);
List<String> corpus = loadTrainingCorpus(_trainingCorpusFile);
List<List<Acronym>> trainingExtractedCandidates = new ArrayList<List<Acronym>>();
List<Map<String, String>> trueLabelsForTraining = new ArrayList<Map<String,String>>();
for(Integer docID = 0; docID < corpus.size(); ++docID){
// Adds to training examples, all the extracted pairs from the current document.
trainingExtractedCandidates.add( extractCandidatePairs(corpus.get(docID)) );
trueLabelsForTraining.add( trueLabels.get(docID) );
}
return _abbvHmm.train(trainingExtractedCandidates, trueLabelsForTraining, true);
}
// Trains on candidate pairs extracted from the corpus
public boolean trainOnCandidates(){
List<String> corpus = loadTrainingCorpus(_trainingCorpusFile);
List<List<Acronym>> trainingExtractedCandidates = new ArrayList<List<Acronym>>();
for(Integer docID = 0; docID < corpus.size(); ++docID){
// Adds to training examples, all the extracted pairs from the current document.
trainingExtractedCandidates.add( extractCandidatePairs(corpus.get(docID)) );
}
return _abbvHmm.train(trainingExtractedCandidates, null, true);
}
public boolean train(List<String> corpus, List<Integer> trainingSet, List<Map<String, String>> trueLabels) {
List<List<Acronym>> trainingExtractedCandidates = new ArrayList<List<Acronym>>();
List<Map<String, String>> trueLabelsForTraining = new ArrayList<Map<String,String>>();
if(trainingSet != null){
for (Integer docID : trainingSet) {
// Adds to training examples, all the extracted pairs from the current document.
trainingExtractedCandidates.add( extractCandidatePairs(corpus.get(docID)) );
trueLabelsForTraining.add( trueLabels.get(docID) );
}
}
else{
// Iterates over all documents in the corpus
for(int docID = 0; docID < corpus.size(); ++docID){
// Adds to training examples, all the extracted pairs from the current document.
trainingExtractedCandidates.add( extractCandidatePairs(corpus.get(docID)) );
trueLabelsForTraining.add( trueLabels.get(docID) );
}
}
return _abbvHmm.train(trainingExtractedCandidates, trueLabelsForTraining, true);
}
public AbbreviationAlignmentContainer<AbbvGapsHMM.Emissions, AbbvGapsHMM.States> predict(String sf, String lf) {
return predictAlignment(new Acronym(sf, lf));
}
public AbbreviationAlignmentContainer<AbbvGapsHMM.Emissions, AbbvGapsHMM.States> predictAlignment(Acronym candidatePair) {
return _abbvHmm.viterbi(candidatePair);
}
public Acronym predict(Acronym candidatePair) {
AbbreviationAlignmentContainer<AbbvGapsHMM.Emissions, AbbvGapsHMM.States> alignment = predictAlignment(candidatePair);
Acronym currAcronym = null;
try {
if(alignment == null){
// No good alignment found
return null;
}
currAcronym = alignment.getAcronym();
if(currAcronym != null){
AbbreviationAlignmentContainer<AbbvGapsHMM.Emissions, AbbvGapsHMM.States> acronymAlignment = predictAlignment(currAcronym);
currAcronym._probability = acronymAlignment.getProbability();
currAcronym._alignment = alignment;
}
} catch (Exception e) {
e.printStackTrace();
}
return currAcronym;
}
public Map<String, Acronym> acronymsArrayToMap(Collection<Acronym> pairs){
Map<String, Acronym> out = new HashMap<String, Acronym>();
for (Acronym acronymPair : pairs) {
if(out.containsKey(acronymPair._shortForm)){
Acronym prevAcronym = out.get(acronymPair._shortForm);
if(acronymPair._probability != null && prevAcronym._probability != null){
if(acronymPair._probability.compareTo(prevAcronym._probability) > 0){
out.put(acronymPair._shortForm, acronymPair);
}
}
}
else{
out.put(acronymPair._shortForm, acronymPair);
}
}
return out;
}
public Collection<Acronym> predict(String text) {
List<Acronym> candidates = extractCandidatePairs(text);
List<Acronym> predictions = new ArrayList<Acronym>();
Acronym currPrediction;
for (Acronym candidateAcronym : candidates) {
currPrediction = predict(candidateAcronym);
if(currPrediction != null){
predictions.add(currPrediction);
}
}
return predictions;
}
public boolean trainIfNeeded() {
if(!_abbvHmm.loadModelParams()){
return trainOnCandidates();
}
return true;
}
/**** Candidates Extraction ****/
public List<Acronym> extractCandidatePairs(String text) {
ArrayList<Acronym> extractedPairs = new ArrayList<Acronym>();
extractedPairs.addAll(extractSingleAcronyms(text));
extractedPairs.addAll(extractPatternAcronyms(text));
return extractedPairs;
}
protected List<Acronym> extractPatternAcronyms(String text){
ArrayList<Acronym> extractedPairs = new ArrayList<Acronym>();
extractedPairs.addAll(extractHeadNounPattern_2Parts(text));
extractedPairs.addAll(extractHeadNounPattern_3Parts(text));
extractedPairs.addAll(extractTrailingNounPattern_2Parts(text));
extractedPairs.addAll(extractTrailingNounPattern_3Parts(text));
return extractedPairs;
}
protected void addCandidatePair(List<Acronym> allPairs, String longFormCandidate, String shortFormCandidate){
Acronym pair = parseCandidate(longFormCandidate, shortFormCandidate);
if(pair != null && !pair._shortForm.isEmpty()){
allPairs.add(pair);
}
}
protected List<Acronym> extractHeadNounPattern_3Parts(String text){
ArrayList<Acronym> extractedPairs = new ArrayList<Acronym>();
String nounExp = "([a-zA-Z0-9\\-]{1,20})";
String shortFormExp = "\\(([^\\(]*?)\\)";
Matcher matcher = Pattern.compile (nounExp+" "+nounExp+" "+shortFormExp+",? "+nounExp+" "+shortFormExp+",? and "+nounExp+" "+shortFormExp).matcher(text);
int startPos = 0;
while (startPos < text.length() && matcher.find(startPos))
{
String mainNoun = matcher.group(1);
String part1 = matcher.group(2);
String part1_short = matcher.group(3);
String part2 = matcher.group(4);
String part2_short = matcher.group(5);
String part3 = matcher.group(6);
String part3_short = matcher.group(7);
startPos = matcher.regionEnd() + 1;
addCandidatePair(extractedPairs, mainNoun+" "+part1, part1_short);
addCandidatePair(extractedPairs, mainNoun+" "+part2, part2_short);
addCandidatePair(extractedPairs, mainNoun+" "+part3, part3_short);
}
return extractedPairs;
}
protected List<Acronym> extractHeadNounPattern_2Parts(String text){
ArrayList<Acronym> extractedPairs = new ArrayList<Acronym>();
String nounExp = "([a-zA-Z0-9\\-]{1,20})";
String shortFormExp = "\\(([^\\(]*?)\\)";
Matcher matcher = Pattern.compile (nounExp+" "+nounExp+" "+shortFormExp+",? and "+nounExp+" "+shortFormExp).matcher(text);
int startPos = 0;
while (startPos < text.length() && matcher.find(startPos))
{
String mainNoun = matcher.group(1);
String part1 = matcher.group(2);
String part1_short = matcher.group(3);
String part2 = matcher.group(4);
String part2_short = matcher.group(5);
startPos = matcher.regionEnd() + 1;
addCandidatePair(extractedPairs, mainNoun+" "+part1, part1_short);
addCandidatePair(extractedPairs, mainNoun+" "+part2, part2_short);
}
return extractedPairs;
}
protected List<Acronym> extractTrailingNounPattern_3Parts(String text){
ArrayList<Acronym> extractedPairs = new ArrayList<Acronym>();
String finalNounExp = "([a-zA-Z0-9\\-]{1,20})";
String nounExp = "(.{1,20}?)";
String shortFormExp = "\\(([^\\(]*?)\\)";
Matcher matcher = Pattern.compile (nounExp+" "+shortFormExp+",? "+nounExp+" "+shortFormExp+",? and "+nounExp+" "+shortFormExp+" "+finalNounExp).matcher(text);
int startPos = 0;
while (startPos < text.length() && matcher.find(startPos))
{
String part1 = matcher.group(1);
String part1_short = matcher.group(2);
String part2 = matcher.group(3);
String part2_short = matcher.group(4);
String part3 = matcher.group(5);
String part3_short = matcher.group(6);
String mainNoun = matcher.group(7);
startPos = matcher.regionEnd() + 1;
addCandidatePair(extractedPairs, part1 + " " + mainNoun, part1_short);
addCandidatePair(extractedPairs, part2 + " " + mainNoun, part2_short);
addCandidatePair(extractedPairs, part3 + " " + mainNoun, part3_short);
}
return extractedPairs;
}
protected List<Acronym> extractTrailingNounPattern_2Parts(String text){
ArrayList<Acronym> extractedPairs = new ArrayList<Acronym>();
String finalNounExp = "([a-zA-Z0-9\\-]{1,20})";
String nounExp = "(.{1,20}?)";
String shortFormExp = "\\(([^\\(]*?)\\)";
Matcher matcher = Pattern.compile (nounExp+" "+shortFormExp+",? and "+nounExp+" "+shortFormExp+" "+finalNounExp).matcher(text);
int startPos = 0;
while (startPos < text.length() && matcher.find(startPos))
{
String part1 = matcher.group(1);
String part1_short = matcher.group(2);
String part2 = matcher.group(3);
String part2_short = matcher.group(4);
String mainNoun = matcher.group(5);
startPos = matcher.regionEnd() + 1;
addCandidatePair(extractedPairs, part1 + " " + mainNoun, part1_short);
addCandidatePair(extractedPairs, part2 + " " + mainNoun, part2_short);
}
return extractedPairs;
}
protected List<Acronym> extractSingleAcronyms(String text){
ArrayList<Acronym> extractedPairs = new ArrayList<Acronym>();
int iOpen = text.indexOf("(");
int iClose = -1;
String mOutOfPar = "";
String mInPar = "";
while(iOpen != -1){
iClose = -1;
int numPar = 0;
for (int p = iOpen+1; p < text.length(); p++) {
if(text.charAt(p) == '('){
numPar++;
}
if(text.charAt(p) == ')'){
if(numPar > 0)
numPar--;
else{
iClose = p;
break;
}
}
}
if(iClose != -1){
mInPar = text.substring(iOpen+1, iClose);
mOutOfPar = text.substring(0, iOpen).trim();
addCandidatePair(extractedPairs, mOutOfPar, mInPar);
}
iOpen = text.indexOf("(", iOpen+1);
}
return extractedPairs;
}
protected Acronym parseCandidate(String outOfParenthesis, String inParenthesis) {
if(inParenthesis.indexOf(";") != -1){
int i = inParenthesis.indexOf(";");
inParenthesis = inParenthesis.substring(0, i);
}
if(outOfParenthesis.indexOf(";") != -1){
int i = outOfParenthesis.indexOf(";");
outOfParenthesis = outOfParenthesis.substring(i+1);
}
// Default assumption: long form is outside the parenthesis
String shortForm = inParenthesis.trim();
String longForm = outOfParenthesis.trim();
// Unless default was found not to be true
if(!isShortForm(shortForm)){
longForm = inParenthesis.trim();
String parts[] = outOfParenthesis.trim().split(" ");
shortForm = parts[parts.length-1];
}
// Is the short form valid?
if(!isValidShortForm(shortForm)){
return null;
}
if(!isValidExpression(shortForm) || ! isValidExpression(longForm)){
return null;
}
// Chunk long form to correct size
String parts[] = longForm.split(" ");
int sfSize = shortForm.length();
int maxLongFormLength = Math.min( sfSize+5, sfSize*2 );
int finalLfSize = Math.min( maxLongFormLength, parts.length );
String finalLongForm = "";
for (int i = parts.length-1; i > parts.length-finalLfSize-1; i--) {
finalLongForm = parts[i] + " " + finalLongForm;
}
finalLongForm = finalLongForm.trim();
if(shortForm.equalsIgnoreCase(finalLongForm)){
return null;
}
return new Acronym(shortForm, finalLongForm);
}
protected String chunkLongForm(String longForm, int size){
int foundWords = 0;
int i = longForm.length()-1;
for (; i >= 0 && foundWords < size ; i--) {
if(i == 0 || !Character.isLetterOrDigit(longForm.charAt(i-1))){
foundWords++;
}
}
return longForm.substring(i+1, longForm.length());
}
protected boolean isValidExpression(String exp){
if( exp == null
||
exp.isEmpty()
){
return false;
}
return true;
}
protected boolean isShortForm(String candidate) {
String parts[] = candidate.split(" ");
return parts.length <= 3;
}
protected boolean isValidShortForm(String candidate) {
// length restriction
if(candidate.length() > 15)
return false;
// length restriction
if(candidate.length() < 1)
return false;
// first char is alpha-numeric
if(!Pattern.matches("^[a-zA-Z0-9].*", candidate))
return false;
// at least one of these characters is a letter
if(!Pattern.matches(".*[a-zA-Z].*", candidate))
return false;
return true;
}
public List<Double> getEmmisions(){
return _abbvHmm.getEmmisionParams();
}
public List<Double> getTransitions(){
return _abbvHmm.getTransitionParams();
}
public void setStartingParams(List<Double> emmisions, List<Double> transitions){
_abbvHmm.setStartingParams(emmisions, transitions);
}
}
|