Пример #1
0
        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);
            }
        }
Пример #2
0
    //**************************************************************************************

    /// <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)));
    }
Пример #3
0
        static public List <string> do_Classification_bySerialClassfier()
        {
            List <string> listPredictClass = new List <string>();

            //----------
            predict_numCorrect = 0;
            double predictedClass;
            double actualClass;

            weka.core.Instance currentInst;
            listResult = new List <Weka_EachResult>();
            for (int i = split_trainSize; i < insts.numInstances(); i++)
            {
                currentInst = insts.instance(i);
                //TheSys.showError(currentInst.ToString(), true);
                predictedClass = serialClassifier.classifyInstance(currentInst);
                actualClass    = insts.instance(i).classValue();
                if (predictedClass == actualClass)
                {
                    predict_numCorrect++;
                }
                //==================================
                listResult.Add(new Weka_EachResult()
                {
                    ID      = i.ToString(),
                    Actual  = actualClass.ToString(),
                    Predict = predictedClass.ToString(),
                    Diff    = (predictedClass - actualClass).ToString()
                });
                //Get Class Name
                listPredictClass.Add(insts.classAttribute().value((int)predictedClass));
            }
            return(listPredictClass);
        }
Пример #4
0
        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);
            }
        }
Пример #5
0
        //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));
        }
Пример #6
0
        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;
                    //}));
                }
            }
        }
    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");
        }
    }
Пример #8
0
        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);
        }
Пример #9
0
        /// <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;
        }
Пример #10
0
        private void button_Discover_Click(object sender, EventArgs e)
        {
            String       s_newInstance = "";
            StreamReader sr            = new StreamReader(fileDirectory);
            StreamWriter sw            = new StreamWriter(@"test.arff", true);
            String       newDirectory  = "test.arff"; // for algortihms
            string       line          = "";
            string       comp          = "@data";
            string       comp2         = "@DATA";

            line = sr.ReadLine();
            do
            {
                sw.WriteLine(line);
                if (line == comp || line == comp2)
                {
                    break;
                }
            } while ((line = sr.ReadLine()) != null);

            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                s_newInstance += (String)dataGridView1.Rows[i].Cells[1].Value + ","; //değiştir
            }
            s_newInstance += "?";
            sw.WriteLine(s_newInstance);

            sr.Close();
            sw.Close();

            switch (count)
            {
            case 1:
                weka.core.Instances insts = new weka.core.Instances(new java.io.FileReader(newDirectory));
                insts.setClassIndex(insts.numAttributes() - 1);

                weka.filters.Filter myNominalData = new weka.filters.unsupervised.attribute.Discretize();
                myNominalData.setInputFormat(insts);
                insts = weka.filters.Filter.useFilter(insts, myNominalData);

                //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);

                double predictedClass = cl_Naive.classifyInstance(insts.instance(0));
                Console.WriteLine("hey", insts.instance(0));
                textBox3.Text = insts.classAttribute().value(Convert.ToInt32(predictedClass));

                break;

            case 2:
                weka.core.Instances insts2 = new weka.core.Instances(new java.io.FileReader(fileDirectory));

                insts2.setClassIndex(insts2.numAttributes() - 1);

                //Nominal to Binary
                weka.filters.Filter myBinaryData = new weka.filters.unsupervised.attribute.NominalToBinary();
                myBinaryData.setInputFormat(insts2);
                insts2 = weka.filters.Filter.useFilter(insts2, myBinaryData);

                //Normalization
                weka.filters.Filter myNormalized = new weka.filters.unsupervised.instance.Normalize();
                myNormalized.setInputFormat(insts2);
                insts2 = weka.filters.Filter.useFilter(insts2, myNormalized);

                //randomize the order of the instances in the dataset.
                weka.filters.Filter myRandom2 = new weka.filters.unsupervised.instance.Randomize();
                myRandom2.setInputFormat(insts2);
                insts2 = weka.filters.Filter.useFilter(insts2, myRandom2);

                double predictedClass2 = cl_Knn.classifyInstance(insts2.instance(0));
                textBox3.Text = insts2.classAttribute().value(Convert.ToInt32(predictedClass2));
                break;

            case 3:
                weka.core.Instances insts3 = new weka.core.Instances(new java.io.FileReader(newDirectory));

                insts3.setClassIndex(insts3.numAttributes() - 1);
                weka.filters.Filter myNormalized2 = new weka.filters.unsupervised.instance.Normalize();
                myNormalized2.setInputFormat(insts3);
                insts3 = weka.filters.Filter.useFilter(insts3, myNormalized2);


                //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);

                double predictedClass3 = cl_Tree.classifyInstance(insts3.instance(0));
                textBox3.Text = insts3.classAttribute().value(Convert.ToInt32(predictedClass3));
                break;

            case 4:
                weka.core.Instances insts4 = new weka.core.Instances(new java.io.FileReader(newDirectory));
                insts4.setClassIndex(insts4.numAttributes() - 1);
                //cl = new weka.classifiers.functions.MultilayerPerceptron();

                //Nominal to Binary
                weka.filters.Filter myBinaryData2 = new weka.filters.unsupervised.attribute.NominalToBinary();
                myBinaryData2.setInputFormat(insts4);
                insts4 = weka.filters.Filter.useFilter(insts4, myBinaryData2);

                //Normalization
                weka.filters.Filter myNormalized3 = new weka.filters.unsupervised.instance.Normalize();
                myNormalized3.setInputFormat(insts4);
                insts4 = weka.filters.Filter.useFilter(insts4, myNormalized3);

                //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);

                double predictedClass4 = cl_NN.classifyInstance(insts4.instance(0));
                textBox3.Text = insts4.classAttribute().value(Convert.ToInt32(predictedClass4));

                break;

            case 5:
                weka.core.Instances insts5 = new weka.core.Instances(new java.io.FileReader(newDirectory));

                insts5.setClassIndex(insts5.numAttributes() - 1);


                //Nominal to Binary
                weka.filters.Filter myBinaryData3 = new weka.filters.unsupervised.attribute.NominalToBinary();
                myBinaryData3.setInputFormat(insts5);
                insts5 = weka.filters.Filter.useFilter(insts5, myBinaryData3);

                //Normalization
                weka.filters.Filter myNormalized4 = new weka.filters.unsupervised.instance.Normalize();
                myNormalized4.setInputFormat(insts5);
                insts5 = weka.filters.Filter.useFilter(insts5, myNormalized4);

                //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);

                double predictedClass5 = cl_SVM.classifyInstance(insts5.instance(0));
                textBox3.Text = insts5.classAttribute().value(Convert.ToInt32(predictedClass5));
                break;

            default:
                textBox3.Text = "Error!";
                break;
            }
        }