rescale method

Matrix rescale({
  1. Rescale rescaleBy = Rescale.column,
})

Rescales each column of the matrix to the range 0-1.

It applies the Min-Max normalization technique on each column of the matrix.

Example:

var mat = Matrix.fromList([
   [2, 3, 3, 3],
   [9, 9, 8, 6],
   [1, 1, 2, 9]
]);
print(m.rescale());
// Output:
// Matrix: 3x4
// ┌ 0.125 0.25 0.167 0.0 ┐
// │   1.0  1.0   1.0 0.5 │
// └   0.0  0.0   0.0 1.0 ┘

Implementation

Matrix rescale({Rescale rescaleBy = Rescale.column}) {
  var rescaledMatrix = Matrix.zeros(rowCount, columnCount, isDouble: true);

  switch (rescaleBy) {
    case Rescale.row:
      for (int i = 0; i < rowCount; i++) {
        var row = _Utils.toSDList(_data[i]);
        var maxElement = row.reduce(math.max);
        var minElement = row.reduce(math.min);

        for (int j = 0; j < columnCount; j++) {
          rescaledMatrix[i][j] =
              (this[i][j] - minElement) / (maxElement - minElement);
        }
      }

      return rescaledMatrix;
    case Rescale.column:
      for (int j = 0; j < columnCount; j++) {
        var col = _Utils.toSDList(column(j).asList);
        var maxElement = col.reduce(math.max);
        var minElement = col.reduce(math.min);

        for (int i = 0; i < rowCount; i++) {
          rescaledMatrix[i][j] =
              (this[i][j] - minElement) / (maxElement - minElement);
        }
      }

      return rescaledMatrix;
    case Rescale.all:
      var maxElement = max();
      var minElement = min();

      for (int i = 0; i < rowCount; i++) {
        for (int j = 0; j < columnCount; j++) {
          rescaledMatrix[i][j] =
              (this[i][j] - minElement) / (maxElement - minElement);
        }
      }

      return rescaledMatrix;
    default:
      throw Exception('Invalid RescaleType');
  }
}