Author: ragerri
Date: Mon Mar  9 12:25:49 2015
New Revision: 1665208

URL: http://svn.apache.org/r1665208
Log:
OPENNLP-714 added brown clustering features for token, token class and bigrams, 
plus support class to serialize brown cluster lexicons

Added:
    
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownBigramFeatureGenerator.java
    
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownCluster.java
    
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownTokenClassFeatureGenerator.java
    
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownTokenClasses.java
    
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownTokenFeatureGenerator.java
Modified:
    
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/namefind/TokenNameFinderModel.java
    
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/GeneratorFactory.java

Modified: 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/namefind/TokenNameFinderModel.java
URL: 
http://svn.apache.org/viewvc/opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/namefind/TokenNameFinderModel.java?rev=1665208&r1=1665207&r2=1665208&view=diff
==============================================================================
--- 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/namefind/TokenNameFinderModel.java
 (original)
+++ 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/namefind/TokenNameFinderModel.java
 Mon Mar  9 12:25:49 2015
@@ -38,6 +38,7 @@ import opennlp.tools.util.SequenceCodec;
 import opennlp.tools.util.ext.ExtensionLoader;
 import opennlp.tools.util.featuregen.AdaptiveFeatureGenerator;
 import opennlp.tools.util.featuregen.AggregatedFeatureGenerator;
+import opennlp.tools.util.featuregen.BrownCluster;
 import opennlp.tools.util.featuregen.FeatureGeneratorResourceProvider;
 import opennlp.tools.util.featuregen.GeneratorFactory;
 import opennlp.tools.util.featuregen.W2VClassesDictionary;
@@ -273,7 +274,10 @@ public class TokenNameFinderModel extend
 
     serializers.put("featuregen", new ByteArraySerializer());
     serializers.put("w2vwordcluster", new 
W2VClassesDictionary.W2VClassesDictionarySerializer());
-
+    serializers.put("brownclustertoken", new 
BrownCluster.BrownClusterSerializer());
+    serializers.put("brownclustertokenclass", new 
BrownCluster.BrownClusterSerializer());
+    serializers.put("brownclusterbigram", new 
BrownCluster.BrownClusterSerializer());
+    
     return serializers;
   }
 

Added: 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownBigramFeatureGenerator.java
URL: 
http://svn.apache.org/viewvc/opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownBigramFeatureGenerator.java?rev=1665208&view=auto
==============================================================================
--- 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownBigramFeatureGenerator.java
 (added)
+++ 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownBigramFeatureGenerator.java
 Mon Mar  9 12:25:49 2015
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package opennlp.tools.util.featuregen;
+
+import java.util.List;
+
+/**
+ * Generates Brown cluster features for token bigrams.
+ */
+public class BrownBigramFeatureGenerator extends FeatureGeneratorAdapter {
+  
+  private BrownCluster brownLexicon;
+  
+  public BrownBigramFeatureGenerator(BrownCluster dict){
+    this.brownLexicon = dict;
+  }
+  
+  public void createFeatures(List<String> features, String[] tokens, int index,
+      String[] previousOutcomes) {
+    
+    List<String> wordClasses = BrownTokenClasses.getWordClasses(tokens[index], 
brownLexicon);
+    if (index > 0) {
+      List<String> prevWordClasses = 
BrownTokenClasses.getWordClasses(tokens[index - 1], brownLexicon);
+      for (int i = 0; i < wordClasses.size() && i < prevWordClasses.size(); 
i++)
+      features.add("p" + "browncluster" + "," + "browncluster" + "=" + 
prevWordClasses.get(i) + "," + wordClasses.get(i));
+    }
+    
+    if (index + 1 < tokens.length) {
+      List<String> nextWordClasses = 
BrownTokenClasses.getWordClasses(tokens[index + 1], brownLexicon);
+      for (int i = 0; i < wordClasses.size() && i < nextWordClasses.size(); 
i++) {
+        features.add("browncluster" + "," + "n" + "browncluster" + "=" + 
wordClasses.get(i) + "," + nextWordClasses.get(i));
+      }
+    }
+  }
+  
+}
+

