示例#1
0
        /// <summary>
        /// Multiplying two matrices
        /// </summary>
        /// <param name="one">MatrixMB - first matrix</param>
        /// <param name="two">MatrixMB - second matrix</param>
        /// <returns>MatrixMB - new Matrix as a result of multiplication</returns>
        /// <remarks>tested according to https://www.youtube.com/watch?v=kuixY2bCc_0 </remarks>
        public static MatrixMB operator *(MatrixMB one, MatrixMB two)
        {
            var mat = new MatrixMB(one.Rows, two.Cols);

            if (one.Cols != two.Rows)
            {
                throw new MatrixException(
                          "Cannot multiply two matrices. Matrix one cols number doesn't match matrix two rows size. " +
                          System.String.Format("Matrix one: {0}x{1}, Matrix two: {2}x{3}", one.Cols, one.Rows, two.Cols, two.Rows));
            }
            else
            {
                for (int i = 0; i < one.Rows; i++)
                {
                    for (int j = 0; j < two.Cols; j++)
                    {
                        for (int k = 0; k < one.Cols; k++)
                        {
                            mat.Data[i][j] += one.Data[i][k] * two.Data[k][j];
                        }
                    }
                }
                return(mat);
            }
        }
示例#2
0
        /// <summary>
        /// Creates matrix filled with zeros
        /// </summary>
        /// <param name="rows">int - matrix rows number</param>
        /// <param name="cols">int - matrix cols number</param>
        /// <returns>MatrixMB</returns>
        public static MatrixMB Zeros(int rows, int cols)
        {
            MatrixMB mat = new MatrixMB(rows, cols);

            mat.FillWithNumber(0);
            return(mat);
        }
示例#3
0
        /// <summary>
        /// Create matrix filled with ones
        /// </summary>
        /// <param name="rows">int - matrix rows number</param>
        /// <param name="cols">int - matrix cols number</param>
        /// <returns>MatrixMB</returns>
        public static MatrixMB Ones(int rows, int cols)
        {
            MatrixMB m = new MatrixMB(rows, cols);

            m.FillWithNumber(1);
            return(m);
        }
示例#4
0
        /// <summary>
        /// Gets specified row
        /// </summary>
        /// <param name="row">int - row index</param>
        /// <returns>MatrixMB</returns>
        public MatrixMB Row(int row)
        {
            MatrixMB mat = new MatrixMB(1, this.Cols);

            mat.Data[0] = Data[row];
            return(mat);
        }
示例#5
0
 /// <summary>
 /// Set column
 /// </summary>
 /// <param name="v">MatrixMB - column vector</param>
 /// <param name="column">int - column index</param>
 public void SetCol(MatrixMB v, int column)
 {
     for (int i = 0; i < Rows; i++)
     {
         Data[i][column] = v.Data[i][0];
     }
 }
示例#6
0
        public void CalculatingLowerUpperMatrices()
        {
            MatrixMB mat = new MatrixMB(2, 2);
            mat.Data[0][0] = 4;
            mat.Data[0][1] = 7;
            mat.Data[1][0] = 2;
            mat.Data[1][1] = 6;

            mat.MakeLU();
            Assert.AreEqual(4, mat.Data[0][0]);
            Assert.AreEqual(7, mat.Data[0][1]);
            Assert.AreEqual(2, mat.Data[1][0]);
            Assert.AreEqual(6, mat.Data[1][1]);

            var L = mat.L;
            Assert.AreEqual(1, L.Data[0][0]);
            Assert.AreEqual(0, L.Data[0][1]);
            Assert.AreEqual(0.5, L.Data[1][0]);
            Assert.AreEqual(1, L.Data[1][1]);

            var U = mat.U;
            Assert.AreEqual(4, U.Data[0][0]);
            Assert.AreEqual(7, U.Data[0][1]);
            Assert.AreEqual(0, U.Data[1][0]);
            Assert.AreEqual(2.5, U.Data[1][1]);
        }
示例#7
0
 /// <summary>
 /// Substraction of two matrices
 /// </summary>
 /// <param name="one">MatrixMB - first matrix</param>
 /// <param name="two">MatrixMB - second matrix</param>
 /// <returns>MatrixMB - new MatrixMB as a result of substraction</returns>
 public static MatrixMB operator -(MatrixMB one, MatrixMB two)
 {
     try
     {
         if (one.Cols == two.Cols && one.Rows == two.Rows)
         {
             var matrix = new MatrixMB(one.Rows, one.Cols);
             int row, col;
             for (row = 0; row < one.Rows; row++)
             {
                 for (col = 0; col < one.Cols; col++)
                 {
                     matrix.Data[row][col] = one.Data[row][col] - two.Data[row][col];
                 }
             }
             return(matrix);
         }
         else
         {
             throw new System.Exception(System.String.Format("Cannot substract two matrices. Matrix size doesn't match. Matrix one: {0}x{1}, Matrix two: {2}x{3}", one.Cols, one.Rows, two.Cols, two.Rows));
         }
     }
     catch (System.Exception ex)
     {
         throw new MatrixException("Matrix addition error", ex);
     }
 }
示例#8
0
        /// <summary>
        /// Function resolves Ax = v in confirmity with solution vector
        /// </summary>
        /// <param name="vector">Matrix - solution vector</param>
        /// <returns>Matrix</returns>
        public MatrixMB SolveWith(MatrixMB vector)
        {
            if (Rows != Cols)
            {
                throw new MatrixException("Solve: Matrix is not square.");
            }
            if (Rows != vector.Rows)
            {
                throw new MatrixException("Solve: wrong number of results in solution vector.");
            }
            if (L == null)
            {
                MakeLU();
            }

            MatrixMB b = new MatrixMB(Rows, 1);

            for (int i = 0; i < Rows; i++)
            {
                b[i, 0] = vector[PermutationVector[i], 0];                              // switch two items in "v" due to permutation matrix
            }
            MatrixMB z = SubsForth(L, b);
            MatrixMB x = SubsBack(U, z);

            return(x);
        }
示例#9
0
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="result">LearnResult - learning result</param>
        /// <param name="chartFilename">string - char filename</param>
        /// <param name="includeDataTable">bool - true id learning data should be included</param>
        public HistoryPDF(LearnByErrorLibrary.LearnResult result, String chartFilename, bool includeDataTable = false)
        {
            this.result        = result;
            this.chartFilename = chartFilename;

            document               = new Document();
            document.Info.Title    = "NBN C# - wynik uczenia sieci neuronowej";
            document.Info.Subject  = "Uczenie sieci neuronowej za pomocą algorytmu NBN C#";
            document.Info.Author   = "Marek Bar 33808";
            document.Info.Comment  = "...ponieważ tylko dobry kod się liczy.";
            document.Info.Keywords = "C#, NBN, neuron, uczenie, sieć, nbn c#";

            DefineStyles(document);
            DefineCover(document);
            DefineInfo(document, result);
            DefineChartArea(document, chartFilename, Path.GetFileNameWithoutExtension(result.Filename));
            DefineWeightsSection(document, result);

            if (includeDataTable)
            {
                MatrixMB mat = MatrixMB.Load(result.Filename);
                AddMatrixTable(document, mat);
            }

            Section section = document.LastSection;

            section.AddPageBreak();//index of pages
            Paragraph paragraph = section.AddParagraph("Spis treści");

            paragraph.Format.Font.Size    = 14;
            paragraph.Format.Font.Bold    = true;
            paragraph.Format.SpaceAfter   = 24;
            paragraph.Format.OutlineLevel = OutlineLevel.Level1;

            paragraph       = section.AddParagraph();
            paragraph.Style = "TOC";

            //first link
            Hyperlink hyperlink = paragraph.AddHyperlink("Informacje na temat sieci neuronowej");

            hyperlink.AddText("\r\n" + "Informacje na temat sieci neuronowej" + "\t");
            hyperlink.AddPageRefField("Informacje na temat sieci neuronowej");

            hyperlink = paragraph.AddHyperlink("Wykres przebiegu uczenia");
            hyperlink.AddText("\r\n" + "Wykres przebiegu uczenia" + "\t");
            hyperlink.AddPageRefField("Wykres przebiegu uczenia");

            hyperlink = paragraph.AddHyperlink("Wagi otrzymane w procesie uczenia");
            hyperlink.AddText("\r\n" + "Wagi otrzymane w procesie uczenia" + "\t");
            hyperlink.AddPageRefField("Wagi otrzymane w procesie uczenia");
            if (includeDataTable)
            {
                hyperlink = paragraph.AddHyperlink("Dane wejściowe");
                hyperlink.AddText("\r\n" + "Dane wejściowe" + "\t");
                hyperlink.AddPageRefField("Dane wejściowe");
            }
        }
