Exemplo n.º 1
0
        public List <Data.Point> getSolution()
        {
            List <Data.Point> result = new List <Data.Point>();

            /* double maxGradient = -255;
             * double minGradient = 255;
             *
             * for (int i = 0; i < swingSharpness.GetLength(0); i++)
             *   for (int j = 0; j < swingSharpness.GetLength(1); j++)
             *   {
             *       if (maxGradient < swingSharpness[i, j]) maxGradient = swingSharpness[i, j];
             *       if (minGradient > swingSharpness[i, j]) minGradient = swingSharpness[i, j];
             *   }
             */

            double maxGradient = swingSharpness.Cast <double>().Max();
            double minGradient = swingSharpness.Cast <double>().Min();
            double delta       = matematical.getDeltaThreshold();
            double threshold   = minGradient + ((maxGradient - minGradient) * delta);

            for (int x = 0; x < swingSharpness.GetLength(0); x++)
            {
                for (int y = 0; y < swingSharpness.GetLength(1); y++)
                {
                    if (swingSharpness[x, y] >= threshold)
                    {
                        result.Add(new Data.Point(x, y));
                    }
                }
            }

            return(result);
        }
Exemplo n.º 2
0
        public override void SetMatrixForPlotting(double[,] newMat, string[] WontBeUsed = null, string[] WontBeUsed2 = null)
        {
            double min = newMat.Cast <double>().Min();
            double max = newMat.Cast <double>().Max();

            CreateNewMat(min, max);
        }
Exemplo n.º 3
0
        public unsafe static Bitmap DensityGraph(double[,] data, int maxCores, ref Bitmap image, bool greyscale = false, double rangeHigh = 0, double rangeLow = 0)
        {
            int num = Environment.ProcessorCount;

            if (maxCores < 1 || maxCores >= num)
            {
                num = Environment.ProcessorCount;
            }
            else
            {
                num = maxCores;
            }
            Bitmap     imgBuffer  = (Bitmap)image.Clone();
            BitmapData bitmapData = imgBuffer.LockBits(new Rectangle(0, 0, imgBuffer.Width, imgBuffer.Height), ImageLockMode.ReadWrite, imgBuffer.PixelFormat);

            int    bytesPerPixel  = Bitmap.GetPixelFormatSize(imgBuffer.PixelFormat) / 8;
            int    heightInPixels = bitmapData.Height;
            int    widthInBytes   = bitmapData.Width * bytesPerPixel;
            byte * PtrFirstPixel  = (byte *)bitmapData.Scan0;
            bool   isAutoscale    = rangeHigh - rangeLow == 0;
            double maxValue       = isAutoscale ? data.Cast <double>().Max() : rangeHigh;
            double minValue       = isAutoscale ? data.Cast <double>().Min() : rangeLow;

            Parallel.For(0, heightInPixels, new ParallelOptions()
            {
                MaxDegreeOfParallelism = num
            }, y =>
            {
                byte *currentLine = PtrFirstPixel + (y * bitmapData.Stride);
                int red;
                int green;
                int blue;
                double h, s, v;

                for (int x = 0; x < bitmapData.Width; x++)
                {
                    double value = Math.Min(maxValue, data[y, x]);
                    value        = Math.Max(minValue, data[y, x]);
                    value        = maxValue - minValue == 0 ? 0 : (value - minValue) / (maxValue - minValue);

                    h = greyscale ? 0 : 360.0 * value;
                    s = greyscale ? 0 : 1;
                    v = greyscale ? value : 1;

                    HsvToRgb(h, s, v, out red, out green, out blue);

                    currentLine[x * bytesPerPixel]     = (byte)red;
                    currentLine[x * bytesPerPixel + 1] = (byte)green;
                    currentLine[x * bytesPerPixel + 2] = (byte)blue;
                }
            });
            imgBuffer.UnlockBits(bitmapData);
            return(imgBuffer);
        }
