Example usage for weka.core Instances numAttributes

List of usage examples for weka.core Instances numAttributes

Introduction

In this page you can find the example usage for weka.core Instances numAttributes.

Prototype


publicint numAttributes() 

Source Link

Document

Returns the number of attributes.

Usage

From source file:PCADetector.java

License:Apache License

public double[] getStandardDeviation(Instances Matrix) {
    int numAtts = Matrix.numAttributes();
    int numInsts = Matrix.numInstances();
    double[] att1 = new double[numInsts];
    double[] std = new double[numAtts];
    for (int i = 0; i < numAtts; i++) {
        for (int j = 0; j < numInsts; j++) {
            att1[j] = Matrix.instance(j).value(i);
        }/* w ww .  ja  v a 2  s  . c  o m*/
        std[i] = Math.sqrt(Utils.variance(att1));
    }
    return std;
}

From source file:A_AdvanceMachineLearning.java

private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
    UIManager.put("OptionPane.yesButtonText", "Confirm");
    UIManager.put("OptionPane.noButtonText", "Cancel");
    int dialogButton = JOptionPane.YES_NO_OPTION;
    int dialogResult = JOptionPane.showConfirmDialog(this, "The labels must be the same used in the weka model",
            "Advance Machine learning", dialogButton, JOptionPane.WARNING_MESSAGE);
    if (dialogResult == 0) {
        this.list.clear();
        //txtcodigo1.setText("hola");
        this.valor = txtcodigo1.getText();
        this.valor1 = txtcodigo2.getText();
        this.valor2 = txtcodigo3.getText();
        this.valor3 = txtcodigo4.getText();
        this.valor4 = txtcodigo5.getText();
        this.valor5 = txtcodigo6.getText();
        //IJ.showMessage("your label 1 is = "+valor+", "+valor1+", "+valor2+", "+valor3+", "+valor4);
        // Array list
        this.list.add(this.valor);
        this.list.add(this.valor1);
        this.list.add(this.valor2);
        this.list.add(this.valor3);
        this.list.add(this.valor4);
        this.list.add(this.valor5);
        this.list.removeAll(Arrays.asList("", null));
        System.out.println(this.list);
        this.liststring = "";

        for (String s : this.list) {
            this.liststring += s + ",";
        }/*  w  ww.  ja  v a 2s .  c  o m*/
        txtlabel.setText(this.liststring);

        System.out.println(this.liststring);
        txtarea.setText("Your labels are = " + this.list + "\nThe labels had been saved");
        //txtarea.setText("The labels had been saved");

        System.out.println(label);

    } else {
        System.out.println("No Option");

    }
    Instances data;
    try {
        System.out.println(this.file2 + "arff");
        FileReader reader = new FileReader(this.file2 + ".arff");
        BufferedReader br = new BufferedReader(reader);

        data = new Instances(br);
        System.out.println(data);
        Instances newData = null;
        Add filter;
        newData = new Instances(data);
        filter = new Add();
        filter.setAttributeIndex("last");
        filter.setNominalLabels(this.liststring);
        filter.setAttributeName(txtcodigo7.getText());
        filter.setInputFormat(newData);
        newData = Filter.useFilter(newData, filter);
        System.out.print("hola" + newData);
        Vector vec = new Vector();
        newData.setClassIndex(newData.numAttributes() - 1);
        if (!newData.equalHeaders(newData)) {
            throw new IllegalArgumentException("Train and test are not compatible!");
        }

        Classifier cls = (Classifier) weka.core.SerializationHelper.read(this.model);
        System.out.println("PROVANT MODEL.classifyInstance");
        for (int i = 0; i < newData.numInstances(); i++) {
            double pred = cls.classifyInstance(newData.instance(i));
            double[] dist = cls.distributionForInstance(newData.instance(i));
            System.out.print((i + 1) + " - ");
            System.out.print(newData.classAttribute().value((int) pred) + " - ");
            //txtarea2.setText(Utils.arrayToString(dist));

            System.out.println(Utils.arrayToString(dist));

            vec.add(newData.classAttribute().value((int) pred));

            classif.add(newData.classAttribute().value((int) pred));
        }

        classif.removeAll(Arrays.asList("", null));
        System.out.println(classif);
        String vecstring = "";

        for (Object s : classif) {
            vecstring += s + ",";

        }
        Map<String, Integer> seussCount = new HashMap<String, Integer>();
        for (String t : classif) {
            Integer i = seussCount.get(t);
            if (i == null) {
                i = 0;
            }
            seussCount.put(t, i + 1);
        }
        String s = vecstring;
        String in = vecstring;
        int i = 0;
        Pattern p = Pattern.compile(this.valor1);
        Matcher m = p.matcher(in);
        while (m.find()) {
            i++;
        }

        System.out.println("hola " + i); // Prints 2

        System.out.println(seussCount);
        txtarea2.append("Your file:" + this.file2 + "arff" + "\n is composed by" + seussCount);
        IJ.showMessage("Your file:" + this.file2 + "arff" + "\n is composed by" + seussCount);
    } catch (Exception ex) {
        Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex);
    }

    //IJ.showMessage("analysing complete ");// TODO add your handling code here:
}