示例#10
0
        /// <summary>
        /// Gets specified column
        /// </summary>
        /// <param name="column">int - column index</param>
        /// <returns>MatrixMB</returns>
        public MatrixMB Col(int column)
        {
            MatrixMB matrix = new MatrixMB(Rows, 1);

            for (int i = 0; i < Rows; i++)
            {
                matrix.Data[i][0] = Data[i][column];
            }
            return(matrix);
        }
示例#11
0
        /// <summary>
        /// Convert MatrixMB to VectorVertical
        /// </summary>
        /// <param name="mat">MatrixMB</param>
        /// <returns>VectorVertical</returns>
        public static VectorVertical ToVectorVertical(this MatrixMB mat)
        {
            VectorVertical vv = new VectorVertical(mat.Rows);

            for (int row = 0; row < mat.Cols; row++)
            {
                vv.Data[row][0] = mat.Data[row][0];
            }
            return(vv);
        }
示例#12
0
        /// <summary>
        /// Creates identity matrix
        /// </summary>
        /// <param name="rows">int - matrix rows number</param>
        /// <param name="cols">int - matrix cols number</param>
        /// <returns>MatrixMB</returns>
        public static MatrixMB Identity(int rows, int cols)
        {
            MatrixMB m = new MatrixMB(rows, cols);

            for (int i = 0; i < System.Math.Min(rows, cols); i++)
            {
                m.Data[i][i] = 1;
            }
            return(m);
        }
示例#13
0
        /// <summary>
        /// Convert MatrixMB to VectorHorizontal
        /// </summary>
        /// <param name="mat">MatrixMB</param>
        /// <returns>VectorHorizontal</returns>
        public static VectorHorizontal ToVectorHorizontal(this MatrixMB mat)
        {
            VectorHorizontal vh = new VectorHorizontal(mat.Cols);

            for (int col = 0; col < mat.Cols; col++)
            {
                vh.Data[0][col] = mat.Data[0][col];
            }
            return(vh);
        }
示例#14
0
        /// <summary>
        /// Create new Matrix from specified set of rows
        /// </summary>
        /// <param name="start">int - position of first row in original Matrix</param>
        /// <param name="stop">int - position of last row in original Matrix</param>
        /// <returns>MatrixMB - new matrix from selected rows</returns>
        public MatrixMB CopyRows(int start, int stop)
        {
            MatrixMB m = new MatrixMB(stop - start + 1, this.Cols);

            for (int i = start, c = 0; i <= stop; i++, c++)
            {
                m.Data[c] = this.Data[i];
            }
            return(m);
        }
示例#15
0
        /// <summary>
        /// Convert MatrixMB to Weights
        /// </summary>
        /// <param name="mat">MatrixMB</param>
        /// <returns>Weights</returns>
        public static Weights ToWeights(this MatrixMB mat)
        {
            Weights weights = new Weights(mat.Cols);

            for (int col = 0; col < mat.Cols; col++)
            {
                weights.Data[0][col] = mat.Data[0][col];
            }
            return(weights);
        }
示例#16
0
        public MatrixMB SolveEquatation(MatrixMB other)
        {
            return(this.Inverted * other);

            /*Accord version - the most accurate*/
            var m = Data.ToMultidimensionalArray(Rows, Cols).Solve(other.Data.ToMultidimensionalArray(other.Rows, other.Cols));
            //var m = Data.ToMultidimensionalArray().Inverse().Multiply(other.Data.ToMultidimensionalArray());
            MatrixMB tmp = new MatrixMB(m.GetLength(0), m.GetLength(1));

            tmp.Data = m.ToJaggedArray(tmp.Rows, tmp.Cols);
            return(tmp);
        }
示例#17
0
        /// <summary>
        /// Matrix eye - with ones on diagonal
        /// </summary>
        /// <param name="size">int - matrix size</param>
        /// <returns>MatrixMB</returns>
        public static MatrixMB Eye(int size)
        {
            MatrixMB m = new MatrixMB(size, size);

            for (int i = 0; i < size; i++)
            {
                for (int j = 0; j < size; j++)
                {
                    m.Data[i][j] = i == j ? 1 : 0;
                }
            }
            return(m);
        }
示例#18
0
        /// <summary>
        /// Convert MatrixMB to Output
        /// </summary>
        /// <param name="mat">MatrixMB</param>
        /// <returns>Output</returns>
        public static Output ToOutput(this MatrixMB mat)
        {
            Output output = new Output(mat.Rows, mat.Cols);

            for (int col = 0; col < mat.Cols; col++)
            {
                for (int row = 0; row < mat.Rows; row++)
                {
                    output.Data[row][col] = mat.Data[row][col];
                }
            }
            return(output);
        }
示例#19
0
        /// <summary>
        /// Convert MatrixMB to Input
        /// </summary>
        /// <param name="mat">MatrixMB</param>
        /// <returns>Input</returns>
        public static Input ToInput(this MatrixMB mat)
        {
            Input input = new Input(mat.Rows, mat.Cols);

            for (int col = 0; col < mat.Cols; col++)
            {
                for (int row = 0; row < mat.Rows; row++)
                {
                    input.Data[row][col] = mat.Data[row][col];
                }
            }
            return(input);
        }
示例#20
0
        /// <summary>
        /// Create new matrix from specified set of columns
        /// </summary>
        /// <param name="start">int - position of first column</param>
        /// <param name="stop">int - position of last column</param>
        /// <returns>MatrixMB</returns>
        public MatrixMB CopyColumns(int start, int stop)
        {
            MatrixMB m = new MatrixMB(this.Rows, stop - start + 1);

            for (int i = 0; i < m.Rows; i++)
            {
                for (int j = start, c = 0; j <= stop; j++, c++)
                {
                    m.Data[i][c] = this.Data[i][j];
                }
            }
            return(m);
        }