Exemplo n.º 4
0
 private static bool isParametersChanged(
     double sigma,
     double T,
     double kappa,
     double B,
     double risk_free,
     double credit_spread,
     double stock_growth,
     double[,] couponInfoMatrix,
     double[,] callInfoMatrix,
     double[,] putInfoMatrix)
 {
     if (_sigma != sigma ||
         _T != T ||
         _kappa != kappa ||
         _B != B ||
         _risk_free != risk_free ||
         _credit_spread != credit_spread ||
         _stock_growth != stock_growth ||
         _couponInfoMatrix.Length != couponInfoMatrix.Length ||
         _callInfoMatrix.Length != callInfoMatrix.Length ||
         _putInfoMatrix.Length != putInfoMatrix.Length)
     {
         return(true);
     }
     if (!couponInfoMatrix.Cast <double>().SequenceEqual(_couponInfoMatrix.Cast <double>()) ||
         !callInfoMatrix.Cast <double>().SequenceEqual(_callInfoMatrix.Cast <double>()) ||
         !putInfoMatrix.Cast <double>().SequenceEqual(_putInfoMatrix.Cast <double>()))
     {
         return(true);
     }
     return(false);
 }
Exemplo n.º 5
0
        private void ShowResultText()
        {
            //string precision = "";
            //string recall = "";

            //double acc = ((double)RealNum / (double)TotalNum) * 100;

            int sum        = (int)confusionMatrix.Cast <double>().Sum();
            int correctSum = 0;

            for (int j = 0; j < confusionMatrix.GetLength(1); j++)
            {
                for (int i = 0; i < confusionMatrix.GetLength(0); i++)
                {
                    if (i == j)
                    {
                        correctSum += (int)confusionMatrix[i, j];
                    }
                }
            }

            double acc = (double)correctSum / (double)sum * 100;

            ResultText_TB.Text = "Total : " + sum.ToString() + "  /  Acc : " + string.Format("{0:0.00}", acc);
        }
Exemplo n.º 6
0
        public static KMeansClusteringSolution CreateKMeansSolution(IClusteringProblemData problemData, int k, int restarts)
        {
            var dataset = problemData.Dataset;
            IEnumerable <string> allowedInputVariables = problemData.AllowedInputVariables;
            IEnumerable <int>    rows = problemData.TrainingIndices;
            int info;

            double[,] centers;
            int[] xyc;
            double[,] inputMatrix = AlglibUtil.PrepareInputMatrix(dataset, allowedInputVariables, rows);
            if (inputMatrix.Cast <double>().Any(x => double.IsNaN(x) || double.IsInfinity(x)))
            {
                throw new NotSupportedException("k-Means clustering does not support NaN or infinity values in the input dataset.");
            }

            alglib.kmeansgenerate(inputMatrix, inputMatrix.GetLength(0), inputMatrix.GetLength(1), k, restarts + 1, out info, out centers, out xyc);
            if (info != 1)
            {
                throw new ArgumentException("Error in calculation of k-Means clustering solution");
            }

            KMeansClusteringSolution solution = new KMeansClusteringSolution(new KMeansClusteringModel(centers, allowedInputVariables), (IClusteringProblemData)problemData.Clone());

            return(solution);
        }
Exemplo n.º 7
0
        public Matrix(double[,] matrix, bool rowMajor = true)
        {
            // NOTE copies elements
            if (rowMajor)
            {
                rows = matrix.GetLength(0);
                cols = matrix.GetLength(1);
                mat  = matrix.Cast <double>().ToArray();
            }
            // column-major
            else
            {
                rows = matrix.GetLength(1);
                cols = matrix.GetLength(0);
                mat  = new double[rows * cols];

                for (int row = 0; row < rows; row++)
                {
                    for (int col = 0; col < cols; col++)
                    {
                        this[row, col] = matrix[matrix.GetLowerBound(0) + col, matrix.GetLowerBound(1) + row];
                    }
                }
            }
        }
