private static Matrix<double> ComputeMatrixCrossproduct(Matrix<double> matrix, IList<int> columnIndexes) { var result = new DenseMatrix(columnIndexes.Count, columnIndexes.Count); for (int iRow = 0; iRow < columnIndexes.Count; iRow++) { for (int iCol = 0; iCol < columnIndexes.Count; iCol++) { result[iRow, iCol] = matrix.Column(columnIndexes[iRow]).DotProduct(matrix.Column(columnIndexes[iCol])); } } return result; }
/// <summary> /// Finds the intersection of the two planes, throws if they are parallel /// http://mathworld.wolfram.com/Plane-PlaneIntersection.html /// </summary> /// <param name="intersectingPlane"></param> /// <param name="tolerance"></param> /// <returns></returns> public Ray3D IntersectionWith(Plane intersectingPlane, double tolerance = float.Epsilon) { var a = new DenseMatrix(2, 3); a.SetRow(0, this.Normal.ToVector()); a.SetRow(1, intersectingPlane.Normal.ToVector()); var svd = a.Svd(true); if (svd.S[1] < tolerance) { throw new ArgumentException("Planes are parallel"); } var y = new DenseMatrix(2, 1); y[0, 0] = -1 * this.D; y[1, 0] = -1 * intersectingPlane.D; Matrix <double> pointOnIntersectionLine = svd.Solve(y); var throughPoint = new Point3D(pointOnIntersectionLine.Column(0)); var direction = new UnitVector3D(svd.VT.Row(2)); return(new Ray3D(throughPoint, direction)); }
/// <summary> /// returns the eigen values and eigen vectors of a matrix /// IMPORTANT: THIS METHOD NEEDS DEBUGGING. /// IT RETURNS THE NEGATIVE VALUES OF THE EIGEN VECTORS ON A TOY EXMAPLE /// double[,] matrix = { /// { 3.0, -1.0 }, /// { -1.0, 3.0 } /// }; /// eigen values are correct ie, 2.0, 4.0; but in the wrong order /// </summary> public static Tuple <double[], double[, ]> EigenVectors(double[,] matrix) { Evd <double> eigen = DenseMatrix.OfArray(matrix).Evd(); Vector <System.Numerics.Complex> eigenvaluesComplex = eigen.EigenValues; //WriteArrayOfComplexNumbers(eigenvalues); double[] eigenvaluesReal = new double[eigenvaluesComplex.Count]; for (int i = 0; i < eigenvaluesComplex.Count; i++) { System.Numerics.Complex c = eigenvaluesComplex[i]; double magnitude = c.Magnitude; Console.WriteLine("eigen value[{0}] {1} Magnitude={2}", i, c.ToString(), magnitude); } Matrix <double> eigenvectorsComplex = eigen.EigenVectors; double[,] eigenvectorsReal = new double[eigenvaluesComplex.Count, matrix.GetLength(0)]; for (int col = 0; col < eigenvectorsComplex.RowCount; col++) { Vector <double> ev = eigenvectorsComplex.Column(col); for (int i = 0; i < ev.Count; i++) { eigenvectorsReal[col, i] = ev[i]; Console.WriteLine("eigen vector {0}, value {1} = {2}", col, i, ev[i]); } } return(Tuple.Create(eigenvaluesReal, eigenvectorsReal)); }
/// <summary> /// Solves the matrix equation AX = B, where A is the coefficient matrix, B is the /// solution matrix and X is the unknown matrix. /// </summary> /// <param name="matrix">The coefficient <see cref="Matrix{T}"/>, <c>A</c>.</param> /// <param name="input">The solution <see cref="Matrix{T}"/>, <c>B</c>.</param> /// <param name="result">The result <see cref="Matrix{T}"/>, <c>X</c></param> public void Solve(Matrix<float> matrix, Matrix<float> input, Matrix<float> result) { if (matrix == null) { throw new ArgumentNullException("matrix"); } if (input == null) { throw new ArgumentNullException("input"); } if (result == null) { throw new ArgumentNullException("result"); } if (matrix.RowCount != input.RowCount || input.RowCount != result.RowCount || input.ColumnCount != result.ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixDimensions); } for (var column = 0; column < input.ColumnCount; column++) { var solution = Solve(matrix, input.Column(column)); foreach (var element in solution.GetIndexedEnumerator()) { result.At(element.Key, column, element.Value); } } }
/// <summary> /// Solves the matrix equation AX = B, where A is the coefficient matrix, B is the /// solution matrix and X is the unknown matrix. /// </summary> /// <param name="matrix">The coefficient matrix, <c>A</c>.</param> /// <param name="input">The solution matrix, <c>B</c>.</param> /// <param name="result">The result matrix, <c>X</c></param> public void Solve(Matrix matrix, Matrix input, Matrix result) { if (matrix == null) { throw new ArgumentNullException("matrix"); } if (input == null) { throw new ArgumentNullException("input"); } if (result == null) { throw new ArgumentNullException("result"); } if (matrix.RowCount != input.RowCount || input.RowCount != result.RowCount || input.ColumnCount != result.ColumnCount) { throw Matrix.DimensionsDontMatch <ArgumentException>(matrix, input, result); } for (var column = 0; column < input.ColumnCount; column++) { var solution = Solve(matrix, (Vector)input.Column(column)); foreach (var element in solution.GetIndexedEnumerator()) { result.At(element.Item1, column, element.Item2); } } }
public override Matrix Process(Matrix m, VectorType vtype = VectorType.Column) { int cols = m.ColumnCount; int rows = m.RowCount; if (vtype == VectorType.Row) { this._m = new DenseVector(cols); for (int n = 0; n < cols; n++) { this._m[n] = m.Column(n).Mean(); } } else { this._m = new DenseVector(rows); for (int n = 0; n < rows; n++) { this._m[n] = m.Row(n).Mean(); } } return(this.ProcessForPrediction(m, vtype, this._m, this._s)); }
/// <summary> /// Gets the dense data array. /// </summary> /// <param name="matrix">The matrix to get the data from.</param> /// <param name="name">The name of the matrix.</param> /// <returns>The matrix data as an array.</returns> private static byte[] GetDenseDataArray(Matrix <float> matrix, string name) { byte[] data; using (var dataMemoryStream = new MemoryStream()) using (var dataWriter = new BinaryWriter(dataMemoryStream)) { WriteMatrixTagAndName(dataWriter, ArrayClass.Single, false, name, matrix.RowCount, matrix.ColumnCount, 0); // write data dataWriter.Write((int)DataType.Single); dataWriter.Write(matrix.RowCount * matrix.ColumnCount * 4); for (var j = 0; j < matrix.ColumnCount; j++) { var column = matrix.Column(j); foreach (var value in column) { dataWriter.Write(value); } } var pad = (matrix.RowCount * matrix.ColumnCount * 4) % 8; PadData(dataWriter, pad); data = dataMemoryStream.ToArray(); } return(data); }
/// <summary> /// Finds the coefficients to describe a quintic path using start and final time, position and velocity /// It assumes when half the time has elapsed it is hafway and with the average velocity /// </summary> private Vector <double> FindCurve(double t0, double tf, double x0, double xf, double v0, double vf) { double tm = (tf - t0) / 2; Matrix <Double> A = Matrix <Double> .Build.DenseOfArray(new double[, ] { { 1, t0, Math.Pow(t0, 2), Math.Pow(t0, 3), Math.Pow(t0, 4), Math.Pow(t0, 5) }, // start position { 0, 1, 2 * t0, 3 * Math.Pow(t0, 2), 4 * Math.Pow(t0, 3), 5 * Math.Pow(t0, 4) }, // start velocity { 1, tm, Math.Pow(tm, 2), Math.Pow(tm, 3), Math.Pow(tm, 4), Math.Pow(tm, 5) }, // mid position { 1, tf, Math.Pow(tf, 2), Math.Pow(tf, 3), Math.Pow(tf, 4), Math.Pow(tf, 5) }, // final position { 0, 1, 2 * tf, 3 * Math.Pow(tf, 2), 4 * Math.Pow(tf, 3), 5 * Math.Pow(tf, 4) }, // final velocity { 0, 1, 2 * tm, 3 * Math.Pow(tm, 2), 4 * Math.Pow(tm, 3), 5 * Math.Pow(tm, 4) } }); // mid velocity Matrix <Double> Y = Matrix <Double> .Build.DenseOfArray(new double[, ] { { x0 }, // start position { v0 }, // start velocity { x0 + (xf - x0) / 2 }, // mid position (half way) { xf }, // final position { vf }, // final velocity { AVE_SPEED } }); // mid velocity Matrix <Double> X = A.Solve(Y); return(X.Column(0)); }
public static Vector <double> Sole(Matrix <double> matrix) { if ((matrix == null) || (matrix.RowCount < 2) || (matrix.ColumnCount < 2)) { return(null); } Matrix <double> matrix_copy = Matrix <double> .Build.DenseOfMatrix(matrix); // максимальное собственное значение double MaxEigenVal = MaxEigenValue(matrix_copy); //из главной диагонали матрицы вычитаем это собственное значение matrix_copy.SetDiagonal((matrix_copy.Diagonal() - MaxEigenVal)); int n = matrix_copy.RowCount; //создаем вектор, необходимый для решения слау (первый столбец умножанный на -1, без 1 элемента Vector <double> _vector = Vector <double> .Build.DenseOfVector((matrix_copy.Column(0) * (-1)).SubVector(0, n - 1)); //преобразуем матрицу для слау matrix_copy = matrix_copy.RemoveColumn(0); matrix_copy = matrix_copy.RemoveRow(n - 1); //вычисляем решение Vector <double> result = Vector <double> .Build.Dense(n, 1); matrix_copy.Solve(_vector).CopySubVectorTo(result, 0, 1, _vector.Count); return(result); }
/// <summary> /// /// </summary> /// <param name="m"></param> /// <param name="vtype"></param> /// <returns></returns> public virtual Matrix Process(Matrix m, VectorType vtype = VectorType.Column) { var d = new DenseMatrix(m.RowCount, m.ColumnCount); int count = vtype == VectorType.Row ? m.RowCount : m.ColumnCount; this._Busying = true; for (int i = 0; i < count; i++) { if (vtype == VectorType.Row) { d.SetRow(i, Process((Vector)m.Row(i))); } else { d.SetColumn(i, Process((Vector)m.Column(i))); } } if (this.ComputeFinished != null) { this.ComputeFinished(this, null); } this._Busying = false; return(d); }
public Tuple <Matrix <double>, Matrix <double> > ArnoldiStep( Matrix <double> A, Matrix <double> V, Matrix <double> H, List <int> REPEATED, double kappa = 0.2) { int k = V.ColumnCount - 1; Vector <double> v = A * V.Column(k); Tuple <Vector <double>, Vector <double> > tuple = Orthogonalise(V, v, REPEATED, kappa); v = tuple.Item1; Vector <double> h = tuple.Item2; V = V.InsertColumn(V.ColumnCount, v); if (H == null) { Matrix <double> H_new = new DenseMatrix(2, 1); H_new.SetColumn(H_new.ColumnCount - 1, h); return(new Tuple <Matrix <double>, Matrix <double> >(V, H_new)); } else { Matrix <double> H_new = Matrix <double> .Build.Dense(H.RowCount + 1, H.ColumnCount + 1); H_new.SetSubMatrix(0, 0, H); H_new.SetColumn(H_new.ColumnCount - 1, h); return(new Tuple <Matrix <double>, Matrix <double> >(V, H_new)); } }
void ProcessSpiralForceGesture(Matrix <double> P, Matrix <double> V) { V.SetColumn(0, new double[V.RowCount]); var avgSpeed = MathNet.Numerics.Statistics.Statistics.Mean(V.RowNorms(2.0)); P.SetColumn(0, V.Column(2)); double[] angles = new double[P.RowCount]; Func <Vector <double>, Vector <double>, int> CrossXSign = (a, b) => { return(Math.Sign(a[1] * b[2] - b[1] * a[2])); }; List <int> crossData = new List <int>(P.RowCount); for (var i = 0; i < P.RowCount; ++i) { crossData.Add(CrossXSign(P.Row(i), V.Row(i))); } // module by avg. direction of P x V TimeManager.StackEmissionSpiral(SpiralFrequency, animScript); SpiralFrequency = Math.Sign(crossData.Sum()) * (float)(avgSpeed / MathNet.Numerics.Statistics.Statistics.Mean(P.RowNorms(2.0))); Debug.Log("Spiral freq: " + SpiralFrequency + "P x V sign: " + (float)crossData.Sum() / P.RowCount); }
public void MatrixColumn() { Utils.ProcessInEnv(env => { var dec = mat.GetColumn(0).Decrypt(env); Compare(m.Column(0), dec); }, Factory); }
/// <summary> /// Pairwise distance between pairs of objects /// </summary> /// <see cref="http://www.mathworks.cn/help/toolbox/stats/pdist.html"/> /// <see cref="http://www.mathworks.cn/help/toolbox/stats/squareform.html"/> /// <param name="m"></param> /// <param name="dis">距离度量方式</param> /// <param name="vtype"></param> /// <returns></returns> public static Matrix PDist(Matrix m, IDistance dis, VectorType vtype = VectorType.Column) { int count = vtype == VectorType.Row ? m.RowCount : m.ColumnCount; DenseMatrix result = new DenseMatrix(count, count); for (int i = 0; i < count; i++) { Vector x1 = (Vector)(vtype == VectorType.Row ? m.Row(i) : m.Column(i)); for (int j = i + 1; j < count; j++) { Vector x2 = (Vector)(vtype == VectorType.Row ? m.Row(j) : m.Column(j)); result[i, j] = dis.Compute(x1, x2); result[j, i] = result[i, j]; } } return(result); }
public void UpdateMainWeightsBaseOnDropoutWeightsBeetwenHiddenAndOutputLayer(Matrix <double> mainWeights, Matrix <double> droputWeights, List <int> activeNeurons) { for (var i = 0; i < activeNeurons.Count; i++) { mainWeights.SetColumn(activeNeurons[i], droputWeights.Column(i)); } }
public void CanGetColumnIntoResult(TestMatrix testMatrix) { Matrix <T> matrix = Get(testMatrix); var col = Vector <T> .Build.Dense(matrix.RowCount); matrix.Column(0, col); for (var i = 0; i < matrix.RowCount; i++) { Assert.AreEqual(matrix[i, 0], col[i]); } Assert.That(() => matrix.Column(0, null), Throws.InstanceOf <ArgumentNullException>()); Assert.That(() => matrix.Column(-1, col), Throws.InstanceOf <ArgumentOutOfRangeException>()); Assert.That(() => matrix.Column(matrix.ColumnCount, col), Throws.InstanceOf <ArgumentOutOfRangeException>()); }
private static void TestChangeOfBasisMatrixCorrectness(Matrix <double> transformMatrix, Matrix <double> base1, Matrix <double> base2) { Vector <double> v1t = transformMatrix.Multiply(base1.Column(0)); Vector <double> v2t = transformMatrix.Multiply(base1.Column(1)); Vector <double> v3t = transformMatrix.Multiply(base1.Column(2)); Console.Write("v1: " + base2.Column(0)); Console.WriteLine("v1t: " + v1t.ToString()); Console.Write("v2: " + base2.Column(1)); Console.WriteLine("v2t: " + v2t.ToString()); Console.Write("v3: " + base2.Column(2)); Console.WriteLine("v3t: " + v3t.ToString()); return; }
//private static Vector<double> CalculateOneStep(Vector<double> X, Vector<double> z, int n, double h) //{ // double tamedCoeff = 1 / (1 + Math.Pow(n, -1 / 2) * X.L2Norm()); // return tamedCoeff * X * (lambda * (mu - X.L2Norm())) * h + tamedCoeff * eta * Math.Pow(X.L2Norm(), 3 / 2) * z * Math.Sqrt(h); //} private static Vector <double> RunMC() { Vector <double> Xs = Vector <double> .Build.Dense(n2length, 0); Matrix <double> Xn = Matrix <double> .Build.Dense(2, n2length, 1); //Generate Random Number Matrix double[] randn1 = new double[Nmax]; double[] randn2 = new double[Nmax]; Normal.Samples(randn1, 0, 1); Normal.Samples(randn2, 0, 1); Matrix <double> randnMatrix = Matrix <double> .Build.DenseOfRowArrays(randn1, randn2); for (int n = 0; n < Nmax; n++) { for (int i = 0; i < n2length; i++) { if (n % Nmax / Narr[Narr.Length - 1 - i] == 0) { Vector <double> X = Xn.Column(i); Vector <double> z = Vector <double> .Build.Dense(2); for (int j = 0; j < Nmax / Narr[Narr.Length - 1 - i]; j++) { z += randnMatrix.Column(n + j); } z *= Math.Sqrt(1 / Nmax); double h = T / Narr[i]; double tamedCoeff = 1 / (1 + Math.Pow(n, -1 / 2) * X.L2Norm()); Vector <double> oneStep = tamedCoeff * X * (lambda * (mu - X.L2Norm())) * h + tamedCoeff * eta * Math.Pow(X.L2Norm(), 3 / 2) * z * Math.Sqrt(h); //Xn.SetColumn(i, Xn.Column(i) + CalculateOneStep(Xn.Column(i), randnMatrix.Column(n), n, T / Narr[i])); Xn.SetColumn(i, Xn.Column(i) + oneStep); } } } for (int i = 0; i < n2length; i++) { Xs[i] = Math.Pow((Xn.Column(Xn.ColumnCount - 1) - Xn.Column(i)).L2Norm(), 2); } return(Xs); }
/// <summary> /// ForTesting /// Sets the norm of column vectors in a matrix to 1 /// </summary> /// <param name="matrix"></param> private static void NormalizeCollumnVectorsInMatrix(Matrix <double> matrix) { for (int i = 0; i < matrix.ColumnCount; i++) { Vector <double> v = matrix.Column(i); v.Divide(Math.Sqrt(PCATester.ScalarProduct(v, v))); matrix.SetColumn(i, v); } }
private static void PlotProgresskMeans(Matrix <double> X, Matrix <double> centroids, Matrix <double> previous_centroids, Vector <double> idx, int K, int i) { GnuPlot.Set($"title \"Iteration number {i+1}"); PlotDataPoints(X, idx, K); // Plot the centroids as black x's double[] x1 = centroids.Column(0).ToArray(); double[] x2 = centroids.Column(1).ToArray(); GnuPlot.Plot(x1, x2, "pt 2 ps 1 lw 3 lc rgb \"black\" notitle"); // Plot the history of the centroids with lines for (int j = 0; j < centroids.RowCount; j++) { double[] x = new double[] { centroids[j, 0], previous_centroids[j, 0] }; double[] y = new double[] { centroids[j, 1], previous_centroids[j, 1] }; GnuPlot.Plot(x, y, "with lines linestyle 1 linewidth 2 notitle"); } }
private static void PlotDataPoints(Matrix <double> X, Vector <double> idx, int K) { double[] x1 = X.Column(0).ToArray(); double[] x2 = X.Column(1).ToArray(); string[] colors = { "red", "green", "cyan", "blue", "purple", "yellow", "orange" }; string color = colors[0]; Matrix <double> sel = null; for (int k = 0; k < K; k++) { color = colors[k]; sel = SelectFromIndexes(X, FindIndexes(idx, k)); x1 = sel.Column(0).ToArray(); x2 = sel.Column(1).ToArray(); GnuPlot.Plot(x1, x2, $"pt 6 ps .7 lc rgb \"{color}\" notitle"); } }
public static LPSTerm[] FromUnderlyingTransposeAlgebra(Matrix <double> outm, Vector <double> outv) { LPSTerm[] ret = new LPSTerm[outm.ColumnCount]; for (int i = 0; i < outm.ColumnCount; i++) { ret[i] = new LPSTerm(outm.Column(i), outv[i]); } return(ret); }
private static void PlotJ(Matrix <double> j_history, string title, string color) { double[] x = MathNet.Numerics.Generate.LinearRange(1, 1, j_history.RowCount); double[] y = j_history.Column(0).ToArray(); GnuPlot.Set("xlabel \"Number of iteration\""); GnuPlot.Set("ylabel \"Cost J\""); GnuPlot.Plot(x, y, "with lines linestyle 1 lc rgb \"" + color + "\" linewidth 2 title \"" + title + "\" "); }
private static void PlotBoundary(Matrix <double> x, C_SVC svc) { double min = x.Column(0).Min(); double max = x.Column(0).Max(); double[] x0 = MathNet.Numerics.Generate.LinearSpaced(100, min, max); min = x.Column(1).Min(); max = x.Column(1).Max(); double[] x1 = MathNet.Numerics.Generate.LinearSpaced(100, min, max); int size = x0.Length * x1.Length; double[] sx = new double[size]; double[] sy = new double[size]; double[] sz = new double[size]; int idx = 0; for (int i = 0; i < x0.Length; i++) { for (int j = 0; j < x1.Length; j++) { sx[idx] = x0[i]; sy[idx] = x1[j]; svm_node n1 = new svm_node(); n1.index = 1; n1.value = x0[i]; svm_node n2 = new svm_node(); n2.index = 2; n2.value = x1[j]; double z = svc.Predict(new [] { n1, n2 }); sz[idx] = z; idx++; } } GnuPlot.Set("cntrparam levels discrete 0.5"); GnuPlot.Contour(sx, sy, sz, "title \"Decision Boundary\""); }
public static IList <Vector <T> > ColumnsAsVectors <T>(this Matrix <T> matrix) where T : struct, IEquatable <T>, IFormattable { var result = new List <Vector <T> >(); for (int i = 0; i < matrix.ColumnCount; i++) { result.Add(matrix.Column(i)); } return(result); }
/// <summary> /// Flip matrix left to right /// </summary> /// <see cref="http://www.mathworks.cn/help/techdoc/ref/fliplr.html"/> /// <param name="m"></param> /// <returns>B = fliplr(A) returns A with columns flipped in the left-right direction, that is, about a vertical axis.If A is a row vector, then fliplr(A) returns a vector of the same length with the order of its elements reversed. If A is a column vector, then fliplr(A) simply returns A.</returns> public static Matrix Flip(this Matrix m) { var d = new DenseMatrix(m.RowCount, m.ColumnCount); for (int c = 0; c < m.ColumnCount; c++) { d.SetColumn(c, m.Column(m.ColumnCount - c - 1)); } return(d); }
public Matrix <double> Decompose(int k, Matrix <double> raw_data) { double[] range_start = new double[k]; double[] v_ms = new double[k]; Matrix <double> converted_data = ConvertLambdas(raw_data); var result = Matrix <double> .Build.Dense(raw_data.RowCount, k + 1); double lowestscore = 0; double currentscore = 0; _stepsize = 5; List <int[]> combos = GetCombos(20, k); for (int i = 0; i < combos[0].Length; i++) { v_ms[i] = 10000000 / (300 + (combos[0][i] * _stepsize)); } var Intens = GetIntensities(converted_data.Column(0), converted_data.Column(1), v_ms); lowestscore = CalcSScore(converted_data.Column(0), converted_data.Column(1), v_ms, Intens); foreach (var item in combos) { for (int i = 0; i < item.Length; i++) { v_ms[i] = 10000000 / (300 + (item[i] * _stepsize)); } Intens = GetIntensities(converted_data.Column(0), converted_data.Column(1), v_ms); currentscore = CalcSScore(converted_data.Column(0), converted_data.Column(1), v_ms, Intens); //MessageBox.Show(v_ms[0].ToString() + "," + v_ms[1].ToString() + " : " + Intens[0].ToString() + "," + Intens[1].ToString() + " : " + currentscore); if (currentscore < lowestscore) { for (int i = 0; i < k; i++) { for (int j = 0; j < raw_data.RowCount; j++) { result[j, i] = CalcLogNormVals(converted_data.Column(0), v_ms)[j, i] * Intens[i]; result[j, k] += result[j, i]; } } } } return(result); }
// makes copies of the vectors passed in, as this is a terrible way to do this. really. public static Vector <Complex> KronProd(Vector <Complex>[] states) { Matrix <Complex> retval = Matrix <Complex> .Build.Dense(1, 1, 1); foreach (var state in states) { retval = retval.KroneckerProduct(MathNet.Numerics.LinearAlgebra.Complex.DenseMatrix.OfColumnVectors(new Vector <Complex>[] { state })); } return(retval.Column(0)); }
public void CanFoldColumns(Matrix <T> matrix) { // not forced T[] colSum = matrix.FoldByColumn((s, x) => Operator <T> .Add(s, x), Operator <T> .Zero, Zeros.AllowSkip); for (int i = 0; i < colSum.Length; i++) { Assert.That(colSum[i], Is.EqualTo(matrix.Column(i).Enumerate().Aggregate((a, b) => Operator <T> .Add(a, b))), "not forced"); } // forced colSum = matrix.FoldByColumn((s, x) => Operator <T> .Add(s, x), Operator <T> .Zero, Zeros.Include); for (int i = 0; i < colSum.Length; i++) { Assert.That(colSum[i], Is.EqualTo(matrix.Column(i).Enumerate().Aggregate((a, b) => Operator <T> .Add(a, b))), "forced"); } Assert.That(matrix.FoldByColumn((s, x) => s + 1.0, 0.0, Zeros.Include), Is.EqualTo(Vector <double> .Build.Dense(matrix.ColumnCount, matrix.RowCount)), "forced - full coverage"); }
internal static Double CrossEntropyErrorDouble(Matrix <Double> input, Matrix <Double> teach) { Double sum = 0; for (Int32 i = 0; i < input.ColumnCount; i++) { sum += CrossEntropyErrorDouble(input.Column(i), teach.Column(i)); } return(sum / input.ColumnCount); }
public static void GramSchmidt(Matrix <double> X) { var epsilon = 9.094947017729282e-13; double low_limit = -1.0; // TODO: Decide this dynamically ... var nTasks = 1; var nRows = X.RowCount; var nCols = X.ColumnCount; // Initialize counters //var rowsToProcess = nRows; //var rowsPerTask = (int)Math.Floor((double)rowsToProcess / nTasks); //var missingRows = rowsToProcess - nTasks * rowsPerTask; var colsToProcess = nCols; var colsPerTask = (int)Math.Floor((double)colsToProcess / nTasks); var missingCols = colsToProcess - nTasks * colsPerTask; for (int i = 0; i < nCols; i++) { // Guard if (i == nCols - 1) { break; } // Normalize adjusted row //X.SetRow(i, X.Row(i).Normalize(2)); X.SetColumn(i, X.Column(i).Normalize(2)); // Update counters colsToProcess -= 1; colsPerTask = (int)Math.Floor((double)colsToProcess / nTasks); missingCols = colsToProcess - nTasks * colsPerTask; // Start threads var tasks = new List <Task <int> >(); for (int j = 0; j < nTasks; j++) { // Calculate starting idx and number of rows to process var idx = (i + 1) + j * colsPerTask; var rows = j != nTasks ? colsPerTask : colsPerTask + missingCols; // Run task for given data slice tasks.Add(Task.Run(() => OrthogonalizeColumns(X, i, idx, rows))); } Task.WaitAll(tasks.ToArray()); //Console.WriteLine("Samples handled: {0}", i + 1); } }
/// <summary> /// Gram-Schmidtian orthogonalization of an m by n matrix A, such that /// {Q, R} is returned, where A = QR, Q is m by n and orthogonal, R is /// n by n and upper triangular matrix. /// </summary> /// <returns></returns> public Matrix[] QRGramSchmidt() { int m = rowCount; int n = columnCount; Matrix A = this.Clone(); Matrix Q = new Matrix(m, n); Matrix R = new Matrix(n, n); // the first column of Q equals the first column of this matrix for (int i = 1; i <= m; i++) Q[i, 1] = A[i, 1]; R[1, 1] = Complex.One; for (int k = 1; k <= n; k++) { R[k, k] = new Complex(A.Column(k).Norm()); for (int i = 1; i <= m; i++) Q[i, k] = A[i, k] / R[k, k]; for (int j = k + 1; j <= n; j++) { R[k, j] = Dot(Q.Column(k), A.Column(j)); for (int i = 1; i <= m; i++) A[i, j] = A[i, j] - Q[i, k] * R[k, j]; } } return new Matrix[] { Q, R }; }
private Quaternion QuaternionFromMatrix(Matrix<double> m) { Vector<double> col2 = m.Column(2); Vector<double> col1 = m.Column(1); return Quaternion.LookRotation(numericToUnity(col2), numericToUnity(col1)); }
/// <summary> /// Vertically concats matrices A and B, which do not have to be of the same height. /// </summary> /// <param name="A"></param> /// <param name="B"></param> /// <returns>Matrix [A|B]</returns> public static Matrix VerticalConcat(Matrix A, Matrix B) { Matrix C = A.Column(1); for (int j = 2; j <= A.ColumnCount; j++) { C.InsertColumn(A.Column(j), j); } for (int j = 1; j <= B.ColumnCount; j++) { C.InsertColumn(B.Column(j), C.ColumnCount + 1); } return C; }