From source file:MeansClassifier.java

public static void main(String[] args) throws Exception {
    Instances read = null;
    String str = "\\\\ueahome4\\stusci4\\ysj13kxu\\data\\Documents\\Sheet2_Train.arff";
    FileReader r;/*from  w  ww. jav  a  2 s.c o  m*/
    try {
        r = new FileReader(str);
        read = new Instances(r);
        read.setClassIndex(read.numAttributes() - 1);
    } catch (Exception e) {
        System.out.println(" Exception caught =" + e);
    }
    MeansClassifier m = new MeansClassifier();
    m.buildClassifier(read);
}

From source file:MeansClassifier.java

@Override
public void buildClassifier(Instances i) throws Exception {

    double[][] means = new double[i.numClasses()][i.numAttributes() - 1];

    for (int j = 0; j < i.size(); j++) {
        if (i.instance(j).classValue() == 0) {
            zeros.add(i.instance(j).value(0));
        }//from   w  ww  . ja  v a2  s . co  m
        if (i.instance(j).classValue() == 1) {
            ones.add(i.instance(j).value(0));
        }
    }
    double zero1 = 0, one1 = 0;
    for (int k = 0; k < zeros.size(); k++) {
        zero1 = zero1 + zeros.get(k);
    }
    for (int l = 0; l < ones.size(); l++) {
        one1 = one1 + ones.get(l);
    }
    System.out.println("For class 0, mean is " + (zero1 / zeros.size()));
    System.out.println("For class 1, mean is " + (one1 / ones.size()));
}

From source file:aaa.util.test.CreateArff.java

License:Open Source License

/**
 * Generates the Instances object and outputs it in ARFF format to stdout.
 *
 * @param args   ignored/*from  w  w w.  j  a  va 2 s . co  m*/
 * @throws Exception   if generation of instances fails
 */
