public MusicAnalyzer(List <string> contexts)
        {
            // _storedSongs = new double[MaxSongsAtOnce][];
            // _storedTypes = new int[MaxSongsAtOnce][];
            _allContexts = contexts;
            // _currentIndex = 0;

            // _network = new ActivationNetwork(new SigmoidFunction(), InputsSize, (int) ((InputsSize * (2.0/3.0)) + contexts.Count), (int)((InputsSize * (1.0 / 3.0)) + contexts.Count), contexts.Count);
            int sum = (InputsSize + contexts.Count);

            _network = new ActivationNetwork(new SigmoidFunction(), InputsSize, contexts.Count, contexts.Count);
            // _network = new ActivationNetwork(new SigmoidFunction(), InputsSize, contexts.Count * 3, contexts.Count, contexts.Count);
            _network.Randomize();

            _learning = new BackPropagationLearning(_network)
            {
                LearningRate = 0.2,
                Momentum     = 0.5
            };


            _standard = new Standardizer();

            // _learning = new ParallelResilientBackpropagationLearning(_network);

            // learning.RunEpoch()

            //_teacher = new MultilabelSupportVectorLearning<Linear>()
            //{
            //    Learner = (p) => new SequentialMinimalOptimization<Linear>()
            //    {
            //        Complexity = 100.0
            //    }
            //};
        }
Пример #2
0
        public Tuple <double, TimeSpan> Train(double[][] inputs, double[][] outputs)
        {
            Network = new ActivationNetwork(new BipolarSigmoidFunction(SigmoidAlphaValue), NeuronsInFirstLayer, NeuronsInHiddenLayer, 1);

            BackPropagationLearning teacher = new BackPropagationLearning(Network);

            teacher.LearningRate = LearningRate;

            Network.Randomize();

            var    sw       = Stopwatch.StartNew();
            double error    = double.PositiveInfinity;
            double previous = double.PositiveInfinity;

            for (int i = 1; i <= EpochCount; i++)
            {
                error = teacher.RunEpoch(inputs, outputs);

                if (error == 0 || previous < error)
                {
                    break;
                }

                previous = error;

                // Console.WriteLine(String.Format("Epoch={0} Error={1}", i, error));
            }

            sw.Stop();

            return(Tuple.Create(error, sw.Elapsed));
        }
        void TrainNetworkForWeight()
        {
            inputWeight = LoadFromFile("Ideal_Input_Weight.cfg");

            weightNetwork.Randomize();

            ResilientBackpropagationLearning learning = new ResilientBackpropagationLearning(weightNetwork);

            learning.LearningRate = 0.5;

            outputWeight = LoadFromFile("Ideal_Output_Weight.cfg");

            bool needToStop = false;
            int  iteration  = 0;

            while (!needToStop)
            {
                double error = learning.RunEpoch(inputWeight, outputWeight);

                if (error == 0)
                {
                    break;
                }
                else if (iteration < 50000)
                {
                    iteration++;
                }
                else
                {
                    needToStop = true;
                }
            }
        }
Пример #4
0
 private void button2_Click_1(object sender, EventArgs e)
 {
     button2.Enabled = false;
     network2        = null;
     reprop          = null;
     network2        = new ActivationNetwork(new BipolarSigmoidFunction(param1), 100, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 1);
     reprop          = new ResilientBackpropagationLearning(network3);
     network2.Randomize();
 }
Пример #5
0
 private void button3_Click_1(object sender, EventArgs e)
 {
     button3.Enabled = false;
     network1        = null;
     teacher         = null;
     network1        = new ActivationNetwork(new BipolarSigmoidFunction(param2), 100, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 1);
     teacher         = new BackPropagationLearning(network1);
     network1.Randomize();
 }
Пример #6
0
 private void button4_Click_1(object sender, EventArgs e)
 {
     button4.Enabled = false;
     network3        = null;
     evteacher       = null;
     network3        = new ActivationNetwork(new BipolarSigmoidFunction(param3), 100, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 1);
     evteacher       = new EvolutionaryLearning(network2, 100);
     network3.Randomize();
 }