Exemplo n.º 8
0
        public static double[,] SwapMatrixRows(double[,] source, int row, int size, out int swaps)
        {
            var list       = new List <List <double> >();
            var flatMatrix = source.Cast <double>();

            for (var i = 0; i < size; i++)
            {
                var matrixRow = flatMatrix.Skip(i * size).Take(size).ToList();
                list.Add(matrixRow);
            }

            for (var i = 1; i < size - row; i++)
            {
                if (list[row + i][row + i] != 0)
                {
                    swaps = row + i;
                    var listRow = list[row];
                    list.RemoveAt(row);
                    list.Insert(row + i, listRow);
                    return(list.To2DArray());
                }
            }


            throw new InfiniteSystemSolutionsException();
        }
Exemplo n.º 9
0
        public static double[,] ThresholdFilter(double[,] original, double threshold)
        {
            var width  = original.GetLength(0);
            var height = original.GetLength(1);

            if (threshold < 0 || threshold > 1)
            {
                return(new double[width, height]);
            }

            var res         = new double[width, height];
            var whitePixels = (int)(threshold * original.Length);
            var tmp         = original.Cast <double>().OrderByDescending(x => x).ToList();
            var bright      = tmp.FirstOrDefault(y => (whitePixels <= tmp.Count(z => z > y)));

            for (var i = 0; i < width; i++)
            {
                for (var j = 0; j < height; j++)
                {
                    res[i, j] = original[i, j] > bright ? 1 : 0;
                }
            }

            return(res);
        }
Exemplo n.º 10
0
        public double[] QueryBack(double[,] xTargets)
        {
            //BACK QUERY NEURAL NETWORK
            double[,] finalOutputs = Transpose(xTargets);
            double[,] finalInputs  = LogitFunction(finalOutputs);

            //CALCULATE THE SIGNAL OUT OF THE HIDDEN LAYER
            double[,] hiddenOutputs = Multiply(Transpose(weightOutput), finalInputs);
            hiddenOutputs           = Subtract(hiddenOutputs, MatrixMinimum(hiddenOutputs));
            hiddenOutputs           = Division(hiddenOutputs, MatrixMaximum(hiddenOutputs));
            hiddenOutputs           = Multiply(0.98, hiddenOutputs);
            hiddenOutputs           = Addition(0.01, hiddenOutputs);

            //CALCULATE THE SIGNAL INTO THE HIDEEN LAYER
            double[,] hiddenInputs = LogitFunction(hiddenOutputs);

            //CALCULATE THE SIGNAL OUT OF THE INPUT LAYER
            double[,] inputs = Multiply(Transpose(weightInput), hiddenInputs);
            inputs           = Subtract(inputs, MatrixMinimum(inputs));
            inputs           = Division(inputs, MatrixMaximum(inputs));
            inputs           = Multiply(0.98, inputs);
            inputs           = Addition(0.01, inputs);

            return(inputs.Cast <double>().ToArray());
        }
 static void LinqLoop()
 {
     if (!data.Cast <double>().Any(d => double.IsNaN(d) || double.IsInfinity(d)))
     {
         Console.WriteLine("FOUND!");
     }
 }
Exemplo n.º 12
0
        public static double[,] ThresholdFilter(double[,] original, double whitePixelsFraction)
        {
            var n = original.GetLength(0) * original.GetLength(1);
            var amountOfWhitePixels = (int)(whitePixelsFraction * n);
            var pixels = original.Cast <double>().ToList();

            pixels.Sort();
            var newMass    = pixels.ToArray();
            var middleCell = 1.0;

            if (amountOfWhitePixels > 0)
            {
                middleCell = newMass[n - amountOfWhitePixels];
            }

            for (var i = n - 1 - amountOfWhitePixels; i >= 0; i--)
            {
                if (newMass[i] == middleCell && amountOfWhitePixels > 0 && amountOfWhitePixels < n)
                {
                    amountOfWhitePixels++;
                }
            }
            for (var i = n - 1 - amountOfWhitePixels; i >= 0; i--)
            {
                WhiteCicle(original, newMass[i], false);
            }

            for (var i = n - 1; i >= n - amountOfWhitePixels; i--)
            {
                WhiteCicle(original, newMass[i], true);
            }
            return(original);
        }
