Example usage for weka.core SerializationHelper writeAll

List of usage examples for weka.core SerializationHelper writeAll

Introduction

In this page you can find the example usage for weka.core SerializationHelper writeAll.

Prototype

public static void writeAll(OutputStream stream, Object[] o) throws Exception 

Source Link

Document

serializes the given objects to the specified stream.

Usage

From source file:homemadeWEKA.java

public static void save_modelWithEval(Classifier cls, Evaluation eval) throws Exception {
    Object[] o = new Object[2];
    o[0] = cls;/*from ww w. j  a va  2s. co m*/
    o[1] = eval;
    SerializationHelper.writeAll("j48_10folds.model", o);
}

From source file:meka.classifiers.multilabel.Evaluation.java

License:Open Source License

/**
 * RunExperiment - Build and evaluate a model with command-line options.
 * @param   h      multi-label classifier
 * @param   options   command line options
 *///from   www .  j  a va 2s  .  c om
public static void runExperiment(MultiLabelClassifier h, String options[]) throws Exception {

    // Help
    if (Utils.getOptionPos('h', options) >= 0) {
        System.out.println("\nHelp requested");
        Evaluation.printOptions(h.listOptions());
        return;
    }

    h.setOptions(options);

    if (h.getDebug())
        System.out.println("Loading and preparing dataset ...");

    // Load Instances from a file
    Instances D_train = loadDataset(options);

    Instances D_full = D_train;

    // Try extract and set a class index from the @relation name
    MLUtils.prepareData(D_train);

    // Override the number of classes with command-line option (optional)
    if (Utils.getOptionPos('C', options) >= 0) {
        int L = Integer.parseInt(Utils.getOption('C', options));
        D_train.setClassIndex(L);
    }

    // We we still haven't found -C option, we can't continue (don't know how many labels)
    int L = D_train.classIndex();
    if (L <= 0) {
        throw new Exception(
                "[Error] Number of labels not specified.\n\tYou must set the number of labels with the -C option, either inside the @relation tag of the Instances file, or on the command line.");
        // apparently the dataset didn't contain the '-C' flag, check in the command line options ...
    }

    // Randomize (Instances) 
    int seed = (Utils.getOptionPos('s', options) >= 0) ? Integer.parseInt(Utils.getOption('s', options)) : 0;
    if (Utils.getFlag('R', options)) {
        D_train.randomize(new Random(seed));
    }
    boolean Threaded = false;
    if (Utils.getOptionPos("Thr", options) >= 0) {
        Threaded = Utils.getFlag("Thr", options);
    }

    // Verbosity Option
    String voption = "1";
    if (Utils.getOptionPos("verbosity", options) >= 0) {
        voption = Utils.getOption("verbosity", options);
    }

    // Save for later?
    //String fname = null;
    //if (Utils.getOptionPos('f',options) >= 0) {
    //   fname = Utils.getOption('f',options);
    //}
    // Dump for later?
    String dname = null;
    if (Utils.getOptionPos('d', options) >= 0) {
        dname = Utils.getOption('d', options);
    }
    // Load from file?
    String lname = null;
    Instances dataHeader = null;
    if (Utils.getOptionPos('l', options) >= 0) {
        lname = Utils.getOption('l', options);
        Object[] data = SerializationHelper.readAll(lname);
        h = (MultiLabelClassifier) data[0];
        if (data.length > 1)
            dataHeader = (Instances) data[1];
        //Object o[] = SerializationHelper.readAll(lname);
        //h = (MultilabelClassifier)o[0];
    }

    try {

        Result r = null;

        // Threshold OPtion
        String top = "PCut1"; // default
        if (Utils.getOptionPos("threshold", options) >= 0)
            top = Utils.getOption("threshold", options);

        if (Utils.getOptionPos('x', options) >= 0) {
            // CROSS-FOLD-VALIDATION

            int numFolds = MLUtils.getIntegerOption(Utils.getOption('x', options), 10); // default 10
            // Check for remaining options
            Utils.checkForRemainingOptions(options);
            r = Evaluation.cvModel(h, D_train, numFolds, top, voption);
            System.out.println(r.toString());
        } else {
            // TRAIN-TEST SPLIT

            Instances D_test = null;

            if (Utils.getOptionPos('T', options) >= 0) {
                // load separate test set
                try {
                    D_test = loadDataset(options, 'T');
                    MLUtils.prepareData(D_test);
                } catch (Exception e) {
                    throw new Exception("[Error] Failed to Load Test Instances from file.", e);
                }
            } else {
                // split training set into train and test sets
                // default split
                int N_T = (int) (D_train.numInstances() * 0.60);
                if (Utils.getOptionPos("split-percentage", options) >= 0) {
                    // split by percentage
                    double percentTrain = Double.parseDouble(Utils.getOption("split-percentage", options));
                    N_T = (int) Math.round((D_train.numInstances() * (percentTrain / 100.0)));
                } else if (Utils.getOptionPos("split-number", options) >= 0) {
                    // split by number
                    N_T = Integer.parseInt(Utils.getOption("split-number", options));
                }

                int N_t = D_train.numInstances() - N_T;
                D_test = new Instances(D_train, N_T, N_t);
                D_train = new Instances(D_train, 0, N_T);

            }

            // Invert the split?
            if (Utils.getFlag('i', options)) { //boolean INVERT          = Utils.getFlag('i',options);
                Instances temp = D_test;
                D_test = D_train;
                D_train = temp;
            }

            // Check for remaining options
            Utils.checkForRemainingOptions(options);

            if (h.getDebug())
                System.out.println(":- Dataset -: " + MLUtils.getDatasetName(D_train) + "\tL=" + L
                        + "\tD(t:T)=(" + D_train.numInstances() + ":" + D_test.numInstances() + ")\tLC(t:T)="
                        + Utils.roundDouble(MLUtils.labelCardinality(D_train, L), 2) + ":"
                        + Utils.roundDouble(MLUtils.labelCardinality(D_test, L), 2) + ")");

            if (lname != null) {
                // h is already built, and loaded from a file, test it!
                r = testClassifier(h, D_test);

                String t = top;

                if (top.startsWith("PCut")) {
                    // if PCut is specified we need the training data,
                    // so that we can calibrate the threshold!
                    t = MLEvalUtils.getThreshold(r.predictions, D_train, top);
                }
                r = evaluateModel(h, D_test, t, voption);
            } else {
                //check if train and test set size are > 0
                if (D_train.numInstances() > 0 && D_test.numInstances() > 0) {
                    if (Threaded) {
                        r = evaluateModelM(h, D_train, D_test, top, voption);
                    } else {

                        r = evaluateModel(h, D_train, D_test, top, voption);
                    }
                } else {
                    // otherwise just train on full set. Maybe better throw an exception.
                    h.buildClassifier(D_full);

                }
            }

            // @todo, if D_train==null, assume h is already trained
            if (D_train.numInstances() > 0 && D_test.numInstances() > 0) {
                System.out.println(r.toString());
            }
        }

        // Save model to file?
        if (dname != null) {
            dataHeader = new Instances(D_train, 0);
            SerializationHelper.writeAll(dname, new Object[] { h, dataHeader });
        }

    } catch (Exception e) {
        e.printStackTrace();
        Evaluation.printOptions(h.listOptions());
        System.exit(1);
    }

    System.exit(0);
}

From source file:meka.gui.explorer.classify.SaveModel.java

License:Open Source License

/**
 * Returns the action lister to use in the menu.
 *
 * @param history   the current history//from www.j  a  va 2  s . c om
 * @param index     the selected history item
 * @return          the listener
 */
@Override
public ActionListener getActionListener(final ResultHistoryList history, final int index) {
    return new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int retVal = getFileChooser().showSaveDialog(null);
            if (retVal != MekaFileChooser.APPROVE_OPTION)
                return;
            File file = getFileChooser().getSelectedFile();
            try {
                SerializationHelper.writeAll(file.getAbsolutePath(), (Object[]) history.getPayloadAt(index));
            } catch (Exception ex) {
                String msg = "Failed to write model to '" + file + "'!";
                System.err.println(msg);
                ex.printStackTrace();
                JOptionPane.showMessageDialog(null, msg + "\n" + e);
            }
        }
    };
}