示例#21
0
        /// <summary>
        /// Get matrix data nice format
        /// </summary>
        /// <param name="mat">MatrixMB</param>
        /// <returns>string - matrix text representation</returns>
        public static String NiceMatrixFormat(this MatrixMB mat)
        {
            string s = "";

            for (int i = 0; i < mat.Rows; i++)
            {
                for (int j = 0; j < mat.Cols; j++)
                {
                    s += String.Format("{0,5:0.00}", mat.Data[i][j]) + " ";
                }
                s += "\r\n";
            }
            return(s);
        }
示例#22
0
        /// <summary>
        /// Creates random filled matrix
        /// </summary>
        /// <param name="rows">int - matrix rows numer</param>
        /// <param name="cols">int - matrix cols number</param>
        /// <param name="dispersion">int - randomize range</param>
        /// <returns>MatrixMB</returns>
        public static MatrixMB Random(int rows, int cols, int dispersion)
        {
            System.Random random = new System.Random();
            MatrixMB      matrix = new MatrixMB(rows, cols);
            int           max    = dispersion;
            int           min    = -dispersion;

            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < cols; j++)
                {
                    matrix.Data[i][j] = random.NextDouble() * (max - min) + min;
                }
            }
            return(matrix);
        }
示例#23
0
        /// <summary>
        /// Convert Matrix to string representation
        /// </summary>
        /// <param name="mat">MatrixMB</param>
        /// <returns>String</returns>
        public static String MatrixToString(this MatrixMB mat)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            for (var row = 0; row < mat.Rows; row++)
            {
                for (var col = 0; col < mat.Cols; col++)
                {
                    sb.Append(mat.Data[row][col]);
                    sb.Append(",    ");
                }
                sb.AppendLine();
            }

            return(sb.ToString());
        }
示例#24
0
        /// <summary>
        /// Check if matrix is filled with zeros only
        /// </summary>
        /// <param name="mat">MatrixMB</param>
        /// <returns>bool</returns>
        public static bool IsZeroed(this MatrixMB mat)
        {
            int counter = mat.Rows * mat.Cols;

            for (int r = 0; r < mat.Rows; r++)
            {
                for (int c = 0; c < mat.Cols; c++)
                {
                    if (mat.Data[r][c] == 0)
                    {
                        counter--;
                    }
                }
            }

            return(counter == 0);
        }
示例#25
0
        public void DivideMatrixByMatrix()
        {
            MatrixMB mat = new MatrixMB(2, 2);
            mat.Data[0][0] = 4;
            mat.Data[0][1] = 7;
            mat.Data[1][0] = 2;
            mat.Data[1][1] = 6;

            MatrixMB b = new MatrixMB(2, 1);
            b[0, 0] = 1;
            b[1, 0] = 2;

            var divided = mat.Inverted * b;

            Assert.AreEqual(-0.8, Math.Round(divided[0, 0], 4));
            Assert.AreEqual(0.6, Math.Round(divided[1, 0], 4));
        }
示例#26
0
        /// <summary>
        /// Execute operation on each value in matrix
        /// </summary>
        /// <param name="operation">MatrixValueOperation - operation type</param>
        /// <param name="number">double - value</param>
        /// <returns>MatrixMB</returns>
        public MatrixMB OperationNew(MatrixAction operation, double number)
        {
            MatrixMB mat = this.Copy();

            switch (operation)
            {
            case MatrixAction.Add:
            {
                mat.AddNumber(number);
            } break;

            case MatrixAction.Substract:
            {
                mat.SubNumber(number);
            } break;

            case MatrixAction.Multiply:
            {
                mat.MulByNumber(number);
            } break;

            case MatrixAction.Divide:
            {
                mat.DivByNumber(number);
            } break;

            case MatrixAction.Power:
            {
                mat.PowerByNumber(number);
            } break;

            case MatrixAction.Sqrt:
            {
                mat.SqrtFromNumber();
            } break;

            case MatrixAction.Abs:
            {
                mat.AbsoluteNumber();
            } break;
            }
            return(mat);
        }
示例#27
0
 /// <summary>
 /// Check if object is Matrix - equal are Matrix and its derivates
 /// </summary>
 /// <param name="obj">object - some object</param>
 /// <returns>bool - true - same, false - sth. else</returns>
 public override bool Equals(object obj)
 {
     if (obj is MatrixMB)
     {
         try
         {
             MatrixMB m = (MatrixMB)obj;
             return(this.Cols == m.Cols && this.Rows == m.Rows);
         }
         catch
         {
             return(false);
         }
     }
     else
     {
         return(false);
     }
 }
示例#28
0
        /// <summary>
        /// Function solves Ax = b for A as an upper triangular matrix
        /// </summary>
        /// <param name="A">MatrixMB - upper triangular matrix</param>
        /// <param name="b">MatrixMB</param>
        /// <returns>MatrixMB</returns>
        public static MatrixMB SubsBack(MatrixMB A, MatrixMB b)
        {
            if (A.L == null)
            {
                A.MakeLU();
            }
            int      n = A.Rows;
            MatrixMB x = new MatrixMB(n, 1);

            for (int i = n - 1; i > -1; i--)
            {
                x[i, 0] = b[i, 0];
                for (int j = n - 1; j > i; j--)
                {
                    x[i, 0] -= A[i, j] * x[j, 0];
                }
                x[i, 0] = x[i, 0] / A[i, i];
            }
            return(x);
        }
示例#29
0
        /// <summary>
        /// Function solves Ax = b for A as a lower triangular matrix
        /// </summary>
        /// <param name="A">MatrixMB - lower triangular matrix</param>
        /// <param name="b">MatrixMB</param>
        /// <returns>MatrixMB</returns>
        public static MatrixMB SubsForth(MatrixMB A, MatrixMB b)
        {
            if (A.L == null)
            {
                A.MakeLU();
            }
            int      n = A.Rows;
            MatrixMB x = new MatrixMB(n, 1);

            for (int i = 0; i < n; i++)
            {
                x[i, 0] = b[i, 0];
                for (int j = 0; j < i; j++)
                {
                    x[i, 0] -= A[i, j] * x[j, 0];
                }
                x[i, 0] = x[i, 0] / A[i, i];
            }
            return(x);
        }
示例#30
0
        /// <summary>
        /// Function resolves Ax = v in confirmity with solution vector 
        /// </summary>
        /// <param name="vector">Matrix - solution vector</param>
        /// <returns>Matrix</returns>
        public MatrixMB SolveWith(MatrixMB vector)
        {
            if (Rows != Cols) throw new MatrixException("Solve: Matrix is not square.");
            if (Rows != vector.Rows) throw new MatrixException("Solve: wrong number of results in solution vector.");
            if (L == null) MakeLU();

            MatrixMB b = new MatrixMB(Rows, 1);
            for (int i = 0; i < Rows; i++) b[i, 0] = vector[PermutationVector[i], 0];   // switch two items in "v" due to permutation matrix

            MatrixMB z = SubsForth(L, b);
            MatrixMB x = SubsBack(U, z);

            return x;
        }
示例#31
0
 /// <summary>
 /// Multiplying two matrices
 /// </summary>
 /// <param name="one">MatrixMB - first matrix</param>
 /// <param name="two">MatrixMB - second matrix</param>
 /// <returns>MatrixMB - new Matrix as a result of multiplication</returns>
 /// <remarks>tested according to https://www.youtube.com/watch?v=kuixY2bCc_0 </remarks>
 public static MatrixMB operator *(MatrixMB one, MatrixMB two)
 {
     var mat = new MatrixMB(one.Rows, two.Cols);
     if (one.Cols != two.Rows)
     {
         throw new MatrixException(
             "Cannot multiply two matrices. Matrix one cols number doesn't match matrix two rows size. " +
             System.String.Format("Matrix one: {0}x{1}, Matrix two: {2}x{3}", one.Cols, one.Rows, two.Cols, two.Rows));
     }
     else
     {
         for (int i = 0; i < one.Rows; i++)
         {
             for (int j = 0; j < two.Cols; j++)
             {
                 for (int k = 0; k < one.Cols; k++)
                 {
                     mat.Data[i][j] += one.Data[i][k] * two.Data[k][j];
                 }
             }
         }
         return mat;
     }
 }