Exemplo n.º 13
0
 private static void AssertInputMatrix(double[,] inputMatrix)
 {
     if (inputMatrix.Cast <double>().Any(x => Double.IsNaN(x) || Double.IsInfinity(x)))
     {
         throw new NotSupportedException("Random forest modeling does not support NaN or infinity values in the input dataset.");
     }
 }
Exemplo n.º 14
0
        // Determinant of matrixA
        private void determinantA_Click(object sender, EventArgs e)
        {
            res = new Result();

            if (combo1[0].Text == combo1[1].Text && combo1[0].Text != "" && combo1[1].Text != "")
            {
                matrixA = matrix.FillMatrix(textBoxes1, int.Parse(combo1[0].Text), int.Parse(combo1[1].Text));
                double determinant = matrix.Determinant(matrixA, int.Parse(combo1[0].Text), int.Parse(combo1[1].Text));

                double[] temp = matrixA.Cast <double>().ToArray();

                WriteLabel("Deter:", res);

                int x = 20, y = 55;
                int count1 = 0;
                for (int i = 0; i < int.Parse(combo1[0].Text) * int.Parse(combo1[1].Text); i++)
                {
                    if (count1 == int.Parse(combo1[1].Text))
                    {
                        count1 = 0;
                        x      = 20;
                        y     += 25;
                    }

                    textBoxes1.Add(CreateTextBoxes(x, y, res, temp[i].ToString()));

                    x += 40;
                    count1++;
                }

                Label lab = new Label();
                lab.Text     = "Determinant of matrixA: ";
                lab.Location = new Point(20, 270);
                lab.Size     = new Size(200, 50);
                lab.Font     = new Font("Tobota", 10, FontStyle.Bold);
                res.Controls.Add(lab);

                TextBox tex = new TextBox();

                tex.Top       = 270;
                tex.Left      = 230;
                tex.Width     = 60;
                tex.TextAlign = HorizontalAlignment.Center;
                tex.Text      = determinant.ToString();

                res.Controls.Add(tex);

                res.Show();
            }
            else if (combo1[0].Text == "" && combo1[1].Text == "" || combo1[0].Text == "" || combo1[1].Text == "")
            {
                MessageBox.Show("The number of rows and columns in matrixA is not specified!");
            }
            else if (combo1[0].Text != combo1[1].Text)
            {
                MessageBox.Show("The matrix must be square!");
            }
        }
        public Graph(double[,] adjacencyTable, bool isDirected)
        {
            adjacencyTable.GetLength(0).Should().Be(adjacencyTable.GetLength(1));

            _adjacencyTable  = adjacencyTable;
            IsDirected       = isDirected;
            NumberOfVertices = adjacencyTable.GetLength(0);
            NumberOfEdges    = adjacencyTable.Cast <double>().Count(edgeDistance => !double.IsPositiveInfinity(edgeDistance));
        }
        public static IClassificationSolution CreateLinearDiscriminantAnalysisSolution(IClassificationProblemData problemData)
        {
            var    dataset        = problemData.Dataset;
            string targetVariable = problemData.TargetVariable;
            IEnumerable <string> allowedInputVariables = problemData.AllowedInputVariables;
            IEnumerable <int>    rows = problemData.TrainingIndices;
            int nClasses = problemData.ClassNames.Count();

            double[,] inputMatrix = AlglibUtil.PrepareInputMatrix(dataset, allowedInputVariables.Concat(new string[] { targetVariable }), rows);
            if (inputMatrix.Cast <double>().Any(x => double.IsNaN(x) || double.IsInfinity(x)))
            {
                throw new NotSupportedException("Linear discriminant analysis does not support NaN or infinity values in the input dataset.");
            }

            // change class values into class index
            int           targetVariableColumn = inputMatrix.GetLength(1) - 1;
            List <double> classValues          = problemData.ClassValues.OrderBy(x => x).ToList();

            for (int row = 0; row < inputMatrix.GetLength(0); row++)
            {
                inputMatrix[row, targetVariableColumn] = classValues.IndexOf(inputMatrix[row, targetVariableColumn]);
            }
            int info;

            double[] w;
            alglib.fisherlda(inputMatrix, inputMatrix.GetLength(0), allowedInputVariables.Count(), nClasses, out info, out w);
            if (info < 1)
            {
                throw new ArgumentException("Error in calculation of linear discriminant analysis solution");
            }

            ISymbolicExpressionTree     tree      = new SymbolicExpressionTree(new ProgramRootSymbol().CreateTreeNode());
            ISymbolicExpressionTreeNode startNode = new StartSymbol().CreateTreeNode();

            tree.Root.AddSubtree(startNode);
            ISymbolicExpressionTreeNode addition = new Addition().CreateTreeNode();

            startNode.AddSubtree(addition);

            int col = 0;

            foreach (string column in allowedInputVariables)
            {
                VariableTreeNode vNode = (VariableTreeNode) new HeuristicLab.Problems.DataAnalysis.Symbolic.Variable().CreateTreeNode();
                vNode.VariableName = column;
                vNode.Weight       = w[col];
                addition.AddSubtree(vNode);
                col++;
            }

            var model = LinearDiscriminantAnalysis.CreateDiscriminantFunctionModel(tree, new SymbolicDataAnalysisExpressionTreeInterpreter(), problemData, rows);
            SymbolicDiscriminantFunctionClassificationSolution solution = new SymbolicDiscriminantFunctionClassificationSolution(model, (IClassificationProblemData)problemData.Clone());

            return(solution);
        }