Пример #7
0
 public NeuralNetwork(double[][] inputData, double[][] outputData)
 {
     _inputData  = inputData;
     _outputData = outputData;
     Network     = new ActivationNetwork(new SigmoidFunction(),
                                         inputData[0].Length,   // Input neuron count
                                         outputData[0].Length); // Output neuron count
     Network.Randomize();
 }
Пример #8
0
 public void Init()
 {
     an.Randomize();
     bp = new BackPropagationLearning(an);
     bp.LearningRate = 0.5;
     InfoControl.device.GetSportStatus += new DeviceDataManager.F2(device_GetSportStatus);
     InfoControl.device.GetGameControl += new DeviceDataManager.F8(device_GetGameControl);
     data.value = 0;
     InfoControl.device.SetDamp(data);
 }
Пример #9
0
        public async void Validate(int inputSize, int outputSize)
        {
            List <KFoldData> inputsList = new List <KFoldData>();

            for (double trainingweights = 0.01; trainingweights <= 1.6; trainingweights += 0.1)
            {
                for (int breadth = 10; breadth <= 1000; breadth += 50)
                {
                    for (int depth = 1; depth < 5; depth++)
                    {
                        inputsList.Add(new KFoldData(breadth, depth, trainingweights, 0, 0));
                    }
                }
            }

            var kFoldList = await Task.WhenAll(inputsList.Select(i => kfold(inputSize, outputSize, i.Breadth, i.Depth, i.TrainingSpeed)));

            KFoldData returnedKFoldData = new KFoldData(0, 0, 0, 0, double.MaxValue);

            KFoldData[] KFoldArray = kFoldList;
            foreach (var tempKFoldData in KFoldArray)
            {
                if (tempKFoldData.K < returnedKFoldData.K)
                {
                    returnedKFoldData = tempKFoldData;
                }
            }

            Console.WriteLine("Best value is:");
            Console.WriteLine("Depth: " + returnedKFoldData.Depth);
            Console.WriteLine("Breadth: " + returnedKFoldData.Breadth);
            Console.WriteLine("Training Speed: " + returnedKFoldData.TrainingSpeed);
            Console.WriteLine("Avg K Value: " + returnedKFoldData.K);

            int[] returnArray = new int[returnedKFoldData.Depth];
            for (int fillVal = 0; fillVal < returnedKFoldData.Depth; fillVal++)
            {
                if (fillVal == returnedKFoldData.Depth - 1)
                {
                    returnArray[fillVal] = outputSize;
                }
                else
                {
                    returnArray[fillVal] = returnedKFoldData.Breadth;
                }
            }

            topResults = returnedKFoldData;
            network    = new ActivationNetwork(new SigmoidFunction(), inputSize, returnArray);
            network.Randomize();
            Save();
            Console.WriteLine("Done!");
        }
Пример #10
0
        private void rANDOMIZEToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var c = MessageBox.Show("Warning Randomizing will erase memmory! Do you want to proceed?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

            if (c == System.Windows.Forms.DialogResult.Yes)
            {
                network1.Randomize();
                network2.Randomize();
                network3.Randomize();
                network4.Randomize();
                network5.Randomize();
            }
        }
Пример #11
0
        private static void TrainNetwork(LearningData learningData, String networkPath)
        {
            ActivationNetwork network = new ActivationNetwork(
                UseBipolar ? (IActivationFunction) new BipolarSigmoidFunction(1) : (IActivationFunction) new SigmoidFunction(),
                784,
                //784,
                10);

            network.Randomize();

            Int32 epochIndex = 0;

            //// create teacher
            PerceptronLearning teacher = new PerceptronLearning(network);            // new BackPropagationLearning(network);

            //PerceptronLearning teacher = new PerceptronLearning(network);// new BackPropagationLearning(network);

            teacher.LearningRate = 0.1f;
            ////teacher.Momentum = 0.5f;

            Double error = Double.MaxValue;

            Double previousError = Double.MaxValue;

            Int32 counter = 100;

            // loop
            while (counter > 0)
            {
                // run epoch of learning procedure
                error = teacher.RunEpoch(learningData.Input, learningData.Output);

                if (error > previousError)
                {
                    teacher.LearningRate = teacher.LearningRate * 0.5f;
                }

                Console.WriteLine(String.Format("{0} {1}", epochIndex, error));

                epochIndex++;

                previousError = error;

                counter--;
            }

            network.Save(networkPath);

            //Double[] output = network.Compute(learningData.Input[0]);
        }
