public void Test() { weka.core.Instances insts = new weka.core.Instances(new java.io.FileReader("D:\\android_analysis\\attributes.arff")); insts.setClassIndex(insts.numAttributes() - 1); weka.classifiers.Classifier cl = new weka.classifiers.trees.J48(); cl.buildClassifier(insts); weka.filters.Filter myRandom = new weka.filters.unsupervised.instance.Randomize(); myRandom.setInputFormat(insts); insts = weka.filters.Filter.useFilter(insts, myRandom); int trainSize = (int)(insts.numInstances() * 0.66); int testSize = insts.numInstances() - trainSize; weka.core.Instances train = new weka.core.Instances(insts, 0, trainSize); cl.buildClassifier(train); for (int i = trainSize; i < insts.numInstances(); i++) { weka.core.Instance currentInst = insts.instance(i); double predictedClass = cl.classifyInstance(currentInst); double[] distrs = cl.distributionForInstance(currentInst); string actual = insts.classAttribute().value((int)currentInst.classValue()); string predicted = insts.classAttribute().value((int)predictedClass); System.Console.WriteLine("ID: " + (i + 1) + ", " + actual + " --> " + predicted); } }
public static string WEKA_GETMLP(weka.core.Instances insts) { string THEOUTPUT = " "; try { insts.setClassIndex(insts.numAttributes() - 1); weka.classifiers.functions.MultilayerPerceptron mlp = new weka.classifiers.functions.MultilayerPerceptron(); //SETTING PARAMETERS weka.core.Utils.splitOptions("-L 0.3 -M 0.2 -N 500 -V 0 -S 0 -E 20 -H 3"); mlp.buildClassifier(insts); THEOUTPUT = mlp.ToString(); } catch (java.lang.Exception ex) { ex.printStackTrace(); } return(THEOUTPUT); //new Program().Method3 }
private weka.core.Instances CreateEmptyInstances() { var atts = new java.util.ArrayList(); atts.add(new weka.core.Attribute("x")); atts.add(new weka.core.Attribute("y")); if (!ckbClassIsNominal.Checked) { atts.add(new weka.core.Attribute("v")); } else { // - nominal var attVals = new java.util.ArrayList(); //for(int i=0; i<MAXCLASSNUM; ++i) // attVals.add(i.ToString()); attVals.add("0"); attVals.add("1"); atts.add(new weka.core.Attribute("v", attVals)); } weka.core.Instances data = new weka.core.Instances("MyRelation", atts, 0); data.setClassIndex(data.numAttributes() - 1); return(data); }
public List <string> Classify(string model, string test) { List <string> ret = new List <string>(); try { java.io.ObjectInputStream ois = new java.io.ObjectInputStream(new java.io.FileInputStream(model)); weka.classifiers.Classifier cl = (weka.classifiers.Classifier)ois.readObject(); ois.close(); weka.core.Instances insts = new weka.core.Instances(new java.io.FileReader(test)); insts.setClassIndex(insts.numAttributes() - 1); for (int i = 0; i < 1; i++) { weka.core.Instance currentInst = insts.instance(i); double predictedClass = cl.classifyInstance(currentInst); double[] distrs = cl.distributionForInstance(currentInst); //string actual = insts.classAttribute().value((int)currentInst.classValue()); //string predicted = insts.classAttribute().value((int)predictedClass); // System.Console.WriteLine("ID: " + (i + 1) + ", " + predicted); for (int j = 0; j < distrs.Length; j++) { string predicted = insts.classAttribute().value(j); string distr = distrs[j].ToString("#0.000"); ret.Add(predicted + "," + distr); } } return(ret); } catch { return(ret); } }
/// <summary> /// Creates a classifier of the desired type from an .arff file /// </summary> /// <param name="ARFFfile">The arff file to read from. Should be a full path.</param> /// <param name="classifier">The type of classifier you want to make.</param> /// <returns>The classifier you created</returns> public void createModel(string ARFFfile, Classifier myClassifier) { if (debug) { Console.WriteLine("Loading ARFF file " + ARFFfile); } _classifier = GetClassifier(myClassifier); try { _dataSet = new weka.core.Instances(new java.io.FileReader(ARFFfile)); if (debug) { Console.WriteLine("You have " + _dataSet.numAttributes() + " attributes."); } _dataSet.setClassIndex(_dataSet.numAttributes() - 1); _classifier.buildClassifier(_dataSet); if (debug) { Console.WriteLine(_classifier.toString()); } } catch (Exception e) { Console.WriteLine("You failed. End of Game. Poor Weka."); Console.WriteLine(e); } }
public static void Main(String[] args) { try { // Load the model java.io.ObjectInputStream stream = new java.io.ObjectInputStream(new java.io.FileInputStream("iris_j48.model")); weka.classifiers.Classifier qhClassifier = (weka.classifiers.Classifier)stream.readObject(); stream.close(); // This model was trained on 66% of instances from the iris dataset. Test the model on remaining 34% instances. weka.core.Instances insts = new weka.core.Instances(new java.io.FileReader("iris.arff")); insts.setClassIndex(insts.numAttributes() - 1); int percentSplit = 66; int trainSize = insts.numInstances() * percentSplit / 100; int testSize = insts.numInstances() - trainSize; int numCorrect = 0; for (int i = trainSize; i < insts.numInstances(); i++) { weka.core.Instance currentInst = insts.instance(i); double predictedClass = qhClassifier.classifyInstance(currentInst); if (predictedClass == insts.instance(i).classValue()) { numCorrect++; } } Console.WriteLine(numCorrect + " out of " + testSize + " correct (" + (double)((double)numCorrect / (double)testSize * 100.0) + "%)"); } catch (java.lang.Exception e) { e.printStackTrace(); } }
private void btnLoad_Click(object sender, EventArgs e) { using (OpenFileDialog d = new OpenFileDialog()) { d.Filter = "Arff File|*.arff"; if (d.ShowDialog() == System.Windows.Forms.DialogResult.OK) { var fileReader = new java.io.FileReader(d.FileName); var instances = new weka.core.Instances(new java.io.BufferedReader(fileReader)); instances.setClassIndex(instances.numAttributes() - 1); fileReader.close(); clear_all(); foreach (weka.core.Instance i in instances) { var p = new valuePoint(i.value(0), i.value(1), (int)i.classValue()); if (p.x < 0 || p.x >= 1 || p.y < 0 || p.y >= 1) { continue; } point_list.Add(p); } draw_all_points(); this.pictureBox1.Invalidate(); } } }
//************************************************************************************** /// <summary> /// Returns classifier prediction based on provided parameters. /// </summary> /// <param name="iParameters"></param> public Prediction Predict(float[] iParameters) { if (iParameters is null) { throw new ArgumentNullException(nameof(iParameters)); } WaitTillModelReady(); // Create instances object var instances = new weka.core.Instances("Test", Attributes, 1); instances.setClassIndex(instances.numAttributes() - 1); // Create single instance var instance = new weka.core.DenseInstance(instances.numAttributes() - 1); instance.setDataset(instances); // Fill instance with data for (int i = 0; i < iParameters.Length; i++) { instance.setValue(i, iParameters[i]); } // Get prediction double prediction = Model.classifyInstance(instance); // Convert prediction to decision return((Prediction)Enum.Parse(typeof(Prediction), instances.classAttribute().value((int)prediction))); }
//Only 1 output: last instance static public string do_Classification_bySerialClassfier_1out_standAlone (SerializedClassifier serialClassifier, weka.core.Instances instances, int colClass) { instances.setClassIndex(colClass); weka.core.Instance each = instances.instance(instances.numInstances() - 1); double predictedClass = serialClassifier.classifyInstance(each); return(instances.classAttribute().value((int)predictedClass)); }
//void report_write(){ // Evaluation eval = new Evaluation(trainCases); // eval.crossValidateModel(tree, trainCases, 3, new Random(1)); // System.out.println(eval.toSummaryString("\nResults\n======\n", false)); // System.out.println(eval.toClassDetailsString()); // System.out.println(eval.toMatrixString()); // System.out.println("accuracy:"+eval.pctCorrect()); // System.out.println("Specificity:"+eval.truePositiveRate(0)); // System.out.println("sensitivity:"+eval.trueNegativeRate(0)); //} //====================================================================== //--------- Seperate Part ------- public static weka.core.Instances getInst(string path_file, int colIndex) { try { weka.core.Instances ins = new weka.core.Instances(new java.io.FileReader(path_file)); ins.setClassIndex(colIndex); return(ins); } catch (Exception ex) { TheSys.showError("Err: " + ex.ToString(), true); return(null); } }
/// <summary> /// Loads a classifier from a model file. /// </summary> /// <param name="filename">The filename (full path) that you want to load. Should be an .arff file and a .model file in your working directory.</param> public void loadModel(string filename) { if (debug) { Console.WriteLine("Model loading..."); } _classifier = (weka.classifiers.Classifier)weka.core.SerializationHelper.read(filename + MODEL); _dataSet = new weka.core.Instances(new java.io.FileReader(filename + ARFF)); _dataSet.setClassIndex(_dataSet.numAttributes() - 1); if (debug) { Console.WriteLine("Model locked and loaded!"); } }
//************************************************************************************** /// <summary> /// Creates and fills in weka instances object. /// </summary> protected static weka.core.Instances CreateInstances(CandlestickCollection iCandlesticks, List <int> iTrainingPoints, java.util.ArrayList iAttributes, List <ClassifierParameter> iParameters, Candlestick.Period iPeriod, int iMaxProfitTime) { int dataSize = iTrainingPoints.Count; // Create instance object var instances = new weka.core.Instances("Data", iAttributes, dataSize); // Set class index instances.setClassIndex(instances.numAttributes() - 1); // Fill instances FillInstances(instances, CalculateDecisions(iCandlesticks[kTrainingPeriod], iTrainingPoints, iMaxProfitTime), CalculateParameters(iParameters, iCandlesticks, iTrainingPoints, iPeriod)); return(instances); }
private weka.core.Instances ReadFile(string path) { try { weka.core.Instances insts = new weka.core.Instances(new java.io.FileReader(path)); insts.setClassIndex(insts.numAttributes() - 1); return(insts); } catch (java.lang.Exception ex) { ex.printStackTrace(); MessageBox.Show(ex.ToString(), "Error reading file", MessageBoxButtons.OK, MessageBoxIcon.Error); return(null); } }
protected void Button2_Click(object sender, EventArgs e) { weka.core.Instances data = new weka.core.Instances(new java.io.FileReader("d:\\train.arff")); data.setClassIndex(data.numAttributes() - 1); weka.classifiers.Classifier cls = new weka.classifiers.bayes.NaiveBayes(); // weka.classifiers.functions.supportVector.SMOset(); int runs = 1; int folds = 10; //string sq = "delete from nbresults"; //dbc.execfn(sq); // perform cross-validation for (int i = 0; i < runs; i++) { // randomize data int seed = i + 1; java.util.Random rand = new java.util.Random(seed); weka.core.Instances randData = new weka.core.Instances(data); randData.randomize(rand); if (randData.classAttribute().isNominal()) { randData.stratify(folds); } // weka.classifiers.trees.j48 jj; weka.classifiers.Evaluation eval = new weka.classifiers.Evaluation(randData); for (int n = 0; n < folds; n++) { weka.core.Instances train = randData.trainCV(folds, n); weka.core.Instances test = randData.testCV(folds, n); // build and evaluate classifier weka.classifiers.Classifier clsCopy = weka.classifiers.Classifier.makeCopy(cls); clsCopy.buildClassifier(train); eval.evaluateModel(clsCopy, test); } preci_value.Text = eval.precision(0).ToString(); recall_value.Text = eval.recall(0).ToString(); acc_value.Text = eval.fMeasure(0).ToString(); string s = "NB"; // string str = "insert into evaluation values('" + instid.Text + "','" + courid.Text.ToString() + "','" + preci_value.Text.ToString() + "','" + recall_value.Text.ToString() + "','" + acc_value.Text.ToString() + "','" + s + "' )"; // db.execfn(str); // MessageBox.Show("saved"); } }
private void btnLoadStep_Click(object sender, EventArgs e) { if (m_loadStepInstances == null) { using (OpenFileDialog d = new OpenFileDialog()) { d.Filter = "Arff File|*.arff"; if (d.ShowDialog() == System.Windows.Forms.DialogResult.OK) { m_loadStepInstances = new weka.core.Instances(new java.io.BufferedReader(new java.io.FileReader(d.FileName))); m_loadStepInstances.setClassIndex(m_loadStepInstances.numAttributes() - 1); clear_all(); } } } else { for (int i = m_loadStepIdx; i < m_loadStepInstances.numInstances(); ++i) { var ins = m_loadStepInstances.instance(i); var p = new valuePoint(ins.value(0), ins.value(1), (int)ins.classValue()); if (p.x < 0 || p.x >= 1 || p.y < 0 || p.y >= 1) { continue; } point_list.Add(p); draw_point(p); m_loadStepIdx = i + 1; if (i % 1000 == 0) { break; } } pictureBox1.Invalidate(); if (m_loadStepIdx == m_loadStepInstances.numInstances()) { m_loadStepIdx = 0; m_loadStepInstances = null; } } }
//Knn public static double Knn(weka.core.Instances insts) { try { insts.setClassIndex(insts.numAttributes() - 1); Knncl = new weka.classifiers.lazy.IBk(); weka.filters.Filter myDummy = new weka.filters.unsupervised.attribute.NominalToBinary(); myDummy.setInputFormat(insts); insts = weka.filters.Filter.useFilter(insts, myDummy); weka.filters.Filter myNormalize = new weka.filters.unsupervised.instance.Normalize(); myNormalize.setInputFormat(insts); insts = weka.filters.Filter.useFilter(insts, myNormalize); weka.filters.Filter myRandom = new weka.filters.unsupervised.instance.Randomize(); myRandom.setInputFormat(insts); insts = weka.filters.Filter.useFilter(insts, myRandom); int trainSize = insts.numInstances() * percentSplit / 100; int testSize = insts.numInstances() - trainSize; weka.core.Instances train = new weka.core.Instances(insts, 0, trainSize); Knncl.buildClassifier(train); int numCorrect = 0; for (int i = trainSize; i < insts.numInstances(); i++) { weka.core.Instance currentInst = insts.instance(i); double predictedClass = Knncl.classifyInstance(currentInst); if (predictedClass == insts.instance(i).classValue()) { numCorrect++; } } return((double)numCorrect / (double)testSize * 100.0); } catch (java.lang.Exception ex) { ex.printStackTrace(); return(0); } }
public void Test2() { java.io.ObjectInputStream ois = new java.io.ObjectInputStream(new java.io.FileInputStream("D:\\android_analysis\\som_model.model")); weka.classifiers.Classifier cl = (weka.classifiers.Classifier)ois.readObject(); ois.close(); weka.core.Instances insts = new weka.core.Instances(new java.io.FileReader("D:\\android_analysis\\test1.arff")); insts.setClassIndex(insts.numAttributes() - 1); for (int i = 0; i < insts.numInstances(); i++) { weka.core.Instance currentInst = insts.instance(i); double predictedClass = cl.classifyInstance(currentInst); double[] distrs = cl.distributionForInstance(currentInst); //string actual = insts.classAttribute().value((int)currentInst.classValue()); //string predicted = insts.classAttribute().value((int)predictedClass); // System.Console.WriteLine("ID: " + (i + 1) + ", " + predicted); } }
public static string classifyTest() { try { String result = ""; weka.core.Instances insts = new weka.core.Instances(new java.io.FileReader("C:\\Program Files\\Weka-3-7\\data\\iris.arff")); insts.setClassIndex(insts.numAttributes() - 1); weka.classifiers.Classifier cl = new weka.classifiers.trees.J48(); // Console.WriteLine("Performing " + percentSplit + "% split evaluation."); result += "Performing " + percentSplit + "% split evaluation.\n"; //randomize the order of the instances in the dataset. weka.filters.Filter myRandom = new weka.filters.unsupervised.instance.Randomize(); myRandom.setInputFormat(insts); insts = weka.filters.Filter.useFilter(insts, myRandom); int trainSize = insts.numInstances() * percentSplit / 100; int testSize = insts.numInstances() - trainSize; weka.core.Instances train = new weka.core.Instances(insts, 0, trainSize); cl.buildClassifier(train); int numCorrect = 0; for (int i = trainSize; i < insts.numInstances(); i++) { weka.core.Instance currentInst = insts.instance(i); double predictedClass = cl.classifyInstance(currentInst); if (predictedClass == insts.instance(i).classValue()) { numCorrect++; } } //Console.WriteLine(numCorrect + " out of " + testSize + " correct (" + (double)((double)numCorrect / (double)testSize * 100.0) + "%)"); result += (numCorrect + " out of " + testSize + " correct (" + (double)((double)numCorrect / (double)testSize * 100.0) + "%)"); return(result); } catch (Exception ex) { MessageBox.Show(ex.Message); return(ex.Message); } }
private void initialiseClassifier() { // Loads the file to grab the filename. GameObject player = GameObject.Find("Player"); PlayerBehaviour playerBehaviourScript = player.GetComponent <PlayerBehaviour>(); //loads training and test data, builds new classifier and trains it insts = new weka.core.Instances(new java.io.FileReader(playerBehaviourScript.stringToEdit)); insts.setClassIndex(4); j48Classifier = new weka.classifiers.trees.J48(); //Optionals methods currently testing for improvements //j48Classifier.setUnpruned (true); //j48Classifier.setUseLaplace (true); j48Classifier.buildClassifier(insts); //NO CURRENT TEST SET READY TO USE //weka.core.Instances testData = new weka.core.Instances(new java.io.FileReader("TestSet.arff")); //testData.setClassIndex(5); //weka.classifiers.Evaluation eval = new weka.classifiers.Evaluation(insts); //eval.evaluateModel (j48Classifier,testData); Debug.Log(j48Classifier.toSummaryString()); }
/* Use when the player logs in to initially create the classifier with data from server */ public void InitializeClassifier(String dataString) { try { java.io.StringReader stringReader = new java.io.StringReader(dataString); java.io.BufferedReader buffReader = new java.io.BufferedReader(stringReader); playerData = new weka.core.Instances(buffReader); /* State where in each Instance the class attribute is, if its not already specified by the file */ if (playerData.classIndex() == -1) { playerData.setClassIndex(playerData.numAttributes() - 1); } /* NAIVE BAYES */ //classifier = new weka.classifiers.bayes.NaiveBayes(); /* NEURAL NET */ //classifier = new weka.classifiers.functions.MultilayerPerceptron(); //((weka.classifiers.functions.MultilayerPerceptron)classifier).setHiddenLayers("12"); /* J48 TREE */ //classifier = new weka.classifiers.trees.J48(); /* IB1 NEAREST NEIGHBOUR */ //classifier = new weka.classifiers.lazy.IB1(); /* RANDOM FOREST */ classifier = new weka.classifiers.trees.RandomForest(); classifier.buildClassifier(playerData); Debug.Log("Initialized Classifier"); } catch (java.lang.Exception ex) { Debug.LogError(ex.getMessage()); } }
static public List <string> do_Classification_bySerialClassfier_standAlone (SerializedClassifier serialClassifier, weka.core.Instances instances, int colClass) { instances.setClassIndex(colClass); List <string> listPredictClass = new List <string>(); double predictedClass; double actualClass; predict_numCorrect = 0; weka.core.Instance each; for (int i = 0; i < instances.numInstances(); i++) { each = instances.instance(i); predictedClass = serialClassifier.classifyInstance(each); actualClass = instances.instance(i).classValue(); if (predictedClass == actualClass) { predict_numCorrect++; } //Get Class Name listPredictClass.Add(instances.classAttribute().value((int)predictedClass)); } return(listPredictClass); }
public static void do_Classification_full(Boolean loadData) { try { if (loadData == true) { step_loadInstance(); } insts.setClassIndex(colClass);//Which Column is classified if (random_sort == true) { step_randomInstanceOrder(); } //------ Train & Test ---------- classifier = step_buildClassifier(classify_model); txtResult_Reset(); step_train_test(); } catch (Exception ex) { TheSys.showError("Err: " + ex.ToString(), true); } }
public int InitializeClassifier(string[] atributes, string[] gestures, string classAttribute, string modelLocation) { java.io.ObjectInputStream ois = new java.io.ObjectInputStream(new java.io.FileInputStream(modelLocation)); m_cl = (weka.classifiers.Classifier)ois.readObject(); //Declare the feature vector weka.core.FastVector fvWekaFeatureVector = new weka.core.FastVector(atributes.Length + 1); for (int i = 0; i < atributes.Length; i++) { weka.core.Attribute aux = new weka.core.Attribute(atributes[i]); fvWekaFeatureVector.addElement(aux); } //Declare the class weka.core.Attribute along with its values weka.core.FastVector fvClassValues = new weka.core.FastVector(gestures.Length); for (int i = 0; i < gestures.Length; i++) { weka.core.Attribute z1 = new weka.core.Attribute(atributes[i]); fvClassValues.addElement(gestures[i]); } //fvClassValues.addElement("yes"); //fvClassValues.addElement("no"); weka.core.Attribute ClassAttribute = new weka.core.Attribute(classAttribute, fvClassValues); fvWekaFeatureVector.addElement(ClassAttribute); dataSet = new weka.core.Instances("TestRel", fvWekaFeatureVector, 10); dataSet.setClassIndex(atributes.Length); testInstance = new weka.core.Instance(atributes.Length + 1); return(1); }
public static void classifyTest() { try { Console.WriteLine("Hello Java, from C#!"); weka.core.Instances insts = new weka.core.Instances(new java.io.FileReader("D:/iris.arff")); insts.setClassIndex(insts.numAttributes() - 1); weka.classifiers.Classifier cl = new weka.classifiers.trees.J48(); Console.WriteLine("Performing " + 33 + "% split evaluation."); //randomize the order of the instances in the dataset. weka.filters.Filter myRandom = new weka.filters.unsupervised.instance.Randomize(); myRandom.setInputFormat(insts); insts = weka.filters.Filter.useFilter(insts, myRandom); int trainSize = insts.numInstances() * 33 / 100; int testSize = insts.numInstances() - trainSize; weka.core.Instances train = new weka.core.Instances(insts, 0, trainSize); cl.buildClassifier(train); int numCorrect = 0; for (int i = trainSize; i < insts.numInstances(); i++) { weka.core.Instance currentInst = insts.instance(i); double predictedClass = cl.classifyInstance(currentInst); if (predictedClass == insts.instance(i).classValue()) numCorrect++; } Console.WriteLine(numCorrect + " out of " + testSize + " correct (" + (double)((double)numCorrect / (double)testSize * 100.0) + "%)"); } catch (Exception ex) { } }
private void btnLoadStep_Click(object sender, EventArgs e) { if (m_loadStepInstances == null) { using (OpenFileDialog d = new OpenFileDialog()) { d.Filter = "Arff File|*.arff"; if (d.ShowDialog() == System.Windows.Forms.DialogResult.OK) { m_loadStepInstances = new weka.core.Instances(new java.io.BufferedReader(new java.io.FileReader(d.FileName))); m_loadStepInstances.setClassIndex(m_loadStepInstances.numAttributes() - 1); clear_all(); } } } else { for (int i = m_loadStepIdx; i < m_loadStepInstances.numInstances(); ++i) { var ins = m_loadStepInstances.instance(i); var p = new valuePoint(ins.value(0), ins.value(1), (int)ins.classValue()); if (p.x < 0 || p.x >= 1 || p.y < 0 || p.y >= 1) continue; point_list.Add(p); draw_point(p); m_loadStepIdx = i + 1; if (i % 1000 == 0) { break; } } pictureBox1.Invalidate(); if (m_loadStepIdx == m_loadStepInstances.numInstances()) { m_loadStepIdx = 0; m_loadStepInstances = null; } } }
private void button1_Click(object sender, EventArgs e) { string fname = ""; OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Weka Files (*.arff)|*.arff|All files (*.*)|*.*"; dialog.InitialDirectory = Application.StartupPath; dialog.Title = "Select a .arff file"; if (dialog.ShowDialog() == DialogResult.OK) { fname = dialog.FileName; //label5.Text = System.IO.Directory.; } if (fname == "") { return; } try { weka.core.Instances insts = new weka.core.Instances(new java.io.FileReader(fname.ToString())); insts.setClassIndex(insts.numAttributes() - 1); Classifier cl = new weka.classifiers.functions.SMO(); //label1.Text = "Performing " + percentSplit + "% split evaluation."; //randomize the order of the instances in the dataset. weka.filters.Filter myRandom = new weka.filters.unsupervised.instance.Randomize(); myRandom.setInputFormat(insts); insts = weka.filters.Filter.useFilter(insts, myRandom); int trainSize = insts.numInstances() * percentSplit / 100; int testSize = insts.numInstances() - trainSize; weka.core.Instances train = new weka.core.Instances(insts, 0, trainSize); cl.buildClassifier(train); int numCorrect = 0; for (int i = trainSize; i < insts.numInstances(); i++) { weka.core.Instance currentInst = insts.instance(i); double predictedClass = cl.classifyInstance(currentInst); if (predictedClass == insts.instance(i).classValue()) { numCorrect++; } } //label1.Text = numCorrect + " out of " + testSize + " correct (" + //(double)((double)numCorrect / (double)testSize * 100.0) + "%)"; label6.Text = testSize.ToString(); label7.Text = numCorrect.ToString(); label8.Text = (double)((double)numCorrect / (double)testSize * 100.0) + "%"; double result_perc = (double)((double)numCorrect / (double)testSize * 100.0); result_perc = Math.Truncate(result_perc); try { // Send Data On Serial port SerialPort serialPort = new SerialPort("COM" + textBox1.Text + "", Int32.Parse(textBox2.Text), Parity.None, 8); serialPort.Open(); if (result_perc <= 75) { serialPort.WriteLine("1"); } serialPort.WriteLine("a"); serialPort.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } catch (java.lang.Exception ex) { MessageBox.Show(ex.getMessage().ToString(), ""); } }
//public object Clone() { // MemoryStream ms = new MemoryStream(500000000); // System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = // new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(null, // new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Clone)); // bf.Serialize(ms, this); // ms.Seek(0, SeekOrigin.Begin); // object obj = bf.Deserialize(ms); // ms.Close(); // return obj; //} public void train(bool LoadingFromFile) { if (!LoadingFromFile) { DisplayMessage("Begin training on Efigi galaxies..."); Console.Write("Begin training on Efigi galaxies..."); } else { DisplayImage(0); DisplayMessage("Load from file..."); Console.Write("Load from file..."); frV = new GeneralMatrix(ReadFVMatrix(0)); fgV = new GeneralMatrix(ReadFVMatrix(1)); fbV = new GeneralMatrix(ReadFVMatrix(2)); } weka.classifiers.trees.M5P tree = new weka.classifiers.trees.M5P(); String[] options = new String[1]; weka.core.converters.ConverterUtils.DataSource source = new weka.core.converters.ConverterUtils.DataSource(OutputDir + "Results/" + "resultsGalaxy.arff"); data = source.getDataSet(); if (data == null) { DisplayMessage("Cannot load from file."); throw new Exception("Arff File not valid"); } data.setClassIndex(0); tree.buildClassifier(data); StreamWriter output = new StreamWriter(OutputDir + "Results/" + "classification.txt"); rmse = 0.0; int classifiedCount = 0; weka.filters.unsupervised.attribute.Remove rm = new weka.filters.unsupervised.attribute.Remove(); rm.setInputFormat(data); fc = new FilteredClassifier(); fc.setFilter(rm); fc.setClassifier(tree); for (int i = 0; i < data.numInstances(); i++) { int classPrediction = (int)Math.Round(fc.classifyInstance(data.instance(i))); if (classPrediction < -6) { classPrediction = -6; } else if (classPrediction > 11) { classPrediction = 11; } int actualClass = (int)Math.Round(data.instance(i).classValue()); int error = Math.Abs(classPrediction - actualClass); rmse += error * error; classifiedCount++; output.WriteLine("\n" + classPrediction + ", " + error); if (i % 10 == 0 && !LoadingFromFile) DisplayImage(i); } rmse = Math.Sqrt(rmse / classifiedCount); output.WriteLine("\nRMSE: " + rmse); DisplayMessage("RMSE: " + rmse); output.Flush(); output.Close(); output.Dispose(); readyToClassify = true; Console.WriteLine("Finished training on Efigi galaxies; RMSE: " + rmse.ToString()); }
private void button1_Click(object sender, EventArgs e) { OpenFileDialog file = new OpenFileDialog(); if (file.ShowDialog() == DialogResult.OK) { string filename = file.FileName; string filee = Path.GetFileName(filename); bool attributeType; string attributeName = " "; int numAttributeValue = 0; string attributeValueName = " "; textBox1.Text = filee + " chosen succesfully!"; ///////Decision Tree weka.core.Instances insts = new weka.core.Instances(new java.io.FileReader(filename)); insts.setClassIndex(insts.numAttributes() - 1); //find nominal or numeric attributes and create dropbox or textbox int numofAttributes = insts.numAttributes() - 1; for (int i = 0; i < numofAttributes; i++) { attributeType = insts.attribute(i).isNumeric(); attributeName = insts.attribute(i).name(); dataGridView1.Rows.Add(attributeName); if (attributeType == true) { } else { numAttributeValue = insts.attribute(i).numValues(); string[] name = new string[numAttributeValue]; for (int j = 0; j < numAttributeValue; j++) { attributeValueName = insts.attribute(i).value(j); name[j] += attributeValueName; } DataGridViewComboBoxCell combo = new DataGridViewComboBoxCell(); combo.DataSource = name.ToList(); dataGridView1.Rows[i].Cells[1] = combo; } } cl = new weka.classifiers.trees.J48(); textBox2.Text = "Performing " + percentSplit + "% split evaluation."; //filling missing values weka.filters.Filter missingval = new weka.filters.unsupervised.attribute.ReplaceMissingValues(); missingval.setInputFormat(insts); insts = weka.filters.Filter.useFilter(insts, missingval); weka.filters.Filter myNormalized = new weka.filters.unsupervised.instance.Normalize(); myNormalized.setInputFormat(insts); insts = weka.filters.Filter.useFilter(insts, myNormalized); //randomize the order of the instances in the dataset. weka.filters.Filter myRandom = new weka.filters.unsupervised.instance.Randomize(); myRandom.setInputFormat(insts); insts = weka.filters.Filter.useFilter(insts, myRandom); int trainSize = insts.numInstances() * percentSplit / 100; int testSize = insts.numInstances() - trainSize; weka.core.Instances train = new weka.core.Instances(insts, 0, trainSize); cl.buildClassifier(train); string str = cl.toString(); int numCorrect = 0; for (int i = trainSize; i < insts.numInstances(); i++) { weka.core.Instance currentInst = insts.instance(i); double predictedClass = cl.classifyInstance(currentInst); if (predictedClass == insts.instance(i).classValue()) { numCorrect++; } } textBox3.Text = numCorrect + " out of " + testSize + " correct (" + (double)((double)numCorrect / (double)testSize * 100.0) + "%)"; //////////Naive Bayes //dosya okuma weka.core.Instances insts2 = new weka.core.Instances(new java.io.FileReader(filename)); insts2.setClassIndex(insts2.numAttributes() - 1); //naive bayes cl2 = new weka.classifiers.bayes.NaiveBayes(); //filling missing values weka.filters.Filter missingval2 = new weka.filters.unsupervised.attribute.ReplaceMissingValues(); missingval2.setInputFormat(insts2); insts2 = weka.filters.Filter.useFilter(insts2, missingval2); //for naive bayes weka.filters.Filter discrete2 = new weka.filters.unsupervised.attribute.Discretize(); discrete2.setInputFormat(insts2); insts2 = weka.filters.Filter.useFilter(insts2, discrete2); //randomize the order of the instances in the dataset. -ortak weka.filters.Filter myRandom2 = new weka.filters.unsupervised.instance.Randomize(); myRandom2.setInputFormat(insts2); insts2 = weka.filters.Filter.useFilter(insts2, myRandom2); //ortak int trainSize2 = insts2.numInstances() * percentSplit / 100; int testSize2 = insts2.numInstances() - trainSize2; weka.core.Instances train2 = new weka.core.Instances(insts2, 0, trainSize2); cl2.buildClassifier(train2); string str2 = cl2.toString(); int numCorrect2 = 0; for (int i = trainSize2; i < insts2.numInstances(); i++) { weka.core.Instance currentInst2 = insts2.instance(i); double predictedClass2 = cl2.classifyInstance(currentInst2); if (predictedClass2 == insts2.instance(i).classValue()) { numCorrect2++; } } textBox4.Text = numCorrect2 + " out of " + testSize2 + " correct (" + (double)((double)numCorrect2 / (double)testSize2 * 100.0) + "%)"; /////////K-Nearest Neigbour //dosya okuma weka.core.Instances insts3 = new weka.core.Instances(new java.io.FileReader(filename)); insts3.setClassIndex(insts3.numAttributes() - 1); cl3 = new weka.classifiers.lazy.IBk(); //filling missing values weka.filters.Filter missingval3 = new weka.filters.unsupervised.attribute.ReplaceMissingValues(); missingval3.setInputFormat(insts3); insts3 = weka.filters.Filter.useFilter(insts3, missingval3); //Convert to dummy attribute knn,svm,neural network weka.filters.Filter dummy3 = new weka.filters.unsupervised.attribute.NominalToBinary(); dummy3.setInputFormat(insts3); insts3 = weka.filters.Filter.useFilter(insts3, dummy3); //normalize numeric attribute weka.filters.Filter myNormalized3 = new weka.filters.unsupervised.instance.Normalize(); myNormalized3.setInputFormat(insts3); insts3 = weka.filters.Filter.useFilter(insts3, myNormalized3); //randomize the order of the instances in the dataset. weka.filters.Filter myRandom3 = new weka.filters.unsupervised.instance.Randomize(); myRandom3.setInputFormat(insts3); insts3 = weka.filters.Filter.useFilter(insts3, myRandom3); int trainSize3 = insts3.numInstances() * percentSplit / 100; int testSize3 = insts3.numInstances() - trainSize3; weka.core.Instances train3 = new weka.core.Instances(insts3, 0, trainSize3); cl3.buildClassifier(train3); string str3 = cl3.toString(); int numCorrect3 = 0; for (int i = trainSize3; i < insts3.numInstances(); i++) { weka.core.Instance currentInst3 = insts3.instance(i); double predictedClass3 = cl3.classifyInstance(currentInst3); if (predictedClass3 == insts3.instance(i).classValue()) { numCorrect3++; } } textBox5.Text = numCorrect3 + " out of " + testSize3 + " correct (" + (double)((double)numCorrect3 / (double)testSize3 * 100.0) + "%)"; //////////Artificial neural network //dosya okuma weka.core.Instances insts4 = new weka.core.Instances(new java.io.FileReader(filename)); insts4.setClassIndex(insts4.numAttributes() - 1); cl4 = new weka.classifiers.functions.MultilayerPerceptron(); //filling missing values weka.filters.Filter missingval4 = new weka.filters.unsupervised.attribute.ReplaceMissingValues(); missingval4.setInputFormat(insts4); insts4 = weka.filters.Filter.useFilter(insts4, missingval4); //Convert to dummy attribute weka.filters.Filter dummy4 = new weka.filters.unsupervised.attribute.NominalToBinary(); dummy4.setInputFormat(insts4); insts4 = weka.filters.Filter.useFilter(insts4, dummy4); //normalize numeric attribute weka.filters.Filter myNormalized4 = new weka.filters.unsupervised.instance.Normalize(); myNormalized4.setInputFormat(insts4); insts4 = weka.filters.Filter.useFilter(insts4, myNormalized4); //randomize the order of the instances in the dataset. weka.filters.Filter myRandom4 = new weka.filters.unsupervised.instance.Randomize(); myRandom4.setInputFormat(insts4); insts4 = weka.filters.Filter.useFilter(insts4, myRandom4); int trainSize4 = insts4.numInstances() * percentSplit / 100; int testSize4 = insts4.numInstances() - trainSize4; weka.core.Instances train4 = new weka.core.Instances(insts4, 0, trainSize4); cl4.buildClassifier(train4); string str4 = cl4.toString(); int numCorrect4 = 0; for (int i = trainSize4; i < insts4.numInstances(); i++) { weka.core.Instance currentInst4 = insts4.instance(i); double predictedClass4 = cl4.classifyInstance(currentInst4); if (predictedClass4 == insts4.instance(i).classValue()) { numCorrect4++; } } textBox6.Text = numCorrect4 + " out of " + testSize4 + " correct (" + (double)((double)numCorrect4 / (double)testSize4 * 100.0) + "%)"; ///////Support Vector Machine // dosya okuma weka.core.Instances insts5 = new weka.core.Instances(new java.io.FileReader(filename)); insts5.setClassIndex(insts5.numAttributes() - 1); cl5 = new weka.classifiers.functions.SMO(); //filling missing values weka.filters.Filter missingval5 = new weka.filters.unsupervised.attribute.ReplaceMissingValues(); missingval5.setInputFormat(insts5); insts5 = weka.filters.Filter.useFilter(insts5, missingval5); //Convert to dummy attribute weka.filters.Filter dummy5 = new weka.filters.unsupervised.attribute.NominalToBinary(); dummy5.setInputFormat(insts5); insts5 = weka.filters.Filter.useFilter(insts5, dummy5); //normalize numeric attribute weka.filters.Filter myNormalized5 = new weka.filters.unsupervised.instance.Normalize(); myNormalized5.setInputFormat(insts5); insts5 = weka.filters.Filter.useFilter(insts5, myNormalized5); //randomize the order of the instances in the dataset. weka.filters.Filter myRandom5 = new weka.filters.unsupervised.instance.Randomize(); myRandom5.setInputFormat(insts5); insts5 = weka.filters.Filter.useFilter(insts5, myRandom5); int trainSize5 = insts5.numInstances() * percentSplit / 100; int testSize5 = insts5.numInstances() - trainSize5; weka.core.Instances train5 = new weka.core.Instances(insts5, 0, trainSize5); cl5.buildClassifier(train5); string str5 = cl5.toString(); int numCorrect5 = 0; for (int i = trainSize5; i < insts5.numInstances(); i++) { weka.core.Instance currentInst5 = insts5.instance(i); double predictedClass5 = cl5.classifyInstance(currentInst5); if (predictedClass5 == insts5.instance(i).classValue()) { numCorrect5++; } } textBox7.Text = numCorrect5 + " out of " + testSize5 + " correct (" + (double)((double)numCorrect5 / (double)testSize5 * 100.0) + "%)"; string result1 = textBox3.Text; string output1 = result1.Split('(', ')')[1]; output1 = output1.Remove(output1.Length - 1); double r1 = Convert.ToDouble(output1); string result2 = textBox4.Text; string output2 = result2.Split('(', ')')[1]; output2 = output2.Remove(output2.Length - 1); double r2 = Convert.ToDouble(output2); string result3 = textBox5.Text; string output3 = result3.Split('(', ')')[1]; output3 = output3.Remove(output3.Length - 1); double r3 = Convert.ToDouble(output3); string result4 = textBox6.Text; string output4 = result4.Split('(', ')')[1]; output4 = output4.Remove(output4.Length - 1); double r4 = Convert.ToDouble(output4); string result5 = textBox7.Text; string output5 = result5.Split('(', ')')[1]; output5 = output5.Remove(output5.Length - 1); double r5 = Convert.ToDouble(output5); double[] max_array = new double[] { r1, r2, r3, r4, r5 }; double max = max_array.Max(); if (r1 == max) { textBox8.Text = "Best Algoritm is Decision Tree Algorithm "; } else if (r2 == max) { textBox8.Text = "Best Algoritm is Naive Bayes Algorithm "; } else if (r3 == max) { textBox8.Text = "Best Algoritm is K-Nearest Neighbour Algorithm "; } else if (r4 == max) { textBox8.Text = "Best Algoritm is Artificial Neural Network Algorithm "; } else if (r5 == max) { textBox8.Text = "Best Algoritm is Support Vector Machine Algorithm "; } } }
// Test the classification result of each map that a user played, // with the data available as if they were playing through it public static void classifyTest(String dataString, String playerID) { try { java.io.StringReader stringReader = new java.io.StringReader(dataString); java.io.BufferedReader buffReader = new java.io.BufferedReader(stringReader); /* NOTE THAT FOR NAIVE BAYES ALL WEIGHTS CAN BE = 1*/ //weka.core.converters.ConverterUtils.DataSource source = new weka.core.converters.ConverterUtils.DataSource("iris.arff"); weka.core.Instances thisData = new weka.core.Instances(buffReader); //source.getDataSet(); if (thisData.classIndex() == -1) { thisData.setClassIndex(thisData.numAttributes() - 1); } weka.core.Instances thisUniqueData = new weka.core.Instances(thisData); if (thisUniqueData.classIndex() == -1) { thisUniqueData.setClassIndex(thisUniqueData.numAttributes() - 1); } thisUniqueData.delete(); if (allUniqueData == null) { allUniqueData = new weka.core.Instances(thisData); if (allUniqueData.classIndex() == -1) { allUniqueData.setClassIndex(allUniqueData.numAttributes() - 1); } allUniqueData.delete(); } weka.core.InstanceComparator com = new weka.core.InstanceComparator(false); for (int i = 0; i < thisData.numInstances(); i++) { bool dup = false; for (int j = 0; j < allUniqueData.numInstances(); j++) { if (com.compare(thisData.instance(i), allUniqueData.instance(j)) == 0) { Debug.Log("Duplicate found!"); dup = true; break; } } if (!dup) { allUniqueData.add(thisData.instance(i)); } else { dupInstances++; } } for (int i = 0; i < thisData.numInstances(); i++) { bool dup = false; for (int j = 0; j < thisUniqueData.numInstances(); j++) { if (com.compare(thisData.instance(i), thisUniqueData.instance(j)) == 0) { Debug.Log("Duplicate found!"); dup = true; break; } } if (!dup) { thisUniqueData.add(thisData.instance(i)); } else { dupInstancesSamePlayer++; } } //Debug.Log("All Data Instance Count = " + thisData.numInstances()); //Debug.Log("Unique Data Instance Count = " + thisUniqueData.numInstances()); //Debug.Log("Done!"); } catch (java.lang.Exception ex) { Debug.LogError(ex.getMessage()); } }
private void Classify(string path) { readyToTest = false; // initialize flag // Try reading file, if failed exit function insts = ReadFile(path); if (insts == null) { // Error occured reading file, display error message MessageBox.Show("Instances are null!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var form = Form.ActiveForm as Form1; // get the current form object // Reset UI and lists succesRates.Clear(); classifiers.Clear(); form.inputPanel.Controls.Clear(); inputObjects.Clear(); form.textMostSuccessful.Text = ""; form.testResult.Text = ""; // Place attribute inputs on UI, max 18, numeric and nominal int offsetV = 60; int offsetH = 10; int width = 75; int height = 30; for (int i = 0; i < insts.numAttributes() - 1; i++) { // Create and place label Label label = new Label(); label.Width = width; label.Height = height; label.Text = insts.attribute(i).name(); label.Parent = form.inputPanel; label.Location = new Point((width * (i % 8)) + offsetH, (height * (i / 8)) + (offsetV * (i / 8))); // NumericUpDown for numeric and ComboBox for nominal values if (insts.attribute(i).isNumeric()) { NumericUpDown nud = new NumericUpDown(); nud.Width = width - 10; nud.Height = height; nud.Parent = form.inputPanel; nud.Location = new Point((width * (i % 8)) + offsetH, (height * (i / 8)) + (offsetV * (i / 8)) + height); inputObjects.Add(new UserInput(nud)); } else { string[] values = insts.attribute(i).toString().Split('{', '}')[1].Split(','); ComboBox comboBox = new ComboBox(); comboBox.DataSource = values; comboBox.Width = width - 10; comboBox.Height = height; comboBox.Parent = form.inputPanel; comboBox.Location = new Point((width * (i % 8)) + offsetH, (height * (i / 8)) + (offsetV * (i / 8)) + height); inputObjects.Add(new UserInput(comboBox)); } } // Set train and test sizes trainSize = insts.numInstances() * percentSplit / 100; testSize = insts.numInstances() - trainSize; // Set target attribute insts.setClassIndex(insts.numAttributes() - 1); // Randomize weka.filters.Filter rndFilter = new weka.filters.unsupervised.instance.Randomize(); rndFilter.setInputFormat(insts); insts = weka.filters.Filter.useFilter(insts, rndFilter); // Start threads for each method Thread t_SuccessNb = new Thread(() => CalculateSuccessForNb(insts)); t_SuccessNb.Start(); Thread t_SuccessKn = new Thread(() => CalculateSuccessForKn(insts)); t_SuccessKn.Start(); Thread t_SuccessDt = new Thread(() => CalculateSuccessForDt(insts)); t_SuccessDt.Start(); Thread t_SuccessAnn = new Thread(() => CalculateSuccessForAnn(insts)); t_SuccessAnn.Start(); Thread t_SuccessSvm = new Thread(() => CalculateSuccessForSvm(insts)); t_SuccessSvm.Start(); // Wait for threads t_SuccessNb.Join(); t_SuccessKn.Join(); t_SuccessDt.Join(); t_SuccessAnn.Join(); t_SuccessSvm.Join(); // Find out which algorithm has the best success rate foreach (var item in succesRates) { if (highestSuccessRate.Equals(default(KeyValuePair <Classifier, double>)) || highestSuccessRate.Value < item.Value) { highestSuccessRate = item; } } form.textMostSuccessful.Text = "Most successful algorithm is " + highestSuccessRate.Key + " and it will be used for testing."; readyToTest = true; // switch flag }
public void classifyTest() { try { CSV2Arff(); java.io.FileReader arrfFile = new java.io.FileReader("D:/final_version/Gesture-Gis-master/GestureGis2/ComparisonFeaturefile.arff"); weka.core.Instances insts = new weka.core.Instances(arrfFile); //weka.core.Instances insts2 = new weka.core.Instances(new java.io.FileReader("D:/Gesture-Gis-master/GestureGis2/ComparisonFeaturefile.arff")); insts.setClassIndex(insts.numAttributes() - 1); //int percentSplit = 66; weka.classifiers.Classifier cl = new weka.classifiers.trees.J48(); //Console.WriteLine("Performing " + percentSplit + "% split evaluation."); //randomize the order of the instances in the dataset. //weka.filters.Filter myRandom = new weka.filters.unsupervised.instance.Randomize(); //myRandom.setInputFormat(insts); //insts = weka.filters.Filter.useFilter(insts, myRandom); int count = insts.numInstances(); int trainSize = count - 1; int testSize = count - trainSize; weka.core.Instances train = new weka.core.Instances(insts, 0, trainSize); cl.buildClassifier(train); //weka.core.Instance current = insts2.instance(0); int numCorrect = 0; /*for (int i = trainSize; i < insts.numInstances(); i++) * { * weka.core.Instance currentInst = insts.instance(i); * double predictedClass = cl.classifyInstance(currentInst); * if (predictedClass == insts.instance(i).classValue()) * numCorrect++; * }*/ int index = count - 1; weka.core.Instance currentInst = insts.instance(index); double predictedClass = cl.classifyInstance(currentInst); int pre = (int)predictedClass; if (predictedClass == insts.instance(index).classValue()) { numCorrect++; } //insts.instance(index).classAttribute(); //insts.attribute(11); string s = insts.toString(); s = s.Substring(s.IndexOf("{") + 1); s = s.Substring(0, s.IndexOf("}")); s = s.Substring(0, s.Length); string[] ae = s.Split(','); /*ArrayList arr = new ArrayList(); * string path_class = @"D:\final_version\Gesture-Gis-master\GestureGis2\Classfile.txt"; * using (StreamReader reader = new StreamReader(path_class)) * { * while (!reader.EndOfStream) * { * arr.Add(reader.ReadLine()); * } * reader.Close(); * }*/ PredictedClassbyWeka = (string)(ae[pre]); arrfFile.close(); //insts.instance(index).attribute(3); /*System.Diagnostics.Debug.WriteLine(numCorrect + " out of " + testSize + " correct (" + * (double)((double)numCorrect / (double)testSize * 100.0) + "%)"); * Console.WriteLine(numCorrect + " out of " + testSize + " correct (" + * (double)((double)numCorrect / (double)testSize * 100.0) + "%)");*/ } catch (java.lang.Exception ex) { ex.printStackTrace(); } }
public weka.core.Instances[] GenerateRegressionInstances(int rIdx) { var instances = new weka.core.Instances[3]; string dataName = ((Rounds)rIdx).ToString().ToLower() + "_{0}_data"; for(int i = 0; i < 3; i++) { var atts = generateStateAttributes(rIdx); string className = i == 0 ? "Fold" : i == 1 ? "Call" : "Raise"; atts.addElement(new weka.core.Attribute(className)); var data = new weka.core.Instances(string.Format(dataName, className.ToLower()), atts, 0); data.setClassIndex(data.numAttributes() - 1); instances[i] = data; } return instances; }
// Test the classification result of each map that a user played, // with the data available as if they were playing through it public static void classifyTest(String dataString, String playerID) { String results = ""; try { java.io.StringReader stringReader = new java.io.StringReader(dataString); java.io.BufferedReader buffReader = new java.io.BufferedReader(stringReader); /* NOTE THAT FOR NAIVE BAYES ALL WEIGHTS CAN BE = 1*/ //weka.core.converters.ConverterUtils.DataSource source = new weka.core.converters.ConverterUtils.DataSource("iris.arff"); weka.core.Instances data = new weka.core.Instances(buffReader); //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); } weka.classifiers.Classifier cl; for (int i = 3; i < data.numInstances(); i++) { cl = new weka.classifiers.bayes.NaiveBayes(); //cl = new weka.classifiers.trees.J48(); //cl = new weka.classifiers.lazy.IB1(); //cl = new weka.classifiers.functions.MultilayerPerceptron(); ((weka.classifiers.functions.MultilayerPerceptron)cl).setHiddenLayers("12"); weka.core.Instances subset = new weka.core.Instances(data, 0, i); cl.buildClassifier(subset); weka.classifiers.Evaluation eval = new weka.classifiers.Evaluation(subset); eval.crossValidateModel(cl, subset, 3, new java.util.Random(1)); results = results + eval.pctCorrect(); // For accuracy measurement /* For Mathews Correlation Coefficient */ //double TP = eval.numTruePositives(1); //double FP = eval.numFalsePositives(1); //double TN = eval.numTrueNegatives(1); //double FN = eval.numFalseNegatives(1); //double correlationCoeff = ((TP*TN)-(FP*FN))/Math.Sqrt((TP+FP)*(TP+FN)*(TN+FP)*(TN+FN)); //results = results + correlationCoeff; if (i != data.numInstances() - 1) { results = results + ", "; } if (i == data.numInstances() - 1) { Debug.Log("Player: " + playerID + ", Num Maps: " + data.numInstances() + ", AUC: " + eval.areaUnderROC(1)); } } } catch (java.lang.Exception ex) { Debug.LogError(ex.getMessage()); } // Write values to file for a matlab read // For accuracy StreamWriter writer = new StreamWriter("DataForMatlab/" + playerID + "_CrossFoldValidations_NeuralNet.txt"); //StreamWriter writer = new StreamWriter("DataForMatlab/"+playerID+"_CrossFoldCorrCoeff.txt"); // For mathews cc writer.WriteLine(results); writer.Close(); Debug.Log(playerID + " has been written to file"); }
public static string classifyTest(string file, string classifier) { string data = "No data"; try { //weka.core.Instances insts = new weka.core.Instances(new java.io.FileReader("C:\\Users\\kinli\\source\\repos\\WebApplication2\\WebApplication2\\iris.arff")); weka.core.Instances insts = new weka.core.Instances(new java.io.FileReader(file)); insts.setClassIndex(insts.numAttributes() - 1); weka.classifiers.Classifier cl = new weka.classifiers.trees.J48(); if (classifier == "J48") { cl = new weka.classifiers.trees.J48(); } else if (classifier == "MLP") { cl = new weka.classifiers.functions.MultilayerPerceptron(); } else if (classifier == "NaiveBayes") { cl = new weka.classifiers.bayes.NaiveBayes(); } //data = ("Performing " + percentSplit + "% split evaluation.\n"); data = ("Performing use training set evaluation.\n"); //randomize the order of the instances in the dataset. weka.filters.Filter myRandom = new weka.filters.unsupervised.instance.Randomize(); myRandom.setInputFormat(insts); insts = weka.filters.Filter.useFilter(insts, myRandom); /* * int trainSize = insts.numInstances() * percentSplit / 100; * int testSize = insts.numInstances() - trainSize; * weka.core.Instances train = new weka.core.Instances(insts, 0, trainSize); * * cl.buildClassifier(train); * int numCorrect = 0; * for (int i = trainSize; i < insts.numInstances(); i++) * { * weka.core.Instance currentInst = insts.instance(i); * double predictedClass = cl.classifyInstance(currentInst); * if (predictedClass == insts.instance(i).classValue()) * numCorrect++; * }*/ cl.buildClassifier(insts); int numCorrect = 0; for (int i = 0; i < insts.numInstances(); i++) { weka.core.Instance currentInst = insts.instance(i); double predictedClass = cl.classifyInstance(currentInst); if (predictedClass == insts.instance(i).classValue()) { numCorrect++; } } data = data + (numCorrect + " out of " + insts.numInstances() + " correct (" + (double)((double)numCorrect / (double)insts.numInstances() * 100.0) + "%)"); } catch (java.lang.Exception ex) { data = "Error"; ex.printStackTrace(); } return(data); }
private void btnLoad_Click(object sender, EventArgs e) { using (OpenFileDialog d = new OpenFileDialog()) { d.Filter = "Arff File|*.arff"; if (d.ShowDialog() == System.Windows.Forms.DialogResult.OK) { var fileReader = new java.io.FileReader(d.FileName); var instances = new weka.core.Instances(new java.io.BufferedReader(fileReader)); instances.setClassIndex(instances.numAttributes() - 1); fileReader.close(); clear_all(); foreach (weka.core.Instance i in instances) { var p = new valuePoint(i.value(0), i.value(1), (int)i.classValue()); if (p.x < 0 || p.x >= 1 || p.y < 0 || p.y >= 1) continue; point_list.Add(p); } draw_all_points(); this.pictureBox1.Invalidate(); } } }
private weka.core.Instances CreateEmptyInstances() { var atts = new java.util.ArrayList(); atts.add(new weka.core.Attribute("x")); atts.add(new weka.core.Attribute("y")); if (!ckbClassIsNominal.Checked) { atts.add(new weka.core.Attribute("v")); } else { // - nominal var attVals = new java.util.ArrayList(); //for(int i=0; i<MAXCLASSNUM; ++i) // attVals.add(i.ToString()); attVals.add("0"); attVals.add("1"); atts.add(new weka.core.Attribute("v", attVals)); } weka.core.Instances data = new weka.core.Instances("MyRelation", atts, 0); data.setClassIndex(data.numAttributes() - 1); return data; }
public weka.core.Instances GenerateClassifierInstances(int rIdx) { var atts = generateStateAttributes(rIdx); var classVals = new weka.core.FastVector(); classVals.addElement("Fold"); classVals.addElement("Call"); classVals.addElement("Raise"); atts.addElement(new weka.core.Attribute("Action", classVals)); var data = new weka.core.Instances(((Rounds)rIdx).ToString().ToLower() + "_data", atts, 0); data.setClassIndex(data.numAttributes() - 1); return data; }