コード例 #1
0
        static void Main(string[] args)
        {
            // AND Gate
            // Or Gate
            // Nand Gate
            // Xor (will be big no possible)

            Perceptron orGate   = new Perceptron(2);
            Perceptron andGate  = new Perceptron(2);
            Perceptron nandGate = new Perceptron(2);


            double[][] inputs =
            {
                new double[] { 0, 0 },
                new double[] { 0, 1 },
                new double[] { 1, 0 },
                new double[] { 1, 1 }
            };

            double[] outputs = { 0, 1, 1, 0 };

            trainPerceptron(orGate, inputs, new double[] { 0, 1, 1, 1 });
            trainPerceptron(andGate, inputs, new double[] { 0, 0, 0, 1 });
            trainPerceptron(nandGate, inputs, new double[] { 1, 1, 1, 0 });
            Console.ReadKey();
        }
コード例 #2
0
        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            // ESTABLECE LOS RECTANGULOS
            var pic = this.pictureBox1;

            DestRect = new RectangleF(0f, 0f, (float)pic.Width, (float)pic.Height);
            OrigRect = new RectangleF(-(float)pic.Width / 2 / 10, (float)pic.Height / 2 / 10, (float)pic.Width / 10, -(float)pic.Height / 10);

            var ptron = new Perceptron(3);
            int salida;

            var linea    = new Line2D(-3, -7);
            var trainers = new List <Trainer>();
            var rnd      = new Random(DateTime.Now.Millisecond);
            int i;

            for (i = 0; i < TOTAL_TRAINERS; i++)
            {
                var inputs = new double[] { rnd.NextDouble() *(Math.Abs(OrigRect.Width)) - (Math.Abs(OrigRect.Width) / 2), rnd.NextDouble() * (Math.Abs(OrigRect.Height)) - (Math.Abs(OrigRect.Height) / 2), 1 };
                int answer = linea.evaluatePoint(inputs[0], inputs[1]);
                trainers.Add(new Trainer(inputs, answer));
            }
            bmp = new Bitmap(pic.Width, pic.Height);

            Graphics g;
            Pen      pen1 = new System.Drawing.Pen(Color.Black, 2F);

            g = Graphics.FromImage(bmp);

            // DIBUJA LOS EJES
            g.DrawLine(pen1, pic.Width / 2, 0, pic.Width / 2, pic.Height);
            g.DrawLine(pen1, 0, pic.Height / 2, pic.Width, pic.Height / 2);

            // DIBUJA LA RECTA
            Pen pen2 = new System.Drawing.Pen(Color.Blue, 2F);

            DrawLine2D(linea, g, pen2);

            DrawTrainers(trainers, ptron, g);
            backgroundWorker1.ReportProgress(0);
            System.Threading.Thread.Sleep(100);

            i = 0;
            int j;

            for (j = 0; j < TRAIN_PASSES; j++)
            {
                foreach (var tr in trainers)
                {
                    i++;
                    ptron.entrenar(tr);
                    if (i % 10 == 0)
                    {
                        DrawTrainers(trainers, ptron, g);
                        backgroundWorker1.ReportProgress(i);
                    }
                }
            }
            g.Dispose();
        }