Пример #12
0
        public NeuralNetwork()
        {
            network = new ActivationNetwork(
                new SigmoidFunction(1), //activation function
                170,                    //neurons in the input layer
                15,                     //neurons in the hidden layer
                10);                    //neurons in the output layer

            network.Randomize();
            teacher = new BackPropagationLearning(network);

            teacher.LearningRate = 0.5;
            teacher.Momentum     = 0.9;
        }
Пример #13
0
        public void Main()
        {
            WriteLine("Execution begins...");

            var fn   = @"c:\DEMO\Data\train.csv";
            var f    = File.ReadLines(fn);
            var data = from z in f.Skip(1)
                       let zz = z.Split(',').Select(int.Parse)
                                select new Digit
            {
                Label = zz.First(),
                Image = zz.Skip(1).ToArray()
            };
            var train = data.Take(10000).ToArray();
            var test  = data.Skip(10000).Take(1000).ToArray();

            var nn    = new ActivationNetwork(new SigmoidFunction(0.1), 784, 10);
            var learn = new BackPropagationLearning(nn);

            nn.Randomize();

            WriteLine("Starting learning");

            for (int ep = 0; ep < 150; ep++)
            {
                var err = learn.RunEpoch((from x in train select x.Image.Select(t => (double)t / 256.0).ToArray()).ToArray(),
                                         (from x in train select x.Label.ToOneHot10(10).ToDoubleArray()).ToArray());
                WriteLine($"Epoch={ep}, Error={err}");
            }

            int count = 0, correct = 0;

            foreach (var z in test)
            {
                var t = nn.Compute(z.Image.Select(tt => (double)tt / 256.0).ToArray());
                var n = t.MaxIndex();
                WriteLine("{0} => {1}", z, z.Label);
                if (n == z.Label)
                {
                    correct++;
                }
                count++;
            }

            WriteLine("Done, {0} of {1} correct ({2}%)", correct, count, (double)correct / (double)count * 100);
            ReadKey();
        }
Пример #14
0
        public Tuple <double, TimeSpan> Train()
        {
            if (SourceMatrix == null)
            {
                return(null);
            }

            List <int> listColumns = new List <int>();

            for (int i = 0; i < FeaturesAmount; i++)
            {
                listColumns.Add(i);
            }

            double[][] inputs  = SourceMatrix.GetColumns(listColumns.ToArray()).ToJagged();
            double[][] outputs = SourceMatrix.GetColumn(FeaturesAmount).Transpose().ToJagged();

            Network = new ActivationNetwork(new BipolarSigmoidFunction(SigmoidAlphaValue), NeuronsInFirstLayer, NeuronsInHiddenLayer, 1);

            BackPropagationLearning teacher = new BackPropagationLearning(Network);

            teacher.LearningRate = LearningRate;

            Network.Randomize();

            var    sw    = Stopwatch.StartNew();
            double error = double.PositiveInfinity;
            double previous;

            for (int i = 1; i <= EpochCount; i++)
            {
                previous = error;


                error = teacher.RunEpoch(inputs, outputs);

                if (error == 0)
                {
                    break;
                }

                //Console.WriteLine(String.Format("Epoch={0} Error={1}", i, error));
            }
            sw.Stop();

            return(Tuple.Create(error, sw.Elapsed));
        }
Пример #15
0
        public override void Train()
        {
            var(inputs, outputs) = GetTrainData();

            classifer = new ActivationNetwork(new SigmoidFunction(ALPHA), INPUTS_COUNT, 425, 181, 77, 33, 14, OUTPUTS_COUNT);
            BackPropagationLearning teacher = new BackPropagationLearning(classifer);

            classifer.Randomize();

            StringBuilder sb = new StringBuilder();

            for (int epoch = 0; epoch < 500; epoch++)
            {
                var err = teacher.RunEpoch(inputs.Select(r => r.Select(UseSigmoigFunc).ToArray()).ToArray(),
                                           outputs.Select(ConvertToBooleanVector).ToArray());
                sb.Append($"Epoch = {epoch}, Error = {err};");
            }
        }
