| 11 | import com.winvector.util.ThreadedReducer; |
| 12 | |
| 13 | public class HelperFns { |
| 14 | |
| 15 | |
| 16 | public static int argmax(final double[] pred) { |
| 17 | int choice = 0; |
| 18 | final int n = pred.length; |
| 19 | for(int i=1;i<n;++i) { |
| 20 | if(pred[i]>pred[choice]) { |
| 21 | choice = i; |
| 22 | } |
| 23 | } |
| 24 | return choice; |
| 25 | } |
| 26 | |
| 27 | public static boolean isGoodPrediction(final double[] pred, final ExampleRow ei) { |
| 28 | final int predi = argmax(pred); |
| 29 | final boolean good = predi==ei.category(); |
| 30 | return good; |
| 31 | } |
| 32 | |
| 33 | private static final class AccuracyCounter<T extends ExampleRow> implements ReducibleObserver<T,AccuracyCounter<T>> { |
| 34 | public long n = 0; |
| 35 | public long nGood = 0; |
| 36 | private final DModel<T> fn; |
| 37 | private final double[] x; |
| 38 | private final double[] pred; |
| 39 | |
| 40 | public AccuracyCounter(final DModel<T> fn, final double[] x) { |
| 41 | this.fn = fn; |
| 42 | this.x = x; |
| 43 | pred = new double[fn.noutcomes()]; |
| 44 | } |
| 45 | |
| 46 | @Override |
| 47 | public void observe(final T ei) { |
| 48 | if(ei.category()>=0) { |
| 49 | fn.predict(x,ei,pred); |
| 50 | final boolean good = (pred!=null)&&isGoodPrediction(pred,ei); |
| 51 | if(good) { |
| 52 | ++nGood; |
| 53 | } |
| 54 | ++n; |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | @Override |
| 59 | public void observe(final AccuracyCounter<T> o) { |
| 60 | n += o.n; |
| 61 | nGood += o.nGood; |
| 62 | } |
| 63 | |
| 64 | @Override |
| 65 | public AccuracyCounter<T> newObserver() { |
| 66 | return new AccuracyCounter<T>(fn,x); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | public static <T extends ExampleRow> double accuracy(final DModel<T> fn, final Iterable<T> as, final double[] x) { |