Exemplo n.º 1
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);
        }
Exemplo n.º 2
0
        public void Run()
        {
            int counter = 0;

            Parallel.ForEach(Items, file =>
                 {
                     for (int nn = 1; nn < NeuronNumber; nn++)//neuron number
                     {
                         for (int i = 0; i < RepeatForEachFile; i++)//learning tests for file with x neurons in network
                         {
                             try
                             {
                                 NBN nbn = new NBN(nn, file);
                                 var result = nbn.Run(1);

                                 DateTime d = DateTime.Now;
                                 History h = new History();
                                 h.Name = String.Format("{0}_{1}_{2}_{3}_{4}_{5}_{6}_{7}", Path.GetFileNameWithoutExtension(result.Filename),
                                     d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second, d.Millisecond);
                                 h.Data = marekbar.Xml.Serialize<LearnResult>(result);
                                 h.Insert();

                                 if (PDF)
                                 {
                                     try
                                     {
                                         string filename = Common.Folder.Data + "\\" + h.Name + ".pdf";

                                         PDFGenerate data = new PDFGenerate();
                                         data.Filename = filename;
                                         data.Result = result;
                                         data.ChartFilename = GeneratePlot(result.RMSE[0], Path.GetFileNameWithoutExtension(result.Filename));
                                         HistoryPDF pdf = new HistoryPDF(data.Result, data.ChartFilename, true);
                                         pdf.Save(data.Filename);
                                     }
                                     catch
                                     { //don't care about it
                                     }
                                 }
                             }
                             catch (Exception ex)
                             {
                                 ex.GetError();
                             }
                             finally
                             {
                                 counter++;
                                 if (OnUpdate != null)
                                 {
                                     OnUpdate(counter);
                                 }
                             }
                         }
                     }
                 });
        }
Exemplo n.º 3
0
        private void saveToPdfSimple(bool flag)
        {
            try
            {
                String filename = Common.Dialog.Save(LearnByError.Internazional.Resource.Inst.Get("r68"), "pdf");
                if (filename != "" && result != null)
                {
                    String chartFilename = Common.Folder.Data + "\\" +
                                DateTime.Now.ToString().Replace(':', '_').Replace(' ', '_').Replace('-', '_') + ".bmp";
                    chart.SaveImage(chartFilename, System.Drawing.Imaging.ImageFormat.Bmp);

                    PDFGenerate tmp = new PDFGenerate();
                    tmp.Filename = filename;
                    tmp.Result = result;
                    tmp.ChartFilename = chartFilename;

                    var bw = new System.ComponentModel.BackgroundWorker();
                    bw.DoWork += (a, b) =>
                    {
                        var data = (PDFGenerate)b.Argument;
                        HistoryPDF pdf = new HistoryPDF(data.Result, data.ChartFilename, flag);

                        if (pdf.Save(data.Filename))
                        {
                            pdf.Open();

                            b.Result = LearnByError.Internazional.Resource.Inst.Get("r69") + data.Filename;
                        }
                        else
                        {
                            b.Result = LearnByError.Internazional.Resource.Inst.Get("r70");
                        }
                    };
                    bw.RunWorkerCompleted += (a, b) =>
                    {
                        status.Text = (String)b.Result;
                        progress.Visible = false;
                    };
                    progress.Visible = true;
                    bw.RunWorkerAsync(tmp);
                }
            }
            catch (Exception ex)
            {
                ex.ToLog();
                status.Text = ex.Message;
            }
        }
Exemplo n.º 4
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;
        }