Esempio n. 1
0
 /// <summary>
 /// Score the model for regression or classification.
 /// For classification, the score is the percentage correct.
 /// For regression, the score is mean square error (MSE).
 /// http://www.heatonresearch.com/wiki/Mean_Square_Error
 /// </summary>
 /// <param name="model">The model to score.</param>
 /// <param name="testSubject">The test subject.</param>
 /// <param name="input">The input.</param>
 /// <param name="ideal">The ideal.</param>
 /// <returns>The score.</returns>
 public static double Score(IGAModel model, Genome testSubject, double[][] input, double[][] ideal)
 {
     if (ideal[0].Length > 1)
     {
         return(ScoreClassification(model, testSubject, input, ideal));
     }
     return(ScoreRegression(model, testSubject, input, ideal));
 }
        public NURBSElement2D(int id, IGAModel model, IList <Knot> knots, IVector <int> connectivity)
        {
            this.id           = id;
            this.knots        = knots;
            this.connectivity = connectivity;
            this.model        = model;

            this.CreateElementGaussPoints();
        }
Esempio n. 3
0
        public ShapeNURBS2D(NURBSElement2D element, IGAModel model, IVector <double> parametricCoordinateKsi, IVector <double> parametricCoordinateHeta, IList <ControlPoint> controlPoints)
        {
            int numberOfCPHeta = model.KnotValueVectorHeta.Length - model.DegreeHeta - 1;

            BSPLines1D bsplinesKsi  = new BSPLines1D(model.DegreeKsi, model.KnotValueVectorKsi, parametricCoordinateKsi);
            BSPLines1D bsplinesHeta = new BSPLines1D(model.DegreeHeta, model.KnotValueVectorHeta, parametricCoordinateHeta);

            nurbsValues = new Matrix2D <double>((model.DegreeKsi + 1) * (model.DegreeHeta + 1), element.gaussPoints.Count);
            nurbsDerivativeValuesKsi  = new Matrix2D <double>((model.DegreeKsi + 1) * (model.DegreeHeta + 1), element.gaussPoints.Count);
            nurbsDerivativeValuesHeta = new Matrix2D <double>((model.DegreeKsi + 1) * (model.DegreeHeta + 1), element.gaussPoints.Count);

            int supportKsi  = model.DegreeKsi + 1;
            int supportHeta = model.DegreeHeta + 1;
            int numberOfElementGaussPoints = (model.DegreeKsi + 1) * (model.DegreeHeta + 1);

            for (int i = 0; i < supportKsi; i++)
            {
                for (int j = 0; j < supportHeta; j++)
                {
                    double sumKsiHeta  = 0;
                    double sumdKsiHeta = 0;
                    double sumKsidHeta = 0;

                    for (int k = 0; k < numberOfElementGaussPoints; k++)
                    {
                        sumKsiHeta += bsplinesKsi.BSPLValues[element.connectivity[k] / numberOfCPHeta, i] *
                                      bsplinesHeta.BSPLValues[element.connectivity[k] % numberOfCPHeta, j] *
                                      controlPoints[k].Weight;

                        sumdKsiHeta = +bsplinesKsi.BSPLDerivativeValues[element.connectivity[k] / numberOfCPHeta, i] *
                                      bsplinesHeta.BSPLDerivativeValues[element.connectivity[k] % numberOfCPHeta, j] *
                                      controlPoints[k].Weight;

                        sumKsidHeta = +bsplinesKsi.BSPLValues[element.connectivity[k] / numberOfCPHeta, i] *
                                      bsplinesHeta.BSPLDerivativeValues[element.connectivity[k] % numberOfCPHeta, j] *
                                      controlPoints[k].Weight;
                    }
                    for (int k = 0; k < numberOfElementGaussPoints; k++)
                    {
                        nurbsValues[k, i *supportHeta + j] = bsplinesKsi.BSPLValues[element.connectivity[k] / numberOfCPHeta, i] *
                                                             bsplinesHeta.BSPLValues[element.connectivity[k] % numberOfCPHeta, j] *
                                                             controlPoints[k].Weight / sumKsiHeta;

                        nurbsDerivativeValuesKsi[k, i *supportHeta + j] = bsplinesHeta.BSPLValues[element.connectivity[k] % numberOfCPHeta, j] * controlPoints[k].Weight *
                                                                          (bsplinesKsi.BSPLDerivativeValues[element.connectivity[k] / numberOfCPHeta, i] * sumKsiHeta -
                                                                           bsplinesKsi.BSPLValues[element.connectivity[k] / numberOfCPHeta, i] * sumdKsiHeta) / Math.Pow(sumKsiHeta, 2);

                        nurbsDerivativeValuesHeta[k, i *supportHeta + j] = bsplinesKsi.BSPLValues[element.connectivity[k] / numberOfCPHeta, i] *
                                                                           controlPoints[k].Weight *
                                                                           (bsplinesHeta.BSPLDerivativeValues[element.connectivity[k] % numberOfCPHeta, j] * sumKsiHeta -
                                                                            bsplinesHeta.BSPLValues[element.connectivity[k] % numberOfCPHeta, j] * sumKsidHeta) / Math.Pow(sumKsiHeta, 2);
                    }
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Score the model when the output is regression.
        /// For regression, the score is mean square error (MSE).
        /// http://www.heatonresearch.com/wiki/Mean_Square_Error
        /// </summary>
        /// <param name="model">The model to score.</param>
        /// <param name="testSubject">The test subject.</param>
        /// <param name="input">The input.</param>
        /// <param name="ideal">The ideal.</param>
        /// <returns>The score.</returns>
        private static double ScoreRegression(IGAModel model, Genome testSubject, double[][] input, double[][] ideal)
        {
            double error        = 0;
            double elementCount = 0;

            Parallel.For(0, input.Length, row =>
            {
                double[] output = model.Compute(input[row], testSubject);
                for (int col = 0; col < output.Length; col++)
                {
                    double delta = output[col] - ideal[row][col];
                    error       += delta * delta;
                    elementCount++;
                }
            });

            return(Math.Sqrt(error / elementCount));
        }
Esempio n. 5
0
        /// <summary>
        /// Score the model when the output is classification.
        /// For classification, the score is the percentage correct.
        /// </summary>
        /// <param name="model">The model to score.</param>
        /// <param name="testSubject">The test subject.</param>
        /// <param name="input">The input.</param>
        /// <param name="ideal">The ideal.</param>
        /// <returns>The score.</returns>
        private static double ScoreClassification(IGAModel model, Genome testSubject, double[][] input, double[][] ideal)
        {
            double error        = 0;
            double elementCount = 0;
            int    badCount     = 0;

            Parallel.For(0, input.Length, row =>
            {
                double[] output = model.Compute(input[row], testSubject);
                int outputIndex = FindTopIndex(output);
                int idealIndex  = FindTopIndex(ideal[row]);
                if (outputIndex != idealIndex)
                {
                    badCount++;
                }
                elementCount++;
            });

            return(badCount / elementCount);
        }
Esempio n. 6
0
        public static void CreateModelFromFile(IGAModel model, string fileName)
        {
            char[]     delimeters = { ' ', '=', '\t' };
            Attributes?name       = null;

            String[] text = System.IO.File.ReadAllLines(fileName);

            for (int i = 0; i < text.Length; i++)
            {
                String[] line = text[i].Split(delimeters, StringSplitOptions.RemoveEmptyEntries);
                if (line.Length == 0)
                {
                    continue;
                }
                try
                {
                    name = (Attributes)Enum.Parse(typeof(Attributes), line[0].ToLower());
                }catch (Exception e)
                {
                    throw new KeyNotFoundException("Variable name is not found " + line[0]);
                }

                switch (name)
                {
                case Attributes.numberofdimensions:
                    model.NumberOfDimensions = Int32.Parse(line[1]);
                    break;

                case Attributes.degreeksi:
                    model.DegreeKsi = Int32.Parse(line[1]);
                    break;

                case Attributes.degreeheta:
                    model.DegreeHeta = Int32.Parse(line[1]);
                    break;

                case Attributes.degreezeta:
                    model.DegreeZeta = Int32.Parse(line[1]);
                    break;

                case Attributes.numberofcpksi:
                    model.NumberOfCPKsi = Int32.Parse(line[1]);
                    break;

                case Attributes.numberofcpheta:
                    model.NumberOfCPHeta = Int32.Parse(line[1]);
                    break;

                case Attributes.numberofcpzeta:
                    model.NumberOfCPZeta = Int32.Parse(line[1]);
                    break;

                case Attributes.knotvaluevectorksi:
                    if (model.DegreeKsi == 0 || model.NumberOfCPKsi == 0)
                    {
                        throw new ArgumentOutOfRangeException("Degree Ksi and number of Control Points per axis Ksi must be defined before Knot Value Vector Ksi.");
                    }
                    model.KnotValueVectorKsi = new Vector <double>(model.NumberOfCPKsi + model.DegreeKsi + 1);
                    for (int j = 0; j < model.NumberOfCPKsi + model.DegreeKsi + 1; j++)
                    {
                        model.KnotValueVectorKsi[j] = Double.Parse(line[j + 1], CultureInfo.InvariantCulture);
                    }
                    break;

                case Attributes.knotvaluevectorheta:
                    if (model.DegreeHeta == 0 || model.NumberOfCPHeta == 0)
                    {
                        throw new ArgumentOutOfRangeException("Degree Heta and number of Control Points per axis Heta must be defined before Knot Value Vector Heta.");
                    }
                    model.KnotValueVectorHeta = new Vector <double>(model.NumberOfCPHeta + model.DegreeHeta + 1);
                    for (int j = 0; j < model.NumberOfCPHeta + model.DegreeHeta + 1; j++)
                    {
                        model.KnotValueVectorHeta[j] = Double.Parse(line[j + 1], CultureInfo.InvariantCulture);
                    }
                    break;

                case Attributes.knotvaluevectorzeta:
                    if (model.DegreeZeta == 0 || model.NumberOfCPZeta == 0)
                    {
                        throw new ArgumentOutOfRangeException("Degree Zeta and number of Control Points per axis Zeta must be defined before Knot Value Vector Zeta.");
                    }
                    model.KnotValueVectorZeta = new Vector <double>(model.NumberOfCPZeta + model.DegreeZeta + 1);
                    for (int j = 0; j < model.NumberOfCPZeta + model.DegreeZeta + 1; j++)
                    {
                        model.KnotValueVectorZeta[j] = Double.Parse(line[j + 1], CultureInfo.InvariantCulture);
                    }
                    break;

                case Attributes.cpcoord:
                    if (model.NumberOfDimensions == 2)
                    {
                        Matrix2D <double> cpCoordinates = new Matrix2D <double>(model.NumberOfCPKsi * model.NumberOfCPHeta, 3);
                        cpCoordinates[0, 0] = Double.Parse(line[1], CultureInfo.InvariantCulture);
                        cpCoordinates[0, 1] = Double.Parse(line[2], CultureInfo.InvariantCulture);
                        cpCoordinates[0, 2] = Double.Parse(line[3], CultureInfo.InvariantCulture);
                        for (int j = 1; j < model.NumberOfCPKsi * model.NumberOfCPHeta; j++)
                        {
                            i++;
                            line = text[i].Split(delimeters);
                            cpCoordinates[j, 0] = Double.Parse(line[0], CultureInfo.InvariantCulture);
                            cpCoordinates[j, 1] = Double.Parse(line[1], CultureInfo.InvariantCulture);
                            cpCoordinates[j, 2] = Double.Parse(line[2], CultureInfo.InvariantCulture);
                        }
                        model.CreateModelData(cpCoordinates);
                    }
                    else
                    {
                        Matrix2D <double> cpCoordinates = new Matrix2D <double>(model.NumberOfCPKsi * model.NumberOfCPHeta * model.NumberOfCPZeta, 4);
                        cpCoordinates[0, 0] = Double.Parse(line[1], CultureInfo.InvariantCulture);
                        cpCoordinates[0, 1] = Double.Parse(line[2], CultureInfo.InvariantCulture);
                        cpCoordinates[0, 2] = Double.Parse(line[3], CultureInfo.InvariantCulture);
                        cpCoordinates[0, 3] = Double.Parse(line[4], CultureInfo.InvariantCulture);
                        for (int j = 1; j < model.NumberOfCPKsi * model.NumberOfCPHeta * model.NumberOfCPZeta; j++)
                        {
                            i++;
                            line = text[i].Split(delimeters);
                            cpCoordinates[j, 0] = Double.Parse(line[0], CultureInfo.InvariantCulture);
                            cpCoordinates[j, 1] = Double.Parse(line[1], CultureInfo.InvariantCulture);
                            cpCoordinates[j, 2] = Double.Parse(line[2], CultureInfo.InvariantCulture);
                            cpCoordinates[j, 3] = Double.Parse(line[3], CultureInfo.InvariantCulture);
                        }
                        model.CreateModelData(cpCoordinates);
                    }
                    break;

                case Attributes.end:
                    return;
                }
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Load specified filename.
        /// </summary>
        /// <param name="filename">The filename.</param>
        public void Load(string filename)
        {
            XDocument xml = XDocument.Load(filename);

            XElement root = xml.Element("GeneticAlgorithmUtil");

            // read in attributes from the GA node
            XElement ga = root.Element("GA");

            _populationSize  = int.Parse(ga.Element("PopulationSize").Value);
            _maxParents      = int.Parse(ga.Element("MaxParents").Value);
            _mutationPercent = double.Parse(ga.Element("MutationPercent").Value, CultureInfo.InvariantCulture);

            // determine the score goal
            _maxGoal = (string.Compare(ga.Element("ScoreGoal").Value, "max", true) == 0);

            // use reflection to create the model class
            string typeStr = ga.Element("Model").Value;

            if (ga.Element("Model").Attribute("config") != null)
            {
                _modelConfig = ga.Element("Model").Attribute("config").Value;
            }

            Assembly assembly = Assembly.GetExecutingAssembly();

            Type type = assembly.GetTypes()
                        .First(t => t.Name == typeStr);

            _model = (IGAModel)Activator.CreateInstance(type);

            // read in information from the files node
            XElement files = root.Element("Files");

            _populationFile       = files.Element("PopulationFile").Value;
            _trainingFile         = files.Element("TrainingFile").Value;
            _evaluationFile       = files.Element("EvaluationFile").Value;
            _evaluationOutputFile = files.Element("EvaluationOutputFile").Value;

            // make sure that the filenames have path information
            string scriptPath = Path.GetDirectoryName(filename);

            if (scriptPath.Length == 0)
            {
                scriptPath = Directory.GetCurrentDirectory();
            }

            if (Path.GetDirectoryName(_populationFile).Length == 0)
            {
                _populationFile = Path.Combine(scriptPath, _populationFile);
            }

            if (Path.GetDirectoryName(_trainingFile).Length == 0)
            {
                _trainingFile = Path.Combine(scriptPath, _trainingFile);
            }

            if (Path.GetDirectoryName(_evaluationFile).Length == 0)
            {
                _evaluationFile = Path.Combine(scriptPath, _evaluationFile);
            }

            if (Path.GetDirectoryName(_evaluationOutputFile).Length == 0)
            {
                _evaluationOutputFile = Path.Combine(scriptPath, _evaluationOutputFile);
            }

            // read in normalization field data
            XElement fmt = root.Element("DataFileFormat");

            _predictField  = fmt.Element("PredictField").Value;
            _normalizeHigh = double.Parse(fmt.Element("Normalize").Attribute("max").Value, CultureInfo.InvariantCulture);
            _normalizeLow  = double.Parse(fmt.Element("Normalize").Attribute("min").Value, CultureInfo.InvariantCulture);

            // read in the normalized fields
            XElement fields = root.Element("DataFileFormat");

            foreach (XElement fieldElement in fields.Elements("Fields").Elements("Field"))
            {
                var    dataField = new DataField();
                string actionStr = fieldElement.Attribute("action").Value;
                string nameStr   = fieldElement.Attribute("name").Value;

                dataField.Name = nameStr;

                if (string.Compare(actionStr, "norm", true) == 0)
                {
                    dataField.Action = FieldAction.Normalize;
                }
                else if (string.Compare(actionStr, "class", true) == 0)
                {
                    dataField.Action = FieldAction.Class;
                }
                else if (string.Compare(actionStr, "ignore", true) == 0)
                {
                    dataField.Action = FieldAction.Ignore;
                }
                else if (string.Compare(actionStr, "direct", true) == 0)
                {
                    dataField.Action = FieldAction.Direct;
                }

                dataField.NormalizedLow  = NormalizeLow;
                dataField.NormalizedHigh = NormalizeHigh;

                _fields.Add(dataField);
                _fieldMap.Add(dataField.Name, dataField);
            }
        }
Esempio n. 8
0
        public ShapeNURBS3D(NURBSElement3D element, IGAModel model, IVector <double> parametricCoordinateKsi, IVector <double> parametricCoordinateHeta, IVector <double> parametricCoordinateZeta, IList <ControlPoint> controlPoints)
        {
            int numberOfCPHeta = model.KnotValueVectorHeta.Length - model.DegreeHeta - 1;
            int numberOfCPZeta = model.KnotValueVectorZeta.Length - model.DegreeZeta - 1;

            BSPLines1D bsplinesKsi  = new BSPLines1D(model.DegreeKsi, model.KnotValueVectorKsi, parametricCoordinateKsi);
            BSPLines1D bsplinesHeta = new BSPLines1D(model.DegreeHeta, model.KnotValueVectorHeta, parametricCoordinateHeta);
            BSPLines1D bsplinesZeta = new BSPLines1D(model.DegreeZeta, model.KnotValueVectorZeta, parametricCoordinateZeta);

            nurbsValues = new Matrix2D <double>((model.DegreeKsi + 1) * (model.DegreeHeta + 1) * (model.DegreeZeta + 1), element.gaussPoints.Count);
            nurbsDerivativeValuesKsi  = new Matrix2D <double>((model.DegreeKsi + 1) * (model.DegreeHeta + 1) * (model.DegreeZeta + 1), element.gaussPoints.Count);
            nurbsDerivativeValuesHeta = new Matrix2D <double>((model.DegreeKsi + 1) * (model.DegreeHeta + 1) * (model.DegreeZeta + 1), element.gaussPoints.Count);
            nurbsDerivativeValuesZeta = new Matrix2D <double>((model.DegreeKsi + 1) * (model.DegreeHeta + 1) * (model.DegreeZeta + 1), element.gaussPoints.Count);

            int supportKsi  = model.DegreeKsi + 1;
            int supportHeta = model.DegreeHeta + 1;
            int supportZeta = model.DegreeZeta + 1;
            int numberOfElementGaussPoints = (model.DegreeKsi + 1) * (model.DegreeHeta + 1) * (model.DegreeZeta + 1);


            for (int i = 0; i < supportKsi; i++)
            {
                for (int j = 0; j < supportHeta; j++)
                {
                    for (int k = 0; k < supportZeta; k++)
                    {
                        double sumKsiHetaZeta  = 0;
                        double sumdKsiHetaZeta = 0;
                        double sumKsidHetaZeta = 0;
                        double sumKsiHetadZeta = 0;

                        for (int m = 0; m < numberOfElementGaussPoints; m++)
                        {
                            int indexKsi  = element.connectivity[m] / (numberOfCPHeta * numberOfCPZeta);
                            int indexHeta = element.connectivity[m] % (numberOfCPHeta * numberOfCPZeta) / numberOfCPZeta;
                            int indexZeta = element.connectivity[m] % (numberOfCPHeta * numberOfCPZeta) % numberOfCPZeta;

                            sumKsiHetaZeta += bsplinesKsi.BSPLValues[indexKsi, i] *
                                              bsplinesHeta.BSPLValues[indexHeta, j] *
                                              bsplinesZeta.BSPLValues[indexZeta, k] *
                                              controlPoints[m].Weight;

                            sumdKsiHetaZeta += bsplinesKsi.BSPLDerivativeValues[indexKsi, i] *
                                               bsplinesHeta.BSPLValues[indexHeta, j] *
                                               bsplinesZeta.BSPLValues[indexZeta, k] *
                                               controlPoints[m].Weight;

                            sumKsidHetaZeta += bsplinesKsi.BSPLValues[indexKsi, i] *
                                               bsplinesHeta.BSPLDerivativeValues[indexHeta, j] *
                                               bsplinesZeta.BSPLValues[indexZeta, k] *
                                               controlPoints[m].Weight;

                            sumKsiHetadZeta += bsplinesKsi.BSPLValues[indexKsi, i] *
                                               bsplinesHeta.BSPLValues[indexHeta, j] *
                                               bsplinesZeta.BSPLDerivativeValues[indexZeta, k] *
                                               controlPoints[m].Weight;
                        }
                        for (int m = 0; m < numberOfElementGaussPoints; m++)
                        {
                            int indexKsi  = element.connectivity[m] / (numberOfCPHeta * numberOfCPZeta);
                            int indexHeta = element.connectivity[m] % (numberOfCPHeta * numberOfCPZeta) / numberOfCPZeta;
                            int indexZeta = element.connectivity[m] % (numberOfCPHeta * numberOfCPZeta) % numberOfCPZeta;

                            nurbsValues[m, i *supportHeta *supportZeta + j * supportZeta + k] =
                                bsplinesKsi.BSPLValues[indexKsi, i] *
                                bsplinesHeta.BSPLValues[indexHeta, j] *
                                bsplinesZeta.BSPLValues[indexZeta, k] *
                                controlPoints[m].Weight / sumKsiHetaZeta;

                            nurbsDerivativeValuesKsi[m, i *supportHeta *supportZeta + j * supportZeta + k] =
                                (bsplinesKsi.BSPLDerivativeValues[indexKsi, i] * sumKsiHetaZeta -
                                 bsplinesKsi.BSPLValues[indexKsi, i] * sumdKsiHetaZeta) *
                                bsplinesHeta.BSPLValues[indexHeta, j] *
                                bsplinesZeta.BSPLValues[indexZeta, k] *
                                controlPoints[m].Weight / Math.Pow(sumKsiHetaZeta, 2);

                            nurbsDerivativeValuesHeta[m, i *supportHeta *supportZeta + j * supportZeta + k] =
                                bsplinesKsi.BSPLValues[indexKsi, i] *
                                (bsplinesHeta.BSPLDerivativeValues[indexHeta, j] * sumKsiHetaZeta -
                                 bsplinesHeta.BSPLValues[indexHeta, j] * sumKsidHetaZeta) *
                                bsplinesZeta.BSPLValues[indexZeta, k] *
                                controlPoints[m].Weight / Math.Pow(sumKsiHetaZeta, 2);

                            nurbsDerivativeValuesZeta[m, i *supportHeta *supportZeta + j * supportZeta + k] =
                                bsplinesKsi.BSPLValues[indexKsi, i] *
                                bsplinesHeta.BSPLValues[indexHeta, j] *
                                (bsplinesZeta.BSPLDerivativeValues[indexZeta, k] * sumKsiHetaZeta -
                                 bsplinesZeta.BSPLValues[indexZeta, k] * sumKsiHetadZeta) *
                                controlPoints[m].Weight / Math.Pow(sumKsiHetaZeta, 2);
                        }
                    }
                }
            }
        }
Esempio n. 9
0
        private static void SolveIsogeometricModelExample()
        {
            IGAModel model = new IGAModel();

            IGAModelReader.CreateModelFromFile(model, "Cantilever2D biquadratic");
        }
Esempio n. 10
0
        /// <summary>
        /// Score the model when the output is regression.  
        /// For regression, the score is mean square error (MSE).
        /// http://www.heatonresearch.com/wiki/Mean_Square_Error
        /// </summary>
        /// <param name="model">The model to score.</param>
        /// <param name="testSubject">The test subject.</param>
        /// <param name="input">The input.</param>
        /// <param name="ideal">The ideal.</param>
        /// <returns>The score.</returns>
        private static double ScoreRegression(IGAModel model, Genome testSubject, double[][] input, double[][] ideal)
        {
            double error = 0;
            double elementCount = 0;

            Parallel.For(0, input.Length, row =>
            {
                double[] output = model.Compute(input[row], testSubject);
                for (int col = 0; col < output.Length; col++)
                {
                    double delta = output[col] - ideal[row][col];
                    error += delta * delta;
                    elementCount++;
                }
            });

            return Math.Sqrt(error / elementCount);
        }
Esempio n. 11
0
        /// <summary>
        /// Score the model when the output is classification.  
        /// For classification, the score is the percentage correct.
        /// </summary>
        /// <param name="model">The model to score.</param>
        /// <param name="testSubject">The test subject.</param>
        /// <param name="input">The input.</param>
        /// <param name="ideal">The ideal.</param>
        /// <returns>The score.</returns>
        private static double ScoreClassification(IGAModel model, Genome testSubject, double[][] input, double[][] ideal)
        {
            double error = 0;
            double elementCount = 0;
            int badCount = 0;

            Parallel.For(0, input.Length, row =>
            {
                double[] output = model.Compute(input[row], testSubject);
                int outputIndex = FindTopIndex(output);
                int idealIndex = FindTopIndex(ideal[row]);
                if (outputIndex != idealIndex)
                {
                    badCount++;
                }
                elementCount++;
            });

            return badCount / elementCount;
        }
Esempio n. 12
0
 /// <summary>
 /// Score the model for regression or classification.
 /// For classification, the score is the percentage correct.  
 /// For regression, the score is mean square error (MSE).
 /// http://www.heatonresearch.com/wiki/Mean_Square_Error
 /// </summary>
 /// <param name="model">The model to score.</param>
 /// <param name="testSubject">The test subject.</param>
 /// <param name="input">The input.</param>
 /// <param name="ideal">The ideal.</param>
 /// <returns>The score.</returns>
 public static double Score(IGAModel model, Genome testSubject, double[][] input, double[][] ideal)
 {
     if (ideal[0].Length > 1)
     {
         return ScoreClassification(model, testSubject, input, ideal);
     }
     return ScoreRegression(model, testSubject, input, ideal);
 }
Esempio n. 13
0
        /// <summary>
        /// Load specified filename.
        /// </summary>
        /// <param name="filename">The filename.</param>
        public void Load(string filename)
        {
            XDocument xml = XDocument.Load(filename);

            XElement root = xml.Element("GeneticAlgorithmUtil");

            // read in attributes from the GA node
            XElement ga = root.Element("GA");
            _populationSize = int.Parse(ga.Element("PopulationSize").Value);
            _maxParents = int.Parse(ga.Element("MaxParents").Value);
            _mutationPercent = double.Parse(ga.Element("MutationPercent").Value, CultureInfo.InvariantCulture);

            // determine the score goal
            _maxGoal = (string.Compare(ga.Element("ScoreGoal").Value, "max", true) == 0);

            // use reflection to create the model class
            string typeStr = ga.Element("Model").Value;

            if (ga.Element("Model").Attribute("config") != null)
            {
                _modelConfig = ga.Element("Model").Attribute("config").Value;
            }

            Assembly assembly = Assembly.GetExecutingAssembly();

            Type type = assembly.GetTypes()
                .First(t => t.Name == typeStr);

            _model = (IGAModel) Activator.CreateInstance(type);

            // read in information from the files node
            XElement files = root.Element("Files");

            _populationFile = files.Element("PopulationFile").Value;
            _trainingFile = files.Element("TrainingFile").Value;
            _evaluationFile = files.Element("EvaluationFile").Value;
            _evaluationOutputFile = files.Element("EvaluationOutputFile").Value;

            // make sure that the filenames have path information
            string scriptPath = Path.GetDirectoryName(filename);

            if (scriptPath.Length == 0)
            {
                scriptPath = Directory.GetCurrentDirectory();
            }

            if (Path.GetDirectoryName(_populationFile).Length == 0)
            {
                _populationFile = Path.Combine(scriptPath, _populationFile);
            }

            if (Path.GetDirectoryName(_trainingFile).Length == 0)
            {
                _trainingFile = Path.Combine(scriptPath, _trainingFile);
            }

            if (Path.GetDirectoryName(_evaluationFile).Length == 0)
            {
                _evaluationFile = Path.Combine(scriptPath, _evaluationFile);
            }

            if (Path.GetDirectoryName(_evaluationOutputFile).Length == 0)
            {
                _evaluationOutputFile = Path.Combine(scriptPath, _evaluationOutputFile);
            }

            // read in normalization field data
            XElement fmt = root.Element("DataFileFormat");

            _predictField = fmt.Element("PredictField").Value;
            _normalizeHigh = double.Parse(fmt.Element("Normalize").Attribute("max").Value, CultureInfo.InvariantCulture);
            _normalizeLow = double.Parse(fmt.Element("Normalize").Attribute("min").Value, CultureInfo.InvariantCulture);

            // read in the normalized fields
            XElement fields = root.Element("DataFileFormat");
            foreach (XElement fieldElement in fields.Elements("Fields").Elements("Field"))
            {
                var dataField = new DataField();
                string actionStr = fieldElement.Attribute("action").Value;
                string nameStr = fieldElement.Attribute("name").Value;

                dataField.Name = nameStr;

                if (string.Compare(actionStr, "norm", true) == 0)
                {
                    dataField.Action = FieldAction.Normalize;
                }
                else if (string.Compare(actionStr, "class", true) == 0)
                {
                    dataField.Action = FieldAction.Class;
                }
                else if (string.Compare(actionStr, "ignore", true) == 0)
                {
                    dataField.Action = FieldAction.Ignore;
                }
                else if (string.Compare(actionStr, "direct", true) == 0)
                {
                    dataField.Action = FieldAction.Direct;
                }

                dataField.NormalizedLow = NormalizeLow;
                dataField.NormalizedHigh = NormalizeHigh;

                _fields.Add(dataField);
                _fieldMap.Add(dataField.Name, dataField);
            }
        }