/** * 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; } }
@Override public DoubleMatrix divide(DoubleMatrix other) { SparseDoubleRowMatrix m = new SparseDoubleRowMatrix(other); for (int row : this.matrix.keys()) { Iterator<DoubleVectorElement> iterateNonZero = matrix.get(row) .iterateNonZero(); while (iterateNonZero.hasNext()) { DoubleVectorElement e = iterateNonZero.next(); m.set(row, e.getIndex(), get(row, e.getIndex()) / other.get(row, e.getIndex())); } } for (int col : other.columnIndices()) { Iterator<DoubleVectorElement> iterateNonZero = other.getColumnVector(col) .iterateNonZero(); while (iterateNonZero.hasNext()) { DoubleVectorElement e = iterateNonZero.next(); m.set(e.getIndex(), col, get(e.getIndex(), col) / other.get(e.getIndex(), col)); } } return m; }
@Override public DoubleMatrix gradient(DoubleMatrix matrix) { DoubleMatrix newInstance = newInstance(matrix); if (matrix.isSparse()) { // if we have a sparse matrix, it is more efficient to loop over the // sparse column vectors int[] columnIndices = matrix.columnIndices(); for (int col : columnIndices) { newInstance.setColumnVector(col, gradient(matrix.getColumnVector(col))); } } else { // on dense matrices we can be faster by directly looping over the items for (int i = 0; i < matrix.getRowCount(); i++) { for (int j = 0; j < matrix.getColumnCount(); j++) { newInstance.set(i, j, gradient(matrix.get(i, j))); } } } return newInstance; }