示例#32
0
 /// <summary>
 /// Set column
 /// </summary>
 /// <param name="v">MatrixMB - column vector</param>
 /// <param name="column">int - column index</param>
 public void SetCol(MatrixMB v, int column)
 {
     for (int i = 0; i < Rows; i++)
     {
         Data[i][column] = v.Data[i][0];
     }
 }
示例#33
0
        public MatrixMB SolveEquatation(MatrixMB other)
        {
            return this.Inverted * other;
            /*Accord version - the most accurate*/
            var m = Data.ToMultidimensionalArray(Rows,Cols).Solve(other.Data.ToMultidimensionalArray(other.Rows,other.Cols));
            //var m = Data.ToMultidimensionalArray().Inverse().Multiply(other.Data.ToMultidimensionalArray());
            MatrixMB tmp = new MatrixMB(m.GetLength(0), m.GetLength(1));

            tmp.Data = m.ToJaggedArray(tmp.Rows, tmp.Cols);
            return tmp;
        }
示例#34
0
 /// <summary>
 /// Creates random filled matrix
 /// </summary>
 /// <param name="rows">int - matrix rows numer</param>
 /// <param name="cols">int - matrix cols number</param>
 /// <param name="dispersion">int - randomize range</param>
 /// <returns>MatrixMB</returns>
 public static MatrixMB Random(int rows, int cols, int dispersion)
 {
     System.Random random = new System.Random();
     MatrixMB matrix = new MatrixMB(rows, cols);
     int max = dispersion;
     int min = -dispersion;
     for (int i = 0; i < rows; i++)
     {
         for (int j = 0; j < cols; j++)
         {
             matrix.Data[i][j] = random.NextDouble() * (max - min) + min;
         }
     }
     return matrix;
 }
示例#35
0
 /// <summary>
 /// Create new Matrix from specified set of rows
 /// </summary>
 /// <param name="start">int - position of first row in original Matrix</param>
 /// <param name="stop">int - position of last row in original Matrix</param>
 /// <returns>MatrixMB - new matrix from selected rows</returns>
 public MatrixMB CopyRows(int start, int stop)
 {
     MatrixMB m = new MatrixMB(stop - start + 1, this.Cols);
     for (int i = start, c = 0; i <= stop; i++, c++)
     {
         m.Data[c] = this.Data[i];
     }
     return m;
 }
示例#36
0
 /// <summary>
 /// Creates identity matrix
 /// </summary>
 /// <param name="rows">int - matrix rows number</param>
 /// <param name="cols">int - matrix cols number</param>
 /// <returns>MatrixMB</returns>
 public static MatrixMB Identity(int rows, int cols)
 {
     MatrixMB m = new MatrixMB(rows, cols);
     for (int i = 0; i < System.Math.Min(rows, cols); i++)
     {
         m.Data[i][i] = 1;
     }
     return m;
 }
示例#37
0
        /// <summary>
        /// Loads matrix from file
        /// </summary>
        /// <param name="filename">String - filename</param>
        /// <returns>MatrixMB</returns>
        public static MatrixMB Load(System.String filename)
        {
            char splitter = ',';
            try
            {
                if (!System.IO.File.Exists(filename) || filename == "")
                {
                    throw new System.Exception("Cannot find file: " + filename);
                }

                string text;
                using (System.IO.StreamReader streamReader = new System.IO.StreamReader(filename, System.Text.Encoding.UTF8))
                {
                    text = streamReader.ReadToEnd();
                }

                var lines = text.Split(new char[] { '\r', '\n' });
                var rows = lines.Length;
                foreach (var line in lines)
                {
                    if (line == "") rows--;
                }
                string[] splitted = lines[0].Split(new char[] { splitter });
                if (splitted.Length == 1)
                {
                    splitter = ' ';
                    splitted = lines[0].Split(new char[] { splitter });
                }
                if (splitted.Length == 1)
                {
                    splitter = ';';
                    splitted = lines[0].Split(new char[] { splitter });
                }
                if (splitted.Length == 1)
                {
                    splitter = '\t';
                    splitted = lines[0].Split(new char[] { splitter });
                }
                var cols = splitted.Length;
                for (int i = 0; i < splitted.Length; i++) { if (splitted[i] == "") cols--; }

                MatrixMB m = new MatrixMB(rows, cols);

                var row = 0;
                foreach (var line in lines)
                {
                    if (line != "")
                    {
                        var data = line.TrimEnd(new char[] { ',', ' ' }).Split(new char[] { splitter });
                        var col = 0;
                        foreach (var number in data)
                        {
                            if (number != "")
                            {
                                m.Data[row][col] = double.Parse(number.Replace('.', ',').Trim());
                                col++;
                            }
                        }
                        row++;
                    }
                }

                m.Name = System.IO.Path.GetFileNameWithoutExtension(filename);
                return m;
            }
            catch (System.Exception ex)
            {
                throw new MatrixException("Loading matrix from file error (splitter: " + splitter.ToString() + "). File: " + filename, ex);
            }
        }
示例#38
0
        public void TransposeMatrix()
        {
            MatrixMB mat = new MatrixMB(3, 3);
            mat[0, 0] = 1;
            mat[0, 1] = 2;
            mat[0, 2] = 3;
            mat[1, 0] = 4;
            mat[1, 1] = 5;
            mat[1, 2] = 6;
            mat[2, 0] = 7;
            mat[2, 1] = 8;
            mat[2, 2] = 9;

            var t = mat.Transposed;
            Assert.AreEqual(1, t[0, 0]);
            Assert.AreEqual(2, t[1, 0]);
            Assert.AreEqual(3, t[2, 0]);

            Assert.AreEqual(4, t[0, 1]);
            Assert.AreEqual(5, t[1, 1]);
            Assert.AreEqual(6, t[2, 1]);

            Assert.AreEqual(7, t[0, 2]);
            Assert.AreEqual(8, t[1, 2]);
            Assert.AreEqual(9, t[2, 2]);
        }
示例#39
0
 /// <summary>
 /// Substraction of two matrices
 /// </summary>
 /// <param name="one">MatrixMB - first matrix</param>
 /// <param name="two">MatrixMB - second matrix</param>
 /// <returns>MatrixMB - new MatrixMB as a result of substraction</returns>
 public static MatrixMB operator -(MatrixMB one, MatrixMB two)
 {
     try
     {
         if (one.Cols == two.Cols && one.Rows == two.Rows)
         {
             var matrix = new MatrixMB(one.Rows, one.Cols);
             int row, col;
             for (row = 0; row < one.Rows; row++)
             {
                 for (col = 0; col < one.Cols; col++)
                 {
                     matrix.Data[row][col] = one.Data[row][col] - two.Data[row][col];
                 }
             }
             return matrix;
         }
         else
         {
             throw new System.Exception(System.String.Format("Cannot substract two matrices. Matrix size doesn't match. Matrix one: {0}x{1}, Matrix two: {2}x{3}", one.Cols, one.Rows, two.Cols, two.Rows));
         }
     }
     catch (System.Exception ex)
     {
         throw new MatrixException("Matrix addition error", ex);
     }
 }