Added: 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownCluster.java
URL: 
http://svn.apache.org/viewvc/opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownCluster.java?rev=1665208&view=auto
==============================================================================
--- 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownCluster.java
 (added)
+++ 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownCluster.java
 Mon Mar  9 12:25:49 2015
@@ -0,0 +1,110 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package opennlp.tools.util.featuregen;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.nio.charset.Charset;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+import opennlp.tools.util.InvalidFormatException;
+import opennlp.tools.util.model.ArtifactSerializer;
+import opennlp.tools.util.model.SerializableArtifact;
+
+/**
+ * 
+ * Class to load a Brown cluster document: word\tword_class\tprob
+ * http://metaoptimize.com/projects/wordreprs/
+ * 
+ * The file containing the clustering lexicon has to be passed as the 
+ * value of the dict attribute of each BrownCluster feature generator.
+ * 
+ */
+public class BrownCluster implements SerializableArtifact {
+  
+  private static final Pattern tabPattern = Pattern.compile("\t");
+
+  public static class BrownClusterSerializer implements 
ArtifactSerializer<BrownCluster> {
+
+    public BrownCluster create(InputStream in) throws IOException,
+        InvalidFormatException {
+      return new BrownCluster(in);
+    }
+
+    public void serialize(BrownCluster artifact, OutputStream out)
+        throws IOException {
+      artifact.serialize(out);
+    }
+  }
+  
+  private Map<String, String> tokenToClusterMap = new HashMap<String, 
String>();
+
+  /**
+   * Generates the token to cluster map from Brown cluster input file.
+   * NOTE: we only add those tokens with frequency > 5.
+   * @param in the inputstream
+   * @throws IOException the io exception
+   */
+  public BrownCluster(InputStream in) throws IOException {
+
+    BufferedReader breader = new BufferedReader(new InputStreamReader(in, 
Charset.forName("UTF-8")));
+    String line;
+    while ((line = breader.readLine()) != null) {
+      String[] lineArray = tabPattern.split(line);
+      if (lineArray.length == 3) {
+        int freq = Integer.parseInt(lineArray[2]);
+          if (freq > 5 ) {
+            tokenToClusterMap.put(lineArray[1], lineArray[0]);
+        }
+      }
+      else if (lineArray.length == 2) {
+        tokenToClusterMap.put(lineArray[0], lineArray[1]);
+      }
+    }
+  }
+
+  /**
+   * Check if a token is in the Brown<paths, token> map.
+   * @param string the token to look-up
+   * @return the brown class if such token is in the brown cluster map
+   */
+  public String lookupToken(String string) {
+    return tokenToClusterMap.get(string);
+  }
+
+  public void serialize(OutputStream out) throws IOException {
+    Writer writer = new BufferedWriter(new OutputStreamWriter(out));
+
+    for (Map.Entry<String, String> entry : tokenToClusterMap.entrySet()) {
+      writer.write(entry.getKey() + "\t" + entry.getValue() + "\n");
+    }
+    writer.flush();
+  }
+
+  public Class<?> getArtifactSerializerClass() {
+    return BrownClusterSerializer.class;
+  }
+}

Added: 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownTokenClassFeatureGenerator.java
URL: 
http://svn.apache.org/viewvc/opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownTokenClassFeatureGenerator.java?rev=1665208&view=auto
==============================================================================
--- 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownTokenClassFeatureGenerator.java
 (added)
