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(); } }
public void WriteFile(List <List <string> > numericDataset, string file, List <string> atrNames, List <string> targetValues, bool isTargetNumeric) { weka.core.FastVector targetVals = new weka.core.FastVector(); weka.core.Instances dataRel; for (int i = 0; i < targetValues.Count; i++) { targetVals.addElement(targetValues[i]); } weka.core.Instances data; weka.core.FastVector atts = new weka.core.FastVector(); // fill and prepare the dataset for the arrf file for (int j = 0; j < insts.numAttributes(); j++) { if (j == insts.numAttributes() - 1 && isTargetNumeric == false) // target value can be nominal { atts.addElement(new weka.core.Attribute(atrNames[j], targetVals)); } else { atts.addElement(new weka.core.Attribute(atrNames[j])); } } data = new weka.core.Instances("MyRelation", atts, 0); for (int i = 0; i < insts.numInstances(); i++) { double[] vals = new double[insts.numAttributes()]; for (int j = 0; j < insts.numAttributes(); j++) { if (j == insts.numAttributes() - 1 && isTargetNumeric == false) // target value can be nominal { vals[j] = targetVals.indexOf(numericDataset[j][i]); } else { vals[j] = Convert.ToDouble(numericDataset[j][i]); } } data.add(new weka.core.DenseInstance(1.0, vals)); } if (File.Exists(file)) { File.Delete(file); } var saver = new weka.core.converters.ArffSaver(); saver.setInstances(data); saver.setFile(new java.io.File(file)); // files are saved into {AppFolder}/bin/Debug folder. You can find two files in this path. saver.writeBatch(); }
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); } }
/// <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 void Build(weka.core.Instances instances) { WekaUtils.DebugAssert(instances.numClasses() == 3, "instance's numClasses should be 3."); for (int i = 0; i < m_counts.Length; i++) { m_counts[i] = 0; } double c = m_tp / m_sl; foreach (weka.core.Instance instance in instances) { int v = (int)instance.classValue(); if (v == 2) { m_counts[2] += c; } else if (v == 0) { m_counts[0]++; } else { m_counts[1]++; } } }
public static double[] GetCount(Instances instances) { double a = 0, b = 0, c = 0; foreach (Instance i in instances) { if (i.classValue() == 2) c++; else if (i.classValue() == 0) a++; else b++; } //if (a == 0 || b == 0) // return null; //double c = a + b; //a = a / c; //b = b / c; //if (a > b) //{ // a = a / b; // b = 1; //} //else //{ // b = b / a; // a = 1; //} return new double[] { a, b, c }; }
public void test_has_class_value_with_limited_training_set() { TestingRow5[] rows = new[] { new TestingRow5 { CLASS = 1.0, ATT_1 = "1" }, new TestingRow5 { CLASS = 33.0, ATT_1 = "2" }, new TestingRow5 { CLASS = 22.0, ATT_1 = "3" }, new TestingRow5 { CLASS = 33.0, ATT_1 = "4" }, new TestingRow5 { CLASS = 33.0, ATT_1 = "5" }, new TestingRow5 { CLASS = 11.0, ATT_1 = "2" } }; InstancesBuilder <TestingRow5> builder = new InstancesBuilder <TestingRow5>(rows, 0, 3); weka.core.Instances instances = builder.Build(); Assert.AreEqual(3, instances.numAttributes()); Assert.AreEqual(6, instances.numInstances()); CollectionAssert.AreEqual(new[] { "1", "2", "3", "4", "5", "2" }, instances.GetAttrStrings(1)); CollectionAssert.AreEqual(new[] { "0", "1", "0", "0", "0", "1" }, instances.GetAttrStrings(2)); }
private void AlgoritmAccurancy(weka.core.Instances insts, Classifier classifier, string algoritmName, bool?isNominal = null) { ClassifierManager manager = new ClassifierManager(insts); manager.EliminateTargetAttribute(); if (isNominal == true) { manager.Discreatization(manager.Instance); } else if (isNominal == false) { manager.NominalToBinary(manager.Instance); manager.Normalization(manager.Instance); } manager.Randomize(manager.Instance); TrainModel model = manager.Train(manager.Instance, classifier); SuccessfulAlgorithm.Add(new AlgorithmModel() { SuccessRatio = manager.FindAccurancy(), AlgorithName = algoritmName, TrainModel = model });; }
/// <summary> Sets the format of the input instances. /// /// </summary> /// <param name="instanceInfo">an Instances object containing the input instance /// structure (any instances contained in the object are ignored - only the /// structure is required). /// </param> /// <returns> true if the outputFormat may be collected immediately /// </returns> /// <exception cref="Exception">if the format couldn't be set successfully /// </exception> public override bool setInputFormat(Instances instanceInfo) { base.setInputFormat(instanceInfo); m_SelectCols.Upper = instanceInfo.numAttributes() - 1; // Create the output buffer FastVector attributes = new FastVector(); int outputClass = - 1; m_SelectedAttributes = m_SelectCols.Selection; int inStrKeepLen = 0; int[] inStrKeep = new int[m_SelectedAttributes.Length]; for (int i = 0; i < m_SelectedAttributes.Length; i++) { int current = m_SelectedAttributes[i]; if (instanceInfo.classIndex() == current) { outputClass = attributes.size(); } Attribute keep = (Attribute) instanceInfo.attribute(current).copy(); if (keep.type() == Attribute.STRING) { inStrKeep[inStrKeepLen++] = current; } attributes.addElement(keep); } m_InputStringIndex = new int[inStrKeepLen]; Array.Copy(inStrKeep, 0, m_InputStringIndex, 0, inStrKeepLen); Instances outputFormat = new Instances(instanceInfo.relationName(), attributes, 0); outputFormat.ClassIndex = outputClass; setOutputFormat(outputFormat); return true; }
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); } }
public static void FilterInstances(weka.core.Instances allInstances) { DateTime nextHpDate = DateTime.MinValue; java.util.LinkedList deleteList = new java.util.LinkedList(); for (int i = 0; i < allInstances.numInstances(); ++i) { DateTime nowDate = WekaUtils.GetDateValueFromInstances(allInstances, 0, i); if (TestParameters2.RealTimeMode && i == allInstances.numInstances() - 1) { allInstances.instance(i).setClassValue(0); allInstances.instance(i).setValue(1, WekaUtils.GetTimeFromDate(Parameters.MaxDate) * 1000); } else { if (nowDate < nextHpDate) { deleteList.Add(allInstances.instance(i)); } else { DateTime hpDate = WekaUtils.GetDateValueFromInstances(allInstances, 1, i); nextHpDate = hpDate; } } } allInstances.removeAll(deleteList); }
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(); } } }
public override void buildClassifier(Instances instances) { // can classifier handle the data? getCapabilities().testWithFail(instances); // remove instances with missing class instances = new Instances(instances); instances.deleteWithMissingClass(); double sum = 0; int cnt = 0; foreach (Instance instance in instances) { if (!instance.classIsMissing()) { sum += instance.value(idxAttribute); cnt++; } } mean = sum / cnt; sum = 0; foreach (Instance instance in instances) { if (!instance.classIsMissing()) { sum += (instance.value(idxAttribute) - mean) * (instance.value(idxAttribute) - mean); } } sigma2 = sum / cnt; epsilon = SelectBestEpsilon(instances, mean, sigma2); }
//************************************************************************************** /// <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))); }
public static weka.core.Instances GET_INSTS() { // weka.core.converters.ConverterUtils.DataSource DATA = new weka.core.converters.ConverterUtils.DataSource(); weka.core.Instances insts = new weka.core.Instances(new java.io.FileReader("testing.arff")); return(insts); }
/// <summary> Stump method for building the classifiers. /// /// </summary> /// <param name="data">the training data to be used for generating the /// bagged classifier. /// </param> /// <exception cref="Exception">if the classifier could not be built successfully /// </exception> public override void buildClassifier(Instances data) { if (m_Classifier == null) { throw new System.Exception("A base classifier has not been specified!"); } m_Classifiers = Classifier.makeCopies(m_Classifier, m_NumIterations); }
/// <summary> Sets the format of the input instances. /// /// </summary> /// <param name="instanceInfo">an Instances object containing the input instance /// structure (any instances contained in the object are ignored - only the /// structure is required). /// </param> /// <returns> true if the outputFormat may be collected immediately /// </returns> public override bool setInputFormat(Instances instanceInfo) { base.setInputFormat(instanceInfo); setOutputFormat(instanceInfo); //UPGRADE_TODO: The differences in the expected value of parameters for constructor 'java.util.Random.Random' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" m_Random = new System.Random((System.Int32) m_Seed); return true; }
//private weka.core.Instances m_instances; public void evaluateModel(double[] v, weka.core.Instances instances) { double[] c = new double[instances.numInstances()]; for (int i = 0; i < c.Length; ++i) { c[i] = instances.instance(i).classValue(); } evaluateModel(v, c); }
//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)); }
public WekaNETBridge.WekaClassifier CreateWekaClassifier(weka.classifiers.Classifier currentClassifier, Solution <DRComponent> solution) { weka.core.Instances reducedDataset = WekaNETBridge.WekaClassification.GetReducedDataset(this.WekaClassification.OriginalDataset, solution.AttributesToRemove(), solution.InstancesToRemove()); weka.classifiers.Classifier classifier = this.WekaClassification.CreateClassifier(reducedDataset, currentClassifier); WekaNETBridge.WekaClassifier wekaClassifier = new WekaNETBridge.WekaClassifier(); wekaClassifier.Classifier = classifier; wekaClassifier.AttributesToRemove = solution.AttributesToRemove(); return(wekaClassifier); }
public static weka.core.Instances Normalize(weka.core.Instances insts) { weka.filters.Filter normalizeFilter = new weka.filters.unsupervised.instance.Normalize(); normalizeFilter.setInputFormat(insts); weka.filters.Filter missingFilter = new weka.filters.unsupervised.attribute.ReplaceMissingValues(); missingFilter.setInputFormat(insts); insts = weka.filters.Filter.useFilter(insts, normalizeFilter); return(weka.filters.Filter.useFilter(insts, missingFilter)); }
public void Test(weka.core.Instances testInstances = null) { if (testInstances == null) { testInstances = CreateCurrentInstances(); } //if (m_cls is MLEA.IBatchClassifier) //{ // StringBuilder sb = new StringBuilder(); // MLEA.IBatchClassifier batchClassifier = m_cls as MLEA.IBatchClassifier; // double[] d = batchClassifier.classifyInstances(testInstances); // for (int i = 0; i < d.Length; ++i) // { // string s = string.Format("{0}, {1}: {2}", testInstances.instance(i).value(0).ToString("N2"), testInstances.instance(i).value(1).ToString("N2"), d[i].ToString("N0")); // sb.AppendLine(s); // } // this.Invoke(new Action(() => // { // txtEval.Text = sb.ToString(); // })); //} //else { MLEA.MyEvaluation eval = null; if (testInstances.classAttribute().isNominal()) { var costMatrix = MLEA.TestParameters.CostMatrix; eval = new MLEA.MyEvaluation(costMatrix); eval.evaluateModel(m_cls, testInstances); this.Invoke(new Action(() => { txtEval.Text = string.Format("TP:{0}, FP:{1}, Cost:{2}", eval.numTruePositives(1), eval.numFalsePositives(1), eval.totalCost().ToString()); })); } else { //eval = new MLEA.MyEvaluation(costMatrix); //eval.evaluateModel(m_cls, testInstances); //this.Invoke(new Action(() => //{ // txtEval.Text = eval.toSummaryString().Replace("\n", System.Environment.NewLine) // + System.Environment.NewLine; //})); } } }
public void evaluateModel(weka.classifiers.Classifier classifier, weka.core.Instances instances) { double[] v = WekaUtils.ClassifyInstances(instances, classifier); //weka.classifiers.Evaluation eval = new weka.classifiers.Evaluation(instances, m_costMatrix); //v = eval.evaluateModel(classifier, instances); evaluateModel(v, instances); //int n = 0; //for (int i = 0; i < v.Length; ++i) // if (v[i] != 0) // n++; }
//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!"); } }
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); } }
//************************************************************************************** /// <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); }
public string BuildCandlePatternDeals() { WekaUtils.Instance.WriteLog("Now BuildCandlePatternDeals"); var cp = TestParameters2.CandidateParameter; string resultFile = TestParameters.GetBaseFilePath(string.Format("IncrementTest_{0}_{1}_{2}.txt", cp.MainSymbol, "CandlePattern", cp.MainPeriod)); if (File.Exists(resultFile)) { return(string.Empty); } string txtFileName = TestParameters.GetBaseFilePath(string.Format("{0}_{1}_{2}.txt", cp.MainSymbol, "CandlePattern", cp.MainPeriod)); System.IO.File.Delete(txtFileName); if (!File.Exists(txtFileName)) { bool ret = GenerateCandlePatterns(txtFileName); if (!ret) { return(string.Empty); } } string arffFileName = TestParameters.GetBaseFilePath(string.Format("{0}_{1}_{2}.arff", cp.MainSymbol, "CandlePattern", cp.MainPeriod)); if (!System.IO.File.Exists(arffFileName)) { GenerateArff(arffFileName, txtFileName); } weka.core.Instances allInstances = WekaUtils.LoadInstances(arffFileName); //FilterInstances(allInstances); WekaUtils.SaveInstances(allInstances, arffFileName); int n = (int)(24 / TestParameters2.MainPeriodOfHour); n = TestParameters2.nPeriod; return(TestManager.IncrementTest(allInstances, () => { return WekaUtils.CreateClassifier(typeof(MinDistanceClassifier)); //return WekaUtils.CreateClassifier(typeof(weka.classifiers.lazy.IBk)); }, "1,2,3,4", resultFile, n)); }
public static void CalculateSuccessForAnn(weka.core.Instances originalInsts) { try { var form = Form.ActiveForm as Form1; form.successPrcAnn.Text = "Training..."; form.successRtAnn.Text = "../" + testSize; weka.core.Instances insts = originalInsts; // Pre-process insts = ConvertNominalToNumeric(insts); insts = Normalize(insts); // Classify weka.classifiers.Classifier cl = new weka.classifiers.functions.MultilayerPerceptron(); weka.core.Instances train = new weka.core.Instances(insts, 0, trainSize); cl.buildClassifier(train); int numCorrect = 0; double percentage = 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++; } percentage = (double)numCorrect / (double)testSize * 100.0; form.successRtAnn.Text = numCorrect + "/" + testSize; form.successPrcAnn.Text = String.Format("{0:0.00}", percentage) + "%"; } succesRates.Add(Classifier.ANN, percentage); classifiers.Add(Classifier.ANN, cl); } catch (java.lang.Exception ex) { ex.printStackTrace(); MessageBox.Show(ex.ToString(), "Error for Neural Network", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception) { MessageBox.Show("Error for Neural Network", "Error for Neural Network", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void CSV2Arff() { //load csv weka.core.converters.CSVLoader loader = new weka.core.converters.CSVLoader(); //weka.core.converters.TextDirectoryLoader loader = new weka.core.converters.TextDirectoryLoader(); // C:/ Users / DELL / source / repos / WekafromCtest / WekafromCtest / loader.setSource(new java.io.File("D:/final_version/Gesture-Gis-master/GestureGis2/ComparisonFeaturefile.txt")); weka.core.Instances data = loader.getDataSet(); //save arff weka.core.converters.ArffSaver saver = new weka.core.converters.ArffSaver(); saver.setInstances(data); //and save as arff file saver.setFile(new java.io.File("D:/final_version/Gesture-Gis-master/GestureGis2/ComparisonFeaturefile.arff")); saver.writeBatch(); }
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; } } }
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"); } }
//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); } }
/// /// <summary> * Generates the classifier. /// * </summary> /// * <param name="instances"> set of instances serving as training data </param> /// * <exception cref="Exception"> if the classifier has not been generated successfully </exception> /// public override void buildClassifier(Instances instances) { // can classifier handle the data? getCapabilities().testWithFail(instances); // remove instances with missing class instances = new Instances(instances); instances.deleteWithMissingClass(); double sumOfWeights = 0; WekaUtils.DebugAssert(instances.numClasses() == 3, "instance's numClasses should be 3."); m_counts = new double[instances.numClasses()]; m_normalCounts = new double[instances.numClasses()]; for (int i = 0; i < m_counts.Length; i++) { m_counts[i] = 0; m_normalCounts[i] = 0; } double c = m_tp / m_sl; foreach (Instance instance in instances) { int v = (int)instance.classValue(); if (v == 2) { m_counts[v] += instance.weight() * c; sumOfWeights += instance.weight() * c; } else { m_counts[v] += instance.weight(); sumOfWeights += instance.weight(); } } double start = 0; for (int i = 0; i < m_counts.Length; ++i) { m_normalCounts[i] = (double)m_counts[i] / sumOfWeights + start; start = m_normalCounts[i]; } }
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) { } }
public static void ClassifyTest() { try { weka.core.Instances insts = new ConverterUtils.DataSource("weka").getDataSet(); insts.setClassIndex(insts.numAttributes() - 1); 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 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) + "%)"); } catch (java.lang.Exception ex) { ex.printStackTrace(); } }
/// /// <summary> * Generates the classifier. /// * </summary> /// * <param name="instances"> set of instances serving as training data </param> /// * <exception cref="Exception"> if the classifier has not been generated successfully </exception> /// public override void buildClassifier(Instances instances) { // can classifier handle the data? getCapabilities().testWithFail(instances); // remove instances with missing class var trainInstances = new Instances(instances); trainInstances.deleteWithMissingClass(); WekaUtils.DebugAssert(instances.numClasses() == 3, "instance's numClasses should be 3."); m_counts = new double[instances.numClasses()]; for (int i = 0; i < m_counts.Length; i++) { m_counts[i] = 0; } //double c = m_tp / m_sl; foreach (Instance instance in instances) { int v = (int)instance.classValue(); m_counts[v] += 1; sumOfWeights += 1; } }
/// <summary> Applies the cost matrix to a set of instances. If a random number generator is /// supplied the instances will be resampled, otherwise they will be rewighted. /// Adapted from code once sitting in Instances.java /// /// </summary> /// <param name="data">the instances to reweight. /// </param> /// <param name="random">a random number generator for resampling, if null then instances are /// rewighted. /// </param> /// <returns> a new dataset reflecting the cost of misclassification. /// </returns> /// <exception cref="Exception">if the data has no class or the matrix in inappropriate. /// </exception> public virtual Instances applyCostMatrix(Instances data, System.Random random) { double sumOfWeightFactors = 0, sumOfMissClassWeights, sumOfWeights; double[] weightOfInstancesInClass, weightFactor, weightOfInstances; Instances newData; if (data.classIndex() < 0) { throw new System.Exception("Class index is not set!"); } if (size() != data.numClasses()) { throw new System.Exception("Misclassification cost matrix has " + "wrong format!"); } weightFactor = new double[data.numClasses()]; weightOfInstancesInClass = new double[data.numClasses()]; for (int j = 0; j < data.numInstances(); j++) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" weightOfInstancesInClass[(int) data.instance(j).classValue()] += data.instance(j).weight(); } sumOfWeights = Utils.sum(weightOfInstancesInClass); // normalize the matrix if not already for (int i = 0; i < size(); i++) if (!Utils.eq(getXmlElement(i, i), 0)) { CostMatrix normMatrix = new CostMatrix(this); normMatrix.normalize(); return normMatrix.applyCostMatrix(data, random); } for (int i = 0; i < data.numClasses(); i++) { // Using Kai Ming Ting's formula for deriving weights for // the classes and Breiman's heuristic for multiclass // problems. sumOfMissClassWeights = 0; for (int j = 0; j < data.numClasses(); j++) { if (Utils.sm(getXmlElement(i, j), 0)) { throw new System.Exception("Neg. weights in misclassification " + "cost matrix!"); } sumOfMissClassWeights += getXmlElement(i, j); } weightFactor[i] = sumOfMissClassWeights * sumOfWeights; sumOfWeightFactors += sumOfMissClassWeights * weightOfInstancesInClass[i]; } for (int i = 0; i < data.numClasses(); i++) { weightFactor[i] /= sumOfWeightFactors; } // Store new weights weightOfInstances = new double[data.numInstances()]; for (int i = 0; i < data.numInstances(); i++) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" weightOfInstances[i] = data.instance(i).weight() * weightFactor[(int) data.instance(i).classValue()]; } // Change instances weight or do resampling if (random != null) { return data.resampleWithWeights(random, weightOfInstances); } else { Instances instances = new Instances(data); for (int i = 0; i < data.numInstances(); i++) { instances.instance(i).Weight = weightOfInstances[i]; } return instances; } }
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; } } }
/// <summary> This will remove all buffered instances from the inputformat dataset. /// Use this method rather than getInputFormat().delete(); /// </summary> protected internal virtual void flushInput() { if (m_InputStringAtts.Length > 0) { m_InputFormat = m_InputFormat.stringFreeStructure(); } else { // This more efficient than new Instances(m_InputFormat, 0); m_InputFormat.delete(); } }
/// <summary> Takes string values referenced by an Instance and copies them from a /// source dataset to a destination dataset. The instance references are /// updated to be valid for the destination dataset. The instance may have the /// structure (i.e. number and attribute position) of either dataset (this /// affects where references are obtained from). Only works if the number /// of string attributes is the same in both indices (implicitly these string /// attributes should be semantically same but just with shifted positions). /// /// </summary> /// <param name="instance">the instance containing references to strings in the source /// dataset that will have references updated to be valid for the destination /// dataset. /// </param> /// <param name="instSrcCompat">true if the instance structure is the same as the /// source, or false if it is the same as the destination (i.e. which of the /// string attribute indices contains the correct locations for this instance). /// </param> /// <param name="srcDataset">the dataset for which the current instance string /// references are valid (after any position mapping if needed) /// </param> /// <param name="srcStrAtts">an array containing the indices of string attributes /// in the source datset. /// </param> /// <param name="destDataset">the dataset for which the current instance string /// references need to be inserted (after any position mapping if needed) /// </param> /// <param name="destStrAtts">an array containing the indices of string attributes /// in the destination datset. /// </param> protected internal virtual void copyStringValues(Instance instance, bool instSrcCompat, Instances srcDataset, int[] srcStrAtts, Instances destDataset, int[] destStrAtts) { if (srcDataset == destDataset) { return ; } if (srcStrAtts.Length != destStrAtts.Length) { throw new System.ArgumentException("Src and Dest string indices differ in length!!"); } for (int i = 0; i < srcStrAtts.Length; i++) { int instIndex = instSrcCompat?srcStrAtts[i]:destStrAtts[i]; Attribute src = srcDataset.attribute(srcStrAtts[i]); Attribute dest = destDataset.attribute(destStrAtts[i]); if (!instance.isMissing(instIndex)) { //System.err.println(instance.value(srcIndex) // + " " + src.numValues() // + " " + dest.numValues()); //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" int valIndex = dest.addStringValue(src, (int) instance.value_Renamed(instIndex)); // setValue here shouldn't be too slow here unless your dataset has // squillions of string attributes instance.setValue(instIndex, (double) valIndex); } } }
/// <summary> Copies string values contained in the instance copied to a new /// dataset. The Instance must already be assigned to a dataset. This /// dataset and the destination dataset must have the same structure. /// /// </summary> /// <param name="instance">the Instance containing the string values to copy. /// </param> /// <param name="destDataset">the destination set of Instances /// </param> /// <param name="strAtts">an array containing the indices of any string attributes /// in the dataset. /// </param> private void copyStringValues(Instance inst, Instances destDataset, int[] strAtts) { if (strAtts.Length == 0) { return ; } if (inst.dataset() == null) { throw new System.ArgumentException("Instance has no dataset assigned!!"); } else if (inst.dataset().numAttributes() != destDataset.numAttributes()) { throw new System.ArgumentException("Src and Dest differ in # of attributes!!"); } copyStringValues(inst, true, inst.dataset(), strAtts, destDataset, strAtts); }
/// <summary> Sets the format of the input instances. /// /// </summary> /// <param name="instanceInfo">an Instances object containing the input instance /// structure (any instances contained in the object are ignored - only the /// structure is required). /// </param> /// <exception cref="UnsupportedAttributeTypeException">if the specified attribute /// is neither numeric or nominal. /// </exception> public override bool setInputFormat(Instances instanceInfo) { base.setInputFormat(instanceInfo); m_AttIndex.Upper=instanceInfo.numAttributes() - 1; if (!Numeric && !Nominal) { throw new Exception("Can only handle numeric " + "or nominal attributes."); } m_Values.Upper=instanceInfo.attribute(m_AttIndex.Index).numValues() - 1; if (Nominal && m_ModifyHeader) { instanceInfo = new Instances(instanceInfo, 0); // copy before modifying Attribute oldAtt = instanceInfo.attribute(m_AttIndex.Index); int[] selection = m_Values.Selection; FastVector newVals = new FastVector(); for (int i = 0; i < selection.Length; i++) { newVals.addElement(oldAtt.value_Renamed(selection[i])); } instanceInfo.deleteAttributeAt(m_AttIndex.Index); instanceInfo.insertAttributeAt(new Attribute(oldAtt.name(), newVals), m_AttIndex.Index); m_NominalMapping = new int[oldAtt.numValues()]; for (int i = 0; i < m_NominalMapping.Length; i++) { bool found = false; for (int j = 0; j < selection.Length; j++) { if (selection[j] == i) { m_NominalMapping[i] = j; found = true; break; } } if (!found) { m_NominalMapping[i] = - 1; } } } setOutputFormat(instanceInfo); return true; }
/// <summary> Filters an entire set of instances through a filter and returns /// the new set. /// /// </summary> /// <param name="data">the data to be filtered /// </param> /// <param name="filter">the filter to be used /// </param> /// <returns> the filtered set of data /// </returns> /// <exception cref="Exception">if the filter can't be used successfully /// </exception> public static Instances useFilter(Instances data, Filter filter) { /* System.err.println(filter.getClass().getName() + " in:" + data.numInstances()); */ for (int i = 0; i < data.numInstances(); i++) { filter.input(data.instance(i)); } filter.batchFinished(); Instances newData = filter.getOutputFormat(); Instance processed; while ((processed = filter.output()) != null) { newData.add(processed); } /* System.err.println(filter.getClass().getName() + " out:" + newData.numInstances()); */ return newData; }
/// <summary> Sets the format of the input instances. /// /// </summary> /// <param name="instanceInfo">an Instances object containing the input /// instance structure (any instances contained in the object are /// ignored - only the structure is required). /// </param> /// <returns> true if the outputFormat may be collected immediately /// </returns> /// <exception cref="Exception">if the input format can't be set /// successfully /// </exception> public override bool setInputFormat(Instances instanceInfo) { base.setInputFormat(instanceInfo); setOutputFormat(instanceInfo); return true; }
/// <summary> Method for testing filters ability to process multiple batches. /// /// </summary> /// <param name="argv">should contain the following arguments:<br> /// -i (first) input file <br> /// -o (first) output file <br> /// -r (second) input file <br> /// -s (second) output file <br> /// -c class_index <br> /// or -h for help on options /// </param> /// <exception cref="Exception">if something goes wrong or the user requests help on /// command options /// </exception> public static void batchFilterFile(Filter filter, System.String[] options) { Instances firstData = null; Instances secondData = null; //UPGRADE_ISSUE: Class hierarchy differences between 'java.io.Reader' and 'System.IO.StreamReader' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1186'" System.IO.StreamReader firstInput = null; //UPGRADE_ISSUE: Class hierarchy differences between 'java.io.Reader' and 'System.IO.StreamReader' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1186'" System.IO.StreamReader secondInput = null; System.IO.StreamWriter firstOutput = null; System.IO.StreamWriter secondOutput = null; bool helpRequest; try { helpRequest = Utils.getFlag('h', options); System.String fileName = Utils.getOption('i', options); if (fileName.Length != 0) { //UPGRADE_TODO: The differences in the expected value of parameters for constructor 'java.io.BufferedReader.BufferedReader' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" //UPGRADE_WARNING: At least one expression was used more than once in the target code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1181'" //UPGRADE_TODO: Constructor 'java.io.FileReader.FileReader' was converted to 'System.IO.StreamReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" firstInput = new System.IO.StreamReader(new System.IO.StreamReader(fileName, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(fileName, System.Text.Encoding.Default).CurrentEncoding); } else { throw new System.Exception("No first input file given.\n"); } fileName = Utils.getOption('r', options); if (fileName.Length != 0) { //UPGRADE_TODO: The differences in the expected value of parameters for constructor 'java.io.BufferedReader.BufferedReader' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" //UPGRADE_WARNING: At least one expression was used more than once in the target code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1181'" //UPGRADE_TODO: Constructor 'java.io.FileReader.FileReader' was converted to 'System.IO.StreamReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" secondInput = new System.IO.StreamReader(new System.IO.StreamReader(fileName, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(fileName, System.Text.Encoding.Default).CurrentEncoding); } else { throw new System.Exception("No second input file given.\n"); } fileName = Utils.getOption('o', options); if (fileName.Length != 0) { //UPGRADE_TODO: Constructor 'java.io.FileOutputStream.FileOutputStream' was converted to 'System.IO.FileStream.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileOutputStreamFileOutputStream_javalangString'" firstOutput = new System.IO.StreamWriter(new System.IO.FileStream(fileName, System.IO.FileMode.Create), System.Text.Encoding.Default); } else { firstOutput = new System.IO.StreamWriter(System.Console.OpenStandardOutput(), System.Text.Encoding.Default); } fileName = Utils.getOption('s', options); if (fileName.Length != 0) { //UPGRADE_TODO: Constructor 'java.io.FileOutputStream.FileOutputStream' was converted to 'System.IO.FileStream.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileOutputStreamFileOutputStream_javalangString'" secondOutput = new System.IO.StreamWriter(new System.IO.FileStream(fileName, System.IO.FileMode.Create), System.Text.Encoding.Default); } else { secondOutput = new System.IO.StreamWriter(System.Console.OpenStandardOutput(), System.Text.Encoding.Default); } System.String classIndex = Utils.getOption('c', options); // if (filter instanceof OptionHandler) // { // ((OptionHandler)filter).setOptions(options); // } Utils.checkForRemainingOptions(options); if (helpRequest) { throw new System.Exception("Help requested.\n"); } firstData = new Instances(firstInput, 1); secondData = new Instances(secondInput, 1); if (!secondData.equalHeaders(firstData)) { throw new System.Exception("Input file formats differ.\n"); } if (classIndex.Length != 0) { if (classIndex.Equals("first")) { firstData.ClassIndex = 0; secondData.ClassIndex = 0; } else if (classIndex.Equals("last")) { firstData.ClassIndex = firstData.numAttributes() - 1; secondData.ClassIndex = secondData.numAttributes() - 1; } else { firstData.ClassIndex = System.Int32.Parse(classIndex) - 1; secondData.ClassIndex = System.Int32.Parse(classIndex) - 1; } } } catch (System.Exception ex) { System.String filterOptions = ""; // Output the error and also the valid options // if (filter instanceof OptionHandler) // { // filterOptions += "\nFilter options:\n\n"; // Enumeration enu = ((OptionHandler)filter).listOptions(); // while (enu.hasMoreElements()) // { // Option option = (Option) enu.nextElement(); // filterOptions += option.synopsis() + '\n' // + option.description() + "\n"; // } // } System.String genericOptions = "\nGeneral options:\n\n" + "-h\n" + "\tGet help on available options.\n" + "-i <filename>\n" + "\tThe file containing first input instances.\n" + "-o <filename>\n" + "\tThe file first output instances will be written to.\n" + "-r <filename>\n" + "\tThe file containing second input instances.\n" + "-s <filename>\n" + "\tThe file second output instances will be written to.\n" + "-c <class index>\n" + "\tThe number of the attribute to use as the class.\n" + "\t\"first\" and \"last\" are also valid entries.\n" + "\tIf not supplied then no class is assigned.\n"; //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" throw new System.Exception('\n' + ex.Message + filterOptions + genericOptions); } bool printedHeader = false; if (filter.setInputFormat(firstData)) { //UPGRADE_TODO: Method 'java.io.PrintWriter.println' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioPrintWriterprintln_javalangString'" firstOutput.WriteLine(filter.getOutputFormat().ToString()); printedHeader = true; } // Pass all the instances to the filter while (firstData.readInstance(firstInput)) { if (filter.input(firstData.instance(0))) { if (!printedHeader) { throw new System.ApplicationException("Filter didn't return true from setInputFormat() " + "earlier!"); } //UPGRADE_TODO: Method 'java.io.PrintWriter.println' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioPrintWriterprintln_javalangString'" firstOutput.WriteLine(filter.output().ToString()); } firstData.delete(0); } // Say that input has finished, and print any pending output instances if (filter.batchFinished()) { if (!printedHeader) { //UPGRADE_TODO: Method 'java.io.PrintWriter.println' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioPrintWriterprintln_javalangString'" firstOutput.WriteLine(filter.getOutputFormat().ToString()); } while (filter.numPendingOutput() > 0) { //UPGRADE_TODO: Method 'java.io.PrintWriter.println' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioPrintWriterprintln_javalangString'" firstOutput.WriteLine(filter.output().ToString()); } } if (firstOutput != null) { //UPGRADE_NOTE: Exceptions thrown by the equivalent in .NET of method 'java.io.PrintWriter.close' may be different. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1099'" firstOutput.Close(); } printedHeader = false; if (filter.OutputFormatDefined) { //UPGRADE_TODO: Method 'java.io.PrintWriter.println' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioPrintWriterprintln_javalangString'" secondOutput.WriteLine(filter.getOutputFormat().ToString()); printedHeader = true; } // Pass all the second instances to the filter while (secondData.readInstance(secondInput)) { if (filter.input(secondData.instance(0))) { if (!printedHeader) { throw new System.ApplicationException("Filter didn't return true from" + " isOutputFormatDefined() earlier!"); } //UPGRADE_TODO: Method 'java.io.PrintWriter.println' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioPrintWriterprintln_javalangString'" secondOutput.WriteLine(filter.output().ToString()); } secondData.delete(0); } // Say that input has finished, and print any pending output instances if (filter.batchFinished()) { if (!printedHeader) { //UPGRADE_TODO: Method 'java.io.PrintWriter.println' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioPrintWriterprintln_javalangString'" secondOutput.WriteLine(filter.getOutputFormat().ToString()); } while (filter.numPendingOutput() > 0) { //UPGRADE_TODO: Method 'java.io.PrintWriter.println' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioPrintWriterprintln_javalangString'" secondOutput.WriteLine(filter.output().ToString()); } } if (secondOutput != null) { //UPGRADE_NOTE: Exceptions thrown by the equivalent in .NET of method 'java.io.PrintWriter.close' may be different. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1099'" secondOutput.Close(); } }
//Added by Alain Espinosa/////////////////////////////////////////////////////// /// <summary> Filters an entire set of instances and returnsthe new set. /// /// </summary> /// <param name="data">the data to be filtered /// </param> /// <returns> the filtered set of data /// </returns> /// <exception cref="Exception">if the filter can't be used successfully /// </exception> public virtual Instances FilterInstances(Instances data) { setInputFormat(data); for (int i = 0; i < data.numInstances(); i++) { input(data.instance(i)); } batchFinished(); Instances newData = getOutputFormat(); Instance processed; while ((processed = output()) != null) { newData.add(processed); } return newData; }
/// <summary> Sets the format of the input instances. /// /// </summary> /// <param name="instanceInfo">an Instances object containing the input /// instance structure (any instances contained in the object are /// ignored - only the structure is required). /// </param> /// <returns> true if the outputFormat may be collected immediately /// </returns> /// <exception cref="Exception">if the input format can't be set /// successfully /// </exception> public override bool setInputFormat(Instances instanceInfo) { if (instanceInfo.classIndex() < 0 || !instanceInfo.classAttribute().Nominal) { throw new System.ArgumentException("Supervised resample requires nominal class"); } base.setInputFormat(instanceInfo); setOutputFormat(instanceInfo); return true; }
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; }
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; }
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> Output an instance after filtering and remove from the output queue. /// /// </summary> /// <returns> the instance that has most recently been filtered (or null if /// the queue is empty). /// </returns> /// <exception cref="NullPointerException">if no output structure has been defined /// </exception> public virtual Instance output() { if (m_OutputFormat == null) { throw new System.NullReferenceException("No output instance format defined"); } if (m_OutputQueue.empty()) { return null; } Instance result = (Instance) m_OutputQueue.pop(); // Clear out references to old strings occasionally if (m_OutputQueue.empty() && m_NewBatch) { if (m_OutputStringAtts.Length > 0) { m_OutputFormat = m_OutputFormat.stringFreeStructure(); } } return result; }
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; }
/// <summary> Sets the format of the input instances. If the filter is able to /// determine the output format before seeing any input instances, it /// does so here. This default implementation clears the output format /// and output queue, and the new batch flag is set. Overriders should /// call <code>super.setInputFormat(Instances)</code> /// /// </summary> /// <param name="instanceInfo">an Instances object containing the input instance /// structure (any instances contained in the object are ignored - only the /// structure is required). /// </param> /// <returns> true if the outputFormat may be collected immediately /// </returns> /// <exception cref="Exception">if the inputFormat can't be set successfully /// </exception> public virtual bool setInputFormat(Instances instanceInfo) { m_InputFormat = instanceInfo.stringFreeStructure(); m_InputStringAtts = getStringIndices(instanceInfo); m_OutputFormat = null; m_OutputQueue = new Queue(); m_NewBatch = true; m_FirstBatchDone = false; return false; }
/// <summary> Takes string values referenced by an Instance and copies them from a /// source dataset to a destination dataset. The instance references are /// updated to be valid for the destination dataset. The instance may have the /// structure (i.e. number and attribute position) of either dataset (this /// affects where references are obtained from). The source dataset must /// have the same structure as the filter input format and the destination /// must have the same structure as the filter output format. /// /// </summary> /// <param name="instance">the instance containing references to strings in the source /// dataset that will have references updated to be valid for the destination /// dataset. /// </param> /// <param name="instSrcCompat">true if the instance structure is the same as the /// source, or false if it is the same as the destination /// </param> /// <param name="srcDataset">the dataset for which the current instance string /// references are valid (after any position mapping if needed) /// </param> /// <param name="destDataset">the dataset for which the current instance string /// references need to be inserted (after any position mapping if needed) /// </param> protected internal virtual void copyStringValues(Instance instance, bool instSrcCompat, Instances srcDataset, Instances destDataset) { copyStringValues(instance, instSrcCompat, srcDataset, m_InputStringAtts, destDataset, m_OutputStringAtts); }
/// <deprecated> use <code>setInputFormat(Instances)</code> instead. /// </deprecated> public virtual bool inputFormat(Instances instanceInfo) { return setInputFormat(instanceInfo); }
/// <summary> Gets an array containing the indices of all string attributes. /// /// </summary> /// <param name="insts">the Instances to scan for string attributes. /// </param> /// <returns> an array containing the indices of string attributes in /// the input structure. Will be zero-length if there are no /// string attributes /// </returns> protected internal virtual int[] getStringIndices(Instances insts) { // Scan through getting the indices of String attributes int[] index = new int[insts.numAttributes()]; int indexSize = 0; for (int i = 0; i < insts.numAttributes(); i++) { if (insts.attribute(i).type() == Attribute.STRING) { index[indexSize++] = i; } } int[] result = new int[indexSize]; Array.Copy(index, 0, result, 0, indexSize); return result; }
public override void buildClassifier(weka.core.Instances insts) { m_instances = insts; }