public static void main(String[] args) throws Exception {
    ArrayList<Attribute> atts;
    ArrayList<Attribute> attsRel;
    ArrayList<String> attVals;
    ArrayList<String> attValsRel;
    Instances data;
    Instances dataRel;
    double[] vals;
    double[] valsRel;
    int i;

    // 1. set up attributes
    atts = new ArrayList<Attribute>();
    // - numeric
    atts.add(new Attribute("att1"));
    // - nominal
    attVals = new ArrayList<String>();
    for (i = 0; i < 5; i++)
        attVals.add("val" + (i + 1));
    atts.add(new Attribute("att2", attVals));
    // - string
    atts.add(new Attribute("att3", (ArrayList<String>) null));
    // - date
    atts.add(new Attribute("att4", "yyyy-MM-dd"));
    // - relational
    attsRel = new ArrayList<Attribute>();
    // -- numeric
    attsRel.add(new Attribute("att5.1"));
    // -- nominal
    attValsRel = new ArrayList<String>();
    for (i = 0; i < 5; i++)
        attValsRel.add("val5." + (i + 1));
    attsRel.add(new Attribute("att5.2", attValsRel));
    dataRel = new Instances("att5", attsRel, 0);
    atts.add(new Attribute("att5", dataRel, 0));

    // 2. create Instances object
    data = new Instances("MyRelation", atts, 0);

    // 3. fill with data
    // first instance
    vals = new double[data.numAttributes()];
    // - numeric
    vals[0] = Math.PI;
    // - nominal
    vals[1] = attVals.indexOf("val3");
    // - string
    vals[2] = data.attribute(2).addStringValue("This is a string!");
    // - date
    vals[3] = data.attribute(3).parseDate("2001-11-09");
    // - relational
    dataRel = new Instances(data.attribute(4).relation(), 0);
    // -- first instance
    valsRel = new double[2];
    valsRel[0] = Math.PI + 1;
    valsRel[1] = attValsRel.indexOf("val5.3");
    dataRel.add(new DenseInstance(1.0, valsRel));
    // -- second instance
    valsRel = new double[2];
    valsRel[0] = Math.PI + 2;
    valsRel[1] = attValsRel.indexOf("val5.2");
    dataRel.add(new DenseInstance(1.0, valsRel));
    vals[4] = data.attribute(4).addRelation(dataRel);
    // add
    data.add(new DenseInstance(1.0, vals));

    // second instance
    vals = new double[data.numAttributes()]; // important: needs NEW array!
    // - numeric
    vals[0] = Math.E;
    // - nominal
    vals[1] = attVals.indexOf("val1");
    // - string
    vals[2] = data.attribute(2).addStringValue("And another one!");
    // - date
    vals[3] = data.attribute(3).parseDate("2000-12-01");
    // - relational
    dataRel = new Instances(data.attribute(4).relation(), 0);
    // -- first instance
    valsRel = new double[2];
    valsRel[0] = Math.E + 1;
    valsRel[1] = attValsRel.indexOf("val5.4");
    dataRel.add(new DenseInstance(1.0, valsRel));
    // -- second instance
    valsRel = new double[2];
    valsRel[0] = Math.E + 2;
    valsRel[1] = attValsRel.indexOf("val5.1");
    dataRel.add(new DenseInstance(1.0, valsRel));
    vals[4] = data.attribute(4).addRelation(dataRel);
    // add
    data.add(new DenseInstance(1.0, vals));

    // 4. output data
    System.out.println(data);
}

From source file:AaronTest.ShapeletTransformExperiments.java

public static void initializeShapelet(FullShapeletTransform s, Instances data,
        QualityMeasures.ShapeletQualityChoice qm) {
    //transform from 3- n, where n is the max length of the series.
    s.setNumberOfShapelets(data.numAttributes() / 2);
    int minLength = 3;
    int maxLength = data.numAttributes() - 1;
    s.setShapeletMinAndMax(minLength, maxLength);
    s.setQualityMeasure(qm);/*from   w w  w .j av  a  2  s . c om*/
    s.turnOffLog();
}

From source file:ab.demo.AIAssignment2.java

License:Open Source License

