Пример #1
0
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="result">LearnResult - learning result</param>
        /// <param name="chartFilename">string - char filename</param>
        /// <param name="includeDataTable">bool - true id learning data should be included</param>
        public HistoryPDF(LearnByErrorLibrary.LearnResult result, String chartFilename, bool includeDataTable = false)
        {
            this.result        = result;
            this.chartFilename = chartFilename;

            document               = new Document();
            document.Info.Title    = "NBN C# - wynik uczenia sieci neuronowej";
            document.Info.Subject  = "Uczenie sieci neuronowej za pomocą algorytmu NBN C#";
            document.Info.Author   = "Marek Bar 33808";
            document.Info.Comment  = "...ponieważ tylko dobry kod się liczy.";
            document.Info.Keywords = "C#, NBN, neuron, uczenie, sieć, nbn c#";

            DefineStyles(document);
            DefineCover(document);
            DefineInfo(document, result);
            DefineChartArea(document, chartFilename, Path.GetFileNameWithoutExtension(result.Filename));
            DefineWeightsSection(document, result);

            if (includeDataTable)
            {
                MatrixMB mat = MatrixMB.Load(result.Filename);
                AddMatrixTable(document, mat);
            }

            Section section = document.LastSection;

            section.AddPageBreak();//index of pages
            Paragraph paragraph = section.AddParagraph("Spis treści");

            paragraph.Format.Font.Size    = 14;
            paragraph.Format.Font.Bold    = true;
            paragraph.Format.SpaceAfter   = 24;
            paragraph.Format.OutlineLevel = OutlineLevel.Level1;

            paragraph       = section.AddParagraph();
            paragraph.Style = "TOC";

            //first link
            Hyperlink hyperlink = paragraph.AddHyperlink("Informacje na temat sieci neuronowej");

            hyperlink.AddText("\r\n" + "Informacje na temat sieci neuronowej" + "\t");
            hyperlink.AddPageRefField("Informacje na temat sieci neuronowej");

            hyperlink = paragraph.AddHyperlink("Wykres przebiegu uczenia");
            hyperlink.AddText("\r\n" + "Wykres przebiegu uczenia" + "\t");
            hyperlink.AddPageRefField("Wykres przebiegu uczenia");

            hyperlink = paragraph.AddHyperlink("Wagi otrzymane w procesie uczenia");
            hyperlink.AddText("\r\n" + "Wagi otrzymane w procesie uczenia" + "\t");
            hyperlink.AddPageRefField("Wagi otrzymane w procesie uczenia");
            if (includeDataTable)
            {
                hyperlink = paragraph.AddHyperlink("Dane wejściowe");
                hyperlink.AddText("\r\n" + "Dane wejściowe" + "\t");
                hyperlink.AddPageRefField("Dane wejściowe");
            }
        }