示例#40
0
 public void SumTwoMatrices()
 {
     MatrixMB mat1 = new MatrixMB(5, 5);
     MatrixMB mat2 = new MatrixMB(5, 5);
     mat1.FillWithNumber(1);
     mat2.FillWithNumber(2);
     var mat = mat1 + mat2;
     Assert.AreEqual(75, mat.SumAllValues());
 }
示例#41
0
 public void SubstractTwoMatrices()
 {
     MatrixMB mat1 = new MatrixMB(5, 5);
     MatrixMB mat2 = new MatrixMB(5, 5);
     mat1.FillWithNumber(4);
     mat2.FillWithNumber(2);
     var mat = mat1 - mat2;
     Assert.AreEqual(50, mat.SumAllValues());
 }
示例#42
0
        /// <summary>
        /// Calculate lower and upper traingular matrix - this is LU decomposition of matrix
        /// </summary>
        public void MakeLU()
        {
            //try
            //{
            //    if (!IsSquare) throw new MatrixException("The matrix is not square!");
            //    var lu = new Accord.Math.Decompositions.LuDecomposition(this.Data.ToMultidimensionalArray(Rows, Cols));
            //    var l = lu.LowerTriangularFactor;
            //    var u = lu.UpperTriangularFactor;
            //    L = new MatrixMB(l.GetLength(0), l.GetLength(1), l.ToJaggedArray(l.GetLength(0), l.GetLength(1)));
            //    U = new MatrixMB(u.GetLength(0), u.GetLength(1), u.ToJaggedArray(u.GetLength(0), u.GetLength(1)));
            //    PermutationVector = lu.PivotPermutationVector;
            //}
            //catch (System.Exception ex)
            //{
            //    throw new System.Exception(ex.Message);
            //}

            //return;
            //--------------------------------------------------------------------

            if (!IsSquare)
            {
                throw new MatrixException("The matrix is not square!");
            }
            L = MatrixMB.Identity(Rows, Cols);
            U = this.Copy();

            PermutationVector = new int[Rows];
            for (int i = 0; i < Rows; i++)
            {
                PermutationVector[i] = i;
            }

            double p = 0;
            double pom2;
            int    k0   = 0;
            int    pom1 = 0;

            for (int k = 0; k < Rows - 1; k++)
            {
                p = 0;
                for (int i = k; i < Rows; i++)      // find the row with the biggest pivot
                {
                    if (System.Math.Abs(U.Data[i][k]) > p)
                    {
                        p  = System.Math.Abs(U.Data[i][k]);
                        k0 = i;
                    }
                }
                if (p == 0)
                {
                    throw new MatrixException("Making LU: matrix is singular!");
                }
                pom1 = PermutationVector[k];
                PermutationVector[k]  = PermutationVector[k0];
                PermutationVector[k0] = pom1;

                for (int i = 0; i < k; i++)
                {
                    pom2          = L.Data[k][i];
                    L.Data[k][i]  = L.Data[k0][i];
                    L.Data[k0][i] = pom2;
                }

                if (k != k0)
                {
                    detOfP *= -1;
                }

                for (int i = 0; i < Rows; i++)
                {
                    pom2          = U.Data[k][i];
                    U.Data[k][i]  = U.Data[k0][i];
                    U.Data[k0][i] = pom2;
                }

                for (int i = k + 1; i < Rows; i++)
                {
                    L.Data[i][k] = U.Data[i][k] / U.Data[k][k];
                    for (int j = k; j < Rows; j++)
                    {
                        U.Data[i][j] -= L.Data[i][k] * U.Data[k][j];
                    }
                }
            }
        }
示例#43
0
        /// <summary>
        /// Function solves Ax = b for A as a lower triangular matrix
        /// </summary>
        /// <param name="A">MatrixMB - lower triangular matrix</param>
        /// <param name="b">MatrixMB</param>
        /// <returns>MatrixMB</returns>
        public static MatrixMB SubsForth(MatrixMB A, MatrixMB b)
        {
            if (A.L == null) A.MakeLU();
            int n = A.Rows;
            MatrixMB x = new MatrixMB(n, 1);

            for (int i = 0; i < n; i++)
            {
                x[i, 0] = b[i, 0];
                for (int j = 0; j < i; j++) x[i, 0] -= A[i, j] * x[j, 0];
                x[i, 0] = x[i, 0] / A[i, i];
            }
            return x;
        }
示例#44
0
        /// <summary>
        /// Initialize NBN with data from specified file
        /// </summary>
        /// <param name="filename">String - filename</param>
        /// <returns>bool - success flag</returns>
        private bool loadInputData(String filename)
        {
            try
            {
                if (!File.Exists(filename))
                {
                    throw new NeuralNetworkError(String.Format(Properties.Settings.Default.NBN1, filename));
                }

                try
                {
                    var data = MatrixMB.Load(filename);

                    if (MatLabCompareDataFolder.Length > 0)
                    {
                        //data from matlab are normalized
                        string name = Path.GetFileNameWithoutExtension(Directory.GetFiles(MatLabCompareDataFolder, "*.dat")[0]);
                        inputLearn  = MatrixMB.Load(string.Format("{0}\\uczenie_wejscie_{1}.txt", MatLabCompareDataFolder, name)).ToInput();
                        inputTest   = MatrixMB.Load(string.Format("{0}\\testowanie_wejscie_{1}.txt", MatLabCompareDataFolder, name)).ToInput();
                        outputLearn = MatrixMB.Load(string.Format("{0}\\uczenie_wyjscie_{1}.txt", MatLabCompareDataFolder, name)).ToOutput();
                        outputTest  = MatrixMB.Load(string.Format("{0}\\testowanie_wyjscie_{1}.txt", MatLabCompareDataFolder, name)).ToOutput();
                    }
                    else
                    {
                        input = data.CopyColumnsWithoutLast().ToInput();
                        input.Normalize();

                        output = data.LastColumn.ToOutput();
                        output.Normalize();

                        if (IsClassification)
                        {
                            int Tnp = data.Rows;
                            inputLearn  = input.CopyRows(Tnp - 1).ToInput();
                            inputTest   = input.CopyRows(Tnp - 1).ToInput();
                            outputLearn = output.CopyRows(Tnp - 1).ToOutput();
                            outputTest  = output.CopyRows(Tnp - 1).ToOutput();
                        }
                        else
                        {
                            int[] ind = data.Rows.RandomPermutation();
                            int   Tnp = Math.Round(data.Rows * 0.7).ToInt();

                            inputTest   = input.CopyRows(Tnp, input.Rows - 1).ToInput();
                            inputLearn  = input.CopyRows(Tnp - 1).ToInput();
                            outputTest  = output.CopyRows(Tnp, input.Rows - 1).ToOutput();
                            outputLearn = output.CopyRows(Tnp - 1).ToOutput();
                        }
                    }
                    try
                    {
                        if (IsResearchMode)//export for matlab - out of use
                        {
                            string   name = Path.GetFileNameWithoutExtension(filename);
                            DateTime d    = DateTime.Now;

                            string dir = String.Format("{0}\\Executed research\\{1}\\{2}_{3}_{4}_{5}_{6}_{7}",
                                                       Path.GetDirectoryName(filename), name,
                                                       d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second);

                            if (!Directory.Exists(dir))
                            {
                                Directory.CreateDirectory(dir);
                            }

                            extractionFolder  = dir;
                            _reasearch_folder = dir;
                            string learn_input     = String.Format("{0}\\{1}_learn_input.dat", dir, name);
                            string test_input      = String.Format("{0}\\{1}_test_input.dat", dir, name);
                            string learn_output    = String.Format("{0}\\{1}_learn_output.dat", dir, name);
                            string test_output     = String.Format("{0}\\{1}_test_output.dat", dir, name);
                            string initialWweights = String.Format("{0}\\{1}_initial_weights.dat", dir, name);

                            inputTest.Store(test_input);
                            inputLearn.Store(learn_input);
                            outputTest.Store(test_output);
                            outputLearn.Store(learn_output);
                        }
                    }
                    catch (Exception)
                    { }
                }
                catch (Exception iex)
                {
                    throw new NeuralNetworkError(String.Format(Properties.Settings.Default.NBN2, filename), iex);
                }
                return(true);
            }
            catch (Exception ex)
            {
                updateErrorNBN(ex);
                return(false);
            }
        }
