Esempio n. 1
0
    IEnumerator LoadTrainingSet()
    {
        string path = ann.GetPath("trainingData");
        string line;

        if (File.Exists(path))
        {
            int          lineCount = File.ReadAllLines(path).Length;
            StreamReader tdf       = File.OpenText(path);

            List <double> calcOutputs = new List <double>();
            List <double> inputs      = new List <double>();
            List <double> outputs     = new List <double>();

            for (int i = 0; i < epochs; i++)
            {
                // set file pointer to beginning of file
                sse = 0;
                tdf.BaseStream.Position = 0;
                string currentWeights = ann.PrintWeights();
                while ((line = tdf.ReadLine()) != null)
                {
                    string[] data = line.Split(',');
                    // if nothing to be learned ignore this line
                    float thisError = 0;
                    if (System.Convert.ToDouble(data[5]) != 0 && System.Convert.ToDouble(data[6]) != 0)
                    {
                        inputs.Clear();
                        outputs.Clear();
                        inputs.Add(System.Convert.ToDouble(data[0]));
                        inputs.Add(System.Convert.ToDouble(data[1]));
                        inputs.Add(System.Convert.ToDouble(data[2]));
                        inputs.Add(System.Convert.ToDouble(data[3]));
                        inputs.Add(System.Convert.ToDouble(data[4]));

                        double out1 = Utils.Map(0, 1, -1, 1, System.Convert.ToSingle(data[5]));
                        double out2 = Utils.Map(0, 1, -1, 1, System.Convert.ToSingle(data[6]));
                        outputs.Add(out1);
                        outputs.Add(out2);

                        calcOutputs = ann.Train(inputs, outputs);
                        thisError   = ((Mathf.Pow((float)(outputs[0] - calcOutputs[0]), 2) +
                                        Mathf.Pow((float)(outputs[1] - calcOutputs[1]), 2))) / 2.0f;
                    }
                    sse += thisError;
                }
                trainingProgress = ((float)i / (float)epochs) * 100;
                sse /= lineCount;

                if (lastSSE < sse)   // if sse isnt better reload old one and decrease alpha
                {
                    ann.LoadWeights(currentWeights);
                    ann.alpha = Mathf.Clamp((float)ann.alpha - 0.001f, 0.01f, 0.9f);
                }
                else     // increase alpha
                {
                    ann.alpha = Mathf.Clamp((float)ann.alpha + 0.001f, 0.01f, 0.9f);
                    lastSSE   = sse;
                }
                yield return(null);
            }
            tdf.Close();
        }
        trainingDone = true;
        ann.SaveWeightsToFile();
    }