Ejemplo n.º 1
0
        public void XorTest()
        {
            NeuralNetwork network = new NeuralNetwork(2, 1, 1, 1);

            float[,] xorInput = new float[4, 2]
            {
                { 0, 0 },
                { 0, 1 },
                { 1, 0 },
                { 1, 1 }
            };

            float[,] xorOutput = new float[4, 1]
            {
                { 1 },
                { 0 },
                { 0 },
                { 1 }
            };
            SparseMatrix X = new SparseMatrix(SparseCompressedRowMatrixStorage <float> .OfArray(xorInput));
            SparseMatrix Y = new SparseMatrix(SparseCompressedRowMatrixStorage <float> .OfArray(xorOutput));

            network.LearnNetwork(X, Y, 5000, 0.001f, 0);
            network.Inputs = DenseVector.OfArray(new float[2] {
                0, 0
            });
            network.ForwardPropagation();
            var test = network.GetAswer();

            Assert.IsNotNull(test);
            Assert.AreEqual(Math.Round(test[0]), 1);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Create a new sparse matrix straight from an initialized matrix storage instance.
        /// The storage is used directly without copying.
        /// Intended for advanced scenarios where you're working directly with
        /// storage for performance or interop reasons.
        /// </summary>
        public static Matrix <T> Sparse <T>(SparseCompressedRowMatrixStorage <T> storage)
            where T : struct, IEquatable <T>, IFormattable
        {
            MatrixBuilder <T> m_builder = BuilderInstance <T> .Matrix;

            return(m_builder.Sparse(storage));
        }
        public SparseStorageAdapter(SparseMatrix matrix)
        {
            this.matrix  = matrix;
            this.storage = matrix.Storage as SparseCompressedRowMatrixStorage <float>;

            this.service = new SparseStorageInfoService <float>(matrix, new MathService());
        }
Ejemplo n.º 4
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var serializationModel = serializer.Deserialize <MatrixSerializationModel>(reader);

            if (serializationModel.IsDense)
            {
                var storage = DenseColumnMajorMatrixStorage <double> .OfColumnMajorEnumerable(
                    serializationModel.RowCount,
                    serializationModel.ColumnCount,
                    serializationModel.Storage
                    );

                var matrix = new DenseMatrix(storage);
                return(matrix);
            }
            else
            {
                var storage = SparseCompressedRowMatrixStorage <double> .OfColumnMajorList(
                    serializationModel.RowCount,
                    serializationModel.ColumnCount,
                    serializationModel.Storage
                    );

                var matrix = new SparseMatrix(storage);
                return(matrix);
            }
        }
 /// <summary>
 ///     Create a new sparse matrix and initialize each value to the same provided value.
 /// </summary>
 public static SparseMatrix Create(int rows, int columns, double value)
 {
     if (value == 0d)
     {
         return(new SparseMatrix(rows, columns));
     }
     return(new SparseMatrix(SparseCompressedRowMatrixStorage <double> .OfValue(rows, columns, value)));
 }
Ejemplo n.º 6
0
        void CopyToUnchecked(SparseCompressedRowMatrixStorage <T> target, ExistingData existingData)
        {
            if (existingData == ExistingData.Clear)
            {
                target.Clear();
            }

            for (int i = 0; i < Data.Length; i++)
            {
                target.At(i, i, Data[i]);
            }
        }
Ejemplo n.º 7
0
        public static MatrixStorage <T> MatrixStorage <T>(TestMatrixStorage type, T[,] data)
            where T : struct, IEquatable <T>, IFormattable
        {
            switch (type)
            {
            case TestMatrixStorage.DenseMatrix:
                return(DenseColumnMajorMatrixStorage <T> .OfArray(data));

            case TestMatrixStorage.SparseMatrix:
                return(SparseCompressedRowMatrixStorage <T> .OfArray(data));

            case TestMatrixStorage.DiagonalMatrix:
                return(DiagonalMatrixStorage <T> .OfArray(data));

            default:
                throw new NotSupportedException();
            }
        }
        public SparseStorageInfoService(Matrix <T> matrix, IMathService <T> mathService)
        {
            A = matrix;
            S = matrix.Storage as SparseCompressedRowMatrixStorage <T>;

            this.math = mathService;

            this.StorageInfo = new StorageInfo();

            this.StorageInfo.RowCount    = S.RowCount;
            this.StorageInfo.ColumnCount = S.ColumnCount;
            this.StorageInfo.ValueCount  = S.ValueCount;

            int size = Helper.SizeOf <T>();
            int i    = Constants.SizeOfInt;

            this.StorageInfo.TotalBytes = i * S.RowPointers.Length +
                                          i * S.ColumnIndices.Length + size * S.Values.Length;
        }
        /// <summary>
        /// Computes the Frobenius norm of A.
        /// </summary>
        /// <returns>Frobenius norm of A.</returns>
        private double FrobeniusNorm(SparseCompressedRowMatrixStorage <T> A)
        {
            int n = A.RowCount;

            var ax = A.Values;
            var ap = A.RowPointers;
            var ai = A.ColumnIndices;

            int    i, k;
            double fnorm = 0.0;

            for (i = 0; i < n; ++i)
            {
                for (k = ap[i]; k < ap[i + 1]; ++k)
                {
                    fnorm += math.Square(ax[k]);
                }
            }

            return(Math.Sqrt(fnorm));
        }