示例#45
0
 /// <summary>
 /// Matrix eye - with ones on diagonal
 /// </summary>
 /// <param name="size">int - matrix size</param>
 /// <returns>MatrixMB</returns>
 public static MatrixMB Eye(int size)
 {
     MatrixMB m = new MatrixMB(size, size);
     for (int i = 0; i < size; i++)
     {
         for (int j = 0; j < size; j++)
         {
             m.Data[i][j] = i == j ? 1 : 0;
         }
     }
     return m;
 }
示例#46
0
 public void Creation()
 {
     MatrixMB mat = new MatrixMB(5, 5);
     mat.FillWithNumber(1);
     Assert.AreEqual(25, mat.SumAllValues());
 }
示例#47
0
 /// <summary>
 /// Left division
 /// </summary>
 /// <param name="one">MatrixMB - first matrix</param>
 /// <param name="two">MatrixMB - second matrix</param>
 /// <returns>MatrixMB - divided</returns>
 public static MatrixMB Left(ref MatrixMB one, ref MatrixMB two)
 {
     return one.Inverted * two;
 }
示例#48
0
        public void Test__WeightCorrectionCalculation()
        {
            //this is just check of calculation: ((hessian+mu*I)\gradient)' if is correct
            /*
             >> %((hessian+mu*I)\gradient)'
            >> hessian = [1 2; 3 4]
            hessian =

             1     2
             3     4
            >> mu = 2
            mu =
             2
            >> I = eye(2)
            I =
             1     0
             0     1
            >> gradient=[1;2]
            gradient =
             1
             2
            >> res=((hessian+mu*I)\gradient)'
            res =
            0.1667    0.2500
             */
            var hessian = new MatrixMB(2, 2);
            //no matter if its hessian result or not
            hessian[0, 0] = 1;
            hessian[0, 1] = 2;
            hessian[1, 0] = 3;
            hessian[1, 1] = 4;

            double mu = 2;

            var I = MatrixMB.Eye(2);

            var gradient = new MatrixMB(2, 1);
            gradient[0, 0] = 1;
            gradient[1, 0] = 2;

            // var diff = ((hessian.HessianMat + (I * setting.MU)).Inverted * hessian.GradientMat).Transposed;
            var add = hessian + I * mu;
            var inv = add.Inverted;
            var div = inv * gradient;
            var res = div.Transposed;

            Assert.AreEqual(1, res.Rows);
            Assert.AreEqual(2, res.Cols);
            Assert.AreEqual(0.1667, Math.Round(res[0, 0],4));
            Assert.AreEqual(0.25, Math.Round(res[0, 1],4));
        }
示例#49
0
 /// <summary>
 /// Create matrix filled with ones
 /// </summary>
 /// <param name="rows">int - matrix rows number</param>
 /// <param name="cols">int - matrix cols number</param>
 /// <returns>MatrixMB</returns>
 public static MatrixMB Ones(int rows, int cols)
 {
     MatrixMB m = new MatrixMB(rows, cols);
     m.FillWithNumber(1);
     return m;
 }
示例#50
0
 /// <summary>
 /// Gets specified row
 /// </summary>
 /// <param name="row">int - row index</param>
 /// <returns>MatrixMB</returns>
 public MatrixMB Row(int row)
 {
     MatrixMB mat = new MatrixMB(1, this.Cols);
     mat.Data[0] = Data[row];
     return mat;
 }
示例#51
0
        /// <summary>
        /// Function solves Ax = b for A as an upper triangular matrix
        /// </summary>
        /// <param name="A">MatrixMB - upper triangular matrix</param>
        /// <param name="b">MatrixMB</param>
        /// <returns>MatrixMB</returns>
        public static MatrixMB SubsBack(MatrixMB A, MatrixMB b)
        {
            if (A.L == null) A.MakeLU();
            int n = A.Rows;
            MatrixMB x = new MatrixMB(n, 1);

            for (int i = n - 1; i > -1; i--)
            {
                x[i, 0] = b[i, 0];
                for (int j = n - 1; j > i; j--) x[i, 0] -= A[i, j] * x[j, 0];
                x[i, 0] = x[i, 0] / A[i, i];
            }
            return x;
        }
示例#52
0
 /// <summary>
 /// Gets specified column
 /// </summary>
 /// <param name="column">int - column index</param>
 /// <returns>MatrixMB</returns>
 public MatrixMB Col(int column)
 {
     MatrixMB matrix = new MatrixMB(Rows, 1);
     for (int i = 0; i < Rows; i++)
     {
         matrix.Data[i][0] = Data[i][column];
     }
     return matrix;
 }
示例#53
0
 /// <summary>
 /// Creates matrix filled with zeros
 /// </summary>
 /// <param name="rows">int - matrix rows number</param>
 /// <param name="cols">int - matrix cols number</param>
 /// <returns>MatrixMB</returns>
 public static MatrixMB Zeros(int rows, int cols)
 {
     MatrixMB mat = new MatrixMB(rows, cols);
     mat.FillWithNumber(0);
     return mat;
 }
示例#54
0
        public void MultiplyTwoMatrices()
        {
            MatrixMB mat1 = new MatrixMB(2, 3);
            mat1.Data[0][0] = 1;
            mat1.Data[0][1] = 2;
            mat1.Data[0][2] = 3;
            mat1.Data[1][0] = 4;
            mat1.Data[1][1] = 5;
            mat1.Data[1][2] = 6;

            MatrixMB mat2 = new MatrixMB(3, 2);
            mat2.Data[0][0] = 7;
            mat2.Data[0][1] = 8;
            mat2.Data[1][0] = 9;
            mat2.Data[1][1] = 10;
            mat2.Data[2][0] = 11;
            mat2.Data[2][1] = 12;

            var mat = mat1 * mat2;
            Assert.AreEqual(58, mat[0,0]);
            Assert.AreEqual(64, mat[0, 1]);
            Assert.AreEqual(139,mat[1, 0]);
            Assert.AreEqual(154, mat[1, 1]);
        }