Пример #16
0
        public Form1()
        {
            InitializeComponent();

            sampleStorage = new SampleStorage();
            sampleStorage.ReadFromFile("dataSet.txt");

            //  Network Params

            var alpha = 2;

            neuronNet = new ActivationNetwork(new SigmoidFunction(alpha), 8, 8, 1);
            neuronNet.Randomize();
            teacher = new BackPropagationLearning(neuronNet)
            {
                LearningRate = 1, Momentum = 0.1
            };
        }
Пример #17
0
        /* DANE WEJSCIOWE
         *
         * Dane odcinka wejsciowego skryżowania x 4     = 32
         * - idealny czas odcinka
         * - średni czas odcinka przez ostatnia godzine
         * - średni czas odcinka dla tej godziny poprzedniego dnia
         * - ilość pojazdów na odcinku
         * - średni czas odcinka dla tej godziny poprzedniego dnia
         * - czy coś na kierunku [0, 1] x 3     (lewo prosto prawo)
         *
         * Czas od zmiany na pozycje swiatel x 6
         *
         * Dane sasiadow x 4                = 48
         * - Dance odcinka wejsciowego x 4
         * - - idealny czas odcinka
         * - - średni czas odcinka przez ostatnia godzine
         * - - ilosc na odcinku
         *
         * RAZEM 86
         */
        public SterowanieSi()
        {
            zestawyUczace = new List <ZestawDanychSieci>();
            siecNeuronowa = new ActivationNetwork(
                new SigmoidFunction(),   // funkcja aktywacji
                WIELKOSC_WEJSCIE,        // wielkosc wejscia
                WIELKOSC_UKRYTE,         // wielkosc 1. warstwy ukrytej (kolejne po przecinku)
                WIELKOSC_WYJSCIE         // wielkoscy wyjscia
                );

            siecNeuronowa.Randomize();

            //nauczyciel = new BackPropagationLearning(siecNeuronowa);
            //nauczyciel.LearningRate = 0.1;

            ewolutor = new EvolutionaryLearning(siecNeuronowa, 100);

            UczenieWstepne();
        }
Пример #18
0
 public Form1()
 {
     InitializeComponent();
     timer1.Interval = 100;
     an.Randomize();
     bp = new BackPropagationLearning(an);
     bp.LearningRate = 0.5;
     if (device.OpenDevice(ref device.m_oBuzzDevice, 0x8888, 0x0006))
     {
     }
     else
     {
         MessageBox.Show("Error");
     }
     device.GetSportStatus += new DeviceDataManager.F2(device_GetSportStatus);
     device.GetGameControl += new DeviceDataManager.F8(device_GetGameControl);
     data.value             = 0;
     device.SetDamp(data);
 }
Пример #19
0
        public void CreateNetworkCustom(string activation, double coef, params int[] neuronCount)
        {
            this.activation = activation;
            network         = null;
            switch (activation)
            {
            case "Sigmoid":
                network = new ActivationNetwork(new SigmoidFunction(coef), inputSize, neuronCount);
                break;

            case "Tanh":
                network = new ActivationNetwork(new Tanh(coef), inputSize, neuronCount);
                break;

            case "ReLU":
                network = new ActivationNetwork(new ReLU(coef), inputSize, neuronCount);
                break;

            default:
                network         = new ActivationNetwork(new SigmoidFunction(0.4), inputSize, 30, outputSize);
                this.activation = "Sigmoid";
                break;
            }
            network.Randomize();
            foreach (var l in network.Layers)
            {
                foreach (var n in l.Neurons)
                {
                    for (int i = 0; i < n.Weights.Length; i++)
                    {
                        n.Weights[i] = rnd.NextDouble() * 2 - 1;
                    }
                }
            }

            teacher = new BackPropagationLearning(network);
            teacher.LearningRate = 1;
            teacher.Momentum     = 0.4;

            networkUpdated(this, activation);
        }
