import java.util.*; import java.text.*; public class Gradient extends NullClassifier { int numIterations = 5000; ArrayList>[] trainingData; // We inherit the variables: numClasses, dim. // Note: w[dim] = the threshold. double[] w; double initWLeft = -0.5, initWRight = 0.5; public String train (int numClasses, boolean isFixedDimension, ArrayList>[] trainingData) { this.numClasses = numClasses; this.trainingData = trainingData; if (isFixedDimension) { dim = trainingData[0].get(0).size(); } else { this.trainingData = makeFixedDimension (numClasses, trainingData); } // Next, add one more dimension with value 1.0 to multiply // with threshold w[dim]. We'll leave the for-loops as i X = trainingData[c].get(k); double z = applyDirect (X); double y = c; if (c == 0) { y = -1; } double g = -2 * (y-z) * X.get(i); G[i] = G[i] + g; } } } return G; } double computef (double[] w) { double sum = 0; for (int c=0; c X = trainingData[c].get(k); double y = c; if (c == 0) { y = -1; } // Compute z using parameters. double z = 0; for (int i=0; i v, double y) { double z = applyDirect (v); return (z-y)*(z-y); } double applyDirect (Vector v) { // Compute sum_i w_i*w_i double sum = 0; for (int i=0; i v) { double sum = 0; for (int i=0; i 0) { return 1; } else { return -1; } } public int classify (Vector sample) { sample = makeFixedDimension (sample); double z = apply (sample); if (z == -1) { return 0; } else { return 1; } } void printWeights (String msg) { System.out.print (msg + ": w: "); for (int i=0; i