示例#55
0
 /// <summary>
 /// Create new matrix from specified set of columns
 /// </summary>
 /// <param name="start">int - position of first column</param>
 /// <param name="stop">int - position of last column</param>
 /// <returns>MatrixMB</returns>
 public MatrixMB CopyColumns(int start, int stop)
 {
     MatrixMB m = new MatrixMB(this.Rows, stop - start + 1);
     for (int i = 0; i < m.Rows; i++)
     {
         for (int j = start, c = 0; j <= stop; j++, c++)
         {
             m.Data[i][c] = this.Data[i][j];
         }
     }
     return m;
 }
示例#56
0
        public void FillMatrix()
        {
            MatrixMB mat = new MatrixMB(3, 3);
            mat.Data[0][0] = 1;
            mat.Data[0][1] = 2;
            mat.Data[0][2] = 3;

            mat.Data[1][0] = 4;
            mat.Data[1][1] = 5;
            mat.Data[1][2] = 6;

            mat.Data[2][0] = 7;
            mat.Data[2][1] = 8;
            mat.Data[2][2] = 9;
            Assert.AreEqual(1, mat[0, 0]);
            Assert.AreEqual(2, mat[0, 1]);
            Assert.AreEqual(3, mat[0, 2]);

            Assert.AreEqual(4, mat[1, 0]);
            Assert.AreEqual(5, mat[1, 1]);
            Assert.AreEqual(6, mat[1, 2]);

            Assert.AreEqual(7, mat[2, 0]);
            Assert.AreEqual(8, mat[2, 1]);
            Assert.AreEqual(9, mat[2, 2]);
        }
示例#57
0
        /// <summary>
        /// Calculate lower and upper traingular matrix - this is LU decomposition of matrix
        /// </summary>
        public void MakeLU()
        {
            //try
            //{
            //    if (!IsSquare) throw new MatrixException("The matrix is not square!");
            //    var lu = new Accord.Math.Decompositions.LuDecomposition(this.Data.ToMultidimensionalArray(Rows, Cols));
            //    var l = lu.LowerTriangularFactor;
            //    var u = lu.UpperTriangularFactor;
            //    L = new MatrixMB(l.GetLength(0), l.GetLength(1), l.ToJaggedArray(l.GetLength(0), l.GetLength(1)));
            //    U = new MatrixMB(u.GetLength(0), u.GetLength(1), u.ToJaggedArray(u.GetLength(0), u.GetLength(1)));
            //    PermutationVector = lu.PivotPermutationVector;
            //}
            //catch (System.Exception ex)
            //{
            //    throw new System.Exception(ex.Message);
            //}

            //return;
            //--------------------------------------------------------------------

            if (!IsSquare) throw new MatrixException("The matrix is not square!");
            L = MatrixMB.Identity(Rows, Cols);
            U = this.Copy();

            PermutationVector = new int[Rows];
            for (int i = 0; i < Rows; i++) PermutationVector[i] = i;

            double p = 0;
            double pom2;
            int k0 = 0;
            int pom1 = 0;

            for (int k = 0; k < Rows - 1; k++)
            {
                p = 0;
                for (int i = k; i < Rows; i++)      // find the row with the biggest pivot
                {
                    if (System.Math.Abs(U.Data[i][k]) > p)
                    {
                        p = System.Math.Abs(U.Data[i][k]);
                        k0 = i;
                    }
                }
                if (p == 0)
                {
                    throw new MatrixException("Making LU: matrix is singular!");
                }
                pom1 = PermutationVector[k];
                PermutationVector[k] = PermutationVector[k0];
                PermutationVector[k0] = pom1;

                for (int i = 0; i < k; i++)
                {
                    pom2 = L.Data[k][i];
                    L.Data[k][i] = L.Data[k0][i];
                    L.Data[k0][i] = pom2;
                }

                if (k != k0) detOfP *= -1;

                for (int i = 0; i < Rows; i++)
                {
                    pom2 = U.Data[k][i];
                    U.Data[k][i] = U.Data[k0][i];
                    U.Data[k0][i] = pom2;
                }

                for (int i = k + 1; i < Rows; i++)
                {
                    L.Data[i][k] = U.Data[i][k] / U.Data[k][k];
                    for (int j = k; j < Rows; j++)
                    {
                        U.Data[i][j] -= L.Data[i][k] * U.Data[k][j];
                    }
                }
            }
        }
示例#58
0
        public void InvertMatrix()
        {
            Console.WriteLine("Testowanie odwracania macierzy");
            //mat.Inverted * mat = mat.Identity
            //Jeśli A ma odwrotną A to odwrotna A jest równa A
            MatrixMB mat = new MatrixMB(2,2);
            mat.Data[0][0] = 4;
            mat.Data[0][1] = 7;
            mat.Data[1][0] = 2;
            mat.Data[1][1] = 6;
            Console.WriteLine("Macierz odwracana");
            Console.WriteLine(mat.MatrixToString());

            double det = mat.Determinant;
            Assert.AreNotEqual(0, det);
            Assert.AreEqual(10, det);

            var inv = mat.Inverted;
            Console.WriteLine("Macierz odwrócona");
            Console.WriteLine(inv.MatrixToString());

            Assert.AreEqual(0.6000, Math.Round(inv.Data[0][0],4));
            Assert.AreEqual(-0.7000, Math.Round(inv.Data[0][1],4));
            Assert.AreEqual(-0.2000, Math.Round(inv.Data[1][0],4));
            Assert.AreEqual(0.4000, Math.Round(inv.Data[1][1],4));

            var A = inv.Inverted;
            Console.WriteLine("Odwrócenie macierzy odwróconej");
            Console.WriteLine(inv.MatrixToString());

            int accuracy = 15;
            for (int i = 0; i < A.Rows; i++)
            {
                for (int j = 0; j < A.Cols; j++)
                {
                    decimal o = Math.Round((decimal)mat[i, j], accuracy);
                    decimal a = Math.Round((decimal)A[i, j], accuracy);
                    Console.WriteLine(string.Format("Orginał: {0}\tPorównywana: {1}", o, a));
                }
            }

            for (int i = 0; i < A.Rows; i++)
            {
                for (int j = 0; j < A.Cols; j++)
                {
                    decimal o = Math.Round((decimal)mat[i, j], accuracy);
                    decimal a = Math.Round((decimal)A[i, j], accuracy);
                    Assert.AreEqual(o, a);
                }
            }

            var identity = inv * mat;
            Assert.AreEqual(1, Math.Round(identity.Data[0][0], accuracy));
            Assert.AreEqual(0, Math.Round(identity.Data[0][1], accuracy));
            Assert.AreEqual(0, Math.Round(identity.Data[1][0], accuracy));
            Assert.AreEqual(1, Math.Round(identity.Data[1][1], accuracy));
        }