Пример #20
0
        private void ZnajdźPropagacja(List <List <Osoba> > listaOsób, int IlośćUczeń, out int[,] Mapa, Size WIelkość)
        {
            int L = 0;
            Dictionary <List <Osoba>, int> Dz = new Dictionary <List <Osoba>, int>();

            AForge.Neuro.Network Sieć = new ActivationNetwork(new SigmoidFunction(1), 2, 3, 3);
            Sieć.Randomize();
            AForge.Neuro.Learning.BackPropagationLearning br = new BackPropagationLearning((ActivationNetwork)Sieć);

            for (int i = 0; i < IlośćUczeń; i++)
            {
                int R = 0;
                foreach (var item in listaOsób)
                {
                    double[] ftp = new double[listaOsób.Count];
                    ftp[R] = 1;
                    R++;
                    foreach (var item2 in item)
                    {
                        br.Run(item2.TablicaUczącaD, ftp);
                    }
                }
            }

            int   Wn  = WIelkość.Width - 1;
            int   Hn  = WIelkość.Height - 1;
            float Skx = 1f / Wn;
            float Sky = 1f / Hn;

            Mapa = new int[WIelkość.Width, WIelkość.Height];
            for (int i = 0; i < WIelkość.Width; i++)
            {
                for (int j = 0; j < WIelkość.Height; j++)
                {
                    double[] t = new double[] { (Skx * i) - 0.5f, (Sky * j) - 0.5f };
                    Mapa[i, j] = SprawdźPewnośćSieci(Sieć.Compute(t));
                }
            }
        }
Пример #21
0
        public void Train(double[][] dataset, double[][] labels)
        {
            if (dataset.Length <= 0)
            {
                return;
            }

            net.Randomize();

            double error = 100;
            int    epoch = 0;
            int    len   = dataset.Length;

            while (error > 0.01 && epoch < Epochs)
            {
                error = backprop.RunEpoch(dataset, labels) / len;
                Debug.WriteLine("iteration = " + epoch.ToString());
                Debug.WriteLine("error = " + error.ToString());
                ++epoch;
            }
            net.Save("net1");
        }
        public void Train(int games)
        {
            ActivationNetwork       net     = new ActivationNetwork(new BipolarSigmoidFunction(), 9, 18, 9, 3, 1);
            BackPropagationLearning teacher = new BackPropagationLearning(net);

            net.Randomize();

            teacher.LearningRate = 0.025;

            for (int i = 0; i < games; i++)
            {
                var        trainingGame = PlayTrainingGame(net, i % 2 == 0, i % 3 == 0);
                double[][] inputs       = trainingGame.Item1;
                double[][] outputs      = trainingGame.Item2;
                for (int j = 0; j < inputs.Length; j++)
                {
                    teacher.Run(inputs[j], outputs[j]);
                }
            }

            Model = new Model(net);
        }
Пример #23
0
        //todo: loss, optimizer(use different backprop), metrics
        public void CreateNetwork()
        {
            //инициализация сети и процесса обучения с backpropagation'ом
            network = new ActivationNetwork(new SigmoidFunction(0.4), inputSize, 30, outputSize);
            //рандомизирование весов
            network.Randomize(); //?
            foreach (var l in network.Layers)
            {
                foreach (var n in l.Neurons)
                {
                    for (int i = 0; i < n.Weights.Length; i++)
                    {
                        n.Weights[i] = rnd.NextDouble() * 2 - 1;
                    }
                }
            }

            teacher = new BackPropagationLearning(network);
            teacher.LearningRate = 1;
            teacher.Momentum     = 0.4;

            networkUpdated(this, "Sigmoid");
        }
Пример #24
0
    // Use this for initialization
    void InitNetwork(double[] data)
    {
        network = CreateNetwork();
        network.Randomize();
        GenomSize = CalculateNetworkSize(network);
        if (GenomSize != data.Length)
        {
            Debug.LogError("data has wrong length");
            return;
        }
        int index = 0;

        foreach (var l in network.Layers)
        {
            foreach (var n in l.Neurons)
            {
                for (int i = 0; i < n.Weights.Length; i++)
                {
                    n.Weights[i] = data[index];
                    index++;
                }
            }
        }
    }
