public static void main(String[] args) {
    int n = 3;
    int f = 1;

    TrainingExample[] t = new TrainingExample[n];

    double[] i0 = {0, 0};
    t[0] = new TrainingExample(i0, 0);

    double[] i1 = {1, 0};
    t[1] = new TrainingExample(i1, 1);

    double[] i2 = {2, 1};
    t[2] = new TrainingExample(i2, 3);

    LogisticRegression l = new LogisticRegression(1, .1, t);
    l.tune(100);
    System.out.println(l.classifyDefinitive(i1));
    l.show();

    try {
      File file = new File("C:\\Users\\BrianCarlsen\\Documents\\testExample.txt");
      l.writeToFile(file);

      LogisticRegression l2 = new LogisticRegression(new TrainingExample[] {t[0]});
      l2.loadFromFile(file);

      l2.show();
      System.out.println(l2.classifyDefinitive(i1));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * @param lr is the learning rate.
   * @param ts is the training set.
   */
  public LogisticRegression(double lr, double rp, TrainingExample[] ts) {
    learningRate = lr;
    regularizationParam = rp;
    trainingSet = ts;

    // Construct the correct number of hypothesis given
    // the number of features in the trainingSet
    // and the number of different classifications
    ArrayList<Integer> classifications = new ArrayList<Integer>();
    for (TrainingExample t : trainingSet) {
      Integer c = t.getAnswer();
      if (!classifications.contains(c)) classifications.add(c);
    }

    hypothesis = new Hypothesis[classifications.size() - 0];
    int s = trainingSet[0].getInput().length + 1;

    for (int i = 0; i < classifications.size() - 0; ++i) {
      hypothesis[i] = new Hypothesis(s, classifications.get(i));
    }

    try {
      costFunction = this.getClass().getMethod("defaultCostFunction", Hypothesis.class);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#3
0
文件: A.java 项目: hiroshi-cl/wakaba
 private static void setStream(String in, String out) {
   try {
     System.setIn(new BufferedInputStream(new FileInputStream(in)));
     System.setOut(new PrintStream(out));
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
示例#4
0
 // BEGIN CUT HERE
 public static void main(String[] args) {
   try {
     eq(0, (new AccessLevel()).canAccess(new int[] {0, 1, 2, 3, 4, 5}, 2), "DDAAAA");
     eq(1, (new AccessLevel()).canAccess(new int[] {5, 3, 2, 10, 0}, 20), "DDDDD");
     eq(2, (new AccessLevel()).canAccess(new int[] {}, 20), "");
     eq(3, (new AccessLevel()).canAccess(new int[] {34, 78, 9, 52, 11, 1}, 49), "DADADD");
   } catch (Exception exx) {
     System.err.println(exx);
     exx.printStackTrace(System.err);
   }
 }
    /**
     * @param input is an array of matrices, each of which represents the values to input into that
     *     feature
     * @return Returns the probability that the input is of this class
     */
    public double predict(double[] input) {
      Double p;
      try {
        p = (Double) function.invoke(this, input);
      } catch (Exception e) {
        e.printStackTrace();
        p = new Double(-1);
      }

      return p;
    }
示例#6
0
 // BEGIN CUT HERE
 public static void main(String[] args) {
   try {
     eq(0, (new KnockoutTourney()).meetRival(16, 1, 2), 1);
     eq(1, (new KnockoutTourney()).meetRival(16, 8, 9), 4);
     eq(2, (new KnockoutTourney()).meetRival(1000, 20, 31), 4);
     eq(3, (new KnockoutTourney()).meetRival(65536, 1000, 35000), 16);
     eq(4, (new KnockoutTourney()).meetRival(60000, 101, 891), 10);
   } catch (Exception exx) {
     System.err.println(exx);
     exx.printStackTrace(System.err);
   }
 }
    // CONSTRUCTOR
    public Hypothesis(int nF, int c) {
      numFeatures = nF;
      classification = c;
      parameter = new Matrix(numFeatures, 1);
      for (int i = 0; i < numFeatures; i++) parameter.set(i, 0, 1);

      try {
        function = this.getClass().getMethod("defaultHypothesis", double[].class);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    public void writeToFile(File f) {
      try {
        PrintWriter fw = new PrintWriter(new FileWriter(f, true));
        String s = Integer.toString(numFeatures) + ", ";
        s += Integer.toString(classification) + "; ";
        for (int i = 0; i < parameter.getRowDimension(); ++i) s += parameter.get(i, 0) + ", ";
        fw.println(s + "\n");

        fw.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
 public static void main(String[] args) {
   try {
     eq(
         0,
         (new BallsSeparating_2())
             .minOperations(new int[] {1, 1, 1}, new int[] {1, 1, 1}, new int[] {1, 1, 1}),
         6);
     eq(
         1,
         (new BallsSeparating_2()).minOperations(new int[] {5}, new int[] {6}, new int[] {8}),
         -1);
     eq(
         2,
         (new BallsSeparating_2())
             .minOperations(
                 new int[] {4, 6, 5, 7}, new int[] {7, 4, 6, 3}, new int[] {6, 5, 3, 8}),
         37);
     eq(
         3,
         (new BallsSeparating_2())
             .minOperations(
                 new int[] {7, 12, 9, 9, 7},
                 new int[] {7, 10, 8, 8, 9},
                 new int[] {8, 9, 5, 6, 13}),
         77);
     eq(
         4,
         (new BallsSeparating_2())
             .minOperations(
                 new int[] {
                   842398, 491273, 958925, 849859, 771363, 67803, 184892, 391907, 256150, 75799
                 },
                 new int[] {
                   268944, 342402, 894352, 228640, 903885, 908656, 414271, 292588, 852057, 889141
                 },
                 new int[] {
                   662939, 340220, 600081, 390298, 376707, 372199, 435097, 40266, 145590, 505103
                 }),
         7230607);
     int[] a = new int[50];
     int[] b = new int[50];
     int[] c = new int[50];
     fill(a, 1);
     fill(b, 1);
     fill(c, 1);
     eq(5, (new BallsSeparating_2()).minOperations(a, b, c), 7230607);
   } catch (Exception exx) {
     System.err.println(exx);
     exx.printStackTrace(System.err);
   }
 }
  // BEGIN CUT HERE
  public static void main(String[] args) {
    try {
      eq(0, (new ImprovingStatistics_NOTSOLVED()).howManyGames(10, 8), 1);
      eq(1, (new ImprovingStatistics_NOTSOLVED()).howManyGames(100, 80), 6);
      eq(2, (new ImprovingStatistics_NOTSOLVED()).howManyGames(47, 47), -1);
      eq(3, (new ImprovingStatistics_NOTSOLVED()).howManyGames(99000, 0), 1000);
      eq(4, (new ImprovingStatistics_NOTSOLVED()).howManyGames(1000000000, 470000000), 19230770);
      eq(4, (new ImprovingStatistics_NOTSOLVED()).howManyGames(1750, 1015), 43);
      eq(4, (new ImprovingStatistics_NOTSOLVED()).howManyGames(32532, 3342), 266);

    } catch (Exception exx) {
      System.err.println(exx);
      exx.printStackTrace(System.err);
    }
  }
    public void loadFromFile(File f) {
      try {
        BufferedReader reader = new BufferedReader(new FileReader(f));
        String s = reader.readLine();
        String[] ins = s.split("[,;] ");
        numFeatures = new Integer(ins[0]);
        classification = new Integer(ins[1]);

        double[][] d = new double[ins.length - 2][1];
        for (int i = 2; i < ins.length; ++i) d[i - 2][0] = new Double(ins[i]);
        Matrix m = new Matrix(d);
        parameter = m;
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
示例#12
0
文件: A.java 项目: hiroshi-cl/wakaba
    public void diff(int id, String small, String large) {
      try {
        Scanner sm = new Scanner(new File(small));
        Scanner lg = new Scanner(new File(large));
        int line = 0;
        while (sm.hasNextLine() && lg.hasNextLine()) {
          String s = sm.nextLine();
          String l = lg.nextLine();
          if (!s.equals(l)) {
            System.out.println(line + ">" + s);
            System.out.println(line + "<" + l);
          }
          line++;
        }

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
 private IntervalXYDataset getHistrogrammedDataAttributes(
     String[] attributes, long barsize, long timesize) {
   IntervalXYDataset dataset = null;
   if (no_intervals) {
     dataset = new XYSeriesCollection();
   } else {
     dataset = new YIntervalSeriesCollection();
   }
   for (int index = 0; index < attributes.length; index++) {
     Histogram histogram = new Histogram(barsize);
     String attribute = attributes[index];
     for (ProcessInstance pi : mylog.getInstances()) {
       Date begin;
       try {
         begin = pi.getAuditTrailEntryList().get(0).getTimestamp();
       } catch (Exception e) {
         Message.add(e.getMessage(), Message.ERROR);
         return null;
       } // starting time of process instance
       int j = 0;
       for (AuditTrailEntry ate : pi.getListOfATEs()) {
         if (ate.getAttributes().containsKey(attribute)) {
           Double val;
           val = Double.valueOf(ate.getAttributes().get(attribute));
           if (xbox.getSelectedIndex() == 2) {
             histogram.addValue(j, val);
           }
           if (xbox.getSelectedIndex() == 3) {
             histogram.addValue(timediff(begin, ate.getTimestamp()), val);
           }
           j++;
         }
       }
     }
     if (no_intervals) {
       ((XYSeriesCollection) dataset).addSeries(histogram.getXYSeries(attribute, timesize));
     } else {
       ((YIntervalSeriesCollection) dataset)
           .addSeries(histogram.getYIntervalSeries(attribute, timesize));
     }
   }
   return dataset;
 }
示例#14
0
  private void highlightError(int index) {
    String message = (String) messages.elementAt(index);
    int i = message.indexOf(":");

    if ((i != -1) && (i < 10)) {
      try {
        int lineNumber = Integer.parseInt(message.substring(0, i).trim()) - 1;
        if (lineNumber < sourceArea.getLineCount()) {
          int start = sourceArea.getLineStartOffset(lineNumber);
          int end = sourceArea.getLineEndOffset(lineNumber);

          sourceArea.requestFocus();
          sourceArea.setSelectionStart(start);
          sourceArea.setSelectionEnd(end - 1);
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }
    public void loadFromString(String s) {
      try {
        String[] ins = s.split("[,;] ");
        ArrayList<String> inl = new ArrayList<String>();
        for (String in : ins) {
          in.trim();
          if (!in.isEmpty()) inl.add(in);
        }

        numFeatures = new Integer(inl.get(0));
        classification = new Integer(inl.get(1));

        double[][] d = new double[inl.size() - 2][1];
        for (int i = 0; i < numFeatures; ++i) d[i][0] = new Double(inl.get(i + 2));
        Matrix m = new Matrix(d);
        parameter = m;
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  /**
   * Calculates the cost of the <code>trainingSet</code>.
   *
   * @param hyp the hypothesis to use in calculating the cost.
   * @return the cost associated with the hypothesis.
   */
  public double defaultCostFunction(Hypothesis hyp) {
    double error = 0;
    double h;
    int answer;
    for (TrainingExample t : trainingSet) {
      try {
        h = (Double) hyp.predict(t.getInput());
      } catch (Exception e) {
        e.printStackTrace();
        continue;
      }
      answer = t.getAnswer();
      error -= answer * log(h) + (1 - answer) * log(1 - h);
    }

    double regError = 0;
    for (int i = 0; i < hyp.getNumFeatures(); ++i) {
      regError += pow(hyp.getParameter(i), 2);
    }
    error += regError / regularizationParam;

    return error / (2 * trainingSet.length);
  }
  public void loadFromFile(File f) {
    ArrayList<Hypothesis> hl = new ArrayList<Hypothesis>();
    String s;
    try {
      BufferedReader reader = new BufferedReader(new FileReader(f));
      Hypothesis hyp;
      while ((s = reader.readLine()) != null) {
        if (s.equals("")) continue;
        hyp = new Hypothesis(0, 0);
        hyp.loadFromString(s);
        hl.add(hyp);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    hypothesis = new Hypothesis[hl.size()];
    int i = 0;
    for (Hypothesis h : hl) {
      hypothesis[i] = h;
      ++i;
    }
  }
示例#18
0
  EditFrame(RopeFrame parent) {
    super(parent);

    // Implement a smarter way to set the initial frame position and size
    setLocation(0, 0);
    setSize(670, 705);

    try {
      jbInit();
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    sourceArea.addCaretListener(this);
    browseButton.addActionListener(this);
    optionsButton.addActionListener(this);
    assembleButton.addActionListener(this);
    saveButton.addActionListener(this);

    messageList.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent event) {
            highlightError(messageList.locationToIndex(event.getPoint()));
          }
        });

    undoMgr = new CompoundUndoManager(sourceArea);

    undoAction = undoMgr.getUndoAction();
    redoAction = undoMgr.getRedoAction();

    undoMgr.updateUndoAction = new UpdateUndoAction();
    undoMgr.updateRedoAction = new UpdateRedoAction();

    document = sourceArea.getDocument();

    ActionMap am = sourceArea.getActionMap();
    InputMap im = sourceArea.getInputMap(JComponent.WHEN_FOCUSED);

    // Remove automatic key bindings because we want them controlled by menu items
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, RopeHelper.modifierMaks), "none");
    im.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_Z, RopeHelper.modifierMaks + InputEvent.SHIFT_MASK),
        "none");
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, RopeHelper.modifierMaks), "none");
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, RopeHelper.modifierMaks), "none");
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, RopeHelper.modifierMaks), "none");
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, RopeHelper.modifierMaks), "none");
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_L, RopeHelper.modifierMaks), "none");

    // Set custom binding action for tab key
    String action = "tabKeyAction";
    im.put(KeyStroke.getKeyStroke("TAB"), action);
    am.put(
        action,
        new AbstractAction() {
          private static final long serialVersionUID = 1L;

          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              int caretPos = sourceArea.getCaretPosition();
              int lineNum = sourceArea.getLineOfOffset(caretPos);
              int startLine = sourceArea.getLineStartOffset(lineNum);
              int endLine = sourceArea.getLineEndOffset(lineNum);
              int linePos = caretPos - startLine;

              if (linePos >= 39 && linePos < 79) {
                caretPos = startLine + linePos + 10 - ((linePos + 1) % 10);
              } else if (linePos >= 20 && linePos <= 39) {
                caretPos = startLine + 39;
              } else if (linePos >= 15 && linePos <= 19) {
                caretPos = startLine + 20;
              } else if (linePos >= 5 && linePos <= 14) {
                caretPos = startLine + 15;
              } else {
                caretPos = startLine + 5;
              }

              // If the line is shorter than the new position fo the caret add enough spaces...
              if (caretPos > endLine) {
                StringBuilder str = new StringBuilder();
                int size = caretPos - endLine;
                while (size-- >= 0) {
                  str.append(' ');
                }
                document.insertString(endLine - 1, str.toString(), null);
              }

              sourceArea.setCaretPosition(caretPos);
            } catch (BadLocationException ex) {
              ex.printStackTrace();
            }
          }
        });

    // Set custom binding action for return/enter key
    String actionKey = "backspaceKeyAction";
    im.put(KeyStroke.getKeyStroke("BACK_SPACE"), actionKey);
    am.put(
        actionKey,
        new AbstractAction()
        // How can I get the original action?
        {
          private static final long serialVersionUID = 1L;

          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              int caretPos = sourceArea.getCaretPosition();
              int lineNum = sourceArea.getLineOfOffset(caretPos);
              int startLine = sourceArea.getLineStartOffset(lineNum);
              int endLine = sourceArea.getLineEndOffset(lineNum);
              int linePos = caretPos - startLine;

              if (linePos == 15) {
                int endPos = 5;
                int charPos = linePos;
                for (; charPos > endPos; charPos--) {
                  char ch = sourceArea.getText().charAt((startLine + charPos) - 1);
                  if (!Character.isWhitespace(ch)) {
                    break;
                  }
                }

                sourceArea.setCaretPosition(startLine + charPos);
              } else {
                int startSel = sourceArea.getSelectionStart();
                int endSel = sourceArea.getSelectionEnd();
                if (startSel == endSel) {
                  startSel = caretPos - 1;
                  endSel = caretPos;
                }

                StringBuilder sb = new StringBuilder(sourceArea.getText());
                sb.replace(startSel, endSel, "");
                sourceArea.setText(sb.toString());
                sourceArea.setCaretPosition(startSel);
              }
            } catch (BadLocationException ex) {
              ex.printStackTrace();
            }
          }
        });

    // Set custom binding action for return/enter key
    action = "enterKeyAction";
    im.put(KeyStroke.getKeyStroke("ENTER"), action);
    am.put(
        action,
        new AbstractAction() {
          private static final long serialVersionUID = 1L;

          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              int caretPos = sourceArea.getCaretPosition();
              int lineNum = sourceArea.getLineOfOffset(caretPos);
              int startLine = sourceArea.getLineStartOffset(lineNum);
              int linePos = caretPos - startLine;

              if (linePos >= 5) {
                document.insertString(caretPos, "\n     ", null);
              } else {
                document.insertString(caretPos, "\n", null);
              }
            } catch (BadLocationException ex) {
              ex.printStackTrace();
            }
          }
        });

    document.addDocumentListener(
        new DocumentListener() {
          @Override
          public void insertUpdate(DocumentEvent e) {
            setSourceChanged(true);
          }

          @Override
          public void removeUpdate(DocumentEvent e) {
            setSourceChanged(true);
          }

          @Override
          public void changedUpdate(DocumentEvent e) {
            setSourceChanged(true);
          }
        });
  }