示例#59
0
        /// <summary>
        /// Run NBN training and its test - this is the first version
        /// </summary>
        /// <param name="trials">int - number of learning trials</param>
        /// <returns>LearnResult</returns>R
        private LearnResult RunFirstVersion(int trials)
        {
            backupSettings               = new NeuralNetworkSettings();
            backupSettings.MaxError      = settings.MaxError;
            backupSettings.MaxIterations = settings.MaxIterations;
            backupSettings.MU            = settings.MU;
            backupSettings.MUH           = settings.MUH;
            backupSettings.MUL           = settings.MUL;
            backupSettings.Scale         = settings.Scale;

            Trials = trials;
            LearnResult result = new LearnResult();

            result.Filename = Filename;
            if (MatLabCompareDataFolder.Length > 0)
            {
                result.Filename = string.Format("{0}\\{1}.dat", MatLabCompareDataFolder, Path.GetFileNameWithoutExtension(Directory.GetFiles(MatLabCompareDataFolder, "*.dat")[0]));
            }

            if (!loadInputData(Filename))
            {
                updateErrorNBN("Dane nie zostały wczytane.");
                return(result);
            }
            if (OnDebug != null)
            {
                debug("Data loaded from file: " + Filename);
            }

            var tmp = new System.Collections.Generic.List <int>();

            tmp.Add(inputLearn.Cols);

            //setting number of hidden neurons
            for (int i = 0; i < Handle; i++)
            {
                tmp.Add(1);
            }
            tmp.Add(1);

            var vh = new VectorHorizontal(tmp.Count);

            for (int i = 0; i < vh.Length; i++)
            {
                vh[i] = tmp[i];
            }

            switch (NBN_Topography)
            {
            case 0:
            {
                topo = Topography.Generate(TopographyType.BMLP, vh);
            } break;

            case 1:
            {
                topo = Topography.Generate(TopographyType.MLP, vh);
            } break;
            }



            result.Topo = topo.Data[0];
            if (OnDebug != null)
            {
                debug(topo.ToString());
            }

            if (topo == null)
            {
                updateErrorNBN("Topologia sieci nie została utworzona.");
                return(result);
            }

            info = this.checkInputs(ref inputLearn, ref outputLearn, ref topo, out indexes);//here are set indexes

            result.TopoIndex = indexes.Data[0];
            result.Info      = info;
            if (OnDebug != null)
            {
                debug(indexes.ToString());
                debug(info.ToString());
            }

            Activation act = new Activation(info.nn);

            act.FillWithNumber(NBN_Activation);
            act.setValue(info.nn - 1, 0);
            result.ActivationFunction = act.Data[0];

            Gain gain = new Gain(info.nn);

            gain.FillWithNumber(NBN_Gain);
            result.GainValue = gain.Data[0];

            result.Settings = this.settings;

            for (trial = 0; trial < trials; trial++)
            {
                Weights initialWeights = new Weights(info.nw);
                if (MatLabCompareDataFolder.Length > 0)
                {
                    initialWeights = MatrixMB.Load(string.Format("{0}\\poczatkowe_wagi_proba_{1}.txt", MatLabCompareDataFolder, trial + 1)).ToWeights();
                }
                else
                {
                    initialWeights = Weights.Generate(info.nw);
                }

                if (IsResearchMode)
                {
                    string initialWeightsFile = String.Format("{0}\\{1}{2}_initial_weights.dat", _reasearch_folder, trial, Path.GetFileNameWithoutExtension(result.Filename));
                    initialWeights.Store(initialWeightsFile);
                }

                initialWeights.Name = "Initial";
                if (OnDebug != null)
                {
                    debug(String.Format("\r\nTrial {0} from {1}\r\n", trial + 1, trials));
                    debug(initialWeights.ToString());
                }

                settings               = null;
                settings               = NeuralNetworkSettings.Default();
                settings.MaxError      = backupSettings.MaxError;
                settings.MaxIterations = backupSettings.MaxIterations;
                settings.MU            = backupSettings.MU;
                settings.MUH           = backupSettings.MUH;
                settings.MUL           = backupSettings.MUL;
                settings.Scale         = backupSettings.Scale;

                I = MatrixMB.Eye(info.nw);

                tic();//learn time measure start
                var tr = Train(ref this.settings, ref this.info, ref this.inputLearn, ref this.outputLearn,
                               ref this.topo, initialWeights, ref act, ref gain, ref indexes);

                String LearnExecutionTime = toc(); //learn time measure stop
                LearnTimeList = time.ElapsedTicks; //learn time measure save

                result.Add(tr.weights.Data[0], SSE.ToDoubleArray(), RMSE.ToDoubleArray());

                result.LearnRMSE = (double)RMSE[RMSE.Count];
                LearnRmseList    = LastRMSE;

                if (OnDebug != null)
                {
                    debug(tr.weights.ToString());
                    debug("\r\nLearn execution time: " + LearnExecutionTime + "(hours:minutes:seconds:miliseconds)\r\n");
                    debug("\r\nLearn SSE: " + tr.sse.ToString() + "\r\n");
                    debug("\r\nLearn RMSE: " + result.LearnRMSE.ToString() + "\r\n");
                }

                updateError(result.LearnRMSE);

                NetworkInfo infoTest = info.Copy();
                infoTest.np = inputTest.Rows;

                tic();

                error.CalculateError(ref infoTest, ref inputTest, ref outputTest, ref topo, tr.weights, ref act, ref gain, ref indexes);

                var TestExecutionTime = toc();
                TestTimeList = time.ElapsedTicks;

                result.TestRMSE = Math.Sqrt(error.Error / infoTest.np);
                TestRmseList    = result.TestRMSE;
                result.TestingRmseList.Add(result.TestRMSE);
                if (OnDebug != null)
                {
                    debug("\r\nTest execution time: " + TestExecutionTime + "(hours:minutes:seconds:miliseconds)\r\n");
                    debug("\r\nTest SSE: " + error.Error.ToString() + "\r\n");
                    debug("\r\nTest RMSE: " + result.TestRMSE.ToString() + "\r\n");
                }

                //if (result.LearnRMSE < Threshold) IsTrainOK++;
                if (result.SSE[trial][result.SSE[trial].Length - 1] < Threshold)
                {
                    IsTrainOK++;
                }
            }

            result.LearnRMSE = AverageLearnRMSE;
            result.TestRMSE  = AverageTestRMSE;

            result.setStatisticsData(LearnRMSE, TestRMSE, LearnTime, TestTime, Trials);
            result.SuccessRate = (double)IsTrainOK / Trials;

            if (IsResearchMode)//save research
            {
                try
                {
                    string filename = extractionFolder + "\\research result.pdf";

                    PDFGenerate data = new PDFGenerate();
                    data.Filename      = filename;
                    data.Result        = result;
                    data.ChartFilename = GeneratePlot(result.RMSE, Path.GetFileNameWithoutExtension(result.Filename));
                    HistoryPDF pdf = new HistoryPDF(data.Result, data.ChartFilename, true);
                    pdf.Save(data.Filename);
                }
                catch { }
            }

            return(result);
        }
示例#60
0
        public void MatrixDeterminant()
        {
            MatrixMB mat = new MatrixMB(3, 3);
            mat.Data[0][0] = 1;
            mat.Data[0][1] = 9;
            mat.Data[0][2] = 1;
            mat.Data[1][0] = 9;
            mat.Data[1][1] = 1;
            mat.Data[1][2] = 9;
            mat.Data[2][0] = 1;
            mat.Data[2][1] = 9;
            mat.Data[2][2] = 1;
            double det = mat.Determinant;
            Assert.AreEqual(det, 0);
            Assert.AreEqual(1, mat.Data[0][0]);
            Assert.AreEqual(9, mat.Data[0][1]);
            Assert.AreEqual(1, mat.Data[0][2]);

            Assert.AreEqual(9, mat.Data[1][0]);
            Assert.AreEqual(1, mat.Data[1][1]);
            Assert.AreEqual(9, mat.Data[1][2]);

            Assert.AreEqual(1, mat.Data[2][0]);
            Assert.AreEqual(9, mat.Data[2][1]);
            Assert.AreEqual(1, mat.Data[2][2]);
        }