Page 1 of 1

C# Wrapper Beispiel

Posted: Wed 4. Apr 2018, 22:46
by ThomasN
Hallo,

es gibt ja ein gutes Beispiel zum Erstellen eines Netzes in C# als Download. Allerdings fehlt darin ein Beispiel, wie man das Netz innerhalb von C# trainiert. Da ich nun eine ganze Weile benötigt habe, das herauszufinden, möchte ich hier einen Beispielcode veröffentlichen, um es späteren Nutzern zu erleichtern:

Code: Select all

using MemBrainLib;
using System;

namespace NeuralNets.Examples
{
    /// <summary>
    /// A sample code for working with neural nets.
    /// The net has two output and two input neurons.
    /// The task is, that it gets two equal input values and outputs these same values    /// 
    /// </summary>
    public static class MemBrainSampleCode
    {
        /// <summary>
        /// Start the sample code which shows how to
        /// - load a net
        /// - create a lesson
        /// - train the net
        /// - save the trained net
        /// - query the net
        /// </summary>
        public static void StartTrainingSample()
        {
            // load and prepare the net
            NeuralNet net = new NeuralNet();
            net.Load(@"d:\test.mbn"); // load a net with two input neurons and two output neurons, to fit the patterns below
            net.Randomize();

            // create a training lesson
            Lesson lesson = CreateLesson(net);

            // teach the net
            TeachWithLesson(net, lesson);

            // save the trained net
            net.SaveAs(@"d:\test_trained.mbn");

            // query the net
            double[] inputs = new double[] { 0.6d, 0.6d };
            double[] outputs = Calculate(net, inputs);

            // write the result
            Console.WriteLine(string.Join("; ", outputs));
        }

        /// <summary>
        /// Teaches a net wit a lesson
        /// </summary>
        /// <param name="net">The net to teach</param>
        /// <param name="lesson">The lesson to teach</param>
        public static void TeachWithLesson(NeuralNet net, Lesson lesson)
        {
            // teach 50 times
            for (int i = 0; i < 50; i++)
            {
                Console.WriteLine(net.TeachStep().ToString());
                Console.WriteLine(net.GetLastNetError());
            }
        }

        /// <summary>
        /// Creates a lesson for the given net
        /// </summary>
        /// <param name="net">The net from which to take names and count of input/output neurons</param>
        /// <returns>The lesson with the patterns</returns>
        public static Lesson CreateLesson(NeuralNet net)
        {
            // initialize the lesson with the correct net size
            Lesson lesson = new Lesson();

            // adjust the input nodes (count and names)
            lesson.SetInputCount(net.GetInputCount());
            for (int i = 0; i < net.GetInputCount(); i++)
                lesson.SetInputName(i, net.GetInputName(i));

            // adjust the output nodes (count and names)
            lesson.SetOutputCount(net.GetOutputCount());
            for (int i = 0; i < net.GetOutputCount(); i++)
                lesson.SetOutputName(i, net.GetOutputName(i));

            // import the patterns, if you don't want to add them here programatically
            // lesson.ImportRaw(@"d:\lesson.csv");

            // add 10 patterns
            // in this example, for each pattern, all the input nodes and output nodes should have the same value
            for (int i=0; i<10; i++)
            {
                double val = 0.1d * i;
                lesson.AddPattern();
                lesson.SelectPattern(i);
                lesson.SetPatternInput(0, val);
                lesson.SetPatternInput(1, val);
                lesson.SetPatternOutput(0, val);
                lesson.SetPatternOutput(1, val);
            }

            // if you want to export the patterns (for loading into membrain)
            // lesson.ExportRaw(@"d:\lesson.csv", 4);

            // return the created lesson
            return lesson;
        }

        /// <summary>
        /// Lets the neural net think about input values and return the values of the output nodes
        /// </summary>
        /// <param name="net">The net which will think</param>
        /// <param name="inputs">The values for the input nodes</param>
        /// <returns>The values of the output nodes</returns>
        public static double[] Calculate(NeuralNet net, double[] inputs)
        {
            // set input
            for (int i = 0; i < inputs.Length; i++)
                net.ApplyInputAct(i, inputs[i]);

            // think
            net.ThinkStep();

            // get output
            double[] outputs = new double[net.GetOutputCount()];
            for (int i = 0; i < outputs.Length; i++)
            {
                double result;
                net.GetOutputOut(i, out result);
                outputs[i] = result;
            }

            // return the output
            return outputs;
        }
    }
}