List of usage examples for org.apache.commons.math3.linear RealMatrix transpose
RealMatrix transpose();
From source file:org.wso2.siddhi.extension.kf.KalmanFilter.java
@Override protected Object execute(Object[] data) { if (data[0] == null) { throw new ExecutionPlanRuntimeException( "Invalid input given to kf:kalmanFilter() " + "function. First argument should be a double"); }/* w w w. j av a 2 s. com*/ if (data[1] == null) { throw new ExecutionPlanRuntimeException( "Invalid input given to kf:kalmanFilter() " + "function. Second argument should be a double"); } if (data.length == 2) { double measuredValue = (Double) data[0]; //to remain as the initial state if (prevEstimatedValue == 0) { transition = 1; variance = 1000; measurementNoiseSD = (Double) data[1]; prevEstimatedValue = measuredValue; } prevEstimatedValue = transition * prevEstimatedValue; double kalmanGain = variance / (variance + measurementNoiseSD); prevEstimatedValue = prevEstimatedValue + kalmanGain * (measuredValue - prevEstimatedValue); variance = (1 - kalmanGain) * variance; return prevEstimatedValue; } else { if (data[2] == null) { throw new ExecutionPlanRuntimeException("Invalid input given to kf:kalmanFilter() " + "function. Third argument should be a double"); } if (data[3] == null) { throw new ExecutionPlanRuntimeException( "Invalid input given to kf:kalmanFilter() " + "function. Fourth argument should be a long"); } double measuredXValue = (Double) data[0]; double measuredChangingRate = (Double) data[1]; double measurementNoiseSD = (Double) data[2]; long timestamp = (Long) data[3]; long timestampDiff; double[][] measuredValues = { { measuredXValue }, { measuredChangingRate } }; if (measurementMatrixH == null) { timestampDiff = 1; double[][] varianceValues = { { 1000, 0 }, { 0, 1000 } }; double[][] measurementValues = { { 1, 0 }, { 0, 1 } }; measurementMatrixH = MatrixUtils.createRealMatrix(measurementValues); varianceMatrixP = MatrixUtils.createRealMatrix(varianceValues); prevMeasuredMatrix = MatrixUtils.createRealMatrix(measuredValues); } else { timestampDiff = (timestamp - prevTimestamp); } double[][] Rvalues = { { measurementNoiseSD, 0 }, { 0, measurementNoiseSD } }; RealMatrix rMatrix = MatrixUtils.createRealMatrix(Rvalues); double[][] transitionValues = { { 1d, timestampDiff }, { 0d, 1d } }; RealMatrix transitionMatrixA = MatrixUtils.createRealMatrix(transitionValues); RealMatrix measuredMatrixX = MatrixUtils.createRealMatrix(measuredValues); //Xk = (A * Xk-1) prevMeasuredMatrix = transitionMatrixA.multiply(prevMeasuredMatrix); //Pk = (A * P * AT) + Q varianceMatrixP = (transitionMatrixA.multiply(varianceMatrixP)).multiply(transitionMatrixA.transpose()); //S = (H * P * HT) + R RealMatrix S = ((measurementMatrixH.multiply(varianceMatrixP)).multiply(measurementMatrixH.transpose())) .add(rMatrix); RealMatrix S_1 = new LUDecomposition(S).getSolver().getInverse(); //P * HT * S-1 RealMatrix kalmanGainMatrix = (varianceMatrixP.multiply(measurementMatrixH.transpose())).multiply(S_1); //Xk = Xk + kalmanGainMatrix (Zk - HkXk ) prevMeasuredMatrix = prevMeasuredMatrix.add(kalmanGainMatrix .multiply((measuredMatrixX.subtract(measurementMatrixH.multiply(prevMeasuredMatrix))))); //Pk = Pk - K.Hk.Pk varianceMatrixP = varianceMatrixP .subtract((kalmanGainMatrix.multiply(measurementMatrixH)).multiply(varianceMatrixP)); prevTimestamp = timestamp; return prevMeasuredMatrix.getRow(0)[0]; } }
From source file:pl.matrix.core.MatrixCalculator.java
public Matrix transposeMatrix(Matrix a) { RealMatrix aRealMatrix = a.toRealMatrix(); Matrix result = new Matrix(aRealMatrix.transpose()); return result; }
From source file:playground.sergioo.facilitiesGenerator2012.WorkFacilitiesGeneration.java
private static Set<PointPerson> getPCATransformation(Collection<PointPerson> points) { RealMatrix pointsM = new Array2DRowRealMatrix(points.iterator().next().getDimension(), points.size()); int k = 0;/* w ww. ja va 2s . c o m*/ for (PointND<Double> point : points) { for (int f = 0; f < point.getDimension(); f++) pointsM.setEntry(f, k, point.getElement(f)); k++; } RealMatrix means = new Array2DRowRealMatrix(pointsM.getRowDimension(), 1); for (int r = 0; r < means.getRowDimension(); r++) { double mean = 0; for (int c = 0; c < pointsM.getColumnDimension(); c++) mean += pointsM.getEntry(r, c) / pointsM.getColumnDimension(); means.setEntry(r, 0, mean); } RealMatrix deviations = new Array2DRowRealMatrix(pointsM.getRowDimension(), pointsM.getColumnDimension()); for (int r = 0; r < deviations.getRowDimension(); r++) for (int c = 0; c < deviations.getColumnDimension(); c++) deviations.setEntry(r, c, pointsM.getEntry(r, c) - means.getEntry(r, 0)); RealMatrix covariance = deviations.multiply(deviations.transpose()) .scalarMultiply(1 / (double) pointsM.getColumnDimension()); EigenDecomposition eigenDecomposition = new EigenDecomposition(covariance, 0); RealMatrix eigenVectorsT = eigenDecomposition.getVT(); RealVector eigenValues = new ArrayRealVector(eigenDecomposition.getD().getRowDimension()); for (int r = 0; r < eigenDecomposition.getD().getRowDimension(); r++) eigenValues.setEntry(r, eigenDecomposition.getD().getEntry(r, r)); for (int i = 0; i < eigenValues.getDimension(); i++) { for (int j = i + 1; j < eigenValues.getDimension(); j++) if (eigenValues.getEntry(i) < eigenValues.getEntry(j)) { double tempValue = eigenValues.getEntry(i); eigenValues.setEntry(i, eigenValues.getEntry(j)); eigenValues.setEntry(j, tempValue); RealVector tempVector = eigenVectorsT.getRowVector(i); eigenVectorsT.setRowVector(i, eigenVectorsT.getRowVector(j)); eigenVectorsT.setRowVector(j, tempVector); } eigenVectorsT.setRowVector(i, eigenVectorsT.getRowVector(i).mapMultiply(Math.sqrt(1 / eigenValues.getEntry(i)))); } RealVector standardDeviations = new ArrayRealVector(pointsM.getRowDimension()); for (int r = 0; r < covariance.getRowDimension(); r++) standardDeviations.setEntry(r, Math.sqrt(covariance.getEntry(r, r))); double zValue = standardDeviations.dotProduct(new ArrayRealVector(pointsM.getRowDimension(), 1)); RealMatrix zScore = deviations.scalarMultiply(1 / zValue); pointsM = eigenVectorsT.multiply(zScore); Set<PointPerson> pointsC = new HashSet<PointPerson>(); k = 0; for (PointPerson point : points) { PointPerson pointC = new PointPerson(point.getId(), point.getOccupation(), new Double[] { pointsM.getEntry(0, k), pointsM.getEntry(1, k) }, point.getPlaceType()); pointC.setWeight(point.getWeight()); pointsC.add(pointC); k++; } return pointsC; }
From source file:plugins.SURFPixelMatching.java
private void run() { try {/*from w w w . j a v a 2 s .com*/ // variables int a, b, c, i, j, k, n, r; int row, col; int progress, oldProgress; double x, y, z, newX, newY; double x2, y2; double north, south, east, west; double newNorth, newSouth, newEast, newWest; double rightNodata; double leftNodata; Object[] rowData; whitebox.geospatialfiles.shapefile.Point outputPoint; ShapeFile rightTiePoints; ShapeFile leftTiePoints; ShapeFile rightFiducials; ShapeFile leftFiducials; XYPoint xyPoint; ArrayList<XYPoint> leftTiePointsList = new ArrayList<>(); ArrayList<XYPoint> rightTiePointsList = new ArrayList<>(); float balanceValue = 0.81f; float threshold = 0.004f; int octaves = 4; double maxAllowableRMSE = 1.0; double matchingThreshold = 0.6; // left image //String leftImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/GuelphCampus_C6430-74072-L9_253_Blue_clipped.dep"; //String leftImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/Guelph_A19409-82_Blue.dep"; //String leftImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/GuelphCampus 253.dep"; //String leftImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/GuelphCampus 253 epipolar.dep"; String leftImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/Guelph_A19409-82_Blue low res.dep"; //String leftImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/tmp1.dep"; // right image //String rightImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/GuelphCampus_C6430-74072-L9_254_Blue_clipped.dep"; //String rightImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/Guelph_A19409-83_Blue.dep"; //String rightImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/GuelphCampus 254.dep"; //String rightImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/GuelphCampus 254 epipolar.dep"; String rightImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/Guelph_A19409-83_Blue low res.dep"; //String rightImageName = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/GuelphCampus 253.dep"; String leftOutputHeader = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/tmp4.shp"; String rightOutputHeader = "/Users/johnlindsay/Documents/Teaching/GEOG2420/airphotos/tmp4_2.shp"; DBFField[] fields = new DBFField[5]; fields[0] = new DBFField(); fields[0].setName("FID"); fields[0].setDataType(DBFField.DBFDataType.NUMERIC); fields[0].setDecimalCount(4); fields[0].setFieldLength(10); fields[1] = new DBFField(); fields[1].setName("ORIENT"); fields[1].setDataType(DBFField.DBFDataType.NUMERIC); fields[1].setDecimalCount(4); fields[1].setFieldLength(10); fields[2] = new DBFField(); fields[2].setName("SCALE"); fields[2].setDataType(DBFField.DBFDataType.NUMERIC); fields[2].setDecimalCount(4); fields[2].setFieldLength(10); fields[3] = new DBFField(); fields[3].setName("LAPLAC"); fields[3].setDataType(DBFField.DBFDataType.NUMERIC); fields[3].setDecimalCount(4); fields[3].setFieldLength(10); fields[4] = new DBFField(); fields[4].setName("RESID"); fields[4].setDataType(DBFField.DBFDataType.NUMERIC); fields[4].setDecimalCount(4); fields[4].setFieldLength(10); // read the input data WhiteboxRaster leftImage = new WhiteboxRaster(leftImageName, "r"); // leftImage.setForceAllDataInMemory(true); int nRowsLeft = leftImage.getNumberRows(); int nColsLeft = leftImage.getNumberColumns(); leftNodata = leftImage.getNoDataValue(); WhiteboxRaster rightImage = new WhiteboxRaster(rightImageName, "r"); //rightImage.setForceAllDataInMemory(true); // int nRowsRight = rightImage.getNumberRows(); // int nColsRight = rightImage.getNumberColumns(); rightNodata = rightImage.getNoDataValue(); // ArrayList<InterestPoint> interest_points; // double threshold = 600; // double balanceValue = 0.9; // int octaves = 4; // ISURFfactory mySURF = SURF.createInstance(leftImage, balanceValue, threshold, octaves); // IDetector detector = mySURF.createDetector(); // interest_points = detector.generateInterestPoints(); // System.out.println("Interest points generated"); // IDescriptor descriptor = mySURF.createDescriptor(interest_points); // descriptor.generateAllDescriptors(); System.out.println("Performing SURF analysis on left image..."); Surf leftSurf = new Surf(leftImage, balanceValue, threshold, octaves); // if (leftSurf.getNumberOfPoints() > 500000) { // System.out.println("Number of points exceeds limit, reset threshold: " + leftSurf.getNumberOfPoints()); // return; // } if (leftSurf.getNumberOfPoints() == 0) { System.out .println("Number of points equals zero, reset threshold: " + leftSurf.getNumberOfPoints()); return; } System.out.println("Performing SURF analysis on right image..."); Surf rightSurf = new Surf(rightImage, balanceValue, threshold, octaves); if (rightSurf.getNumberOfPoints() == 0) { System.out .println("Number of points equals zero, reset threshold: " + leftSurf.getNumberOfPoints()); return; } System.out.println("Matching points of interest..."); Map<SURFInterestPoint, SURFInterestPoint> matchingPoints = leftSurf.getMatchingPoints(rightSurf, matchingThreshold, false); int numTiePoints = matchingPoints.size(); if (numTiePoints < 3) { System.err.println( "The number of potential tie points is less than 3. Adjust your threshold parameters and retry."); return; } System.out.println(numTiePoints + " potential tie points located"); System.out.println("Trimming outlier tie points..."); boolean flag; do { flag = false; leftTiePointsList.clear(); rightTiePointsList.clear(); i = 0; for (SURFInterestPoint point : matchingPoints.keySet()) { x = point.getX(); y = point.getY(); SURFInterestPoint target = matchingPoints.get(point); x2 = target.getX(); y2 = target.getY(); leftTiePointsList.add(new XYPoint(x, y)); rightTiePointsList.add(new XYPoint(x2, y2)); i++; } PolynomialLeastSquares2DFitting overallFit = new PolynomialLeastSquares2DFitting(leftTiePointsList, rightTiePointsList, 1); double maxDist = 0; SURFInterestPoint mostInfluentialPoint = null; i = 0; for (SURFInterestPoint point : matchingPoints.keySet()) { leftTiePointsList.clear(); rightTiePointsList.clear(); for (SURFInterestPoint point2 : matchingPoints.keySet()) { if (point2 != point) { x = point2.getX(); y = point2.getY(); SURFInterestPoint target = matchingPoints.get(point2); x2 = target.getX(); y2 = target.getY(); leftTiePointsList.add(new XYPoint(x, y)); rightTiePointsList.add(new XYPoint(x2, y2)); } } PolynomialLeastSquares2DFitting newFit = new PolynomialLeastSquares2DFitting(leftTiePointsList, rightTiePointsList, 1); x = point.getX(); y = point.getY(); XYPoint pt1 = overallFit.getForwardCoordinates(x, y); XYPoint pt2 = newFit.getForwardCoordinates(x, y); double dist = pt1.getSquareDistance(pt2); if (dist > maxDist) { maxDist = dist; mostInfluentialPoint = point; } } if (maxDist > 10 && mostInfluentialPoint != null) { matchingPoints.remove(mostInfluentialPoint); flag = true; } System.out.println(maxDist); } while (flag); int numPoints = matchingPoints.size(); // create homogeneous points matrices double[][] leftPoints = new double[3][numPoints]; double[][] rightPoints = new double[3][numPoints]; i = 0; for (SURFInterestPoint point : matchingPoints.keySet()) { leftPoints[0][i] = point.getX(); leftPoints[1][i] = point.getY(); leftPoints[2][i] = 1; SURFInterestPoint target = matchingPoints.get(point); rightPoints[0][i] = target.getX(); rightPoints[1][i] = target.getY(); rightPoints[2][i] = 1; i++; } double[][] normalizedLeftPoints = Normalize2DHomogeneousPoints.normalize(leftPoints); RealMatrix Tl = MatrixUtils.createRealMatrix(Normalize2DHomogeneousPoints.T); double[][] normalizedRightPoints = Normalize2DHomogeneousPoints.normalize(rightPoints); RealMatrix Tr = MatrixUtils.createRealMatrix(Normalize2DHomogeneousPoints.T); RealMatrix pnts1 = MatrixUtils.createRealMatrix(normalizedLeftPoints); RealMatrix pnts2 = MatrixUtils.createRealMatrix(normalizedRightPoints); RealMatrix A = MatrixUtils.createRealMatrix(buildA(normalizedLeftPoints, normalizedRightPoints)); //RealMatrix ata = A.transpose().multiply(A); SingularValueDecomposition svd = new SingularValueDecomposition(A); RealMatrix V = svd.getV(); RealVector V_smallestSingularValue = V.getColumnVector(8); RealMatrix F = MatrixUtils.createRealMatrix(3, 3); for (i = 0; i < 9; i++) { F.setEntry(i / 3, i % 3, V_smallestSingularValue.getEntry(i)); } for (i = 0; i < V.getRowDimension(); i++) { System.out.println(V.getRowVector(i).toString()); } SingularValueDecomposition svd2 = new SingularValueDecomposition(F); RealMatrix U = svd2.getU(); RealMatrix S = svd2.getS(); V = svd2.getV(); RealMatrix m = MatrixUtils.createRealMatrix( new double[][] { { S.getEntry(1, 1), 0, 0 }, { 0, S.getEntry(2, 2), 0 }, { 0, 0, 0 } }); F = U.multiply(m).multiply(V).transpose(); // Denormalise F = Tr.transpose().multiply(F).multiply(Tl); for (i = 0; i < F.getRowDimension(); i++) { System.out.println(F.getRowVector(i).toString()); } svd2 = new SingularValueDecomposition(F); //[U,D,V] = svd(F,0); RealMatrix e1 = svd2.getV().getColumnMatrix(2); //hnormalise(svd2.getV(:,3)); RealMatrix e2 = svd2.getU().getColumnMatrix(2); //e2 = hnormalise(U(:,3)); e1.setEntry(0, 0, (e1.getEntry(0, 0) / e1.getEntry(2, 0))); e1.setEntry(1, 0, (e1.getEntry(1, 0) / e1.getEntry(2, 0))); e1.setEntry(2, 0, 1); e2.setEntry(0, 0, (e2.getEntry(0, 0) / e2.getEntry(2, 0))); e2.setEntry(1, 0, (e2.getEntry(1, 0) / e2.getEntry(2, 0))); e2.setEntry(2, 0, 1); System.out.println(""); // boolean[] removeTiePoint = new boolean[numTiePoints]; // double[] residuals = null; // double[] residualsOrientation = null; // boolean flag; // do { // // perform the initial tie point transformation // leftTiePointsList.clear(); // rightTiePointsList.clear(); // int numPointsIncluded = 0; // i = 0; // for (SURFInterestPoint point : matchingPoints.keySet()) { // if (i < numTiePoints && !removeTiePoint[i]) { // x = point.getX(); // y = point.getY(); // // SURFInterestPoint target = matchingPoints.get(point); // x2 = target.getX(); // y2 = target.getY(); // // leftTiePointsList.add(new XYPoint(x, y)); // rightTiePointsList.add(new XYPoint(x2, y2)); // // numPointsIncluded++; // } // i++; // } // // PolynomialLeastSquares2DFitting plsFit = new PolynomialLeastSquares2DFitting( // leftTiePointsList, rightTiePointsList, 1); // // double rmse = plsFit.getOverallRMSE(); // System.out.println("RMSE: " + rmse + " with " + numPointsIncluded + " points included."); // // flag = false; // residuals = plsFit.getResidualsXY(); // residualsOrientation = plsFit.getResidualsOrientation(); // if (rmse > maxAllowableRMSE) { // i = 0; // for (k = 0; k < numTiePoints; k++) { // if (!removeTiePoint[k]) { // if (residuals[i] > 3 * rmse) { // removeTiePoint[k] = true; // flag = true; // } // i++; // } // } // } // } while (flag); // // i = 0; // for (k = 0; k < numTiePoints; k++) { // if (!removeTiePoint[k]) { // i++; // } // } System.out.println(numPoints + " tie points remain."); System.out.println("Outputing tie point files..."); ShapeFile leftOutput = new ShapeFile(leftOutputHeader, ShapeType.POINT, fields); ShapeFile rightOutput = new ShapeFile(rightOutputHeader, ShapeType.POINT, fields); i = 0; k = 0; for (SURFInterestPoint point : matchingPoints.keySet()) { // if (i < numTiePoints && !removeTiePoint[i]) { x = leftImage.getXCoordinateFromColumn((int) point.getX()); y = leftImage.getYCoordinateFromRow((int) point.getY()); SURFInterestPoint target = matchingPoints.get(point); x2 = rightImage.getXCoordinateFromColumn((int) target.getX()); y2 = rightImage.getYCoordinateFromRow((int) target.getY()); outputPoint = new whitebox.geospatialfiles.shapefile.Point(x, y); rowData = new Object[5]; rowData[0] = new Double(k + 1); rowData[1] = new Double(point.getOrientation()); rowData[2] = new Double(point.getScale()); rowData[3] = new Double(point.getLaplacian()); rowData[4] = new Double(0); //residuals[k]); leftOutput.addRecord(outputPoint, rowData); outputPoint = new whitebox.geospatialfiles.shapefile.Point(x2, y2); rowData = new Object[5]; rowData[0] = new Double(k + 1); rowData[1] = new Double(target.getOrientation()); rowData[2] = new Double(target.getScale()); rowData[3] = new Double(target.getLaplacian()); rowData[4] = new Double(0); //residuals[k]); rightOutput.addRecord(outputPoint, rowData); k++; // } i++; } leftOutput.write(); rightOutput.write(); System.out.println("Done!"); } catch (Exception e) { e.printStackTrace(); } }
From source file:put.ci.cevo.framework.algorithms.ApacheCMAES.java
/** * Update of the covariance matrix C.//from w ww . j ava2s . com * * @param hsig Flag indicating a small correction. * @param bestArx Fitness-sorted matrix of the argument vectors producing the current offspring. * @param arz Unsorted matrix containing the gaussian random values of the current offspring. * @param arindex Indices indicating the fitness-order of the current offspring. * @param xold xmean matrix of the previous generation. */ private void updateCovariance(boolean hsig, final RealMatrix bestArx, final RealMatrix arz, final int[] arindex, final RealMatrix xold) { double negccov = 0; if (ccov1 + ccovmu > 0) { final RealMatrix arpos = bestArx.subtract(repmat(xold, 1, mu)).scalarMultiply(1 / sigma); // mu difference vectors final RealMatrix roneu = pc.multiply(pc.transpose()).scalarMultiply(ccov1); // rank one update // minor correction if hsig==false double oldFac = hsig ? 0 : ccov1 * cc * (2 - cc); oldFac += 1 - ccov1 - ccovmu; if (isActiveCMA) { // Adapt covariance matrix C active CMA negccov = (1 - ccovmu) * 0.25 * mueff / (FastMath.pow(dimension + 2, 1.5) + 2 * mueff); // keep at least 0.66 in all directions, small popsize are most // critical final double negminresidualvariance = 0.66; // where to make up for the variance loss final double negalphaold = 0.5; // prepare vectors, compute negative updating matrix Cneg final int[] arReverseIndex = reverse(arindex); RealMatrix arzneg = selectColumns(arz, MathArrays.copyOf(arReverseIndex, mu)); RealMatrix arnorms = sqrt(sumRows(square(arzneg))); final int[] idxnorms = sortedIndices(arnorms.getRow(0)); final RealMatrix arnormsSorted = selectColumns(arnorms, idxnorms); final int[] idxReverse = reverse(idxnorms); final RealMatrix arnormsReverse = selectColumns(arnorms, idxReverse); arnorms = divide(arnormsReverse, arnormsSorted); final int[] idxInv = inverse(idxnorms); final RealMatrix arnormsInv = selectColumns(arnorms, idxInv); // check and set learning rate negccov final double negcovMax = (1 - negminresidualvariance) / square(arnormsInv).multiply(weights).getEntry(0, 0); if (negccov > negcovMax) { negccov = negcovMax; } arzneg = times(arzneg, repmat(arnormsInv, dimension, 1)); final RealMatrix artmp = BD.multiply(arzneg); final RealMatrix Cneg = artmp.multiply(diag(weights)).multiply(artmp.transpose()); oldFac += negalphaold * negccov; C = C.scalarMultiply(oldFac).add(roneu) // regard old matrix .add(arpos.scalarMultiply( // plus rank one update ccovmu + (1 - negalphaold) * negccov) // plus rank mu update .multiply(times(repmat(weights, 1, dimension), arpos.transpose()))) .subtract(Cneg.scalarMultiply(negccov)); } else { // Adapt covariance matrix C - nonactive C = C.scalarMultiply(oldFac) // regard old matrix .add(roneu) // plus rank one update .add(arpos.scalarMultiply(ccovmu) // plus rank mu update .multiply(times(repmat(weights, 1, dimension), arpos.transpose()))); } } updateBDFast(negccov); }
From source file:RBFNN.MainFrame.java
public static RealMatrix RBFtrain(ArrayList<instance> trainingdata) { RealMatrix W = MatrixUtils.createRealMatrix(K, 1); int n = K;//denotes the number of hidden layer neurons int m = trainingdata.size(); Dmax = Dmax(centers);//from w w w. j a v a 2 s. c o m double[][] hiddenout = new double[n][m]; for (int i = 0; i < n; i++) {//compute the output matrix of hidden neurons RealVector cen = MatrixUtils.createRealVector(centers.get(i).getnumFeature()); double[] outCol = new double[m]; for (int j = 0; j < m; j++) { double[] Xi = trainingdata.get(j).getnumFeature(); RealVector Xii = MatrixUtils.createRealVector(Xi); outCol[j] = Math.exp(-Math.pow(Xii.subtract(cen).getNorm(), 2) * K / (Dmax * Dmax)); //employ the Guassian function to implement } hiddenout[i] = outCol; } RealMatrix hiddenoutM = MatrixUtils.createRealMatrix(hiddenout);//n*m double[][] Yexp = new double[m][1]; for (int j = 0; j < m; j++) { Yexp[j][0] = trainingdata.get(j).getnumcls(); } RealMatrix YexpM = MatrixUtils.createRealMatrix(Yexp);//size: m*1 Matrix hiddenM = new Matrix(hiddenoutM.transpose().getData());//change to another matrix library Matrix pseuInversHM = MoorePenroseInverse.pinv(hiddenM); RealMatrix pseuInversRM = MatrixUtils.createRealMatrix(pseuInversHM.getArray()); W = pseuInversRM.multiply(YexpM);//size: n*1 or K*1 return W; }
From source file:RBFNN.MainFrame.java
public static int[] RBFtest(RealMatrix W, ArrayList<instance> testingdata, double accuracy) { //return four elements in the confusion Matrix int n = K;//denotes the number of hidden layer neurons int m = testingdata.size(); double[][] hiddenout = new double[n][m]; int[] confusion = new int[4]; for (int i = 0; i < K; i++) {//compute the output matrix of hidden neurons RealVector cen = MatrixUtils.createRealVector(centers.get(i).getnumFeature()); double[] outCol = new double[m]; for (int j = 0; j < m; j++) { double[] Xi = testingdata.get(j).getnumFeature(); RealVector Xii = MatrixUtils.createRealVector(Xi); outCol[j] = Math.exp(-Math.pow(Xii.subtract(cen).getNorm(), 2) * K / (Dmax * Dmax)); //employ the Guassian function to implement }/*from w w w . j ava2 s .com*/ hiddenout[i] = outCol; } RealMatrix hiddenoutM = MatrixUtils.createRealMatrix(hiddenout);//n*m RealMatrix YactM = hiddenoutM.transpose().multiply(W); double[][] Yexp = new double[m][1]; for (int j = 0; j < m; j++) { Yexp[j][0] = testingdata.get(j).getnumcls(); } RealMatrix YexpM = MatrixUtils.createRealMatrix(Yexp);//size: m*1 confusion = compare(YactM, YexpM); return confusion; }
From source file:shapeCompare.ProcrustesAnalysis.java
public void run(RealMatrix matrixPointsModel, RealMatrix matrixPointsCandidate) { RealMatrix transposedMatrixPointsCandidate = matrixPointsCandidate.transpose(); RealMatrix matrixToApplyToSingularValueDecomposition = matrixPointsModel .multiply(transposedMatrixPointsCandidate); SingularValueDecomposition singularValueDecomposition = new SingularValueDecomposition( matrixToApplyToSingularValueDecomposition); RealMatrix uMatrix = singularValueDecomposition.getU(); RealMatrix vTMatrix = singularValueDecomposition.getVT(); RealMatrix uVt = uMatrix.multiply(vTMatrix); LUDecomposition lUDecomposition = new LUDecomposition(uVt); double detUvT = lUDecomposition.getDeterminant(); matrixInBetween.setEntry(2, 2, detUvT); RealMatrix matrixInBetweenXvTMatrix = matrixInBetween.multiply(vTMatrix); RealMatrix rotationMatrix = uMatrix.multiply(matrixInBetweenXvTMatrix); this.rotationMatrix = rotationMatrix; RealMatrix rotatedmatrixPointsCandidate = rotationMatrix.multiply(matrixPointsCandidate); this.residual = computeResidual(matrixPointsModel, rotatedmatrixPointsCandidate); }
From source file:syncleus.dann.data.matrix.SimpleRealMatrix.java
@Override public RealMatrix solveTranspose(final RealMatrix operand) { return this.transpose().solve(operand.transpose()); }
From source file:tinfour.gwr.SurfaceGwr.java
public void computeVarianceAndHat() { if (areVarianceAndHatPrepped) { return;// w w w. j a v a2 s. c om } areVarianceAndHatPrepped = true; if (sampleWeightsMatrix == null) { throw new NullPointerException("Null specification for sampleWeightsMatrix"); } else if (sampleWeightsMatrix.length != nSamples) { throw new IllegalArgumentException("Incorrectly specified sampleWeightsMatrix"); } double[][] bigS = new double[nSamples][nSamples]; double[][] bigW = sampleWeightsMatrix; double[][] input = computeDesignMatrix(model, xOffset, yOffset, nSamples, samples); RealMatrix mX = new BlockRealMatrix(input); RealMatrix mXT = mX.transpose(); // in the loop below, we compute // Tr(hat) and Tr(Hat' x Hat) // this second term is actually the square of the // Frobenius Norm. Internally, the Apache Commons classes // may provide a more numerically stable implementation of this operation. // This may be worth future investigation. double sTrace = 0; double sTrace2 = 0; for (int i = 0; i < nSamples; i++) { DiagonalMatrix mW = new DiagonalMatrix(bigW[i]); //NOPMD RealMatrix mXTW = mXT.multiply(mW); RealMatrix rx = mX.getRowMatrix(i); RealMatrix c = mXTW.multiply(mX); QRDecomposition cd = new QRDecomposition(c); // NOPMD DecompositionSolver cdSolver = cd.getSolver(); RealMatrix cInv = cdSolver.getInverse(); RealMatrix r = rx.multiply(cInv).multiply(mXTW); double[] row = r.getRow(0); sTrace += row[i]; System.arraycopy(row, 0, bigS[i], 0, nSamples); for (int j = 0; j < nSamples; j++) { sTrace2 += row[j] * row[j]; } } hat = new BlockRealMatrix(bigS); traceHat = sTrace; traceHat2 = sTrace2; double[][] zArray = new double[nSamples][1]; for (int i = 0; i < nSamples; i++) { zArray[i][0] = samples[i][2]; } RealMatrix mY = new BlockRealMatrix(zArray); RealMatrix mYH = hat.multiply(mY); double sse = 0; for (int i = 0; i < nSamples; i++) { double yHat = mYH.getEntry(i, 0); double e = zArray[i][0] - yHat; sse += e * e; } rss = sse; double d1 = nSamples - (2 * traceHat - sTrace2); sigma2 = rss / d1; mlSigma2 = rss / nSamples; RealMatrix mIL = hat.copy(); for (int i = 0; i < nSamples; i++) { double c = 1.0 - mIL.getEntry(i, i); mIL.setEntry(i, i, c); } RealMatrix mILT = mIL.transpose().multiply(mIL); delta1 = mILT.getTrace(); delta2 = (mILT.multiply(mILT)).getTrace(); }