public GameState solve() {

    // capture Image
    BufferedImage screenshot = ActionRobot.doScreenShot();

    // process image
    Vision vision = new Vision(screenshot);

    // find the slingshot
    Rectangle sling = vision.findSlingshotMBR();

    // confirm the slingshot
    while (sling == null && aRobot.getState() == GameState.PLAYING) {
        System.out.println("No slingshot detected. Please remove pop up or zoom out");
        ActionRobot.fullyZoomOut();/*ww  w. j a va 2s  .  c o  m*/
        screenshot = ActionRobot.doScreenShot();
        vision = new Vision(screenshot);
        sling = vision.findSlingshotMBR();
    }

    // get all the pigs
    List<ABObject> pigs = vision.findPigsMBR();
    List<ABObject> blocks = vision.findBlocksMBR();

    GameState state = aRobot.getState();

    // if there is a sling, then play, otherwise just skip.
    if (sling != null) {

        if (!pigs.isEmpty()) { //if there are pigs in the level

            Point releasePoint = null;
            Shot shot = new Shot();
            int dx, dy;
            {
                //random pick up a pig
                ABObject pig = pigs.get(randomGenerator.nextInt(pigs.size()));
                Point _tpt = pig.getCenter();

                // estimate the trajectory
                ArrayList<Point> pts = tp.estimateLaunchPoint(sling, _tpt);

                //define all of the wood, ice and stone in the stage
                ArrayList<ABObject> wood = new ArrayList<ABObject>();
                ArrayList<ABObject> stone = new ArrayList<ABObject>();
                ArrayList<ABObject> ice = new ArrayList<ABObject>();
                ArrayList<ABObject> tnt = new ArrayList<ABObject>();

                //initialise counters to store how many times the trajectory intersects blocks of these types
                int woodCount = 0;
                int stoneCount = 0;
                int iceCount = 0;
                int pigsCount = 0;
                int tntCount = 0;

                //populate the wood, stone and ice ArrayLists with the correct materials
                for (int i = 0; i < blocks.size(); i++) {
                    if (blocks.get(i).type == ABType.Wood)
                        wood.add(blocks.get(i));
                    if (blocks.get(i).type == ABType.Stone)
                        stone.add(blocks.get(i));
                    if (blocks.get(i).type == ABType.Ice)
                        ice.add(blocks.get(i));
                    if (blocks.get(i).type == ABType.TNT)
                        tnt.add(blocks.get(i));
                }

                //check whether the trajectory intersects any wood blocks
                for (int i = 0; i < wood.size(); i++) {
                    for (int j = 0; j < pts.size(); j++) {
                        if (wood.get(i).contains(pts.get(j))) {
                            System.out.println("Trajectory intersects some wood");
                            woodCount++;
                        }
                        if (pig.contains(pts.get(j))) //if we find the pig on this point
                            j = pts.size() - 1; //stop looking for wood on the trajectory (escape for loop)
                    }
                }

                //check whether the trajectory intersects any ice blocks
                for (int i = 0; i < ice.size(); i++) {
                    for (int j = 0; j < pts.size(); j++) {
                        if (ice.get(i).contains(pts.get(j))) {
                            System.out.println("Trajectory intersects some ice");
                            iceCount++;
                        }
                        if (pig.contains(pts.get(j))) //if we find the pig on this point
                            j = pts.size() - 1; //stop looking for ice on the trajectory (escape for loop)
                    }
                }

                //check whether the trajectory intersects any stone blocks            
                for (int i = 0; i < stone.size(); i++) {
                    for (int j = 0; j < pts.size(); j++) {
                        if (stone.get(i).contains(pts.get(j))) {
                            System.out.println("Trajectory intersects some stone");
                            stoneCount++;
                        }
                        if (pig.contains(pts.get(j))) //if we find the pig on this point
                            j = pts.size() - 1; //stop looking for stone on the trajectory (escape for loop)
                    }
                }

                //how many pigs the trajectory intersects (this should always be at least 1)         
                for (int i = 0; i < pigs.size(); i++) {
                    for (int j = 0; j < pts.size(); j++) {
                        if (pigs.get(i).contains(pts.get(j))) {
                            System.out.println("Trajectory intersects a pig");
                            pigsCount++;
                        }
                    }
                }

                //how many tnt blocks the trajectory intersects            
                for (int i = 0; i < tnt.size(); i++) {
                    for (int j = 0; j < pts.size(); j++) {
                        if (tnt.get(i).contains(pts.get(j))) {
                            System.out.println("Trajectory intersects some tnt");
                            tntCount++;
                        }
                        if (pig.contains(pts.get(j))) //if we find the pig on this point
                            j = pts.size() - 1; //stop looking for tnt on the trajectory
                    }
                }

                StringBuilder sb = new StringBuilder();
                sb.append(pigsCount + "," + woodCount + "," + iceCount + "," + stoneCount + "," + tntCount
                        + ",?");
                String dataEntry = sb.toString();
                try (PrintWriter out = new PrintWriter(
                        new BufferedWriter(new FileWriter("dataset/birds.level.arff", true)))) {
                    out.println(dataEntry);
                } catch (IOException e) {
                    System.out.println("Error - dataset/birds.level.arff file not found or in use!");
                }

                //indicator of if the agent should continue this shot or not (used in the bayes classifier)
                ArrayList<Boolean> takeShot = new ArrayList<Boolean>();

                try {
                    DataSource source = new DataSource("dataset/birds.data.arff"); //initialise the learning set for the agent
                    Instances data = source.getDataSet();

                    // setting class attribute if the data format does not provide this information
                    // For example, the XRFF format saves the class attribute information as well
                    if (data.classIndex() == -1)
                        data.setClassIndex(data.numAttributes() - 1);

                    DataSource thisLevel = new DataSource("dataset/birds.level.arff"); //initialise the data retrieved from the current level for the agent
                    Instances thisLevelData = thisLevel.getDataSet();
                    if (thisLevelData.classIndex() == -1)
                        thisLevelData.setClassIndex(data.numAttributes() - 1);

                    //build a new NaiveBayes classifier
                    NaiveBayes bayes = new NaiveBayes();
                    bayes.buildClassifier(data);

                    for (int i = 0; i < thisLevelData.numInstances(); i++) { //for all instances in the current level
                        double label = bayes.classifyInstance(thisLevelData.instance(i)); //generate an outcome/classify an instance in the current level
                        thisLevelData.instance(i).setClassValue(label); //store this outcome
                        System.out.println(thisLevelData.instance(i).stringValue(5)); //print it
                        if (thisLevelData.instance(i).stringValue(5) != "?") { //if there is a decisive choice as to whether a shot should be taken
                            data.add(thisLevelData.instance(i)); //store it
                            if (thisLevelData.instance(i).stringValue(5) == "yes") {//if the classifier classifies a good shot, store it
                                takeShot.add(true);
                            } else { //if no, store this too
                                takeShot.add(false);
                            }
                        }
                    }

                    //add all non ? entries to the learning set
                    BufferedWriter writer = new BufferedWriter(new FileWriter("dataset/birds.data.arff"));
                    writer.write(data.toString());
                    writer.flush();
                    writer.close();

                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("Exception caught - file handle error");
                }

                //TODO: roll a random number to determine whether we take a shot or not.
                //populated using the bayesian classification above.
                //if we roll true, continue with the random pig shot as usual.
                //if not, take a new random pig and try again.
                //TODO: implement a failsafe so the agent does not get stuck randomly choosing pigs which the bayesian classification does not allow.
                Random rng = new Random(takeShot.size());
                if (takeShot.get(rng.nextInt()))
                    System.out.println("Taking this shot.");
                else {
                    System.out.println("Not taking this shot. Finding another random pig.");
                    return state;
                }

                // if the target is very close to before, randomly choose a
                // point near it
                if (prevTarget != null && distance(prevTarget, _tpt) < 10) {
                    double _angle = randomGenerator.nextDouble() * Math.PI * 2;
                    _tpt.x = _tpt.x + (int) (Math.cos(_angle) * 10);
                    _tpt.y = _tpt.y + (int) (Math.sin(_angle) * 10);
                    System.out.println("Randomly changing to " + _tpt);
                }

                prevTarget = new Point(_tpt.x, _tpt.y);

                // do a high shot when entering a level to find an accurate velocity
                if (firstShot && pts.size() > 1) {
                    releasePoint = pts.get(1);
                } else if (pts.size() == 1)
                    releasePoint = pts.get(0);
                else if (pts.size() == 2) {
                    // randomly choose between the trajectories, with a 1 in
                    // 6 chance of choosing the high one
                    if (randomGenerator.nextInt(6) == 0)
                        releasePoint = pts.get(1);
                    else
                        releasePoint = pts.get(0);
                } else if (pts.isEmpty()) {
                    System.out.println("No release point found for the target");
                    System.out.println("Try a shot with 45 degree");
                    releasePoint = tp.findReleasePoint(sling, Math.PI / 4);
                }

                // Get the reference point
                Point refPoint = tp.getReferencePoint(sling);

                //Calculate the tapping time according the bird type 
                if (releasePoint != null) {
                    double releaseAngle = tp.getReleaseAngle(sling, releasePoint);
                    System.out.println("Release Point: " + releasePoint);
                    System.out.println("Release Angle: " + Math.toDegrees(releaseAngle));
                    int tapInterval = 0;
                    switch (aRobot.getBirdTypeOnSling()) {

                    case RedBird:
                        tapInterval = 0;
                        break; // start of trajectory
                    case YellowBird:
                        tapInterval = 65 + randomGenerator.nextInt(25);
                        break; // 65-90% of the way
                    case WhiteBird:
                        tapInterval = 70 + randomGenerator.nextInt(20);
                        break; // 70-90% of the way
                    case BlackBird:
                        tapInterval = 70 + randomGenerator.nextInt(20);
                        break; // 70-90% of the way
                    case BlueBird:
                        tapInterval = 65 + randomGenerator.nextInt(20);
                        break; // 65-85% of the way
                    default:
                        tapInterval = 60;
                    }

                    int tapTime = tp.getTapTime(sling, releasePoint, _tpt, tapInterval);
                    dx = (int) releasePoint.getX() - refPoint.x;
                    dy = (int) releasePoint.getY() - refPoint.y;
                    shot = new Shot(refPoint.x, refPoint.y, dx, dy, 0, tapTime);
                } else {
                    System.err.println("No Release Point Found");
                    return state;
                }
            }

            // check whether the slingshot is changed. the change of the slingshot indicates a change in the scale.
            {
                ActionRobot.fullyZoomOut();
                screenshot = ActionRobot.doScreenShot();
                vision = new Vision(screenshot);
                Rectangle _sling = vision.findSlingshotMBR();
                if (_sling != null) {
                    double scale_diff = Math.pow((sling.width - _sling.width), 2)
                            + Math.pow((sling.height - _sling.height), 2);
                    if (scale_diff < 25) {
                        if (dx < 0) {
                            aRobot.cshoot(shot);
                            state = aRobot.getState();
                            if (state == GameState.PLAYING) {
                                screenshot = ActionRobot.doScreenShot();
                                vision = new Vision(screenshot);
                                List<Point> traj = vision.findTrajPoints();
                                tp.adjustTrajectory(traj, sling, releasePoint);
                                firstShot = false;
                            }
                        }
                    } else
                        System.out.println(
                                "Scale is changed, can not execute the shot, will re-segement the image");
                } else
                    System.out
                            .println("no sling detected, can not execute the shot, will re-segement the image");
            }

        }

    }
    return state;
}

