public int ClassifyTest(Dataset testData)
        {
            int NumExampleCorrect = 0;
            int[] example;
            for (int i = 0; i < testData.TrainingSet.Count; i++)
            {
                example = (int[])testData.getTrainingExample(i);
                List<Rule> RulesCanBeCalssifies = new List<Rule>();

                for(int j = 0 ; j < ListRules.Count; j ++)
                {
                    bool b = isClassified(example, ListRules[j], testData);// true classified, false not classified
                    if (b == true)
                    {
                        RulesCanBeCalssifies.Add(ListRules[j]);
                    }
                }

                // xác định phân lớp đúng cho mẫu
                int[] count = new int[3];
                for (int j = 0; j < RulesCanBeCalssifies.Count; j++)
                {
                    if ((string)RulesCanBeCalssifies[j].AttributeTargets[0] == "-1")
                    {
                        count[0]++;
                    }
                    else if ((string)RulesCanBeCalssifies[j].AttributeTargets[0] == "0")
                    {
                        count[1]++;
                    }
                    else
                    {
                        count[2]++;
                    }
                }
                int max = -1;
                int pos = -1;
                for (int j = 0; j < count.Length; j++)
                {
                    if (max == -1 || max < count[j])
                    {
                        max = count[j];
                        pos = j;
                    }
                }

                // kiểm tra phân lớp đúng sai
                int exampleTargetValue = example[0];

                if (pos == exampleTargetValue)
                {
                    NumExampleCorrect++;
                }

            }
            return NumExampleCorrect;
        }
        public List<int> ClassifyAgain(Dataset testData)
        {
            List<int> correctPos = new List<int>();

            int[] example;
            for (int i = 0; i < testData.TrainingSet.Count; i++)
            {
                example = (int[])testData.getTrainingExample(i);

                // Kiểm tra thoả điều kiện chưa?
                List<Rule> RulesCanBeCalssifies = new List<Rule>();
                for (int j = 0; j < ListRules.Count; j++)
                {
                    bool b = isMatchCondition(example, ListRules[j], testData);// true classified, false not classified
                    if (b == true)
                    {
                        RulesCanBeCalssifies.Add(ListRules[j]);
                    }
                }

                // xác định phân lớp đúng cho mẫu
                if (RulesCanBeCalssifies.Count != 0)
                {
                    int[] count = new int[3];
                    for (int j = 0; j < RulesCanBeCalssifies.Count; j++)
                    {
                        if ((string)RulesCanBeCalssifies[j].AttributeTargetValues[0] == "-1")
                        {
                            count[0]++;
                        }
                        else if ((string)RulesCanBeCalssifies[j].AttributeTargetValues[0] == "0")
                        {
                            count[1]++;
                        }
                        else
                        {
                            count[2]++;
                        }
                    }
                    int max = -1;
                    int pos = -1;
                    for (int j = 0; j < count.Length; j++)
                    {
                        if (max == -1 || max < count[j])
                        {
                            max = count[j];
                            pos = j;
                        }
                    }

                    // kiểm tra phân lớp đúng sai
                    int exampleTargetValue = example[0];

                    if (pos == exampleTargetValue)
                    {
                        correctPos.Add(i);
                    }
                }
            }
            return correctPos;
        }
