reluMatrix function

Tensor<Matrix> reluMatrix(
  1. Tensor<Matrix> m
)

Implementation

Tensor<Matrix> reluMatrix(Tensor<Matrix> m) {
  int numRows = m.value.length;
  int numCols = m.value[0].length;
  Matrix outValue = [];
  for (int i = 0; i < numRows; i++) {
    Vector row = [];
    for (int j = 0; j < numCols; j++) {
      row.add(m.value[i][j] > 0 ? m.value[i][j] : 0.0);
    }
    outValue.add(row);
  }
  Tensor<Matrix> out = Tensor<Matrix>(outValue);
  out.creator = Node(
    [m],
    () {
      for (int i = 0; i < numRows; i++) {
        for (int j = 0; j < numCols; j++) {
          m.grad[i][j] += out.grad[i][j] * (m.value[i][j] > 0 ? 1.0 : 0.0);
        }
      }
    },
    opName: 'relu_matrix', // <-- Renamed for clarity
    cost: numRows * numCols,
  );
  return out;
}