From source file:adams.data.conversion.SpreadSheetToWekaInstances.java

License:Open Source License

/**
 * Performs the actual conversion.//w  w w  .  j a v  a  2 s.co m
 *
 * @return      the converted data
 * @throws Exception   if something goes wrong with the conversion
 */
@Override
protected Object doConvert() throws Exception {
    Instances result;
    SpreadSheet sheet;
    DenseInstance inst;
    ArrayList<Attribute> atts;
    HashSet<String> unique;
    ArrayList<String> labels;
    Row row;
    Cell cell;
    int i;
    int n;
    double[] values;
    Collection<ContentType> types;
    ContentType type;
    boolean added;
    int[] classIndices;

    sheet = (SpreadSheet) m_Input;

    // create header
    atts = new ArrayList<>();
    for (i = 0; i < sheet.getColumnCount(); i++) {
        added = false;
        types = sheet.getContentTypes(i);
        if (types.contains(ContentType.DOUBLE))
            types.remove(ContentType.LONG);
        if (types.contains(ContentType.LONG)) {
            types.add(ContentType.DOUBLE);
            types.remove(ContentType.LONG);
        }

        if (types.size() == 1) {
            type = (ContentType) types.toArray()[0];
            if (type == ContentType.DOUBLE) {
                atts.add(new Attribute(sheet.getHeaderRow().getCell(i).getContent()));
                added = true;
            } else if (type == ContentType.DATE) {
                atts.add(new Attribute(sheet.getHeaderRow().getCell(i).getContent(),
                        Constants.TIMESTAMP_FORMAT));
                added = true;
            } else if (type == ContentType.TIME) {
                atts.add(new Attribute(sheet.getHeaderRow().getCell(i).getContent(), Constants.TIME_FORMAT));
                added = true;
            }
        }

        if (!added) {
            unique = new HashSet<>();
            for (n = 0; n < sheet.getRowCount(); n++) {
                row = sheet.getRow(n);
                cell = row.getCell(i);
                if ((cell != null) && !cell.isMissing())
                    unique.add(cell.getContent());
            }
            if ((unique.size() > m_MaxLabels) || (m_MaxLabels < 1)) {
                atts.add(new Attribute(sheet.getHeaderRow().getCell(i).getContent(), (FastVector) null));
            } else {
                labels = new ArrayList<>(unique);
                Collections.sort(labels);
                atts.add(new Attribute(sheet.getHeaderRow().getCell(i).getContent(), labels));
            }
        }
    }
    result = new Instances(Environment.getInstance().getProject(), atts, sheet.getRowCount());
    if (sheet.hasName())
        result.setRelationName(sheet.getName());

    // add data
    for (n = 0; n < sheet.getRowCount(); n++) {
        row = sheet.getRow(n);
        values = new double[result.numAttributes()];
        for (i = 0; i < result.numAttributes(); i++) {
            cell = row.getCell(i);
            values[i] = weka.core.Utils.missingValue();
            if ((cell != null) && !cell.isMissing()) {
                if (result.attribute(i).type() == Attribute.DATE) {
                    if (cell.isTime())
                        values[i] = cell.toTime().getTime();
                    else
                        values[i] = cell.toDate().getTime();
                } else if (result.attribute(i).isNumeric()) {
                    values[i] = Utils.toDouble(cell.getContent());
                } else if (result.attribute(i).isString()) {
                    values[i] = result.attribute(i).addStringValue(cell.getContent());
                } else {
                    values[i] = result.attribute(i).indexOfValue(cell.getContent());
                }
            }
        }
        inst = new DenseInstance(1.0, values);
        result.add(inst);
    }

    if (sheet instanceof Dataset) {
        classIndices = ((Dataset) sheet).getClassAttributeIndices();
        if (classIndices.length > 0)
            result.setClassIndex(classIndices[0]);
    }

    return result;
}

