public static Tuple <List <double>, List <int> > GetDistances(Matrix <double> X) { int n = X.RowCount; //Vector<double> d = new DenseVector(n * (n - 1) / 2, 0); List <double> d = new List <double>(); for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { //d[(i - 1) * n - (i - 1) * 1 / 2 + j - i] = (X.Row(i) - X.Row(j)).Norm(1); d.Add((X.Row(i) - X.Row(j)).Norm(1)); } } List <double> d_unique = new List <double>(); List <int> J = new List <int>(); foreach (var g in d.GroupBy(v => v)) { d_unique.Add(g.Key); J.Add(g.Count()); } return(new Tuple <List <double>, List <int> >(d_unique, J)); }
public Vector <double> compute(int k) { Ik = Matrix <double> .Build.DenseIdentity(n + k); B = Vector <double> .Build.Dense(n + k, 0); FillP(k); var A = P.Transpose() - Ik; B = -A.Column(0); A = A.RemoveColumn(0); Vector <double> mX = A.Solve(B); for (int i = 0; i < n + k; i++) { if (i == 0) { Xs[k - Kmin, i] = 1; continue; } Xs[k - Kmin, i] = (mX[i - 1] *= S[i] / S[0]); // m = 1/si; xi = mXi/m => xi = mXi*si/s0; } XisValid[k - Kmin] = true; return(Xs.Row(k - Kmin)); }
/// <summary> /// this method for calculate cosine simularity. /// </summary> /// <param name="data">Metrix data</param> /// <returns></returns> public static Matrix <double> cosin(Matrix <double> data) { Matrix <double> similar_matrix = DenseMatrix.Create(data.RowCount, data.RowCount, 0); for (int vector1 = 0; vector1 < data.RowCount; vector1++) { for (int vector2 = vector1; vector2 < data.RowCount; vector2++) { double dotProduct = data.Row(vector1).DotProduct(data.Row(vector2)); Vector <double> vectorA = data.Row(vector1); Vector <double> vectorB = data.Row(vector2); for (int i = 0; i < vectorA.Count; i++) { vectorA[i] = vectorA[i] * vectorA[i]; } for (int i = 0; i < vectorB.Count; i++) { vectorB[i] = vectorB[i] * vectorB[i]; } double sqrtVectorA = Math.Sqrt(vectorA.Sum()); double sqrtVectorB = Math.Sqrt(vectorB.Sum()); double valueSimilar = 0; if (sqrtVectorA * sqrtVectorB != 0) { valueSimilar = dotProduct / (sqrtVectorA * sqrtVectorB); } similar_matrix[vector1, vector2] = valueSimilar; similar_matrix[vector2, vector1] = valueSimilar; } } return(similar_matrix); }
public Matrix <double> determineSurfaceFaces(Matrix <double> faces, int numElements) { HashSet <Vector <double> > surfaceSet = new HashSet <Vector <double> >(); for (int i = 0; i < numElements * 4; i++) { if (surfaceSet.Contains(faces.Row(i))) { surfaceSet.Remove(faces.Row(i)); } else { surfaceSet.Add(faces.Row(i)); } } Matrix <double> surface = Matrix <double> .Build.Dense(surfaceSet.Count, 3); int row = 0; foreach (Vector <double> temp in surfaceSet) { surface.SetRow(row, temp); row++; } return(surface); }
private static double ComputeValidationError(C_SVC svc, Matrix <double> xval, Vector <double> yval) { int m = xval.RowCount; double errorCount = 0; for (int i = 0; i < m; i++) { svm_node n1 = new svm_node(); n1.index = 1; n1.value = xval.Row(i)[0]; svm_node n2 = new svm_node(); n2.index = 2; n2.value = xval.Row(i)[1]; double pred = svc.Predict(new [] { n1, n2 }); if (pred != yval[i]) { errorCount++; } } return(errorCount / m); }
public void IsNotEqualToPermutation(TestMatrix testMatrix) { Matrix <T> matrix = Get(testMatrix); if (!matrix.Storage.IsFullyMutable) { return; } Matrix <T> permutation; if (matrix.RowCount >= 2 && matrix.Row(1).Any(x => !Zero.Equals(x))) { matrix.ClearRow(0); permutation = matrix.Clone(); permutation.ClearRow(1); permutation.SetRow(0, matrix.Row(1)); } else if (matrix.ColumnCount >= 2 && matrix.Column(1).Any(x => !Zero.Equals(x))) { matrix.ClearColumn(0); permutation = matrix.Clone(); permutation.ClearColumn(1); permutation.SetColumn(0, matrix.Column(1)); } else { return; } Assert.That(matrix, Is.Not.EqualTo(permutation)); Assert.IsFalse(matrix.Equals(permutation)); }
public static void Print(Matrix matrix, Matrix resultRow) { Console.WriteLine("Print the matrix and result row"); var numberOfRows = matrix.Column(0).Count(); var numberOfColumns = matrix.Row(0).Count(); var numberOfColumnsInResult = resultRow.Row(0).Count(); for (int i = 0; i < numberOfRows; i++) { for (int k = 0; k < numberOfColumnsInResult - numberOfColumns; k++) { Console.Write("| "); } for (int j = 0; j < numberOfColumns; j++) { var l = matrix.Cell(i, j).Letter != null?matrix.Cell(i, j).Letter.ToString() : " "; Console.Write("|" + l); } Console.WriteLine("|"); } Console.WriteLine("-------"); foreach (Unit u in resultRow.Row(0)) { Console.Write("|" + u.Letter); } Console.WriteLine("|"); }
public void CanGetRow(TestMatrix testMatrix) { Matrix <T> matrix = Get(testMatrix); // First Row var firstrow = matrix.Row(0); Assert.That(firstrow.Count, Is.EqualTo(matrix.ColumnCount)); for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(matrix[0, j], firstrow[j]); } // Last Row var lastrow = matrix.Row(matrix.RowCount - 1); Assert.That(lastrow.Count, Is.EqualTo(matrix.ColumnCount)); for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(matrix[matrix.RowCount - 1, j], lastrow[j]); } // Invalid Rows Assert.That(() => matrix.Row(-1), Throws.InstanceOf <ArgumentOutOfRangeException>()); Assert.That(() => matrix.Row(matrix.RowCount), Throws.InstanceOf <ArgumentOutOfRangeException>()); }
private void ArrangeTestSet(int size) { if (size > TrainingInputs.RowCount - 1) { throw new Exception("Size of the training set is greater than total amount of members introduced to the model."); } if (size > 0) { TestInputs = Matrix <double> .Build.Dense(size, NumberOfInputs); TestOutputs = Matrix <double> .Build.Dense(size, NumberOfOutputs); Random rnd = new Random(); for (int i = 1; i <= size; i++) { int index = rnd.Next(TrainingInputs.RowCount); TestInputs.SetRow(i - 1, TrainingInputs.Row(index).ToArray()); TestOutputs.SetRow(i - 1, TrainingOutputs.Row(index).ToArray()); TrainingInputs = TrainingInputs.RemoveRow(index); TrainingOutputs = TrainingOutputs.RemoveRow(index); } } }
public Matrix <double> CalculateMatrixC() { for (int i = 0; i < 4; ++i) { matrixC[i, 0] = 0.25 * (1 - ksi[i]) * (1 - eta[i]); matrixC[i, 1] = 0.25 * (1 + ksi[i]) * (1 - eta[i]); matrixC[i, 2] = 0.25 * (1 + ksi[i]) * (1 + eta[i]); matrixC[i, 3] = 0.25 * (1 - ksi[i]) * (1 + eta[i]); } for (int i = 0; i < 4; ++i) { pc[i] = matrixC.Row(i).ToColumnMatrix() * matrixC.Row(i).ToRowMatrix(); double toMul = C * ro * detJ[i]; pc[i] = pc[i].Multiply(toMul); } matrixC.Clear(); for (int i = 0; i < 4; ++i) { matrixC = matrixC.Add(pc[i]); } return(matrixC); }
public List <int> GetNeighbours(int a0, List <int> excludeList = null) { _busy++; List <int> neighbours = new List <int>(); int index = 0; if (excludeList == null) { foreach (double n in adjacencyMatrix.Row(a0)) { if (n > 0.0) { neighbours.Add(index); } index++; } } else { foreach (double n in adjacencyMatrix.Row(a0)) { if (n > 0.0 && !excludeList.Contains(index)) { neighbours.Add(index); } index++; } } _busy--; return(neighbours); }
public void TrainingSet(double[,] x, int[] y) { if (x.GetUpperBound(0) + 1 < y.Length) { throw new Exception("You have more labels than training examples!"); } if (x.GetUpperBound(0) + 1 > y.Length) { throw new Exception("You have more training examples than labels!"); } int cv_size = (int)(0.2 * (x.GetUpperBound(0) + 1)); double[] _y = new double[y.Length - 2 * cv_size]; y = (int[])y.Clone(); X = CreateMatrix.DenseOfArray(x); Random r = new Random(); for (int i = 0; i < X.RowCount - 2; i++) { int j = r.Next(i, X.RowCount); var a = X.Row(i); var b = X.Row(j); X.SetRow(j, a); X.SetRow(i, b); int t = y[i]; y[i] = y[j]; y[j] = t; } CV = CreateMatrix.DenseOfRowVectors(X.Row(0)); X = X.RemoveRow(0); Test = CreateMatrix.DenseOfRowVectors(X.Row(0)); X = X.RemoveRow(0); for (int i = 0; i < cv_size - 1; i++) { CV = CV.InsertRow(i + 1, X.Row(0)); X = X.RemoveRow(0); Test = Test.InsertRow(i + 1, X.Row(0)); X = X.RemoveRow(0); } double[] _cvy = new double[cv_size]; double[] _testy = new double[cv_size]; for (int i = 0; i < 2 * cv_size; i++) { _cvy[i / 2] = y[i++]; _testy[i / 2] = y[i]; } for (int i = 2 * cv_size; i < y.Length; i++) { _y[i - 2 * cv_size] = y[i]; } Y = CreateVector.DenseOfArray(_y); CVY = CreateVector.DenseOfArray(_cvy); TestY = CreateVector.DenseOfArray(_testy); }
public void TestRow(string matrixKey, string rowKey, int i) { Matrix <RealFieldElement> matrix = TestRealMatrices[matrixKey]; Matrix <RealFieldElement> row = TestRealMatrices[rowKey]; Assert.IsTrue(matrix.Row(i) == row); Assert.IsFalse(matrix.Row(i) != row); }
private static void Calculate_dNdxdNdxT_dNdydNdyT() { for (int i = 0; i < FiniteElementPointsCount; i++) { dNdxdNdxTMatrices[i] = dNdxMatrix.Row(i).ToColumnMatrix() * dNdxMatrix.Row(i).ToRowMatrix(); dNdydNdyTMatrices[i] = dNdyMatrix.Row(i).ToColumnMatrix() * dNdyMatrix.Row(i).ToRowMatrix(); } }
public static Matrix <double> SwapRows(this Matrix <double> matrix, int rowA, int rowB) { var tempMatrix = matrix.Clone(); tempMatrix.SetRow(rowA, matrix.Row(rowB)); tempMatrix.SetRow(rowB, matrix.Row(rowA)); return(tempMatrix); }
/// <summary> /// This function computes the elementary row interchange operation on /// the given matrix. /// </summary> /// /// <param name="a"> /// An N-by-M matrix to perform the elementary row operation on. /// </param> /// <param name="i"> /// The index of the first row of the rows to interchange. /// </param> /// <param name="j"> /// The index of the second row of the rows to interchange. /// </param> /// /// <returns> /// The resulting N-by-M matrix after having performed the elementary /// row operation. /// </returns> public static Matrix ElementaryRowInterchange( this Matrix a, int i, int j) { // rowI and rowJ are introduced for clarity and to avoid changing a row to itself. Vector rowI = a.Row(i); Vector rowJ = a.Row(j); return(a.InsertRow(i, rowJ).InsertRow(j, rowI)); }
public void Optimize(LpModel model) { int m = model.A.RowCount; int n = model.A.ColumnCount; Iteration currentIteration = GetStartingBasis(model); while (true) { Matrix <double> B = GetColumnSubset(model, currentIteration.BasicColumns); Matrix <double> NonB = GetColumnSubset(model, currentIteration.NonBasicColumns); Matrix <double> B_inv = B.Inverse(); Vector <double> Xb = B_inv.Multiply(model.b); _log.Info($"Iteration 0: Xb = {Xb.ToString()}"); //reduced cost currentIteration.BasicCostVector = GetCostVector(model, currentIteration.BasicColumns); currentIteration.NonBasicCostVector = GetCostVector(model, currentIteration.NonBasicColumns); currentIteration.ObjectiveValue = currentIteration.BasicCostVector.ToRowMatrix().Multiply(Xb)[0]; _log.Info($"Objective: {currentIteration.ObjectiveValue}"); Matrix <double> cbInv = currentIteration.BasicCostVector.ToRowMatrix().Multiply(B_inv); Matrix <double> reducedCosts = cbInv.Multiply(NonB) - Matrix <double> .Build.DenseOfRowVectors(currentIteration.NonBasicCostVector); var min = reducedCosts.Row(0).Minimum(); if (min >= 0) { break; } var minId = reducedCosts.Row(0).MinimumIndex();//entering column etc, Taha 314 int enteringColumn = currentIteration.NonBasicColumns[minId]; _log.Info($"The Entering column is: {enteringColumn}"); var bp = B_inv.Multiply(model.A.Column(enteringColumn)); //check if unbounded.. if all entries negative or zero //ratio test to determine leaving vector //ratio test for positive denominator only -> set rest to NaN to ignore.. bp.Map((a) => { if (a <= 0) { return(double.NaN); } else { return(a); } }, bp); var feas = Xb.PointwiseDivide(bp); int leavingColumn = currentIteration.BasicColumns[feas.MinimumIndex()]; _log.Info($"Leaving column: {leavingColumn}"); //modify basis and continue currentIteration = ExchangeBasisColumns(model, currentIteration, enteringColumn, leavingColumn); _log.Info(Environment.NewLine + PrintIteration(model, currentIteration)); } _log.Info($"Final Objective is: {Math.Round(currentIteration.ObjectiveValue, 2)}"); }
/// <summary> /// Main ctor. /// </summary> /// <param name="columns">The column values.</param> /// <param name="forwards">An array of forwards to the expiry dates. The length of this array is + 1, as the first element is the spot value.</param> /// <param name="values">The discrete surface ie 2 dimensional.</param> /// <param name="xInterpolation">The basic interpolation to be applied to the x axis.</param> /// <param name="yInterpolation">The basic interpolation to be applied to the y axis.</param> /// <param name="rows">The row values.</param> public ExtendedInterpolatedSurface(double[] rows, double[] columns, double[] forwards, Matrix values, IInterpolation xInterpolation, IInterpolation yInterpolation) : base(new DiscreteSurface(rows, columns, values), xInterpolation, yInterpolation, true) { var width = values.ColumnCount; var discreteSurface = new DiscreteSurface(rows, columns, values); var x = discreteSurface.XArray; if (forwards != null) { SpotValue = forwards[0]; var n = forwards.Length; var fwds = new double[n - 1]; for (var index = 1; index < n; index++) { fwds[index - 1] = forwards[index]; } ForwardCurve = new LinearInterpolation(); ForwardCurve.Initialize(rows, fwds); } if (yInterpolation.GetType() == typeof(SABRModelInterpolation)) { var length = values.RowCount; var y = discreteSurface.YArray; for (int i = 0; i < length; i++) { //interpolate each maturity first (in strike) with SABR var yinterp = (SABRModelInterpolation)yInterpolation.Clone(); yinterp.ExpiryTime = x[i]; if (Forward != null && Spot != null) { yinterp.AssetPrice = Convert.ToDecimal(Forward); } else { var fwd = ForwardCurve.ValueAt(yinterp.ExpiryTime, true); yinterp.AssetPrice = Convert.ToDecimal(fwd); } yinterp.Initialize(y, values.Row(i).Data); var curve = new DiscreteCurve(y, values.Row(i).Data); var interpolatedCol = new InterpolatedCurve(curve, yinterp, true); _interpolatedColumns.Add(interpolatedCol); } } else //o.w interpolate at each strike point (in time) { for (int i = 0; i < width; i++) { var interp = xInterpolation.Clone(); interp.Initialize(x, values.Column(i).Data); var curve = new DiscreteCurve(x, values.Column(i).Data); var interpolatedCol = new InterpolatedCurve(curve, interp, true); _interpolatedColumns.Add(interpolatedCol); } } }
private static void LeastSquaresConjugateGradient(Dictionary <int, Dictionary <int, double> > Cui, Matrix <double> X, Matrix <double> Y, double regularization, int iterations = 3) { var users = X.RowCount; var factors = X.ColumnCount; var YtY = Y.TransposeThisAndMultiply(Y).Add(Matrix <double> .Build.DenseIdentity(factors).Multiply(regularization)); Parallel.For(0, users, u => { var xu = X.Row(u); var r = YtY.Multiply(xu).Multiply(-1); foreach (var pair in Cui[u]) { var i = pair.Key; var confidence = pair.Value; var yi = Y.Row(i); r.Add(yi.Multiply(confidence - ((confidence - 1) * yi.DotProduct(xu))), r); } var p = r.Clone(); var rsold = r.DotProduct(r); for (var iteration = 0; iteration < iterations; iteration++) { var Ap = YtY.Multiply(p); foreach (var pair in Cui[u]) { var i = pair.Key; var confidence = pair.Value; var yi = Y.Row(i); Ap.Add(yi.Multiply(yi.DotProduct(p)).Multiply(confidence - 1), Ap); } var alpha = rsold / p.DotProduct(Ap); xu.Add(p.Multiply(alpha), xu); r.Subtract(Ap.Multiply(alpha), r); var rsnew = r.DotProduct(r); if (rsnew < UserFeatures.Epsilon) { break; } p = r.Add(p.Multiply(rsnew / rsold)); rsold = rsnew; } X.SetRow(u, xu); }); }
private static Matrix <double> CumSum(Matrix <double> W) { Vector <double> tmp = Vector <double> .Build.Dense(W.ColumnCount, 0.0); for (int i = 0; i < W.RowCount; i++) { W.SetRow(i, W.Row(i) + tmp); tmp = W.Row(i); } return(W); }
public static void ExchangeRows(this Matrix <double> matrix, int from, int to) { if (from >= matrix.RowCount || to >= matrix.RowCount) { throw new Exception("Exchange Rows row index out of bounds!"); } var tmp = matrix.Row(to); matrix.SetRow(to, matrix.Row(from)); matrix.SetRow(from, tmp); }
/// <summary> /// Procustes statistics which gives a (di)similiarity measure of two set of points, by removing translation, rotation and dilation(stretching) degrees of freedom. /// Zero as result means the two sets of points are basically the same after translation, rotation and dilation with the corresponding matrices. /// Reference: Modern Multidimensional Scaling, Theory and Applications, page 436, Procrustes Analysis /// </summary> /// <param name="A"></param> /// <param name="B"></param> /// <returns></returns> public static Tuple <String, double> ProcrustesStatistics(List <Point> A, List <Point> B) { int n = A.Count; //make A to be unitlength double minX = A.Min(p => p.X); double maxX = A.Max(p => p.X); double minY = A.Min(p => p.Y); double maxY = A.Max(p => p.Y); double deltaX = maxX - minX; double deltaY = maxY - minY; double scale = Math.Max(deltaX, deltaY); A = A.Select(p => new Point(p.X / scale, p.Y / scale)).ToList(); var centerA = new Point(A.Average(a => a.X), A.Average(a => a.Y)); var centerB = new Point(B.Average(b => b.X), B.Average(b => b.Y)); Matrix X = DenseMatrix.Create(n, 2, (i, j) => j == 0 ? A[i].X:A[i].Y); Matrix Y = DenseMatrix.Create(n, 2, (i, j) => j == 0 ? B[i].X:B[i].Y); Matrix Xc = DenseMatrix.Create(n, 2, (i, j) => j == 0 ? A[i].X - centerA.X : A[i].Y - centerA.Y); Matrix Yc = DenseMatrix.Create(n, 2, (i, j) => j == 0 ? B[i].X - centerB.X : B[i].Y - centerB.Y); //Reference: Modern Multidimensional Scaling, Theory and Applications, page 436, Procrustes Analysis DenseMatrix C = (DenseMatrix)(Xc.Transpose() * Y); Svd svd = new DenseSvd(C, true); //rotation Matrix <double> T = (svd.VT().Transpose()) * (svd.U().Transpose()); //dilation double s = ((C * T).Trace()) / ((Yc.Transpose() * Y).Trace()); //column Vector with n times 1 Vector <double> vector1 = DenseVector.Create(n, i => 1); //translation vector Vector <double> t = (1.0 / n) * (X - s * Y * T).Transpose() * vector1; Matrix translationMatrix = DenseMatrix.Create(n, 2, (i, j) => t.At(j)); Matrix <double> YPrime = s * Y * T + translationMatrix; Matrix <double> delta = X - YPrime; double rSquare = 0; for (int i = 0; i < n; i++) { rSquare += delta.Row(i) * delta.Row(i); } return(Tuple.Create("ProcrustesStatistics", Math.Sqrt(rSquare))); }
private static void CalculateJaobianMatrices() { for (int i = 0; i < FiniteElementPointsCount; i++) { dxdksiVector[i] = dNdksiMatrix.Row(i) * xFiniteElementPointsVector; dydksiVector[i] = dNdksiMatrix.Row(i) * yFiniteEelementPointsVector; dxdetaVector[i] = dNdetaMatrix.Row(i) * xFiniteElementPointsVector; dydetaVector[i] = dNdetaMatrix.Row(i) * yFiniteEelementPointsVector; jacobianMatrices[i][0, 0] = dxdksiVector[i]; jacobianMatrices[i][0, 1] = dydksiVector[i]; jacobianMatrices[i][1, 0] = dxdetaVector[i]; jacobianMatrices[i][1, 1] = dydetaVector[i]; } }
private static int OrthogonalizeRows(Matrix <double> M, int i, int idx, int nRows) { var q_j = M.Row(i); var end = idx + nRows; for (int k = idx; k < end; k++) { var v_k = M.Row(k); M.SetRow(k, v_k - ((q_j * v_k) * q_j)); } return(1); }
/// <summary> /// Generate primal coefficients from dual coefficients /// for the one-vs-one multi class LibSVM in the case /// of a linear kernel. /// </summary> private static Vector <double>[] OneVsOneCoef( Matrix <double> dualCoef, int[] nSupport, Matrix <double> supportVectors) { // get 1vs1 weights for all n*(n-1) classifiers. // this is somewhat messy. // shape of dual_coef_ is nSV * (n_classes -1) // see docs for details int nClass = dualCoef.RowCount + 1; // XXX we could do preallocation of coef but // would have to take care in the sparse case var coef = new List <Vector <double> >(); var svLocs = CumSum(new[] { 0 }.Concat(nSupport).ToArray()); for (int class1 = 0; class1 < nClass; class1++) { // SVs for class1: var sv1 = supportVectors.SubMatrix( svLocs[class1], svLocs[class1 + 1] - svLocs[class1], 0, supportVectors.ColumnCount); for (int class2 = class1 + 1; class2 < nClass; class2++) { // SVs for class1: var sv2 = supportVectors.SubMatrix( svLocs[class2], svLocs[class2 + 1] - svLocs[class2], 0, supportVectors.ColumnCount); // dual coef for class1 SVs: var alpha1 = dualCoef.Row(class2 - 1).SubVector( svLocs[class1], svLocs[class1 + 1] - svLocs[class1]); // dual coef for class2 SVs: var alpha2 = dualCoef.Row(class1).SubVector( svLocs[class2], svLocs[class2 + 1] - svLocs[class2]); // build weight for class1 vs class2 coef.Add((alpha1 * sv1) + (alpha2 * sv2)); } } return(coef.ToArray()); }
private static double CalculateLoss(Dictionary <int, Dictionary <int, double> > Cui, Matrix <double> X, Matrix <double> Y, double regularization) { var nnz = 0; var loss = 0.0; var total_confidence = 0.0; var item_norm = 0.0; var user_norm = 0.0; var factors = X.ColumnCount; var YtY = Y.TransposeThisAndMultiply(Y); var xu = Vector <double> .Build.Dense(factors); var yi = Vector <double> .Build.Dense(factors); var r = Vector <double> .Build.Dense(factors); for (var u = 0; u < X.RowCount; u++) { X.Row(u, xu); YtY.Multiply(xu, r); foreach (var pair in Cui[u]) { var i = pair.Key; var confidence = pair.Value; Y.Row(i, yi); var temp = ((confidence - 1) * yi.DotProduct(xu)) - (2 * confidence); r.Add(yi.Multiply(temp), r); nnz += 1; total_confidence += confidence; loss += confidence; } loss += r.DotProduct(xu); user_norm += xu.DotProduct(xu); } for (var i = 0; i < Y.RowCount; i++) { Y.Row(i, yi); item_norm += yi.DotProduct(yi); } loss += regularization * (item_norm + user_norm); return(loss / (total_confidence + (Y.RowCount * X.RowCount) - nnz)); }
public override Matrix ProcessForPrediction(Matrix m, VectorType vtype = VectorType.Column, Vector xMean = null, Vector xScale = null) { var mean = xMean == null ? this._m : xMean; int cols = m.ColumnCount; int rows = m.RowCount; var result = new DenseMatrix(rows, cols); var meanRow = new DenseVector(cols); var meanCol = new DenseVector(rows); for (int n = 0; n < rows; n++) { meanCol[n] = m.Row(n).Sum() / cols; } for (int n = 0; n < cols; n++) { meanRow[n] = m.Column(n).Sum() / rows; } if (vtype == VectorType.Row) { var m3 = mean.Sum() / mean.Count; for (int i = 0; i < rows; i++) { var d1 = m.Row(i).Subtract(meanCol[i]); var d2 = mean.Subtract(m3); var b = d1.DotProduct(d2) / d2.DotProduct(d2); var a = meanCol[i] - b * m3; result.SetRow(i, m.Row(i).Subtract(a) / b); } this._m = meanRow; } else { var m3 = mean.Sum() / mean.Count; for (int i = 0; i < cols; i++) { var d1 = m.Column(i).Subtract(meanRow[i]); var d2 = mean.Subtract(m3); var b = d1.DotProduct(d2) / d2.DotProduct(d2); var a = meanRow[i] - b * m3; result.SetColumn(i, m.Column(i).Subtract(a) / b); } this._m = meanCol; } return(result); }
//build the matrix M for SIRT-Cimmino public Matrix <double> MBuilderCimmino() { int m = _A.RowCount; Vector <double> mDiag = Vector <double> .Build.Dense(m, 0); for (int i = 0; i < m; i++) { double diag = _A.Row(i).L2Norm(); mDiag[i] = 1 / (m * diag * diag); } Matrix <double> M = Matrix <double> .Build.DenseOfDiagonalVector(m, m, mDiag); return(M); }
private double loss(Matrix <double> X, Matrix <double> Y) { Matrix <double> y = predict(X); Vector <double> yv = CreateVector.Dense <double>(X.RowCount); foreach (MathNet.Numerics.Tuple <int, Vector <double> > row in y.EnumerateRowsIndexed()) { yv[row.Item1] = Y.Row(row.Item1)[0] == 1.0 ? y.Row(row.Item1)[0] : y.Row(row.Item1)[1]; } Vector <double> correctLogs = -1.0 * yv.PointwiseLog(); double loss = correctLogs.Sum(); return((1.0 / (double)X.RowCount) * loss); }
public void CanGetRowIntoResult(Matrix <T> matrix) { var row = CreateVectorZero(matrix.ColumnCount); matrix.Row(0, row); for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(matrix[0, j], row[j]); } Assert.That(() => matrix.Row(0, null), Throws.InstanceOf <ArgumentNullException>()); Assert.That(() => matrix.Row(-1, row), Throws.InstanceOf <ArgumentOutOfRangeException>()); Assert.That(() => matrix.Row(matrix.RowCount, row), Throws.InstanceOf <ArgumentOutOfRangeException>()); }
/// <summary>Generates a clustering.</summary> /// <param name="X">The Matrix to process.</param> /// <param name="linker">The linker.</param> /// <param name="data">(Optional) the data.</param> /// <returns>The clustering.</returns> private Cluster GenerateClustering(Matrix X, ILinker linker, object[] data = null) { // Initialize Linker = linker; var clusters = new List<Cluster>(); var distances = new Dictionary<Tuple<int, int>, double>(); // Create a new cluster for each data point for (int i = 0; i < X.Rows; i++) clusters.Add(new Cluster { Id = i, Points = new Vector[] { (Vector)X.Row(i) }, Members = data != null ? new object[] { data[i] } : new object[] { X.Row(i) } }); // Set the current closest distance/pair to the first pair of clusters var key = new Tuple<int, int>(0, 0); var distance = 0.0; var clusterId = X.Rows; while (clusters.Count > 1) { var closestClusters = new Tuple<int, int>(0, 1); var smallestDistance = Linker.Distance(clusters[0].Points, clusters[1].Points); // this needs to be parallelized.... // Loop through each of the clusters looking for the two closest for (int i = 0; i < clusters.Count; i++) { for (int j = i + 1; j < clusters.Count; j++) { key = new Tuple<int, int>(clusters[i].Id, clusters[j].Id); // Cache the distance if it hasn't been calculated yet if (!distances.ContainsKey(key)) distances.Add(key, Linker.Distance(clusters[i].Points, clusters[j].Points)); // Update closest clusters and distance if necessary distance = distances[key]; if (distance < smallestDistance) { smallestDistance = distance; closestClusters = new Tuple<int, int>(i, j); } } } // order clusters by distance var min = System.Math.Min(closestClusters.Item1, closestClusters.Item2); var max = System.Math.Max(closestClusters.Item1, closestClusters.Item2); var newCluster = new Cluster(clusterId, clusters[min], clusters[max]); // Remove the merged clusters clusters.RemoveAt(min); clusters.RemoveAt(max - 1); // Add new cluster clusters.Add(newCluster); clusterId++; } return clusters.Single(); }
/// <summary> /// Каждый элемент матрицы - вектора значений подставляется в соответсвующую строку исходной матрицы. /// Не знаю зачем этот метод. /// </summary> /// <param name="valuesVector"></param> /// <returns></returns> public Matrix SetVariablesValuessByOne(Matrix valuesVector) { if (!(this[0, 0] is FunctionMatrixElement)) return new Matrix(this); Matrix m = new Matrix(this.Rows, this.Cols, new FunctionMatrixElement()); for (int i = 0; i < this.Rows; i++) { for (int j = 0; j < this.Cols; j++) { var temp = valuesVector.Row(i); Matrix tempM = new Matrix(1, temp.Length); int k = 0; foreach (var item in temp) { tempM[0, k] = temp[k++]; } m[i, j] = new FunctionMatrixElement((this[i, j] as FunctionMatrixElement).Function.SetVariablesValues(tempM)); } } return m; }
public static Matrix HorizontalConcat(Matrix A, Matrix B) { Matrix C = A.Row(1); for (int i = 2; i <= A.RowCount; i++) { C.InsertRow(A.Row(i), i); } for (int i = 1; i <= B.RowCount; i++) { C.InsertRow(B.Row(i), C.RowCount + 1); } return C; }
/// <summary> /// Return a new matrix after GaussianElimination (row reduction) of the original matrix /// </summary> /// <returns></returns> public Matrix GaussianElimination() { //if (Height != Width) // throw new Exception(); Matrix newM = new Matrix(this); int position = -1; double param = 0; int count = 0; Vector positionV = new Vector(Width); for (int i = 0; i < Width; i++) { if (position != -1) { newM.SwitchRow(position, count); count++; position = -1; } for (int j = count; j < Height; j++) { if (newM.field[i, j] != 0) { if (position != -1) newM.SetRow(j, newM.Row(j) - positionV * newM[i, j] / param); else { position = j; param = newM[i, j]; newM.SetRow(j, newM.Row(j)); positionV = newM.Row(j); } } } } return newM; }
public int[] Extract_last_row(string input) { var matrix = new Matrix(input); return matrix.Row(matrix.Rows - 1); }
public int[] Extract_first_row(string input) { var matrix = new Matrix(input); return matrix.Row(0); }