+++ 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownTokenClassFeatureGenerator.java
 Mon Mar  9 12:25:49 2015
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package opennlp.tools.util.featuregen;
+
+import java.util.List;
+
+/**
+ * Generates Brown cluster features for current token and token class.
+ */
+public class BrownTokenClassFeatureGenerator extends FeatureGeneratorAdapter {
+  
+  private BrownCluster brownLexicon;
+  
+  public BrownTokenClassFeatureGenerator(BrownCluster dict){
+    this.brownLexicon = dict;
+  }
+  
+  public void createFeatures(List<String> features, String[] tokens, int index,
+      String[] previousOutcomes) {
+    
+    String wordShape = FeatureGeneratorUtil.tokenFeature(tokens[index]);
+    List<String> wordClasses = BrownTokenClasses.getWordClasses(tokens[index], 
brownLexicon);
+    
+    for (int i = 0; i < wordClasses.size(); i++) {
+      features.add("c," + "browncluster" + "=" + wordShape + "," + 
wordClasses.get(i));
+    }
+  }
+  
+}
+

Added: 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownTokenClasses.java
URL: 
http://svn.apache.org/viewvc/opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownTokenClasses.java?rev=1665208&view=auto
==============================================================================
--- 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownTokenClasses.java
 (added)
+++ 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownTokenClasses.java
 Mon Mar  9 12:25:49 2015
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package opennlp.tools.util.featuregen;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Obtain the paths listed in the pathLengths array from the Brown class.
+ * This class is not to be instantiated.
+ *
+ */
+public class BrownTokenClasses {
+  
+  public static final int[] pathLengths = { 4, 6, 10, 20 };
+  
+  /**
+   * It provides a list containing the pathLengths for a token if found
+   * in the {@code BrownCluster} Map<token,BrownClass>.
+   * 
+   * @param token the token to be looked up in the brown clustering map
+   * @param brownLexicon the Brown clustering map
+   * @return the list of the paths for a token
+   */
+  public static List<String> getWordClasses(String token, BrownCluster 
brownLexicon) {
+    if (brownLexicon.lookupToken(token) == null) {
+      return new ArrayList<String>(0);
+    } else {
+      String brownClass = brownLexicon.lookupToken(token);
+      List<String> pathLengthsList = new ArrayList<String>();
+      pathLengthsList.add(brownClass.substring(0,
+          Math.min(brownClass.length(), pathLengths[0])));
+      for (int i = 1; i < pathLengths.length; i++) {
+        if (pathLengths[i - 1] < brownClass.length()) {
+          pathLengthsList.add(brownClass.substring(0,
+              Math.min(brownClass.length(), pathLengths[i])));
+        }
+      }
+      return pathLengthsList;
+    }
+  }
+  
+}
+

Added: 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownTokenFeatureGenerator.java
URL: 
http://svn.apache.org/viewvc/opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownTokenFeatureGenerator.java?rev=1665208&view=auto
==============================================================================
--- 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownTokenFeatureGenerator.java
 (added)
+++ 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/BrownTokenFeatureGenerator.java
 Mon Mar  9 12:25:49 2015
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package opennlp.tools.util.featuregen;
+
+import java.util.List;
+
+/**
+ * Generates Brown cluster features for current token.
+ */
+public class BrownTokenFeatureGenerator extends FeatureGeneratorAdapter {
+  
+  private BrownCluster brownLexicon;
+  
+  public BrownTokenFeatureGenerator(BrownCluster dict){
+    this.brownLexicon = dict;
+  }
+  
+  public void createFeatures(List<String> features, String[] tokens, int index,
+      String[] previousOutcomes) {
+    
+    List<String> wordClasses = BrownTokenClasses.getWordClasses(tokens[index], 
brownLexicon);
+    
+    for (int i = 0; i < wordClasses.size(); i++) {
+      features.add("browncluster" + "=" + wordClasses.get(i));
+    }
+  }
+  
+}

Modified: 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/GeneratorFactory.java
URL: 
http://svn.apache.org/viewvc/opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/GeneratorFactory.java?rev=1665208&r1=1665207&r2=1665208&view=diff
==============================================================================
--- 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/GeneratorFactory.java
 (original)
+++ 
opennlp/trunk/opennlp-tools/src/main/java/opennlp/tools/util/featuregen/GeneratorFactory.java
 Mon Mar  9 12:25:49 2015