Пример #2
0
        /// <summary>
        /// Run NBN training and its test - this is the first version
        /// </summary>
        /// <param name="trials">int - number of learning trials</param>
        /// <returns>LearnResult</returns>R
        private LearnResult RunFirstVersion(int trials)
        {
            backupSettings               = new NeuralNetworkSettings();
            backupSettings.MaxError      = settings.MaxError;
            backupSettings.MaxIterations = settings.MaxIterations;
            backupSettings.MU            = settings.MU;
            backupSettings.MUH           = settings.MUH;
            backupSettings.MUL           = settings.MUL;
            backupSettings.Scale         = settings.Scale;

            Trials = trials;
            LearnResult result = new LearnResult();

            result.Filename = Filename;
            if (MatLabCompareDataFolder.Length > 0)
            {
                result.Filename = string.Format("{0}\\{1}.dat", MatLabCompareDataFolder, Path.GetFileNameWithoutExtension(Directory.GetFiles(MatLabCompareDataFolder, "*.dat")[0]));
            }

            if (!loadInputData(Filename))
            {
                updateErrorNBN("Dane nie zostały wczytane.");
                return(result);
            }
            if (OnDebug != null)
            {
                debug("Data loaded from file: " + Filename);
            }

            var tmp = new System.Collections.Generic.List <int>();

            tmp.Add(inputLearn.Cols);

            //setting number of hidden neurons
            for (int i = 0; i < Handle; i++)
            {
                tmp.Add(1);
            }
            tmp.Add(1);

            var vh = new VectorHorizontal(tmp.Count);

            for (int i = 0; i < vh.Length; i++)
            {
                vh[i] = tmp[i];
            }

            switch (NBN_Topography)
            {
            case 0:
            {
                topo = Topography.Generate(TopographyType.BMLP, vh);
            } break;

            case 1:
            {
                topo = Topography.Generate(TopographyType.MLP, vh);
            } break;
            }



            result.Topo = topo.Data[0];
            if (OnDebug != null)
            {
                debug(topo.ToString());
            }

            if (topo == null)
            {
                updateErrorNBN("Topologia sieci nie została utworzona.");
                return(result);
            }

            info = this.checkInputs(ref inputLearn, ref outputLearn, ref topo, out indexes);//here are set indexes

            result.TopoIndex = indexes.Data[0];
            result.Info      = info;
            if (OnDebug != null)
            {
                debug(indexes.ToString());
                debug(info.ToString());
            }

            Activation act = new Activation(info.nn);

            act.FillWithNumber(NBN_Activation);
            act.setValue(info.nn - 1, 0);
            result.ActivationFunction = act.Data[0];

            Gain gain = new Gain(info.nn);

            gain.FillWithNumber(NBN_Gain);
            result.GainValue = gain.Data[0];

            result.Settings = this.settings;

            for (trial = 0; trial < trials; trial++)
            {
                Weights initialWeights = new Weights(info.nw);
                if (MatLabCompareDataFolder.Length > 0)
                {
                    initialWeights = MatrixMB.Load(string.Format("{0}\\poczatkowe_wagi_proba_{1}.txt", MatLabCompareDataFolder, trial + 1)).ToWeights();
                }
                else
                {
                    initialWeights = Weights.Generate(info.nw);
                }

                if (IsResearchMode)
                {
                    string initialWeightsFile = String.Format("{0}\\{1}{2}_initial_weights.dat", _reasearch_folder, trial, Path.GetFileNameWithoutExtension(result.Filename));
                    initialWeights.Store(initialWeightsFile);
                }

                initialWeights.Name = "Initial";
                if (OnDebug != null)
                {
                    debug(String.Format("\r\nTrial {0} from {1}\r\n", trial + 1, trials));
                    debug(initialWeights.ToString());
                }

                settings               = null;
                settings               = NeuralNetworkSettings.Default();
                settings.MaxError      = backupSettings.MaxError;
                settings.MaxIterations = backupSettings.MaxIterations;
                settings.MU            = backupSettings.MU;
                settings.MUH           = backupSettings.MUH;
                settings.MUL           = backupSettings.MUL;
                settings.Scale         = backupSettings.Scale;

                I = MatrixMB.Eye(info.nw);

                tic();//learn time measure start
                var tr = Train(ref this.settings, ref this.info, ref this.inputLearn, ref this.outputLearn,
                               ref this.topo, initialWeights, ref act, ref gain, ref indexes);

                String LearnExecutionTime = toc(); //learn time measure stop
                LearnTimeList = time.ElapsedTicks; //learn time measure save

                result.Add(tr.weights.Data[0], SSE.ToDoubleArray(), RMSE.ToDoubleArray());

                result.LearnRMSE = (double)RMSE[RMSE.Count];
                LearnRmseList    = LastRMSE;

                if (OnDebug != null)
                {
                    debug(tr.weights.ToString());
                    debug("\r\nLearn execution time: " + LearnExecutionTime + "(hours:minutes:seconds:miliseconds)\r\n");
                    debug("\r\nLearn SSE: " + tr.sse.ToString() + "\r\n");
                    debug("\r\nLearn RMSE: " + result.LearnRMSE.ToString() + "\r\n");
                }

                updateError(result.LearnRMSE);

                NetworkInfo infoTest = info.Copy();
                infoTest.np = inputTest.Rows;

                tic();

                error.CalculateError(ref infoTest, ref inputTest, ref outputTest, ref topo, tr.weights, ref act, ref gain, ref indexes);

                var TestExecutionTime = toc();
                TestTimeList = time.ElapsedTicks;

                result.TestRMSE = Math.Sqrt(error.Error / infoTest.np);
                TestRmseList    = result.TestRMSE;
                result.TestingRmseList.Add(result.TestRMSE);
                if (OnDebug != null)
                {
                    debug("\r\nTest execution time: " + TestExecutionTime + "(hours:minutes:seconds:miliseconds)\r\n");
                    debug("\r\nTest SSE: " + error.Error.ToString() + "\r\n");
                    debug("\r\nTest RMSE: " + result.TestRMSE.ToString() + "\r\n");
                }

                //if (result.LearnRMSE < Threshold) IsTrainOK++;
                if (result.SSE[trial][result.SSE[trial].Length - 1] < Threshold)
                {
                    IsTrainOK++;
                }
            }

            result.LearnRMSE = AverageLearnRMSE;
            result.TestRMSE  = AverageTestRMSE;

            result.setStatisticsData(LearnRMSE, TestRMSE, LearnTime, TestTime, Trials);
            result.SuccessRate = (double)IsTrainOK / Trials;

            if (IsResearchMode)//save research
            {
                try
                {
                    string filename = extractionFolder + "\\research result.pdf";

                    PDFGenerate data = new PDFGenerate();
                    data.Filename      = filename;
                    data.Result        = result;
                    data.ChartFilename = GeneratePlot(result.RMSE, Path.GetFileNameWithoutExtension(result.Filename));
                    HistoryPDF pdf = new HistoryPDF(data.Result, data.ChartFilename, true);
                    pdf.Save(data.Filename);
                }
                catch { }
            }

            return(result);
        }