Ejemplo n.º 10
0
        protected override double[] SolveForMatrixX()
        {
            int numberToElimiate = NumberOfEquations - NumberOfUnknowns;

            var A = Matrix <double> .Build.Sparse(SparseCompressedRowMatrixStorage <double> .OfIndexedEnumerable(NumberOfEquations, NumberOfUnknowns, MatrixAConstants));

            var b = MathNet.Numerics.LinearAlgebra.Vector <double> .Build.DenseOfEnumerable(VectorBValues);

            //Find the least squares solution
            // x  =  (A^T A)^-1 A^T b

            var At      = A.Transpose();
            var AtA     = At.Multiply(A);
            var AtA_inv = AtA.Inverse();

            SolutionOfA = AtA_inv.Multiply(At);

            var result = SolutionOfA.Multiply(b);

            return(result.ToArray());
        }
Ejemplo n.º 11
0
        public void Initialize(Matrix <Complex> matrix)
        {
            this.storage = matrix.Storage as SparseCompressedRowMatrixStorage <Complex>;

            if (storage == null)
            {
                throw new ArgumentException(Resources.MatrixMustBeSparse, "matrix");
            }

            int rowCount = storage.RowCount;

            if (rowCount != storage.ColumnCount)
            {
                throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix");
            }

            this.reverse = true;
            this.omega   = 1.0;
            this.work    = new Complex[rowCount];
            this.diag    = storage.FindDiagonalIndices(true);

            IsInitialized = true;
        }
