/** * Creates a new matrix with the given vector into the first column and the * other matrix to the other columns. This is usually used in machine learning * algorithms that add a bias on the zero-index column. * * @param first the new first column. * @param otherMatrix the other matrix to set on from the second column. */ public DenseDoubleMatrix(DenseDoubleVector first, DoubleMatrix otherMatrix) { this(otherMatrix.getRowCount(), otherMatrix.getColumnCount() + 1); // copy the first column System.arraycopy(first.toArray(), 0, matrix, 0, first.getDimension()); int offset = first.getDimension(); for (int col : otherMatrix.columnIndices()) { double[] clv = otherMatrix.getColumnVector(col).toArray(); System.arraycopy(clv, 0, matrix, offset, clv.length); offset += clv.length; } }
/** * @return the transition probabilities for the states. */ public DoubleVector getTransitionProbabilities(int[] stateSequence) { DenseDoubleVector distribution = new DenseDoubleVector( stateSequence.length - 1); for (int i = 0; i < distribution.getDimension(); i++) { distribution.set(i, transitionProbabilities.get(stateSequence[i], stateSequence[i + 1])); } return distribution; }
/** * @return a log'd matrix that was guarded against edge cases of the * logarithm. */ public static DoubleVector logVector(DoubleVector input) { DenseDoubleVector log = new DenseDoubleVector(input.getDimension()); for (int col = 0; col < log.getDimension(); col++) { log.set(col, guardedLogarithm(input.get(col))); } return log; }
@Override public Tuple<Double, DoubleVector> call() throws Exception { // loop over all particles and calculate new positions for (int particleIndex = range.getStart(); particleIndex < range.getEnd(); particleIndex++) { DoubleVector currentPosition = particlePositions[particleIndex]; DoubleVector currentBest = particlePersonalBestPositions[particleIndex]; DenseDoubleVector vec = new DenseDoubleVector(dim); for (int index = 0; index < vec.getDimension(); index++) { double value = (phi * currentPosition.get(index)) // inertia + (alpha * random.nextDouble() * (currentBest.get(index) - currentPosition .get(index))) // personal memory + (beta * random.nextDouble() * (globalBestPosition.get(index) - currentPosition .get(index))); // group memory vec.set(index, value); } particlePositions[particleIndex] = vec; double cost = f.evaluateCost(vec).getCost(); // check if we have a personal best if (cost < particlePersonalBestCost[particleIndex]) { particlePersonalBestCost[particleIndex] = cost; particlePersonalBestPositions[particleIndex] = vec; // if we had a personal best, do we have a better global? if (cost < globalCost) { globalCost = cost; globalBestPosition = vec; } } } return new Tuple<>(globalCost, globalBestPosition); }