@Override public void write(DataOutput out) throws IOException { if (mat.isSparse()) { out.writeByte(SPARSE_DOUBLE_ROW_MATRIX); writeSparseMatrix((SparseDoubleRowMatrix) mat, out); } else { out.writeByte(DENSE_DOUBLE_MATRIX); writeDenseMatrix((DenseDoubleMatrix) mat, out); } }
protected DoubleMatrix newInstance(DoubleMatrix mat) { if (mat.isSparse()) { return new SparseDoubleRowMatrix(mat.getRowCount(), mat.getColumnCount()); } else { return new DenseDoubleMatrix(mat.getRowCount(), mat.getColumnCount()); } }
@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; }
@Override public DoubleMatrix apply(DoubleMatrix matrix) { DoubleMatrix newInstance = newInstance(matrix); if (matrix.isSparse()) { // if we have a sparse matrix, it is more efficient to loop over the // sparse row vectors int[] rows = matrix.rowIndices(); for (int row : rows) { DoubleVector rowVector = matrix.getRowVector(row); if (rowVector.getLength() > 0) { DoubleVector apply = apply(rowVector); newInstance.setRowVector(row, apply); } } } 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, apply(matrix.get(i, j))); } } } return newInstance; }