@@ -297,6 +297,81 @@ public class GeneratorFactory {
       factoryMap.put("w2vwordcluster", new 
W2VClassesFeatureGeneratorFactory());
     }
   }
+  
+  /**
+   * Generates Brown clustering features for current token.
+   */
+  static class BrownClusterTokenFeatureGeneratorFactory implements 
XmlFeatureGeneratorFactory {
+
+    public AdaptiveFeatureGenerator create(Element generatorElement,
+        FeatureGeneratorResourceProvider resourceManager) throws 
InvalidFormatException {
+
+      String dictResourceKey = generatorElement.getAttribute("dict");
+
+      Object dictResource = resourceManager.getResource(dictResourceKey);
+
+
+      if (!(dictResource instanceof BrownCluster)) {
+        throw new InvalidFormatException("Not a BrownLexicon resource for key: 
" + dictResourceKey);
+      }
+
+      return new BrownTokenFeatureGenerator((BrownCluster) dictResource);
+    }
+
+    static void register(Map<String, XmlFeatureGeneratorFactory> factoryMap) {
+      factoryMap.put("brownclustertoken", new 
BrownClusterTokenFeatureGeneratorFactory());
+    }
+  }
+  
+  /**
+   * Generates Brown clustering features for token classes.
+   */
+  static class BrownClusterTokenClassFeatureGeneratorFactory implements 
XmlFeatureGeneratorFactory {
+
+    public AdaptiveFeatureGenerator create(Element generatorElement,
+        FeatureGeneratorResourceProvider resourceManager) throws 
InvalidFormatException {
+
+      String dictResourceKey = generatorElement.getAttribute("dict");
+
+      Object dictResource = resourceManager.getResource(dictResourceKey);
+
+
+      if (!(dictResource instanceof BrownCluster)) {
+        throw new InvalidFormatException("Not a BrownLexicon resource for key: 
" + dictResourceKey);
+      }
+
+      return new BrownTokenClassFeatureGenerator((BrownCluster) dictResource);
+    }
+
+    static void register(Map<String, XmlFeatureGeneratorFactory> factoryMap) {
+      factoryMap.put("brownclustertokenclass", new 
BrownClusterTokenClassFeatureGeneratorFactory());
+    }
+  }
+  
+  /**
+   * Generates Brown clustering features for token bigrams.
+   */
+  static class BrownClusterBigramFeatureGeneratorFactory implements 
XmlFeatureGeneratorFactory {
+
+    public AdaptiveFeatureGenerator create(Element generatorElement,
+        FeatureGeneratorResourceProvider resourceManager) throws 
InvalidFormatException {
+
+      String dictResourceKey = generatorElement.getAttribute("dict");
+
+      Object dictResource = resourceManager.getResource(dictResourceKey);
+
+
+      if (!(dictResource instanceof BrownCluster)) {
+        throw new InvalidFormatException("Not a BrownLexicon resource for key: 
" + dictResourceKey);
+      }
+
+      return new BrownBigramFeatureGenerator((BrownCluster) dictResource);
+    }
+
+    static void register(Map<String, XmlFeatureGeneratorFactory> factoryMap) {
+      factoryMap.put("brownclusterbigram", new 
BrownClusterBigramFeatureGeneratorFactory());
+    }
+  }
 
   /**
    * @see PreviousMapFeatureGenerator
@@ -552,6 +627,9 @@ public class GeneratorFactory {
     SuffixFeatureGeneratorFactory.register(factories);
     WindowFeatureGeneratorFactory.register(factories);
     W2VClassesFeatureGeneratorFactory.register(factories);
+    BrownClusterTokenFeatureGeneratorFactory.register(factories);
+    BrownClusterTokenClassFeatureGeneratorFactory.register(factories);
+    BrownClusterBigramFeatureGeneratorFactory.register(factories);
     CustomFeatureGeneratorFactory.register(factories);
   }
 


Reply via email to