Пример #25
0
        static void Main(string[] args)
        {
            double learningRate      = 0.1;
            double momentum          = 0.0;
            double sigmoidAlphaValue = 1.0;

            // two hidden layers and one output layer
            int[] neuronsInFirstLayer = new int[] { 2, 2, 1 };

            // prepare learning data
            double[][] input  = new double[4][];
            double[][] output = new double[4][];

            input[0]    = new double[2];
            input[0][0] = 0.0;
            input[0][1] = 0.0;
            input[1]    = new double[2];
            input[1][0] = 1.0;
            input[1][1] = 0.0;
            input[2]    = new double[2];
            input[2][0] = 0.0;
            input[2][1] = 1.0;
            input[3]    = new double[2];
            input[3][0] = 1.0;
            input[3][1] = 1.0;

            output[0]    = new double[1];
            output[0][0] = 0.0;
            output[1]    = new double[1];
            output[1][0] = 0.0;
            output[2]    = new double[1];
            output[2][0] = 0.0;
            output[3]    = new double[1];
            output[3][0] = 1.0;

            // create multi-layer neural network
            ActivationNetwork network = new ActivationNetwork(new BipolarSigmoidFunction(sigmoidAlphaValue), 2, neuronsInFirstLayer);


            // create teacher
            BackPropagationLearning teacher = new BackPropagationLearning(network);

            // set learning rate and momentum
            teacher.LearningRate = learningRate;
            teacher.Momentum     = momentum;

            network.Randomize();

            // loop
            int i = 0;

            while (i < 100000)
            {
                // run epoch of learning procedure
                double error = teacher.RunEpoch(input, output) / 4;
                i++;
            }

            Console.WriteLine("Value Input (0, 0): " + network.Compute(new double[2] {
                0.0, 0.0
            })[0].ToString());
            Console.WriteLine("Value Input (0, 1): " + network.Compute(new double[2] {
                0.0, 1.0
            })[0].ToString());
            Console.WriteLine("Value Input (1, 0): " + network.Compute(new double[2] {
                1.0, 0.0
            })[0].ToString());
            Console.WriteLine("Value Input (1, 1): " + network.Compute(new double[2] {
                1.0, 1.0
            })[0].ToString());

            JObject json = new JObject();

            json = network.GetJson();

            Console.ReadLine();

            File.WriteAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\neuralnet.conf", JsonHelpers.Serialize(json));
        }