From source file:adams.data.conversion.WekaInstancesToSpreadSheet.java

License:Open Source License

/**
 * Performs the actual conversion.//w  w  w .  j ava 2 s .c o  m
 *
 * @return      the converted data
 * @throws Exception   if something goes wrong with the conversion
 */
@Override
protected Object doConvert() throws Exception {
    SpreadSheet result;
    Instances data;
    Row row;
    int i;
    int n;
    String str;

    data = (Instances) m_Input;

    // special case for InstancesViews
    if (m_SpreadSheetType instanceof InstancesView) {
        result = new InstancesView((Instances) m_Input);
        return result;
    }

    // create header
    result = m_SpreadSheetType.newInstance();
    result.setDataRowClass(m_DataRowType.getClass());
    row = result.getHeaderRow();
    for (n = 0; n < data.numAttributes(); n++)
        row.addCell("" + n).setContent(data.attribute(n).name());
    if (result instanceof Dataset) {
        if (data.classIndex() != -1)
            ((Dataset) result).setClassAttribute(data.classIndex(), true);
    }

    // fill spreadsheet
    for (i = 0; i < data.numInstances(); i++) {
        row = result.addRow("" + i);

        for (n = 0; n < data.numAttributes(); n++) {
            if (data.instance(i).isMissing(n))
                continue;
            if (data.attribute(n).type() == Attribute.DATE) {
                row.addCell("" + n).setContent(new DateTimeMsec(new Date((long) data.instance(i).value(n))));
            } else if (data.attribute(n).type() == Attribute.NUMERIC) {
                row.addCell("" + n).setContent(data.instance(i).value(n));
            } else {
                str = data.instance(i).stringValue(n);
                if (str.equals(SpreadSheet.MISSING_VALUE))
                    row.addCell("" + n).setContentAsString("'" + str + "'");
                else
                    row.addCell("" + n).setContentAsString(str);
            }
        }
    }

    return result;
}

From source file:adams.data.instances.AbstractInstanceGenerator.java

License:Open Source License

/**
 * Interpretes the position string based on the given dataset.
 * "first", "second", "third", "last-2", "last-1" and "last" and "last+1" are valid as well.
 *
 * @param data   the data to base the intepretation on
 * @param position   the position string
 * @return      the numeric position string
 *//* w w  w. ja va 2 s.  co  m*/
protected String interpretePosition(Instances data, String position) {
    if (position.equals("first"))
        return "1";
    else if (position.equals("second"))
        return "2";
    else if (position.equals("third"))
        return "3";
    else if (position.equals("last-2"))
        return "" + (data.numAttributes() - 2);
    else if (position.equals("last-1"))
        return "" + (data.numAttributes() - 1);
    else if (position.equals("last"))
        return "" + data.numAttributes();
    else if (position.equals("last+1"))
        return "" + (data.numAttributes() + 1);
    else
        return position;
}