001package org.maltparser.core.lw.parser; 002 003 004import org.maltparser.core.exception.MaltChainedException; 005import org.maltparser.core.feature.FeatureVector; 006import org.maltparser.core.feature.value.FeatureValue; 007import org.maltparser.core.feature.value.MultipleFeatureValue; 008import org.maltparser.core.feature.value.SingleFeatureValue; 009import org.maltparser.ml.lib.FeatureList; 010import org.maltparser.ml.lib.FeatureMap; 011import org.maltparser.ml.lib.MaltLibModel; 012import org.maltparser.ml.lib.LibException; 013import org.maltparser.parser.history.action.SingleDecision; 014 015/** 016* A lightweight version of org.maltparser.ml.lib.{Lib,LibLinear,LibSvm} and can only predict the next transition. 017* 018* @author Johan Hall 019*/ 020public class LWClassifier { 021 private final FeatureMap featureMap; 022 private final boolean excludeNullValues; 023 private final MaltLibModel model; 024 025 public LWClassifier(McoModel mcoModel, String prefixFileName, boolean _excludeNullValues) { 026 this.model = (MaltLibModel)mcoModel.getMcoEntryObject(prefixFileName+".moo"); 027 this.featureMap = (FeatureMap)mcoModel.getMcoEntryObject(prefixFileName+".map"); 028 this.excludeNullValues = _excludeNullValues; 029 } 030 031 public boolean predict(FeatureVector featureVector, SingleDecision decision, boolean one_prediction) throws MaltChainedException { 032 final FeatureList featureList = new FeatureList(); 033 final int size = featureVector.size(); 034 for (int i = 1; i <= size; i++) { 035 final FeatureValue featureValue = featureVector.getFeatureValue(i-1); 036 if (featureValue != null && !(excludeNullValues == true && featureValue.isNullValue())) { 037 if (!featureValue.isMultiple()) { 038 SingleFeatureValue singleFeatureValue = (SingleFeatureValue)featureValue; 039 final int index = featureMap.getIndex(i, singleFeatureValue.getIndexCode()); 040 if (index != -1 && singleFeatureValue.getValue() != 0) { 041 featureList.add(index,singleFeatureValue.getValue()); 042 } 043 } 044 else { 045 for (Integer value : ((MultipleFeatureValue)featureValue).getCodes()) { 046 final int v = featureMap.getIndex(i, value); 047 if (v != -1) { 048 featureList.add(v,1); 049 } 050 } 051 } 052 } 053 } 054 try { 055 if (one_prediction) { 056 decision.getKBestList().add(model.predict_one(featureList.toArray())); 057 } else { 058 decision.getKBestList().addList(model.predict(featureList.toArray())); 059 } 060 } catch (OutOfMemoryError e) { 061 throw new LibException("Out of memory. Please increase the Java heap size (-Xmx<size>). ", e); 062 } 063 return true; 064 } 065}