Ejemplo n.º 12
0
        void TransposeToUnchecked(SparseCompressedRowMatrixStorage <T> target)
        {
            var rowPointers   = target.RowPointers;
            var columnIndices = new List <int>();
            var values        = new List <T>();

            for (int j = 0; j < ColumnCount; j++)
            {
                rowPointers[j] = values.Count;
                var index = j * RowCount;
                for (int i = 0; i < RowCount; i++)
                {
                    if (!Zero.Equals(Data[index + i]))
                    {
                        values.Add(Data[index + i]);
                        columnIndices.Add(i);
                    }
                }
            }

            rowPointers[ColumnCount] = values.Count;
            target.ColumnIndices     = columnIndices.ToArray();
            target.Values            = values.ToArray();
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Initializes a square <see cref="SparseMatrix"/> with all zero's except for ones on the diagonal.
        /// </summary>
        /// <param name="order">the size of the square matrix.</param>
        /// <returns>Identity <c>SparseMatrix</c></returns>
        /// <exception cref="ArgumentException">
        /// If <paramref name="order"/> is less than one.
        /// </exception>
        public static SparseMatrix Identity(int order)
        {
            var m = new SparseCompressedRowMatrixStorage<double>(order, order, 0d)
                {
                    ValueCount = order,
                    Values = new double[order],
                    ColumnIndices = new int[order]
                };

            for (var i = 0; i < order; i++)
            {
                m.Values[i] = 1d;
                m.ColumnIndices[i] = i;
                m.RowPointers[i] = i;
            }

            return new SparseMatrix(m);
        }
Ejemplo n.º 14
0
 internal SparseMatrix(SparseCompressedRowMatrixStorage<double> storage)
     : base(storage)
 {
     _storage = storage;
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Create a new sparse matrix straight from an initialized matrix storage instance.
 /// The storage is used directly without copying.
 /// Intended for advanced scenarios where you're working directly with
 /// storage for performance or interop reasons.
 /// </summary>
 public static Matrix <T> Sparse <T>(SparseCompressedRowMatrixStorage <T> storage)
     where T : struct, IEquatable <T>, IFormattable
 {
     return(Matrix <T> .Build.Sparse(storage));
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Create a new sparse matrix straight from an initialized matrix storage instance.
 /// The storage is used directly without copying.
 /// Intended for advanced scenarios where you're working directly with
 /// storage for performance or interop reasons.
 /// </summary>
 public SparseMatrix(SparseCompressedRowMatrixStorage<float> storage)
     : base(storage)
 {
     _storage = storage;
 }
 /// <summary>
 /// Create a new sparse matrix straight from an initialized matrix storage instance.
 /// The storage is used directly without copying.
 /// Intended for advanced scenarios where you're working directly with
 /// storage for performance or interop reasons.
 /// </summary>
 public SparseMatrix(SparseCompressedRowMatrixStorage<Complex32> storage)
     : base(storage)
 {
     _storage = storage;
 }
 /// <summary>
 ///     Create a new sparse matrix straight from an initialized matrix storage instance.
 ///     The storage is used directly without copying.
 ///     Intended for advanced scenarios where you're working directly with
 ///     storage for performance or interop reasons.
 /// </summary>
 public SparseMatrix(SparseCompressedRowMatrixStorage <double> storage)
     : base(storage)
 {
     _storage = storage;
 }
Ejemplo n.º 19
0
 public override Matrix <double> Sparse(SparseCompressedRowMatrixStorage <double> storage)
 {
     return(new SparseMatrix(storage));
 }
Ejemplo n.º 20
0
 /// <summary>
 ///     Create a new sparse matrix straight from an initialized matrix storage instance.
 ///     The storage is used directly without copying.
 ///     Intended for advanced scenarios where you're working directly with
 ///     storage for performance or interop reasons.
 /// </summary>
 public abstract Matrix <T> Sparse(SparseCompressedRowMatrixStorage <T> storage);
Ejemplo n.º 21
0
        /// <summary>
        /// Creates a matrix that contains the values from the requested sub-matrix.
        /// </summary>
        /// <param name="rowIndex">The row to start copying from.</param>
        /// <param name="rowCount">The number of rows to copy. Must be positive.</param>
        /// <param name="columnIndex">The column to start copying from.</param>
        /// <param name="columnCount">The number of columns to copy. Must be positive.</param>
        /// <returns>The requested sub-matrix.</returns>
        /// <exception cref="ArgumentOutOfRangeException">If: <list><item><paramref name="rowIndex"/> is
        /// negative, or greater than or equal to the number of rows.</item>
        /// <item><paramref name="columnIndex"/> is negative, or greater than or equal to the number 
        /// of columns.</item>
        /// <item><c>(columnIndex + columnLength) &gt;= Columns</c></item>
        /// <item><c>(rowIndex + rowLength) &gt;= Rows</c></item></list></exception>        
        /// <exception cref="ArgumentException">If <paramref name="rowCount"/> or <paramref name="columnCount"/>
        /// is not positive.</exception>
        public override Matrix<float> SubMatrix(int rowIndex, int rowCount, int columnIndex, int columnCount)
        {
            // TODO: if rowIndex == columnIndex, use a diagonal matrix instead of a sparse one

            var storage = new SparseCompressedRowMatrixStorage<float>(rowCount, columnCount, 0f);
            _storage.CopySubMatrixTo(storage, rowIndex, 0, rowCount, columnIndex, 0, columnCount, true);
            return new SparseMatrix(storage);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Initializes a square <see cref="SparseMatrix"/> with all zero's except for ones on the diagonal.
        /// </summary>
        /// <param name="order">the size of the square matrix.</param>
        /// <returns>Identity <c>SparseMatrix</c></returns>
        /// <exception cref="ArgumentException">
        /// If <paramref name="order"/> is less than one.
        /// </exception>
        public static SparseMatrix Identity(int order)
        {
            var mStorage = new SparseCompressedRowMatrixStorage<float>(order, order, 0f)
                {
                    ValueCount = order,
                    Values = new float[order],
                    ColumnIndices = new int[order]
                };

            for (var i = 0; i < order; i++)
            {
                mStorage.Values[i] = 1f;
                mStorage.ColumnIndices[i] = i;
                mStorage.RowPointers[i] = i;
            }

            return new SparseMatrix(mStorage);
        }
        // Apenas um teste, não é pra ser executado pela aplicação

        /*
         * public void GeraImagem()
         * {
         *  String im = ".\\SaidaProcessadaVetor.txt";
         *  StreamReader sr = new StreamReader(im);
         *
         *  double[] temp = new double[3600];
         *  using (sr)
         *  {
         *      string line;
         *      int i = 0;
         *      while ((line = sr.ReadLine()) != null)
         *      {
         *          temp[i] = Double.Parse(line);
         *          i++;
         *      }
         *  }
         *
         *  new GeraBitmap().ToBitmap(temp, im.Replace(".\\", ""));
         * }
         */
        /// <summary>
        /// Separar essa função em 3: lê vetor, lê matriz e CGNE
        /// </summary>
        public void CGNE()
        {
            try
            {
                int rows    = 50816;
                int columns = 3600;

                //var path = HttpContext.Current.Server.MapPath("~/Content/Signals/");
                string hFile       = path + "H-1.txt";
                string gFile       = path + @"Sent\" + this.filaDeProcessos.First();
                double intensidade = Double.Parse(gFile.Split('#').GetValue(1).ToString());

                var M = Matrix <double> .Build;
                var V = Vector <double> .Build;

                StreamReader sr = new StreamReader(gFile);

                var g = V.Dense(rows);

                /*
                 * Separar para função de vetor
                 *
                 */
                try
                {
                    System.Diagnostics.Debug.WriteLine(DateTime.Now);

                    double[] temp = new double[rows];
                    using (sr)
                    {
                        string line;
                        int    i = 0;
                        while ((line = sr.ReadLine()) != null)
                        {
                            if (intensidade != 1)
                            {
                                temp[i] = Double.Parse(line) * intensidade;
                            }
                            else
                            {
                                temp[i] = Double.Parse(line);
                            }
                            i++;
                        }
                    }

                    g = V.Dense(temp);
                    System.Diagnostics.Debug.WriteLine(DateTime.Now + " -> Arquivo g lido");
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e.Message);
                    System.Diagnostics.Debug.WriteLine(e.StackTrace);
                }

                sr.Dispose();
                sr = new StreamReader(hFile);

                /*
                 * Separar para função de matriz
                 *
                 */

                try
                {
                    //var f = CGNECall(hFile, rows, columns, g);
                    System.Diagnostics.Debug.WriteLine(DateTime.Now + " -> começou o CGNE");
                    Matrix <double> h;

                    using (StreamReader reader = new StreamReader(File.OpenRead(hFile)))
                    {
                        string line;
                        int    i = 0;
                        double[,] matrixTemp = new double[rows, columns];
                        while ((line = sr.ReadLine()) != null)
                        {
                            string[] tokens = line.Split(',');
                            int      j      = 0;
                            foreach (var token in tokens)
                            {
                                matrixTemp[i, j] = Double.Parse(token);
                                j++;
                            }
                            i++;
                        }

                        /*
                         * var blasMatrix = new BlasMatrix(reader, columns);
                         * int i = 0;
                         * double[,] matrixTemp = new double[rows, columns];
                         * foreach (var element in blasMatrix.Records)
                         * {
                         *  for (int j = 0; j < columns; j++)
                         *  {
                         *      matrixTemp[i, j] = element.getRow(0, j);
                         *  }
                         *  i++;
                         * }
                         */

                        System.Diagnostics.Debug.WriteLine(DateTime.Now + "Arquivo H lido");
                        sr.DiscardBufferedData();
                        reader.DiscardBufferedData();
                        reader.Dispose();
                        sr.Dispose();
                        h = M.Sparse(SparseCompressedRowMatrixStorage <double> .OfArray(matrixTemp));

                        //h = M.DenseOfArray(matrixTemp);

                        /*
                         * Usando Dense dobra o uso de memória (é feita uma cópia de matrixTemp)
                         *
                         * h = M.Dense(DenseColumnMajorMatrixStorage<double>.OfArray(matrixTemp))
                         *
                         */
                    }

                    sr.Dispose();

                    /*
                     * Aqui são as operações de inicialização
                     */

                    Vector <double> f     = V.Dense(columns);
                    Vector <double> f_aux = V.Dense(columns);

                    //var r = g - h.Multiply(f);
                    var             r = g;
                    Vector <double> r_aux;
                    var             hT = h.Transpose();
                    var             p  = hT.Multiply(r);
                    Vector <double> p_aux;

                    for (int i = 0; i < 15; i++)
                    {
                        var r_T        = r.ToRowMatrix();
                        var alfa_upper = r_T.Multiply(r);
                        var p_T        = p.ToRowMatrix();
                        var alfa_down  = p_T.Multiply(p);

                        var alfa = alfa_upper.PointwiseDivide(alfa_down);

                        double alfa_scalar = alfa.Single();
                        f_aux += f.Add(p.Multiply(alfa_scalar));
                        f      = f_aux;
                        r_aux  = r.Subtract(h.Multiply(alfa_scalar).Multiply(p));

                        var r_auxT     = r_aux.ToRowMatrix();
                        var beta_upper = r_auxT.Multiply(r_aux);

                        var beta = beta_upper.PointwiseDivide(alfa_upper);

                        System.Diagnostics.Debug.WriteLine(DateTime.Now + " -> before matrix 2");

                        double beta_scalar = beta.Single();
                        p_aux = hT.Multiply(r_aux);
                        var pplus = p_aux.Add(p.Multiply(beta_scalar));
                        p = pplus;
                        r = r_aux;

                        System.Diagnostics.Debug.WriteLine(DateTime.Now + $" -> iteração {i}");
                    }

                    string sinal = this.filaDeProcessos.First();
                    //COMENTAR ESSA LINHA PARA OTIMIZAR
                    salvaVetor(sinal, f_aux.ToArray(), @"Processed\");

                    // Remove da fila
                    this.filaDeProcessos.Remove(sinal);

                    new GeraBitmap().ToBitmap(f_aux.ToArray(), sinal, pathImagens);
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e.Message);
                    System.Diagnostics.Debug.WriteLine(e.StackTrace);
                }

                sr.Dispose();
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("The file could not be read:");
                System.Diagnostics.Debug.WriteLine(e.Message);
            }
        }
        /// <summary>
        /// Returns the transpose of this matrix.
        /// </summary>
        /// <returns>The transpose of this matrix.</returns>
        public override Matrix<Complex32> Transpose()
        {
            var rowPointers = _storage.RowPointers;
            var columnIndices = _storage.ColumnIndices;
            var values = _storage.Values;

            var ret = new SparseCompressedRowMatrixStorage<Complex32>(ColumnCount, RowCount)
                {
                    ColumnIndices = new int[_storage.ValueCount],
                    Values = new Complex32[_storage.ValueCount]
                };

            // Do an 'inverse' CopyTo iterate over the rows
            for (var i = 0; i < RowCount; i++)
            {
                var startIndex = rowPointers[i];
                var endIndex = rowPointers[i + 1];

                if (startIndex == endIndex)
                {
                    continue;
                }

                for (var j = startIndex; j < endIndex; j++)
                {
                    ret.At(columnIndices[j], i, values[j]);
                }
            }

            return new SparseMatrix(ret);
        }
 /// <summary>
 ///     Create a new sparse matrix and initialize each value using the provided init function.
 /// </summary>
 public static SparseMatrix Create(int rows, int columns, Func <int, int, double> init)
 {
     return(new SparseMatrix(SparseCompressedRowMatrixStorage <double> .OfInit(rows, columns, init)));
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Returns the transpose of this matrix.
        /// </summary>
        /// <returns>The transpose of this matrix.</returns>
        public override Matrix<float> Transpose()
        {
            var rowPointers = _storage.RowPointers;
            var columnIndices = _storage.ColumnIndices;
            var values = _storage.Values;

            var ret = new SparseCompressedRowMatrixStorage<float>(ColumnCount, RowCount)
                {
                    ColumnIndices = new int[_storage.ValueCount],
                    Values = new float[_storage.ValueCount]
                };

            // Do an 'inverse' CopyTo iterate over the rows
            for (var i = 0; i < RowCount; i++)
            {
                // Get the begin / end index for the current row
                var startIndex = rowPointers[i];
                var endIndex = rowPointers[i + 1];

                // Get the values for the current row
                if (startIndex == endIndex)
                {
                    // Begin and end are equal. There are no values in the row, Move to the next row
                    continue;
                }

                for (var j = startIndex; j < endIndex; j++)
                {
                    ret.At(columnIndices[j], i, values[j]);
                }
            }

            return new SparseMatrix(ret);
        }
        /// <summary>
        /// Initializes a square <see cref="SparseMatrix"/> with all zero's except for ones on the diagonal.
        /// </summary>
        /// <param name="order">the size of the square matrix.</param>
        /// <returns>Identity <c>SparseMatrix</c></returns>
        /// <exception cref="ArgumentException">
        /// If <paramref name="order"/> is less than one.
        /// </exception>
        public static SparseMatrix Identity(int order)
        {
            var storage = new SparseCompressedRowMatrixStorage<Complex32>(order, order)
                {
                    Values = new Complex32[order],
                    ColumnIndices = new int[order]
                };

            for (var i = 0; i < order; i++)
            {
                storage.Values[i] = 1f;
                storage.ColumnIndices[i] = i;
                storage.RowPointers[i] = i;
            }

            storage.RowPointers[order] = order;

            return new SparseMatrix(storage);
        }