Пример #26
0
        private void button2_Click(object sender, EventArgs e)
        {
            List <WynikNeuroneowej> wk = new List <WynikNeuroneowej>();
            Random r = new Random();
            int    Najlepsza = 0;
            int    Długość = 0, IlośćPetli = 0;
            double WSPUczenia = 0, WspPendu = 0, Bias = 0;
            float  OstatniaPróbaUcząca, UczeniePopranego; try

            {
                Pobierz(out Długość, out IlośćPetli, out WSPUczenia, out WspPendu, out Bias, out OstatniaPróbaUcząca, out UczeniePopranego);
            }
            catch (Exception)
            {
                MessageBox.Show("źle wpisane dane");
                return;
            }
            Maks = Convert.ToInt32(textBox6.Text);
            listBox1.Items.Clear();
            t = new Thread(new ThreadStart(() =>
            {
                for (int i = 0; i < IlośćPetli; i++)
                {
                    ActivationNetwork network = null;
                    if (DomyślnaSiec == null)
                    {
                        network = KontrukcjaSieci(Bias);

                        Neuron.RandRange = new AForge.Range(-1, 1);
                        network.Randomize();
                    }
                    else
                    {
                        network = DomyślnaSiec;
                    }
                    BackPropagationLearning teacher = new BackPropagationLearning(network);
                    teacher.Momentum = WspPendu;

                    for (int j = 0; j < Długość; j++)
                    {
                        float Współczynik    = ((float)(Długość - j)) / Długość;
                        teacher.LearningRate = WSPUczenia * Współczynik + OstatniaPróbaUcząca;
                        TabelaUcząca rt      = ZbiórUczący[r.Next(ZbiórUczący.Count)];
                        double[] UczWyjście  = (double[])rt.Wyjście.Clone();
                        int p = 0;
                        bool CzyPoprawny;
                        while (p++ < Maks)
                        {
                            CzyPoprawny = (Loto.Matematyka.ZnajdźMaksymalną(network.Compute(rt.Wejście)) == rt.Nr);
                            if (!CzyPoprawny)
                            {
                                teacher.Run(rt.Wejście, rt.Wyjście);
                            }
                            else if (UczPoprawne)
                            {
                                teacher.LearningRate = UczeniePopranego * WSPUczenia;
                                teacher.Run(rt.Wejście, rt.Wyjście);
                                break;
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    int IlośćPoprawnych = 0;
                    double Odhylenie    = 0;
                    StreamWriter sw     = null;
                    if (checkBox2.Checked)
                    {
                        sw = new StreamWriter(new FileStream($"zap{i}.txt", FileMode.Create));
                    }
                    foreach (var item in ZbiórUczący)
                    {
                        double[] tb = network.Compute(item.Wejście);
                        Odhylenie  += OdchylenieStadardowe(tb, item.Wyjście);
                        if (Loto.Matematyka.ZnajdźMaksymalną(tb) == item.Nr)
                        {
                            IlośćPoprawnych++;
                        }
                        foreach (var item2 in ListaNajlepszych(tb))
                        {
                            sw?.Write(item2);
                            sw?.Write('\t');
                        }
                        sw?.WriteLine(item.Nazwa);
                    }
                    sw?.Close();
                    Odhylenie /= ZbiórUczący.Count;
                    if (Najlepsza < IlośćPoprawnych)
                    {
                        network.Save("siec.tv");
                        Najlepsza = IlośćPoprawnych;
                        Console.WriteLine(IlośćPoprawnych);
                    }

                    wk.Add(new WynikNeuroneowej()
                    {
                        błąd = Odhylenie, Poprawne = IlośćPoprawnych
                    });
                    listBox1.Invoke(new TR(() => { listBox1.Items.Add(IlośćPoprawnych.ToString() + " odchylenie stadardowe " + Odhylenie); }));
                }
                this.Invoke(new TR(() => { this.Text = WynikNeuroneowej.Drukuj(wk); }));
            }));
            t.Start();
        }
Пример #27
0
 public NeuralNetworkController()
 {
     network = new ActivationNetwork(new SigmoidFunction(), 5, 4, 3);
     network.Randomize();
     teacher = new LevenbergMarquardtLearning(network);
 }
Пример #28
0
 public override void Reset()
 {
     status.Reset();
     activationNetwork.Randomize();
 }
 private void button4_Click_1(object sender, EventArgs e)
 {
     button4.Enabled = false;
     network3 = null;
     evteacher = null;
     network3 = new ActivationNetwork(new BipolarSigmoidFunction(param3), 100, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 1);
     evteacher = new EvolutionaryLearning(network2, 100);
     network3.Randomize();
 }
Пример #30
0
        public void Init()
        {
            var dataset = CreateDataSet();
            int counter = 0;

            needToStop = false;
            // initialize input and output values
            double[][] input  = new double[dataSetArrayCount][];
            double[][] output = new double[dataSetArrayCount][];

            for (int i = 0; i < dataset.Count; i++)
            {
                input[i]    = new double[6];
                input[i][0] = dataset[i].Erytrocyt;
                input[i][1] = dataset[i].Fibrinogen;
                input[i][2] = dataset[i].Hemocyt;
                input[i][3] = dataset[i].Leukocyt;
                input[i][4] = dataset[i].Protrombin;
                input[i][5] = dataset[i].Trombocyt;

                output[i]    = new double[2];
                output[i][0] = dataset[i].Result1;
                output[i][1] = dataset[i].Result2;
            }



            SigmoidFunction sigmoidFunction = new SigmoidFunction(5);
            // create neural network
            ActivationNetwork network = new ActivationNetwork(
                sigmoidFunction,
                6,  // two inputs in the network
                5,  // two neurons in the first layer
                2); // one neuron in the second layer

            // create teacher

            network.Randomize();
            BackPropagationLearning teacher =
                new BackPropagationLearning(network);

            teacher.LearningRate = 5;
            // loop
            while (!needToStop)
            {
                // run epoch of learning procedure
                double error = teacher.RunEpoch(input, output);
                // check error value to see if we need to stop
                // ...

                counter++;
                if (counter == 2000)
                {
                    Console.WriteLine(error);
                    counter = 0;
                }
                //if (error < 200)
                if (error < 0.05)
                {
                    needToStop = true;
                }
            }

            BloodDonatonNeuralNet bloodDonatonNeuralNet = new BloodDonatonNeuralNet();

            bloodDonatonNeuralNet.NeuralNetwork = network;

            AssetManager assets = this.Assets;
            IFormatter   formatter;

            using (MemoryStream stream = new MemoryStream())
            {
                formatter = new BinaryFormatter();
                formatter.Serialize(stream, bloodDonatonNeuralNet);

                var FullFilePath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), filename);

                stream.Seek(0, SeekOrigin.Begin);

                using (FileStream fs = new FileStream(FullFilePath, FileMode.OpenOrCreate))
                {
                    stream.CopyTo(fs);
                    fs.Flush();
                }
            }
        }
Пример #31
0
        public static void RunXOR(string[] args)
        {
            string            path       = Environment.CurrentDirectory + @"\XORNetwork.txt";
            ActivationNetwork XORNetwork = new ActivationNetwork(new SigmoidFunction(1), 2, 2, 1);

            Console.WriteLine(path);
            int[] trainingSet = new int[8] {
                0, 0, 0, 1, 1, 0, 1, 1
            };
            int[] trainingAnswers = new int[4] {
                0, 1, 1, 0
            };

Start:
            Console.WriteLine("What would you like to do?");
            switch (Console.ReadLine().ToLower())
            {
            case ("train"):
                BackPropagationLearning teacher = new BackPropagationLearning(XORNetwork);
                while (true)
                {
                    int iter = 0;
                    for (iter = 0; iter < 100000000; iter++)
                    {
                        for (int i = 0; i < 4; i++)
                        {
                            //Console.WriteLine(Convert.ToString(trainingSet[i * 2]) + " " + Convert.ToString(trainingSet[i * 2 + 1]));
                            //Console.WriteLine(Convert.ToString(teacher.Run(new double[2] { trainingSet[i * 2], trainingSet[i * 2 + 1] }, new double[1] { trainingAnswers[i] })));
                            teacher.Run(new double[2] {
                                trainingSet[i * 2], trainingSet[i * 2 + 1]
                            }, new double[1] {
                                trainingAnswers[i]
                            });
                        }
                        //Console.WriteLine(iter.ToString());
                    }
                    //if (Console.ReadLine() == "stop")
                    //{
                    Console.WriteLine("Done");
                    XORNetwork.Save(path);
                    goto Start;
                    //}
                }

            case ("read"):
                Network network;
                if (File.Exists(path))
                {
                    network = Network.Load(path);
                }
                else
                {
                    network = XORNetwork;
                }

                for (int i = 0; i < 4; i++)
                {
                    Console.WriteLine(Convert.ToString(trainingSet[i * 2]) + " " + Convert.ToString(trainingSet[i * 2 + 1]));
                    Console.WriteLine(network.Compute((new double[2] {
                        trainingSet[i * 2], trainingSet[i * 2 + 1]
                    }))[0].ToString());
                    Console.WriteLine(Math.Round(network.Compute((new double[2] {
                        trainingSet[i * 2], trainingSet[i * 2 + 1]
                    }))[0]).ToString());
                }

                /*double[] userValues = new double[2];
                 * userValues[0] = Convert.ToDouble(Console.ReadLine());
                 * userValues[1] = Convert.ToDouble(Console.Read());
                 * Console.WriteLine(XORNetwork.Compute(userValues)[0].ToString());*/
                break;

            case "randomize":
                XORNetwork.Randomize();
                XORNetwork.Save(path);
                Console.WriteLine("done");
                break;

            case "status":
                break;
            }
            goto Start;
        }
 private void button3_Click_1(object sender, EventArgs e)
 {
     button3.Enabled = false;
     network1 = null;
     teacher = null;
     network1 = new ActivationNetwork(new BipolarSigmoidFunction(param2), 100, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 1);
     teacher = new BackPropagationLearning(network1);
     network1.Randomize();
 }
 private void button2_Click_1(object sender, EventArgs e)
 {
     button2.Enabled = false;
     network2 = null;
     reprop = null;
     network2 = new ActivationNetwork(new BipolarSigmoidFunction(param1), 100, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 1);
     reprop = new ResilientBackpropagationLearning(network3);
     network2.Randomize();
 }