Пример #3
0
        /// <summary>
        /// Initialize NBN with data from specified file
        /// </summary>
        /// <param name="filename">String - filename</param>
        /// <returns>bool - success flag</returns>
        private bool loadInputData(String filename)
        {
            try
            {
                if (!File.Exists(filename))
                {
                    throw new NeuralNetworkError(String.Format(Properties.Settings.Default.NBN1, filename));
                }

                try
                {
                    var data = MatrixMB.Load(filename);

                    if (MatLabCompareDataFolder.Length > 0)
                    {
                        //data from matlab are normalized
                        string name = Path.GetFileNameWithoutExtension(Directory.GetFiles(MatLabCompareDataFolder, "*.dat")[0]);
                        inputLearn  = MatrixMB.Load(string.Format("{0}\\uczenie_wejscie_{1}.txt", MatLabCompareDataFolder, name)).ToInput();
                        inputTest   = MatrixMB.Load(string.Format("{0}\\testowanie_wejscie_{1}.txt", MatLabCompareDataFolder, name)).ToInput();
                        outputLearn = MatrixMB.Load(string.Format("{0}\\uczenie_wyjscie_{1}.txt", MatLabCompareDataFolder, name)).ToOutput();
                        outputTest  = MatrixMB.Load(string.Format("{0}\\testowanie_wyjscie_{1}.txt", MatLabCompareDataFolder, name)).ToOutput();
                    }
                    else
                    {
                        input = data.CopyColumnsWithoutLast().ToInput();
                        input.Normalize();

                        output = data.LastColumn.ToOutput();
                        output.Normalize();

                        if (IsClassification)
                        {
                            int Tnp = data.Rows;
                            inputLearn  = input.CopyRows(Tnp - 1).ToInput();
                            inputTest   = input.CopyRows(Tnp - 1).ToInput();
                            outputLearn = output.CopyRows(Tnp - 1).ToOutput();
                            outputTest  = output.CopyRows(Tnp - 1).ToOutput();
                        }
                        else
                        {
                            int[] ind = data.Rows.RandomPermutation();
                            int   Tnp = Math.Round(data.Rows * 0.7).ToInt();

                            inputTest   = input.CopyRows(Tnp, input.Rows - 1).ToInput();
                            inputLearn  = input.CopyRows(Tnp - 1).ToInput();
                            outputTest  = output.CopyRows(Tnp, input.Rows - 1).ToOutput();
                            outputLearn = output.CopyRows(Tnp - 1).ToOutput();
                        }
                    }
                    try
                    {
                        if (IsResearchMode)//export for matlab - out of use
                        {
                            string   name = Path.GetFileNameWithoutExtension(filename);
                            DateTime d    = DateTime.Now;

                            string dir = String.Format("{0}\\Executed research\\{1}\\{2}_{3}_{4}_{5}_{6}_{7}",
                                                       Path.GetDirectoryName(filename), name,
                                                       d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second);

                            if (!Directory.Exists(dir))
                            {
                                Directory.CreateDirectory(dir);
                            }

                            extractionFolder  = dir;
                            _reasearch_folder = dir;
                            string learn_input     = String.Format("{0}\\{1}_learn_input.dat", dir, name);
                            string test_input      = String.Format("{0}\\{1}_test_input.dat", dir, name);
                            string learn_output    = String.Format("{0}\\{1}_learn_output.dat", dir, name);
                            string test_output     = String.Format("{0}\\{1}_test_output.dat", dir, name);
                            string initialWweights = String.Format("{0}\\{1}_initial_weights.dat", dir, name);

                            inputTest.Store(test_input);
                            inputLearn.Store(learn_input);
                            outputTest.Store(test_output);
                            outputLearn.Store(learn_output);
                        }
                    }
                    catch (Exception)
                    { }
                }
                catch (Exception iex)
                {
                    throw new NeuralNetworkError(String.Format(Properties.Settings.Default.NBN2, filename), iex);
                }
                return(true);
            }
            catch (Exception ex)
            {
                updateErrorNBN(ex);
                return(false);
            }
        }