예제 #3
0
        /// <summary>
        /// Huấn luyện mô hình ANN - DT
        /// </summary>        
        private void TrainANN_DT(bool isBatchMode)
        {
            string strTrainFile = null;
            if (isBatchMode)
            {
                strTrainFile = _trainFilePath;

            }
            else
            {
                strTrainFile = tbxTrainFilePath.Text;
            }
            // Xác định bộ tham số DT với dữ liệu train tỉ lệ 9:1
            SetBestParamater4DT_ANN(strTrainFile);

            // Bước 1: Xây dựng mô hình DT với dữ liệu train
            int iPos = strTrainFile.LastIndexOf('.');
            string dataFile = strTrainFile.Remove(iPos) + ".data.txt";

            iPos = strTrainFile.IndexOf('_');
            string metaFile = strTrainFile.Remove(iPos) + ".meta";

            // Tạo dữ liệu Train
            Dataset dataDTTrain = new Dataset(metaFile, dataFile);
            DecisionTreeAlgorithm tree = new DecisionTreeAlgorithm(dataDTTrain);

            switch (cmbSplitFunc.SelectedItem.ToString())
            {
                case "Gain":
                    tree.SplitFun = DecisionTreeAlgorithm.SPLIT_GAIN;
                    break;
                case "Gain Ratio":
                    tree.SplitFun = DecisionTreeAlgorithm.SPLIT_GAIN_RATIO;
                    break;
                case "GINI":
                    tree.SplitFun = DecisionTreeAlgorithm.SPLIT_GINI;
                    break;
                case "Random":
                    tree.SplitFun = DecisionTreeAlgorithm.SPLIT_RANDOM;
                    break;
            }
            switch (cmbPruneFunc.SelectedItem.ToString())
            {
                case "Pessimistic":
                    tree.PruneAlg = DecisionTreeAlgorithm.PRUNING_PESSIMISTIC;
                    break;
                case "Reduced-error":
                    tree.PruneAlg = DecisionTreeAlgorithm.PRUNING_REDUCED_ERROR;
                    break;
            }
            // Học, xây dựng lên cây quyết định
            tree.BuildDTTree();

            // Duyệt cây và trích ra tập luật
            tree.ExtractRules();

            iPos = strTrainFile.LastIndexOf('_');
            string ruleFile = strTrainFile.Remove(iPos) + ".rules";
            tree.SaveRule2File(ruleFile);

            // Bước 2: Thực hiện test trên dữ liệu train với mô hình mới tạo
            //         và xác định số mẫu test dúng làm đầu vào cho AN gợi là NewDataTrain
            // Thực hiện test lại với dữ liệu train, những mẫu test phân lớp lại đúng
            // Sẽ là dữ liệu train cho ANN đặt là newANNDataTrain
            Dataset dataDTTest = dataDTTrain;
            List<int> CorrectClassifyTests = tree.ListRules.ClassifyAgain(dataDTTest);

            // Bước 3: Thực hiện xây dựng mô hình ANN với dữ liệu học moi
            // Thực hiện test lại với dữ liệu train
            //khởi tạo các tham số cho mạng
            ANNParameterBUS.HiddenNode = int.Parse(tbxANNHiddenNode.Text);
            ANNParameterBUS.OutputNode = 3;
            ANNParameterBUS.MaxEpoch = int.Parse(tbxMaxLoops.Text);
            ANNParameterBUS.LearningRate = double.Parse(tbxLearningRate.Text);
            ANNParameterBUS.Momentum = double.Parse(tbxMomentum.Text);
            ANNParameterBUS.Bias = double.Parse(tbxBias.Text);

            //Tiến hành train
            BackpropagationNetwork bpNetwork;
            TrainingSet tempTrainingSet = new TrainingSet(strTrainFile, ANNParameterBUS.OutputNode);
            TrainingSet trainSet = new TrainingSet(tempTrainingSet.InputVectorLength, ANNParameterBUS.OutputNode);

            for (int i = 0; i < CorrectClassifyTests.Count; i++)
            {
                int pos = (int)CorrectClassifyTests[i];
                TrainingSample tsp = (TrainingSample)tempTrainingSet[pos];
                trainSet.Add(tsp);
            }

            LinearLayer inputLayer = new LinearLayer(trainSet.InputVectorLength);
            ActivationLayer hidenLayer = null;
            ActivationLayer outputLayer = null;
            switch (cmbActivationFunc.SelectedItem.ToString())
            {
                case "Sigmoid":
                    hidenLayer = new SigmoidLayer(ANNParameterBUS.HiddenNode);
                    outputLayer = new SigmoidLayer(ANNParameterBUS.OutputNode);
                    break;
                case "Tanh":
                    hidenLayer = new TanhLayer(ANNParameterBUS.HiddenNode);
                    outputLayer = new TanhLayer(ANNParameterBUS.OutputNode);
                    break;
                case "Logarithm":
                    hidenLayer = new LogarithmLayer(ANNParameterBUS.HiddenNode);
                    outputLayer = new LogarithmLayer(ANNParameterBUS.OutputNode);
                    break;
                case "Sine":
                    hidenLayer = new SineLayer(ANNParameterBUS.HiddenNode);
                    outputLayer = new SineLayer(ANNParameterBUS.OutputNode);
                    break;
            }
            new BackpropagationConnector(inputLayer, hidenLayer);
            new BackpropagationConnector(hidenLayer, outputLayer);

            bpNetwork = new BackpropagationNetwork(inputLayer, outputLayer);

            bpNetwork.SetLearningRate(ANNParameterBUS.LearningRate);

            bpNetwork.EndEpochEvent += new TrainingEpochEventHandler(
                    delegate(object senderNetwork, TrainingEpochEventArgs args)
                    {
                        tlsProgressBar.Value = (int)(args.TrainingIteration * 100d / ANNParameterBUS.MaxEpoch);
                        Application.DoEvents();
                    });

            bpNetwork.Learn(trainSet, ANNParameterBUS.MaxEpoch);

            // Bước 4: Lưu lại mô hình ANN
            iPos = strTrainFile.LastIndexOf('_');
            string strModelFile = strTrainFile.Remove(iPos + 1) + "model.txt";
            Stream stream = File.Open(strModelFile, FileMode.Create);
            BinaryFormatter bformatter = new BinaryFormatter();
            bformatter.Serialize(stream, bpNetwork);
            stream.Close();
            tlsProgressBar.Value = 0;
        }
        private bool isMatchCondition(int[] example, Rule rule, Dataset testData)
        {
            for (int i = 0; i < rule.AttributeConditions.Count; i++)
            {
                string attributeCondition = (string)rule.AttributeConditions[i];
                string ConditionValue = (string)rule.AttributeConditionValues[i];

                int attributePosition = testData.getAttributePosition(attributeCondition);
                int valuesAtPositionExample = example[attributePosition];

                string exampleAttributeValuesAtPosition = testData.Attributes[attributePosition].getAttributeValueByNum(valuesAtPositionExample);

                if (ConditionValue != exampleAttributeValuesAtPosition)
                {
                    return false;
                }
            }
            return true;
        }
        DecisionTree _tree; // Current decision tree.

        #endregion Fields

        #region Constructors

        /**
           * Prepares to run the decision tree algorithm by
           * creating an empty decision tree.
           *
           * <p>
           * The default splitting function is set to &quot;Random&quot;.
           *
           * @param dataset A Dataset object that is already initialized.
           *
           * @throws NullPointerException If the supplied Dataset or
           *         ComponentManager is null.
           */
        public DecisionTreeAlgorithm(Dataset dataset)
        {
            //super();

            if (dataset == null)
                throw new Exception("Dataset is null.");

            //_manager = manager;

            DatasetUse = dataset;
            SplitFun = SPLIT_RANDOM;
            PruneAlg = PRUNING_NONE;
            RandomGenerator = new Random(2389);
            Tree = new DecisionTree();

            PessPruneZScore = DEFAULT_Z_SCORE;

            // Viết thêm

            ListRules = new DecisionTreeRule();
        }