Exemplo n.º 17
0
        private void calcularValores()
        {
            int rows    = matrix.GetLength(0);
            int columns = matrix.GetLength(1);

            for (int a = 0; a < 100; a++)
            {
                for (int i = 0; i < rows; i++)
                {
                    for (int j = 0; j < columns; j++)
                    {
                        matrix[i, j] = ((((i == 0) ? fN : matrix[i - 1, j]) +
                                         ((j == 0) ? fO : matrix[i, j - 1]) +
                                         ((i == rows - 1) ? fS : matrix[i + 1, j]) +
                                         ((j == columns - 1) ? fE : matrix[i, j + 1])) / 4)
                                       + cMatrix[i, j];
                    }
                }
            }
            mostrarGrid();
            min = matrix.Cast <double>().Min();
            max = matrix.Cast <double>().Max();
            double valor = max / 9;

            foreach (DataGridViewRow r in grid.Rows)
            {
                for (int i = 0; i < r.Cells.Count; i++)
                {
                    double val = Convert.ToDouble(r.Cells[i].Value);
                    r.Cells[i].Style.BackColor =
                        (val > valor) ? ((val > valor * 2) ? ((val > valor * 3)
                        ? ((val > valor * 4) ? ((val > valor * 5) ?
                                                ((val > valor * 6) ? ((val > valor * 7) ?
                                                                      ((val > valor * 8) ? c9 : c8) : c7) : c6) : c5) : c4)
                        : c3) : c2) : c1;
                    r.Cells[i].Style.ForeColor =
                        (r.Cells[i].Style.BackColor == c4) ? Color.Black :
                        Color.White;
                }
            }
            grid.Invalidate();
        }
        // Get Fractal Data
        public int[,] GetData()
        {
            int[,] map     = new int[size, size];
            double[,] data = DiamondSquareAlgorithm();

            double max = data.Cast <double>().Max();
            double min = data.Cast <double>().Min();

            for (int x = 0; x < size - 1; x++)
            {
                for (int y = 0; y < size - 1; y++)
                {
                    double n = data[x, y];
                    n        += roughness / 100 - 1 + Math.Abs(min) / 100;
                    map[x, y] = (int)n;
                }
            }

            return(map);
        }
