List of usage examples for weka.core Instances instance
publicInstance instance(int index)
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); }/*from ww w .java 2s . 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 w w . j ava 2 s .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
@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)); }// w ww. ja v a2 s .c o 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: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();//from w ww. j av a2s.co 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.WekaInstancesToSpreadSheet.java
License:Open Source License
/** * Performs the actual conversion.//w w w.j av a 2 s. c om * * @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.conversion.WekaInstancesToTimeseries.java
License:Open Source License
/** * Performs the actual conversion./*from w w w . j a v a 2 s. c o m*/ * * @return the converted data * @throws Exception if something goes wrong with the conversion */ @Override protected Object doConvert() throws Exception { Timeseries result; Instances input; Instance inst; int indexDate; int indexValue; TimeseriesPoint point; int i; Date timestamp; double value; input = (Instances) m_Input; // determine attribute indices m_DateAttribute.setData(input); indexDate = m_DateAttribute.getIntIndex(); if (indexDate == -1) throw new IllegalStateException("Failed to located date attribute: " + m_DateAttribute.getIndex()); m_ValueAttribute.setData(input); indexValue = m_ValueAttribute.getIntIndex(); if (indexValue == -1) throw new IllegalStateException("Failed to located value attribute: " + m_ValueAttribute.getIndex()); result = new Timeseries(input.relationName() + "-" + input.attribute(indexValue).name()); for (i = 0; i < input.numInstances(); i++) { inst = input.instance(i); if (!inst.isMissing(indexDate) && !inst.isMissing(indexValue)) { timestamp = new Date((long) inst.value(indexDate)); value = inst.value(indexValue); point = new TimeseriesPoint(timestamp, value); result.add(point); } } return result; }
From source file:adams.data.id.AbstractInstanceIDGeneratorTestCase.java
License:Open Source License
/** * Loads the data to process./*from w w w.j av a2 s .c o m*/ * * @param filename the filename to load (without path) * @return the data, null if it could not be loaded * @see #getDataDirectory() */ protected D[] load(String filename) { Instance[] result; Instances data; int i; result = null; m_TestHelper.copyResourceToTmp(filename); try { data = DataSource.read(new TmpFile(filename).getAbsolutePath()); result = new Instance[data.numInstances()]; for (i = 0; i < data.numInstances(); i++) { result[i] = new Instance(); result[i].set(data.instance(i)); result[i].setID(new TmpFile(filename).getName() + "-" + i); } } catch (Exception e) { e.printStackTrace(); result = new Instance[0]; } m_TestHelper.deleteFileFromTmp(filename); return (D[]) result; }
From source file:adams.data.instancesanalysis.pls.AbstractMultiClassPLS.java
License:Open Source License
/** * Postprocesses the data.//from ww w . ja v a 2s .c o m * * @param instances the data to process * @return the postprocessed data */ protected Instances postTransform(Instances instances, Map<String, Object> params) throws Exception { int i; int n; Map<Integer, double[]> classValues; double classValue; int index; classValues = (Map<Integer, double[]>) params.get(PARAM_CLASSVALUES); // add the mean to the class again if predictions are to be performed, // otherwise restore original class values for (i = 0; i < m_ClassAttributeIndices.size(); i++) { index = m_ClassAttributeIndices.get(i); for (n = 0; n < instances.numInstances(); n++) { if (classValues != null) { instances.instance(n).setClassValue(classValues.get(index)[n]); } else { classValue = instances.instance(n).classValue(); instances.instance(n) .setClassValue(classValue * m_ClassStdDev.get(index) + m_ClassMean.get(index)); } } } return instances; }
From source file:adams.data.instancesanalysis.pls.AbstractSingleClassPLS.java
License:Open Source License
/** * Postprocesses the data.//from w ww .j a v a 2 s . c om * * @param instances the data to process * @return the postprocessed data */ protected Instances postTransform(Instances instances, Map<String, Object> params) throws Exception { int i; double[] classValues; double classValue; classValues = (double[]) params.get(PARAM_CLASSVALUES); // add the mean to the class again if predictions are to be performed, // otherwise restore original class values for (i = 0; i < instances.numInstances(); i++) { if (classValues != null) { instances.instance(i).setClassValue(classValues[i]); } else { classValue = instances.instance(i).classValue(); instances.instance(i).setClassValue(classValue * m_ClassStdDev + m_ClassMean); } } return instances; }
From source file:adams.data.instancesanalysis.pls.PLS1.java
License:Open Source License
/** * Performs predictions on the data./*from w w w .j a v a 2 s . com*/ * * @param data the input data * @return the predicted data */ protected Instances predict(Instances data) { Instances result; Instances tmpInst; int i; int j; Matrix x; Matrix X; Matrix T; Matrix t; result = new Instances(getOutputFormat()); for (i = 0; i < data.numInstances(); i++) { // work on each instance tmpInst = new Instances(data, 0); tmpInst.add((Instance) data.instance(i).copy()); x = MatrixHelper.getX(tmpInst); X = new Matrix(1, getNumComponents()); T = new Matrix(1, getNumComponents()); for (j = 0; j < getNumComponents(); j++) { MatrixHelper.setVector(x, X, j); // 1. step: tj = xj * wj t = x.times(MatrixHelper.getVector(m_W, j)); MatrixHelper.setVector(t, T, j); // 2. step: xj+1 = xj - tj*pj^T (tj is 1x1 matrix!) x = x.minus(MatrixHelper.getVector(m_P, j).transpose().times(t.get(0, 0))); } switch (m_PredictionType) { case ALL: tmpInst = MatrixHelper.toInstances(getOutputFormat(), T, T.times(m_b_hat)); break; case NONE: case EXCEPT_CLASS: tmpInst = MatrixHelper.toInstances(getOutputFormat(), T, MatrixHelper.getY(tmpInst)); break; default: throw new IllegalStateException("Unhandled prediction type: " + m_PredictionType); } result.add(tmpInst.instance(0)); } return result; }