Class DenseMatrix

java.lang.Object
org.tribuo.math.la.DenseMatrix
All Implemented Interfaces:
Serializable, Iterable<MatrixTuple>, Matrix, Tensor, ProtoSerializable<org.tribuo.math.protos.TensorProto>
Direct Known Subclasses:
ShrinkingMatrix

public class DenseMatrix extends Object implements Matrix
A dense matrix, backed by a primitive array.
See Also:
  • Field Details

    • CURRENT_VERSION

      public static final int CURRENT_VERSION
      Protobuf serialization version.
      See Also:
    • FACTORIZATION_TOLERANCE

      public static final double FACTORIZATION_TOLERANCE
      Tolerance for non-zero diagonal values in the factorizations.
      See Also:
    • values

      protected final double[][] values
      The value array.
    • dim1

      protected final int dim1
      The number of rows.
    • dim2

      protected final int dim2
      The number of columns.
  • Constructor Details

    • DenseMatrix

      public DenseMatrix(int dim1, int dim2)
      Creates a dense matrix full of zeros.
      Parameters:
      dim1 - The first dimension.
      dim2 - The second dimension.
    • DenseMatrix

      public DenseMatrix(DenseMatrix other)
      Copies the supplied matrix.
      Parameters:
      other - The matrix to copy.
    • DenseMatrix

      public DenseMatrix(Matrix other)
      Copies the supplied matrix, densifying it if it's sparse.
      Parameters:
      other - The matrix to copy.
  • Method Details

    • createDenseMatrix

      public static DenseMatrix createDenseMatrix(double[][] values)
      Defensively copies the values before construction.

      Throws IllegalArgumentException if the supplied values are a ragged array.

      Parameters:
      values - The values of this dense matrix.
      Returns:
      A new dense matrix.
    • createDenseMatrix

      public static DenseMatrix createDenseMatrix(SGDVector[] vectors)
      Constructs a new DenseMatrix copying the values from the supplied vectors.

      Throws IllegalArgumentException if the supplied vectors are ragged (i.e., are not all the same size).

      Parameters:
      vectors - The vectors to coalesce.
      Returns:
      A new dense matrix.
    • deserializeFromProto

      public static DenseMatrix deserializeFromProto(int version, String className, com.google.protobuf.Any message) throws com.google.protobuf.InvalidProtocolBufferException
      Deserialization factory.
      Parameters:
      version - The serialized object version.
      className - The class name.
      message - The serialized data.
      Returns:
      The deserialized object.
      Throws:
      com.google.protobuf.InvalidProtocolBufferException - If the protobuf could not be parsed from the message.
    • unpackProto

      protected static DenseMatrix unpackProto(org.tribuo.math.protos.DenseTensorProto proto)
      Unpacks a DenseTensorProto into a DenseMatrix.
      Parameters:
      proto - The proto to unpack.
      Returns:
      The dense matrix.
    • serialize

      public org.tribuo.math.protos.TensorProto serialize()
      Description copied from interface: ProtoSerializable
      Serializes this object to a protobuf.
      Specified by:
      serialize in interface ProtoSerializable<org.tribuo.math.protos.TensorProto>
      Returns:
      The protobuf.
    • getShape

      public int[] getShape()
      Description copied from interface: Tensor
      Returns an int array specifying the shape of this Tensor.
      Specified by:
      getShape in interface Tensor
      Returns:
      An int array.
    • reshape

      public Tensor reshape(int[] newShape)
      Description copied from interface: Tensor
      Reshapes the Tensor to the supplied shape. Throws IllegalArgumentException if the shape isn't compatible.
      Specified by:
      reshape in interface Tensor
      Parameters:
      newShape - The desired shape.
      Returns:
      A Tensor of the desired shape.
    • copy

      public DenseMatrix copy()
      Copies the matrix.
      Specified by:
      copy in interface Matrix
      Specified by:
      copy in interface Tensor
      Returns:
      A deep copy of the matrix.
    • get

      public double get(int i, int j)
      Description copied from interface: Matrix
      Gets an element from this Matrix.
      Specified by:
      get in interface Matrix
      Parameters:
      i - The index for the first dimension.
      j - The index for the second dimension.
      Returns:
      The value at matrix[i][j].
    • gatherAcrossDim1

      public DenseVector gatherAcrossDim1(int[] elements)
      Constructs a dense vector by gathering values across dimension 1.
      Parameters:
      elements - The indices to gather.
      Returns:
      A dense vector.
    • gatherAcrossDim2

      public DenseVector gatherAcrossDim2(int[] elements)
      Constructs a dense vector by gathering values across dimension 2.
      Parameters:
      elements - The indices to gather.
      Returns:
      A dense vector.
    • transpose

      public DenseMatrix transpose()
      Returns a transposed copy of this matrix.
      Returns:
      A transposed copy.
    • equals

      public boolean equals(Object o)
      Overrides:
      equals in class Object
    • hashCode

      public int hashCode()
      Overrides:
      hashCode in class Object
    • set

      public void set(int i, int j, double value)
      Description copied from interface: Matrix
      Sets an element at the supplied location.
      Specified by:
      set in interface Matrix
      Parameters:
      i - The index for the first dimension.
      j - The index for the second dimension.
      value - The value to be stored at matrix[i][j].
    • getDimension1Size

      public int getDimension1Size()
      Description copied from interface: Matrix
      The size of the first dimension.
      Specified by:
      getDimension1Size in interface Matrix
      Returns:
      The size of the first dimension.
    • getDimension2Size

      public int getDimension2Size()
      Description copied from interface: Matrix
      The size of the second dimension.
      Specified by:
      getDimension2Size in interface Matrix
      Returns:
      The size of the second dimension.
    • leftMultiply

      public DenseVector leftMultiply(SGDVector input)
      Description copied from interface: Matrix
      Multiplies this Matrix by a SGDVector returning a vector of the appropriate size.

      The input must have dimension equal to Matrix.getDimension2Size().

      Specified by:
      leftMultiply in interface Matrix
      Parameters:
      input - The input vector.
      Returns:
      A new SGDVector of size Matrix.getDimension1Size().
    • rightMultiply

      public DenseVector rightMultiply(SGDVector input)
      Description copied from interface: Matrix
      Multiplies this Matrix by a SGDVector returning a vector of the appropriate size.

      The input must have dimension equal to Matrix.getDimension1Size().

      Specified by:
      rightMultiply in interface Matrix
      Parameters:
      input - The input vector.
      Returns:
      A new SGDVector of size Matrix.getDimension2Size().
    • matrixMultiply

      public DenseMatrix matrixMultiply(Matrix other)
      Description copied from interface: Matrix
      Multiplies this Matrix by another Matrix returning a matrix of the appropriate size.

      The input must have dimension 1 equal to Matrix.getDimension2Size().

      Specified by:
      matrixMultiply in interface Matrix
      Parameters:
      other - The input matrix.
      Returns:
      A new Matrix of size Matrix.getDimension1Size(), input.getDimension2Size().
    • matrixMultiply

      public DenseMatrix matrixMultiply(Matrix other, boolean transposeThis, boolean transposeOther)
      Description copied from interface: Matrix
      Multiplies this Matrix by another Matrix returning a matrix of the appropriate size.

      Must obey the rules of matrix multiplication after the transposes are applied.

      Specified by:
      matrixMultiply in interface Matrix
      Parameters:
      other - The input matrix.
      transposeThis - Implicitly transposes this matrix just for the multiplication.
      transposeOther - Implicitly transposes other just for the multiplication.
      Returns:
      A new Matrix.
    • rowSum

      public DenseVector rowSum()
      Description copied from interface: Matrix
      Generates a DenseVector representing the sum of each row.
      Specified by:
      rowSum in interface Matrix
      Returns:
      A new DenseVector of size Matrix.getDimension1Size().
    • rowScaleInPlace

      public void rowScaleInPlace(DenseVector scalingCoefficients)
      Description copied from interface: Matrix
      Scales each row by the appropriate value in the DenseVector.
      Specified by:
      rowScaleInPlace in interface Matrix
      Parameters:
      scalingCoefficients - A DenseVector with size Matrix.getDimension1Size().
    • add

      public void add(int i, int j, double value)
      Description copied from interface: Matrix
      Adds the argument value to the value at the supplied index.
      Specified by:
      add in interface Matrix
      Parameters:
      i - The index for the first dimension.
      j - The index for the second dimension.
      value - The value to add.
    • addAcrossDim1

      public void addAcrossDim1(int[] indices, double value)
      Adds the specified value to the specified elements across dimension 1.
      Parameters:
      indices - The indices to update.
      value - The value to add.
    • addAcrossDim2

      public void addAcrossDim2(int[] indices, double value)
      Adds the specified value to the specified elements across dimension 2.
      Parameters:
      indices - The indices to update.
      value - The value to add.
    • intersectAndAddInPlace

      public void intersectAndAddInPlace(Tensor other, DoubleUnaryOperator f)
      Description copied from interface: Tensor
      Updates this Tensor by adding all the values from the intersection with other.

      The function f is applied to all values from other before the addition.

      Each value is updated as value += f(otherValue).

      Specified by:
      intersectAndAddInPlace in interface Tensor
      Parameters:
      other - The other Tensor.
      f - A function to apply.
    • hadamardProductInPlace

      public void hadamardProductInPlace(Tensor other, DoubleUnaryOperator f)
      Description copied from interface: Tensor
      Updates this Tensor with the Hadamard product (i.e., a term by term multiply) of this and other.

      The function f is applied to all values from other before the addition.

      Each value is updated as value *= f(otherValue).

      Specified by:
      hadamardProductInPlace in interface Tensor
      Parameters:
      other - The other Tensor.
      f - A function to apply.
    • foreachInPlace

      public void foreachInPlace(DoubleUnaryOperator f)
      Description copied from interface: Tensor
      Applies a DoubleUnaryOperator elementwise to this Tensor.
      Specified by:
      foreachInPlace in interface Tensor
      Parameters:
      f - The function to apply.
    • broadcastIntersectAndAddInPlace

      public void broadcastIntersectAndAddInPlace(SGDVector input, boolean broadcastOverDim1)
      Broadcasts the input vector and adds it to each row/column of the matrix.
      Parameters:
      input - The input vector.
      broadcastOverDim1 - If true broadcasts over the first dimension, else broadcasts over the second.
    • numActiveElements

      public int numActiveElements(int row)
      Description copied from interface: Matrix
      The number of non-zero elements in that row.

      An element could be active and zero, if it was active on construction.

      Specified by:
      numActiveElements in interface Matrix
      Parameters:
      row - The index of the row.
      Returns:
      The number of non-zero elements.
    • getRow

      public DenseVector getRow(int i)
      Description copied from interface: Matrix
      An SGDVector view of the row.

      This refers to the same values as the matrix, so updating this vector will update the matrix.

      Specified by:
      getRow in interface Matrix
      Parameters:
      i - The index of the row to extract.
      Returns:
      An SGDVector.
    • getColumn

      public DenseVector getColumn(int index)
      Returns a copy of the specified column.
      Specified by:
      getColumn in interface Matrix
      Parameters:
      index - The column index.
      Returns:
      A copy of the column.
    • setColumn

      public void setColumn(int index, SGDVector vector)
      Sets the column to the supplied vector value.
      Parameters:
      index - The column to set.
      vector - The vector to write.
    • rowSum

      public double rowSum(int rowIndex)
      Calculates the sum of the specified row.
      Parameters:
      rowIndex - The index of the row to sum.
      Returns:
      The row sum.
    • columnSum

      public double columnSum(int columnIndex)
      Calculates the sum of the specified column.
      Parameters:
      columnIndex - The index of the column to sum.
      Returns:
      The column sum.
    • twoNorm

      public double twoNorm()
      Description copied from interface: Tensor
      Calculates the euclidean norm for this vector.
      Specified by:
      twoNorm in interface Tensor
      Returns:
      The euclidean norm.
    • toArray

      public double[][] toArray()
      Returns a copy of this matrix as a 2d array.
      Returns:
      A copy of this matrix.
    • isSquare

      public boolean isSquare()
      Is this a square matrix?
      Returns:
      True if the matrix is square.
    • isSymmetric

      public boolean isSymmetric()
      Returns true if this matrix is square and symmetric.
      Returns:
      True if the matrix is symmetric.
    • choleskyFactorization

      public Optional<DenseMatrix.CholeskyFactorization> choleskyFactorization()
      Computes the Cholesky factorization of a positive definite matrix.

      If the matrix is not symmetric or positive definite then it returns an empty optional.

      Returns:
      The Cholesky factorization or an empty optional.
    • luFactorization

      public Optional<DenseMatrix.LUFactorization> luFactorization()
      Computes the LU factorization of a square matrix.

      If the matrix is singular or not square it returns an empty optional.

      Returns:
      The LU factorization or an empty optional.
    • eigenDecomposition

      public Optional<DenseMatrix.EigenDecomposition> eigenDecomposition()
      Eigen decomposition of a symmetric matrix.

      Non-symmetric matrices return an empty Optional as they may have complex eigenvalues, and any matrix which exceeds the default number of QL iterations in the decomposition also returns an empty Optional.

      Returns:
      The eigen decomposition of a symmetric matrix, or an empty optional if it's not symmetric.
    • toString

      public String toString()
      Overrides:
      toString in class Object
    • iterator

      public MatrixIterator iterator()
      Specified by:
      iterator in interface Iterable<MatrixTuple>
    • normalizeRows

      public void normalizeRows(VectorNormalizer normalizer)
      Normalizes each row using the supplied normalizer in place.
      Parameters:
      normalizer - The vector normalizer to use.
    • columnSum

      public DenseVector columnSum()
      Returns a dense vector containing each column sum.
      Returns:
      The column sums.
    • selectColumns

      public DenseMatrix selectColumns(int[] columnIndices)
      Returns a new DenseMatrix containing a copy of the selected columns.

      Throws IllegalArgumentException if any column index is invalid or the array is null/empty.

      Parameters:
      columnIndices - The column indices
      Returns:
      The submatrix comprising the selected columns.
    • selectColumns

      public DenseMatrix selectColumns(List<Integer> columnIndices)
      Returns a new DenseMatrix containing a copy of the selected columns.

      Throws IllegalArgumentException if any column index is invalid or the list is null/empty.

      Parameters:
      columnIndices - The column indices
      Returns:
      The submatrix comprising the selected columns.