package enju.ccg.ml;

import java.util.List;
import enju.ccg.util.Util;
import enju.ccg.util.Pair;

public class Perceptron<L> extends AbstractClassifier<L> {
  public Perceptron(WeightVector weight) {
    super(weight);
  }

  // multiclass classification
  public void update(Example<L>[] examples, L gold) {
    L pred = predict(examples).getP1();
    if (pred != gold) {
      updateBody(examples, pred, gold);
    }
  }
  // multiclass classification
  public void updateBody(Example<L>[] examples, L pred, L gold) {
    for (Example<L> e : examples) {
      if (e.getLabel().equals(pred)) {
        for (int f : e.getFeature()) {
          weight.add(f, -1);
        }
      } else if (e.getLabel().equals(gold)) {
        for (int f : e.getFeature()) {
          weight.add(f, 1);
        }
      }
    }
  }
  // structured perceptron
  public void update(int[] predFeatures, int[] goldFeatures) {
    for (int f : predFeatures) {
      weight.add(f, -1);
    }
    for (int f : goldFeatures) {
      weight.add(f, 1);
    }
  }
}
@@ -152,16 +152,94 @@
 er%3CL%3E %7B%0A
+  private WeightVector averageWeight;%0A  private int C; // count for averaging%0A
   public
@@ -291,16 +291,71 @@
 weight);
+    %0A    averageWeight = new WeightVector();%0A    C = 1;
 %0A  %7D%0A%0A  
@@ -787,24 +787,60 @@
 add(f, -1);%0A
+          averageWeight.add(f, -C);%0A
         %7D%0A  
@@ -946,24 +946,59 @@
 .add(f, 1);%0A
+          averageWeight.add(f, C);%0A
         %7D%0A  
@@ -1005,24 +1005,33 @@
     %7D%0A    %7D%0A
+    C++;%0A
   %7D%0A  // str
@@ -1166,24 +1166,56 @@
 add(f, -1);%0A
+      averageWeight.add(f, -C);%0A
     %7D%0A    fo
@@ -1233,32 +1233,32 @@
 goldFeatures) %7B%0A
-
       weight.add
@@ -1261,23 +1261,200 @@
 .add(f, 1);%0A
+      averageWeight.add(f, C);%0A    %7D%0A  %7D%0A  public void finalize() %7B%0A    for (int i = 0; i %3C weight.size(); ++i) %7B%0A      weight.set(i, weight.get(i) - averageWeight.get(i) / C);%0A
     %7D%0A  %7D%0A%7D

support average perceptron