List of usage examples for weka.classifiers.bayes NaiveBayes NaiveBayes
NaiveBayes
From source file:TextClassifierUI.java
private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runButtonActionPerformed // TODO add your handling code here: try {/*www . j a v a 2s.co m*/ DocClassifier dr = new DocClassifier(trainFiles, testFiles); Classifier cl; if (naiveBayes.isSelected()) { cl = new NaiveBayes(); } else { cl = new IBk(Integer.parseInt(kNearest.getText())); } Evaluation ev; if (useCV.isSelected()) { ev = dr.cvClassify(cl, Integer.parseInt(kFold.getText())); result.setText(dr.performanceEval(ev)); } else { ev = dr.classify(cl); result.setText(dr.performanceEval(ev)); result.append("\nDOCUMENT\t=>\tPREDICT\n"); for (String p : dr.getDocPredList()) { result.append(p + "\n"); } } ThresholdVisualizePanel vmc = new ThresholdVisualizePanel(); setVMC(ev.predictions(), vmc, true); showVMC(vmc); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(this, "K Nearest and K-Fold must be positive numbers.", "Number Format Error", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "Failed to classify : " + e.getLocalizedMessage(), "Unexpected Error", JOptionPane.ERROR_MESSAGE); } }
From source file:ClassificationClass.java
public Evaluation cls_naivebayes(Instances data) { Evaluation eval = null;//from ww w . ja va 2 s. com try { Classifier classifier; PreparingSteps preparingSteps = new PreparingSteps(); data.setClassIndex(data.numAttributes() - 1); classifier = new NaiveBayes(); classifier.buildClassifier(data); eval = new Evaluation(data); eval.evaluateModel(classifier, data); System.out.println(eval.toSummaryString()); } catch (Exception ex) { Logger.getLogger(ClassificationClass.class.getName()).log(Level.SEVERE, null, ex); } return eval; }
From source file:ClassifierBuilder.java
public static MyClassifier buildClassifier(String name) { MyClassifier toReturn = new MyClassifier(name); switch (name) { case "Decision Table Majority": toReturn.setClassifier(new DecisionTable()); break;//from ww w.j a v a 2 s.co m case "Logistic Regression": toReturn.setClassifier(new Logistic()); break; case "Multi Layer Perceptron": toReturn.setClassifier(new MultilayerPerceptron()); break; case "Naive Baesian": toReturn.setClassifier(new NaiveBayes()); break; case "Random Forest": toReturn.setClassifier(new RandomForest()); break; default: break; } return toReturn; }
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 w w.j a v a 2s . c om*/ 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:at.aictopic1.sentimentanalysis.machinelearning.impl.NaiveBayesClassifier.java
/** * sets classifier//from www.ja va 2s . com */ @Override protected void setClassifier() { //classifier this.usedClassifier = new NaiveBayes(); //.. other options this.fcClassifier.setClassifier(this.usedClassifier); }
From source file:at.aictopic1.sentimentanalysis.machinelearning.impl.TwitterClassifer.java
public void trainModel() { Instances trainingData = loadTrainingData(); System.out.println("Class attribute: " + trainingData.classAttribute().toString()); // Partition dataset into training and test sets RemovePercentage filter = new RemovePercentage(); filter.setPercentage(10);/* ww w .j av a 2s . c om*/ Instances testData = null; // Split in training and testdata try { filter.setInputFormat(trainingData); testData = Filter.useFilter(trainingData, filter); } catch (Exception ex) { //Logger.getLogger(Trainer.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Error getting testData: " + ex.toString()); } // Train the classifier Classifier model = (Classifier) new NaiveBayes(); try { // Save the model to fil // serialize model weka.core.SerializationHelper.write(modelDir + algorithm + ".model", model); } catch (Exception ex) { Logger.getLogger(TwitterClassifer.class.getName()).log(Level.SEVERE, null, ex); } // Set the local model this.trainedModel = model; try { model.buildClassifier(trainingData); } catch (Exception ex) { //Logger.getLogger(Trainer.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Error training model: " + ex.toString()); } try { // Evaluate model Evaluation test = new Evaluation(trainingData); test.evaluateModel(model, testData); System.out.println(test.toSummaryString()); } catch (Exception ex) { //Logger.getLogger(Trainer.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Error evaluating model: " + ex.toString()); } }
From source file:au.edu.usyd.it.yangpy.sampling.BPSO.java
License:Open Source License
/** * the target function in fitness form// ww w. j a v a2s. c o m * * @return classification accuracy */ public double ensembleClassify() { double fitnessValue = 0.0; double classifiersScore = 0.0; /* load in the modified data set */ try { Instances reducedSet = new Instances(new BufferedReader(new FileReader("reduced.arff"))); reducedSet.setClassIndex(reducedSet.numAttributes() - 1); // calculating the evaluation values using each classifier respectively if (verbose == true) { System.out.println(); System.out.println(" |----------J4.8-----------|"); System.out.println(" | | |"); } J48 tree = new J48(); classifiersScore = classify(tree, reducedSet, internalTest); fitnessValue += classifiersScore; if (verbose == true) { System.out.println(); System.out.println(" |-----3NearestNeighbor----|"); System.out.println(" | | |"); } IBk nn3 = new IBk(3); classifiersScore = classify(nn3, reducedSet, internalTest); fitnessValue += classifiersScore; if (verbose == true) { System.out.println(); System.out.println(" |--------NaiveBayes-------|"); System.out.println(" | | |"); } NaiveBayes nb = new NaiveBayes(); classifiersScore = classify(nb, reducedSet, internalTest); fitnessValue += classifiersScore; if (verbose == true) { System.out.println(); System.out.println(" |-------RandomForest------|"); System.out.println(" | | |"); } RandomForest rf5 = new RandomForest(); rf5.setNumTrees(5); classifiersScore = classify(rf5, reducedSet, internalTest); fitnessValue += classifiersScore; if (verbose == true) { System.out.println(); System.out.println(" |---------Logistic--------|"); System.out.println(" | | |"); } Logistic log = new Logistic(); classifiersScore = classify(log, reducedSet, internalTest); fitnessValue += classifiersScore; } catch (IOException ioe) { ioe.printStackTrace(); } fitnessValue /= 5; if (verbose == true) { System.out.println(); System.out.println("Fitness: " + fitnessValue); System.out.println("---------------------------------------------------"); } return fitnessValue; }
From source file:binarizer.LayoutAnalysis.java
public double crossValidation(String arffFile) throws Exception { DataSource source = new DataSource(arffFile); Instances trainingData = source.getDataSet(); if (trainingData.classIndex() == -1) trainingData.setClassIndex(trainingData.numAttributes() - 1); NaiveBayes nb = new NaiveBayes(); nb.setUseSupervisedDiscretization(true); Evaluation evaluation = new Evaluation(trainingData); evaluation.crossValidateModel(nb, trainingData, 10, new Random(1)); System.out.println(evaluation.toSummaryString()); return evaluation.errorRate(); }
From source file:boa.aggregators.NaiveBayesAggregator.java
License:Apache License
/** {@inheritDoc} */ @Override/*from www . j av a 2 s. c o m*/ public void finish() throws IOException, InterruptedException { Instances trainingSet = new Instances("NaiveBayes", fvAttributes, 1); trainingSet.setClassIndex(NumOfAttributes - 1); for (List<Double> vector : this.vectors.values()) { Instance instance = new Instance(NumOfAttributes); for (int i = 0; i < vector.size(); i++) { instance.setValue((Attribute) fvAttributes.elementAt(i), vector.get(i)); } trainingSet.add(instance); } try { this.model = new NaiveBayes(); this.model.setOptions(options); this.model.buildClassifier(trainingSet); } catch (Exception ex) { } this.saveModel(this.model); }
From source file:ca.uottawa.balie.WekaAttributeSelection.java
License:Open Source License
/** * Select the top attributes/*from w ww . j a v a 2 s. c o m*/ */ public void Select(boolean pi_Debug) { Instances insts = m_DummyLearner.GetTrainInstances(); try { ASEvaluation eval = null; ASSearch search = null; if (m_Evaluator == WEKA_CHI_SQUARE) { eval = new ChiSquaredAttributeEval(); search = new Ranker(); ((Ranker) search).setNumToSelect(m_NumAttributes); } else if (m_Evaluator == WEKA_INFO_GAIN) { eval = new InfoGainAttributeEval(); search = new Ranker(); ((Ranker) search).setNumToSelect(m_NumAttributes); } else if (m_Evaluator == WEKA_WRAPPER) { eval = new ClassifierSubsetEval(); ((ClassifierSubsetEval) eval).setClassifier(new NaiveBayes()); search = new Ranker(); // TODO: use something else than ranker ((Ranker) search).setNumToSelect(m_NumAttributes); } else if (m_Evaluator == WEKA_SYM_UNCERT) { eval = new SymmetricalUncertAttributeEval(); search = new Ranker(); ((Ranker) search).setNumToSelect(m_NumAttributes); } else if (m_Evaluator == WEKA_SVM) { eval = new SVMAttributeEval(); search = new Ranker(); ((Ranker) search).setNumToSelect(m_NumAttributes); } else if (m_Evaluator == WEKA_RELIEF) { eval = new ReliefFAttributeEval(); search = new Ranker(); ((Ranker) search).setNumToSelect(m_NumAttributes); } else if (m_Evaluator == WEKA_ONER) { eval = new OneRAttributeEval(); search = new Ranker(); ((Ranker) search).setNumToSelect(m_NumAttributes); } m_AttributeSelection = new AttributeSelection(); m_AttributeSelection.setEvaluator(eval); m_AttributeSelection.setSearch(search); m_AttributeSelection.SelectAttributes(insts); if (pi_Debug) System.out.println(m_AttributeSelection.toResultsString()); } catch (Exception e) { System.err.println(e.getMessage()); } }