Exemplo n.º 19
0
        public void ExponentiateMatrixTest_ReturnMultiplicateMatrix()
        {
            double[,] matrix         = { { 1, 1, 1 }, { 0, 0, 1 }, { 0, 0, 1 } };
            double[,] expectedMatrix = { { 1, 1, 3 }, { 0, 0, 1 }, { 0, 0, 1 } };

            var  actualMatrix = FoxMath.ExponentiateMatrix(matrix);
            bool equal        = actualMatrix.Rank == expectedMatrix.Rank && Enumerable.Range(0, actualMatrix.Rank).All(dimension => actualMatrix.GetLength(dimension) == expectedMatrix.GetLength(dimension)) &&
                                actualMatrix.Cast <double>().SequenceEqual(expectedMatrix.Cast <double>());

            Assert.AreEqual(equal, true);
        }
Exemplo n.º 20
0
        private static double CalcThresholdValue(double[,] original, double whitePixelsFraction)
        {
            var picWidth         = original.GetLength(0);
            var picHeight        = original.GetLength(1);
            var pixelsCount      = picWidth * picHeight;
            var whitePixelsCount = (int)(pixelsCount * whitePixelsFraction);

            return(whitePixelsCount > 0
                ? original.Cast <double>().OrderByDescending(x => x).ElementAt(whitePixelsCount - 1)
                : Double.MaxValue);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Определение границ сингулярности изображения
        /// </summary>
        /// <param name="image">Анализируемое изображение</param>
        /// <param name="converterType">Тип конвертера</param>
        /// <returns>Интервал сингулярностей изображения</returns>
        internal Interval GetSingularityBounds(DirectBitmap image, ConverterType converterType)
        {
            Intensivities = new double[image.Width, image.Height];
            CalculateIntensivities(image, converterType);

            CalculateDensity();

            var densityValues = Densities.Cast <double>();

            return(new Interval(densityValues.Min(), densityValues.Max()));
        }
        private static double FindThresholdValue(double[,] original, double whitePixelsFraction)
        {
            var pixelsList = original.Cast <double>().ToList();

            pixelsList.Sort();
            var whitePixelsCount = (int)(whitePixelsFraction * pixelsList.Count);

            return(whitePixelsCount == 0 ?
                   pixelsList.Last() + 1:
                   pixelsList[pixelsList.Count - whitePixelsCount]);
        }
Exemplo n.º 23
0
Arquivo: Fx.cs Projeto: rajeshwarn/PFX
            private static void DodecFace(int a, int b, int c, int d, int e, PrimitiveType shadeType)
            {
                double[] n0 = new double[3], d1 = new double[3], d2 = new double[3];

                Diff3(_dodec.Cast <double>().Skip(19 * a).Take(3).ToArray(),
                      _dodec.Cast <double>().Skip(19 * b).Take(3).ToArray(), ref d1);
                Diff3(_dodec.Cast <double>().Skip(19 * b).Take(3).ToArray(),
                      _dodec.Cast <double>().Skip(19 * c).Take(3).ToArray(), ref d2);
                Crossprod(d1, d2, ref n0);
                Normalize(n0);

                GL.Begin(shadeType);
                GL.Normal3(n0[0], n0[1], n0[2]);
                GL.Vertex3(_dodec[a, 0], _dodec[a, 1], _dodec[a, 2]);
                GL.Vertex3(_dodec[b, 0], _dodec[b, 1], _dodec[b, 2]);
                GL.Vertex3(_dodec[c, 0], _dodec[c, 1], _dodec[c, 2]);
                GL.Vertex3(_dodec[d, 0], _dodec[d, 1], _dodec[d, 2]);
                GL.Vertex3(_dodec[e, 0], _dodec[e, 1], _dodec[e, 2]);
                GL.End();
            }
Exemplo n.º 24
0
        public void EstimateGmm()
        {
            IDataset dataset = new BasicTextDataset(mz, data, coordinates: null);

            var result = _gmm.EstimateGmm(dataset);

            Console.WriteLine(result);

            // Assert
            Assert.Multiple(testDelegate: () =>
            {
                Assert.IsNotNull(result);
                Assert.True(condition: data.Cast <double>()
                            .Take(count: data.GetLength(dimension: 1))
                            .SequenceEqual(result.OriginalMeanSpectrum));
                Assert.True(condition: mz.SequenceEqual(result.OriginalMz));
                Assert.False(result.IsMerged);
                Assert.False(result.IsNoiseReduced);
                Assert.Null(result.MzMergingThreshold);
            });
        }
        public static IClassificationSolution CreateLogitClassificationSolution(IClassificationProblemData problemData, out double rmsError, out double relClassError)
        {
            var               dataset             = problemData.Dataset;
            string            targetVariable      = problemData.TargetVariable;
            var               doubleVariableNames = problemData.AllowedInputVariables.Where(dataset.VariableHasType <double>);
            var               factorVariableNames = problemData.AllowedInputVariables.Where(dataset.VariableHasType <string>);
            IEnumerable <int> rows = problemData.TrainingIndices;

            double[,] inputMatrix = dataset.ToArray(doubleVariableNames.Concat(new string[] { targetVariable }), rows);

            var factorVariableValues = dataset.GetFactorVariableValues(factorVariableNames, rows);
            var factorMatrix         = dataset.ToArray(factorVariableValues, rows);

            inputMatrix = factorMatrix.HorzCat(inputMatrix);

            if (inputMatrix.Cast <double>().Any(x => double.IsNaN(x) || double.IsInfinity(x)))
            {
                throw new NotSupportedException("Multinomial logit classification does not support NaN or infinity values in the input dataset.");
            }

            alglib.logitmodel lm  = new alglib.logitmodel();
            alglib.mnlreport  rep = new alglib.mnlreport();
            int nRows             = inputMatrix.GetLength(0);
            int nFeatures         = inputMatrix.GetLength(1) - 1;

            double[] classValues = dataset.GetDoubleValues(targetVariable).Distinct().OrderBy(x => x).ToArray();
            int      nClasses    = classValues.Count();
            // map original class values to values [0..nClasses-1]
            Dictionary <double, double> classIndices = new Dictionary <double, double>();

            for (int i = 0; i < nClasses; i++)
            {
                classIndices[classValues[i]] = i;
            }
            for (int row = 0; row < nRows; row++)
            {
                inputMatrix[row, nFeatures] = classIndices[inputMatrix[row, nFeatures]];
            }
            int info;

            alglib.mnltrainh(inputMatrix, nRows, nFeatures, nClasses, out info, out lm, out rep);
            if (info != 1)
            {
                throw new ArgumentException("Error in calculation of logit classification solution");
            }

            rmsError      = alglib.mnlrmserror(lm, inputMatrix, nRows);
            relClassError = alglib.mnlrelclserror(lm, inputMatrix, nRows);

            MultinomialLogitClassificationSolution solution = new MultinomialLogitClassificationSolution(new MultinomialLogitModel(lm, targetVariable, doubleVariableNames, factorVariableValues, classValues), (IClassificationProblemData)problemData.Clone());

            return(solution);
        }
Exemplo n.º 26
0
        private static int[,] SaltandPepper(int[,] arr, double[,] noise, double densitySalt, double densityPepper, int white, SaltandPapperNoise noiseType)
        {
            int[,] result = new int[arr.GetLength(0), arr.GetLength(1)];
            ArrGen <int> d = new ArrGen <int>();

            var vectorArr   = arr.Cast <int>().ToArray();
            var vectorNoise = noise.Cast <double>().ToArray();

            switch (noiseType)
            {
            case SaltandPapperNoise.salt:
                for (int i = 0; i < noise.Length; i++)
                {
                    if (vectorNoise[i] >= (1 - densitySalt / 2))
                    {
                        vectorArr[i] = white;
                    }
                }
                result = d.VecorToArrayRowByRow(arr.GetLength(0), arr.GetLength(1), vectorArr);
                break;

            case SaltandPapperNoise.pepper:
                for (int i = 0; i < noise.Length; i++)
                {
                    if (vectorNoise[i] <= densityPepper / 2)
                    {
                        vectorArr[i] = 0;
                    }
                }
                result = d.VecorToArrayRowByRow(arr.GetLength(0), arr.GetLength(1), vectorArr);
                break;

            case SaltandPapperNoise.saltandpepper:
                for (int i = 0; i < noise.Length; i++)
                {
                    if (vectorNoise[i] >= (1 - densitySalt / 2))
                    {
                        vectorArr[i] = white;
                    }
                }
                for (int i = 0; i < noise.Length; i++)
                {
                    if (vectorNoise[i] <= densityPepper / 2)
                    {
                        vectorArr[i] = 0;
                    }
                }
                result = d.VecorToArrayRowByRow(arr.GetLength(0), arr.GetLength(1), vectorArr);
                break;
            }

            return(result);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Converts double[,] array into 8 bit grayscale image. If <paramref name="image"/> is <see cref="WriteableBitmap"/> values are updated directly in the
        /// image else values are set in the new image which is then returned (since original cannot be modified)
        /// </summary>
        /// <param name="image"></param>
        /// <param name="data"></param>
        /// <returns>Either new image (if source is not writable) or source image with updated vales</returns>
        public static BitmapSource FromDouble2D(this BitmapSource image, double[,] data)
        {
            int rows = data.GetLength(0);
            int cols = data.GetLength(1);

            WriteableBitmap result = null;

            if (image is WriteableBitmap)
            {
                result = image as WriteableBitmap;
            }
            else
            {
                result = new WriteableBitmap(cols, rows, 96, 96, PixelFormats.Gray8, BitmapPalettes.Gray256);
            }

            // Find min max of source data, used later for scaling
            double srcMin = data.Cast <double>().Min();
            double srcMax = data.Cast <double>().Max();

            // Init temp array of pixel values, later to be written into destination image
            byte[] pixels = new byte[rows * cols];

            // Compute pixel values
            for (int row = 0; row < rows; row++)
            {
                for (int col = 0; col < cols; col++)
                {
                    pixels[row * cols + col] = (byte)Scale(data[row, col], srcMin, srcMax, 0, 255);
                }
            }

            // Copy pixels to image
            Int32Rect roi = new Int32Rect(0, 0, cols, rows);

            result.WritePixels(roi, pixels, cols, 0);

            return(result);
        }
Exemplo n.º 28
0
        public void IndexesOfMin(out int i, out int j)
        {
            double min = arr.Cast <double>().Min();

            int resultI = 0;
            int resultJ = 0;

            for (int _i = 0; _i < rows; _i++)
            {
                for (int _j = 0; _j < colls; _j++)
                {
                    if (arr[_i, _j] == min)
                    {
                        resultI = _i;
                        resultJ = _j;
                    }
                }
            }

            i = resultI;
            j = resultJ;
        }
Exemplo n.º 29
0
        public static bool HasInvalidData(this double[,] mat)
        {
            //for (int i = 0; i < mat.Count; i++)
            //{
            //    for (int j = 0; j < lists[i].Count; j++)
            //    {
            //        exData[j, i] = lists[i][j];
            //    }
            //}
            var flattened = mat.Cast <double>().ToArray();

            return(flattened.HasInvalidData());
        }
Exemplo n.º 30
0
        public void DoWork()
        {
            _topo = LoadTopoFromFile(_fileName);
            var a = _topo.SelectMany(x => x).ToList();

            _topoMin = a.Min();
            _topoMax = a.Max();

            _newTopo = NewTopo(_topo);
            var b = _newTopo.Cast <double>().ToList();

            MinValue = b.Min();
            MaxValue = b.Max();
        }