コード例 #3
0
        static void trainPerceptron(Perceptron perceptron, double[][] inputs, double[] outputs)
        {
            double mae   = 0;
            int    epoch = 0;

            do
            {
                for (int i = 0; i < inputs.Length; i++)
                {
                    perceptron.Train(inputs[i], outputs[i], .5);
                }

                Console.SetCursorPosition(0, 0);

                mae = 0;
                for (int i = 0; i < inputs.Length; i++)
                {
                    mae += Math.Abs(outputs[i] - perceptron.Compute(inputs[i]));
                    Console.WriteLine($"{inputs[i][0]},{inputs[i][1]}:{outputs[i]} -> {perceptron.Output}");
                }
                mae /= inputs.Length;


                epoch++;
                Console.WriteLine($"Error: {mae:0.00}\nEpoch: {epoch}");
            } while (mae > 0);
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: DanoRysJan/ia_draw_ito
        public void peticionsalida(Perceptron p, double valoresX, double id)
        {
            while (true)
            {
                double[] val = new double[numentradas];

                /*for (int j = 0; j < fila.Length; j++)
                 * {
                 *  filadatos = fila[j].Split(';');
                 *  for (int h = 0; h < filadatos.Length; h++)
                 *  {
                 *      if (h < numentradas)
                 *      {
                 *          val[h] = Normalizar(double.Parse(filadatos[j]), minentrada, maxentr);
                 *      }
                 *  }
                 * }*/
                //double[] val = new double[numentradas];

                /*for (int i = 0; i < numentradas; i++)
                 * {
                 *  //Console.WriteLine("inserta valor: " + i + ": ");
                 *  //val[i] = Normalizar(double.Parse(Console.ReadLine()), minentrada, maxentr);
                 *  //val[i] = Normalizar(double.Parse(fila[i]), minentrada, maxentr);
                 * }*/
                val[0] = Normalizar(valoresX, minentrada, maxentr);
                val[1] = Normalizar(id, minentrada, maxentr);
                double[] sal = p.activacion(val);
                for (int i = 0; i < numsalidas; i++)
                {
                    Console.WriteLine("respuesta " + i + ": " + desnormalizado(sal[i], minsal, maxsal) + " ");
                }
                Console.WriteLine("");
            }
        }
コード例 #5
0
 private void DrawTrainers(List <Trainer> trainers, Perceptron ptron, Graphics g)
 {
     foreach (var tr in trainers)
     {
         DrawTrainer(tr, ptron, g);
     }
 }
コード例 #6
0
        static void Main(string[] args)
        {
            double[]   outputs = new double[] { 1, 1, 1, 1 };
            double[][] inputs  = new double[4][] {
                new double[] { 1, 0 },
                new double[] { 0, 1 },
                new double[] { 1, 2 },
                new double[] { 0, 3 }
            };
            double[] weights = new double[inputs[0].Length];

            Console.Write("Initial Weights: ");
            foreach (double weight in weights)
            {
                Console.Write(weight + " ");
            }
            Console.WriteLine();

            Perceptron perceptron = new Perceptron();

            perceptron.Inputs  = inputs;
            perceptron.Outputs = outputs;
            perceptron.Weights = weights;
            perceptron.Train();

            Console.ReadKey(true);
        }
コード例 #7
0
 public WindowRecognition(Perceptron p)
 {
     red = p;
     InitializeComponent();
     Training.Checked  = true;
     guessDraw.Visible = false;
     drawList();
 }
コード例 #8
0
        public double[] Output => Perceptrons.Select(n => n.Output).ToArray(); //Linq expressions help with basic selections

        /// <summary>
        /// Constructs a Layer object
        /// </summary>
        /// <param name="activation">the activation function to be set in all neurons of the constructed layer</param>
        /// <param name="inputCount">the number of inputs of the layer</param>
        /// <param name="neuronCount">the number of neurons in the layer</param>
        public Layer(Func <double, double> activation, int inputCount, int neuronCount)
        {
            Perceptrons = new Perceptron[neuronCount];
            for (int i = 0; i < Perceptrons.Length; i++)
            {
                Perceptrons[i] = new Perceptron(activation, inputCount);
            }
        }
コード例 #9
0
        public Form1()
        {
            InitializeComponent();
            inputArea.ColumnCount = Constants.CELL_SIZE;
            inputArea.RowCount    = Constants.CELL_SIZE;

            p = new Perceptron();
            txtExpectedOutput.Text = Constants.LETTERS[currentLetter].ToString();
        }
コード例 #10
0
 private void Form1_Shown(object sender, EventArgs e)
 {
     Perceptron = new Perceptron();
     Graphics   = this.CreateGraphics();
     Grid.setGrphcs(Graphics);
     Grid.clearGrid();
     Grid.drawGridOnly();
     //grphcs.DrawRectangle(myPen, 0, 0, 400, 400);
 }
コード例 #11
0
        private void createPerceptronToolStripMenuItem_Click(object sender, EventArgs e)
        {
            parametersSeter.ShowDialog();
            if (parametersSeter.ok_presed)
            {
                var parameters = parametersSeter.parameters;
                sensor_field_size = new Size(parameters.sinaps_field_width, parameters.sinaps_field_height);
                uint[] Neuron_layers_sizes = new uint[1 + parameters.hidden_layers_count + 1];
                Neuron_layers_sizes[0] = (uint)(parameters.sinaps_field_width * parameters.sinaps_field_height);
                for (int _i = 1; _i <= parameters.hidden_layers_count; _i++)
                {
                    Neuron_layers_sizes[_i] = (uint)parameters.hidden_layer_size;
                }
                Neuron_layers_sizes[parameters.hidden_layers_count + 1] = (uint)study_set.Count();
                perceptron = new Perceptron(Neuron_layers_sizes);

                perceptron_studied_leters = new char[study_set.Count];
                int paterns_count = 0;
                foreach (var pair in study_set)
                {
                    paterns_count += pair.Value.Count;
                }
                Perceptron.Patern[] paterns = new Perceptron.Patern[paterns_count];
                int i            = 0;
                int leter_number = 0;
                foreach (var pair in study_set)
                {
                    double[] outputs = new double[study_set.Count];
                    outputs[leter_number] = 1;
                    perceptron_studied_leters[leter_number] = pair.Key;
                    leter_number++;
                    foreach (Bitmap bmp in pair.Value)
                    {
                        bool[,] sensor_field = get_sensor_field(bmp, sensor_field_size);
                        if (sensor_field != null)
                        {
                            Perceptron.Patern patern = new Perceptron.Patern();
                            patern.inputs = new double[Neuron_layers_sizes[0]];
                            int j = 0;
                            foreach (bool obj in sensor_field)
                            {
                                patern.inputs[j++] = obj ? 1 : 0;
                            }
                            patern.outputs = outputs;
                            paterns[i]     = patern;
                        }
                        i++;
                    }
                }
                perceptron.study(paterns, parameters.eps);

                cleanToolStripMenuItem.Enabled = true;
                drawen();

                MessageBox.Show("Perceptron created for " + perceptron.Epoch + " Epochs\n\rwith eps = " + parameters.eps);
            }
        }
コード例 #12
0
        static void Main(string[] args)
        {
            Perceptron p1 = new Perceptron();

            p1.Run();

            Console.WriteLine("Press any key");
            Console.ReadLine();
        }
コード例 #13
0
        private void RecognizeBtn_Click(object sender, EventArgs e)
        {
            Grid.moveTheDrawedToCorner();
            Grid.scaletheDrawed();
            TeachBtn.Enabled = true;
            var hypothesis = Perceptron.Recognize() ? Perceptron.Category2 : Perceptron.Category1;

            label1.Text    = "Я думаю, это " + hypothesis + ".";
            label1.Visible = true;
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: DanoRysJan/DrawITO
        public static Perceptron valorPerceptron()
        {
            Perceptron p;


            if (!cargarred)
            {
                leerDatos();
                p = new Perceptron(new int[] { entrada[0].Length, 8, 8, salida[0].Length });
                while (!p.aprender(entrada, salida, 0.05, 0.1, 5000000))
                {
                    p = new Perceptron(new int[] { entrada[0].Length, 8, 8, salida[0].Length });
                }
                if (guardarred)
                {
                    FileStream      fs        = new FileStream(rutaneurona, FileMode.Create);
                    BinaryFormatter formatter = new BinaryFormatter();
                    try
                    {
                        formatter.Serialize(fs, p);
                    }
                    catch (SerializationException e)
                    {
                        Console.WriteLine("Fallo la serializacion: " + e.Message);
                        throw;
                    }
                    finally
                    {
                        fs.Close();
                    }
                }
            }
            else
            {
                FileStream fs = new FileStream(rutaneurona, FileMode.Open);
                try
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    p = (Perceptron)formatter.Deserialize(fs);
                }
                catch (SerializationException e)
                {
                    Console.WriteLine("fallo: " + e);
                    throw;
                }
                finally
                {
                    fs.Close();
                }
            }

            //peticionsalida(p);
            // evaluar(p, 0, 5, 0.1);
            return(p);
        }
コード例 #15
0
        private void button2_Click_1(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            string filename = saveFileDialog1.FileName;

            System.IO.File.WriteAllText(filename, Perceptron.SaveWeight());
            MessageBox.Show("Файл сохранен");
        }
コード例 #16
0
 private void LoadPerceptronMenuItem_Click(object sender, EventArgs e)
 {
     if (openFileDialog2.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         PerceptronData data = JsonConvert.DeserializeObject <PerceptronData>(System.IO.File.ReadAllText(openFileDialog2.FileName));
         perceptron = Perceptron.FromString(data.perceptron_str);
         perceptron_studied_leters = data.perceptron_studied_leters;
         sensor_field_size         = data.sensor_field_size;
         drawen();
     }
 }
コード例 #17
0
ファイル: Program.cs プロジェクト: alexey-aristov/Algorithms
        private static void CreateSinusPerceptron()
        {
            List <Tuple <decimal, decimal> > samples = new List <Tuple <decimal, decimal> >()
            {
                new Tuple <decimal, decimal>(0.1m, (decimal)Math.Sin(0.1)),
                new Tuple <decimal, decimal>(0.2m, (decimal)Math.Sin(0.2)),
                //new Tuple<decimal, decimal>(0.3m, (decimal) Math.Sin(0.3)),
                //new Tuple<decimal, decimal>(0.4m, (decimal) Math.Sin(0.4)),
                //new Tuple<decimal, decimal>(0.5m, (decimal) Math.Sin(0.5)),
                //new Tuple<decimal, decimal>(0.6m, (decimal) Math.Sin(0.6)),
                //new Tuple<decimal, decimal>(0.7m, (decimal) Math.Sin(0.7)),
            };
            List <Tuple <decimal, decimal> > tests = new List <Tuple <decimal, decimal> >()
            {
                new Tuple <decimal, decimal>(0.1m, (decimal)Math.Sin(0.1)),
                new Tuple <decimal, decimal>(0.2m, (decimal)Math.Sin(0.2)),
                new Tuple <decimal, decimal>(0.3m, (decimal)Math.Sin(0.3)),
                new Tuple <decimal, decimal>(0.4m, (decimal)Math.Sin(0.4)),
                new Tuple <decimal, decimal>(0.5m, (decimal)Math.Sin(0.5)),
                new Tuple <decimal, decimal>(0.6m, (decimal)Math.Sin(0.6)),
                new Tuple <decimal, decimal>(0.7m, (decimal)Math.Sin(0.7)),
            };
            Perceptron p     = new Perceptron(new[] { 1, 2, 5, 10, 7, 1 }, 0.1m);
            decimal    delta = 0.000001m;

            decimal[] @out;
            decimal[] errors;

            for (int i = 0; i < 50000; i++)
            {
                foreach (var sample in samples)
                {
                    @out   = p.EvaluateInput(new[] { sample.Item1 });
                    errors = new[] { GetError(sample.Item2, @out[0]) };
                    p.Calculate(errors);
                    p.AdjustWeights();
                }
            }


            foreach (var test in tests)
            {
                var result = p.EvaluateInput(new[] { test.Item1 });
                if (Math.Abs(result[0] - test.Item2) > delta)
                {
                    Console.WriteLine("Faled test, expeceted{0},was {1}", test.Item2, result[0]);
                }
                else
                {
                    Console.WriteLine("Success test");
                }
            }
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: DanoRysJan/DrawITO
        static void evaluar(Perceptron p, double inicio, double fin, double salto)
        {
            string salida = "";

            for (double i = inicio; i < fin; i += salto)
            {
                double res = p.activacion(new double[] { Normalizar(i, minentrada, maxentr) })[0];
                salida += i + ";" + desnormalizado(res, minsal, maxsal) + "\n";
                Console.WriteLine(i + ";" + res + "\n");
            }
            System.IO.File.WriteAllText(rutasalida, salida);
        }
コード例 #19
0
        static void Main()
        {
            // Cria um Perceptron com 2 entradas e 4 padrões
            Perceptron p = new Perceptron(2, 4);

            // Treinamento AND
            int[,] padroes = { { 0, 0 },
                               { 0, 1 },
                               { 1, 0 },
                               { 1, 1 } };

            int[] yDesejado_AND = { 0,
                                    0,
                                    0,
                                    1 };

            double taxaDeAprendizado = 0.2;

            p.treinar(padroes, yDesejado_AND, taxaDeAprendizado, "Treinamento AND");

            // Treinamento OR
            int[] yDesejado_OR = { 0,
                                   1,
                                   1,
                                   1 };

            p.treinar(padroes, yDesejado_OR, taxaDeAprendizado, "Treinamento OR");

            // Treinamento A ou T

            /*int[,] padroes_A_T = {  {   1, 1, 1, 1, 1,
             *                          1, 0, 0, 0, 1,
             *                          1, 1, 1, 1, 1,
             *                          1, 0, 0, 0, 1,
             *                          1, 0, 0, 0, 1},
             *
             *                      {   1, 1, 1, 1, 1,
             *                          0, 0, 1, 0, 0,
             *                          0, 0, 1, 0, 0,
             *                          0, 0, 1, 0, 0,
             *                          0, 0, 1, 0, 0 }};
             *
             * int[] yDesejado_A_T = { 0,
             *                      1 };
             *
             * p.treinar(padroes_A_T, yDesejado_A_T, taxaDeAprendizado, "Treinamento T ou A");*/

            while (Console.ReadKey().Key != ConsoleKey.Enter)
            {
            }
        }
コード例 #20
0
        private void button3_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            // получаем выбранный файл
            string filename = openFileDialog1.FileName;

            // читаем файл в строку
            string[] w = System.IO.File.ReadAllText(filename).Split(' ');
            Perceptron.DownloadWeight(System.IO.File.ReadAllText(filename).Split(' '));
            MessageBox.Show("Файл открыт");
        }
コード例 #21
0
        static int TrainPerceptron(int[][] desiredValues, ref Perceptron perry)
        {
            int[][] result =
            {
                new[] { 0, 0, 0 },
                new[] { 0, 1, 0 },
                new[] { 1, 0, 0 },
                new[] { 1, 1, 0 }
            };

            int  totalIterations = 0;
            int  i;
            bool eq1, eq2, eq3, eq4;

            while (true)
            {
                TrainModel(desiredValues, ref perry);
                totalIterations++;
                //Console.WriteLine();

                i = 0;
                foreach (var val in desiredValues)
                {
                    //  Console.WriteLine($"{val[0]}|{val[1]}|{perry.Evaluate(val[0], val[1])}");
                    //construct result
                    var tmp = new int[] { val[0], val[1], perry.Evaluate(val[0], val[1]) };
                    result[i] = tmp;
                    i++;
                }

                eq1 = desiredValues[0][2] == result[0][2];
                eq2 = desiredValues[1][2] == result[1][2];
                eq3 = desiredValues[2][2] == result[2][2];
                eq4 = desiredValues[3][2] == result[3][2];


                if (eq1 && eq2 && eq3 && eq4)
                {
                    break;
                }

                if (totalIterations >= 1023)
                {
                    throw new Exception("Probably impossible to complete!");
                }
            }

            return(totalIterations);
        }
コード例 #22
0
ファイル: FormMain.cs プロジェクト: morphx666/Perceptron
        private void Init()
        {
            lock (syncObj) {
                brain  = new Perceptron(r, 3, learningRate); // Increase the learning rate to increase how fast the algorithm... "learns"
                points = new DataPoint[pointsCount];         // Increase the number of points to increase accuracy

                for (int i = 0; i < points.Length; i++)
                {
                    points[i] = new DataPoint(r, this.DisplayRectangle.Width, this.DisplayRectangle.Height);
                }

                startTime = DateTime.Now;
                iCounter  = 0;
                isDone    = false;
            }
        }
コード例 #23
0
        void Starter(int maxPerceptronInstancesneurons, float perceptronLearningRate)
        {
            SC_anglesQuarterNumber = SC_anglesNumber * SC_Angle_Divider;
            saveCurrentWeightForTheCurrentAngleInsideOfUnitsOf360 = new float[SC_anglesQuarterNumber][];

            random = new System.Random();
            perc   = new Perceptron.Perceptron(maxPerceptronInstancesneurons, perceptronLearningRate);

            //perceptronLearningRate = sc_maths.getSomeRandNumThousandDecimal();

            for (int i = 0; i < saveCurrentWeightForTheCurrentAngleInsideOfUnitsOf360.Length; i++)
            {
                weights = perc.GetWeights();
                saveCurrentWeightForTheCurrentAngleInsideOfUnitsOf360[i] = weights;
            }
        }
コード例 #24
0
        public static double GetAdalineError(Perceptron perceptron)
        {
            if (!perceptron.IsAdaline)
            {
                return(Double.NaN);
            }

            double errorSum = 0;

            foreach (var trainObject in andTraingData.Shuffle())
            {
                errorSum += Math.Pow(perceptron.Train(trainObject), 2);
            }

            errorSum /= andTraingData.Count;
            return(errorSum);
        }
コード例 #25
0
        static void TrainModel(int[][] desiredValues, ref Perceptron perry)
        {
            int weight1, weight2, threshold;
            //var iteration = 0;
            Random rand = new Random();

            foreach (var value in desiredValues)
            {
                while (perry.Evaluate(value[0], value[1]) != value[2])
                {
                    weight1   = rand.Next(-10, 10);
                    weight2   = rand.Next(-10, 10);
                    threshold = rand.Next(-10, 10);
                    perry.AdjustWeights(weight1, weight2, threshold);
                    //iteration++;
                }
            }
        }
コード例 #26
0
        /// <summary>
        /// Constructor for Perceptron </summary>
        /// <param name="label"> Label of Perceptron </param>
        /// <param name="alpha"> Learning Rate </param>
        /// <returns>
        /// Returns Initialized Perceptron </returns>
        private static Perceptron SetupPerceptron(int label, double alpha)
        {
            var p = new Perceptron
            {
                Label   = label,
                Alpha   = alpha,
                Weights = new double[785]
            };

            for (var i = 0; i < p.Weights.Length; i++)
            {
                var r = new Random();
                //p.Weights[i] = 10 * r.NextDouble();
                p.Weights[i] = RandomGaussian();
            }

            p.Weights[784] = 0.0;

            return(p);
        }
コード例 #27
0
        static void Main(string[] args)
        {
            Khepera khepera = new Khepera("192.168.8.115", 2543);

            var fancy = new FancyLedThread(ref khepera);
            //fancy.Start();

            var motor1Perry = new Perceptron.Perceptron(-2, 2, -1);
            var motor2Perry = new Perceptron.Perceptron(8, -5, -3);


            //khepera.Commands.Motors.SetMotors(100,2940);

            while (true)
            {
                //Console.WriteLine($"Swapped motors! {DateTime.Now}");
                var ttl = DateTime.Now.Millisecond;
                var ir  = khepera.Commands.Infrared.GetProximity();


                var infraRight1 = ir.GroundFrontRight <= 500 ? 1 : 0;
                var infraLeft1  = ir.GroundFrontLeft <= 500 ? 1 : 0;
                // int infraRight2 = ir.GroundFrontRight <= 300 ? 1 : 0;
                // int infraLeft2 = ir.GroundFrontLeft <= 300 ? 1 : 0;

                int motorRightSpeed = motor2Perry.Evaluate(infraLeft1, infraRight1) == 1 ? 100 : 0;
                int motorLeftSpeed  = motor1Perry.Evaluate(infraLeft1, infraRight1) == 1 ? 100 : 0;
                //motorRightSpeed = motor2Perry.Evaluate(infraLeft2, infraRight2) == 1 ? 100 : 20;
                //motorLeftSpeed = motor1Perry.Evaluate(infraLeft2, infraRight2) == 1 ? 100 : 20;

                khepera.Commands.Motors.SetMotors(motorLeftSpeed, motorRightSpeed);
                Console.WriteLine($"LOOP TIME: {DateTime.Now.Millisecond - ttl}ms");
                //Thread.Sleep(20);
            }

            /*var proximity = khepera.Commands.Infrared.GetProximity();
             * var ambient = khepera.Commands.Infrared.GetAmbient();
             * var leds = khepera.Commands.Leds.Get();
             */
            Console.WriteLine();
        }
コード例 #28
0
ファイル: Program.cs プロジェクト: alexey-aristov/Algorithms
        private static void SimpleTest()
        {
            Perceptron p    = new Perceptron(new[] { 1, 3, 2, 2 }, 1);
            var        @out = p.EvaluateInput(new[] { 1m });

            decimal[] expected = new[] { 0.05m, 0.01m };
            var       errors   = new[] { GetError(expected[0], @out[0]), GetError(expected[1], @out[1]) };

            p.AdjustWeights();
            decimal delta = 0.000001m;
            int     i     = 0;

            while (Math.Abs(errors[0]) > delta || Math.Abs(errors[1]) > delta)
            {
                i++;
                @out   = p.EvaluateInput(new[] { 1m });
                errors = new[] { GetError(expected[0], @out[0]), GetError(expected[1], @out[1]) };
                p.Calculate(errors);
                p.AdjustWeights();
            }
        }
コード例 #29
0
ファイル: Program.cs プロジェクト: glimadev/perceptron
        static void Main(string[] args)
        {
            double[,] inputs =
            {
                { 1d, 1d, 1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 1d },
                { 0d, 0d, 0d, 0d, 1d, 1d, 1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 1d },
                { 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 1d },
                { 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 1d },
                { 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 1d },
                { 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 1d, 0d, 0d, 0d, 0d, 0d, 1d },
                { 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d, 1d },
                { 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 1d },
                { 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 1d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 1d, 0d, 1d, 1d }
            };

            double[] outputs = { 1d, 0d, 0d, 1d, 0d, 1d, 0d, 1d, 1d };

            Console.WriteLine(inputs.Length);

            //Fit data
            Perceptron perceptron = new Perceptron(inputs, outputs);
            int        epoch      = perceptron.Fit();

            Console.WriteLine(epoch);

            double[] data = { 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 1d, 0d, 0d, 1d, 0d, 1d, 1d };
            int      r    = perceptron.Predict(data);

            Console.WriteLine(r);

            double[] data2 = { 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 1d };
            int      r2    = perceptron.Predict(data2);

            Console.WriteLine(r2);

            Console.ReadLine();
        }
コード例 #30
0
ファイル: Program.cs プロジェクト: TalpalaruBogdan/Perceptron
        static void Main(string[] args)
        {
            Perceptron neuNet = new Perceptron(6);

            Data[] datas = new Data[4];
            datas[0]        = new Data(3);
            datas[1]        = new Data(3);
            datas[2]        = new Data(3);
            datas[3]        = new Data(3);
            datas[0].inputs = new double[] { 1, 0, 1 };
            datas[0].output = 1;
            datas[1].inputs = new double[] { 0, 0, 1 };
            datas[1].output = 0;
            datas[2].inputs = new double[] { 1, 1, 0 };
            datas[2].output = 1;
            datas[3].inputs = new double[] { 0, 0, 0 };
            datas[3].output = 0;

            Data testData = new Data(3);

            testData.inputs = new double[] { 0, 0, 0 };
            neuNet.Train(10000, datas);
            neuNet.Evaluate(testData);
        }
コード例 #31
0
ファイル: mainForm.cs プロジェクト: eXetrum/Perceptron
        private void btnLearn_Click(object sender, EventArgs e)
        {
            perceptron = new Perceptron(sensorCount, associativeCount, reactionCount);
            // Задаем метод логгер
            Perceptron.log = new Perceptron.Log(logBox.AppendText);

            learningSet.Enabled = false;
            learningType.Enabled = false;

            List<Perceptron.PairSet> images = new List<Perceptron.PairSet>();
            for (int img = 0; img < gui.Length; ++img)
            {
                images.Add(new Perceptron.PairSet()
                {
                    image = gui[img].GetImage(),
                    t = ResultKeys[img]
                });
            }

            if (alphaLearningChoice.Checked)
            {
                if (MessageBox.Show("Начать обучение альфа подкреплением ?", "Запуск обучения", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    perceptron.Learn(images, true);
                    currentImgSet = inputNameSet.Checked ? 0 : 1;
                    currentLearningType = 0;
                }
            }
            else
            {
                if (MessageBox.Show("Начать обучение гамма подкреплением ?", "Запуск обучения", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    perceptron.Learn(images, false);
                    currentImgSet = inputNameSet.Checked ? 0 : 1;
                    currentLearningType = 1;
                }
            }

            learningSet.Enabled = true;
            learningType.Enabled = true;
            btnRecognize.Enabled = true;
        }
コード例 #32
0
        static void Main(string[] args)
        {
            #region Création
            Console.WriteLine("Création du Perceptron");
            //Perceptron perceptron = new Perceptron(FonctionsTransfert.Escalier, 0, Colonnes * Lignes);
            //Perceptron perceptron = new Perceptron(FonctionsTransfert.Signe, 0, Colonnes * Lignes);
            Perceptron perceptron = new Perceptron(FonctionsTransfert.Sigmoide, 0.5, Colonnes * Lignes);
            Console.WriteLine("Nombre de neurones: {0}", perceptron.Couches[0].Neurones.Length);
            Console.WriteLine("Biais initial: {0}", perceptron.Couches[0].Neurones[0].Biais);
            Console.WriteLine();
            #endregion

            // Lettre pour laquelle le réseau est entraîné
            string lettreTest = "B";

            #region obtient le jeu d'entrainement
            Dictionary<string, double[]> entrainement = ChargerAlphabet();
            //Dictionary<string, int[]> entrainement = ChargerLettre(lettreTest);
            // affiche ce qui a été chargé
            foreach (string lettre in entrainement.Keys)
            {
                Afficher(entrainement[lettre]);
            }
            #endregion

            #region Entraînement
            int maxIteration = 100;
            double pas = 0.05;
            Console.WriteLine("Après entraînement");
            Console.WriteLine("Pas d'apprentissage: {0}, nombre max d'itégrations: {1}", pas, maxIteration);
            // on entraîne le réseau pour reconnaître la lettre B
            double[] erreur = perceptron.Entrainer(entrainement, lettreTest, maxIteration, pas, 0.05);
            Console.WriteLine("Erreur: {0}", erreur[0]);
            Console.WriteLine("Biais: {0}", perceptron.Couches[0].Neurones[0].Biais);
            Console.WriteLine("Poids synaptiques");

            Neurone neurone = perceptron.Couches[0].Neurones[0];
            for (int l = 0; l < Lignes; l++)
            {
                for (int c = 0; c < Colonnes; c++)
                {
                    Console.Write(neurone.Poids[c + l * Colonnes].ToString("+0.000;-0.000") + " ");
                }
                Console.WriteLine();
            }
            Console.WriteLine();
            #endregion

            while (true)
            {
                Console.WriteLine("Test du réseau");
                // On construit des jeux d'essai avec un bruit de plus en plus important

                for (int entropie = 0; entropie < 50; entropie++)
                {
                    double[] vecteur = new double[Lignes * Colonnes];
                    Array.Copy(entrainement[lettreTest], vecteur, vecteur.Length);

                    double[] test = Degrader(vecteur, entropie);
                    bool prediction = perceptron.Predire(test);

                    Afficher(test);
                    Console.WriteLine("Entropie: {0}", entropie);
                    Console.WriteLine("Reconnu?: {0}", prediction);
                    Console.WriteLine();

                    if (!prediction)
                    {
                        break;
                    }
                }

                Console.WriteLine("Recommencer? (O/N)");
                string ligne = Console.ReadLine();
                if (ligne == "N" || ligne == "n")
                {
                    break;
                }

                Console.Clear();
            }

            Console.WriteLine("Terminé!");
        }
コード例 #33
0
ファイル: perceptronLogisticWorking.cs プロジェクト: sicTa/NN
        static void Main(string[] args)
        {
            Random r = new Random();
            TrainingSeq[] s = new TrainingSeq[1000];
            for (int i = 0; i < 1000; i++)
            {
                int x = r.Next(0, 10);
                int y = r.Next(0, 10);
                while (y == x) y = r.Next(0, 10);
                int rez;
                if (x > y) rez = 1; else rez = 0;
                s[i] = new TrainingSeq(x, y, rez);
            }
            Perceptron p = new Perceptron();
            p.uci2(1, 100, s);
            Console.WriteLine("Tezina w1: " + p.w1);
            Console.WriteLine("Tezina w1: " + p.w2);
            Console.WriteLine("Pritisnite bilo koje dugme");
            Console.ReadLine();
            int brojac = 0;
            for (int i = 0; i < 100; i++)
            {
                int x = r.Next(0, 10);
                int y = r.Next(0, 10);
                while (y == x) y = r.Next(0, 100);
                int control;
                if (x > y) control = 1; else control = 0;
                int vecemanje = p.rezultat(x, y);
                if (control == vecemanje)
                    brojac++;
                Console.WriteLine("X: {0}   Y: {1}  X>Y: {2}", x, y, vecemanje);
            }

            Console.WriteLine("Procentualno pogodjeno: " + brojac + "%");

            Console.ReadLine();
        }